SpringRigImporter and CaptureAsset; the synthetic Capture and TubeMesh are deleted
SpringRigImporter ([ScriptedImporter] for .springrig, a rig GLB) derives everything from the file's bytes: SpringRigData.FromGlb decides acceptance (a refusal is an import error and no main object); glTFast loads and instantiates the same bytes once, driven to completion on a one-thread synchronization context (its RunSync is internal), and the one skinned mesh is repacked into SpringSkin's streams (Float32 position and normal, uv, Float32x4 weights and UInt32x4 indices); the base colour is decoded from the image the material names, sRGB with mips, compressed to BC7 at most MaxTextureSize (4096) a side; the material is on Aetheria/FaunaSkinned with smoothness 1 - roughnessFactor; the rig is a TextAsset of the GLB with every image's bytes zeroed. The main object has MeshFilter, MeshRenderer and SpringRig (Renderer, Rig, Swim from the importer's serialized field). Nothing derived is committed. SpringRigVerify.CaptureAsset (SPRINGRIG_ASSET an Assets path, SPRINGRIG_CAPTURE_OUT absolute) loads the imported main object through AssetDatabase and swims it along +Z with a slow yaw under one shadow-casting directional light and flat ambient; optional focus, distance, side, frames and a floor to see the shadow. It restores the quality settings it changes. MakeMesh in the checks now calls SpringRigImporter.Pack, the one owner of the stream layout. Deleted: Capture (the synthetic-tube swim capture) and TubeMesh, which only it called. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
8930122e92
commit
67120a0236
3 changed files with 292 additions and 98 deletions
229
Assets/Scripts/Editor/SpringRigImporter.cs
Normal file
229
Assets/Scripts/Editor/SpringRigImporter.cs
Normal file
|
|
@ -0,0 +1,229 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Aetheria.FaunaDisplay;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Unity.Mathematics;
|
||||
using UnityEditor;
|
||||
using UnityEditor.AssetImporters;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
|
||||
namespace Aetheria.EditorTools
|
||||
{
|
||||
/// <summary>
|
||||
/// A .springrig file is a rig GLB (Brokkr's recipe export: a mesh, one skin, VRMC_springBone) and the one committed source of a
|
||||
/// fauna rig asset (campaign aetheria-fauna, cut whale-rig-leviathan-asset). The importer derives from its bytes, and commits
|
||||
/// nothing derived: the mesh in SpringSkin's layout, the base colour as a BC7 texture with mips, a material on Aetheria/FaunaSkinned,
|
||||
/// a TextAsset of the GLB with its image bytes zeroed (SpringRig parses it at Awake; the rig reads no image), and a main object with
|
||||
/// MeshFilter, MeshRenderer and SpringRig. SpringRigData.FromGlb decides whether the rig is acceptable and adds no rule here; glTFast
|
||||
/// supplies the mesh in the same handedness as the rig (SpringRigData's mirror) and is used here and in VerifyGlb only.
|
||||
/// </summary>
|
||||
[ScriptedImporter(1, "springrig")]
|
||||
public sealed class SpringRigImporter : ScriptedImporter
|
||||
{
|
||||
public SwimSettings Swim = new SwimSettings { AmplitudeDegrees = 9f, PeriodSeconds = 3.2f, PhasePerBone = 0.1f, Axis = new float3(1, 0, 0) };
|
||||
[Tooltip("The base colour is scaled down to at most this many texels a side before it is compressed.")]
|
||||
public int MaxTextureSize = 4096;
|
||||
|
||||
public override void OnImportAsset(AssetImportContext ctx)
|
||||
{
|
||||
byte[] glb = File.ReadAllBytes(ctx.assetPath);
|
||||
try { SpringRigData.FromGlb(glb); }
|
||||
catch (Exception e) { ctx.LogImportError($"{ctx.assetPath}: not an acceptable rig: {e.Message}"); return; }
|
||||
|
||||
var (json, binAt) = Chunks(glb);
|
||||
var mesh = ImportMesh(glb, out string refusal);
|
||||
if (mesh == null) { ctx.LogImportError($"{ctx.assetPath}: {refusal}"); return; }
|
||||
mesh.name = "mesh";
|
||||
|
||||
ctx.DependsOnSourceAsset("Assets/Shaders/FaunaSkinned.shader"); // the material needs the shader imported first, and reimports with it
|
||||
var material = new Material(Shader.Find("Aetheria/FaunaSkinned")) { name = "material" };
|
||||
var materialIndex = json["meshes"]?[0]?["primitives"]?[0]?["material"];
|
||||
var pbr = materialIndex == null ? null : json["materials"]?[(int)materialIndex]?["pbrMetallicRoughness"];
|
||||
material.SetFloat("_Glossiness", 1f - ((float?)pbr?["roughnessFactor"] ?? 1f));
|
||||
material.SetFloat("_Metallic", 0f);
|
||||
Texture2D albedo = null;
|
||||
var image = BaseColorImage(json, binAt, glb);
|
||||
if (image != null)
|
||||
{
|
||||
albedo = Albedo(image, Math.Max(MaxTextureSize, 4));
|
||||
albedo.name = "albedo";
|
||||
material.SetTexture("_MainTex", albedo);
|
||||
}
|
||||
|
||||
// The rig's bytes with every image's bytes zeroed: FromGlb reads JSON and BIN only, and zeros compress.
|
||||
var rigBytes = (byte[])glb.Clone();
|
||||
foreach (var each in json["images"] as JArray ?? new JArray())
|
||||
if (each["bufferView"] != null)
|
||||
{
|
||||
var view = json["bufferViews"][(int)each["bufferView"]];
|
||||
Array.Clear(rigBytes, binAt + ((int?)view["byteOffset"] ?? 0), (int)view["byteLength"]);
|
||||
}
|
||||
var rig = new TextAsset(rigBytes) { name = "rig" };
|
||||
|
||||
var go = new GameObject(Path.GetFileNameWithoutExtension(ctx.assetPath));
|
||||
go.AddComponent<MeshFilter>().sharedMesh = mesh;
|
||||
var renderer = go.AddComponent<MeshRenderer>();
|
||||
renderer.sharedMaterial = material;
|
||||
var spring = go.AddComponent<SpringRig>();
|
||||
spring.Renderer = renderer;
|
||||
spring.Rig = rig;
|
||||
spring.Swim = Swim;
|
||||
|
||||
ctx.AddObjectToAsset("main", go);
|
||||
ctx.SetMainObject(go);
|
||||
ctx.AddObjectToAsset("mesh", mesh);
|
||||
ctx.AddObjectToAsset("material", material);
|
||||
ctx.AddObjectToAsset("rig", rig);
|
||||
if (albedo != null) ctx.AddObjectToAsset("albedo", albedo);
|
||||
}
|
||||
|
||||
// glTFast loads the GLB and instantiates it once; the one skinned mesh is repacked into SpringSkin's layout.
|
||||
static Mesh ImportMesh(byte[] glb, out string refusal)
|
||||
{
|
||||
refusal = null;
|
||||
var gltf = new GLTFast.GltfImport(deferAgent: new GLTFast.UninterruptedDeferAgent());
|
||||
var root = new GameObject("springrig-import");
|
||||
try
|
||||
{
|
||||
bool ok = RunSync(async () => await gltf.Load(glb) && await gltf.InstantiateMainSceneAsync(root.transform));
|
||||
var skinned = root.GetComponentsInChildren<SkinnedMeshRenderer>();
|
||||
if (!ok || skinned.Length != 1) { refusal = ok ? $"expected one skinned mesh, glTFast made {skinned.Length}" : "glTFast did not import the GLB"; return null; }
|
||||
var src = skinned[0].sharedMesh;
|
||||
var weights = src.boneWeights;
|
||||
var uv = src.uv;
|
||||
return Pack(src.vertices, src.normals, uv.Length == src.vertexCount ? uv : new Vector2[src.vertexCount],
|
||||
weights.Select(w => new Vector4(w.weight0, w.weight1, w.weight2, w.weight3)).ToArray(),
|
||||
weights.SelectMany(w => new[] { (uint)w.boneIndex0, (uint)w.boneIndex1, (uint)w.boneIndex2, (uint)w.boneIndex3 }).ToArray(),
|
||||
src.triangles);
|
||||
}
|
||||
finally
|
||||
{
|
||||
UnityEngine.Object.DestroyImmediate(root);
|
||||
gltf.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
// The mesh as SpringSkin reads it: position and normal in stream 0, uv in 1, blend weights (Float32x4) and indices (UInt32x4)
|
||||
// in 2. bones holds four indices per vertex. Also the layout of every synthetic mesh the checks build.
|
||||
public static Mesh Pack(Vector3[] position, Vector3[] normal, Vector2[] uv, Vector4[] weight, uint[] bones, int[] triangles)
|
||||
{
|
||||
int n = position.Length;
|
||||
var mesh = new Mesh { indexFormat = IndexFormat.UInt32 };
|
||||
mesh.SetVertexBufferParams(n,
|
||||
new VertexAttributeDescriptor(VertexAttribute.Position, VertexAttributeFormat.Float32, 3, 0),
|
||||
new VertexAttributeDescriptor(VertexAttribute.Normal, VertexAttributeFormat.Float32, 3, 0),
|
||||
new VertexAttributeDescriptor(VertexAttribute.TexCoord0, VertexAttributeFormat.Float32, 2, 1),
|
||||
new VertexAttributeDescriptor(VertexAttribute.BlendWeight, VertexAttributeFormat.Float32, 4, 2),
|
||||
new VertexAttributeDescriptor(VertexAttribute.BlendIndices, VertexAttributeFormat.UInt32, 4, 2));
|
||||
// Unity wants position and normal, texcoords and the blend pair in streams 0, 1, 2 for a skinned mesh, and warns otherwise.
|
||||
var stream0 = new float[n * 6]; var stream2 = new byte[n * 32];
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
Buffer.BlockCopy(new[] { position[i].x, position[i].y, position[i].z, normal[i].x, normal[i].y, normal[i].z }, 0, stream0, i * 24, 24);
|
||||
Buffer.BlockCopy(new[] { weight[i].x, weight[i].y, weight[i].z, weight[i].w }, 0, stream2, i * 32, 16);
|
||||
Buffer.BlockCopy(bones, i * 16, stream2, i * 32 + 16, 16);
|
||||
}
|
||||
mesh.SetVertexBufferData(stream0, 0, 0, n * 6, 0);
|
||||
mesh.SetVertexBufferData(uv, 0, 0, n, 1);
|
||||
mesh.SetVertexBufferData(stream2, 0, 0, stream2.Length, 2);
|
||||
mesh.SetIndexBufferParams(triangles.Length, IndexFormat.UInt32);
|
||||
mesh.SetIndexBufferData(triangles, 0, 0, triangles.Length);
|
||||
mesh.subMeshCount = 1;
|
||||
mesh.SetSubMesh(0, new SubMeshDescriptor(0, triangles.Length));
|
||||
mesh.RecalculateBounds();
|
||||
return mesh;
|
||||
}
|
||||
|
||||
// The bytes of the image the first primitive's material names as its base colour, or null.
|
||||
static byte[] BaseColorImage(JObject json, int binAt, byte[] glb)
|
||||
{
|
||||
var material = json["meshes"]?[0]?["primitives"]?[0]?["material"];
|
||||
var index = material == null ? null : json["materials"]?[(int)material]?["pbrMetallicRoughness"]?["baseColorTexture"]?["index"];
|
||||
var source = index == null ? null : json["textures"]?[(int)index]?["source"];
|
||||
var view = source == null ? null : json["images"]?[(int)source]?["bufferView"];
|
||||
if (view == null) return null;
|
||||
var v = json["bufferViews"][(int)view];
|
||||
var bytes = new byte[(int)v["byteLength"]];
|
||||
Buffer.BlockCopy(glb, binAt + ((int?)v["byteOffset"] ?? 0), bytes, 0, bytes.Length);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
// sRGB, mips, BC7. Scaled down first when larger than max.
|
||||
static Texture2D Albedo(byte[] image, int max)
|
||||
{
|
||||
var decoded = new Texture2D(2, 2, TextureFormat.RGBA32, false, false);
|
||||
if (!decoded.LoadImage(image, false)) { UnityEngine.Object.DestroyImmediate(decoded); return null; }
|
||||
int w = decoded.width, h = decoded.height, side = Math.Max(w, h);
|
||||
if (side > max) { w = Math.Max(1, w * max / side); h = Math.Max(1, h * max / side); }
|
||||
var rt = RenderTexture.GetTemporary(w, h, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);
|
||||
var previous = RenderTexture.active;
|
||||
Graphics.Blit(decoded, rt);
|
||||
var texture = new Texture2D(w, h, TextureFormat.RGBA32, true, false);
|
||||
RenderTexture.active = rt;
|
||||
texture.ReadPixels(new Rect(0, 0, w, h), 0, 0);
|
||||
RenderTexture.active = previous;
|
||||
RenderTexture.ReleaseTemporary(rt);
|
||||
UnityEngine.Object.DestroyImmediate(decoded);
|
||||
texture.Apply(true);
|
||||
EditorUtility.CompressTexture(texture, TextureFormat.BC7, TextureCompressionQuality.Normal);
|
||||
return texture;
|
||||
}
|
||||
|
||||
// The JSON chunk and the offset of the BIN chunk's data (the container SpringRigData.FromGlb reads).
|
||||
static (JObject json, int binAt) Chunks(byte[] glb)
|
||||
{
|
||||
JObject json = null; int binAt = -1;
|
||||
for (int at = 12; at + 8 <= glb.Length;)
|
||||
{
|
||||
int length = (int)BitConverter.ToUInt32(glb, at);
|
||||
uint type = BitConverter.ToUInt32(glb, at + 4);
|
||||
if (type == 0x4E4F534A) json = JObject.Parse(Encoding.UTF8.GetString(glb, at + 8, length));
|
||||
else if (type == 0x004E4942 && binAt < 0) binAt = at + 8;
|
||||
at += 8 + length;
|
||||
}
|
||||
return (json, binAt);
|
||||
}
|
||||
|
||||
// glTFast's own importer drives its loader to completion this way (its AsyncHelpers.RunSync is internal): a context that runs
|
||||
// every continuation on this thread, so Unity's API is only touched from it.
|
||||
static bool RunSync(Func<Task<bool>> work)
|
||||
{
|
||||
var previous = SynchronizationContext.Current;
|
||||
var loop = new Loop();
|
||||
SynchronizationContext.SetSynchronizationContext(loop);
|
||||
try { return loop.Run(work); }
|
||||
finally { SynchronizationContext.SetSynchronizationContext(previous); }
|
||||
}
|
||||
|
||||
sealed class Loop : SynchronizationContext
|
||||
{
|
||||
readonly Queue<(SendOrPostCallback, object)> _queue = new Queue<(SendOrPostCallback, object)>();
|
||||
readonly AutoResetEvent _wake = new AutoResetEvent(false);
|
||||
|
||||
public override void Post(SendOrPostCallback d, object state) { lock (_queue) _queue.Enqueue((d, state)); _wake.Set(); }
|
||||
|
||||
public bool Run(Func<Task<bool>> work)
|
||||
{
|
||||
var task = work();
|
||||
task.ContinueWith(_ => _wake.Set(), TaskScheduler.Default);
|
||||
while (!task.IsCompleted)
|
||||
{
|
||||
(SendOrPostCallback, object) item = default; bool any;
|
||||
lock (_queue) { any = _queue.Count > 0; if (any) item = _queue.Dequeue(); }
|
||||
if (any) item.Item1(item.Item2); else _wake.WaitOne(50);
|
||||
}
|
||||
return task.GetAwaiter().GetResult();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Editor/SpringRigImporter.cs.meta
Normal file
2
Assets/Scripts/Editor/SpringRigImporter.cs.meta
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 467b0d4c17afeb24e8a27b9be8f80f59
|
||||
|
|
@ -26,7 +26,10 @@ namespace Aetheria.EditorTools
|
|||
/// SPRINGRIG_GLB (same flags, method VerifyGlb); it adds no rule of its own. .springrig files are GLBs. It is a thin wrapper
|
||||
/// over GlbFile, the file run (a missing path, a refusal or a failed comparison is exit 1, a pass 0) that VerifyGlbCases also runs.
|
||||
/// VerifyGlbCases pins GlbFile's verdicts and exit codes on edited Synth GLBs, the committed asset, a text file and a missing path (same flags).
|
||||
/// Capture renders a short swim to PNG frames in SPRINGRIG_CAPTURE_OUT (same flags, method Capture).
|
||||
/// CaptureAsset renders the imported .springrig at SPRINGRIG_ASSET (an Assets path) swimming under one directional light to PNG frames in
|
||||
/// SPRINGRIG_CAPTURE_OUT (an absolute path; same flags, method CaptureAsset). Optional: SPRINGRIG_FRAMES (300), SPRINGRIG_FOCUS (x,y,z in
|
||||
/// the whale's object space, the camera's target), SPRINGRIG_DISTANCE (1.15), SPRINGRIG_SIDE=-1 (the camera on the -X side), SPRINGRIG_PLANE=1 (a floor
|
||||
/// under the whale, to see its shadow).
|
||||
/// </summary>
|
||||
public static class SpringRigVerify
|
||||
{
|
||||
|
|
@ -938,55 +941,82 @@ namespace Aetheria.EditorTools
|
|||
|
||||
// ---------------------------------------------------------------- capture
|
||||
|
||||
public static void Capture()
|
||||
// The look check: the imported asset (the main object a .springrig imports to, through AssetDatabase) swims along its +Z with a slow
|
||||
// yaw under one directional light with shadows and flat ambient, and every frame is a PNG. The camera follows the whale's position and
|
||||
// looks at SPRINGRIG_FOCUS in its object space, so a close framing follows the part it names.
|
||||
public static void CaptureAsset()
|
||||
{
|
||||
var dir = Environment.GetEnvironmentVariable("SPRINGRIG_CAPTURE_OUT") ?? throw new InvalidOperationException("Set SPRINGRIG_CAPTURE_OUT.");
|
||||
Directory.CreateDirectory(dir);
|
||||
Action restoreQuality = null;
|
||||
try
|
||||
{
|
||||
var s = new Synth { Spine = 8, Chains = 28, Joints = 8, Stiffness = 2.5f, Drag = 0.3f, Gravity = 0f, Ring = 0.45f, Seg = new Vector3(0, -0.12f, -0.34f) };
|
||||
var go = new GameObject("whale");
|
||||
var rig = go.AddComponent<SpringRig>();
|
||||
var data = SpringRigData.FromGlbJson(s.Build(out var bin), bin);
|
||||
var mesh = TubeMesh(data, s);
|
||||
go.AddComponent<MeshFilter>().sharedMesh = mesh;
|
||||
var mr = go.AddComponent<MeshRenderer>();
|
||||
mr.sharedMaterial = SkinMaterial(0);
|
||||
rig.Renderer = mr;
|
||||
rig.Swim = new SwimSettings { AmplitudeDegrees = 7, PeriodSeconds = 3.2f, PhasePerBone = 0.1f, Axis = new float3(1, 0, 0) };
|
||||
rig.Initialize(data, mesh.bounds);
|
||||
var asset = Environment.GetEnvironmentVariable("SPRINGRIG_ASSET") ?? throw new InvalidOperationException("Set SPRINGRIG_ASSET to an Assets path.");
|
||||
var dir = Environment.GetEnvironmentVariable("SPRINGRIG_CAPTURE_OUT") ?? throw new InvalidOperationException("Set SPRINGRIG_CAPTURE_OUT.");
|
||||
if (!Path.IsPathRooted(dir)) throw new InvalidOperationException($"SPRINGRIG_CAPTURE_OUT must be absolute (got '{dir}').");
|
||||
int frames = int.TryParse(Environment.GetEnvironmentVariable("SPRINGRIG_FRAMES"), out var n) ? n : 300;
|
||||
float distance = float.TryParse(Environment.GetEnvironmentVariable("SPRINGRIG_DISTANCE"), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var d) ? d : 1.15f;
|
||||
bool plane = Environment.GetEnvironmentVariable("SPRINGRIG_PLANE") == "1";
|
||||
float side = Environment.GetEnvironmentVariable("SPRINGRIG_SIDE") == "-1" ? -1f : 1f;
|
||||
Directory.CreateDirectory(dir);
|
||||
var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(asset) ?? throw new InvalidOperationException($"No imported asset at {asset}.");
|
||||
var go = UnityEngine.Object.Instantiate(prefab);
|
||||
var rig = go.GetComponent<SpringRig>() ?? throw new InvalidOperationException($"{asset} has no SpringRig.");
|
||||
rig.Initialize();
|
||||
var focus = rig.Renderer.localBounds.center;
|
||||
var spec = Environment.GetEnvironmentVariable("SPRINGRIG_FOCUS");
|
||||
if (!string.IsNullOrEmpty(spec))
|
||||
{
|
||||
var p = spec.Split(',').Select(s => float.Parse(s, System.Globalization.CultureInfo.InvariantCulture)).ToArray();
|
||||
focus = new Vector3(p[0], p[1], p[2]);
|
||||
}
|
||||
// Quality settings persist into ProjectSettings when the editor exits: put them back when the capture ends.
|
||||
var (quality, distanceBefore, resolution) = (QualitySettings.shadows, QualitySettings.shadowDistance, QualitySettings.shadowResolution);
|
||||
restoreQuality = () => { QualitySettings.shadows = quality; QualitySettings.shadowDistance = distanceBefore; QualitySettings.shadowResolution = resolution; };
|
||||
QualitySettings.shadows = ShadowQuality.All;
|
||||
QualitySettings.shadowDistance = 20;
|
||||
QualitySettings.shadowResolution = UnityEngine.ShadowResolution.VeryHigh;
|
||||
var light = new GameObject("sun").AddComponent<Light>();
|
||||
light.type = LightType.Directional; light.intensity = 1.1f;
|
||||
light.type = LightType.Directional; light.intensity = 1.9f; light.shadows = LightShadows.Soft;
|
||||
light.transform.rotation = Quaternion.Euler(45, -35, 0);
|
||||
RenderSettings.ambientMode = AmbientMode.Flat; RenderSettings.ambientLight = new Color(0.25f, 0.28f, 0.34f);
|
||||
RenderSettings.ambientMode = AmbientMode.Flat; RenderSettings.ambientLight = new Color(0.70f, 0.74f, 0.85f);
|
||||
GameObject floor = null;
|
||||
if (plane)
|
||||
{
|
||||
floor = GameObject.CreatePrimitive(PrimitiveType.Plane);
|
||||
floor.GetComponent<Renderer>().sharedMaterial = new Material(Shader.Find("Standard")) { color = new Color(0.55f, 0.55f, 0.6f) };
|
||||
floor.transform.localScale = Vector3.one * 0.5f;
|
||||
}
|
||||
var cam = new GameObject("cam").AddComponent<Camera>();
|
||||
cam.clearFlags = CameraClearFlags.SolidColor; cam.backgroundColor = new Color(0.03f, 0.04f, 0.09f);
|
||||
cam.fieldOfView = 40; cam.nearClipPlane = 0.1f; cam.farClipPlane = 200;
|
||||
var rt = new RenderTexture(960, 540, 24, RenderTextureFormat.ARGB32) { antiAliasing = 4 };
|
||||
cam.fieldOfView = 40; cam.nearClipPlane = 0.02f; cam.farClipPlane = 100;
|
||||
var rt = new RenderTexture(1280, 720, 24, RenderTextureFormat.ARGB32) { antiAliasing = 4 };
|
||||
cam.targetTexture = rt;
|
||||
var read = new Texture2D(rt.width, rt.height, TextureFormat.RGB24, false);
|
||||
for (int f = 0; f < 300; f++)
|
||||
Vector3 pos = Vector3.zero;
|
||||
for (int f = 0; f < frames; f++)
|
||||
{
|
||||
double t = f * Dt;
|
||||
// Swim forward along +z, wandering in a slow S so the body yaws and the tendrils trail across it.
|
||||
var pos = new Vector3(Mathf.Sin((float)t * 0.9f) * 1.6f, Mathf.Sin((float)t * 0.5f) * 0.4f, (float)t * 3.2f);
|
||||
var yaw = Mathf.Cos((float)t * 0.9f) * 14f;
|
||||
rig.Present(t, pos, Quaternion.Euler(0, yaw, 0), 1);
|
||||
var centre = pos + new Vector3(0, -0.2f, 3);
|
||||
cam.transform.position = centre + new Vector3(9.5f, 2.0f, -3.5f);
|
||||
cam.transform.LookAt(centre);
|
||||
// Swim forward along +z, yawing slowly and drifting sideways a little, so the tendrils trail across the body.
|
||||
var rot = Quaternion.AngleAxis(Mathf.Cos((float)t * 0.9f) * 22f, Vector3.up);
|
||||
pos += rot * Vector3.forward * (0.55f / 60f) + Vector3.right * (Mathf.Sin((float)t * 1.3f) * 0.004f);
|
||||
rig.Present(t, pos, rot, 1);
|
||||
var target = pos + rot * focus;
|
||||
if (floor != null) floor.transform.position = new Vector3(pos.x, pos.y - 0.45f, pos.z);
|
||||
cam.transform.position = target + Vector3.right * (side * distance) + Vector3.up * (0.2f * distance) - Vector3.forward * (0.1f * distance);
|
||||
cam.transform.LookAt(target, Vector3.up);
|
||||
cam.Render();
|
||||
RenderTexture.active = rt;
|
||||
read.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
|
||||
RenderTexture.active = null;
|
||||
File.WriteAllBytes(Path.Combine(dir, $"frame_{f:D4}.png"), read.EncodeToPNG());
|
||||
}
|
||||
Debug.Log($"{Tag} captured 300 frames to {dir}");
|
||||
Debug.Log($"{Tag} captured {frames} frames of {asset} to {dir}; steps {rig.SubstepsRun} resets {rig.Resets} level {rig.Level}");
|
||||
restoreQuality?.Invoke();
|
||||
EditorApplication.Exit(0);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.LogError($"{Tag} capture FAIL: {e}");
|
||||
restoreQuality?.Invoke();
|
||||
EditorApplication.Exit(1);
|
||||
}
|
||||
}
|
||||
|
|
@ -1195,31 +1225,11 @@ namespace Aetheria.EditorTools
|
|||
|
||||
// ---------------------------------------------------------------- meshes and materials
|
||||
|
||||
struct PosNormal { public Vector3 p, n; }
|
||||
struct Blend { public Vector4 w; public uint b0, b1, b2, b3; }
|
||||
struct Vertex { public Vector3 p, n; public Vector2 uv; public Vector4 w; public uint b0, b1, b2, b3; }
|
||||
|
||||
static Mesh MakeMesh(List<Vertex> verts, List<int> tris)
|
||||
{
|
||||
var mesh = new Mesh();
|
||||
mesh.SetVertexBufferParams(verts.Count,
|
||||
new VertexAttributeDescriptor(VertexAttribute.Position, VertexAttributeFormat.Float32, 3, 0),
|
||||
new VertexAttributeDescriptor(VertexAttribute.Normal, VertexAttributeFormat.Float32, 3, 0),
|
||||
new VertexAttributeDescriptor(VertexAttribute.TexCoord0, VertexAttributeFormat.Float32, 2, 1),
|
||||
new VertexAttributeDescriptor(VertexAttribute.BlendWeight, VertexAttributeFormat.Float32, 4, 2),
|
||||
new VertexAttributeDescriptor(VertexAttribute.BlendIndices, VertexAttributeFormat.UInt32, 4, 2));
|
||||
// Unity wants position and normal, texcoords and the blend pair in streams 0, 1, 2 for a skinned mesh, and warns otherwise;
|
||||
// other layouts render the same (Soul, four layouts). The contract with a glTFast mesh is BlendWeight Float32x4 and BlendIndices UInt32x4.
|
||||
mesh.SetVertexBufferData(verts.Select(v => new PosNormal { p = v.p, n = v.n }).ToArray(), 0, 0, verts.Count, 0);
|
||||
mesh.SetVertexBufferData(verts.Select(v => v.uv).ToArray(), 0, 0, verts.Count, 1);
|
||||
mesh.SetVertexBufferData(verts.Select(v => new Blend { w = v.w, b0 = v.b0, b1 = v.b1, b2 = v.b2, b3 = v.b3 }).ToArray(), 0, 0, verts.Count, 2);
|
||||
mesh.SetIndexBufferParams(tris.Count, IndexFormat.UInt32);
|
||||
mesh.SetIndexBufferData(tris, 0, 0, tris.Count);
|
||||
mesh.subMeshCount = 1;
|
||||
mesh.SetSubMesh(0, new SubMeshDescriptor(0, tris.Count));
|
||||
mesh.RecalculateBounds();
|
||||
return mesh;
|
||||
}
|
||||
static Mesh MakeMesh(List<Vertex> verts, List<int> tris) =>
|
||||
SpringRigImporter.Pack(verts.Select(v => v.p).ToArray(), verts.Select(v => v.n).ToArray(), verts.Select(v => v.uv).ToArray(), verts.Select(v => v.w).ToArray(),
|
||||
verts.SelectMany(v => new[] { v.b0, v.b1, v.b2, v.b3 }).ToArray(), tris.ToArray());
|
||||
|
||||
static Material SkinMaterial(float cull)
|
||||
{
|
||||
|
|
@ -1248,52 +1258,5 @@ namespace Aetheria.EditorTools
|
|||
}
|
||||
return (verts, tris);
|
||||
}
|
||||
|
||||
// A closed-ish whale: rings of body skinned to the spine, a thin tube along every tendril skinned joint by joint.
|
||||
static Mesh TubeMesh(SpringRigData d, Synth s)
|
||||
{
|
||||
var verts = new List<Vertex>(); var tris = new List<int>();
|
||||
void Ring(Func<int, (Vector3 p, Vector3 n)> shape, int sides, Vector4 w, uint b0, uint b1, Vector2 uv)
|
||||
{
|
||||
for (int i = 0; i < sides; i++) { var (p, n) = shape(i); verts.Add(new Vertex { p = p, n = n, uv = uv, w = w, b0 = b0, b1 = b1 }); }
|
||||
}
|
||||
void Join(int ringA, int ringB, int sides)
|
||||
{
|
||||
for (int i = 0; i < sides; i++)
|
||||
{
|
||||
int j = (i + 1) % sides;
|
||||
tris.AddRange(new[] { ringA + i, ringB + i, ringA + j, ringA + j, ringB + i, ringB + j });
|
||||
}
|
||||
}
|
||||
const int bodySides = 14, stations = 40;
|
||||
float length = s.Spine - 1 + 0.9f;
|
||||
int firstBody = verts.Count;
|
||||
for (int k = 0; k < stations; k++)
|
||||
{
|
||||
float z = -0.45f + length * k / (stations - 1), u = (z + 0.45f) / length;
|
||||
float r = 0.12f + 0.62f * Mathf.Pow(Mathf.Sin(Mathf.PI * Mathf.Clamp01(u * 0.95f + 0.02f)), 0.7f);
|
||||
int lo = Mathf.Clamp(Mathf.FloorToInt(z), 0, s.Spine - 1), hi = Mathf.Min(lo + 1, s.Spine - 1);
|
||||
float f = Mathf.Clamp01(z - lo);
|
||||
Ring(i => { float a = i * 2 * Mathf.PI / bodySides; var nrm = new Vector3(Mathf.Cos(a), Mathf.Sin(a), 0); return (new Vector3(nrm.x * r, nrm.y * r * 0.85f, z), nrm); },
|
||||
bodySides, new Vector4(1 - f, f, 0, 0), (uint)lo, (uint)hi, new Vector2(0.25f, 0.5f));
|
||||
if (k > 0) Join(firstBody + (k - 1) * bodySides, firstBody + k * bodySides, bodySides);
|
||||
}
|
||||
Fk(d, 0, NoSwim, default, quaternion.identity, 1, out var rest, out _);
|
||||
const int tubeSides = 5;
|
||||
for (int c = 0; c < d.ChainCount; c++)
|
||||
{
|
||||
var bones = d.ChainBones(c);
|
||||
int first = verts.Count;
|
||||
for (int k = 0; k < bones.Count; k++)
|
||||
{
|
||||
float r = 0.045f * (1 - 0.7f * k / (bones.Count - 1));
|
||||
var centre = (Vector3)rest[bones[k]];
|
||||
Ring(i => { float a = i * 2 * Mathf.PI / tubeSides; var nrm = new Vector3(Mathf.Cos(a), Mathf.Sin(a), 0); return (centre + nrm * r, nrm); },
|
||||
tubeSides, new Vector4(1, 0, 0, 0), (uint)bones[k], (uint)bones[k], new Vector2(0.75f, 0.5f));
|
||||
if (k > 0) Join(first + (k - 1) * tubeSides, first + k * tubeSides, tubeSides);
|
||||
}
|
||||
}
|
||||
return MakeMesh(verts, tris);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue