using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace SplashEdit.RuntimeCode
{
///
/// Collects all PSXCanvas hierarchies in the scene, bakes RectTransform
/// coordinates into PS1 pixel space, and produces
/// arrays ready for binary serialization.
///
public static class PSXUIExporter
{
///
/// Collect all PSXCanvas components and their child UI elements,
/// converting RectTransform coordinates to PS1 pixel space.
/// Also collects and deduplicates custom fonts.
///
/// Target PS1 resolution (e.g. 320×240).
/// Output: collected custom font data (max 3).
/// Array of canvas data ready for binary writing.
public static PSXCanvasData[] CollectCanvases(Vector2 resolution, out PSXFontData[] fonts)
{
// Collect and deduplicate all custom fonts used by text elements
List uniqueFonts = new List();
#if UNITY_EDITOR
PSXCanvas[] canvases = Object.FindObjectsByType(FindObjectsSortMode.None);
#else
PSXCanvas[] canvases = Object.FindObjectsOfType();
#endif
if (canvases == null || canvases.Length == 0)
{
fonts = new PSXFontData[0];
return new PSXCanvasData[0];
}
// First pass: collect unique fonts
foreach (PSXCanvas canvas in canvases)
{
PSXUIText[] texts = canvas.GetComponentsInChildren(true);
foreach (PSXUIText txt in texts)
{
PSXFontAsset font = txt.GetEffectiveFont();
if (font != null && !uniqueFonts.Contains(font) && uniqueFonts.Count < 3)
uniqueFonts.Add(font);
}
}
// Build font data with VRAM positions
// Font textures go at x=960 (same column as system font), stacking upward from y=464
// System font: (960, 464)-(1023, 511) → 64 wide, 48 tall
List fontDataList = new List();
ushort fontVramY = 0; // start from top of VRAM at x=960
foreach (PSXFontAsset fa in uniqueFonts)
{
byte[] pixelData = fa.ConvertTo4BPP();
if (pixelData == null) continue;
ushort texH = (ushort)fa.TextureHeight;
fontDataList.Add(new PSXFontData
{
Source = fa,
GlyphWidth = (byte)fa.GlyphWidth,
GlyphHeight = (byte)fa.GlyphHeight,
VramX = 960, // same column as system font (64 VRAM hwords for 256px 4bpp)
VramY = fontVramY,
TextureHeight = texH,
PixelData = pixelData
});
fontVramY += texH;
}
fonts = fontDataList.ToArray();
// Second pass: collect canvases with font index assignment
List result = new List();
foreach (PSXCanvas canvas in canvases)
{
Canvas unityCanvas = canvas.GetComponent