diff --git a/docs/batched-model-state.md b/docs/batched-model-state.md index fc7d62771..5211ea716 100644 --- a/docs/batched-model-state.md +++ b/docs/batched-model-state.md @@ -2,9 +2,15 @@ `Renderer.DrawModels` and the model portion of `RenderQueue` now flatten and group opaque submeshes by shared model, material and mesh. Limits remain 128 -objects and 4096 total meshes. The bounded sort uses 64 KiB of extra static -scratch and allocates nothing per frame. Global stable back-to-front -translucency remains a separate pass; it is not reordered by material. +objects and 4096 total meshes. Opaque and translucent submissions share one +64 KiB static table, growing from opposite ends within that combined mesh limit. +This replaces two separate 64 KiB tables and saves 65,536 bytes of native static +memory without allocating per frame. Global stable back-to-front translucency +remains a separate pass; it is not reordered by material. Equal-depth translucent +meshes retain input order, including batches at the 4096-mesh limit. +The saving applies to executables that link this model batching path; builds +using section garbage collection can already omit the table when they only use +ordinary meshes or individual model draws. Within one native batch, compatible repeated materials reuse GX depth/blend, alpha, TEV, sampler and texture-object state. Object/normal matrices, mirrored diff --git a/docs/memory-reduction-audit.md b/docs/memory-reduction-audit.md new file mode 100644 index 000000000..8fc34f687 --- /dev/null +++ b/docs/memory-reduction-audit.md @@ -0,0 +1,178 @@ +# Memory reduction audit + +Baseline: SDK 318, revision `4c8cd26`. Managed allocation measurements below use +the host .NET 8 CLR. They are distinct from native section sizes and from the +GameCube managed heap. The changes retain the existing public APIs. + +## Transform hierarchy caches + +Each transform previously allocated its TRS values (`float[10]`), local matrix +(`float[16]`), world matrix (`float[16]`), a child `List`, and that +list's empty backing array. Most batch transforms and root game objects never +use hierarchy storage. + +The world matrix and TRS values remain eager, and each transform retains its +own stable world array. A never-parented transform now builds TRS directly into +that world array. Its separate local matrix is reserved when it is first +parented, before changing the hierarchy. A child list with initial capacity +four is reserved only on the first attachment to a parent. Caches remain +available after detachment so repeated hierarchy updates do not allocate. + +Validation of cycles and complete subtree depth still precedes allocation and +link changes. The new parent's insertion finishes before removal from the old +parent, preserving the original graph if allocating those buffers fails. A root without a +local cache keeps its local matrix dirty even after computing world state, so +its first attachment recomputes current local TRS. Repeated changes and matrix +reads allocate no additional buffers. + +| Warmed CLR allocation workload | Before | After | Reduction | +| --- | ---: | ---: | ---: | +| 128 root transforms, including their owning reference array | 47,128 B | 28,696 B | 18,432 B | +| 128 children attached to one existing root, including owning array and parent list growth | 49,288 B | 42,152 B | 7,136 B | + +Each never-parented transform eliminates three allocations and 64 B of matrix +element payload. The host CLR reduction is 144 B per transform, including +object/array overhead. For Hypercube's 128 batch poses, this removes 8,192 B of +matrix payload and 384 allocation objects; the measured CLR constructor +reduction is 18,432 B. Parented leaves retain both matrix arrays but no longer +allocate their own empty child list and empty backing array. + +The PPC32 layout gives a different overhead reduction. From `dnd_managed.h`, +the managed object header is 8 B and the array header is 24 B. The allocator +rounds objects to eight-byte boundaries and prefixes each with a 16 B heap +block. The generated `List` instance has 16 B of fields after the +object header. Removing one 64 B matrix array (104 B including headers), one +empty list object (40 B), and its zero-length backing array (40 B) therefore +avoids **184 B per never-parented transform**, or **23,552 B for 128**. This is +a layout calculation, not a hardware heap measurement. It assumes fresh +allocations; already fragmented free blocks can consume different amounts. + +Reproduce the host measurements from the repository root: + +```sh +python3 scripts/measure_transform_allocations.py --revision 4c8cd26 +python3 scripts/measure_transform_allocations.py +dotnet run --project tests/TransformMemoryTests -c Release +``` + +The probe exports the selected source revision into a temporary project and +does not modify the checkout. Focused CLR tests cover first attachment, +detachment/edit/reattachment, propagation to descendants, rejected cycles and +depth overflow, stable distinct world caches, and allocation-free repeated +updates. `ModelSmoke/TransformChecks.cs` exercises the same critical hierarchy +transitions through AOT with production native math. The graphics CI domain +runs the CLR checks and the model acceptance script runs native/AOT checks, +including managed GC stress. + +## Further candidates and tradeoffs + +* **Material sampling options:** options are already lazy, but assigning an + explicit default sampler or UV transform still allocates `float[40]` (160 B + element payload). Hypercube intentionally preallocates these arrays before + batching to avoid frame allocations. Skipping default assignments alone + would move a future nondefault allocation into material registration or + updates. A shared default representation needs careful reset semantics + because the renderer's native sampler state is global. +* **Managed model overrides:** every `ModelInstance` owns 10-float node and + four-float color scratch arrays (56 B payload) even if no override is used. + Making them lazy saves unused storage but adds a first-override allocation. + The native color ABI requires exactly four floats, so sharing the 10-float + buffer requires an ABI change. Native override storage is already lazy. +* **Crossfade poses:** `DndInstance.other` reserves `40 * nodeCount` B even + when no crossfade is played. Laziness would defer allocation/budget failure + from instance creation to the first fade. It needs explicit rollback tests + for failed fade admission and animation state before implementation. +* **Render queue storage:** each queue entry is a separately allocated object; + default capacity is 512. Inline struct entries could remove those objects + and the reference array indirection, but all mutating paths and AOT reference + scanning must be verified. Changing the two bounded sort index arrays to + `ushort` would save `4 * capacity` B (2,048 B at default capacity), with + compiler signedness and maximum-capacity coverage required. +* **Bulk draw matrices:** replacing transforms with one shared mutable world + array is incompatible with `DrawMeshes` and `RenderQueue`, which borrow + multiple distinct matrices in one submission. A flat matrix submission API + could reduce object overhead while preserving that lifetime contract, but + requires separate API and renderer validation. +* **Streaming textures and native reads:** both texture images protect active + GPU readers during staging/publication. `Stage` retains its native source + until completion, and publication checks the destination fence. AssetStream + native reads already write directly into the destination; their 4 KiB bounce + buffers are temporary stack storage. Removing an image or the conservative + `NativeBuffer` release wait needs a new ownership contract, including callers + that expose raw addresses to GX. +* **Native alignment and shared scratch:** resource allocations may reserve up + to `alignment-1` extra bytes (usually 31 B, up to 4,095 B); a portable aligned + allocator and matching free/accounting path need validation before changing + this. Model overrides and ordinary mesh drawing also reserve separate + 768-vertex workspaces, a possible 27,648 B saving. Sharing them requires an + explicit executor/reentrancy contract; the larger immediate/glyph workspace + has different capacity requirements. + +Native persistent and scratch reductions are described below. Their presence +in an executable depends on the native linker retaining the relevant code; +they must not be added unconditionally to the managed savings above. + +## Native model batch submission scratch + +The existing 4,096-mesh batch limit applies to the total number of opaque and +alpha meshes. Previously, each pass reserved its own 4,096-entry table even +though both could not be full at the same time. A single table now grows opaque +entries from its front and alpha entries from its back. Opaque and alpha slices +are still sorted independently. Original sequence numbers preserve alpha order +for equal depths despite insertion from the back. + +`ModelSubmission` is 16 B, so replacing two tables with one saves **65,536 B of +static native storage** when `dnd_model_draw_models` is retained by the linker. +Production `model_graphics.o`, built with the recording fixture flags, changed +from 158,904 to 93,368 B of BSS. Its text changed from 16,296 to 16,307 B (+11 B) +on the host compiler. Those object-file figures are compiler-specific, and +linker section collection can omit this scratch entirely from an application +which only draws raw meshes. + +Recording tests verify every submitted mesh for 4,096 all-opaque, all-alpha and +mixed batches in both cached and uncached state modes. They also check stable +equal-depth order and rejection of a 4,097-mesh batch before any draw occurs. +No heap allocation was added to submissions. + +## Native model skin workspace + +Skin evaluation previously reserved space for 256 position matrices and 256 +normal matrices for each skinned model instance: `256 * 32 * sizeof(float)`, +or 32,768 B of payload. Model skins are immutable after loading and each has a +validated joint count from one to 256. Each new workspace allocation caches the +maximum joint count across the model's skins and reserves both palettes using +that count. Their separate matrix strides remain intact. + +| Maximum skin joint count | Previous workspace charge | New workspace charge | Workspace reduction | +| --- | ---: | ---: | ---: | +| 1 | 32,800 B | 160 B | 32,640 B | +| 2 | 32,800 B | 288 B | 32,512 B | +| 256 | 32,800 B | 32,800 B | 0 B | + +The native allocator charges a 32 B allocation header plus a rounded payload; +these sizes include that charge. The cached maximum adds four bytes to the +PPC instance structure (eight bytes after host pointer alignment), so a model +with two-joint skins saves **32,508 B net per instance on PPC**, or 32,504 B on +the host. A maximum-size skin retains its previous workspace size and adds +only the cached field. Instances without evaluated skins do not allocate a +workspace. + +The maximum is computed only when allocating workspace, avoiding a scan on +ordinary updates. +Native byte accounting, budgets and allocator alignment remain in use. The +workspace retains instance ownership and is freed by vertex dropping, model +unload and instance disposal. Dropping the workspace also clears its cached +stride; recreation derives a fresh bound from the resident model's validated +skins. + +`tests/model_skin_workspace_test.c` uses production allocation and animation +code. It verifies one-, two- and 256-joint skins, mixed one-/256-joint skins, +position and normal transforms under nonuniform scale, reuse without new +allocation, drop/recreation with changed valid skin counts, exact-budget +admission, and one-byte-under-budget failure cleanup. Run the complete native and AOT model acceptance with generated +fixtures: + +```sh +dotnet run --project tests/ModelAssetTests -c Release -- /tmp/dnd-model-fixtures +python3 scripts/ci_model_tests.py /tmp/dnd-model-fixtures +``` diff --git a/include/dnd_model_internal.h b/include/dnd_model_internal.h index 822cc334b..8979f974b 100644 --- a/include/dnd_model_internal.h +++ b/include/dnd_model_internal.h @@ -70,6 +70,7 @@ typedef struct { unsigned char *done; float **vertices; float *workspace; + unsigned palette_joints; unsigned *draw_order; float *draw_depth; } DndInstance; diff --git a/scripts/ci_model_tests.py b/scripts/ci_model_tests.py index 4fd6a17be..8206916df 100644 --- a/scripts/ci_model_tests.py +++ b/scripts/ci_model_tests.py @@ -24,10 +24,15 @@ def main(fixtures): work.mkdir(parents=True, exist_ok=True) cc = os.environ.get("CC", "cc") flags = ["-pthread", "-O1", "-g", "-std=c11", "-Wall", "-Wextra", "-Werror", "-Iinclude"] + dead_strip = "-Wl,-dead_strip" if sys.platform == "darwin" else "-Wl,--gc-sections" common = ["source/managed_runtime.c", "source/async_runtime.c"] model = sorted(str(p.relative_to(ROOT)) for p in (ROOT / "source").glob("model*.c")) runtime = common + ["source/storage.c", "source/contiguous_write.c", "source/file_optimize.c","source/verified_copy.c"] + model + [ "source/graphics_device.c", "source/draw_resources.c", "source/graphics_gx.c", "source/performance.c"] + skin = work / "model-skin-workspace" + run(cc, *flags, "-ffunction-sections", "-fdata-sections", "tests/model_skin_workspace_test.c", + "source/model.c", "source/model_animation.c", dead_strip, "-lm", "-o", skin) + run(skin) inflate = work / "model-inflate" run(cc, *flags, "tests/model_inflate_test.c", "source/model_ufbx.c", "-lm", "-o", inflate) run(inflate) @@ -50,7 +55,6 @@ def main(fixtures): "-c", source, "-o", obj) objects.append(obj) recording = work / "model-recording" - dead_strip = "-Wl,-dead_strip" if sys.platform == "darwin" else "-Wl,--gc-sections" run(cc, *flags, *objects, dead_strip, "-lm", "-o", recording) run(recording) diff --git a/scripts/ci_test_suite.py b/scripts/ci_test_suite.py index 5c7dce4f8..4bb9796be 100644 --- a/scripts/ci_test_suite.py +++ b/scripts/ci_test_suite.py @@ -159,6 +159,7 @@ def main(area): run("dotnet","run","--project","tests/ModelAssetTests","-c","Release","--",tmp) run("python3","scripts/ci_model_tests.py",tmp) test("tests/TevMaterialTests") + test("tests/TransformMemoryTests") for p in ("GraphicsSmoke","SystemFirmwareSmoke","IplFontSmoke","ModelSmoke","ModelAsyncSmoke"): build("tests/"+p+"/"+p+".csproj") elif area=="assets": diff --git a/scripts/measure_transform_allocations.py b/scripts/measure_transform_allocations.py new file mode 100644 index 000000000..795f6594c --- /dev/null +++ b/scripts/measure_transform_allocations.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +"""Measure warmed host CLR allocations for SDK transforms; not a PPC heap probe.""" +import argparse +from pathlib import Path +import shutil +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[1] +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument("--revision", help="Git source revision; omit for the working tree") +args = parser.parse_args() +sources = [ + "src/DolphinDotNet.GameCube/Dolphin/Graphics/Transform.cs", + "src/DolphinDotNet.GameCube/Dolphin/Graphics/Vector3.cs", + "src/DolphinDotNet.GameCube/Dolphin/Graphics/Quaternion.cs", + "src/DolphinDotNet.Core/Dolphin/Collections/List.cs", + "src/DolphinDotNet.Core/Dolphin/Collections/ReadOnlyCollection.cs", +] +with tempfile.TemporaryDirectory(prefix="dnd-transform-memory-") as temporary: + work = Path(temporary) + for source in sources: + content = subprocess.check_output(["git", "show", args.revision + ":" + source], cwd=ROOT) if args.revision else (ROOT / source).read_bytes() + (work / Path(source).name).write_bytes(content) + for name in ("Program.cs", "NativeModel.cs"): + shutil.copyfile(ROOT / "tests/TransformMemoryTests" / name, work / name) + (work / "Probe.csproj").write_text('Exenet8.0enable') + print("Source:", args.revision or "working tree", flush=True) + subprocess.run(["dotnet", "run", "--project", str(work / "Probe.csproj"), "-c", "Release", "--", "--measure-only"], check=True) diff --git a/source/model_animation.c b/source/model_animation.c index c0ccb592a..f5b921311 100644 --- a/source/model_animation.c +++ b/source/model_animation.c @@ -184,6 +184,7 @@ static void global(DndInstance *in, unsigned node) { void dnd_model_drop_vertices(DndInstance *in) { dnd_model_free(in->workspace, &in->bytes); in->workspace = NULL; + in->palette_joints = 0; if (in->vertices) for (unsigned i = 0; i < in->model->meshes; i++) { dnd_model_free(in->vertices[i], &in->bytes); @@ -234,12 +235,18 @@ int dnd_model_evaluate(DndInstance *in) { } DndSkin *skin = &m->skin[mesh->skin]; if (!in->workspace) { - in->workspace = dnd_model_alloc(256 * 32 * 4, &in->bytes, in->budget); + /* Validated skins have 1..256 joints. Cache their largest bound with this + * allocation, shared by both palette halves and every skinned mesh. */ + in->palette_joints = 0; + for (unsigned j = 0; j < m->skins; j++) + if ((unsigned)m->skin[j].count > in->palette_joints) + in->palette_joints = (unsigned)m->skin[j].count; + in->workspace = dnd_model_alloc(in->palette_joints * 32 * sizeof(float), &in->bytes, in->budget); if (!in->workspace) return -2; } float(*palette)[16] = (float(*)[16])in->workspace, - (*normal)[16] = (float(*)[16])(in->workspace + 256 * 16); + (*normal)[16] = (float(*)[16])(in->workspace + in->palette_joints * 16); for (int j = 0; j < skin->count; j++) { const unsigned char *joint = skin->data + (unsigned)j * 68; float bind[16]; diff --git a/source/model_graphics.c b/source/model_graphics.c index 91e84c874..2a60beb85 100644 --- a/source/model_graphics.c +++ b/source/model_graphics.c @@ -450,11 +450,15 @@ int dnd_model_draw_animated(int token,DndArray *transform,DndArray *channels) { * bounded and application-executor-owned; no model handles or pointers survive * this call. Opaque meshes from all instances precede the global alpha pass. */ typedef struct {unsigned object,mesh,sequence;float depth;} ModelSubmission; -static ModelSubmission alpha_submissions[4096],opaque_submissions[4096]; +#define MODEL_SUBMISSION_LIMIT 4096 +/* The total mesh bound applies to both passes together. Opaque submissions grow + * from the front, alpha from the back; neither scratch slice survives this call + * or is referenced by GX after a draw. */ +static ModelSubmission submissions[MODEL_SUBMISSION_LIMIT]; static bool submission_later(ModelSubmission a,ModelSubmission b){ return a.depth>b.depth||(a.depth==b.depth&&a.sequence>b.sequence); } -static void submission_sift(unsigned count,unsigned root){ +static void submission_sift(ModelSubmission *alpha_submissions,unsigned count,unsigned root){ for(;;){unsigned child=root*2+1;if(child>=count)return; if(child+1b.mesh; return a.sequence>b.sequence; } -static void opaque_sift(unsigned count,unsigned root,const int *ids){ +static void opaque_sift(ModelSubmission *opaque_submissions,unsigned count,unsigned root,const int *ids){ for(;;){unsigned child=root*2+1;if(child>=count)return; if(child+1model->ready)return -1; float *world=worlds+i*16;for(int k=0;k<16;k++)if(!isfinite(world[k]))return -1; - DndModel *model=in->model;if(model->meshes>4096-total)return -1;total+=model->meshes; + DndModel *model=in->model;if(model->meshes>MODEL_SUBMISSION_LIMIT-total)return -1;total+=model->meshes; for(unsigned j=0;jmeshes;j++){ DndMesh *mesh=&model->mesh[j];float object[16],mv[16],inverse[16]; if(mesh->skin<0)dnd_model_multiply(object,world,in->global+(unsigned)mesh->node*16); @@ -494,15 +498,18 @@ int dnd_model_draw_models(DndArray *tokens,DndArray *matrices,int count){ if(dnd_model_translucent(in,(unsigned)mesh->material)){ float depth=mv[2]*mesh->center[0]+mv[6]*mesh->center[1]+mv[10]*mesh->center[2]+mv[14]; if(!isfinite(depth))return -1; - alpha_submissions[alpha_count]=(ModelSubmission){(unsigned)i,j,alpha_count,depth};alpha_count++; - }else{opaque_submissions[opaque_count]=(ModelSubmission){(unsigned)i,j,opaque_count,0};opaque_count++;} + submissions[MODEL_SUBMISSION_LIMIT-1-alpha_count]=(ModelSubmission){(unsigned)i,j,alpha_count,depth};alpha_count++; + }else{submissions[opaque_count]=(ModelSubmission){(unsigned)i,j,opaque_count,0};opaque_count++;} } } - for(unsigned i=alpha_count/2;i>0;i--)submission_sift(alpha_count,i-1); - for(unsigned end=alpha_count;end>1;end--){ModelSubmission t=alpha_submissions[0];alpha_submissions[0]=alpha_submissions[end-1];alpha_submissions[end-1]=t;submission_sift(end-1,0);} + ModelSubmission *opaque_submissions=submissions,*alpha_submissions=submissions+MODEL_SUBMISSION_LIMIT-alpha_count; + /* Depth plus the original sequence restores stable alpha order, regardless + * of its backwards insertion into the shared scratch table. */ + for(unsigned i=alpha_count/2;i>0;i--)submission_sift(alpha_submissions,alpha_count,i-1); + for(unsigned end=alpha_count;end>1;end--){ModelSubmission t=alpha_submissions[0];alpha_submissions[0]=alpha_submissions[end-1];alpha_submissions[end-1]=t;submission_sift(alpha_submissions,end-1,0);} if(model_state_cache_enabled){ - for(unsigned i=opaque_count/2;i>0;i--)opaque_sift(opaque_count,i-1,ids); - for(unsigned end=opaque_count;end>1;end--){ModelSubmission t=opaque_submissions[0];opaque_submissions[0]=opaque_submissions[end-1];opaque_submissions[end-1]=t;opaque_sift(end-1,0,ids);} + for(unsigned i=opaque_count/2;i>0;i--)opaque_sift(opaque_submissions,opaque_count,i-1,ids); + for(unsigned end=opaque_count;end>1;end--){ModelSubmission t=opaque_submissions[0];opaque_submissions[0]=opaque_submissions[end-1];opaque_submissions[end-1]=t;opaque_sift(opaque_submissions,end-1,0,ids);} model_batch_active=true;model_batch_light_ready=model_batch_vertex_ready=false; #if defined(DND_GAMECUBE_STORAGE) || defined(DND_MODEL_GX_TEST) batch_model=NULL;batch_material=NULL; diff --git a/src/DolphinDotNet.GameCube/Dolphin/Graphics/Transform.cs b/src/DolphinDotNet.GameCube/Dolphin/Graphics/Transform.cs index 423f44be5..8eaed9c46 100644 --- a/src/DolphinDotNet.GameCube/Dolphin/Graphics/Transform.cs +++ b/src/DolphinDotNet.GameCube/Dolphin/Graphics/Transform.cs @@ -9,9 +9,11 @@ public sealed class Transform private const int MaximumHierarchyDepth = 128; // Native TRS layout: position XYZ, quaternion XYZW, scale XYZ. private readonly float[] values = new float[10]; - private readonly float[] local = new float[16]; + // Root transforms can build directly into world. Reserve a distinct local + // cache only when first attached, before changing the hierarchy. + private float[]? local; private readonly float[] world = new float[16]; - private readonly List children = new List(); + private List? children; private Transform? parent; private bool localDirty = true; private bool worldDirty = true; @@ -96,8 +98,13 @@ public Transform? Parent } // Validate the complete subtree before changing either parent's child list. ValidateDepth(depth); - if (value != null) value.children.Add(this); - if (parent != null) parent.children.Remove(this); + if (value != null) + { + if (local == null) local = new float[16]; + if (value.children == null) value.children = new List(4); + value.children.Add(this); + } + if (parent != null) parent.children!.Remove(this); parent = value; DirtyWorld(); } @@ -112,7 +119,8 @@ private static void CheckDepth(int depth) private void ValidateDepth(int depth) { CheckDepth(depth); - for (int i = 0; i < children.Count; i++) children[i].ValidateDepth(depth + 1); + if (children != null) + for (int i = 0; i < children.Count; i++) children[i].ValidateDepth(depth + 1); } private void Changed() @@ -126,7 +134,8 @@ private void DirtyWorld() // A dirty node's descendants are already dirty. Stop repeated subtree walks. if (worldDirty) return; worldDirty = true; - for (int i = 0; i < children.Count; i++) children[i].DirtyWorld(); + if (children != null) + for (int i = 0; i < children.Count; i++) children[i].DirtyWorld(); } public void Translate(Vector3 offset, bool worldSpace = false) @@ -152,6 +161,15 @@ internal float[] WorldMatrix get { if (!worldDirty) return world; + if (local == null) + { + if (NativeModel.ModelTrs(values, world) < 0) + throw new ArgumentException("Transform must be finite, with nonzero quaternion and scale."); + // Keep local dirty until a separate local cache is populated. + // Attaching a root must not reuse a world matrix as local TRS. + worldDirty = false; + return world; + } if (localDirty) { if (NativeModel.ModelTrs(values, local) < 0) diff --git a/tests/ModelSmoke/TransformChecks.cs b/tests/ModelSmoke/TransformChecks.cs index c53b04b9e..ed051361d 100644 --- a/tests/ModelSmoke/TransformChecks.cs +++ b/tests/ModelSmoke/TransformChecks.cs @@ -70,6 +70,28 @@ public static void Run() catch (ArgumentException) { } Check(child.Parent == null && leaf.Parent == child, "Rejected subtree move preserves links."); + // A root draws directly into its world cache until it is first attached. + // Detaching, editing and reattaching must still use current local TRS. + var moving = new Transform(); + moving.LocalPosition = new Vector3(2, 0, 0); + moving.CopyWorldMatrix(matrix); + Check(matrix[12] == 2, "Root placement before first attachment."); + var firstParent = new Transform(); + firstParent.LocalPosition = new Vector3(10, 0, 0); + moving.Parent = firstParent; + moving.CopyWorldMatrix(matrix); + Check(matrix[12] == 12, "Root matrix is not reused as stale local TRS."); + moving.Parent = null; + moving.LocalPosition = new Vector3(4, 0, 0); + moving.CopyWorldMatrix(matrix); + Check(matrix[12] == 4, "Detached root edit updates its local cache."); + moving.Parent = firstParent; + moving.CopyWorldMatrix(matrix); + Check(matrix[12] == 14, "Reattaching uses edited local placement."); + firstParent.LocalPosition = new Vector3(20, 0, 0); + moving.CopyWorldMatrix(matrix); + Check(matrix[12] == 24, "First lazy child list propagates invalidation."); + root.LocalRotation = new Quaternion(0, 0, 0, 0); try { root.CopyWorldMatrix(matrix); throw new InvalidOperationException("Zero quaternion accepted."); } catch (ArgumentException) { } diff --git a/tests/TransformMemoryTests/NativeModel.cs b/tests/TransformMemoryTests/NativeModel.cs new file mode 100644 index 000000000..48755ff10 --- /dev/null +++ b/tests/TransformMemoryTests/NativeModel.cs @@ -0,0 +1,31 @@ +// CLR-only matrix backend. The AOT ModelSmoke suite separately verifies the +// same hierarchy transitions against the production native matrix functions. +using System; +using System.Numerics; +namespace Dolphin.Graphics; +internal static class NativeModel +{ + internal static int ModelTrs(float[] values,float[] matrix) + { + for(int i=0;i<10;i++)if(!float.IsFinite(values[i]))return -1; + var q=new System.Numerics.Quaternion(values[3],values[4],values[5],values[6]); + if(q.LengthSquared()==0||values[7]==0||values[8]==0||values[9]==0)return -1; + Write(Matrix4x4.CreateScale(values[7],values[8],values[9])* + Matrix4x4.CreateFromQuaternion(System.Numerics.Quaternion.Normalize(q))* + Matrix4x4.CreateTranslation(values[0],values[1],values[2]),matrix); + return 0; + } + internal static int ModelMultiply(float[] a,float[] b,float[] output) + {Write(Read(b)*Read(a),output);return 0;} + private static Matrix4x4 Read(float[] a)=>new Matrix4x4(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],a[10],a[11],a[12],a[13],a[14],a[15]); + private static void Write(Matrix4x4 a,float[] b) + { + b[0]=a.M11;b[1]=a.M12;b[2]=a.M13;b[3]=a.M14; + b[4]=a.M21;b[5]=a.M22;b[6]=a.M23;b[7]=a.M24; + b[8]=a.M31;b[9]=a.M32;b[10]=a.M33;b[11]=a.M34; + b[12]=a.M41;b[13]=a.M42;b[14]=a.M43;b[15]=a.M44; + } + internal static int ModelPosition(float[] a,float[] b,float x,float y,float z)=>throw new NotSupportedException(); + internal static int ModelTranslate(float[] a,float x,float y,float z)=>throw new NotSupportedException(); + internal static int ModelRotate(float[] a,float x,float y,float z)=>throw new NotSupportedException(); +} diff --git a/tests/TransformMemoryTests/Program.cs b/tests/TransformMemoryTests/Program.cs new file mode 100644 index 000000000..db2ea6544 --- /dev/null +++ b/tests/TransformMemoryTests/Program.cs @@ -0,0 +1,75 @@ +using System; +using System.Reflection; +using Dolphin.Graphics; + +static class Program +{ + private static void Check(bool value,string message) + {if(!value)throw new InvalidOperationException(message);} + private static object? Storage(Transform transform,string field) + =>typeof(Transform).GetField(field,BindingFlags.NonPublic|BindingFlags.Instance)!.GetValue(transform); + private static void At(Transform transform,float x) + {Check(Math.Abs(transform.WorldMatrix[12]-x)<.001f,"Unexpected world placement.");} + public static void Main(string[] args) + { + // Warm JIT and static initialization outside the measurements. + MeasureRoots();MeasureChildren(); + long roots=MeasureRoots(),children=MeasureChildren(); + Console.WriteLine("CLR allocations: 128 roots="+roots+" B; 128 children of one existing root="+children+" B"); + if(args.Length!=0&&args[0]=="--measure-only")return; + + var root=new Transform();var other=new Transform();var leaf=new Transform(); + var stable=leaf.WorldMatrix; + Check(Storage(root,"local")==null&&Storage(root,"children")==null,"Unused hierarchy storage must stay absent."); + leaf.LocalPosition=new Vector3(2,0,0);At(leaf,2); + Check(Storage(leaf,"local")==null,"Drawing an unparented transform must not allocate a local cache."); + root.LocalPosition=new Vector3(10,0,0);leaf.Parent=root;At(leaf,12); + Check(Storage(root,"children")!=null&&Storage(leaf,"children")==null,"Only parents reserve a child list."); + object local=Storage(leaf,"local")!; + leaf.Parent=null;leaf.LocalPosition=new Vector3(4,0,0);At(leaf,4); + other.LocalPosition=new Vector3(20,0,0);leaf.Parent=other;At(leaf,24); + Check(ReferenceEquals(local,Storage(leaf,"local")),"Reattachment must retain its local cache."); + Check(ReferenceEquals(stable,leaf.WorldMatrix),"The world cache must remain stable across parenting changes."); + Check(!ReferenceEquals(root.WorldMatrix,leaf.WorldMatrix),"Batch transforms must have distinct world caches."); + other.LocalPosition=new Vector3(30,0,0);At(leaf,34); + root.LocalPosition=new Vector3(100,0,0);At(leaf,34); + + // Rejected hierarchy changes must leave the old graph and clean caches usable. + var grandchild=new Transform{Parent=leaf};At(grandchild,34); + try{other.Parent=grandchild;throw new InvalidOperationException("Cycle accepted.");}catch(ArgumentException){} + Check(other.Parent==null&&leaf.Parent==other&&grandchild.Parent==leaf,"Rejected cycle changed links."); + other.LocalPosition=new Vector3(40,0,0);At(grandchild,44); + var deepest=new Transform(); + for(int i=1;i<128;i++)deepest=new Transform{Parent=deepest}; + try{leaf.Parent=deepest;throw new InvalidOperationException("Excess depth accepted.");}catch(ArgumentException){} + Check(leaf.Parent==other,"Rejected depth changed the old parent.");At(grandchild,44); + var rejected=new Transform(); + try{rejected.Parent=deepest;throw new InvalidOperationException("Excess depth accepted.");}catch(ArgumentException){} + Check(Storage(rejected,"local")==null,"Validation must precede hierarchy allocations."); + + var destination=new float[16]; + Update(root,leaf,grandchild,destination,1); + long before=GC.GetAllocatedBytesForCurrentThread(); + for(int i=0;i<10000;i++)Update(root,leaf,grandchild,destination,i); + Check(GC.GetAllocatedBytesForCurrentThread()==before,"Repeated transform updates and matrix copies allocated."); + Check(ReferenceEquals(stable,leaf.WorldMatrix),"Repeated updates replaced the world cache."); + Console.WriteLine("Transform lazy storage, hierarchy transitions and allocation checks passed."); + } + private static void Update(Transform root,Transform leaf,Transform child,float[] destination,int tick) + { + root.LocalPosition=new Vector3(tick,0,0);root.CopyWorldMatrix(destination); + leaf.LocalPosition=new Vector3(tick,0,0);child.CopyWorldMatrix(destination); + } + private static long MeasureRoots() + { + long before=GC.GetAllocatedBytesForCurrentThread();var transforms=new Transform[128]; + for(int i=0;i + Exenet8.0enable + + + + + + + + diff --git a/tests/model_effect_test.c b/tests/model_effect_test.c index 54c3606b4..361ad5b5e 100644 --- a/tests/model_effect_test.c +++ b/tests/model_effect_test.c @@ -47,6 +47,7 @@ typedef struct { float position[9],uv[6],world_x; GXColor vertex[3]; } Draw; static Draw state,record[16];static int draws,restores,position_index,color_index,uv_index,texture_loads,light_loads,vertex_invalidations; +static int boundary_mode,boundary_draws;static bool boundary_cached; void GX_SetTevIndWarp(int stage,int indstage,int signed_offset,int replace,int matrix){ assert(active_indirect==1&&indstage==0&&signed_offset==GX_TRUE&&!replace&&matrix==GX_ITM_0); state.stages[stage].direct=2; @@ -109,7 +110,18 @@ void GX_Begin(int p,int f,u16 n){assert(p==GX_TRIANGLES&&f==0&&n==3&&state.count void GX_Position3f32(float x,float y,float z){assert(position_index<9);state.position[position_index++]=x;state.position[position_index++]=y;state.position[position_index++]=z;} void GX_Color4u8(u8 r,u8 g,u8 b,u8 a){assert(color_index<3);state.vertex[color_index++]=(GXColor){r,g,b,a};} void GX_TexCoord2f32(float u,float v){assert(uv_index<6);state.uv[uv_index++]=u;state.uv[uv_index++]=v;} -void GX_End(void){assert(position_index==9&&color_index==3&&uv_index==6);record[draws++%16]=state;} +void GX_End(void){assert(position_index==9&&color_index==3&&uv_index==6); + if(boundary_mode){ + unsigned at=(unsigned)boundary_draws++,object,mesh;bool alpha=boundary_mode==2||(boundary_mode==3&&at>=2048); + if(boundary_mode==2){object=at/32;mesh=at%32;} + else if(boundary_mode==3&&alpha){at-=2048;object=at/16;mesh=(at%16)*2+1;} + else if(boundary_cached){object=at%128;mesh=at/128;mesh=boundary_mode==3?mesh*2:mesh<16?mesh*2:(mesh-16)*2+1;} + else{unsigned per_object=boundary_mode==3?16:32;object=at/per_object;mesh=(at%per_object)*(boundary_mode==3?2:1);} + assert(state.world_x==(float)(object*100+mesh)); + assert(state.blend==(alpha?GX_BM_BLEND:GX_BM_NONE)); + } + record[draws++%16]=state; +} void dnd_draw_set_camera(const float *v,const float *p){(void)v;(void)p;} void dnd_draw_backend_vertices(const DndDrawVertex *v,int n,int p,const DndDrawTexture *t,const DndDrawMaterial *m,const float *w){assert(n==3&&p==0x90&&t&&m->secondary&&m->flags==65&&m->color==0x12345678&&w[0]==-1);assert(v[0].nz==-1&&v[0].color==0xcc99667f);if(v[0].x==10)full_skin++;full_draws++;} void dnd_draw_backend_camera(const float *v,const float *p){(void)v;(void)p;} @@ -190,6 +202,46 @@ static void assert_geometry_equal(Draw a,Draw b) { memset(a.konst,0,sizeof(a.konst));memset(b.konst,0,sizeof(b.konst)); assert_draw_equal(a,b); } +/* Both scratch slices must fit at their shared 4096-mesh bound, preserve the + * full stable alpha order, and keep all opaque draws ahead of alpha. Record + * every production GX draw rather than relying on the 16-entry history ring. */ +static void submission_boundaries(DndArray *camera,const unsigned char *data,const unsigned char *indices,DndTexture *texture){ + DndInstance *saved[DND_INSTANCE_SLOTS];memcpy(saved,dnd_instances,sizeof(saved)); + DndInstance *instances=calloc(128,sizeof(*instances));assert(instances); + DndArray *ids=calloc(1,sizeof(*ids)+128*4),*worlds=calloc(1,sizeof(*worlds)+128*64);assert(ids&&worlds); + ids->element_size=worlds->element_size=4;ids->length=128;worlds->length=128*16; + DndMesh meshes[33]={0};float globals[32*16]; + DndMaterial materials[2]={ + {.color={1,1,1,1},.texture=0,.mode=2}, + {.color={1,1,1,1},.texture=0,.mode=2} + }; + for(unsigned j=0;j<32;j++){ + dnd_model_identity(globals+j*16);globals[j*16+12]=(float)j; + meshes[j]=(DndMesh){.node=(int)j,.skin=-1,.material=(int)(j%2),.vertices=3,.indices=3,.data=data,.index=indices}; + } + meshes[32]=meshes[0]; + DndModel model={.ready=true,.nodes=32,.meshes=32,.materials=2,.textures=1,.mesh=meshes,.material=materials,.texture=texture}; + DndModel oversized=model;oversized.meshes=33; + for(unsigned i=0;i<128;i++){ + instances[i]=(DndInstance){.token=1000+(int)i,.model=&model,.global=globals};dnd_instances[i]=&instances[i]; + ((int*)ids->data)[i]=instances[i].token; + float *world=(float*)worlds->data+i*16;dnd_model_identity(world);world[12]=(float)(i*100); + } + for(int cached=0;cached<=1;cached++){ + assert(dnd_model_state_cache(cached)==cached&&dnd_model_frame_begin(camera,camera)==0); + for(int mode=1;mode<=3;mode++){ + materials[0].mode=2|(mode==2?4:0);materials[1].mode=2|(mode>=2?4:0); + boundary_cached=cached!=0;boundary_draws=0;boundary_mode=mode;size_t before_allocations=allocations;int before=draws; + assert(dnd_model_draw_models(ids,worlds,128)==0&&draws==before+4096&&boundary_draws==4096&&allocations==before_allocations); + boundary_mode=0; + } + instances[127].model=&oversized;int before=draws;uint32_t triangles=dnd_performance_stats()->triangles; + assert(dnd_model_draw_models(ids,worlds,128)<0&&draws==before&&dnd_performance_stats()->triangles==triangles); + instances[127].model=&model; + assert(dnd_model_frame_end()==0); + } + assert(dnd_model_state_cache(1)==1);memcpy(dnd_instances,saved,sizeof(saved));free(instances);free(ids);free(worlds); +} int main(void) { assert(dnd_model_indexed_path(-1)==1&&dnd_model_indexed_path(0)==0&&dnd_model_indexed_path(1)==1&&dnd_model_indexed_path(2)<0); DndDrawEffect dual={.count=3,.texture=3,.stages={{15,15,15,10,0,0,0,0},{15,15,15,8,0,0,0,1},{15,15,15,0,0,0,0,0}}}; @@ -425,6 +477,7 @@ int main(void) { assert(texture_loads-original_loads==5&&dnd_performance_stats()->texture_binds-old_bindings==5); assert(dnd_performance_stats()->drawing_api_calls-old_api==1&&dnd_performance_stats()->material_changes-old_changes==3); assert(dnd_model_frame_end()==0);free(batch_ids);free(batch_worlds);memcpy(materials,original_materials,sizeof(materials)); + submission_boundaries(camera,data,indices,&texture); assert(dnd_draw_release(dual_alpha_effect)==0&&dnd_draw_release(alpha_effect)==0&&dnd_draw_release(short_effect)==0&&dnd_draw_release(textured)==0&&dnd_draw_release(replacement)==0&&dnd_draw_release(wrong)==0); assert(dnd_draw_total_bytes()==0&&dnd_draw_live()==0); assert(indirect_resets>=restores); diff --git a/tests/model_skin_workspace_test.c b/tests/model_skin_workspace_test.c new file mode 100644 index 000000000..dc7906993 --- /dev/null +++ b/tests/model_skin_workspace_test.c @@ -0,0 +1,104 @@ +/* Exercise production palette allocation, skin math, budgeting and unload-style + * cleanup without a desktop asset converter or GX backend. */ +#include "dnd_model_internal.h" +#include "dnd_draw.h" +#include "dnd_storage.h" +#include +#include +#include +#include +#include + +bool dnd_device_active(void){return false;} +void dnd_fs_close(int token){(void)token;assert(!"Fixture does not own a storage handle.");} + +static void put(unsigned char *p, unsigned value) { + for (unsigned i = 0; i < 4; i++)p[i]=(unsigned char)(value >> (24-i*8)); +} +static void put_float(unsigned char *p, float value) { + unsigned bits;memcpy(&bits,&value,sizeof(bits));put(p,bits); +} +static void near(float actual,float expected){assert(fabsf(actual-expected)<.0001f);} +static unsigned charged(unsigned payload){return (payload+63u)&~31u;} +static unsigned allocation_bytes(const void *p){return ((const unsigned *)p)[-8];} + +static void check_workspace(unsigned first_joints,unsigned second_joints){ + unsigned largest=second_joints>first_joints?second_joints:first_joints; + unsigned mesh_count=second_joints?2:1; + DndNode *nodes=calloc(largest,sizeof(*nodes));assert(nodes); + DndSkin skins[2]={{0}};DndMesh meshes[2]={{0}}; + unsigned char *joint_data[2]={NULL,NULL};unsigned char vertices[2][80]={{0}}; + for(unsigned i=0;iworkspace&&in->palette_joints==largest); + unsigned workspace_bytes=charged(largest*32*sizeof(float)); + assert(allocation_bytes(in->workspace)==workspace_bytes); + unsigned before=in->bytes;float *workspace=in->workspace; + for(unsigned i=0;iworkspace==workspace&&in->bytes==before); + dnd_model_drop_vertices(in); + assert(!in->workspace&&!in->palette_joints&&in->bytes==before-workspace_bytes-mesh_count*charged(6*sizeof(float))); + for(unsigned i=0;ivertices[i]); + assert(dnd_model_evaluate(in)==0&&in->bytes==before&&allocation_bytes(in->workspace)==workspace_bytes); + if(largest==256){ + /* A newly validated package can have a different largest palette. Fresh + * workspace ownership must recalculate its bound after dropping the old. */ + unsigned changed=mesh_count-1;dnd_model_drop_vertices(in);skins[changed].count=2; + for(unsigned j=0;j<4;j++)put(vertices[changed]+48+j*4,1); + assert(dnd_model_evaluate(in)==0&&in->palette_joints==2); + assert(allocation_bytes(in->workspace)==charged(2*32*sizeof(float))); + assert(in->bytes==before-workspace_bytes+charged(2*32*sizeof(float))); + float value[6];assert(dnd_model_vertex(token,(int)changed,0,value)==0);near(value[0],4); + dnd_model_drop_vertices(in);skins[changed].count=256; + for(unsigned j=0;j<4;j++)put(vertices[changed]+48+j*4,255); + assert(dnd_model_evaluate(in)==0&&in->palette_joints==256&&in->bytes==before); + } + assert(dnd_model_instance_dispose(token)==0&&model.refs==1); + if(before>1024){ + token=dnd_model_instance(model.token,(int)before);assert(token); + assert(dnd_model_instance_bytes(token)==(int)before); + assert(dnd_model_instance_dispose(token)==0); + assert(!dnd_model_instance(model.token,(int)before-1)&&model.refs==1); + for(unsigned i=0;i