Finalize the cursed work

This commit is contained in:
Michal Pikulski
2025-11-27 00:58:19 +01:00
parent 5bab6d9596
commit 8bc4a88958
11 changed files with 381 additions and 530 deletions

View File

@@ -13,45 +13,39 @@ namespace Minigames.StatueDressup.Display
/// Place this component on a GameObject with a SpriteRenderer showing the statue.
/// On Start, loads all DecorationData via Addressables label, then spawns decorations from metadata.
/// </summary>
[RequireComponent(typeof(SpriteRenderer))]
public class StatueDecorationLoader : ManagedBehaviour
{
[Header("Settings")]
[Tooltip("Root GameObject for spawning decorations (clears only this, not statue children)")]
[SerializeField] private Transform decorationRoot;
[SerializeField] private SpriteRenderer statueSpriteRenderer;
[Tooltip("Load specific photo ID, or leave empty to load latest")]
[SerializeField] private string specificPhotoId = "";
[Tooltip("Apply pivot offset to position decorations relative to sprite's visual center instead of pivot point")]
[SerializeField] private bool applyPivotOffset = true;
[Header("Debug")]
[SerializeField] private bool showDebugInfo = true;
private SpriteRenderer _statueSpriteRenderer;
private Dictionary<string, DecorationData> _decorationDataDict;
private AsyncOperationHandle<IList<DecorationData>> _decorationDataHandle;
private AppleHills.Core.Settings.IStatueDressupSettings _settings;
private Dictionary<string, DecorationData> decorationDataDict;
private AsyncOperationHandle<IList<DecorationData>> decorationDataHandle;
private AppleHills.Core.Settings.IStatueDressupSettings settings;
internal override void OnManagedStart()
{
base.OnManagedStart();
_statueSpriteRenderer = GetComponent<SpriteRenderer>();
if (statueSpriteRenderer == null)
statueSpriteRenderer = GetComponent<SpriteRenderer>();
if (statueSpriteRenderer == null)
{
Logging.Error("[StatueDecorationLoader] No SpriteRenderer found! Please assign statueSpriteRenderer.");
return;
}
// Get settings
_settings = GameManager.GetSettingsObject<AppleHills.Core.Settings.IStatueDressupSettings>();
// Ensure decoration root exists
if (decorationRoot == null)
{
GameObject rootObj = new GameObject("DecorationRoot");
rootObj.transform.SetParent(transform, false);
decorationRoot = rootObj.transform;
if (showDebugInfo)
{
Logging.Debug("[StatueDecorationLoader] Created decoration root automatically");
}
}
settings = GameManager.GetSettingsObject<AppleHills.Core.Settings.IStatueDressupSettings>();
// Start async loading via coroutine wrapper
StartCoroutine(LoadAndDisplayDecorationsCoroutine());
@@ -87,7 +81,7 @@ namespace Minigames.StatueDressup.Display
/// </summary>
private async System.Threading.Tasks.Task LoadDecorationDataAsync()
{
string label = _settings?.DecorationDataLabel;
string label = settings?.DecorationDataLabel;
if (string.IsNullOrEmpty(label))
{
@@ -107,12 +101,12 @@ namespace Minigames.StatueDressup.Display
progress => { /* Optional: could show loading bar */ }
);
_decorationDataDict = result.dictionary;
_decorationDataHandle = result.handle;
decorationDataDict = result.dictionary;
decorationDataHandle = result.handle;
if (showDebugInfo)
{
Logging.Debug($"[StatueDecorationLoader] Loaded {_decorationDataDict.Count} DecorationData assets");
Logging.Debug($"[StatueDecorationLoader] Loaded {decorationDataDict.Count} DecorationData assets");
}
}
@@ -122,7 +116,7 @@ namespace Minigames.StatueDressup.Display
public void LoadAndDisplayDecorations()
{
// Check if DecorationData is loaded
if (_decorationDataDict == null || _decorationDataDict.Count == 0)
if (decorationDataDict == null || decorationDataDict.Count == 0)
{
Logging.Warning("[StatueDecorationLoader] DecorationData not loaded yet. Cannot display decorations.");
return;
@@ -149,13 +143,13 @@ namespace Minigames.StatueDressup.Display
ClearDecorations();
// Calculate coordinate conversion factor if needed
float conversionFactor = CalculateCoordinateConversion(data);
float conversionFactor = CalculateCoordinateConversion(data, out Vector2 targetStatueWorldSize);
// Spawn each decoration synchronously (data already loaded)
int successCount = 0;
foreach (var placement in data.placements)
{
if (SpawnDecoration(placement, conversionFactor))
if (SpawnDecoration(placement, conversionFactor, data.sourceStatueSize, targetStatueWorldSize))
{
successCount++;
}
@@ -170,7 +164,7 @@ namespace Minigames.StatueDressup.Display
/// <summary>
/// Calculate coordinate conversion factor between source and target coordinate systems
/// </summary>
private float CalculateCoordinateConversion(StatueDecorationData data)
private float CalculateCoordinateConversion(StatueDecorationData data, out Vector2 targetStatueWorldSize)
{
// If source was world space and we're also world space, no conversion needed
if (data.coordinateSystem == CoordinateSystemType.WorldSpace)
@@ -179,29 +173,32 @@ namespace Minigames.StatueDressup.Display
{
Logging.Debug("[StatueDecorationLoader] No coordinate conversion needed (WorldSpace → WorldSpace)");
}
targetStatueWorldSize = Vector2.one;
return 1f;
}
// Source was UI RectTransform (pixels), target is WorldSpace (units)
// Need to convert from source statue pixel size to target statue world size
// Need to convert from source statue pixel size to target statue VISUAL world size
// Get target statue size (world units)
Vector2 targetStatueSize = Vector2.one;
if (_statueSpriteRenderer != null && _statueSpriteRenderer.sprite != null)
{
targetStatueSize = _statueSpriteRenderer.sprite.bounds.size;
}
// Get target statue VISUAL size (including transform scale)
Vector2 spriteNativeSize = statueSpriteRenderer.sprite.bounds.size;
Vector3 spriteScale = statueSpriteRenderer.transform.localScale;
targetStatueWorldSize = new Vector2(
spriteNativeSize.x * spriteScale.x,
spriteNativeSize.y * spriteScale.y
);
// Calculate conversion factor (target size / source size)
float conversionX = targetStatueSize.x / data.sourceStatueSize.x;
float conversionY = targetStatueSize.y / data.sourceStatueSize.y;
float conversionX = targetStatueWorldSize.x / data.sourceStatueSize.x;
float conversionY = targetStatueWorldSize.y / data.sourceStatueSize.y;
// Use average of X and Y for uniform scaling (or could use separate X/Y)
float conversionFactor = (conversionX + conversionY) / 2f;
if (showDebugInfo)
{
Logging.Debug($"[StatueDecorationLoader] Coordinate conversion: UI({data.sourceStatueSize}) → World({targetStatueSize}) = factor {conversionFactor:F3}");
Logging.Debug($"[StatueDecorationLoader] Coordinate conversion: UI({data.sourceStatueSize}px) → World({targetStatueWorldSize}units)");
Logging.Debug($"[StatueDecorationLoader] Sprite native: {spriteNativeSize}, scale: {spriteScale}, conversion factor: {conversionFactor:F3}");
}
return conversionFactor;
@@ -211,10 +208,10 @@ namespace Minigames.StatueDressup.Display
/// Spawn a single decoration from placement data
/// Looks up DecorationData from pre-loaded dictionary and applies coordinate conversion
/// </summary>
private bool SpawnDecoration(DecorationPlacement placement, float conversionFactor)
private bool SpawnDecoration(DecorationPlacement placement, float conversionFactor, Vector2 sourceStatueSize, Vector2 targetStatueWorldSize)
{
// Look up DecorationData from dictionary
if (!_decorationDataDict.TryGetValue(placement.decorationId, out DecorationData decorationData))
if (!decorationDataDict.TryGetValue(placement.decorationId, out DecorationData decorationData))
{
Logging.Warning($"[StatueDecorationLoader] DecorationData not found for ID: {placement.decorationId}");
return false;
@@ -229,47 +226,151 @@ namespace Minigames.StatueDressup.Display
return false;
}
// Create GameObject for decoration
// Create GameObject for decoration as child of statue sprite renderer
GameObject decorationObj = new GameObject($"Decoration_{placement.decorationId}");
decorationObj.transform.SetParent(decorationRoot, false); // false = keep local position
decorationObj.transform.SetParent(statueSpriteRenderer.transform, false);
// Add SpriteRenderer
SpriteRenderer spriteRenderer = decorationObj.AddComponent<SpriteRenderer>();
spriteRenderer.sprite = decorationSprite;
spriteRenderer.sortingLayerName = "Foreground";
spriteRenderer.sortingOrder = _statueSpriteRenderer.sortingOrder + placement.sortingOrder;
spriteRenderer.sortingOrder = statueSpriteRenderer.sortingOrder + placement.sortingOrder;
// Apply transform with coordinate conversion
Vector3 convertedPosition = placement.localPosition * conversionFactor;
decorationObj.transform.localPosition = convertedPosition;
decorationObj.transform.localScale = placement.localScale;
// ===== POSITION CALCULATION =====
// Calculate pivot offset - decorations should be positioned relative to sprite's visual center, not pivot
Sprite statueSprite = statueSpriteRenderer.sprite;
Bounds spriteBounds = statueSprite.bounds;
// Sprite.bounds.center gives us the offset from pivot to visual center in local space
Vector2 pivotToCenterOffset = spriteBounds.center;
// Convert UI pixel position to world space position
Vector3 worldPosition = placement.localPosition * conversionFactor;
// Convert world position to local position (accounting for parent scale)
Vector3 parentScale = statueSpriteRenderer.transform.localScale;
Vector3 localPosition = new Vector3(
worldPosition.x / parentScale.x,
worldPosition.y / parentScale.y,
worldPosition.z
);
// Apply pivot offset IN LOCAL SPACE (after conversion from world to local)
// This ensures both values are in the same coordinate system
if (applyPivotOffset)
{
localPosition += new Vector3(pivotToCenterOffset.x, pivotToCenterOffset.y, 0f);
if (showDebugInfo)
{
Logging.Debug($"[StatueDecorationLoader] Pivot offset APPLIED: {pivotToCenterOffset} (bounds center: {spriteBounds.center}, pivot normalized: {statueSprite.pivot / statueSprite.rect.size})");
}
}
else if (showDebugInfo)
{
Logging.Debug($"[StatueDecorationLoader] Pivot offset SKIPPED (applyPivotOffset = false)");
}
// ===== SCALE CALCULATION =====
Vector3 localScale = placement.localScale;
if (placement.sizeDelta != Vector2.zero)
{
// Calculate relative size in UI (decoration size / statue size)
Vector2 relativeSizeUI = new Vector2(
placement.sizeDelta.x / sourceStatueSize.x,
placement.sizeDelta.y / sourceStatueSize.y
);
// Calculate target world size for decoration (relative size × statue world size)
Vector2 targetDecorationWorldSize = new Vector2(
relativeSizeUI.x * targetStatueWorldSize.x,
relativeSizeUI.y * targetStatueWorldSize.y
);
// Get decoration sprite's native world size
Vector2 decorationNativeWorldSize = decorationSprite.bounds.size;
// Calculate world scale needed to achieve target size
Vector2 worldScaleNeeded = new Vector2(
targetDecorationWorldSize.x / decorationNativeWorldSize.x,
targetDecorationWorldSize.y / decorationNativeWorldSize.y
);
// Apply saved scale multiplier
worldScaleNeeded = new Vector2(
worldScaleNeeded.x * placement.localScale.x,
worldScaleNeeded.y * placement.localScale.y
);
// Convert world scale to local scale (accounting for parent scale)
localScale = new Vector3(
worldScaleNeeded.x / parentScale.x,
worldScaleNeeded.y / parentScale.y,
1f
);
if (showDebugInfo)
{
Logging.Debug($"[StatueDecorationLoader] Size calc: UI sizeDelta={placement.sizeDelta}, relativeUI={relativeSizeUI}");
Logging.Debug($"[StatueDecorationLoader] Target world size={targetDecorationWorldSize}, native={decorationNativeWorldSize}, worldScale={worldScaleNeeded}, localScale={localScale}");
}
}
else
{
// No sizeDelta saved, just apply saved scale divided by parent scale
localScale = new Vector3(
placement.localScale.x / parentScale.x,
placement.localScale.y / parentScale.y,
1f
);
if (showDebugInfo)
{
Logging.Debug($"[StatueDecorationLoader] No sizeDelta saved, using scale directly (compensated): {localScale}");
}
}
// Apply transform
decorationObj.transform.localPosition = localPosition;
decorationObj.transform.localScale = localScale;
decorationObj.transform.localEulerAngles = new Vector3(0, 0, placement.rotation);
if (showDebugInfo)
{
Logging.Debug($"[StatueDecorationLoader] Spawned: {placement.decorationId} at {convertedPosition} (original: {placement.localPosition}, factor: {conversionFactor:F3})");
Logging.Debug($"[StatueDecorationLoader] Spawned: {placement.decorationId}");
Logging.Debug($"[StatueDecorationLoader] Position: UI={placement.localPosition} → world={worldPosition} → local={localPosition}");
Logging.Debug($"[StatueDecorationLoader] Parent scale: {parentScale}");
}
return true;
}
/// <summary>
/// Clear all existing decorations from decorationRoot
/// Clear all existing decorations (children of statue sprite renderer that are decorations)
/// </summary>
public void ClearDecorations()
{
if (decorationRoot == null) return;
if (statueSpriteRenderer == null) return;
// Remove all children from decoration root only
for (int i = decorationRoot.childCount - 1; i >= 0; i--)
Transform parent = statueSpriteRenderer.transform;
// Remove all children that are decorations (identified by name pattern)
for (int i = parent.childCount - 1; i >= 0; i--)
{
if (Application.isPlaying)
GameObject child = parent.GetChild(i).gameObject;
// Only destroy objects that look like decorations (by name pattern)
if (child.name.StartsWith("Decoration_"))
{
Destroy(decorationRoot.GetChild(i).gameObject);
}
else
{
DestroyImmediate(decorationRoot.GetChild(i).gameObject);
if (Application.isPlaying)
{
Destroy(child);
}
else
{
DestroyImmediate(child);
}
}
}
}
@@ -280,7 +381,7 @@ namespace Minigames.StatueDressup.Display
private void OnDestroy()
{
// Release DecorationData handle
AddressablesUtility.ReleaseHandle(_decorationDataHandle);
AddressablesUtility.ReleaseHandle(decorationDataHandle);
}
/// <summary>