Publish verified live restoration source snapshot and known limits
This commit is contained in:
@@ -0,0 +1,220 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
using Gallop.RenderPipeline;
|
||||
|
||||
// Isolated GPU contract tests for the shipped shaders, not a whole-Live parity test.
|
||||
// Expected equations come from local DXBC (documented in LIVE_RENDER_RESTORATION.md).
|
||||
public static class LiveBloomDiffusionRegression
|
||||
{
|
||||
static void Check(bool condition, string message)
|
||||
{
|
||||
if (!condition) throw new Exception("LiveBloomDiffusionRegression: " + message);
|
||||
}
|
||||
|
||||
static void Near(Color actual, Color expected, string label)
|
||||
{
|
||||
for (int c = 0; c < 3; ++c)
|
||||
Check(!float.IsNaN(actual[c]) && Math.Abs(actual[c] - expected[c]) < 0.00015f,
|
||||
label + " channel " + c + " actual=" + actual[c] + " expected=" + expected[c]);
|
||||
}
|
||||
|
||||
static RenderTexture Texture(int width, int height)
|
||||
{
|
||||
var rt = new RenderTexture(width, height, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear);
|
||||
rt.filterMode = FilterMode.Bilinear;
|
||||
rt.wrapMode = TextureWrapMode.Clamp;
|
||||
rt.Create();
|
||||
return rt;
|
||||
}
|
||||
|
||||
static void Fill(RenderTexture rt, Color color)
|
||||
{
|
||||
RenderTexture.active = rt;
|
||||
GL.Clear(false, true, color);
|
||||
}
|
||||
|
||||
static Color Read(RenderTexture rt, Texture2D read)
|
||||
{
|
||||
RenderTexture.active = rt;
|
||||
read.ReadPixels(new Rect(rt.width / 2, rt.height / 2, 1, 1), 0, 0);
|
||||
read.Apply();
|
||||
return read.GetPixel(0, 0);
|
||||
}
|
||||
|
||||
static Color Composite(Color source, Color bloom, float weight, bool screen)
|
||||
{
|
||||
Color result = source;
|
||||
for (int c = 0; c < 3; ++c)
|
||||
result[c] = screen ? 1 - (1 - source[c]) * (1 - bloom[c] * weight) : source[c] + bloom[c] * weight;
|
||||
return result;
|
||||
}
|
||||
|
||||
static Color Diffusion(Color composite, Color blur, Vector4 parameters)
|
||||
{
|
||||
Color result = composite;
|
||||
for (int c = 0; c < 3; ++c)
|
||||
{
|
||||
float square = composite[c] * composite[c];
|
||||
result[c] = Mathf.Max(composite[c], Mathf.Max(0, square + blur[c] - blur[c] * square - parameters.w)) * parameters.x;
|
||||
}
|
||||
float luminance = result.r * 0.2125f + result.g * 0.7154f + result.b * 0.0721f;
|
||||
for (int c = 0; c < 3; ++c)
|
||||
result[c] = (luminance + parameters.y * (result[c] - luminance) - 0.5f) * parameters.z + 0.5f;
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void RunGpu()
|
||||
{
|
||||
Check(Application.isBatchMode, "run only in an isolated batch-mode project");
|
||||
string path = Environment.GetEnvironmentVariable("UMA_POSTFILM_TEST_BUNDLE");
|
||||
Check(File.Exists(path), "missing local shader bundle");
|
||||
var bundle = AssetBundle.LoadFromFile(path);
|
||||
Check(bundle != null, "bundle load");
|
||||
var previous = RenderTexture.active;
|
||||
var source = Texture(64, 32);
|
||||
var low = Texture(16, 8);
|
||||
var vertical = Texture(16, 8);
|
||||
var bloom = Texture(16, 8);
|
||||
var target = Texture(64, 32);
|
||||
var read = new Texture2D(1, 1, TextureFormat.RGBAFloat, false, true);
|
||||
Material fast = null, post = null, diffusion = null, diffusionDof = null;
|
||||
string[] floats = { "_bloomDofWeight", "_BloomIsScreenBlend" };
|
||||
float[] oldFloats = Array.ConvertAll(floats, Shader.GetGlobalFloat);
|
||||
string[] vectors = { "_Parameter", "_ColorParam", "_PixelSize" };
|
||||
Vector4[] oldVectors = Array.ConvertAll(vectors, Shader.GetGlobalVector);
|
||||
var oldBloom = Shader.GetGlobalTexture("_Bloom");
|
||||
var oldRgb = Shader.GetGlobalTexture("_RgbTex");
|
||||
var oldLowBackground = Shader.GetGlobalTexture("_TapLowBackground");
|
||||
try
|
||||
{
|
||||
foreach (var shader in bundle.LoadAllAssets<Shader>())
|
||||
{
|
||||
if (shader.name == "Gallop/ImageEffects/FastBloom") fast = new Material(shader);
|
||||
if (shader.name == "Gallop/ImageEffects/Rich/PostBloom_Rich") post = new Material(shader);
|
||||
if (shader.name == "Gallop/ImageEffects/Rich/PostDiffusionBloom_Rich") diffusion = new Material(shader);
|
||||
if (shader.name == "Gallop/ImageEffects/Rich/PostDiffusionDofBloom_Rich") diffusionDof = new Material(shader);
|
||||
}
|
||||
Check(fast && post && diffusion && diffusionDof, "four shipped shaders present");
|
||||
Check(fast.shader.isSupported && post.shader.isSupported && diffusion.shader.isSupported &&
|
||||
diffusionDof.shader.isSupported, "shaders supported");
|
||||
post.SetColor("_DimmerColor", Color.white);
|
||||
Color input = new Color(0.05f, 0.4f, 1.4f, 1);
|
||||
Fill(source, input);
|
||||
foreach (float threshold in new[] { 0f, 0.1f, 0.23f })
|
||||
foreach (float intensity in new[] { 0f, 0.5f, 0.9f, 2f })
|
||||
{
|
||||
Color expected = input;
|
||||
for (int c = 0; c < 3; ++c) expected[c] = Mathf.Max(0, input[c] - threshold) * intensity;
|
||||
// Zero-radius native path: threshold/intensity both in downsample.
|
||||
Shader.SetGlobalVector("_Parameter", new Vector4(0, 0, threshold, intensity));
|
||||
Graphics.Blit(source, bloom, fast, 1);
|
||||
Near(Read(bloom, read), expected, "zero-radius extraction");
|
||||
// Positive radius path: neutral reduction, threshold only in vertical,
|
||||
// intensity only in horizontal. Both Gaussian kernels sum to one.
|
||||
Shader.SetGlobalVector("_Parameter", new Vector4(0, 0, 0, 1));
|
||||
Graphics.Blit(source, low, fast, 1);
|
||||
Shader.SetGlobalVector("_Parameter", new Vector4(1f / 1024, 1f / 512, threshold, intensity));
|
||||
Graphics.Blit(low, vertical, fast, 2);
|
||||
Graphics.Blit(vertical, bloom, fast, 3);
|
||||
Near(Read(bloom, read), expected, "two-axis extraction (no double threshold/intensity)");
|
||||
}
|
||||
var bloomColor = new Color(0.1f, 0.3f, 0.8f, 1);
|
||||
var blurColor = new Color(0.2f, 0.6f, 0.9f, 1);
|
||||
Fill(bloom, bloomColor);
|
||||
Fill(low, blurColor);
|
||||
Shader.SetGlobalTexture("_Bloom", bloom);
|
||||
Shader.SetGlobalTexture("_RgbTex", low);
|
||||
foreach (bool screen in new[] { false, true, false })
|
||||
foreach (float weight in new[] { 0f, 0.5f, 1f })
|
||||
{
|
||||
Shader.SetGlobalFloat("_bloomDofWeight", weight);
|
||||
Shader.SetGlobalFloat("_BloomIsScreenBlend", screen ? 1 : 0);
|
||||
var composite = Composite(input, bloomColor, weight, screen);
|
||||
Graphics.Blit(source, target, post, 0);
|
||||
Near(Read(target, read), composite, "Bloom Add/Screen HDR");
|
||||
foreach (var parameters in new[] { new Vector4(1, 1, 1, 0), new Vector4(0.8f, 0.5f, 1.1f, 0.2f), new Vector4(1.2f, 0, 0.9f, 0.1f) })
|
||||
{
|
||||
Shader.SetGlobalVector("_ColorParam", parameters);
|
||||
Graphics.Blit(source, target, diffusion, 2);
|
||||
Near(Read(target, read), Diffusion(composite, blurColor, parameters), "Diffusion composite and color order");
|
||||
}
|
||||
}
|
||||
// Pass 1 combines Bloom and the first film layer. Pass 3 consumes
|
||||
// the previous output without sampling Bloom again.
|
||||
var film = new Gallop.RenderPipeline.ScreenOverlayRender.Render();
|
||||
var first = Gallop.RenderPipeline.ScreenOverlayRender.Parameter.Default();
|
||||
first.PostFilmMode = Gallop.ImageEffect.ScreenOverlay.Overlay.PostFilmMode.Add;
|
||||
first.PostFilmPower = 0.5f;
|
||||
first.PostFilmColor0 = first.PostFilmColor1 = first.PostFilmColor2 = first.PostFilmColor3 =
|
||||
new Color(0.4f, 0.2f, 0.1f, 1f);
|
||||
var later = Gallop.RenderPipeline.ScreenOverlayRender.Parameter.Default();
|
||||
later.PostFilmMode = Gallop.ImageEffect.ScreenOverlay.Overlay.PostFilmMode.Lerp;
|
||||
later.PostFilmPower = 0.5f;
|
||||
later.PostFilmColor0 = later.PostFilmColor1 = later.PostFilmColor2 = later.PostFilmColor3 = Color.black;
|
||||
Fill(source, new Color(0.2f, 0.3f, 0.4f, 1f));
|
||||
Fill(bloom, new Color(0.1f, 0.2f, 0.3f, 1f));
|
||||
Shader.SetGlobalTexture("_Bloom", bloom);
|
||||
Shader.SetGlobalFloat("_bloomDofWeight", 0.5f);
|
||||
Shader.SetGlobalFloat("_BloomIsScreenBlend", 0f);
|
||||
post.SetColor("_DimmerColor", Color.white);
|
||||
using (var cmd = new CommandBuffer())
|
||||
{
|
||||
film.Blit(ref first, cmd, RenderTextureHandle.Make(source), RenderTextureHandle.Make(target), post, 1);
|
||||
Graphics.ExecuteCommandBuffer(cmd);
|
||||
cmd.Clear();
|
||||
Near(Read(target, read), new Color(0.45f, 0.5f, 0.6f, 1f), "Bloom plus first film layer");
|
||||
film.Blit(ref later, cmd, RenderTextureHandle.Make(target), RenderTextureHandle.Make(source), post, 3);
|
||||
Graphics.ExecuteCommandBuffer(cmd);
|
||||
cmd.Clear();
|
||||
Near(Read(source, read), new Color(0.225f, 0.25f, 0.3f, 1f), "second film layer without repeated Bloom");
|
||||
film.Blit(ref later, cmd, RenderTextureHandle.Make(source), RenderTextureHandle.Make(target), post, 3);
|
||||
Graphics.ExecuteCommandBuffer(cmd);
|
||||
Near(Read(target, read), new Color(0.1125f, 0.125f, 0.15f, 1f), "third film layer without repeated Bloom");
|
||||
}
|
||||
// The DiffusionDofBloom mode can remain selected when its Bloom flag
|
||||
// is off. Execute binds black before the conditional extraction; verify
|
||||
// that its first film pass does not reuse the previous frame's bloom.
|
||||
var noBloomFilm = Gallop.RenderPipeline.ScreenOverlayRender.Parameter.Default();
|
||||
noBloomFilm.PostFilmMode = Gallop.ImageEffect.ScreenOverlay.Overlay.PostFilmMode.Lerp;
|
||||
noBloomFilm.PostFilmPower = 0.5f;
|
||||
noBloomFilm.PostFilmColor0 = noBloomFilm.PostFilmColor1 =
|
||||
noBloomFilm.PostFilmColor2 = noBloomFilm.PostFilmColor3 = Color.black;
|
||||
diffusionDof.SetColor("_DimmerColor", Color.white);
|
||||
Fill(source, new Color(0.2f, 0.3f, 0.4f, 1f));
|
||||
Fill(low, new Color(0.2f, 0.3f, 0.4f, 1f));
|
||||
Fill(bloom, new Color(0.9f, 0.9f, 0.9f, 1f));
|
||||
// Suppress diffusion's extra lift so this fixture isolates stale Bloom.
|
||||
Shader.SetGlobalVector("_ColorParam", new Vector4(1f, 1f, 1f, 1f));
|
||||
Shader.SetGlobalTexture("_TapLowBackground", low);
|
||||
Shader.SetGlobalTexture("_Bloom", bloom);
|
||||
Shader.SetGlobalTexture("_Bloom", Texture2D.blackTexture);
|
||||
using (var cmd = new CommandBuffer())
|
||||
{
|
||||
film.Blit(ref noBloomFilm, cmd, RenderTextureHandle.Make(source),
|
||||
RenderTextureHandle.Make(target), diffusionDof, 11);
|
||||
Graphics.ExecuteCommandBuffer(cmd);
|
||||
}
|
||||
Near(Read(target, read), new Color(0.1f, 0.15f, 0.2f, 1f),
|
||||
"DiffusionDofBloom first film pass with Bloom disabled");
|
||||
Debug.Log("LiveBloomDiffusionRegression GPU PASS: 24 extraction, 9 Bloom and 27 diffusion equations; HDR/Add/Screen, three-layer Bloom-once PostFilm, and Bloom-disabled DiffusionDofBloom first film pass");
|
||||
}
|
||||
finally
|
||||
{
|
||||
for (int i = 0; i < floats.Length; ++i) Shader.SetGlobalFloat(floats[i], oldFloats[i]);
|
||||
for (int i = 0; i < vectors.Length; ++i) Shader.SetGlobalVector(vectors[i], oldVectors[i]);
|
||||
Shader.SetGlobalTexture("_Bloom", oldBloom);
|
||||
Shader.SetGlobalTexture("_RgbTex", oldRgb);
|
||||
Shader.SetGlobalTexture("_TapLowBackground", oldLowBackground);
|
||||
RenderTexture.active = previous;
|
||||
foreach (var rt in new[] { source, low, vertical, bloom, target }) { rt.Release(); UnityEngine.Object.DestroyImmediate(rt); }
|
||||
UnityEngine.Object.DestroyImmediate(read);
|
||||
if (fast) UnityEngine.Object.DestroyImmediate(fast);
|
||||
if (post) UnityEngine.Object.DestroyImmediate(post);
|
||||
if (diffusion) UnityEngine.Object.DestroyImmediate(diffusion);
|
||||
if (diffusionDof) UnityEngine.Object.DestroyImmediate(diffusionDof);
|
||||
bundle.Unload(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e9872ed211ac4fa4bdbde21cc709704e
|
||||
@@ -0,0 +1,81 @@
|
||||
#if UNITY_EDITOR
|
||||
using System;
|
||||
using System.Linq;
|
||||
using UnityEngine;
|
||||
|
||||
// Reference manifests describe timeline frames; video extraction offsets must NOT
|
||||
// be applied a second time when seeking the Live Director.
|
||||
[Serializable]
|
||||
public sealed class LiveCapturePlan
|
||||
{
|
||||
public int songId = 1001;
|
||||
public string stageId = "10102";
|
||||
public string[] characters;
|
||||
public int fps = 60, width = 1920, height = 1080;
|
||||
public int[] frames;
|
||||
|
||||
public static LiveCapturePlan Default()
|
||||
{
|
||||
return new LiveCapturePlan {
|
||||
characters = new[] { "1068_00", "1006_00", "1030_00" }
|
||||
.Concat(Enumerable.Repeat("1003_00", 15)).ToArray(),
|
||||
frames = new[] { 1710, 1732, 1740, 1755, 3000 }
|
||||
};
|
||||
}
|
||||
public void Validate()
|
||||
{
|
||||
if (songId <= 0 || string.IsNullOrEmpty(stageId) || fps != 60 ||
|
||||
width < 1 || height < 1 || width > 8192 || height > 8192 ||
|
||||
frames == null || frames.Length == 0 || frames.Any(x => x < 0) ||
|
||||
frames.Distinct().Count() != frames.Length || characters == null || characters.Length == 0)
|
||||
throw new InvalidOperationException("Invalid Live capture manifest (60fps timeline required).");
|
||||
foreach (string character in characters)
|
||||
{
|
||||
ParseCharacterIdentity(character, out _, out _);
|
||||
}
|
||||
}
|
||||
// The first separator belongs to the capture identity; remaining separators
|
||||
// are part of a generic costume ID (e.g. 0001_00), not extra characters.
|
||||
public static void ParseCharacterIdentity(string identity, out int id, out string costume)
|
||||
{
|
||||
int separator = (identity ?? "").IndexOf('_');
|
||||
id = 0;
|
||||
costume = separator >= 0 ? identity.Substring(separator + 1) : "";
|
||||
if (separator <= 0 || !int.TryParse(identity.Substring(0, separator), out id) || id <= 0 ||
|
||||
costume.Split('_').Any(part => part.Length == 0 || part.Any(c => c < '0' || c > '9')))
|
||||
throw new InvalidOperationException("Invalid reference character/costume identity.");
|
||||
}
|
||||
|
||||
public void SelectFrames(int[] selected)
|
||||
{
|
||||
if (selected == null || selected.Length == 0 || selected.Any(x => !frames.Contains(x)))
|
||||
throw new InvalidOperationException("Requested capture frames must exist in the reference manifest.");
|
||||
var previous = frames;
|
||||
frames = selected;
|
||||
try { Validate(); } catch { frames = previous; throw; }
|
||||
}
|
||||
public bool MatchesIdentity(int song, string stage, string[] cast)
|
||||
{
|
||||
return song == songId && stage == stageId && cast != null && characters.SequenceEqual(cast);
|
||||
}
|
||||
}
|
||||
|
||||
// Require consecutive renders at the intended timeline frame, not editor update
|
||||
// ticks. Duplicate camera callbacks in one Unity frame cannot advance the gate.
|
||||
public sealed class LiveCaptureStabilityGate
|
||||
{
|
||||
readonly int required;
|
||||
int count, lastUnityFrame = -1;
|
||||
public LiveCaptureStabilityGate(int requiredFrames = 60) { required = requiredFrames; }
|
||||
public void Reset() { count = 0; lastUnityFrame = -1; }
|
||||
public bool Observe(float seconds, int timelineFrame, int fps, int unityFrame, bool ready)
|
||||
{
|
||||
if (unityFrame == lastUnityFrame) return false;
|
||||
lastUnityFrame = unityFrame;
|
||||
if (!ready || float.IsNaN(seconds) || float.IsInfinity(seconds) ||
|
||||
Math.Abs((double)seconds * fps - timelineFrame) > .1)
|
||||
{ count = 0; return false; }
|
||||
return ++count >= required;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7d316dcf24d44b9c853e3db15e3d802d
|
||||
@@ -0,0 +1,105 @@
|
||||
#if UNITY_EDITOR
|
||||
using System;
|
||||
using System.IO;
|
||||
using UnityEngine;
|
||||
using Gallop.RenderPipeline;
|
||||
using Overlay = Gallop.ImageEffect.ScreenOverlay.Overlay;
|
||||
|
||||
public static class LiveCaptureContractRegression
|
||||
{
|
||||
static void Check(bool ok, string message)
|
||||
{ if (!ok) throw new Exception("LiveCaptureContractRegression: " + message); }
|
||||
static void Reject(Action action, string message)
|
||||
{
|
||||
bool rejected = false;
|
||||
try { action(); } catch (InvalidOperationException) { rejected = true; }
|
||||
Check(rejected, message);
|
||||
}
|
||||
public static void Run()
|
||||
{
|
||||
Check(Application.isBatchMode, "isolated batch only");
|
||||
var plan = LiveCapturePlan.Default(); plan.Validate();
|
||||
LiveCapturePlan.ParseCharacterIdentity("1068_0001_00", out int genericId, out string genericCostume);
|
||||
Check(genericId == 1068 && genericCostume == "0001_00", "full generic costume preserved");
|
||||
LiveCapturePlan.ParseCharacterIdentity("1068_00", out int normalId, out string normalCostume);
|
||||
Check(normalId == 1068 && normalCostume == "00", "short costume preserved");
|
||||
foreach (string bad in new[] { "", "1068", "1068_", "1068__00", "1068_00_", "1068_../00", "0_00" })
|
||||
Reject(() => LiveCapturePlan.ParseCharacterIdentity(bad, out _, out _), "reject malformed identity");
|
||||
var genericPlan = LiveCapturePlan.Default();
|
||||
genericPlan.characters[0] = "1068_0001_00";
|
||||
genericPlan.Validate();
|
||||
var genericRoundTrip = JsonUtility.FromJson<LiveCapturePlan>(JsonUtility.ToJson(genericPlan));
|
||||
genericRoundTrip.Validate();
|
||||
Check(genericRoundTrip.MatchesIdentity(genericPlan.songId, genericPlan.stageId, genericPlan.characters), "generic identity survives reload");
|
||||
Check(!genericRoundTrip.MatchesIdentity(genericPlan.songId, genericPlan.stageId, LiveCapturePlan.Default().characters), "generic costume not truncated during comparison");
|
||||
Check(plan.characters.Length == 18 && plan.MatchesIdentity(1001, "10102", plan.characters), "default aligned identity");
|
||||
Check(!plan.MatchesIdentity(1176, "10102", plan.characters) && !plan.MatchesIdentity(1001, "other", plan.characters), "reject wrong song/stage");
|
||||
var cast = (string[])plan.characters.Clone(); cast[0] = "1068_02";
|
||||
Check(!plan.MatchesIdentity(1001, "10102", cast), "reject wrong costume");
|
||||
Reject(() => plan.SelectFrames(new[] { 1 }), "reject reference-missing frame");
|
||||
Reject(() => plan.SelectFrames(new[] { 1740, 1740 }), "reject duplicate and restore plan");
|
||||
Check(plan.frames.Length == 5, "bad subset must not mutate plan");
|
||||
plan.SelectFrames(new[] { 3000, 1740 });
|
||||
Check(plan.frames[0] == 3000, "backseek capture order retained");
|
||||
var restored = JsonUtility.FromJson<LiveCapturePlan>(JsonUtility.ToJson(plan));
|
||||
restored.Validate(); Check(restored.frames[1] == 1740 && restored.characters[2] == "1030_00", "domain-reload plan roundtrip");
|
||||
foreach (string name in new[] { "UMA_CAPTURE_TEST_REFERENCE1001", "UMA_CAPTURE_TEST_REFERENCE1176" })
|
||||
{
|
||||
string path = Environment.GetEnvironmentVariable(name);
|
||||
Check(Path.GetFileName(path) == "manifest.json" && File.Exists(path), "explicit real reference manifest");
|
||||
var reference = JsonUtility.FromJson<LiveCapturePlan>(File.ReadAllText(path));
|
||||
reference.Validate();
|
||||
Check(reference.songId == (name.EndsWith("1176") ? 1176 : 1001), "actual song manifest identity");
|
||||
reference.SelectFrames(new[] { reference.frames[1], reference.frames[reference.frames.Length - 1] });
|
||||
}
|
||||
var gate = new LiveCaptureStabilityGate();
|
||||
for (int i = 0; i < 59; ++i)
|
||||
{
|
||||
Check(!gate.Observe(50, 3000, 60, i, true), "needs sixty distinct renders");
|
||||
Check(!gate.Observe(50, 3000, 60, i, true), "duplicate callback doesn't advance");
|
||||
}
|
||||
Check(gate.Observe(50, 3000, 60, 59, true), "sixtieth correct render ready");
|
||||
gate.Reset();
|
||||
for (int i = 0; i < 80; ++i) Check(!gate.Observe(49, 3000, 60, i, true), "old frame cannot be mislabeled");
|
||||
Check(!gate.Observe(float.NaN, 3000, 60, 80, true), "invalid clock");
|
||||
for (int i = 81; i < 140; ++i) Check(!gate.Observe(50, 3000, 60, i, true), "settle after mismatch");
|
||||
Check(!gate.Observe(50, 3000, 60, 140, false), "shader/feature unavailable clears settle");
|
||||
for (int i = 141; i < 200; ++i) Check(!gate.Observe(50, 3000, 60, i, true), "settle after readiness loss");
|
||||
Check(gate.Observe(50, 3000, 60, 200, true), "stable readiness restored");
|
||||
// Simulate the exact scoped noFilm parameter mutation without a Live camera.
|
||||
// The URP 14 callback order is begin -> AddRenderPasses -> Execute -> end;
|
||||
// this contract tests struct write-back and restoration, not GPU pixels.
|
||||
var runtime = PostImageEffectFeature.RuntimeParameter;
|
||||
var old = runtime.DofDiffuionBloomOverlay;
|
||||
try
|
||||
{
|
||||
var film = old;
|
||||
film.Overlay1.PostFilmMode = Overlay.PostFilmMode.Add;
|
||||
film.Overlay1.PostFilmPower = .31f;
|
||||
film.Overlay2.PostFilmMode = Overlay.PostFilmMode.Mul;
|
||||
film.Overlay2.PostFilmPower = .42f;
|
||||
film.Overlay3.PostFilmMode = Overlay.PostFilmMode.ScreenBlend;
|
||||
film.Overlay3.PostFilmPower = .53f;
|
||||
runtime.DofDiffuionBloomOverlay = film;
|
||||
LiveRenderCapture.SuppressFilm();
|
||||
var suppressed = runtime.DofDiffuionBloomOverlay;
|
||||
Check(!suppressed.IsEnableOverlay && suppressed.Overlay1.PostFilmPower == .31f &&
|
||||
suppressed.Overlay2.PostFilmPower == .42f && suppressed.Overlay3.PostFilmPower == .53f,
|
||||
"noFilm must suppress all three overlay validity flags without changing strengths");
|
||||
Reject(() => LiveRenderCapture.SuppressFilm(), "nested film suppression must fail");
|
||||
suppressed.BloomIntensity = .67f; // another callback can change unrelated timeline state
|
||||
runtime.DofDiffuionBloomOverlay = suppressed;
|
||||
LiveRenderCapture.RestoreFilm();
|
||||
var restoredFilm = runtime.DofDiffuionBloomOverlay;
|
||||
Check(restoredFilm.Overlay1.PostFilmMode == Overlay.PostFilmMode.Add &&
|
||||
restoredFilm.Overlay2.PostFilmMode == Overlay.PostFilmMode.Mul &&
|
||||
restoredFilm.Overlay3.PostFilmMode == Overlay.PostFilmMode.ScreenBlend &&
|
||||
restoredFilm.BloomIntensity == .67f,
|
||||
"restoration must preserve other timeline fields and all three modes");
|
||||
LiveRenderCapture.RestoreFilm(); // harmless after an early cancellation
|
||||
}
|
||||
finally { LiveRenderCapture.RestoreFilm(); runtime.DofDiffuionBloomOverlay = old; }
|
||||
Debug.Log("LiveCaptureContractRegression PASS: two actual reference manifests, identity/subset/reload, stale-frame/duplicate/readiness gates. No full Live was loaded.");
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6aeed533117c4250b51792e7cee86d78
|
||||
@@ -0,0 +1,193 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using Gallop.Live.Cutt;
|
||||
using Gallop.RenderPipeline;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
using Overlay = Gallop.ImageEffect.ScreenOverlay.Overlay;
|
||||
|
||||
// Film-only attribution on already captured real pixels. This is NOT a full Live replay:
|
||||
// input is before DOF/Bloom/diffusion; actual depth is absent. Synced BlinkLight RGB
|
||||
// is available only when explicitly recovered from same-frame runtime metadata.
|
||||
// Raw-depth sweeps are explicitly counterfactual, not estimated scene depth.
|
||||
public static class LiveCapturedFilmAttribution
|
||||
{
|
||||
[Serializable] public class CurveKey { public float time, value, inSlope, outSlope, inWeight, outWeight; public int weightedMode; }
|
||||
[Serializable] public class Row { public LiveTimelineKeyPostFilmData key; public CurveKey[] curveKeys; public int preWrap, postWrap; }
|
||||
[Serializable] public class Track { public string name; public int attribute, playMode; public Row[] rows; }
|
||||
[Serializable] public class Frame { public int frame; public string imagePath, sha256; public float[] expectedPowers; public Color rawBlinkRgb; public Color[] expectedColor0; public string blinkLookup; }
|
||||
[Serializable] public class Input { public Track[] tracks; public Frame[] frames; }
|
||||
[Serializable] public class Stats {
|
||||
public string image, stage; public int frame, layer, omittedLayer; public float rawDepth;
|
||||
public float[] mean, maximum; public float anyChannelOverOne, allChannelsNearWhite;
|
||||
public float shaderParityMaxError;
|
||||
}
|
||||
[Serializable] public class ParameterRecord {
|
||||
public int frame, layer; public string mode; public float power, depthPower, depthClip;
|
||||
public bool valid, inverse; public Vector2 offset; public Vector4 options; public Color[] colors;
|
||||
}
|
||||
[Serializable] public class Report {
|
||||
public string limitation, colorSpace, inputPath; public List<ParameterRecord> parameters = new List<ParameterRecord>();
|
||||
public List<Stats> stages = new List<Stats>();
|
||||
}
|
||||
static void Check(bool ok, string message) { if (!ok) throw new Exception("CapturedFilmAttribution: " + message); }
|
||||
static RenderTexture RT(int w, int h, RenderTextureFormat format) {
|
||||
var rt = new RenderTexture(w, h, 0, format, RenderTextureReadWrite.Default) { filterMode = FilterMode.Bilinear, wrapMode = TextureWrapMode.Clamp };
|
||||
rt.Create(); return rt;
|
||||
}
|
||||
static Color[] Read(RenderTexture rt) {
|
||||
var old = RenderTexture.active;
|
||||
var read = new Texture2D(rt.width, rt.height, TextureFormat.RGBAFloat, false, true);
|
||||
try { RenderTexture.active = rt; read.ReadPixels(new Rect(0,0,rt.width,rt.height),0,0); read.Apply(); return read.GetPixels(); }
|
||||
finally { RenderTexture.active = old; UnityEngine.Object.DestroyImmediate(read); }
|
||||
}
|
||||
static void Save(RenderTexture rt, string path) {
|
||||
var old = RenderTexture.active;
|
||||
var read = new Texture2D(rt.width, rt.height, TextureFormat.RGBA32, false, true);
|
||||
try { RenderTexture.active = rt; read.ReadPixels(new Rect(0,0,rt.width,rt.height),0,0); read.Apply(); File.WriteAllBytes(path, read.EncodeToPNG()); }
|
||||
finally { RenderTexture.active = old; UnityEngine.Object.DestroyImmediate(read); }
|
||||
}
|
||||
static Stats Measure(Color[] pixels, int frame, float depth, int layer, string stage, int omitted = 0) {
|
||||
var sums = new double[3]; var maximum = new float[3]; int over = 0, white = 0;
|
||||
foreach (var p in pixels) {
|
||||
bool any = false, all = true;
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
Check(!float.IsNaN(p[c]) && !float.IsInfinity(p[c]), "non-finite output");
|
||||
sums[c] += p[c]; maximum[c] = Mathf.Max(maximum[c], p[c]);
|
||||
any |= p[c] > 1.0001f; all &= p[c] >= 250f / 255f;
|
||||
}
|
||||
if (any) ++over; if (all) ++white;
|
||||
}
|
||||
return new Stats { frame=frame, rawDepth=depth, layer=layer, stage=stage, omittedLayer=omitted,
|
||||
mean=Array.ConvertAll(sums, x => (float)(x / pixels.Length)), maximum=maximum,
|
||||
anyChannelOverOne=over/(float)pixels.Length, allChannelsNearWhite=white/(float)pixels.Length };
|
||||
}
|
||||
static void Draw(ScreenOverlayRender.Render renderer, ref ScreenOverlayRender.Parameter param,
|
||||
Texture source, RenderTexture target, Material material, int pass) {
|
||||
using (var cmd = new CommandBuffer()) {
|
||||
if (source is RenderTexture rt)
|
||||
renderer.Blit(ref param, cmd, RenderTextureHandle.Make(rt), RenderTextureHandle.Make(target), material, pass);
|
||||
else throw new Exception("Source must have an explicit RT descriptor");
|
||||
Graphics.ExecuteCommandBuffer(cmd);
|
||||
}
|
||||
}
|
||||
public static void Run() {
|
||||
Check(Application.isBatchMode, "isolated batch-mode only; do not use user's Editor");
|
||||
Check(QualitySettings.activeColorSpace == ColorSpace.Gamma, "captured Gamma project required");
|
||||
string inputPath = Environment.GetEnvironmentVariable("UMA_FILM_ATTRIBUTION_INPUT");
|
||||
string output = Environment.GetEnvironmentVariable("UMA_FILM_ATTRIBUTION_OUTPUT");
|
||||
string bundlePath = Environment.GetEnvironmentVariable("UMA_POSTFILM_TEST_BUNDLE");
|
||||
Check(File.Exists(inputPath) && File.Exists(bundlePath) && !string.IsNullOrEmpty(output), "missing input environment");
|
||||
Directory.CreateDirectory(output);
|
||||
var input = JsonUtility.FromJson<Input>(File.ReadAllText(inputPath));
|
||||
Check(input.tracks.Length == 3 && input.frames.Length == 3, "three authored tracks and three real frames");
|
||||
var tracks = new LiveTimelineKeyPostFilmDataList[3];
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
var t = input.tracks[i];
|
||||
tracks[i] = new LiveTimelineKeyPostFilmDataList { attribute=(LiveTimelineKeyDataListAttr)t.attribute, playMode=(TimelineKeyPlayMode)t.playMode };
|
||||
foreach (var row in t.rows) {
|
||||
var keys = Array.ConvertAll(row.curveKeys, x => new Keyframe(x.time,x.value,x.inSlope,x.outSlope,x.inWeight,x.outWeight) { weightedMode=(WeightedMode)x.weightedMode });
|
||||
row.key.curve = new AnimationCurve(keys) { preWrapMode=(WrapMode)row.preWrap, postWrapMode=(WrapMode)row.postWrap };
|
||||
tracks[i].thisList.Add(row.key);
|
||||
}
|
||||
}
|
||||
var report = new Report { inputPath=inputPath, colorSpace=QualitySettings.activeColorSpace.ToString(),
|
||||
limitation="Film-only, before-DOF/Bloom real captured input. Raw hardware-depth sweep is counterfactual; no captured depth, captured BlinkLight RGB when present, no color correction or game-reference parity. Float probes measure shader outputs before ARGB32 clamping; next layer consumes ARGB32 just as native film ping-pong." };
|
||||
var bundle = AssetBundle.LoadFromFile(bundlePath);
|
||||
Check(bundle != null, "load official shader bundle");
|
||||
Material film=null, combined=null;
|
||||
var oldDepth=Shader.GetGlobalTexture("_CameraDepthTexture"); var oldScroll=Shader.GetGlobalVector("_GlobalScreenUVScrollParam");
|
||||
var oldInverseSize=Shader.GetGlobalVector("_InvRenderTargetSize");
|
||||
var depth = new Texture2D(1,1,TextureFormat.RFloat,false,true) { filterMode=FilterMode.Point };
|
||||
try {
|
||||
foreach (var shader in bundle.LoadAllAssets<Shader>()) {
|
||||
if (shader.name == "Gallop/ImageEffects/Rich/PostBlit_Rich") film = new Material(shader);
|
||||
if (shader.name == "Gallop/ImageEffects/Rich/PostDiffusionDofBloom_Rich") combined = new Material(shader);
|
||||
}
|
||||
Check(film != null && film.shader.isSupported && combined != null && combined.shader.isSupported, "shipped shaders supported");
|
||||
film.SetColor("_DimmerColor",Color.white); combined.SetColor("_DimmerColor",Color.white);
|
||||
Shader.DisableKeyword("COLOR_ONLY"); // Match production's color-layer Apply (no enabled blend keyword).
|
||||
Shader.SetGlobalVector("_GlobalScreenUVScrollParam",Vector4.zero);
|
||||
var renderer = new ScreenOverlayRender.Render();
|
||||
foreach (var f in input.frames) {
|
||||
using (var hash = SHA256.Create()) {
|
||||
string actual = BitConverter.ToString(hash.ComputeHash(File.ReadAllBytes(f.imagePath))).Replace("-","").ToLowerInvariant();
|
||||
Check(actual==f.sha256,"input hash " + f.frame);
|
||||
}
|
||||
var image = new Texture2D(2,2,TextureFormat.RGBA32,false,true);
|
||||
Check(image.LoadImage(File.ReadAllBytes(f.imagePath),false),"load real pixels");
|
||||
var source = RT(image.width,image.height,RenderTextureFormat.ARGB32);
|
||||
var a = RT(image.width,image.height,RenderTextureFormat.ARGB32);
|
||||
var b = RT(image.width,image.height,RenderTextureFormat.ARGB32);
|
||||
var probe = RT(image.width,image.height,RenderTextureFormat.ARGBFloat);
|
||||
var alternate = RT(image.width,image.height,RenderTextureFormat.ARGBFloat);
|
||||
try {
|
||||
Graphics.Blit(image,source);
|
||||
Shader.SetGlobalVector("_InvRenderTargetSize",new Vector4(1f/image.width,1f/image.height,image.width,image.height));
|
||||
var param = new ScreenOverlayRender.Parameter[3];
|
||||
for (int i=0;i<3;++i) {
|
||||
var overlay = new Overlay();
|
||||
if (f.expectedColor0 != null && f.expectedColor0.Length == 3) {
|
||||
// Captured current-stage raw RGB, recovered only from a unit-brightness
|
||||
// sync layer. Native key brightness is applied inside Evaluate.
|
||||
LivePostFilmTimeline.BlinkColorResolver resolve = delegate(string name,int hash,int index,out Color raw) {
|
||||
raw = f.rawBlinkRgb; return true;
|
||||
};
|
||||
LivePostFilmTimeline.Evaluate(tracks[i],f.frame,TimelinePlayerMode.Default,overlay,resolve);
|
||||
var expected=f.expectedColor0[i]; var actual=overlay.postFilmColor0;
|
||||
Check(Mathf.Abs(actual.r-expected.r)<0.0002f && Mathf.Abs(actual.g-expected.g)<0.0002f &&
|
||||
Mathf.Abs(actual.b-expected.b)<0.0002f && Mathf.Abs(actual.a-expected.a)<0.0002f,
|
||||
"captured synced color0 frame="+f.frame+" layer="+(i+1)+" actual="+actual+" expected="+expected);
|
||||
} else LivePostFilmTimeline.Evaluate(tracks[i],f.frame,TimelinePlayerMode.Default,overlay);
|
||||
param[i]=ScreenOverlayRender.Parameter.Default(); param[i].Setup(overlay);
|
||||
Check(Mathf.Abs(param[i].PostFilmPower-f.expectedPowers[i])<0.0002f,"evaluated power vs captured runtime frame="+f.frame+" layer="+(i+1)+" actual="+param[i].PostFilmPower+" expected="+f.expectedPowers[i]);
|
||||
report.parameters.Add(new ParameterRecord { frame=f.frame, layer=i+1, mode=param[i].PostFilmMode.ToString(),power=param[i].PostFilmPower,depthPower=param[i].DepthPower,depthClip=param[i].DepthClip,valid=param[i].IsValidity,inverse=param[i].InverseVignette,offset=param[i].PostFilmOffsetParam,options=param[i].PostFilmOptionParam,colors=new[]{param[i].PostFilmColor0,param[i].PostFilmColor1,param[i].PostFilmColor2,param[i].PostFilmColor3} });
|
||||
}
|
||||
report.stages.Add(Measure(Read(source),f.frame,-1,0,"input"));
|
||||
foreach (float raw in new[]{0f,0.02f,0.1f,1f}) {
|
||||
depth.SetPixel(0,0,new Color(raw,0,0,1)); depth.Apply(); Shader.SetGlobalTexture("_CameraDepthTexture",depth);
|
||||
RenderTexture current=source;
|
||||
for (int i=0;i<3;++i) {
|
||||
RenderTexture next = current==a ? b : a;
|
||||
if (param[i].IsValidity) {
|
||||
Draw(renderer,ref param[i],current,probe,film,i==0?1:3);
|
||||
// Production later-pass arithmetic should match plain PostBlit on identical inputs.
|
||||
Draw(renderer,ref param[i],current,alternate,combined,13);
|
||||
var values=Read(probe); var other=Read(alternate); float maxError=0;
|
||||
for (int n=0;n<values.Length;++n) for (int c=0;c<3;++c) maxError=Mathf.Max(maxError,Mathf.Abs(values[n][c]-other[n][c]));
|
||||
Check(maxError<0.002f,"film variant parity " + maxError);
|
||||
var measured=Measure(values,f.frame,raw,i+1,"before-output-clamp"); measured.shaderParityMaxError=maxError; report.stages.Add(measured);
|
||||
Draw(renderer,ref param[i],current,next,film,i==0?1:3);
|
||||
} else Graphics.Blit(current,next);
|
||||
string name="frame"+f.frame.ToString("D6")+"_rawdepth"+raw.ToString("0.00",CultureInfo.InvariantCulture)+"_layer"+(i+1)+".png";
|
||||
Save(next,Path.Combine(output,name)); var s=Measure(Read(next),f.frame,raw,i+1,"ARGB32"); s.image=name; report.stages.Add(s); current=next;
|
||||
}
|
||||
// Leave-one-layer-out experiments retain actual authored powers/order of all other layers.
|
||||
for (int omitted=1;omitted<=3;++omitted) {
|
||||
current=source;
|
||||
for (int i=0;i<3;++i) {
|
||||
RenderTexture next=current==a ? b : a;
|
||||
if (i+1!=omitted && param[i].IsValidity) Draw(renderer,ref param[i],current,next,film,i==0?1:3);
|
||||
else Graphics.Blit(current,next);
|
||||
current=next;
|
||||
}
|
||||
string name="frame"+f.frame.ToString("D6")+"_rawdepth"+raw.ToString("0.00",CultureInfo.InvariantCulture)+"_omit"+omitted+".png";
|
||||
Save(current,Path.Combine(output,name)); var s=Measure(Read(current),f.frame,raw,3,"counterfactual-omit",omitted); s.image=name; report.stages.Add(s);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
foreach (var rt in new[]{source,a,b,probe,alternate}) { rt.Release(); UnityEngine.Object.DestroyImmediate(rt); }
|
||||
UnityEngine.Object.DestroyImmediate(image);
|
||||
}
|
||||
}
|
||||
File.WriteAllText(Path.Combine(output,"report.json"),JsonUtility.ToJson(report,true));
|
||||
Debug.Log("LiveCapturedFilmAttribution PASS: real PNG hashes, nine exact runtime powers, captured sync RGB when provided, authored curves, film variant parity, counterfactual depth sweeps and omit-one layers. NOT full Live parity. Output="+output);
|
||||
} finally {
|
||||
Shader.SetGlobalTexture("_CameraDepthTexture",oldDepth); Shader.SetGlobalVector("_GlobalScreenUVScrollParam",oldScroll); Shader.SetGlobalVector("_InvRenderTargetSize",oldInverseSize);
|
||||
UnityEngine.Object.DestroyImmediate(depth); if(film!=null)UnityEngine.Object.DestroyImmediate(film); if(combined!=null)UnityEngine.Object.DestroyImmediate(combined); bundle.Unload(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: eb50b061425a55a418609340033b5c03
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,313 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using Gallop.Live.Cutt;
|
||||
using Gallop.RenderPipeline;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
|
||||
public static class LiveColorCorrectionRegression
|
||||
{
|
||||
static void Check(bool condition, string message)
|
||||
{
|
||||
if (!condition) throw new Exception("LiveColorCorrectionRegression: " + message);
|
||||
}
|
||||
static void Draw(Material material, Texture lut, float saturation, Texture source, RenderTexture output)
|
||||
{
|
||||
using (var cmd = new CommandBuffer())
|
||||
{
|
||||
// Deliberately poison uniforms: production must establish all draw state.
|
||||
Shader.SetGlobalFloat("_PostFilmPower", 1);
|
||||
Shader.SetGlobalFloat("_Saturation", -8);
|
||||
SimpleColorCorrectionPass.Render(cmd, material, lut, saturation,
|
||||
new RenderTargetIdentifier(source), new RenderTargetIdentifier(output));
|
||||
Graphics.ExecuteCommandBuffer(cmd);
|
||||
Check(Shader.GetGlobalTexture("_RgbTex") == Texture2D.blackTexture, "release LUT global binding");
|
||||
}
|
||||
}
|
||||
static void RunSchedule()
|
||||
{
|
||||
int checks = 0;
|
||||
foreach (int evt in new[] { 500, 550, 600 })
|
||||
for (int mask = 1; mask < 8; ++mask)
|
||||
{
|
||||
bool dof = (mask & 1) != 0, radial = (mask & 2) != 0, color = (mask & 4) != 0;
|
||||
var schedule = PostImageEffectFeature.GetColorChainSchedule(dof, radial, color,
|
||||
(UnityEngine.Rendering.Universal.RenderPassEvent)evt);
|
||||
// Model source ownership in actual event order; a camera resolve consumes temps.
|
||||
var steps = new System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<int, string>>();
|
||||
Action<int, string> add = (e, name) => steps.Add(new System.Collections.Generic.KeyValuePair<int, string>(e, name));
|
||||
add(schedule.FirstEvent, "source");
|
||||
if (dof) add(evt, "dof");
|
||||
if (radial) add(evt, "radial");
|
||||
if (color) add(550, "color");
|
||||
if (schedule.EarlyResolve) add(550, "resolve");
|
||||
if (schedule.FinalResolve) add(schedule.LastEvent, "resolve");
|
||||
// LINQ OrderBy is stable, like URP's pass event sort.
|
||||
bool sourceIsCamera = true, initialized = false;
|
||||
foreach (var step in System.Linq.Enumerable.OrderBy(steps, x => x.Key))
|
||||
{
|
||||
if (step.Value == "source") { initialized = true; continue; }
|
||||
Check(initialized, "source setup must run first");
|
||||
if ((step.Value == "dof" || step.Value == "radial") && step.Key > 550)
|
||||
Check(sourceIsCamera, "late effects must not discard an unresolved color temp");
|
||||
if (step.Value == "color" || step.Value == "radial" || (step.Value == "dof" && step.Key <= 550))
|
||||
sourceIsCamera = false;
|
||||
if (step.Value == "resolve") sourceIsCamera = true;
|
||||
}
|
||||
Check(sourceIsCamera, "final result must resolve to camera");
|
||||
checks++;
|
||||
}
|
||||
Debug.Log("LiveColorCorrection schedule PASS: " + checks + " pass combinations/event boundaries (ownership model, not full URP execution)");
|
||||
}
|
||||
static void RunTimeline(LiveTimelineWorkSheet sheet)
|
||||
{
|
||||
RunSchedule();
|
||||
var groups = sheet.colorCorrectionDataLists;
|
||||
var keys = groups[0].keys.thisList;
|
||||
Func<float, SimpleColorCorrectionPass.Parameter> sample = frame =>
|
||||
LiveColorCorrectionTimeline.Evaluate(groups, frame, TimelinePlayerMode.Default);
|
||||
Check(!sample(-1).Enabled && !sample(float.NaN).Enabled && !sample(float.PositiveInfinity).Enabled,
|
||||
"pre-first and invalid time bypass");
|
||||
Check(!LiveColorCorrectionTimeline.Evaluate(null, 0, TimelinePlayerMode.Default).Enabled, "absent worksheet clears");
|
||||
using (var pass = new SimpleColorCorrectionPass())
|
||||
{
|
||||
Check((int)pass.renderPassEvent == 550, "native color event");
|
||||
foreach (int i in new[] { 0, 1, 2, 3, 4, 5, 3, 0, 5 })
|
||||
{
|
||||
var value = sample(keys[i].frame);
|
||||
Check(value.IsValid && value.Red == keys[i].redCurve, "exact cut/seek " + i);
|
||||
if (i > 0) Check(sample(keys[i].frame - .25f).Red == keys[i-1].redCurve, "hold until cut " + i);
|
||||
int before = pass.LutUploadCount;
|
||||
Check(pass.Prepare(value), "prepare valid");
|
||||
Check(pass.LutUploadCount == before + 1, "cut/seek uploads once");
|
||||
var texture = pass.LutTexture;
|
||||
for (int j = 0; j < 20; ++j) Check(pass.Prepare(value), "repeat valid");
|
||||
value.Saturation = .7f; pass.Prepare(value);
|
||||
Check(pass.LutUploadCount == before + 1 && texture == pass.LutTexture, "stable/saturation avoids upload");
|
||||
}
|
||||
Check(!pass.Prepare(default), "disable");
|
||||
int uploads = pass.LutUploadCount;
|
||||
pass.Prepare(sample(keys[5].frame));
|
||||
Check(pass.LutUploadCount == uploads + 1, "reenable refresh");
|
||||
pass.Dispose(); Check(pass.LutTexture == null, "pass LUT dispose");
|
||||
pass.Prepare(sample(0)); Check(pass.LutTexture != null, "pass recreate");
|
||||
}
|
||||
var list = groups[0].keys;
|
||||
var oldAttribute = list.attribute;
|
||||
list.attribute = LiveTimelineKeyDataListAttr.Disable;
|
||||
Check(!sample(0).Enabled, "disabled list"); list.attribute = oldAttribute;
|
||||
var key = keys[0];
|
||||
key.enable = 0; Check(!sample(0).Enabled, "disabled key"); key.enable = 1;
|
||||
key.mode = 1; Check(!sample(0).Enabled, "advanced bypass"); key.mode = 0;
|
||||
key.selective = 1; Check(!sample(0).Enabled, "selective bypass"); key.selective = 0;
|
||||
groups.Add(groups[0]); Check(!sample(0).Enabled, "ambiguous groups bypass"); groups.RemoveAt(1);
|
||||
PostImageEffectFeature.RuntimeParameter.ColorCorrection = sample(0);
|
||||
var copy = new PostImageEffectFeature.Parameter();
|
||||
copy.ShallowCopyFrom(PostImageEffectFeature.RuntimeParameter);
|
||||
Check(copy.ColorCorrection.IsValid && copy.ColorCorrection.Red == keys[0].redCurve, "parameter copy preserves color");
|
||||
PostImageEffectFeature.ResetRuntimeParameter();
|
||||
Check(!PostImageEffectFeature.RuntimeParameter.ColorCorrection.Enabled, "live teardown reset");
|
||||
Debug.Log("LiveColorCorrection timeline/cache PASS: six real cuts, reverse seek, unsupported modes, reset, LUT lifecycle");
|
||||
}
|
||||
// D3D normalized sampling: pixel centers at (i+.5)/width, exact RGB row centers.
|
||||
// Do not use Texture2D.GetPixelBilinear as a GPU oracle (CPU coordinate convention).
|
||||
static float SampleRow(Texture2D lut, float u, int row)
|
||||
{
|
||||
float x = Mathf.Clamp(u * 256f - 0.5f, 0, 255);
|
||||
int a = Mathf.FloorToInt(x), b = Mathf.Min(a + 1, 255);
|
||||
return Mathf.Lerp(lut.GetPixel(a, row).r, lut.GetPixel(b, row).r, x - a);
|
||||
}
|
||||
static Color Expected(Texture2D lut, Color source, float saturation)
|
||||
{
|
||||
var color = new Color(SampleRow(lut, source.r, 0),
|
||||
SampleRow(lut, source.g, 1), SampleRow(lut, source.b, 2), source.a);
|
||||
float luminance = color.r * 0.2126729f + color.g * 0.7151522f + color.b * 0.072175f;
|
||||
for (int c = 0; c < 3; ++c) color[c] = luminance + saturation * (color[c] - luminance);
|
||||
return color;
|
||||
}
|
||||
// Spatial fixture: all 256 LUT intervals, distinct RGB/alpha ramps, HDR edges.
|
||||
// Also checks the observed native ordering (Bloom -> curves), not only isolated color swatches.
|
||||
static void RunSpatial(AssetBundle bundle, Material material,
|
||||
System.Collections.Generic.List<LiveTimelineKeyColorCorrectionData> keys, ColorCorrectionCurveLut lut)
|
||||
{
|
||||
const int width = 257, height = 9;
|
||||
var pixels = new Color[width * height];
|
||||
for (int y = 0; y < height; ++y)
|
||||
for (int x = 0; x < width; ++x)
|
||||
{
|
||||
float r = x / 256f;
|
||||
float g = ((x * 73 + y * 29) % 257) / 256f;
|
||||
float b = ((x * 31 + y * 67) % 257) / 256f;
|
||||
if (y == 0) { r -= .2f; g += .4f; }
|
||||
pixels[y * width + x] = new Color(r, g, b, (y * width + x) / (float)(pixels.Length - 1));
|
||||
}
|
||||
var source = new Texture2D(width, height, TextureFormat.RGBAFloat, false, true);
|
||||
var read = new Texture2D(width, height, TextureFormat.RGBAFloat, false, true);
|
||||
var bloom = new Texture2D(1, 1, TextureFormat.RGBAFloat, false, true);
|
||||
var intermediate = new RenderTexture(width, height, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear);
|
||||
var output = new RenderTexture(width, height, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear);
|
||||
var previous = RenderTexture.active;
|
||||
var oldAniso = QualitySettings.anisotropicFiltering;
|
||||
var oldBloom = Shader.GetGlobalTexture("_Bloom");
|
||||
float oldWeight = Shader.GetGlobalFloat("_bloomDofWeight"), oldScreen = Shader.GetGlobalFloat("_BloomIsScreenBlend");
|
||||
Material post = null;
|
||||
int checks = 0, orderWitnesses = 0;
|
||||
Color bloomColor = new Color(.16f, .08f, .24f, 1);
|
||||
try
|
||||
{
|
||||
foreach (var shader in bundle.LoadAllAssets<Shader>())
|
||||
if (shader.name == "Gallop/ImageEffects/Rich/PostBloom_Rich") post = new Material(shader);
|
||||
Check(post && post.shader.isSupported, "spatial Bloom shader");
|
||||
QualitySettings.anisotropicFiltering = AnisotropicFiltering.ForceEnable;
|
||||
Check(lut.Texture.anisoLevel == 0, "data LUT must opt out of forced anisotropic filtering");
|
||||
post.SetColor("_DimmerColor", Color.white);
|
||||
source.filterMode = FilterMode.Point; source.wrapMode = TextureWrapMode.Clamp;
|
||||
source.SetPixels(pixels); source.Apply(false, false);
|
||||
bloom.SetPixel(0, 0, bloomColor); bloom.Apply(false, false);
|
||||
intermediate.Create(); output.Create();
|
||||
Shader.SetGlobalTexture("_Bloom", bloom);
|
||||
Shader.SetGlobalFloat("_bloomDofWeight", .7f);
|
||||
foreach (var key in keys)
|
||||
{
|
||||
lut.Update(key.redCurve, key.greenCurve, key.blueCurve);
|
||||
Shader.SetGlobalTexture("_RgbTex", lut.Texture);
|
||||
// -1 = curves alone, 0 = additive Bloom then curves, 1 = screen Bloom then curves.
|
||||
foreach (int blend in new[] { -1, 0, 1 })
|
||||
foreach (float saturation in new[] { 1f, 0f, 1.4f })
|
||||
{
|
||||
Shader.SetGlobalFloat("_Saturation", saturation);
|
||||
if (blend >= 0)
|
||||
{
|
||||
Shader.SetGlobalFloat("_BloomIsScreenBlend", blend);
|
||||
Graphics.Blit(source, intermediate, post, 0);
|
||||
Draw(material, lut.Texture, saturation, intermediate, output);
|
||||
}
|
||||
else Draw(material, lut.Texture, saturation, source, output);
|
||||
RenderTexture.active = output;
|
||||
read.ReadPixels(new Rect(0, 0, width, height), 0, 0); read.Apply(false, false);
|
||||
var actual = read.GetPixels();
|
||||
for (int i = 0; i < pixels.Length; ++i)
|
||||
{
|
||||
Color composed = pixels[i];
|
||||
if (blend >= 0)
|
||||
{
|
||||
for (int c = 0; c < 4; ++c)
|
||||
composed[c] = blend == 0 ? composed[c] + bloomColor[c] * .7f :
|
||||
1 - (1 - composed[c]) * (1 - bloomColor[c] * .7f);
|
||||
// Native PostBloom_Rich applies Add/Screen to all four channels.
|
||||
}
|
||||
Color expected = Expected(lut.Texture, composed, saturation);
|
||||
for (int c = 0; c < 4; ++c)
|
||||
if (float.IsNaN(actual[i][c]) || Mathf.Abs(actual[i][c] - expected[c]) >= .0015f)
|
||||
throw new Exception("LiveColorCorrectionRegression spatial frame=" + key.frame +
|
||||
" blend=" + blend + " saturation=" + saturation + " pixel=" + i +
|
||||
" channel=" + c + " got=" + actual[i][c] + " expected=" + expected[c] + " source=" + pixels[i].ToString("F7") + " rgba=" + actual[i].ToString("F7") + " expectedRGBA=" + expected.ToString("F7"));
|
||||
if (blend == 0 && saturation == 1)
|
||||
{
|
||||
Color reversed = Expected(lut.Texture, pixels[i], saturation);
|
||||
if (Mathf.Abs(expected.r - (reversed.r + bloomColor.r * .7f)) > .02f) orderWitnesses++;
|
||||
}
|
||||
checks++;
|
||||
}
|
||||
}
|
||||
}
|
||||
Check(orderWitnesses > 100, "fixture must detect accidentally moving curves before Bloom");
|
||||
Debug.Log("LiveColorCorrectionRegression spatial PASS: " + checks +
|
||||
" RGBA pixels; LUT ramps/HDR/alpha and Bloom-before-curves Add/Screen; order witnesses=" + orderWitnesses);
|
||||
}
|
||||
finally
|
||||
{
|
||||
QualitySettings.anisotropicFiltering = oldAniso;
|
||||
Shader.SetGlobalTexture("_Bloom", oldBloom);
|
||||
Shader.SetGlobalFloat("_bloomDofWeight", oldWeight); Shader.SetGlobalFloat("_BloomIsScreenBlend", oldScreen);
|
||||
RenderTexture.active = previous;
|
||||
intermediate.Release(); output.Release();
|
||||
UnityEngine.Object.DestroyImmediate(intermediate); UnityEngine.Object.DestroyImmediate(output);
|
||||
UnityEngine.Object.DestroyImmediate(source); UnityEngine.Object.DestroyImmediate(read); UnityEngine.Object.DestroyImmediate(bloom);
|
||||
if (post) UnityEngine.Object.DestroyImmediate(post);
|
||||
}
|
||||
}
|
||||
|
||||
public static void RunGpu()
|
||||
{
|
||||
Check(Application.isBatchMode, "isolated batch mode only");
|
||||
string path = Environment.GetEnvironmentVariable("UMA_COLOR_TEST_KEYS");
|
||||
Check(File.Exists(path), "UMA_COLOR_TEST_KEYS must contain the local Live1176 worksheet fixture");
|
||||
var sheet = ScriptableObject.CreateInstance<LiveTimelineWorkSheet>();
|
||||
AssetBundle bundle = null;
|
||||
Material material = null;
|
||||
var source = new RenderTexture(16, 16, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear);
|
||||
var output = new RenderTexture(16, 16, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear);
|
||||
var read = new Texture2D(16, 16, TextureFormat.RGBAFloat, false, true);
|
||||
var previous = RenderTexture.active;
|
||||
var oldRgb = Shader.GetGlobalTexture("_RgbTex");
|
||||
float oldSaturation = Shader.GetGlobalFloat("_Saturation"), oldPower = Shader.GetGlobalFloat("_PostFilmPower");
|
||||
using (var lut = new ColorCorrectionCurveLut())
|
||||
try
|
||||
{
|
||||
JsonUtility.FromJsonOverwrite(File.ReadAllText(path), sheet);
|
||||
Check(sheet.colorCorrectionDataLists.Count == 1, "real group deserialization");
|
||||
var keys = sheet.colorCorrectionDataLists[0].keys.thisList;
|
||||
Check(keys.Count == 6 && keys[0].enable == 1 && keys[5].frame == 7066, "six actual enabled cuts");
|
||||
RunTimeline(sheet);
|
||||
Check(!keys[0].IsInterpolateKey(), "shipped keys do not have interpolation fields");
|
||||
Check(keys[0].redCurve.length == 2 && Math.Abs(keys[0].redCurve.keys[0].outTangent - 0.7630331f) < 0.00001f,
|
||||
"native AnimationCurve tangents survive deserialization");
|
||||
Check(ColorCorrectionCurveLut.Quantize(-1) == 0 && ColorCorrectionCurveLut.Quantize(2) == 255 &&
|
||||
ColorCorrectionCurveLut.Quantize(0.5f) == 127, "truncating native byte conversion");
|
||||
var identity = AnimationCurve.Linear(0, 0, 1, 1);
|
||||
var zero = AnimationCurve.Constant(0, 1, 0);
|
||||
var one = AnimationCurve.Constant(0, 1, 1);
|
||||
var pixels = new Color32[1024];
|
||||
ColorCorrectionCurveLut.Fill(pixels, zero, one, identity, one, zero, identity, 0.5f);
|
||||
Check(pixels[0].r == 127 && pixels[256].g == 127 && pixels[767].b == 255 && pixels[768].a == 0,
|
||||
"row layout, endpoint, pre-quantization curve blend, unused row");
|
||||
bundle = AssetBundle.LoadFromFile(Environment.GetEnvironmentVariable("UMA_POSTFILM_TEST_BUNDLE"));
|
||||
foreach (var shader in bundle.LoadAllAssets<Shader>())
|
||||
if (shader.name == "Gallop/ImageEffects/ColorCorrectionCurvesSimple") material = new Material(shader);
|
||||
Check(material && material.shader.isSupported, "shipped simple shader supported");
|
||||
// Mask power=0 means full correction in DXBC (not correction disabled).
|
||||
Shader.SetGlobalFloat("_PostFilmPower", 0);
|
||||
source.Create(); output.Create();
|
||||
int checks = 0;
|
||||
Texture2D firstTexture = null;
|
||||
foreach (var key in keys)
|
||||
{
|
||||
lut.Update(key.redCurve, key.greenCurve, key.blueCurve);
|
||||
if (firstTexture == null) firstTexture = lut.Texture;
|
||||
Check(firstTexture == lut.Texture && lut.Texture.mipmapCount == 1, "reuse LUT without mips");
|
||||
foreach (float saturation in new[] { 0f, 1f, 1.4f })
|
||||
foreach (Color color in new[] { new Color(0.2f, 0.4f, 0.8f, 0.35f), new Color(0, 0.5f, 1, 0.8f), new Color(-0.2f, 1.4f, 0.7f, 1) })
|
||||
{
|
||||
Shader.SetGlobalTexture("_RgbTex", lut.Texture);
|
||||
Shader.SetGlobalFloat("_Saturation", saturation);
|
||||
RenderTexture.active = source; GL.Clear(false, true, color);
|
||||
Draw(material, lut.Texture, saturation, source, output);
|
||||
RenderTexture.active = output;
|
||||
read.ReadPixels(new Rect(0, 0, 16, 16), 0, 0); read.Apply();
|
||||
Color actual = read.GetPixel(8, 8), expected = Expected(lut.Texture, color, saturation);
|
||||
for (int c = 0; c < 4; ++c)
|
||||
Check(!float.IsNaN(actual[c]) && Mathf.Abs(actual[c] - expected[c]) < 0.0015f,
|
||||
"GPU curve row/saturation/alpha input=" + color + " saturation=" + saturation + " frame=" + key.frame + " channel=" + c + " got=" + actual[c] + " expected=" + expected[c]);
|
||||
checks++;
|
||||
}
|
||||
}
|
||||
Debug.Log("Color LUT sampling diagnostics aniso=" + lut.Texture.anisoLevel + " filter=" + lut.Texture.filterMode + " qualityAniso=" + QualitySettings.anisotropicFiltering);
|
||||
RunSpatial(bundle, material, keys, lut);
|
||||
lut.Dispose(); Check(lut.Texture == null, "LUT released");
|
||||
lut.Update(identity, identity, identity); Check(lut.Texture != null, "LUT recreated after dispose");
|
||||
Debug.Log("LiveColorCorrectionRegression PASS: actual Live1176 six curve keys, byte packing and " + checks + " GPU color/alpha checks; production command-buffer draw verified; full Live render-context parity not tested");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Shader.SetGlobalTexture("_RgbTex", oldRgb);
|
||||
Shader.SetGlobalFloat("_Saturation", oldSaturation); Shader.SetGlobalFloat("_PostFilmPower", oldPower);
|
||||
RenderTexture.active = previous;
|
||||
source.Release(); output.Release();
|
||||
UnityEngine.Object.DestroyImmediate(source); UnityEngine.Object.DestroyImmediate(output);
|
||||
UnityEngine.Object.DestroyImmediate(read); UnityEngine.Object.DestroyImmediate(sheet);
|
||||
if (material) UnityEngine.Object.DestroyImmediate(material);
|
||||
if (bundle) bundle.Unload(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1725d4c85dcb4a06ac079f31d7dbd6c8
|
||||
@@ -0,0 +1,150 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using Gallop;
|
||||
using Gallop.Live;
|
||||
using Gallop.Live.Cutt;
|
||||
using Gallop.RenderPipeline;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
// Runs the production Director -> image-effect adapter -> render-parameter path.
|
||||
public static class LiveDofFocusRegression
|
||||
{
|
||||
private const BindingFlags PrivateInstance = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
private static void Require(bool value, string message)
|
||||
{
|
||||
if (!value) throw new InvalidOperationException("[LiveDofFocusRegression] " + message);
|
||||
}
|
||||
private static void Set(object obj, string field, object value)
|
||||
{
|
||||
obj.GetType().GetField(field, PrivateInstance).SetValue(obj, value);
|
||||
}
|
||||
private static void SetProperty(object obj, string name, object value)
|
||||
{
|
||||
Set(obj, "<" + name + ">k__BackingField", value);
|
||||
}
|
||||
|
||||
private static void RequirePreparedFocus(float expectedDepth)
|
||||
{
|
||||
// Exercise the real shader-parameter preparation, not a duplicated formula.
|
||||
var pass = new DofDiffusionBloomOverlayPass(
|
||||
UnityEngine.Rendering.Universal.RenderPassEvent.BeforeRenderingPostProcessing);
|
||||
using (var command = new UnityEngine.Rendering.CommandBuffer())
|
||||
{
|
||||
var state = PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay;
|
||||
object[] args = { default(UnityEngine.Rendering.ScriptableRenderContext), command,
|
||||
state, RenderTextureHandle.Make(Shader.PropertyToID("_DofTestSource"), 1920, 1080) };
|
||||
typeof(DofDiffusionBloomOverlayPass).GetMethod("PrepareDofParam", PrivateInstance)
|
||||
.Invoke(pass, args);
|
||||
Require(Mathf.Abs(DofDiffusionBloomOverlayPass.LastDofFocalDepth - expectedDepth) < 0.001f,
|
||||
"Prepared focal depth must use the selected focus, not the default 1m value.");
|
||||
float sharpEnd = DofDiffusionBloomOverlayPass.LastDofFocalEnd *
|
||||
DofDiffusionBloomOverlayPass.LastDofDepthRange;
|
||||
Require(Mathf.Abs(sharpEnd - expectedDepth - state.DofFocalSize * 0.5f) < 0.001f,
|
||||
"Prepared sharp interval must be centered on the selected focal depth.");
|
||||
}
|
||||
}
|
||||
|
||||
[MenuItem("UmaViewer/Rendering/Validate DOF focus routing")]
|
||||
public static void Run()
|
||||
{
|
||||
if (EditorApplication.isPlaying || Director.instance != null)
|
||||
throw new InvalidOperationException("Run outside Live/Play Mode; validation must not replace active Live state.");
|
||||
var previousRuntime = PostImageEffectFeature.RuntimeParameter;
|
||||
bool previousDof = GallopImageEffect.UserDofEnabled;
|
||||
var root = new GameObject("DofFocusRegression");
|
||||
root.SetActive(false);
|
||||
try
|
||||
{
|
||||
var director = root.AddComponent<Director>();
|
||||
var timeline = root.AddComponent<LiveTimelineControl>();
|
||||
director._liveTimelineControl = timeline;
|
||||
var cameraObject = new GameObject("DofTestCamera");
|
||||
cameraObject.transform.SetParent(root.transform);
|
||||
var camera = cameraObject.AddComponent<Camera>();
|
||||
camera.nearClipPlane = 0.8f;
|
||||
camera.farClipPlane = 1000f;
|
||||
camera.transform.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
|
||||
Set(director, "_cameraObjects", new[] { camera });
|
||||
Set(director, "_activeCameraIndex", 0);
|
||||
typeof(Director).GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic).SetValue(null, director);
|
||||
var effect = cameraObject.AddComponent<GallopImageEffect>();
|
||||
effect.DofDiffusionBloomOverlayParam.IsEnableBloom = true;
|
||||
effect.DofDiffusionBloomOverlayParam.IsEnableDiffusion = true;
|
||||
effect.DofDiffusionBloomOverlayParam.BloomIntensity = 0.63f;
|
||||
SetProperty(timeline, "DofTrackCamera", camera);
|
||||
SetProperty(timeline, "DofLookAtCamera", camera);
|
||||
SetProperty(timeline, "HasDofCameraLookAt", true);
|
||||
Vector3 focus = new Vector3(0, 1, 25);
|
||||
SetProperty(timeline, "DofCameraLookAt", focus);
|
||||
var key = new LiveTimelineKeyPostEffectDOFData
|
||||
{
|
||||
frame = 0, attribute = (LiveTimelineKeyAttribute)0x50000,
|
||||
dofFocalPoint = 1f, forcalSize = 30f, blurSpread = 1.75f,
|
||||
dofSmoothness = 0.5f, dofQuality = 1, charactor = 1
|
||||
};
|
||||
var update = typeof(Director).GetMethod("OnUpdatePostEffect_Dof", PrivateInstance);
|
||||
Action apply = () => update.Invoke(director, new object[] { key });
|
||||
PostImageEffectFeature.ResetRuntimeParameter();
|
||||
GallopImageEffect.SetUserDofEnabled(true);
|
||||
apply();
|
||||
var state = PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay;
|
||||
Require(state.IsEnableDof, "Valid camera look-at must enable DOF.");
|
||||
Require(state.DofFocalType == DepthBlurAndBloom.DofFocalType.Position,
|
||||
"Camera look-at was overwritten by the 1m fallback setter (expected Position, got " + state.DofFocalType + ").");
|
||||
Require(state.DofFocalPosition == focus, "Camera target must reach renderer unchanged.");
|
||||
Require(PostImageEffectFeature.RuntimeParameter.IsUseDepthTexture, "DOF must request depth.");
|
||||
RequirePreparedFocus(25f);
|
||||
|
||||
// A subsequent metric-distance key must deliberately switch modes.
|
||||
key.attribute = (LiveTimelineKeyAttribute)0x70000;
|
||||
key.dofFocalPoint = 8f;
|
||||
apply();
|
||||
state = PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay;
|
||||
Require(state.DofFocalType == DepthBlurAndBloom.DofFocalType.Point &&
|
||||
Mathf.Approximately(state.DofFocalPoint, 8f), "Metric-distance focus must be retained.");
|
||||
|
||||
RequirePreparedFocus(8f - camera.nearClipPlane);
|
||||
|
||||
// Switch back on a later cut, with a different world-space target.
|
||||
key.attribute = (LiveTimelineKeyAttribute)0x50000;
|
||||
key.dofFocalPoint = 1f;
|
||||
focus = new Vector3(1, 2, 4);
|
||||
SetProperty(timeline, "DofCameraLookAt", focus);
|
||||
apply();
|
||||
state = PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay;
|
||||
Require(state.DofFocalType == DepthBlurAndBloom.DofFocalType.Position &&
|
||||
state.DofFocalPosition == focus, "Cut back to positional focus must not retain metric mode.");
|
||||
|
||||
RequirePreparedFocus(4f);
|
||||
|
||||
// Invalid target bypasses only DOF, rather than falling back to 1m.
|
||||
SetProperty(timeline, "HasDofCameraLookAt", false);
|
||||
apply();
|
||||
state = PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay;
|
||||
Require(!state.IsEnableDof && state.IsEnableBloom && state.IsEnableDiffusion,
|
||||
"Missing focus must preserve Bloom/Diffusion and disable DOF.");
|
||||
SetProperty(timeline, "HasDofCameraLookAt", true);
|
||||
apply();
|
||||
GallopImageEffect.SetUserDofEnabled(false);
|
||||
state = PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay;
|
||||
Require(!state.IsEnableDof && state.UseDofDiffusionBloomType ==
|
||||
Gallop.ImageEffect.DofDiffusionBloomOverlayParam.DofDiffusionBloomType.DiffusionBloom,
|
||||
"User gate must bypass only DOF immediately.");
|
||||
Require(Mathf.Approximately(state.BloomIntensity, 0.63f), "DOF gate must not alter Bloom intensity.");
|
||||
GallopImageEffect.SetUserDofEnabled(true);
|
||||
state = PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay;
|
||||
Require(state.IsEnableDof && state.DofFocalType == DepthBlurAndBloom.DofFocalType.Position,
|
||||
"Re-enabling while paused must restore positional focus.");
|
||||
Debug.Log("[LiveDofFocusRegression] PASS: startup look-at, metric focus, camera cut, missing target, depth request, prepared focal depths/sharp intervals, DOF gate, paused restore.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
UnityEngine.Object.DestroyImmediate(root);
|
||||
typeof(Director).GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic).SetValue(null, null);
|
||||
typeof(PostImageEffectFeature).GetField("_runtimeParameter", BindingFlags.Static | BindingFlags.NonPublic)
|
||||
.SetValue(null, previousRuntime);
|
||||
GallopImageEffect.SetUserDofEnabled(previousDof);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0d4ad2f55d984032a979b59ec86be287
|
||||
@@ -0,0 +1,113 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using Gallop;
|
||||
using Gallop.ImageEffect;
|
||||
using Gallop.RenderPipeline;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
using UnityEngine.Rendering.Universal;
|
||||
|
||||
// GPU regression for the recovered CoC bridge. No song/game assets required.
|
||||
public static class LiveDofForegroundRegression
|
||||
{
|
||||
[MenuItem("UmaViewer/Rendering/Validate DOF foreground (GPU)")]
|
||||
public static void Run()
|
||||
{
|
||||
if (EditorApplication.isPlaying) throw new InvalidOperationException("Run outside Play Mode.");
|
||||
if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null)
|
||||
throw new InvalidOperationException("GPU test requires graphics; do not pass -nographics.");
|
||||
var root = new GameObject("DofForegroundRegression");
|
||||
var camera = root.AddComponent<Camera>();
|
||||
camera.enabled = false;
|
||||
camera.nearClipPlane = 0.8f;
|
||||
camera.farClipPlane = 1000f;
|
||||
var pass = new DofDiffusionBloomOverlayPass(RenderPassEvent.BeforeRenderingPostProcessing);
|
||||
var shader = Resources.Load<Shader>("RenderPipeline/LiveDofCoC");
|
||||
if (shader == null || !shader.isSupported || ShaderUtil.ShaderHasError(shader))
|
||||
throw new InvalidOperationException("LiveDofCoC shader unavailable or failed compilation.");
|
||||
float[] depths = { 5, 15, 25, 29.23675f, 31.04587f, 34.40935f, 40.81587f, 55.9f, 65, 90 };
|
||||
var depth = new Texture2D(depths.Length, 1, TextureFormat.RFloat, false, true) { filterMode = FilterMode.Point };
|
||||
var source = new Texture2D(depths.Length, 1, TextureFormat.RGBAFloat, false, true) { filterMode = FilterMode.Point };
|
||||
var result = new RenderTexture(depths.Length, 1, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear);
|
||||
var readback = new Texture2D(depths.Length, 1, TextureFormat.RGBAFloat, false, true);
|
||||
var previousRT = RenderTexture.active;
|
||||
var oldDepth = Shader.GetGlobalTexture("_CameraDepthTexture");
|
||||
string[] vectors = { "_ZBufferParams", "_CurveParams", "_GlobalScreenUVScrollParam", "_InvRenderTargetSize" };
|
||||
var oldVectors = Array.ConvertAll(vectors, name => Shader.GetGlobalVector(name));
|
||||
float oldStart = Shader.GetGlobalFloat("_GallopDofFocalStart");
|
||||
float oldSize = Shader.GetGlobalFloat("_dofForegroundSize");
|
||||
float oldWeight = Shader.GetGlobalFloat("_bloomDofWeight");
|
||||
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
try
|
||||
{
|
||||
result.Create();
|
||||
// Synthetic raw depth uses the same ZBufferParams as the shader, both depth conventions.
|
||||
foreach (bool reversed in new[] { false, true })
|
||||
foreach (float size in new[] { 30f, 0f })
|
||||
foreach (float foreground in new[] { 1f, 0f })
|
||||
{
|
||||
float ratio = camera.farClipPlane / camera.nearClipPlane;
|
||||
float x = reversed ? ratio - 1 : 1 - ratio;
|
||||
float y = reversed ? 1 : ratio;
|
||||
for (int i = 0; i < depths.Length; i++)
|
||||
{
|
||||
depth.SetPixel(i, 0, new Color((camera.farClipPlane / depths[i] - y) / x, 0, 0, 0));
|
||||
source.SetPixel(i, 0, new Color(0.2f, 0.4f, 0.6f, 0.7f));
|
||||
}
|
||||
depth.Apply(); source.Apply();
|
||||
var parameter = new DofDiffusionBloomOverlayPass.Parameter
|
||||
{
|
||||
TargetCamera = camera, DofFocalType = DepthBlurAndBloom.DofFocalType.Position,
|
||||
DofFocalPosition = new Vector3(0, 0, 40.81587f), DofFocalSize = size,
|
||||
DofSmoothness = 0.5f, DofForegroundSize = foreground,
|
||||
DofQualityType = (DepthBlurAndBloom.DofQuality)5
|
||||
};
|
||||
var src = RenderTextureHandle.Make(new RenderTargetIdentifier(source));
|
||||
src.Width = depths.Length; src.Height = 1;
|
||||
var dst = RenderTextureHandle.Make(new RenderTargetIdentifier(result));
|
||||
using (var cmd = new CommandBuffer())
|
||||
{
|
||||
typeof(DofDiffusionBloomOverlayPass).GetMethod("PrepareDofParam", flags).Invoke(pass,
|
||||
new object[] { default(ScriptableRenderContext), cmd, parameter, src });
|
||||
cmd.SetGlobalVector("_ZBufferParams", new Vector4(x, y, x / 1000, y / 1000));
|
||||
cmd.SetGlobalVector("_GlobalScreenUVScrollParam", Vector4.zero);
|
||||
cmd.SetGlobalTexture("_CameraDepthTexture", depth);
|
||||
cmd.SetGlobalFloat("_dofForegroundSize", foreground);
|
||||
typeof(DofDiffusionBloomOverlayPass).GetMethod("BlitDofCoc", flags).Invoke(pass,
|
||||
new object[] { cmd, parameter, src, dst, null, 0 });
|
||||
Graphics.ExecuteCommandBuffer(cmd);
|
||||
}
|
||||
RenderTexture.active = result;
|
||||
readback.ReadPixels(new Rect(0, 0, depths.Length, 1), 0, 0); readback.Apply();
|
||||
float range = camera.farClipPlane - camera.nearClipPlane;
|
||||
float focus = 40.81587f / range, half = size * 0.5f / range;
|
||||
for (int i = 0; i < depths.Length; i++)
|
||||
{
|
||||
float z = depths[i] / 1000;
|
||||
float bg = Mathf.Clamp01((z - focus - half) / (focus * 0.5f));
|
||||
float fg = Mathf.Clamp01((Mathf.Max(0, focus - half) - z) / (focus * 0.5f)) * foreground;
|
||||
var actual = readback.GetPixel(i, 0);
|
||||
if (Mathf.Abs(actual.a - Mathf.Max(bg, fg)) > 0.002f ||
|
||||
Mathf.Abs(actual.r - 0.2f) > 0.002f || Mathf.Abs(actual.g - 0.4f) > 0.002f || Mathf.Abs(actual.b - 0.6f) > 0.002f)
|
||||
throw new InvalidOperationException($"CoC mismatch depth={depths[i]} size={size} reversed={reversed}: {actual}");
|
||||
if (size == 30 && foreground == 1 && !reversed)
|
||||
Debug.Log($"[LiveDofForegroundRegression] depth={depths[i]:F2}m alpha={actual.a:F4}");
|
||||
}
|
||||
}
|
||||
Debug.Log("[LiveDofForegroundRegression] PASS: 80 GPU samples, frame3000 focus, near/far CoC, zero-width band, foreground off, RGB preserved, normal/reversed Z.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
RenderTexture.active = previousRT;
|
||||
Shader.SetGlobalTexture("_CameraDepthTexture", oldDepth);
|
||||
for (int i = 0; i < vectors.Length; i++) Shader.SetGlobalVector(vectors[i], oldVectors[i]);
|
||||
Shader.SetGlobalFloat("_GallopDofFocalStart", oldStart);
|
||||
Shader.SetGlobalFloat("_dofForegroundSize", oldSize);
|
||||
Shader.SetGlobalFloat("_bloomDofWeight", oldWeight);
|
||||
pass.Dispose(); result.Release();
|
||||
foreach (UnityEngine.Object obj in new UnityEngine.Object[] { root, depth, source, result, readback })
|
||||
UnityEngine.Object.DestroyImmediate(obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d0b9deaed4d44dddbfe159cbdd9dcd2e
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,196 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using Gallop.Live.Cutt;
|
||||
using Gallop.RenderPipeline;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
using UnityEditor;
|
||||
using Overlay = Gallop.ImageEffect.ScreenOverlay.Overlay;
|
||||
|
||||
public static class LivePostFilmRegression
|
||||
{
|
||||
static void Check(bool ok, string message) { if (!ok) throw new Exception("PostFilm: " + message); }
|
||||
static void Near(float a, float b, string message) { Check(Mathf.Abs(a-b)<0.002f, message + ": " + a + " vs " + b); }
|
||||
[MenuItem("UmaViewer/Rendering/Validate PostFilm timeline")]
|
||||
public static void Run()
|
||||
{
|
||||
var keys = new LiveTimelineKeyPostFilmDataList();
|
||||
var a = new LiveTimelineKeyPostFilmData { frame=10, filmMode=PostFilmMode.Add, filmPower=2,
|
||||
attribute=(LiveTimelineKeyAttribute)0x100000, color0=Color.red, color1=Color.green,
|
||||
color2=Color.blue, color3=Color.white, depthPower=-0.75f, DepthClip=2, FilmScale=Vector2.one };
|
||||
var b = new LiveTimelineKeyPostFilmData { frame=30, filmMode=PostFilmMode.Mul, filmPower=4,
|
||||
interpolateType=LiveCameraInterpolateType.Linear, color0=Color.red, color1=Color.green,
|
||||
color2=Color.blue, color3=Color.white, depthPower=-0.25f, DepthClip=2, FilmScale=Vector2.one };
|
||||
keys.thisList.Add(a); keys.thisList.Add(b);
|
||||
var output = new Overlay();
|
||||
foreach (PostColorType type in Enum.GetValues(typeof(PostColorType)))
|
||||
{
|
||||
a.colorType=type;
|
||||
LivePostFilmTimeline.Evaluate(keys,20,TimelinePlayerMode.Default,output);
|
||||
Near(output.postFilmPower,3,"raw unclamped power"); Near(output.depthPower,-0.5f,"signed depth");
|
||||
Check(output.inverseVignette && output.IsEnableDepth,"inverse is not depth disable");
|
||||
Check(output.postFilmMode==Overlay.PostFilmMode.Add,"mode must not switch before cut");
|
||||
Check(output.postFilmColor0==Color.red,"corner0");
|
||||
Check(output.postFilmColor1==(type==PostColorType.ColorAll || type==PostColorType.Color2TopBottom ? Color.red:Color.green),"corner1");
|
||||
Check(output.postFilmColor2==(type==PostColorType.ColorAll || type==PostColorType.Color2LeftRight ? Color.red:type==PostColorType.Color2TopBottom ? Color.green:Color.blue),"corner2");
|
||||
Check(output.postFilmColor3==(type==PostColorType.ColorAll ? Color.red:type==PostColorType.Color4 ? Color.white:Color.green),"corner3");
|
||||
}
|
||||
LivePostFilmTimeline.Evaluate(keys,30,TimelinePlayerMode.Default,output);
|
||||
Check(output.postFilmMode==Overlay.PostFilmMode.Mul && !output.inverseVignette,"exact cut");
|
||||
LivePostFilmTimeline.Evaluate(keys,20,TimelinePlayerMode.Default,output); Near(output.postFilmPower,3,"seek backward");
|
||||
LivePostFilmTimeline.Evaluate(keys,0,TimelinePlayerMode.Default,output); Check(!output.IsValid(),"before first key");
|
||||
keys.attribute=LiveTimelineKeyDataListAttr.Disable;
|
||||
LivePostFilmTimeline.Evaluate(keys,20,TimelinePlayerMode.Default,output); Check(!output.IsValid(),"disabled track");
|
||||
keys.attribute=0; a.layerMode=LiveTimelineKeyPostFilmData.LayerMode.UVMovie;
|
||||
LivePostFilmTimeline.Evaluate(keys,20,TimelinePlayerMode.Default,output); Check(!output.IsValid(),"unsupported movie bypass");
|
||||
a.layerMode=LiveTimelineKeyPostFilmData.LayerMode.Color; a.FilmScale=Vector2.zero; b.FilmScale=Vector2.zero;
|
||||
LivePostFilmTimeline.Evaluate(keys,20,TimelinePlayerMode.Default,output); Near(output.ScaleParameter.x,1,"safe scale");
|
||||
LivePostFilmTimeline.Evaluate(null,20,TimelinePlayerMode.Default,output); Check(!output.IsValid(),"missing track reset");
|
||||
var sheet=ScriptableObject.CreateInstance<LiveTimelineWorkSheet>();
|
||||
try {
|
||||
JsonUtility.FromJsonOverwrite("{\"postFilmKeys\":{\"thisList\":[{\"frame\":0,\"filmMode\":5,\"attribute\":1048576,\"filmPower\":0.1}]},\"postFilm2Keys\":{\"thisList\":[]},\"postFilm3Keys\":{\"thisList\":[]}}",sheet);
|
||||
Check(sheet.postFilmKeys.Count==1 && sheet.postFilmKeys.thisList[0].filmMode==PostFilmMode.VignetteAdd,"worksheet deserialization");
|
||||
} finally { UnityEngine.Object.DestroyImmediate(sheet); }
|
||||
ValidateBlinkSync();
|
||||
Debug.Log("LivePostFilmRegression timeline PASS");
|
||||
}
|
||||
|
||||
private static void ValidateBlinkSync()
|
||||
{
|
||||
var keys=new LiveTimelineKeyPostFilmDataList();
|
||||
var a=new LiveTimelineKeyPostFilmData { frame=10, filmMode=PostFilmMode.Add,
|
||||
layerMode=LiveTimelineKeyPostFilmData.LayerMode.Color, colorType=PostColorType.Color4,
|
||||
attribute=(LiveTimelineKeyAttribute)0x1e00000,
|
||||
BlinkLightName="stage_beam", BlinkLightContainerIndex=2,
|
||||
BlinkLightBrightnessPower=1f, IsAdjustedBlinkLightColor=false,
|
||||
color0=new Color(.1f,.2f,.3f,.11f), color1=new Color(.1f,.2f,.3f,.22f),
|
||||
color2=new Color(.1f,.2f,.3f,.33f), color3=new Color(.1f,.2f,.3f,.44f), FilmScale=Vector2.one };
|
||||
var b=new LiveTimelineKeyPostFilmData { frame=30, filmMode=PostFilmMode.Add,
|
||||
interpolateType=LiveCameraInterpolateType.Linear, colorType=PostColorType.Color4,
|
||||
color0=Color.white, color1=Color.white, color2=Color.white, color3=Color.white,
|
||||
FilmScale=Vector2.one };
|
||||
keys.thisList.Add(a); keys.thisList.Add(b);
|
||||
var output=new Overlay();
|
||||
int lookups=0;
|
||||
LivePostFilmTimeline.BlinkColorResolver resolve=delegate(string name,int hash,int index,out Color raw) {
|
||||
Check(name=="stage_beam" && index==2,"lookup identity");
|
||||
lookups++; raw=new Color(.2f,.4f,.6f,.9f); return true;
|
||||
};
|
||||
LivePostFilmTimeline.Evaluate(keys,20,TimelinePlayerMode.Default,output,resolve);
|
||||
Check(lookups==1,"one lookup shared by all four corners");
|
||||
foreach(Color c in new[]{output.postFilmColor0,output.postFilmColor1,output.postFilmColor2,output.postFilmColor3})
|
||||
Near(c.r,.6f,"synced R interpolates to next unsynced color");
|
||||
Near(output.postFilmColor0.a,.555f,"synced corner0 preserves authored alpha");
|
||||
Near(output.postFilmColor1.a,.61f,"synced corner1 preserves authored alpha");
|
||||
Near(output.postFilmColor2.a,.665f,"synced corner2 preserves authored alpha");
|
||||
Near(output.postFilmColor3.a,.72f,"synced corner3 preserves authored alpha");
|
||||
b.attribute=(LiveTimelineKeyAttribute)0x1e00000;
|
||||
LivePostFilmTimeline.Evaluate(keys,20,TimelinePlayerMode.Default,output,resolve);
|
||||
foreach(Color c in new[]{output.postFilmColor0,output.postFilmColor1,output.postFilmColor2,output.postFilmColor3})
|
||||
Near(c.r,.2f,"next sync holds current resolved RGB");
|
||||
Near(output.postFilmColor3.a,.44f,"next sync holds current authored alpha");
|
||||
a.attribute=0;
|
||||
LivePostFilmTimeline.Evaluate(keys,20,TimelinePlayerMode.Default,output,resolve);
|
||||
Near(output.postFilmColor0.r,.1f,"next sync holds authored current without lookup");
|
||||
a.attribute=(LiveTimelineKeyAttribute)0x200000;
|
||||
b.attribute=0;
|
||||
a.BlinkLightBrightnessPower=0f; a.IsAdjustedBlinkLightColor=true;
|
||||
LivePostFilmTimeline.Evaluate(keys,10,TimelinePlayerMode.Default,output,resolve);
|
||||
Near(output.postFilmColor0.r,1f,"key brightness zero plus adjusted color");
|
||||
Near(output.postFilmColor1.r,.1f,"only selected corner synced");
|
||||
Near(output.postFilmColor0.a,.11f,"raw stage alpha not copied");
|
||||
LivePostFilmTimeline.BlinkColorResolver missing=delegate(string name,int hash,int index,out Color raw) {
|
||||
raw=Color.black; return false;
|
||||
};
|
||||
LivePostFilmTimeline.Evaluate(keys,10,TimelinePlayerMode.Default,output,missing);
|
||||
Near(output.postFilmColor0.r,.1f,"failed lookup retains authored color");
|
||||
a.BlinkLightBrightnessPower=3f; a.IsAdjustedBlinkLightColor=false;
|
||||
LivePostFilmTimeline.Evaluate(keys,10,TimelinePlayerMode.Default,output,resolve);
|
||||
Check(output.postFilmColor0.b>1f,"key brightness can produce HDR color");
|
||||
Debug.Log("LivePostFilmRegression blink sync PASS");
|
||||
}
|
||||
|
||||
// Only for an isolated batch-mode project: this test changes global shader state.
|
||||
public static void RunGpu()
|
||||
{
|
||||
Check(Application.isBatchMode,"GPU regression must run in isolated batch mode");
|
||||
Run();
|
||||
string bundlePath=Environment.GetEnvironmentVariable("UMA_POSTFILM_TEST_BUNDLE");
|
||||
Check(File.Exists(bundlePath),"set UMA_POSTFILM_TEST_BUNDLE to the locally extracted shader bundle");
|
||||
var bundle=AssetBundle.LoadFromFile(bundlePath);
|
||||
Material material=null;
|
||||
var source=new RenderTexture(32,32,0,RenderTextureFormat.ARGBFloat,RenderTextureReadWrite.Linear);
|
||||
var target=new RenderTexture(32,32,0,RenderTextureFormat.ARGBFloat,RenderTextureReadWrite.Linear);
|
||||
var read=new Texture2D(32,32,TextureFormat.RGBAFloat,false,true);
|
||||
var previous=RenderTexture.active;
|
||||
try {
|
||||
Shader shader=null;
|
||||
foreach(var candidate in bundle.LoadAllAssets<Shader>()) if(candidate.name=="Gallop/ImageEffects/Rich/PostBlit_Rich") shader=candidate;
|
||||
Check(shader!=null && shader.isSupported,"official shader supported");
|
||||
material=new Material(shader);
|
||||
source.Create(); target.Create();
|
||||
RenderTexture.active=source; GL.Clear(false,true,new Color(0.2f,0.3f,0.4f,1));
|
||||
var overlay=new Overlay(); LivePostFilmTimeline.Reset(overlay);
|
||||
overlay.postFilmMode=Overlay.PostFilmMode.Add; overlay.postFilmPower=0.5f;
|
||||
overlay.postFilmColor0=overlay.postFilmColor1=overlay.postFilmColor2=overlay.postFilmColor3=new Color(0.4f,0.2f,0.1f,1);
|
||||
overlay.IsEnableDepth=true;
|
||||
var renderer=new ScreenOverlayRender.Render();
|
||||
var param=new ScreenOverlayRender.Parameter(); param.Setup(overlay);
|
||||
foreach(bool explicitColor in new[]{false,true}) {
|
||||
using(var cmd=new CommandBuffer()) {
|
||||
if(explicitColor) cmd.EnableShaderKeyword("COLOR_ONLY"); else cmd.DisableShaderKeyword("COLOR_ONLY");
|
||||
renderer.Blit(ref param,cmd,RenderTextureHandle.Make(source),RenderTextureHandle.Make(target),material,3);
|
||||
Graphics.ExecuteCommandBuffer(cmd);
|
||||
}
|
||||
RenderTexture.active=target; read.ReadPixels(new Rect(0,0,32,32),0,0); read.Apply();
|
||||
var pixel=read.GetPixel(16,16);
|
||||
Debug.Log("PostFilm GPU COLOR_ONLY="+explicitColor+" pixel="+pixel.ToString("F5"));
|
||||
Near(pixel.r,0.4f,"Add red"); Near(pixel.g,0.4f,"Add green"); Near(pixel.b,0.45f,"Add blue");
|
||||
}
|
||||
// Both first/later passes must execute the requested inverse-vignette variant.
|
||||
overlay.postFilmMode=Overlay.PostFilmMode.VignetteAdd;
|
||||
overlay.postFilmOptionParam=new Vector4(0.3f,0.8f,0,0);
|
||||
overlay.postFilmOffsetParam=new Vector2(0,0.58f);
|
||||
Color[] normal=null;
|
||||
foreach(int pass in new[]{1,3})
|
||||
foreach(bool inverse in new[]{false,true}) {
|
||||
overlay.inverseVignette=inverse; param.Setup(overlay);
|
||||
using(var cmd=new CommandBuffer()) {
|
||||
cmd.DisableShaderKeyword("COLOR_ONLY");
|
||||
renderer.Blit(ref param,cmd,RenderTextureHandle.Make(source),RenderTextureHandle.Make(target),material,pass);
|
||||
Graphics.ExecuteCommandBuffer(cmd);
|
||||
}
|
||||
RenderTexture.active=target; read.ReadPixels(new Rect(0,0,32,32),0,0); read.Apply();
|
||||
var pixels=read.GetPixels(); float maxDifference=0;
|
||||
for(int i=0;i<pixels.Length;i++) {
|
||||
Check(!float.IsNaN(pixels[i].r) && !float.IsInfinity(pixels[i].r),"finite vignette output");
|
||||
if(inverse) maxDifference=Mathf.Max(maxDifference,Mathf.Abs(pixels[i].r-normal[i].r));
|
||||
}
|
||||
if(!inverse) normal=pixels;
|
||||
else Check(maxDifference>0.01f,"inverse pass must change the spatial mask");
|
||||
Debug.Log("PostFilm vignette pass="+pass+" inverse="+inverse+" difference="+maxDifference);
|
||||
}
|
||||
// Sequential layers use the previous layer's pixels, not the original source.
|
||||
overlay.inverseVignette=false; overlay.postFilmMode=Overlay.PostFilmMode.Add; param.Setup(overlay);
|
||||
using(var cmd=new CommandBuffer()) {
|
||||
renderer.Blit(ref param,cmd,RenderTextureHandle.Make(source),RenderTextureHandle.Make(target),material,3);
|
||||
overlay.postFilmMode=Overlay.PostFilmMode.Lerp; overlay.postFilmPower=0.5f;
|
||||
overlay.postFilmColor0=overlay.postFilmColor1=overlay.postFilmColor2=overlay.postFilmColor3=Color.black;
|
||||
param.Setup(overlay);
|
||||
renderer.Blit(ref param,cmd,RenderTextureHandle.Make(target),RenderTextureHandle.Make(source),material,3);
|
||||
Graphics.ExecuteCommandBuffer(cmd);
|
||||
}
|
||||
RenderTexture.active=source; read.ReadPixels(new Rect(0,0,32,32),0,0); read.Apply();
|
||||
var stacked=read.GetPixel(16,16);
|
||||
Near(stacked.r,0.2f,"ordered Add then Lerp red"); Near(stacked.g,0.2f,"ordered Add then Lerp green"); Near(stacked.b,0.225f,"ordered Add then Lerp blue");
|
||||
Debug.Log("LivePostFilmRegression GPU PASS");
|
||||
} finally {
|
||||
RenderTexture.active=previous;
|
||||
if(material!=null) UnityEngine.Object.DestroyImmediate(material);
|
||||
UnityEngine.Object.DestroyImmediate(source); UnityEngine.Object.DestroyImmediate(target); UnityEngine.Object.DestroyImmediate(read);
|
||||
if(bundle!=null) bundle.Unload(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4234cd02b8e84df5ad22e7939cc3c8cc
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,153 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
using Gallop.Live.Cutt;
|
||||
using Gallop.RenderPipeline;
|
||||
|
||||
public static class LiveRadialBlurRegression
|
||||
{
|
||||
static void Check(bool ok, string message) { if (!ok) throw new Exception("RadialBlur: " + message); }
|
||||
static void Near(float a, float b, string message) { Check(Mathf.Abs(a-b)<0.002f,message+" actual="+a+" expected="+b); }
|
||||
public static void Run()
|
||||
{
|
||||
var sheet=ScriptableObject.CreateInstance<LiveTimelineWorkSheet>();
|
||||
try {
|
||||
JsonUtility.FromJsonOverwrite("{\"radialBlurKeys\":{\"thisList\":[{\"frame\":10,\"moveBlurType\":2,\"attribute\":65536,\"radialBlurDownsample\":3,\"radialBlurIteration\":2,\"radialBlurPower\":0.5,\"depthPowerBack\":38},{\"frame\":20,\"moveBlurType\":0}]}}",sheet);
|
||||
var keys=sheet.radialBlurKeys;
|
||||
Check(keys.Count==2,"worksheet track deserialization");
|
||||
var p=LiveRadialBlurTimeline.Evaluate(keys,10,TimelinePlayerMode.Default);
|
||||
Check(p.Type==2 && p.IsEnabledDepth && p.Downsample==3 && p.Iteration==2,"discrete key values");
|
||||
Near(p.Power,0.5f,"raw strength"); Near(p.DepthPowerBack,38,"authored distance");
|
||||
Check(!LiveRadialBlurTimeline.Evaluate(keys,20,TimelinePlayerMode.Default).IsValid,"off key");
|
||||
Check(LiveRadialBlurTimeline.Evaluate(keys,10,TimelinePlayerMode.Default).IsValid,"reverse seek");
|
||||
Check(!LiveRadialBlurTimeline.Evaluate(keys,0,TimelinePlayerMode.Default).IsValid,"pre first");
|
||||
keys.attribute=LiveTimelineKeyDataListAttr.Disable;
|
||||
Check(!LiveRadialBlurTimeline.Evaluate(keys,10,TimelinePlayerMode.Default).IsValid,"disabled");
|
||||
Check(!LiveRadialBlurTimeline.Evaluate(null,10,TimelinePlayerMode.Default).IsValid,"absent track reset");
|
||||
for(int mode=1;mode<=5;mode++) Check(RadialBlurPass.BlurPassIndex(mode)==2*(mode-1),"native pass mapping");
|
||||
Check(RadialBlurPass.AreaDifference(0,0)==0.0001f,"zero interval guard");
|
||||
Check(RadialBlurPass.AreaDifference(1,0.99999f)<0,"signed interval guard");
|
||||
p.DepthCancelRect=new Vector4(0.2f,0.3f,0.4f,0.5f); p.IsExpandDepthCancelRect=true; p.DepthCancelBlendLength=0.1f;
|
||||
var bounds=RadialBlurPass.CancelBounds(p); Near(bounds.x,0.1f,"expanded min"); Near(bounds.w,0.9f,"expanded max");
|
||||
var feature=new PostImageEffectFeature.Parameter(); feature.RadialBlur=p;
|
||||
Check(feature.IsUseDepthTexture,"radial requests depth independently");
|
||||
var copy=new PostImageEffectFeature.Parameter(); copy.ShallowCopyParameters(feature);
|
||||
Check(copy.RadialBlur.Type==2,"parameter copy");
|
||||
} finally { UnityEngine.Object.DestroyImmediate(sheet); }
|
||||
string fixture=Environment.GetEnvironmentVariable("UMA_RADIAL_TEST_KEYS");
|
||||
if(!string.IsNullOrEmpty(fixture)) {
|
||||
var realKeys=JsonUtility.FromJson<LiveTimelineKeyRadialBlurDataList>(File.ReadAllText(fixture));
|
||||
Check(realKeys.Count==28,"Live1001 actual key count");
|
||||
Check(LiveRadialBlurTimeline.Evaluate(realKeys,728,TimelinePlayerMode.Default).Type==0,"real before onset");
|
||||
var onset=LiveRadialBlurTimeline.Evaluate(realKeys,729,TimelinePlayerMode.Default);
|
||||
Check(onset.Type==2&&onset.IsEnabledDepth,"real onset");Near(onset.DepthPowerBack,38,"real mask distance");
|
||||
Check(LiveRadialBlurTimeline.Evaluate(realKeys,988,TimelinePlayerMode.Default).Type==0,"real off cut");
|
||||
Check(LiveRadialBlurTimeline.Evaluate(realKeys,3965,TimelinePlayerMode.Default).Type==1,"real radial impact");
|
||||
for(int f=0;f<=7900;f++) {
|
||||
var sample=LiveRadialBlurTimeline.Evaluate(realKeys,f,TimelinePlayerMode.Default);
|
||||
Check(sample.Type==0||sample.IsValid,"real full track finite frame="+f);
|
||||
}
|
||||
Debug.Log("LiveRadialBlurRegression real Live1001 7901 timeline samples PASS");
|
||||
}
|
||||
Debug.Log("LiveRadialBlurRegression timeline PASS");
|
||||
}
|
||||
static float Difference(Color[] a, Color[] b)
|
||||
{
|
||||
float sum=0;
|
||||
for(int i=0;i<a.Length;i++) {
|
||||
Check(!float.IsNaN(a[i].r)&&!float.IsInfinity(a[i].r)&&!float.IsNaN(a[i].g)&&!float.IsInfinity(a[i].g),"finite pixels");
|
||||
sum+=Mathf.Abs(a[i].r-b[i].r)+Mathf.Abs(a[i].g-b[i].g)+Mathf.Abs(a[i].b-b[i].b);
|
||||
}
|
||||
return sum/(a.Length*3);
|
||||
}
|
||||
public static void RunGpu()
|
||||
{
|
||||
Check(Application.isBatchMode,"isolated batch mode required"); Run();
|
||||
var bundle=AssetBundle.LoadFromFile(Environment.GetEnvironmentVariable("UMA_POSTFILM_TEST_BUNDLE"));
|
||||
Material material=null;
|
||||
var source=new RenderTexture(64,64,0,RenderTextureFormat.ARGBFloat,RenderTextureReadWrite.Linear);
|
||||
var target=new RenderTexture(64,64,0,RenderTextureFormat.ARGBFloat,RenderTextureReadWrite.Linear);
|
||||
var texture=new Texture2D(64,64,TextureFormat.RGBAFloat,false,true);
|
||||
var read=new Texture2D(64,64,TextureFormat.RGBAFloat,false,true);
|
||||
var cameraObject=new GameObject("RadialRegressionCamera"); var camera=cameraObject.AddComponent<Camera>();
|
||||
camera.nearClipPlane=0.3f;camera.farClipPlane=100f;
|
||||
var previous=RenderTexture.active;
|
||||
var depthTexture=new Texture2D(64,64,TextureFormat.RFloat,false,true) { filterMode=FilterMode.Point };
|
||||
var previousDepth=Shader.GetGlobalTexture("_CameraDepthTexture");
|
||||
var previousZ=Shader.GetGlobalVector("_ZBufferParams");
|
||||
var previousScroll=Shader.GetGlobalVector("_GlobalScreenUVScrollParam");
|
||||
try {
|
||||
Shader shader=null; foreach(var candidate in bundle.LoadAllAssets<Shader>()) if(candidate.name=="Cygames/ImageEffects/RadialBlur") shader=candidate;
|
||||
Check(shader!=null&&shader.isSupported,"official shader available"); material=new Material(shader);
|
||||
source.Create();target.Create();
|
||||
var pixels=new Color[64*64];
|
||||
for(int y=0;y<64;y++) for(int x=0;x<64;x++) pixels[y*64+x]=new Color((x%8<4)?0.8f:0.1f,(y%8<4)?0.7f:0.2f,0.3f,1);
|
||||
texture.SetPixels(pixels);texture.Apply();Graphics.Blit(texture,source);
|
||||
Func<RadialBlurPass.Parameter,Color[]> render=p=>{
|
||||
using(var cmd=new CommandBuffer()) {
|
||||
RadialBlurPass.Render(cmd,material,p,camera,source,target,source.descriptor);
|
||||
Graphics.ExecuteCommandBuffer(cmd);
|
||||
}
|
||||
RenderTexture.active=target;read.ReadPixels(new Rect(0,0,64,64),0,0);read.Apply();return read.GetPixels();
|
||||
};
|
||||
var p=RadialBlurPass.Parameter.Default();p.Type=1;p.Power=0;
|
||||
var baseline=render(p);Near(Difference(baseline,pixels),0,"zero power identity");
|
||||
for(int mode=1;mode<=5;mode++) {
|
||||
p.Type=mode;p.Power=2;p.StartArea=0;p.EndArea=0;p.Downsample=2;p.Iteration=2;p.RollEulerAngles=35;
|
||||
var result=render(p);float difference=Difference(result,baseline);
|
||||
Check(difference>0.005f,"mode "+mode+" actually changes source");
|
||||
Debug.Log("Radial GPU mode="+mode+" meanDifference="+difference);
|
||||
}
|
||||
// Real shader's depth gate: front < z <= back preserves source, farther pixels blur.
|
||||
p.Type=2;p.Downsample=1;p.Iteration=1;p.Power=2;p.IsEnabledDepth=true;
|
||||
p.DepthPowerFront=0;p.DepthPowerBack=38;
|
||||
foreach(bool reversed in new[]{false,true}) {
|
||||
float ratio=camera.farClipPlane/camera.nearClipPlane;
|
||||
float zx=reversed?ratio-1:1-ratio, zy=reversed?1:ratio;
|
||||
Shader.SetGlobalVector("_ZBufferParams",new Vector4(zx,zy,zx/100,zy/100));
|
||||
Shader.SetGlobalVector("_GlobalScreenUVScrollParam",Vector4.zero);
|
||||
for(int y=0;y<64;y++) for(int x=0;x<64;x++) {
|
||||
float distance=x<32?10:60;
|
||||
depthTexture.SetPixel(x,y,new Color((100/distance-zy)/zx,0,0,0));
|
||||
}
|
||||
depthTexture.Apply();Shader.SetGlobalTexture("_CameraDepthTexture",depthTexture);
|
||||
var gated=render(p);float protectedError=0,farDifference=0;
|
||||
for(int y=4;y<60;y++) for(int x=4;x<60;x++) {
|
||||
float d=Mathf.Abs(gated[y*64+x].r-baseline[y*64+x].r);
|
||||
if(x<28)protectedError=Mathf.Max(protectedError,d);
|
||||
if(x>36)farDifference+=d;
|
||||
}
|
||||
Near(protectedError,0,"near object depth protection reversed="+reversed);
|
||||
Check(farDifference>1,"far background blur reversed="+reversed);
|
||||
p.IsEnabledDepthCancelRect=true;p.DepthCancelRect=new Vector4(0.1f,0.1f,0.3f,0.8f);
|
||||
p.DepthCancelBlendLength=0.02f;
|
||||
var cancelled=render(p);float restoredBlur=0;
|
||||
for(int y=12;y<52;y++)for(int x=10;x<22;x++)restoredBlur+=Mathf.Abs(cancelled[y*64+x].r-gated[y*64+x].r);
|
||||
Check(restoredBlur>1,"cancel rectangle overrides depth protection");
|
||||
p.IsEnabledDepthCancelRect=false;
|
||||
Debug.Log("Radial depth GPU reversed="+reversed+" protectedError="+protectedError+" farDifference="+farDifference+" rectDifference="+restoredBlur);
|
||||
}
|
||||
p.IsEnabledDepth=true;p.IsEnabledDepthCancelRect=true;p.DepthPowerFront=4;p.DepthPowerBack=38;
|
||||
p.DepthCancelRect=new Vector4(0.2f,0.3f,0.4f,0.5f);p.DepthCancelBlendLength=0.1f;
|
||||
RadialBlurPass.ApplyMaterial(material,p,camera);
|
||||
Near(material.GetFloat("_DepthPowerFront"),(4-0.3f)/99.7f,"normalized front");
|
||||
Near(material.GetFloat("_DepthPowerBack"),(38-0.3f)/99.7f,"normalized back");
|
||||
Check(material.IsKeywordEnabled("ENABLE_DEPTH")&&material.IsKeywordEnabled("ENABLE_DEPTH_CANCEL_RECT"),"depth keywords");
|
||||
p.IsEnabledDepth=false;RadialBlurPass.ApplyMaterial(material,p,camera);
|
||||
Check(!material.IsKeywordEnabled("ENABLE_DEPTH")&&!material.IsKeywordEnabled("ENABLE_DEPTH_CANCEL_RECT"),"stale keyword reset");
|
||||
Near(material.GetFloat("_DepthPowerBack"),0,"stale distance reset");
|
||||
p.Downsample=0;p.Iteration=0;Difference(render(p),baseline);
|
||||
Debug.Log("LiveRadialBlurRegression GPU PASS");
|
||||
} finally {
|
||||
RenderTexture.active=previous;
|
||||
Shader.SetGlobalTexture("_CameraDepthTexture",previousDepth);
|
||||
Shader.SetGlobalVector("_ZBufferParams",previousZ);
|
||||
Shader.SetGlobalVector("_GlobalScreenUVScrollParam",previousScroll);
|
||||
UnityEngine.Object.DestroyImmediate(depthTexture);
|
||||
UnityEngine.Object.DestroyImmediate(material);UnityEngine.Object.DestroyImmediate(source);UnityEngine.Object.DestroyImmediate(target);
|
||||
UnityEngine.Object.DestroyImmediate(texture);UnityEngine.Object.DestroyImmediate(read);UnityEngine.Object.DestroyImmediate(cameraObject);
|
||||
if(bundle!=null) bundle.Unload(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: aa08d67efb5849ba86a6209017d814b6
|
||||
@@ -0,0 +1,407 @@
|
||||
#if UNITY_EDITOR
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Gallop;
|
||||
using Gallop.Live;
|
||||
using Gallop.RenderPipeline;
|
||||
using UnityEditor;
|
||||
using UnityEditor.SceneManagement;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
using UnityEngine.Rendering.Universal;
|
||||
|
||||
/// <summary>Opt-in graphics smoke test. Does not alter saved scenes or user configuration.</summary>
|
||||
[InitializeOnLoad]
|
||||
public static class LiveRenderCapture
|
||||
{
|
||||
const string Armed = "UmaViewer.RenderCapture.Armed";
|
||||
static double deadline;
|
||||
static bool requested;
|
||||
static int captureIndex;
|
||||
const string PlanState = Armed + ".Plan", ExitState = Armed + ".Exit", FilmIsolationState = Armed + ".FilmIsolation";
|
||||
static LiveCapturePlan plan;
|
||||
static readonly LiveCaptureStabilityGate gate = new LiveCaptureStabilityGate();
|
||||
static bool exitOnFinish;
|
||||
static bool filmIsolation;
|
||||
static bool filmSuppressed;
|
||||
static Gallop.ImageEffect.ScreenOverlay.Overlay.PostFilmMode savedMode1, savedMode2, savedMode3;
|
||||
static bool suppressedThisRender;
|
||||
static int CaptureSlots => filmIsolation ? 3 : 2;
|
||||
static int CaptureFrame => plan.frames[captureIndex / CaptureSlots];
|
||||
static int CaptureVariant => captureIndex % CaptureSlots;
|
||||
static string VariantName => CaptureVariant == 0 ? "off" : filmIsolation && CaptureVariant == 1 ? "noFilm" : "on";
|
||||
static float previousProgress;
|
||||
static bool previousSync, previousTouched, previousOuted;
|
||||
static Director capturedDirector;
|
||||
static Camera camera;
|
||||
static RenderTexture target, previousTarget;
|
||||
static PostImageEffectFeature feature;
|
||||
static bool originalActive;
|
||||
static bool originalRendering;
|
||||
static string output;
|
||||
static bool finishing;
|
||||
static CapturePreview preview;
|
||||
|
||||
static LiveRenderCapture()
|
||||
{
|
||||
EditorApplication.update += Tick;
|
||||
RenderPipelineManager.beginCameraRendering += BeforeCamera;
|
||||
RenderPipelineManager.endCameraRendering += AfterCamera;
|
||||
AssemblyReloadEvents.beforeAssemblyReload += () => {
|
||||
if (SessionState.GetBool(Armed, false) && capturedDirector != null)
|
||||
Finish("Cancelled before script reload", 0);
|
||||
if (finishing) RestoreCaptureState();
|
||||
};
|
||||
}
|
||||
|
||||
static void Configure(bool exit)
|
||||
{
|
||||
string reference = Environment.GetEnvironmentVariable("UMA_LIVE_CAPTURE_REFERENCE");
|
||||
if (string.IsNullOrEmpty(reference)) plan = LiveCapturePlan.Default();
|
||||
else
|
||||
{
|
||||
// Only a capture manifest, never arbitrary application configuration.
|
||||
if (!string.Equals(Path.GetFileName(reference), "manifest.json", StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException("UMA_LIVE_CAPTURE_REFERENCE must name a reference manifest.json.");
|
||||
plan = JsonUtility.FromJson<LiveCapturePlan>(File.ReadAllText(reference));
|
||||
}
|
||||
plan.Validate();
|
||||
string frames = Environment.GetEnvironmentVariable("UMA_LIVE_CAPTURE_FRAMES");
|
||||
if (!string.IsNullOrWhiteSpace(frames)) plan.SelectFrames(frames.Split(',').Select(int.Parse).ToArray());
|
||||
SessionState.SetString(PlanState, JsonUtility.ToJson(plan));
|
||||
SessionState.SetBool(ExitState, exit);
|
||||
exitOnFinish = exit;
|
||||
filmIsolation = false;
|
||||
SessionState.SetBool(FilmIsolationState, false);
|
||||
captureIndex = 0; gate.Reset(); requested = false; deadline = 0;
|
||||
}
|
||||
|
||||
public static void Start()
|
||||
{
|
||||
if (!Application.isBatchMode)
|
||||
throw new InvalidOperationException("Automatic scene-loading capture is restricted to an isolated batch Editor. Use Capture current Live in an interactive Editor.");
|
||||
if (SessionState.GetBool(Armed, false) || finishing) throw new InvalidOperationException("A capture is already running or restoring state.");
|
||||
if (EditorApplication.isPlayingOrWillChangePlaymode)
|
||||
throw new InvalidOperationException("Start capture from edit mode.");
|
||||
Configure(true);
|
||||
LiveRenderSetup.Install();
|
||||
SessionState.SetBool(Armed, true);
|
||||
EditorSceneManager.OpenScene("Assets/Scenes/Version2.unity");
|
||||
EditorApplication.isPlaying = true;
|
||||
}
|
||||
|
||||
[MenuItem("UmaViewer/Rendering/Capture current Live diagnostic frames (308,868,3848)")]
|
||||
public static void CaptureCurrentDiagnosticFrames()
|
||||
{
|
||||
BeginCurrentLiveCapture(true);
|
||||
}
|
||||
|
||||
[MenuItem("UmaViewer/Rendering/Capture current Live BlinkFilm diagnostic frames (900,1240,3900)")]
|
||||
public static void CaptureCurrentBlinkFilmFrames()
|
||||
{
|
||||
// Live1176/stage10148 authored PostFilm sync intervals; report still requires
|
||||
// identity/parameter checks if a different song is currently loaded.
|
||||
BeginCurrentLiveCapture(true, new[] { 900, 1240, 3900 });
|
||||
}
|
||||
|
||||
[MenuItem("UmaViewer/Rendering/Capture current Live off/noFilm/on (900,1240,3900)")]
|
||||
public static void CaptureCurrentFilmIsolation()
|
||||
{
|
||||
BeginCurrentLiveCapture(true, new[] { 900, 1240, 3900 });
|
||||
filmIsolation = true;
|
||||
SessionState.SetBool(FilmIsolationState, true);
|
||||
}
|
||||
|
||||
[MenuItem("UmaViewer/Rendering/Capture current Live post-effects off-on")]
|
||||
public static void CaptureCurrentLive()
|
||||
{
|
||||
BeginCurrentLiveCapture(false);
|
||||
}
|
||||
|
||||
private static void BeginCurrentLiveCapture(bool diagnostic, int[] diagnosticFrames = null)
|
||||
{
|
||||
if (SessionState.GetBool(Armed, false) || finishing) throw new InvalidOperationException("A capture is already running or restoring state.");
|
||||
var director = Director.instance;
|
||||
if (!EditorApplication.isPlaying || director == null || !director._isLiveSetup)
|
||||
throw new InvalidOperationException("Load the reference Live and characters first.");
|
||||
if (director.IsRecordVMD) throw new InvalidOperationException("Capture cannot seek while VMD recording is active.");
|
||||
Configure(false);
|
||||
if (diagnostic)
|
||||
{
|
||||
// A same-session off/on experiment, NOT a matched game-reference capture.
|
||||
// Use actual cast identity instead of silently imposing the song1001 preset.
|
||||
plan = new LiveCapturePlan {
|
||||
songId = director.live.MusicId,
|
||||
stageId = director.live.BackGroundId,
|
||||
characters = director.CharaContainerScript.Select(x => x.CharaEntry.Id + "_" + x.VarCostumeIdLong).ToArray(),
|
||||
frames = diagnosticFrames ?? new[] { 308, 868, 3848 }
|
||||
};
|
||||
plan.Validate();
|
||||
if (plan.frames.Any(x => x / (float)plan.fps >= director.totalTime))
|
||||
throw new InvalidOperationException("Diagnostic frame exceeds the loaded Live duration.");
|
||||
SessionState.SetString(PlanState, JsonUtility.ToJson(plan));
|
||||
}
|
||||
requested = true;
|
||||
deadline = EditorApplication.timeSinceStartup + 180;
|
||||
captureIndex = 0; gate.Reset();
|
||||
capturedDirector = director;
|
||||
previousProgress = director.UI.ProgressBar.value;
|
||||
previousSync = director._syncTime;
|
||||
previousTouched = director.sliderControl.is_Touched;
|
||||
previousOuted = director.sliderControl.is_Outed;
|
||||
SessionState.SetBool(Armed, true);
|
||||
preview = ScriptableObject.CreateInstance<CapturePreview>();
|
||||
preview.titleContent = new GUIContent("Live capture preview");
|
||||
preview.minSize = new Vector2(560, 380);
|
||||
preview.ShowUtility();
|
||||
Debug.Log("[LiveRenderCapture] Capturing off-screen: Live time is held temporarily. Use the preview to cancel; playback is restored on completion.");
|
||||
}
|
||||
|
||||
[MenuItem("UmaViewer/Rendering/Cancel Live capture")]
|
||||
public static void CancelCapture()
|
||||
{
|
||||
if (SessionState.GetBool(Armed, false)) Finish("Cancelled by user", 0);
|
||||
}
|
||||
|
||||
private sealed class CapturePreview : EditorWindow
|
||||
{
|
||||
void OnInspectorUpdate() { Repaint(); }
|
||||
void OnGUI()
|
||||
{
|
||||
EditorGUILayout.HelpBox("Capture uses an off-screen camera target. The Game view may say 'No cameras rendering'. Live time is held while each frame settles; this preview shows the capture target.", MessageType.Info);
|
||||
if (plan != null && captureIndex < plan.frames.Length * CaptureSlots)
|
||||
GUILayout.Label("Frame " + CaptureFrame + " / effects " + VariantName + " / saved " + captureIndex + " of " + plan.frames.Length * CaptureSlots);
|
||||
if (GUILayout.Button("Cancel capture and restore playback")) CancelCapture();
|
||||
var rect = GUILayoutUtility.GetRect(100, 100, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
|
||||
if (target != null) GUI.DrawTexture(rect, target, ScaleMode.ScaleToFit, false);
|
||||
}
|
||||
void OnDisable() { if (!finishing) CancelCapture(); }
|
||||
}
|
||||
|
||||
static void Tick()
|
||||
{
|
||||
if (!SessionState.GetBool(Armed, false)) return;
|
||||
// Entering play mode reloads statics. Restore intent rather than hanging
|
||||
// the isolated Editor after a successful batch capture.
|
||||
if (plan == null)
|
||||
{
|
||||
plan = JsonUtility.FromJson<LiveCapturePlan>(SessionState.GetString(PlanState, ""));
|
||||
exitOnFinish = SessionState.GetBool(ExitState, false);
|
||||
filmIsolation = SessionState.GetBool(FilmIsolationState, false);
|
||||
if (plan == null) { Finish("Capture plan missing after reload", 1); return; }
|
||||
}
|
||||
if (deadline == 0) deadline = EditorApplication.timeSinceStartup + System.Math.Max(600, plan.frames.Length * 20);
|
||||
if (EditorApplication.timeSinceStartup > deadline) { Finish("Timed out loading/capturing Live", 1); return; }
|
||||
if (!EditorApplication.isPlaying) return;
|
||||
try
|
||||
{
|
||||
var director = Director.instance;
|
||||
if (director == null || !director._isLiveSetup)
|
||||
{
|
||||
if (requested) return;
|
||||
var main = UmaViewerMain.Instance;
|
||||
var ui = UmaViewerUI.Instance;
|
||||
if (main == null || ui == null || !ShaderManager.IsShaderBundleReady) return;
|
||||
var live = main.Lives.FirstOrDefault(x => x.MusicId == plan.songId);
|
||||
if (live == null || main.Characters.Count < live.MemberCount) return;
|
||||
var selections = new List<LiveCharacterSelect>();
|
||||
if (live.MemberCount != plan.characters.Length || live.BackGroundId != plan.stageId)
|
||||
throw new InvalidOperationException("Reference song/stage/member count differs from loaded Live metadata.");
|
||||
for (int i = 0; i < live.MemberCount; ++i)
|
||||
{
|
||||
var item = new GameObject("CaptureSelection_" + i).AddComponent<LiveCharacterSelect>();
|
||||
LiveCapturePlan.ParseCharacterIdentity(plan.characters[i], out int id, out string costume);
|
||||
item.CharaEntry = main.Characters.First(x => !x.IsMob && x.Id == id);
|
||||
item.CostumeId = costume;
|
||||
selections.Add(item);
|
||||
}
|
||||
ui.LiveMode = 1;
|
||||
ui.isRequireStage = true;
|
||||
ui.isRecordVMD = false;
|
||||
requested = true;
|
||||
Debug.Log("[LiveRenderCapture] loading live" + plan.songId + " characters=" + string.Join(",", selections.Select(x => x.CharaEntry.Id + "_" + x.CostumeId)));
|
||||
UmaViewerBuilder.Instance.LoadLive(live, selections);
|
||||
return;
|
||||
}
|
||||
if (capturedDirector == null)
|
||||
{
|
||||
if (director.IsRecordVMD) throw new InvalidOperationException("Capture cannot seek while VMD recording is active.");
|
||||
capturedDirector = director;
|
||||
previousProgress = director.UI.ProgressBar.value;
|
||||
previousSync = director._syncTime;
|
||||
previousTouched = director.sliderControl.is_Touched;
|
||||
previousOuted = director.sliderControl.is_Outed;
|
||||
}
|
||||
if (!plan.MatchesIdentity(director.live.MusicId, director.live.BackGroundId,
|
||||
director.CharaContainerScript.Select(x => x.CharaEntry.Id + "_" + x.VarCostumeIdLong).ToArray()))
|
||||
throw new InvalidOperationException("Loaded Live cast/costumes/song/stage do not match capture reference.");
|
||||
if (plan.frames.Any(x => x / (float)plan.fps >= director.totalTime))
|
||||
throw new InvalidOperationException("Reference capture frame lies outside this Live timeline.");
|
||||
director._syncTime = true;
|
||||
director.sliderControl.is_Outed = false;
|
||||
director.sliderControl.is_Touched = true;
|
||||
director.UI.ProgressBar.SetValueWithoutNotify(CaptureFrame / ((float)plan.fps * director.totalTime));
|
||||
if (target == null)
|
||||
{
|
||||
output = Path.GetFullPath("captures/render-smoke/" + DateTime.Now.ToString("yyyyMMdd_HHmmss_fff"));
|
||||
Directory.CreateDirectory(output);
|
||||
var renderer = AssetDatabase.LoadAssetAtPath<UniversalRendererData>("Assets/Resources/RenderPipeline/UMAUniversalRenderPipelineAsset_Renderer.asset");
|
||||
feature = renderer.rendererFeatures.OfType<PostImageEffectFeature>().Single();
|
||||
originalActive = feature.isActive;
|
||||
originalRendering = feature.EnableRendering;
|
||||
target = new RenderTexture(plan.width, plan.height, 24, RenderTextureFormat.ARGB32);
|
||||
target.Create();
|
||||
feature.SetActive(true);
|
||||
feature.EnableRendering = false;
|
||||
File.WriteAllText(Path.Combine(output, "capture-plan.json"), JsonUtility.ToJson(plan, true));
|
||||
Debug.Log("[LiveRenderCapture] output=" + output);
|
||||
}
|
||||
if (camera != director.MainRenderCamera)
|
||||
{
|
||||
if (camera != null) camera.targetTexture = previousTarget;
|
||||
camera = director.MainRenderCamera;
|
||||
if (camera == null) return;
|
||||
previousTarget = camera.targetTexture;
|
||||
camera.targetTexture = target;
|
||||
gate.Reset();
|
||||
}
|
||||
}
|
||||
catch (Exception e) { Finish(e.ToString(), 1); }
|
||||
}
|
||||
|
||||
static void BeforeCamera(ScriptableRenderContext context, Camera renderedCamera)
|
||||
{
|
||||
if (!SessionState.GetBool(Armed, false) || !filmIsolation || CaptureVariant != 1 ||
|
||||
target == null || renderedCamera != camera || feature == null || !feature.isActive || filmSuppressed) return;
|
||||
// Scoped to one camera's URP render. The timeline owns these values; never
|
||||
// mutate them outside begin/endCameraRendering or persist them to scene assets.
|
||||
SuppressFilm();
|
||||
suppressedThisRender = true;
|
||||
}
|
||||
|
||||
// Kept separate from the SRP callback so the exact struct write/restore
|
||||
// contract can be checked in an isolated Editor without loading a Live.
|
||||
internal static void SuppressFilm()
|
||||
{
|
||||
if (filmSuppressed) throw new InvalidOperationException("Film capture suppression is already active.");
|
||||
var runtime = PostImageEffectFeature.RuntimeParameter;
|
||||
var p = runtime.DofDiffuionBloomOverlay;
|
||||
savedMode1 = p.Overlay1.PostFilmMode;
|
||||
savedMode2 = p.Overlay2.PostFilmMode;
|
||||
savedMode3 = p.Overlay3.PostFilmMode;
|
||||
p.Overlay1.PostFilmMode = Gallop.ImageEffect.ScreenOverlay.Overlay.PostFilmMode.None;
|
||||
p.Overlay2.PostFilmMode = Gallop.ImageEffect.ScreenOverlay.Overlay.PostFilmMode.None;
|
||||
p.Overlay3.PostFilmMode = Gallop.ImageEffect.ScreenOverlay.Overlay.PostFilmMode.None;
|
||||
runtime.DofDiffuionBloomOverlay = p;
|
||||
filmSuppressed = true;
|
||||
}
|
||||
|
||||
internal static void RestoreFilm()
|
||||
{
|
||||
if (!filmSuppressed) return;
|
||||
var runtime = PostImageEffectFeature.RuntimeParameter;
|
||||
var p = runtime.DofDiffuionBloomOverlay;
|
||||
// Restore only the fields we changed. Other timeline-owned parameters
|
||||
// must survive even if another camera callback refreshed them.
|
||||
p.Overlay1.PostFilmMode = savedMode1;
|
||||
p.Overlay2.PostFilmMode = savedMode2;
|
||||
p.Overlay3.PostFilmMode = savedMode3;
|
||||
runtime.DofDiffuionBloomOverlay = p;
|
||||
filmSuppressed = false;
|
||||
}
|
||||
|
||||
static void AfterCamera(ScriptableRenderContext context, Camera renderedCamera)
|
||||
{
|
||||
if (!SessionState.GetBool(Armed, false) || target == null || renderedCamera != camera) return;
|
||||
bool wasSuppressed = filmSuppressed && suppressedThisRender;
|
||||
RestoreFilm();
|
||||
suppressedThisRender = false;
|
||||
var director = Director.instance;
|
||||
if (director == null || director != capturedDirector || camera != director.MainRenderCamera) { gate.Reset(); return; }
|
||||
if (!gate.Observe(director._liveCurrentTime, CaptureFrame, plan.fps,
|
||||
Time.frameCount, ShaderManager.IsShaderBundleReady && feature.isActive && feature.EnableRendering == (CaptureVariant != 0) &&
|
||||
(CaptureVariant != 1 || !filmIsolation || wasSuppressed))) return;
|
||||
Texture2D image = null;
|
||||
var previous = RenderTexture.active;
|
||||
try
|
||||
{
|
||||
context.Submit();
|
||||
RenderTexture.active = target;
|
||||
image = new Texture2D(target.width, target.height, TextureFormat.RGB24, false);
|
||||
image.ReadPixels(new Rect(0, 0, target.width, target.height), 0, 0);
|
||||
image.Apply();
|
||||
string name = "frame" + CaptureFrame.ToString("D6") + "_" + VariantName;
|
||||
File.WriteAllBytes(Path.Combine(output, name + ".png"), image.EncodeToPNG());
|
||||
var p = PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay;
|
||||
File.WriteAllText(Path.Combine(output, name + ".txt"),
|
||||
$"requestedFrame={CaptureFrame}\nfps={plan.fps}\ntime={Director.instance._liveCurrentTime:R}\ncamera={camera.name}\nmode={p.UseDofDiffusionBloomType}\nfeature={feature.isActive}\nimageEffects={feature.EnableRendering}\nfilmIsolation={filmIsolation && CaptureVariant == 1}\nshaderReady={ShaderManager.IsShaderBundleReady}\nbloomEnabled={p.IsEnableBloom}\ndiffusionEnabled={p.IsEnableDiffusion}\nbloomWeight={p.BloomDofWeight:R}\nintensity={p.BloomIntensity:R}\nthreshold={p.BloomThreshold:R}\nbloomRadius={p.BloomBlurSize:R}\nbloomBlend={p.BloomBlendMode}\ndiffusionBright={p.DiffusionBright:R}\ndiffusionThreshold={p.DiffusionThreshold:R}\ndiffusionSaturation={p.DiffusionSaturation:R}\ndiffusionContrast={p.DiffusionContrast:R}\nfilm1={p.Overlay1.PostFilmMode}:{p.Overlay1.PostFilmPower:R}\nfilm2={p.Overlay2.PostFilmMode}:{p.Overlay2.PostFilmPower:R}\nfilm3={p.Overlay3.PostFilmMode}:{p.Overlay3.PostFilmPower:R}\nfilmBlinkLookup={Director.instance._liveTimelineControl.PostFilmBlinkLookupStatus}\nfilmColor0={FilmColor0(p.Overlay1.PostFilmColor0)}|{FilmColor0(p.Overlay2.PostFilmColor0)}|{FilmColor0(p.Overlay3.PostFilmColor0)}\nformat={target.graphicsFormat}\ndof={p.IsEnableDof}\nfocusType={p.DofFocalType}\nfocusPosition={p.DofFocalPosition}\nfocalPoint={p.DofFocalPoint:R}\nlookAtValid={Director.instance._liveTimelineControl.HasDofCameraLookAt}\nlookAt={Director.instance._liveTimelineControl.DofCameraLookAt}\ncharacters={string.Join(",", Director.instance.CharaContainerScript.Select(x => x.CharaEntry.Id + "_" + x.VarCostumeIdLong))}\n");
|
||||
Debug.Log("[LiveRenderCapture] saved " + name);
|
||||
captureIndex++;
|
||||
gate.Reset();
|
||||
if (captureIndex == plan.frames.Length * CaptureSlots) { Finish("Completed: " + output, 0); return; }
|
||||
feature.EnableRendering = CaptureVariant != 0;
|
||||
}
|
||||
catch (Exception e) { Finish(e.ToString(), 1); }
|
||||
finally
|
||||
{
|
||||
RenderTexture.active = previous;
|
||||
if (image != null) UnityEngine.Object.DestroyImmediate(image);
|
||||
}
|
||||
}
|
||||
|
||||
private static string FilmColor0(Color c) => string.Format(CultureInfo.InvariantCulture,
|
||||
"{0:R},{1:R},{2:R},{3:R}", c.r, c.g, c.b, c.a);
|
||||
|
||||
static void Finish(string message, int code)
|
||||
{
|
||||
if (finishing) return;
|
||||
finishCode = code;
|
||||
RestoreFilm();
|
||||
suppressedThisRender = false;
|
||||
SessionState.SetBool(Armed, false);
|
||||
if (feature != null)
|
||||
{
|
||||
feature.EnableRendering = originalRendering;
|
||||
feature.SetActive(originalActive);
|
||||
}
|
||||
if (camera != null) camera.targetTexture = previousTarget;
|
||||
Debug.Log("[LiveRenderCapture] " + message);
|
||||
finishing = true;
|
||||
// Leave the render callback before releasing render targets.
|
||||
EditorApplication.delayCall += RestoreCaptureState;
|
||||
}
|
||||
|
||||
static void RestoreCaptureState()
|
||||
{
|
||||
if (!finishing) return;
|
||||
EditorApplication.delayCall -= RestoreCaptureState;
|
||||
if (capturedDirector != null)
|
||||
{
|
||||
capturedDirector.UI.ProgressBar.SetValueWithoutNotify(previousProgress);
|
||||
capturedDirector._syncTime = previousSync;
|
||||
capturedDirector.sliderControl.is_Touched = previousTouched;
|
||||
capturedDirector.sliderControl.is_Outed = previousOuted;
|
||||
}
|
||||
if (target != null) { target.Release(); UnityEngine.Object.DestroyImmediate(target); }
|
||||
if (preview != null) preview.Close();
|
||||
preview = null;
|
||||
target = null;
|
||||
camera = null;
|
||||
feature = null;
|
||||
capturedDirector = null;
|
||||
deadline = 0;
|
||||
plan = null;
|
||||
SessionState.EraseString(PlanState);
|
||||
SessionState.EraseBool(ExitState);
|
||||
SessionState.EraseBool(FilmIsolationState);
|
||||
filmIsolation = false;
|
||||
suppressedThisRender = false;
|
||||
finishing = false;
|
||||
if (exitOnFinish) EditorApplication.Exit(finishCode);
|
||||
}
|
||||
static int finishCode;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 29bffc7886f81234fb049722c9554849
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,93 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Gallop.RenderPipeline;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering.Universal;
|
||||
|
||||
/// <summary>Idempotent renderer registration using Unity serialization, not YAML edits.</summary>
|
||||
public static class LiveRenderSetup
|
||||
{
|
||||
[MenuItem("UmaViewer/Live/Install recovered post effects")]
|
||||
public static void Install()
|
||||
{
|
||||
const string path = "Assets/Resources/RenderPipeline/UMAUniversalRenderPipelineAsset_Renderer.asset";
|
||||
var renderer = AssetDatabase.LoadAssetAtPath<UniversalRendererData>(path);
|
||||
if (renderer == null) throw new InvalidOperationException("Missing Live renderer: " + path);
|
||||
var feature = renderer.rendererFeatures.OfType<PostImageEffectFeature>().FirstOrDefault();
|
||||
if (feature == null)
|
||||
{
|
||||
feature = ScriptableObject.CreateInstance<PostImageEffectFeature>();
|
||||
feature.name = "Gallop Live Post Effects";
|
||||
AssetDatabase.AddObjectToAsset(feature, renderer);
|
||||
renderer.rendererFeatures.Add(feature);
|
||||
}
|
||||
feature.SetActive(true);
|
||||
renderer.SetDirty();
|
||||
EditorUtility.SetDirty(feature);
|
||||
EditorUtility.SetDirty(renderer);
|
||||
AssetDatabase.SaveAssets();
|
||||
Debug.Log("[LiveRenderSetup] Installed recovered post effects: " + path);
|
||||
}
|
||||
|
||||
// Batch-mode contract checks. These validate state routing, not rendered pixels.
|
||||
public static void Validate()
|
||||
{
|
||||
Install();
|
||||
Install();
|
||||
var renderer = AssetDatabase.LoadAssetAtPath<UniversalRendererData>(
|
||||
"Assets/Resources/RenderPipeline/UMAUniversalRenderPipelineAsset_Renderer.asset");
|
||||
Require(renderer.rendererFeatures.OfType<PostImageEffectFeature>().Count() == 1,
|
||||
"Renderer registration must be idempotent");
|
||||
var source = new Gallop.ImageEffect.DofDiffusionBloomOverlayParam();
|
||||
var state = DofDiffusionBloomOverlayPass.Parameter.Default();
|
||||
state.Setup(source);
|
||||
state.DecideDrawType(false);
|
||||
Require(!state.IsValidity, "Default must be a lossless bypass");
|
||||
source.IsEnableBloom = true;
|
||||
source.BloomIntensity = 0.63f;
|
||||
state.Setup(source);
|
||||
state.DecideDrawType(false);
|
||||
Require(state.UseDofDiffusionBloomType == Gallop.ImageEffect.DofDiffusionBloomOverlayParam.DofDiffusionBloomType.Bloom,
|
||||
"Bloom timeline must select Bloom mode");
|
||||
Require(Mathf.Approximately(state.BloomIntensity, 0.63f), "Timeline intensity must not be rescaled");
|
||||
source.IsEnableDiffusion = true;
|
||||
state.Setup(source);
|
||||
state.DecideDrawType(false);
|
||||
Require(state.UseDofDiffusionBloomType == Gallop.ImageEffect.DofDiffusionBloomOverlayParam.DofDiffusionBloomType.DiffusionBloom,
|
||||
"Diffusion must select the diffusion composition");
|
||||
source.IsEnableDof = true;
|
||||
source.DofFocalType = Gallop.DepthBlurAndBloom.DofFocalType.Position;
|
||||
source.DofFocalPosition = new Vector3(1, 2, 3);
|
||||
state.Setup(source);
|
||||
state.DecideDrawType(true);
|
||||
Require(new PostImageEffectFeature.Parameter { DofDiffuionBloomOverlay = state }.IsUseDepthTexture,
|
||||
"URP DOF mode must request depth even without overlays");
|
||||
Require(state.UseDofDiffusionBloomType == Gallop.ImageEffect.DofDiffusionBloomOverlayParam.DofDiffusionBloomType.DiffusionDofBloom,
|
||||
"DOF must compose with existing Bloom/Diffusion");
|
||||
Require(state.DofFocalPosition == source.DofFocalPosition, "World-space focus must reach renderer");
|
||||
source.IsEnableBloom = false;
|
||||
source.IsEnableDiffusion = false;
|
||||
state.Setup(source);
|
||||
state.DecideDrawType(true);
|
||||
Require(new PostImageEffectFeature.Parameter { DofDiffuionBloomOverlay = state }.IsUseDepthTexture,
|
||||
"Standalone DOF must request depth without Bloom or overlays");
|
||||
source.IsEnableDof = false;
|
||||
source.IsEnableBloom = false;
|
||||
source.IsEnableDiffusion = false;
|
||||
state.Setup(source);
|
||||
state.DecideDrawType(false);
|
||||
Require(!state.IsValidity, "Disabled key must clear the previous mode");
|
||||
var previous = PostImageEffectFeature.RuntimeParameter;
|
||||
previous.DofDiffuionBloomOverlay = state;
|
||||
PostImageEffectFeature.ResetRuntimeParameter();
|
||||
Require(!ReferenceEquals(previous, PostImageEffectFeature.RuntimeParameter), "New Live must reset shared state");
|
||||
Require(!PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay.IsValidity, "New Live must not inherit effects");
|
||||
Debug.Log("[LiveRenderValidation] PASS: registration, default bypass, Bloom, Diffusion, disable, intensity, reset");
|
||||
}
|
||||
|
||||
private static void Require(bool condition, string message)
|
||||
{
|
||||
if (!condition) throw new InvalidOperationException(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6ee873031d455cb439a61c7e6670811e
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,80 @@
|
||||
#if UNITY_EDITOR
|
||||
using System;
|
||||
using Gallop.Live;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
public static class Master5PhysicsProfileTests
|
||||
{
|
||||
[MenuItem("UmaViewer/Physics/Test master5 Live profile")]
|
||||
public static void Run()
|
||||
{
|
||||
GameObject root = new GameObject("Master5PhysicsProfileTest");
|
||||
root.hideFlags = HideFlags.HideAndDontSave;
|
||||
try
|
||||
{
|
||||
CheckScale(null, 1f);
|
||||
CheckScale("Hip_Skirt_L", 0.2f);
|
||||
CheckScale("hip_mskirt_r", 0.2f);
|
||||
CheckScale("Hip_Skirt", 1f);
|
||||
CheckScale("Hip_Tail_L", 1f);
|
||||
CheckScale("Thigh_MSkirt_L", 0.8f);
|
||||
CheckScale("Thigh_Skirt_L", 1f);
|
||||
var character = root.AddComponent<UmaContainerCharacter>();
|
||||
character.IsLive = true;
|
||||
var hip = root.AddComponent<DynamicBoneCollider>();
|
||||
hip.ColliderName = "Hip_Skirt_L";
|
||||
hip.m_Radius = 0.5f;
|
||||
hip.m_Height = 1.4f;
|
||||
var leg = root.AddComponent<DynamicBoneCollider>();
|
||||
leg.ColliderName = "Thigh_MSkirt_R";
|
||||
leg.m_Radius = 0.1f;
|
||||
var other = root.AddComponent<DynamicBoneCollider>();
|
||||
other.ColliderName = "Hip_Tail_L";
|
||||
other.m_Radius = 0.25f;
|
||||
var skirtBone = root.AddComponent<DynamicBone>();
|
||||
skirtBone.m_ContinuousCollision = true;
|
||||
var skirt = NewParticle();
|
||||
skirtBone.Particles.Add(skirt);
|
||||
var otherBone = root.AddComponent<DynamicBone>();
|
||||
var hair = NewParticle();
|
||||
otherBone.Particles.Add(hair);
|
||||
var profile = root.AddComponent<Master5LivePhysicsProfile>();
|
||||
for (int i = 0; i < 5; ++i) profile.ApplyToNewPhysics();
|
||||
Near(hip.m_Radius, 0.1f, "hip radius / repeat application");
|
||||
Near(leg.m_Radius, 0.08f, "leg radius / repeat application");
|
||||
Near(other.m_Radius, 0.25f, "unrelated collider");
|
||||
Near(hip.m_Height, 1.4f, "capsule height preserved");
|
||||
Near(skirt.m_Damping, 0.3f, "skirt damping");
|
||||
Near(skirt.m_Elasticity, 0.15f, "skirt elasticity");
|
||||
Near(skirt.m_Stiffness, 0.2f, "skirt stiffness");
|
||||
Near(skirt.m_Inert, 0.11f, "skirt inertia");
|
||||
Near(hair.m_Damping, 0.9f, "other damping");
|
||||
Near(hair.m_Stiffness, 0.833f, "other rigidity");
|
||||
Near(hair.m_Elasticity, 0.1925f, "other rebound cap");
|
||||
Near(hair.m_Inert, 0.121f, "other inertia");
|
||||
// Newly rebuilt particles must receive the profile, but colliders must not shrink again.
|
||||
skirtBone.Particles.Clear();
|
||||
var rebuilt = NewParticle();
|
||||
skirtBone.Particles.Add(rebuilt);
|
||||
profile.ApplyToNewPhysics();
|
||||
Near(rebuilt.m_Damping, 0.3f, "rebuilt particles");
|
||||
Near(hip.m_Radius, 0.1f, "rebuild preserves radius");
|
||||
Debug.Log("[PhysicsMigration] master5 profile regression checks PASSED.");
|
||||
}
|
||||
finally { UnityEngine.Object.DestroyImmediate(root); }
|
||||
}
|
||||
|
||||
private static DynamicBone.Particle NewParticle() => new DynamicBone.Particle
|
||||
{
|
||||
m_Damping = 0.1f, m_Elasticity = 0.1f, m_Stiffness = 0.1f, m_Inert = 0.1f
|
||||
};
|
||||
private static void CheckScale(string name, float expected) =>
|
||||
Near(Master5LivePhysicsProfile.RadiusScale(name), expected, "filter: " + name);
|
||||
private static void Near(float actual, float expected, string label)
|
||||
{
|
||||
if (Mathf.Abs(actual - expected) > 0.00001f)
|
||||
throw new Exception($"[PhysicsMigration] {label}: expected {expected}, got {actual}");
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 63c0f0a6306e44749fed26ef04f57036
|
||||
@@ -0,0 +1,583 @@
|
||||
#if UNITY_EDITOR
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using Unity.Collections;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
|
||||
public static class CyalumeMeshDiagnostics
|
||||
{
|
||||
[MenuItem("Tools/Cyalume/Dump Selected Mesh Filters")]
|
||||
private static void DumpSelectedMeshFilters()
|
||||
{
|
||||
var filters = CollectSelectedMeshFilters();
|
||||
if (filters.Count == 0)
|
||||
{
|
||||
Debug.LogWarning("CyalumeMeshDiagnostics: Select one or more GameObjects with MeshFilter components.");
|
||||
return;
|
||||
}
|
||||
|
||||
var report = new StringBuilder();
|
||||
report.AppendLine($"Cyalume mesh dump: {filters.Count} selection(s)");
|
||||
|
||||
foreach (var filter in filters)
|
||||
{
|
||||
report.AppendLine(BuildMeshReport(filter));
|
||||
report.AppendLine(new string('-', 80));
|
||||
}
|
||||
|
||||
Debug.Log(report.ToString());
|
||||
}
|
||||
|
||||
[MenuItem("Tools/Cyalume/Compare First Two Selected Mesh Filters")]
|
||||
private static void CompareFirstTwoSelectedMeshFilters()
|
||||
{
|
||||
var filters = CollectSelectedMeshFilters();
|
||||
if (filters.Count < 2)
|
||||
{
|
||||
Debug.LogWarning("CyalumeMeshDiagnostics: Select at least two GameObjects with MeshFilter components.");
|
||||
return;
|
||||
}
|
||||
|
||||
var left = filters[0];
|
||||
var right = filters[1];
|
||||
var leftMesh = left.sharedMesh;
|
||||
var rightMesh = right.sharedMesh;
|
||||
|
||||
var report = new StringBuilder();
|
||||
report.AppendLine("Cyalume mesh compare");
|
||||
report.AppendLine($"Left : {left.name}");
|
||||
report.AppendLine($"Right: {right.name}");
|
||||
report.AppendLine();
|
||||
report.AppendLine(BuildMeshReport(left));
|
||||
report.AppendLine(new string('=', 80));
|
||||
report.AppendLine(BuildMeshReport(right));
|
||||
report.AppendLine(new string('=', 80));
|
||||
report.AppendLine(BuildComparison(leftMesh, rightMesh));
|
||||
|
||||
Debug.Log(report.ToString());
|
||||
}
|
||||
|
||||
private static List<MeshFilter> CollectSelectedMeshFilters()
|
||||
{
|
||||
var results = new List<MeshFilter>();
|
||||
var seen = new HashSet<MeshFilter>();
|
||||
|
||||
foreach (var gameObject in Selection.gameObjects)
|
||||
{
|
||||
if (gameObject == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var filter = gameObject.GetComponent<MeshFilter>();
|
||||
if (filter != null && seen.Add(filter))
|
||||
{
|
||||
results.Add(filter);
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
private static string BuildMeshReport(MeshFilter filter)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
sb.AppendLine($"GameObject : {filter.name}");
|
||||
|
||||
var renderer = filter.GetComponent<Renderer>();
|
||||
sb.AppendLine($"Renderer : {(renderer != null ? renderer.enabled.ToString() : "missing")}");
|
||||
|
||||
var mesh = filter.sharedMesh;
|
||||
if (mesh == null)
|
||||
{
|
||||
sb.AppendLine("Mesh : <null>");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
sb.AppendLine($"Mesh : {mesh.name}");
|
||||
sb.AppendLine($"Readable : {SafeRead(() => mesh.isReadable, false)}");
|
||||
sb.AppendLine($"Vertices : {SafeRead(() => mesh.vertexCount, -1)}");
|
||||
sb.AppendLine($"SubMeshes : {SafeRead(() => mesh.subMeshCount, -1)}");
|
||||
sb.AppendLine($"Bounds : {SafeBounds(mesh)}");
|
||||
sb.AppendLine($"AssetPath : {AssetDatabase.GetAssetPath(mesh)}");
|
||||
sb.AppendLine($"Importer : {DescribeImporter(mesh)}");
|
||||
sb.AppendLine($"Attrs : {BuildAttributeSummary(mesh)}");
|
||||
sb.AppendLine($"AttrLayout : {BuildAttributeLayout(mesh)}");
|
||||
sb.AppendLine($"RawData : {BuildRawAttributeSummary(mesh)}");
|
||||
|
||||
var uv = SafeArrayRead(() => mesh.uv);
|
||||
sb.AppendLine($"UV Count : {(uv != null ? uv.Length.ToString() : "<unavailable>")}");
|
||||
|
||||
var colors32 = SafeArrayRead(() => mesh.colors32);
|
||||
if (colors32 == null)
|
||||
{
|
||||
sb.AppendLine("Colors32 : <unavailable>");
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.AppendLine($"Colors32 : {colors32.Length}");
|
||||
sb.AppendLine($"ColorStats : {BuildColorStats(colors32)}");
|
||||
sb.AppendLine($"ColorSample: {BuildColorSample(colors32, 8)}");
|
||||
}
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static string BuildComparison(Mesh left, Mesh right)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
|
||||
if (left == null || right == null)
|
||||
{
|
||||
sb.AppendLine("Comparison unavailable: one of the meshes is null.");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
sb.AppendLine("Quick compare");
|
||||
sb.AppendLine($"Readable equal : {SafeRead(() => left.isReadable, false) == SafeRead(() => right.isReadable, false)}");
|
||||
sb.AppendLine($"Vertex count : {SafeRead(() => left.vertexCount, -1)} vs {SafeRead(() => right.vertexCount, -1)}");
|
||||
sb.AppendLine($"UV count : {SafeArrayRead(() => left.uv)?.Length ?? -1} vs {SafeArrayRead(() => right.uv)?.Length ?? -1}");
|
||||
sb.AppendLine($"Attrs : {BuildAttributeSummary(left)} vs {BuildAttributeSummary(right)}");
|
||||
sb.AppendLine($"AttrLayout L : {BuildAttributeLayout(left)}");
|
||||
sb.AppendLine($"AttrLayout R : {BuildAttributeLayout(right)}");
|
||||
sb.AppendLine($"RawData L : {BuildRawAttributeSummary(left)}");
|
||||
sb.AppendLine($"RawData R : {BuildRawAttributeSummary(right)}");
|
||||
|
||||
var leftColors = SafeArrayRead(() => left.colors32);
|
||||
var rightColors = SafeArrayRead(() => right.colors32);
|
||||
|
||||
sb.AppendLine($"Colors count : {leftColors?.Length ?? -1} vs {rightColors?.Length ?? -1}");
|
||||
|
||||
if (leftColors != null && rightColors != null)
|
||||
{
|
||||
sb.AppendLine($"Alpha stats : {BuildAlphaSummary(leftColors)} vs {BuildAlphaSummary(rightColors)}");
|
||||
}
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static string DescribeImporter(Mesh mesh)
|
||||
{
|
||||
var path = AssetDatabase.GetAssetPath(mesh);
|
||||
if (string.IsNullOrEmpty(path))
|
||||
{
|
||||
return "<no importer>";
|
||||
}
|
||||
|
||||
var importer = AssetImporter.GetAtPath(path);
|
||||
if (importer == null)
|
||||
{
|
||||
return "<missing importer>";
|
||||
}
|
||||
|
||||
if (importer is ModelImporter modelImporter)
|
||||
{
|
||||
return $"ModelImporter(readable={modelImporter.isReadable})";
|
||||
}
|
||||
|
||||
return importer.GetType().Name;
|
||||
}
|
||||
|
||||
private static string BuildRawAttributeSummary(Mesh mesh)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var dataArray = Mesh.AcquireReadOnlyMeshData(mesh);
|
||||
if (dataArray.Length == 0)
|
||||
{
|
||||
return "empty";
|
||||
}
|
||||
|
||||
var data = dataArray[0];
|
||||
if (data.vertexCount <= 0)
|
||||
{
|
||||
return "vertexCount=0";
|
||||
}
|
||||
|
||||
var descriptors = mesh.GetVertexAttributes();
|
||||
if (descriptors == null || descriptors.Length == 0)
|
||||
{
|
||||
return "no descriptors";
|
||||
}
|
||||
|
||||
var offsetsByStream = new Dictionary<int, int>();
|
||||
var parts = new List<string>();
|
||||
|
||||
foreach (var descriptor in descriptors)
|
||||
{
|
||||
if (!offsetsByStream.TryGetValue(descriptor.stream, out var offset))
|
||||
{
|
||||
offset = 0;
|
||||
}
|
||||
|
||||
var part = DescribeRawAttribute(data, descriptor, offset);
|
||||
parts.Add(part);
|
||||
offsetsByStream[descriptor.stream] = offset + GetFormatSize(descriptor.format) * descriptor.dimension;
|
||||
}
|
||||
|
||||
return string.Join(" | ", parts);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return $"<error: {ex.Message}>";
|
||||
}
|
||||
}
|
||||
|
||||
private static string DescribeRawAttribute(Mesh.MeshData data, VertexAttributeDescriptor descriptor, int offset)
|
||||
{
|
||||
var stride = data.GetVertexBufferStride(descriptor.stream);
|
||||
var raw = data.GetVertexData<byte>(descriptor.stream);
|
||||
if (!raw.IsCreated || raw.Length == 0)
|
||||
{
|
||||
return $"{descriptor.attribute}:<no data>";
|
||||
}
|
||||
|
||||
switch (descriptor.attribute)
|
||||
{
|
||||
case VertexAttribute.Color:
|
||||
return $"{descriptor.attribute}:{DescribeColor(raw, data.vertexCount, stride, offset)}";
|
||||
case VertexAttribute.TexCoord0:
|
||||
case VertexAttribute.TexCoord1:
|
||||
case VertexAttribute.TexCoord2:
|
||||
return $"{descriptor.attribute}:{DescribeVector2(raw, data.vertexCount, stride, offset, descriptor.format)}";
|
||||
default:
|
||||
return $"{descriptor.attribute}:ok";
|
||||
}
|
||||
}
|
||||
|
||||
private static string BuildAttributeSummary(Mesh mesh)
|
||||
{
|
||||
return
|
||||
$"pos={SafeHasAttr(mesh, VertexAttribute.Position)} " +
|
||||
$"nrm={SafeHasAttr(mesh, VertexAttribute.Normal)} " +
|
||||
$"tan={SafeHasAttr(mesh, VertexAttribute.Tangent)} " +
|
||||
$"col={SafeHasAttr(mesh, VertexAttribute.Color)} " +
|
||||
$"uv0={SafeHasAttr(mesh, VertexAttribute.TexCoord0)} " +
|
||||
$"uv1={SafeHasAttr(mesh, VertexAttribute.TexCoord1)} " +
|
||||
$"uv2={SafeHasAttr(mesh, VertexAttribute.TexCoord2)} " +
|
||||
$"uv3={SafeHasAttr(mesh, VertexAttribute.TexCoord3)}";
|
||||
}
|
||||
|
||||
private static string BuildAttributeLayout(Mesh mesh)
|
||||
{
|
||||
try
|
||||
{
|
||||
var attributes = mesh.GetVertexAttributes();
|
||||
if (attributes == null || attributes.Length == 0)
|
||||
{
|
||||
return "empty";
|
||||
}
|
||||
|
||||
var sb = new StringBuilder();
|
||||
for (var i = 0; i < attributes.Length; i++)
|
||||
{
|
||||
var attribute = attributes[i];
|
||||
if (i > 0)
|
||||
{
|
||||
sb.Append(" | ");
|
||||
}
|
||||
|
||||
var stride = SafeRead(() => mesh.GetVertexBufferStride(attribute.stream), -1);
|
||||
sb.Append(
|
||||
$"{attribute.attribute}:{attribute.format}x{attribute.dimension}@s{attribute.stream}/stride{stride}");
|
||||
}
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return $"<error: {ex.Message}>";
|
||||
}
|
||||
}
|
||||
|
||||
private static string DescribeColor(NativeArray<byte> raw, int vertexCount, int stride, int offset)
|
||||
{
|
||||
byte minR = byte.MaxValue;
|
||||
byte minG = byte.MaxValue;
|
||||
byte minB = byte.MaxValue;
|
||||
byte minA = byte.MaxValue;
|
||||
byte maxR = byte.MinValue;
|
||||
byte maxG = byte.MinValue;
|
||||
byte maxB = byte.MinValue;
|
||||
byte maxA = byte.MinValue;
|
||||
var zeroAlpha = 0;
|
||||
|
||||
var sample = new StringBuilder();
|
||||
var sampleCount = Mathf.Min(vertexCount, 4);
|
||||
|
||||
for (var i = 0; i < vertexCount; i++)
|
||||
{
|
||||
var baseIndex = i * stride + offset;
|
||||
var r = raw[baseIndex + 0];
|
||||
var g = raw[baseIndex + 1];
|
||||
var b = raw[baseIndex + 2];
|
||||
var a = raw[baseIndex + 3];
|
||||
|
||||
if (r < minR) minR = r;
|
||||
if (g < minG) minG = g;
|
||||
if (b < minB) minB = b;
|
||||
if (a < minA) minA = a;
|
||||
if (r > maxR) maxR = r;
|
||||
if (g > maxG) maxG = g;
|
||||
if (b > maxB) maxB = b;
|
||||
if (a > maxA) maxA = a;
|
||||
if (a == 0) zeroAlpha++;
|
||||
|
||||
if (i < sampleCount)
|
||||
{
|
||||
if (sample.Length > 0)
|
||||
{
|
||||
sample.Append(",");
|
||||
}
|
||||
|
||||
sample.Append($"({r},{g},{b},{a})");
|
||||
}
|
||||
}
|
||||
|
||||
return $"R[{minR},{maxR}] G[{minG},{maxG}] B[{minB},{maxB}] A[{minA},{maxA}] zeroA={zeroAlpha}/{vertexCount} sample={sample}";
|
||||
}
|
||||
|
||||
private static string DescribeVector2(NativeArray<byte> raw, int vertexCount, int stride, int offset, VertexAttributeFormat format)
|
||||
{
|
||||
var minX = float.PositiveInfinity;
|
||||
var minY = float.PositiveInfinity;
|
||||
var maxX = float.NegativeInfinity;
|
||||
var maxY = float.NegativeInfinity;
|
||||
var sample = new StringBuilder();
|
||||
var sampleCount = Mathf.Min(vertexCount, 4);
|
||||
|
||||
for (var i = 0; i < vertexCount; i++)
|
||||
{
|
||||
var baseIndex = i * stride + offset;
|
||||
float x;
|
||||
float y;
|
||||
|
||||
switch (format)
|
||||
{
|
||||
case VertexAttributeFormat.Float16:
|
||||
x = HalfToFloat((ushort)(raw[baseIndex + 0] | (raw[baseIndex + 1] << 8)));
|
||||
y = HalfToFloat((ushort)(raw[baseIndex + 2] | (raw[baseIndex + 3] << 8)));
|
||||
break;
|
||||
case VertexAttributeFormat.Float32:
|
||||
x = BitConverter.ToSingle(new[]
|
||||
{
|
||||
raw[baseIndex + 0],
|
||||
raw[baseIndex + 1],
|
||||
raw[baseIndex + 2],
|
||||
raw[baseIndex + 3]
|
||||
}, 0);
|
||||
y = BitConverter.ToSingle(new[]
|
||||
{
|
||||
raw[baseIndex + 4],
|
||||
raw[baseIndex + 5],
|
||||
raw[baseIndex + 6],
|
||||
raw[baseIndex + 7]
|
||||
}, 0);
|
||||
break;
|
||||
default:
|
||||
return $"unsupported({format})";
|
||||
}
|
||||
|
||||
if (x < minX) minX = x;
|
||||
if (y < minY) minY = y;
|
||||
if (x > maxX) maxX = x;
|
||||
if (y > maxY) maxY = y;
|
||||
|
||||
if (i < sampleCount)
|
||||
{
|
||||
if (sample.Length > 0)
|
||||
{
|
||||
sample.Append(",");
|
||||
}
|
||||
|
||||
sample.Append($"({x:0.###},{y:0.###})");
|
||||
}
|
||||
}
|
||||
|
||||
return $"x[{minX:0.###},{maxX:0.###}] y[{minY:0.###},{maxY:0.###}] sample={sample}";
|
||||
}
|
||||
|
||||
private static int GetFormatSize(VertexAttributeFormat format)
|
||||
{
|
||||
switch (format)
|
||||
{
|
||||
case VertexAttributeFormat.Float32:
|
||||
case VertexAttributeFormat.UInt32:
|
||||
case VertexAttributeFormat.SInt32:
|
||||
return 4;
|
||||
case VertexAttributeFormat.Float16:
|
||||
case VertexAttributeFormat.UNorm16:
|
||||
case VertexAttributeFormat.SNorm16:
|
||||
case VertexAttributeFormat.UInt16:
|
||||
case VertexAttributeFormat.SInt16:
|
||||
return 2;
|
||||
case VertexAttributeFormat.UNorm8:
|
||||
case VertexAttributeFormat.SNorm8:
|
||||
case VertexAttributeFormat.UInt8:
|
||||
case VertexAttributeFormat.SInt8:
|
||||
return 1;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static float HalfToFloat(ushort value)
|
||||
{
|
||||
var sign = (value >> 15) & 0x1;
|
||||
var exponent = (value >> 10) & 0x1F;
|
||||
var mantissa = value & 0x3FF;
|
||||
|
||||
if (exponent == 0)
|
||||
{
|
||||
if (mantissa == 0)
|
||||
{
|
||||
return sign == 0 ? 0f : -0f;
|
||||
}
|
||||
|
||||
return (float)((sign == 0 ? 1 : -1) * Math.Pow(2, -14) * (mantissa / 1024.0));
|
||||
}
|
||||
|
||||
if (exponent == 31)
|
||||
{
|
||||
if (mantissa == 0)
|
||||
{
|
||||
return sign == 0 ? float.PositiveInfinity : float.NegativeInfinity;
|
||||
}
|
||||
|
||||
return float.NaN;
|
||||
}
|
||||
|
||||
return (float)((sign == 0 ? 1 : -1) * Math.Pow(2, exponent - 15) * (1.0 + mantissa / 1024.0));
|
||||
}
|
||||
|
||||
private static string SafeBounds(Mesh mesh)
|
||||
{
|
||||
try
|
||||
{
|
||||
var bounds = mesh.bounds;
|
||||
return $"center={bounds.center}, extents={bounds.extents}";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return $"<error: {ex.Message}>";
|
||||
}
|
||||
}
|
||||
|
||||
private static T SafeRead<T>(Func<T> getter, T fallback)
|
||||
{
|
||||
try
|
||||
{
|
||||
return getter();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
private static T[] SafeArrayRead<T>(Func<T[]> getter)
|
||||
{
|
||||
try
|
||||
{
|
||||
return getter();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool SafeHasAttr(Mesh mesh, VertexAttribute attribute)
|
||||
{
|
||||
try
|
||||
{
|
||||
return mesh.HasVertexAttribute(attribute);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static string BuildColorStats(Color32[] colors)
|
||||
{
|
||||
if (colors.Length == 0)
|
||||
{
|
||||
return "empty";
|
||||
}
|
||||
|
||||
byte minR = byte.MaxValue;
|
||||
byte minG = byte.MaxValue;
|
||||
byte minB = byte.MaxValue;
|
||||
byte minA = byte.MaxValue;
|
||||
byte maxR = byte.MinValue;
|
||||
byte maxG = byte.MinValue;
|
||||
byte maxB = byte.MinValue;
|
||||
byte maxA = byte.MinValue;
|
||||
var zeroAlphaCount = 0;
|
||||
|
||||
foreach (var color in colors)
|
||||
{
|
||||
if (color.r < minR) minR = color.r;
|
||||
if (color.g < minG) minG = color.g;
|
||||
if (color.b < minB) minB = color.b;
|
||||
if (color.a < minA) minA = color.a;
|
||||
if (color.r > maxR) maxR = color.r;
|
||||
if (color.g > maxG) maxG = color.g;
|
||||
if (color.b > maxB) maxB = color.b;
|
||||
if (color.a > maxA) maxA = color.a;
|
||||
if (color.a == 0) zeroAlphaCount++;
|
||||
}
|
||||
|
||||
return $"R[{minR},{maxR}] G[{minG},{maxG}] B[{minB},{maxB}] A[{minA},{maxA}] zeroA={zeroAlphaCount}/{colors.Length}";
|
||||
}
|
||||
|
||||
private static string BuildAlphaSummary(Color32[] colors)
|
||||
{
|
||||
if (colors.Length == 0)
|
||||
{
|
||||
return "empty";
|
||||
}
|
||||
|
||||
byte minA = byte.MaxValue;
|
||||
byte maxA = byte.MinValue;
|
||||
var zeroAlphaCount = 0;
|
||||
|
||||
foreach (var color in colors)
|
||||
{
|
||||
if (color.a < minA) minA = color.a;
|
||||
if (color.a > maxA) maxA = color.a;
|
||||
if (color.a == 0) zeroAlphaCount++;
|
||||
}
|
||||
|
||||
return $"A[{minA},{maxA}] zeroA={zeroAlphaCount}/{colors.Length}";
|
||||
}
|
||||
|
||||
private static string BuildColorSample(Color32[] colors, int maxCount)
|
||||
{
|
||||
if (colors.Length == 0)
|
||||
{
|
||||
return "empty";
|
||||
}
|
||||
|
||||
var count = Mathf.Min(colors.Length, maxCount);
|
||||
var sb = new StringBuilder();
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var color = colors[i];
|
||||
if (i > 0)
|
||||
{
|
||||
sb.Append(" | ");
|
||||
}
|
||||
|
||||
sb.Append($"#{i}:({color.r},{color.g},{color.b},{color.a})");
|
||||
}
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e66762c01b96f7c4280248196942465e
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,111 @@
|
||||
#if UNITY_EDITOR
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using Debug = UnityEngine.Debug;
|
||||
|
||||
public static class PhysicsCollisionCacheTests
|
||||
{
|
||||
[MenuItem("UmaViewer/Physics/Toggle collision geometry cache")]
|
||||
public static void ToggleCache()
|
||||
{
|
||||
DynamicBoneCollider.UseGeometryCache = !DynamicBoneCollider.UseGeometryCache;
|
||||
Debug.Log("[PhysicsPerformance] Collision geometry cache: " + DynamicBoneCollider.UseGeometryCache);
|
||||
}
|
||||
|
||||
[MenuItem("UmaViewer/Physics/Test collision cache equivalence")]
|
||||
public static void Run()
|
||||
{
|
||||
bool previous = DynamicBoneCollider.UseGeometryCache;
|
||||
var root = new GameObject("CollisionCacheTest") { hideFlags = HideFlags.HideAndDontSave };
|
||||
int checks = 0;
|
||||
try
|
||||
{
|
||||
var collider = root.AddComponent<DynamicBoneCollider>();
|
||||
var random = new System.Random(1709);
|
||||
var samples = new Vector3[512];
|
||||
for (int i = 0; i < samples.Length; ++i)
|
||||
samples[i] = new Vector3((float)random.NextDouble() * 4 - 2,
|
||||
(float)random.NextDouble() * 4 - 2, (float)random.NextDouble() * 4 - 2);
|
||||
for (int shape = 0; shape < 2; ++shape)
|
||||
for (int bound = 0; bound < 2; ++bound)
|
||||
for (int axis = 0; axis < 3; ++axis)
|
||||
for (int pose = 0; pose < 4; ++pose)
|
||||
{
|
||||
root.transform.position = new Vector3(pose * 0.1f, -0.2f, 0.3f);
|
||||
root.transform.rotation = Quaternion.Euler(pose * 23, pose * 11, -17);
|
||||
root.transform.localScale = new Vector3(pose == 3 ? -1.2f : 1.2f, 0.7f + pose * 0.1f, 1.5f);
|
||||
collider.m_Radius = 0.4f + pose * 0.02f;
|
||||
collider.m_Height = shape == 0 ? 0 : 2;
|
||||
collider.m_Center = new Vector3(0.1f, -0.15f, 0.2f);
|
||||
collider.m_Direction = (DynamicBoneColliderBase.Direction)axis;
|
||||
collider.m_Bound = (DynamicBoneColliderBase.Bound)bound;
|
||||
using (DynamicBoneCollider.BeginCollisionBatch())
|
||||
{
|
||||
foreach (Vector3 sample in samples)
|
||||
{
|
||||
Check(collider, sample, 0.015f);
|
||||
++checks;
|
||||
}
|
||||
using (DynamicBoneCollider.BeginCollisionBatch())
|
||||
Check(collider, samples[0], 0.015f);
|
||||
Check(collider, samples[1], 0.015f);
|
||||
}
|
||||
// No batch: a moved collider must be read immediately, not from the last cache.
|
||||
root.transform.position += Vector3.up * 0.2f;
|
||||
Check(collider, samples[2], 0.03f);
|
||||
}
|
||||
collider.m_Bound = DynamicBoneColliderBase.Bound.Outside;
|
||||
collider.m_Height = 2;
|
||||
const int rounds = 1024;
|
||||
// Warm both paths and use two orders to reduce ordering/JIT bias.
|
||||
Measure(collider, samples, 8, false);
|
||||
Measure(collider, samples, 8, true);
|
||||
double uncached = Measure(collider, samples, rounds, false);
|
||||
double cached = Measure(collider, samples, rounds, true);
|
||||
cached += Measure(collider, samples, rounds, true);
|
||||
uncached += Measure(collider, samples, rounds, false);
|
||||
string report = $"[PhysicsPerformance] PASS: {checks} point comparisons + nested scopes and moved colliders. " +
|
||||
$"Synthetic {rounds * samples.Length * 2} queries/path: uncached={uncached:F2}ms, cached={cached:F2}ms, " +
|
||||
$"ratio={uncached / Math.Max(cached, 0.001):F2}x. This is NOT a Live frame-time benchmark.";
|
||||
Debug.Log(report);
|
||||
string output = Environment.GetEnvironmentVariable("UMA_PHYSICS_TEST_REPORT");
|
||||
if (!string.IsNullOrEmpty(output)) File.WriteAllText(output, report);
|
||||
}
|
||||
finally
|
||||
{
|
||||
DynamicBoneCollider.UseGeometryCache = previous;
|
||||
UnityEngine.Object.DestroyImmediate(root);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Check(DynamicBoneCollider collider, Vector3 input, float radius)
|
||||
{
|
||||
Vector3 expected = input, actual = input;
|
||||
DynamicBoneCollider.UseGeometryCache = false;
|
||||
bool expectedHit = collider.Collide(ref expected, radius);
|
||||
DynamicBoneCollider.UseGeometryCache = true;
|
||||
bool actualHit = collider.Collide(ref actual, radius);
|
||||
if (expectedHit != actualHit || (actual - expected).sqrMagnitude > 1e-12f ||
|
||||
float.IsNaN(actual.x) || float.IsNaN(actual.y) || float.IsNaN(actual.z))
|
||||
throw new Exception($"Collision cache mismatch: expected {expectedHit}/{expected}, actual {actualHit}/{actual}");
|
||||
}
|
||||
|
||||
private static double Measure(DynamicBoneCollider collider, Vector3[] samples, int rounds, bool cached)
|
||||
{
|
||||
DynamicBoneCollider.UseGeometryCache = cached;
|
||||
var timer = Stopwatch.StartNew();
|
||||
for (int i = 0; i < rounds; ++i)
|
||||
using (DynamicBoneCollider.BeginCollisionBatch())
|
||||
foreach (var sample in samples)
|
||||
{
|
||||
Vector3 point = sample;
|
||||
collider.Collide(ref point, 0.015f);
|
||||
}
|
||||
timer.Stop();
|
||||
return timer.Elapsed.TotalMilliseconds;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4111da92019549a083a824c4a20b7e8c
|
||||
@@ -0,0 +1,52 @@
|
||||
#if UNITY_EDITOR
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Gallop;
|
||||
using Gallop.Live;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>Checks loaded characters without changing their pose or stopping playback.</summary>
|
||||
[InitializeOnLoad]
|
||||
public static class PhysicsMigrationValidation
|
||||
{
|
||||
static PhysicsMigrationValidation() { EditorApplication.delayCall += ValidateIfPlaying; }
|
||||
static void ValidateIfPlaying() { if (EditorApplication.isPlaying) Validate(); }
|
||||
|
||||
[MenuItem("UmaViewer/Physics/Validate master5 migration")]
|
||||
public static void Validate()
|
||||
{
|
||||
var characters = UnityEngine.Object.FindObjectsOfType<UmaContainerCharacter>();
|
||||
foreach (var character in characters.Where(c => !c.IsMini))
|
||||
{
|
||||
var bones = character.GetComponentsInChildren<DynamicBone>(true);
|
||||
var surface = character.GetComponent<SkirtSurfaceCollisionSolver>();
|
||||
var oldController = character.GetComponent<CySpringController>();
|
||||
var oldSkirt = character.GetComponent<SkirtController>();
|
||||
string report = $"[PhysicsMigration] character={character.name} dynamicBones={bones.Length} " +
|
||||
$"rings={(surface != null ? surface.RingCount : 0)} " +
|
||||
$"thighColliders={(surface != null ? surface.ColliderCount : 0)} " +
|
||||
$"oldCySpring={(oldController != null)} oldSkirt={(oldSkirt != null)}";
|
||||
if (oldController != null || oldSkirt != null || bones.Length == 0)
|
||||
Debug.LogWarning(report + " Reload this character/Live after script migration.");
|
||||
else Debug.Log(report);
|
||||
if (character.IsLive)
|
||||
{
|
||||
var profile = character.GetComponent<Master5LivePhysicsProfile>();
|
||||
if (profile == null)
|
||||
Debug.LogWarning("[PhysicsMigration] Missing master5 Live profile; reload Live to apply radius tuning.");
|
||||
else
|
||||
Debug.Log($"[PhysicsMigration] master5 profile colliders={profile.TunedColliderCount} horizontalStiffness={surface?.HorizontalStiffness}");
|
||||
foreach (var collider in character.GetComponentsInChildren<DynamicBoneCollider>(true))
|
||||
{
|
||||
float scale = Master5LivePhysicsProfile.RadiusScale(collider.ColliderName);
|
||||
if (scale == 1f) continue;
|
||||
Debug.Log($"[PhysicsMigration] {collider.ColliderName}: localRadius={collider.m_Radius:F5}, " +
|
||||
$"height={collider.m_Height:F5}, lossyScale={collider.transform.lossyScale}, expectedRadiusMultiplier={scale:F2}", collider);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (characters.Length == 0) Debug.Log("[PhysicsMigration] No loaded characters; load a character to validate runtime binding.");
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a970a346d5902f34cac957aba3135a41
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Reference in New Issue
Block a user