Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ on:
push:
branches: [main]
pull_request:
branches: [main, feat/streamable-texture-assets, feature/model-import-compatibility-phase1, codex/asset-throughput, codex/texture-stage-timings, feature/iso-defrag-planning-and-evacuation]
branches: [main, feat/streamable-texture-assets, feat/detached-texture-upload, feature/model-import-compatibility-phase1, codex/asset-throughput, codex/texture-stage-timings, feature/iso-defrag-planning-and-evacuation]
workflow_dispatch:

permissions:
Expand Down
38 changes: 38 additions & 0 deletions docs/streamable-models.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Streamable model materials

`dnd-assets model input.glb output.dndmodel --streamable-textures`
exports a normal DNDM geometry/animation package with **zero embedded images**,
independent DNLT assets, and `output.dndmodel.textures.json`. The default importer
continues to embed its textures. glTF/GLB and Assimp-converted inputs support this
mode; direct PSO GJ/XJ imports reject it explicitly.

Use `--streamable-format auto|rgba8|cmpr` and `--mip-levels` as appropriate
(see CLI help). Auto preserves smooth alpha with RGBA8. Full independent ladders
support up to eleven levels; a level cap authors a partial ladder. Geometry,
skin weights, node transforms, animations and source UVs retain their existing
conversion. Authored glTF UV transforms are baked once by the model importer;
consumers apply only the selected DNLT level's UV transform afterward.

The version 1 JSON sidecar contains the model filename and SHA256, texture
indices with content-addressed family names, relative DNLT paths and SHA256,
logical dimensions, native wrap modes (0 clamp, 1 repeat, 2 mirror) and linear
filtering. Materials retain stable imported IDs (0 default, source index + 1),
primary/secondary image indices (-1 absent), GX combiner (0 none, 1 multiply,
2 add), normalized RGBA, alpha mode bits (1 mask, 2 unlit, 4 blend), cutoff and
double-sided state. Identical texture bytes share the same family hash, while
sampler settings remain material state. Existing GX material compilation also
exports its generated secondary images.

`Renderer.DrawModelMaterialPart(instance, materialIndex, transform, material)`
draws only primitives belonging to that imported material, including their
current skinning and node animation. It borrows the supplied material and
textures. Resolve/pin them immediately before submission and keep them alive
through the final GPU fence. The source `Model` owner may be disposed while its
instance remains alive. The native call validates the material index and
performs no resource allocation. Submit opaque parts first and sort transparent
parts through the application's draw queue; primitive sorting within a part
does not sort transparency across separate calls.

