Files
chameleon/Assets/Scripts/MeshPainter.Persistence.cs
T
adminandClaude Opus 4.8 ee482905f9 Replace auto paint persistence with a named painting library
Persistence rework:
- Drop auto-load on setup and auto-save on teardown; the painter now always
  seeds fresh from the material.
- Named slots under MeshPaint/Saved/<name>.paint via the existing CHMP
  machinery: SavePaintAs / LoadPaintByName / DeletePaint / ListSavedPaintings /
  PaintExists. Slot files carry the display name in the header.
- Remove the obsolete persistence partials (PlayerCharacterController,
  PlayerPoseController, ThirdPersonOrbitInput) and their references.

Paintings HUD panel:
- Authored Panel_Paintings + Save/Load/Delete dialogs into PaintHudPanel.prefab
  (TMP throughout); PaintHud.Library.cs is now a pure binder that clones the
  entry template per slot.
- Save dialog blocks empty/existing names; Load and Delete confirm first.
- Fix dialog z-order: open dialogs SetAsLastSibling so a dragged panel can no
  longer cover them.
- Lib_ListContent horizontal offsets corrected to 0 (was clipping entry labels
  out of the masked viewport).

Multiplayer:
- Loading a painting re-syncs to all peers via the snapshot broadcast path
  (BroadcastLoadedPaint), covering later late-joiners for free.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 18:39:20 +02:00

223 lines
8.6 KiB
C#