Hypercube's sidecar packer generates material factories, so no JSON parser or
image decoding is needed on the console. The renderer API also permits other
engines to perform equivalent wiring.
1 change: 1 addition & 0 deletions include/dnd_model.h
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ int dnd_model_state_cache(int enabled);
int dnd_model_draw_animated(int token, DndArray *transform, DndArray *channels);
int dnd_model_draw_animated_shapes(int token,DndArray *transform,DndArray *channels,DndArray *mesh_visibility);
int dnd_model_draw_material(int token,DndArray *transform,int texture,int secondary,uint32_t color,int flags,float cutoff,int effect);
int dnd_model_draw_material_part(int token,DndArray *transform,int material,int texture,int secondary,uint32_t color,int flags,float cutoff,int effect);
int dnd_model_frame_begin(DndArray *view, DndArray *projection);
int dnd_model_frame_end(void);
/* Reference-output inspection for tests and profiling, not managed heap
Expand Down
17 changes: 12 additions & 5 deletions source/model_graphics.c
Original file line number Diff line number Diff line change
Expand Up @@ -144,12 +144,12 @@ int dnd_model_draw(int token, DndArray *transform) {
/* Full override submission shares the managed mesh backend, so lighting,
* coordinates, samplers, opacity and render state cannot diverge. Bounded
* application-executor scratch storage; never allocate or mutate model assets. */
int dnd_model_draw_material(int token,DndArray *transform,int tex,int secondary,
uint32_t color,int flags,float cutoff,int effect_token) {
static int draw_material_part(int token,DndArray *transform,int tex,int secondary,
uint32_t color,int flags,float cutoff,int effect_token,int material_index) {
dnd_performance_drawing_api();
DndInstance *in=dnd_instance_find(token);float world[16];DndDrawTexture base,extra;
const DndDrawEffect *effect;
if(!in||!in->model->ready||!dnd_model_frame_active||!matrix_array(transform,world)||
if(!in||!in->model->ready||(material_index>=0&&(unsigned)material_index>=in->model->materials)||!dnd_model_frame_active||!matrix_array(transform,world)||
flags<0||flags>255||(flags&192)==192||!isfinite(cutoff)||cutoff<0||cutoff>1||
dnd_texture_resolve(tex,&base)<0||dnd_texture_resolve(secondary,&extra)<0||
dnd_effect_resolve(effect_token,&effect)<0)return -1;
Expand All @@ -158,7 +158,7 @@ int dnd_model_draw_material(int token,DndArray *transform,int tex,int secondary,
DndModel *model=in->model;
/* Validate every submitted transform/skinned buffer before sorting or GX. */
for(unsigned i=0;i<model->meshes;i++){
DndMesh *mesh=&model->mesh[i];float object[16],mv[16],inverse[16];
DndMesh *mesh=&model->mesh[i];if(material_index>=0&&mesh->material!=material_index)continue;float object[16],mv[16],inverse[16];
if(mesh->skin<0)dnd_model_multiply(object,world,in->global+(unsigned)mesh->node*16);
else {if(!in->vertices[i])return -1;memcpy(object,world,64);}
dnd_model_multiply(mv,frame_view,object);if(!dnd_model_inverse(inverse,mv))return -1;
Expand All @@ -167,7 +167,7 @@ int dnd_model_draw_material(int token,DndArray *transform,int tex,int secondary,
static DndDrawVertex vertices[768];
DndDrawMaterial material={color,flags,cutoff,effect,secondary?&extra:NULL};
for(unsigned draw=0;draw<model->meshes;draw++){
unsigned mi=in->draw_order?in->draw_order[draw]:draw;DndMesh *mesh=&model->mesh[mi];float object[16];
unsigned mi=in->draw_order?in->draw_order[draw]:draw;DndMesh *mesh=&model->mesh[mi];if(material_index>=0&&mesh->material!=material_index)continue;float object[16];
if(mesh->skin<0)dnd_model_multiply(object,world,in->global+(unsigned)mesh->node*16);else memcpy(object,world,64);
for(unsigned first=0;first<mesh->indices;){
unsigned count=mesh->indices-first;if(count>768)count=768;
Expand All @@ -186,6 +186,13 @@ int dnd_model_draw_material(int token,DndArray *transform,int tex,int secondary,
}
return 0;
}
int dnd_model_draw_material(int token,DndArray *transform,int tex,int secondary,uint32_t color,int flags,float cutoff,int effect) {
return draw_material_part(token,transform,tex,secondary,color,flags,cutoff,effect,-1);
}
int dnd_model_draw_material_part(int token,DndArray *transform,int material_index,int tex,int secondary,uint32_t color,int flags,float cutoff,int effect) {
if(material_index<0)return -1;
return draw_material_part(token,transform,tex,secondary,color,flags,cutoff,effect,material_index);
}
static int draw_model_selected(DndInstance *in,const float world[16],const DndDrawEffect *effect,int filter,int only);
int dnd_model_draw_effect(int token, DndArray *transform, int effect_token) {
dnd_performance_drawing_api();
Expand Down
1 change: 1 addition & 0 deletions src/DolphinDotNet.GameCube/Dolphin/Graphics/NativeModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ internal static class NativeModel
internal static int ModelDrawAnimated(int token,float[] world,float[] channels)=>throw Unsupported();
internal static int ModelDrawAnimatedShapes(int token,float[] world,float[] channels,float[] visibility)=>throw Unsupported();
internal static int ModelDrawMaterial(int token,float[] matrix,int texture,int secondary,uint color,int flags,float cutoff,int effect)=>throw Unsupported();
internal static int ModelDrawMaterialPart(int token,float[] matrix,int material,int texture,int secondary,uint color,int flags,float cutoff,int effect)=>throw Unsupported();
internal static int ModelFrameBegin(float[] view,float[] projection)=>throw Unsupported();
internal static int ModelFrameEnd()=>throw Unsupported();
}
11 changes: 11 additions & 0 deletions src/DolphinDotNet.GameCube/Dolphin/Graphics/Renderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,17 @@ public void DrawWithMaterial(GameObject gameObject,Material material)
if(gameObject==null)throw new ArgumentNullException("gameObject");
gameObject.Check();if(gameObject.Model!=null)DrawModelWithMaterial(gameObject.Model,gameObject.Transform,material);
}
/// <summary>Draw only primitives using an imported material index, with an
/// explicit replacement material. Geometry, skinning and UV0 stay authored.
/// Resolve/pin borrowed textures immediately before calling. Submit opaque
/// parts first and order transparent parts through the application queue.</summary>
public void DrawModelMaterialPart(ModelInstance instance,int materialIndex,Transform transform,Material material)
{
if(instance==null||transform==null||material==null)throw new ArgumentNullException();
instance.Check();if(materialIndex<0)throw new ArgumentOutOfRangeException("materialIndex");
material.Check();ApplyMaterial(material);
GraphicsDevice.Check(NativeModel.ModelDrawMaterialPart(instance.Token,transform.WorldMatrix,materialIndex,material.TextureToken,material.SecondaryTextureToken,material.Color.Packed,material.Flags,material.AlphaCutoff,material.EffectToken),"Invalid model material part, cold model or 3D pass.");
}
public void DrawPrimitives(VertexPositionColor[] vertices,int offset,int vertexCount,PrimitiveType primitive,Transform transform)
{
if(vertices==null)throw new ArgumentNullException("vertices");if(transform==null)throw new ArgumentNullException("transform");
Expand Down
1 change: 1 addition & 0 deletions tests/ModelAssetTests/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ int Attribute(float[] values,string type,int components)
}
MaterialBakingTests.Run(root,output);
GxMaterialTests.Run(root,output);
StreamableModelTests.Run(root,output);
StudioBakeTests.Run(root,output);
// External buffers and images, plus GLB binary geometry.
root["buffers"]![0]!["uri"]="geometry.bin";root["images"]![0]!["uri"]="texture.png";File.WriteAllBytes(Path.Combine(output,"geometry.bin"),binary.ToArray());File.WriteAllBytes(Path.Combine(output,"texture.png"),png.ToArray());File.WriteAllText(gltf,root.ToJsonString());ModelConverter.Convert(gltf,package+".external");if(!bytes.SequenceEqual(File.ReadAllBytes(package+".external")))throw new Exception("External dependencies differ.");
Expand Down
58 changes: 58 additions & 0 deletions tests/ModelAssetTests/StreamableModelTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
using System.Buffers.Binary;
using System.Text.Json;
using System.Text.Json.Nodes;
using Dolphin.Formats;
using DolphinDotNet.Assets;
using DolphinDotNet.Imaging;

internal static class StreamableModelTests
{
private static int I(byte[] b,int at)=>BinaryPrimitives.ReadInt32BigEndian(b.AsSpan(at,4));
private static void Check(bool v,string message){if(!v)throw new Exception(message);}
internal static void Run(JsonObject template,string output)
{
var root=template.DeepClone().AsObject();
root["materials"]!.AsArray().Add(root["materials"]![0]!.DeepClone());
var primitives=root["meshes"]![0]!["primitives"]!.AsArray();var second=primitives[0]!.DeepClone();second["material"]=1;primitives.Add(second);
using(var image=new RasterImage(16,8,new Rgba32(200,40,80,255)))
{
image[0,0]=new Rgba32(200,40,80,128);using var png=new MemoryStream();image.SaveAsPng(png);
root["images"]![0]!["uri"]="data:image/png;base64,"+Convert.ToBase64String(png.ToArray());
}
string input=Path.Combine(output,"streamed-multi.gltf"),file=Path.Combine(output,"sd","streamed-multi.dndmodel");File.WriteAllText(input,root.ToJsonString());
ModelConverter.Convert(input,file+".resident");var legacy=File.ReadAllBytes(file+".resident");
ModelConverter.Convert(input,file,new ImportOptions{StreamableTextures=true});var bytes=File.ReadAllBytes(file);string text=File.ReadAllText(file+".textures.json");
using var sidecar=JsonDocument.Parse(text);var data=sidecar.RootElement;
Check(I(bytes,I(bytes,68))==0&&I(bytes,72)==4,"Streamable models must embed no resident texture chains.");
Check(I(bytes,I(bytes,52))==3&&data.GetProperty("materials").GetArrayLength()==3,"Different authored material slots survive native fallback deduplication.");
Check(data.GetProperty("textures").GetArrayLength()==1,"Shared source imagery remains one family.");
for(int i=1;i<3;i++){var m=data.GetProperty("materials")[i];Check(m.GetProperty("materialIndex").GetInt32()==i&&m.GetProperty("primaryTexture").GetInt32()==0,"Native material sidecar mapping.");}
var texture=data.GetProperty("textures")[0];string path=Path.Combine(Path.GetDirectoryName(file)!,texture.GetProperty("file").GetString()!);byte[] asset=File.ReadAllBytes(path);var descriptor=StreamableTextureDescriptor.Read(asset);
Check(descriptor.Count==5&&descriptor.GetLevel(0).Width==16&&descriptor.GetLevel(0).Height==8&&descriptor.DefaultFormat==6,"Model mip generation preserves rectangular dimensions and smooth alpha.");
for(int i=0;i<descriptor.Count;i++)Check(descriptor.ValidatePayload(i,asset,descriptor.GetLevel(i).Offset),"Model sidecar level CRC.");
Check(asset[descriptor.GetLevel(0).Offset]==128,"Smooth alpha must survive native model extraction.");
// Skinning, animation, geometry and normalized authored UVs remain
// byte-identical; only the second primitive's native material ID differs.
foreach(int section in new[]{0,4,5})Check(bytes.AsSpan(I(bytes,20+section*16),I(bytes,24+section*16)).SequenceEqual(legacy.AsSpan(I(legacy,20+section*16),I(legacy,24+section*16))),"Streaming must preserve nodes/skins/animation.");
int at=I(bytes,36)+4,oldAt=I(legacy,36)+4;
for(int i=0;i<2;i++)
{
int length=44+I(bytes,at+12)*80+I(bytes,at+16)*4;
Check(bytes.AsSpan(at,8).SequenceEqual(legacy.AsSpan(oldAt,8))&&bytes.AsSpan(at+12,length-12).SequenceEqual(legacy.AsSpan(oldAt+12,length-12)),"Streaming must preserve mesh attributes, UVs, indices and skin weights.");at+=length;oldAt+=length;
}
ModelConverter.Convert(input,file,new ImportOptions{StreamableTextures=true});Check(bytes.SequenceEqual(File.ReadAllBytes(file))&&text==File.ReadAllText(file+".textures.json")&&asset.SequenceEqual(File.ReadAllBytes(path)),"Deterministic model, sidecar and DNLT output.");
string limited=file+".limited";ModelConverter.Convert(input,limited,new ImportOptions{StreamableTextures=true,MaximumMipLevels=1});
using(var json=JsonDocument.Parse(File.ReadAllText(limited+".textures.json")))
{var tx=json.RootElement.GetProperty("textures")[0];var d=StreamableTextureDescriptor.Read(File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(limited)!,tx.GetProperty("file").GetString()!)));Check(d.Count==1,"Streamable model quality limits.");}
foreach(var material in root["materials"]!.AsArray())
{material!.AsObject().Remove("extensions");material["emissiveFactor"]=new JsonArray(.2,.3,.4);material["emissiveTexture"]=new JsonObject{["index"]=0};}
File.WriteAllText(input,root.ToJsonString());string gx=file+".gx";ModelConverter.Convert(input,gx,new ImportOptions{StreamableTextures=true,CompileGxMaterials=true});
using(var json=JsonDocument.Parse(File.ReadAllText(gx+".textures.json")))
{var m=json.RootElement.GetProperty("materials")[1];Check(m.GetProperty("combiner").GetInt32()==2&&m.GetProperty("secondaryTexture").GetInt32()>=0&&json.RootElement.GetProperty("textures").GetArrayLength()>=2,"Secondary generated TEV maps become independent streamed families.");}
Check(I(File.ReadAllBytes(gx),I(File.ReadAllBytes(gx),68))==0,"Generated GX maps must not become hidden resident chains.");
ModelConverter.Convert(input,gx,new ImportOptions{StreamableTextures=true,StreamableFormat=StreamableTextureFormat.Rgba8,CompileGxMaterials=true});
using(var json=JsonDocument.Parse(File.ReadAllText(gx+".textures.json")))
foreach(var tx in json.RootElement.GetProperty("textures").EnumerateArray())Check(StreamableTextureDescriptor.Read(File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(gx)!,tx.GetProperty("file").GetString()!))).DefaultFormat==6,"Explicit streamable model format applies to generated maps.");
Console.WriteLine("Streamable model sidecars: shared families, zero resident images, slots, rectangular/alpha mips, UV/skinning/animation, limits and generated secondary maps passed.");
}
}
1 change: 1 addition & 0 deletions tests/ModelSmoke/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ static int Main()
TransformChecks.Run();
ModelEffectChecks.Run();
SourceImports();
StreamedPartChecks.Run();
using(var transparentModel=Model.LoadFZeroGxAsync("sd:/fz-translucent.gma").Result)
using(var instance=transparentModel.CreateInstance())
{
Expand Down
24 changes: 24 additions & 0 deletions tests/ModelSmoke/StreamedParts.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using System;
using Dolphin.Graphics;

internal static class StreamedPartChecks
{
internal static void Run()
{
using var model=Model.LoadAsync("sd:/streamed-multi.dndmodel").Result;
if(model.MaterialCount!=3)throw new Exception("Streamed material slot count.");
using var instance=model.CreateInstance();instance.Animator.Play("Walk");instance.Update(.5f);
var rgba=new byte[64];for(int i=0;i<16;i++){rgba[i*4]=200;rgba[i*4+1]=40;rgba[i*4+2]=80;rgba[i*4+3]=255;}
using var texture=Texture2D.Create(4,4,rgba);
var material=new Material{Texture=texture,SecondaryTexture=texture,Cull=CullMode.None,TextureTransform=new UvTransform(new Vector2(.1f,.2f),new Vector2(.5f,.7f),30)};
var renderer=new Renderer();var transform=new Transform();
// An instance retains geometry after its source model's owner closes.
model.Dispose();var matrix=new float[]{1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1};
renderer.BeginFrame(matrix,matrix);
renderer.DrawModelMaterialPart(instance,1,transform,material);renderer.DrawModelMaterialPart(instance,2,transform,material);
renderer.DrawModelMaterialPart(instance,0,transform,material); // unused default slot
try{renderer.DrawModelMaterialPart(instance,-1,transform,material);throw new Exception("Negative material index accepted.");}catch(ArgumentOutOfRangeException){}
try{renderer.DrawModelMaterialPart(instance,3,transform,material);throw new Exception("Large material index accepted.");}catch(InvalidOperationException){}
renderer.EndFrame();
}
}
Loading
Loading