using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
public partial class MeshPainter
{
// --- Persistence: named paint slots, saved/loaded explicitly from the HUD ---
//
// The painter no longer auto-loads on start or auto-saves on quit; painting is volatile until the
// player explicitly saves it to a named slot, and a fresh session always starts from the material
// seed. Saved slots live in a single global library folder (role/object independent), so any avatar
// can load any saved painting as a camouflage preset.
// Raw, bit-exact map dump: 'CHMP' magic + version + name + width + height + map count, then each
// map's canonical Color32 bytes. Raw (not PNG) avoids any sRGB/alpha-premultiply ambiguity and
// round-trips the exact canonical bytes ReadCanonical produces.
private const uint PaintFileMagic = 0x504D4843; // 'CHMP' little-endian
private const int PaintFileVersion = 2; // v2: added the display-name header
private const string PaintFileExt = ".paint";
private static string PaintLibraryDir =>
Path.Combine(Application.persistentDataPath, "MeshPaint", "Saved");
private static string SanitizeKey(string s)
{
if (string.IsNullOrEmpty(s)) return "unnamed";
foreach (char c in Path.GetInvalidFileNameChars()) s = s.Replace(c, '_');
return s.Replace(' ', '_');
}
/// <summary>Disk path for a slot. The display name lives inside the file; the file name is a sanitized key.</summary>
private static string PathForName(string name) =>
Path.Combine(PaintLibraryDir, SanitizeKey(name) + PaintFileExt);
/// <summary>True if a slot with this name already exists (used to block overwriting on save).</summary>
public static bool PaintExists(string name) =>
!string.IsNullOrWhiteSpace(name) && File.Exists(PathForName(name));
/// <summary>Display names of every saved slot, sorted alphabetically. Each name is read from the file header.</summary>
public static List<string> ListSavedPaintings()
{
var names = new List<string>();
try
{
if (!Directory.Exists(PaintLibraryDir)) return names;
foreach (string path in Directory.GetFiles(PaintLibraryDir, "*" + PaintFileExt))
{
string n = ReadHeaderName(path);
if (!string.IsNullOrEmpty(n)) names.Add(n);
}
}
catch (System.Exception e)
{
Debug.LogWarning($"[MeshPainter] Listing saved paintings failed: {e.Message}");
}
names.Sort(System.StringComparer.CurrentCultureIgnoreCase);
return names;
}
/// <summary>
/// Writes the current painted maps to a new named slot. Returns false without writing if the painter
/// is not ready or a slot with this name already exists (no silent overwrite).
/// </summary>
public bool SavePaintAs(string name)
{
if (!_setupValid || string.IsNullOrWhiteSpace(name)) return false;
name = name.Trim();
if (PaintExists(name)) return false;
try
{
Directory.CreateDirectory(PaintLibraryDir);
int n = textureSize * textureSize;
using (var fs = new FileStream(PathForName(name), FileMode.Create, FileAccess.Write))
using (var w = new BinaryWriter(fs))
{
w.Write(PaintFileMagic);
w.Write(PaintFileVersion);
w.Write(name); // length-prefixed UTF8 (BinaryWriter.Write(string))
w.Write(textureSize);
w.Write(textureSize);
w.Write(MAP_COUNT);
var bytes = new byte[n * 4];
for (int mi = 0; mi < MAP_COUNT; mi++)
{
Color32[] px = ReadCanonical(mi);
int count = Mathf.Min(n, px.Length);
for (int i = 0; i < count; i++)
{
int o = i * 4;
bytes[o] = px[i].r;
bytes[o + 1] = px[i].g;
bytes[o + 2] = px[i].b;
bytes[o + 3] = px[i].a;
}
w.Write(bytes, 0, count * 4);
}
}
return true;
}
catch (System.Exception e)
{
Debug.LogWarning($"[MeshPainter] Saving paint '{name}' failed: {e.Message}", this);
return false;
}
}
/// <summary>
/// Loads a named slot and re-seeds the active backend with it, replacing the current painting.
/// Returns false if the slot is missing or incompatible (the current painting is left untouched).
/// </summary>
public bool LoadPaintByName(string name)
{
if (!_setupValid) return false;
Color32[][] canonical = ReadMaps(PathForName(name));
if (canonical == null) return false;
// Re-seed exactly like SwitchBackend / ApplyPaintSnapshot, so the island/dilation seeding path
// runs and the edge padding is rebuilt correctly for the loaded content.
if (_gpuActive) TeardownGpu();
else TeardownCpu();
SetupBackend(useGpu, canonical);
_hasLastScreen = false;
return true;
}
/// <summary>Deletes a named slot. Returns true if a file was removed.</summary>
public static bool DeletePaint(string name)
{
try
{
string path = PathForName(name);
if (!File.Exists(path)) return false;
File.Delete(path);
return true;
}
catch (System.Exception e)
{
Debug.LogWarning($"[MeshPainter] Deleting paint '{name}' failed: {e.Message}");
return false;
}
}
/// <summary>Reads just the display-name header of a slot file (or the file name as a fallback).</summary>
private static string ReadHeaderName(string path)
{
try
{
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
using (var r = new BinaryReader(fs, Encoding.UTF8))
{
if (r.ReadUInt32() != PaintFileMagic) return null;
if (r.ReadInt32() != PaintFileVersion) return null;
return r.ReadString();
}
}
catch
{
return Path.GetFileNameWithoutExtension(path);
}
}
/// <summary>
/// Reads all maps from a slot file in canonical layout, or null if missing / incompatible. Per-map
/// null entries are tolerated by both backends (they fall back to the material seed).
/// </summary>
private Color32[][] ReadMaps(string path)
{
if (!File.Exists(path)) return null;
try
{
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
using (var r = new BinaryReader(fs, Encoding.UTF8))
{
if (r.ReadUInt32() != PaintFileMagic) return null;
int ver = r.ReadInt32();
if (ver != PaintFileVersion) return null;
r.ReadString(); // display name (header only; not needed for the pixel load)
int w = r.ReadInt32();
int h = r.ReadInt32();
int maps = r.ReadInt32();
// Resolution change -> ignore rather than smear mismatched data; the brush re-seeds
// from the material instead.
if (w != textureSize || h != textureSize)
{
Debug.LogWarning($"[MeshPainter] Saved paint ignored (got {w}x{h}, expected " +
$"{textureSize}x{textureSize}).", this);
return null;
}
int n = textureSize * textureSize;
var result = new Color32[MAP_COUNT][];
int load = Mathf.Min(maps, MAP_COUNT);
for (int mi = 0; mi < load; mi++)
{
byte[] raw = r.ReadBytes(n * 4);
if (raw.Length != n * 4) break; // truncated file -> remaining maps stay seeded
var px = new Color32[n];
for (int i = 0; i < n; i++)
{
int o = i * 4;
px[i] = new Color32(raw[o], raw[o + 1], raw[o + 2], raw[o + 3]);
}
result[mi] = px;
}
return result;
}
}
catch (System.Exception e)
{
Debug.LogWarning($"[MeshPainter] Loading paint failed: {e.Message}", this);
return null;
}
}
}