diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6cd53407b..d68f99cc7 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -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: diff --git a/docs/streamable-models.md b/docs/streamable-models.md new file mode 100644 index 000000000..b6fc46b4c --- /dev/null +++ b/docs/streamable-models.md @@ -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. diff --git a/include/dnd_model.h b/include/dnd_model.h index 3564cb589..951c9a90e 100644 --- a/include/dnd_model.h +++ b/include/dnd_model.h @@ -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 diff --git a/source/model_graphics.c b/source/model_graphics.c index 91e84c874..3218f4cab 100644 --- a/source/model_graphics.c +++ b/source/model_graphics.c @@ -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; @@ -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;imeshes;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; @@ -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;drawmeshes;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;firstindices;){ unsigned count=mesh->indices-first;if(count>768)count=768; @@ -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(); diff --git a/src/DolphinDotNet.GameCube/Dolphin/Graphics/NativeModel.cs b/src/DolphinDotNet.GameCube/Dolphin/Graphics/NativeModel.cs index de07cab8e..3a0bebca3 100644 --- a/src/DolphinDotNet.GameCube/Dolphin/Graphics/NativeModel.cs +++ b/src/DolphinDotNet.GameCube/Dolphin/Graphics/NativeModel.cs @@ -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(); } diff --git a/src/DolphinDotNet.GameCube/Dolphin/Graphics/Renderer.cs b/src/DolphinDotNet.GameCube/Dolphin/Graphics/Renderer.cs index 5a50b520d..881c51f68 100644 --- a/src/DolphinDotNet.GameCube/Dolphin/Graphics/Renderer.cs +++ b/src/DolphinDotNet.GameCube/Dolphin/Graphics/Renderer.cs @@ -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); } + /// 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. + 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"); diff --git a/tests/ModelAssetTests/Program.cs b/tests/ModelAssetTests/Program.cs index 86c44b5c2..3898bdba8 100644 --- a/tests/ModelAssetTests/Program.cs +++ b/tests/ModelAssetTests/Program.cs @@ -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."); diff --git a/tests/ModelAssetTests/StreamableModelTests.cs b/tests/ModelAssetTests/StreamableModelTests.cs new file mode 100644 index 000000000..d031a79ec --- /dev/null +++ b/tests/ModelAssetTests/StreamableModelTests.cs @@ -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=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."); + } +} diff --git a/tests/ModelSmoke/Program.cs b/tests/ModelSmoke/Program.cs index dbd894165..8724f8dd1 100644 --- a/tests/ModelSmoke/Program.cs +++ b/tests/ModelSmoke/Program.cs @@ -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()) { diff --git a/tests/ModelSmoke/StreamedParts.cs b/tests/ModelSmoke/StreamedParts.cs new file mode 100644 index 000000000..9767d26fb --- /dev/null +++ b/tests/ModelSmoke/StreamedParts.cs @@ -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(); + } +} diff --git a/tests/model_effect_test.c b/tests/model_effect_test.c index 3de510381..30e60b0ba 100644 --- a/tests/model_effect_test.c +++ b/tests/model_effect_test.c @@ -329,10 +329,16 @@ int main(void) { assert(dnd_model_draw_material(123,world,override_texture,override_texture,0x12345678,65,.25f,textured)==0); assert(full_draws==3&&full_skin==1&&order[0]==2&&order[1]==1&&order[2]==0&&allocations==full_allocations); assert(!memcmp(original_materials,materials,sizeof(materials))); - assert(dnd_model_draw_material(123,world,wrong,override_texture,0x12345678,65,.25f,textured)<0&&full_draws==3); - wm[0]=0;assert(dnd_model_draw_material(123,world,override_texture,override_texture,0x12345678,65,.25f,textured)<0&&full_draws==3);wm[0]=-1; + assert(dnd_model_draw_material_part(123,world,1,override_texture,override_texture,0x12345678,65,.25f,textured)==0&&full_draws==4&&full_skin==2); + assert(dnd_model_draw_material_part(123,world,0,override_texture,override_texture,0x12345678,65,.25f,textured)==0&&full_draws==5&&full_skin==2); + assert(dnd_model_draw_material_part(123,world,3,override_texture,override_texture,0x12345678,65,.25f,textured)==0&&full_draws==5); + assert(dnd_model_draw_material_part(123,world,-1,override_texture,override_texture,0x12345678,65,.25f,textured)<0&&full_draws==5); + assert(dnd_model_draw_material_part(123,world,4,override_texture,override_texture,0x12345678,65,.25f,textured)<0&&full_draws==5); + assert(!memcmp(original_materials,materials,sizeof(materials))&&allocations==full_allocations); + assert(dnd_model_draw_material(123,world,wrong,override_texture,0x12345678,65,.25f,textured)<0&&full_draws==5); + wm[0]=0;assert(dnd_model_draw_material(123,world,override_texture,override_texture,0x12345678,65,.25f,textured)<0&&full_draws==5);wm[0]=-1; assert(dnd_draw_release(override_texture)==0); - assert(dnd_model_draw_material(123,world,override_texture,override_texture,0x12345678,65,.25f,textured)<0&&full_draws==3); + assert(dnd_model_draw_material(123,world,override_texture,override_texture,0x12345678,65,.25f,textured)<0&&full_draws==5); custom_scene_active=true;int previous_normals=scene_normals;assert(dnd_model_draw(123,world)==0&&scene_normals>previous_normals&&scene_lights>0);custom_scene_active=false; // The real indexed production path preserves geometry, UV, authored alpha, // culling and imported material state. Skins use evaluated poses, not bind geometry. diff --git a/tools/DolphinDotNet.Assets/Geometry.cs b/tools/DolphinDotNet.Assets/Geometry.cs index de6df754d..f2eebcc1d 100644 --- a/tools/DolphinDotNet.Assets/Geometry.cs +++ b/tools/DolphinDotNet.Assets/Geometry.cs @@ -13,7 +13,7 @@ public byte[] Build() var scenes=Items("scenes");if(scenes.Length!=0){int scene=Int(root,"scene");if((uint)scene>=scenes.Length)throw new InvalidDataException("Invalid scene.");foreach(var n in Array(scenes[scene],"nodes"))Visit(n.GetInt32());}else for(int i=0;ix.GetSingle()).ToArray();if(m.Length!=16)throw new InvalidDataException("Node matrix shape.");var matrix=new Matrix4x4(m[0],m[1],m[2],m[3],m[4],m[5],m[6],m[7],m[8],m[9],m[10],m[11],m[12],m[13],m[14],m[15]);if(!Matrix4x4.Decompose(matrix,out var scale,out var rotation,out var translation))throw new InvalidDataException("Sheared matrix unsupported.");var r=Matrix4x4.CreateScale(scale)*Matrix4x4.CreateFromQuaternion(rotation)*Matrix4x4.CreateTranslation(translation);float[] actual=[r.M11,r.M12,r.M13,r.M14,r.M21,r.M22,r.M23,r.M24,r.M31,r.M32,r.M33,r.M34,r.M41,r.M42,r.M43,r.M44];if(m.Where((v,k)=>Math.Abs(v-actual[k])>1e-4f).Any())throw new InvalidDataException("Sheared matrix unsupported.");t=[translation.X,translation.Y,translation.Z];q=[rotation.X,rotation.Y,rotation.Z,rotation.W];s=[scale.X,scale.Y,scale.Z];}if(t.Length!=3||q.Length!=4||s.Length!=3||s.Any(x=>Math.Abs(x)<1e-6f))throw new InvalidDataException("Invalid node TRS.");var quaternion=Quaternion.Normalize(new(q[0],q[1],q[2],q[3]));nodes.Floats(t);nodes.Floats([quaternion.X,quaternion.Y,quaternion.Z,quaternion.W]);nodes.Floats(s);} var skinList=Items("skins");skins.I(skinList.Length);var jointCounts=new int[skinList.Length];for(int idx=0;idxx.GetInt32()).ToArray();if(joints.Length<1||joints.Length>256||joints.Distinct().Count()!=joints.Length||joints.Any(x=>(uint)x>=ns.Length))throw new InvalidDataException("Skin joint limit/reference.");jointCounts[idx]=joints.Length;skins.I(joints.Length);var matrices=sk.TryGetProperty("inverseBindMatrices",out var ib)?Access(ib.GetInt32(),"MAT4"):Enumerable.Range(0,joints.Length).Select(_=>new float[]{1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1}).ToArray();if(matrices.Length!=joints.Length)throw new InvalidDataException("Inverse bind count.");for(int j=0;j(StringComparer.Ordinal);var records=new List();for(int i=0;i<=mats.Length;i++){using var record=new BigWriter();WriteMaterial(record,i==0?default:mats[i-1],i-1);var bytes=record.Data;string key=System.Convert.ToHexString(bytes);if(!uniqueMaterials.TryGetValue(key,out int id)){id=records.Count;uniqueMaterials.Add(key,id);records.Add(bytes);}materialRemap[i]=id;}materials.I(records.Count);foreach(var bytes in records)materials.Bytes(bytes); + WriteTextures(textures);var mats=Items("materials");materialRemap=new int[mats.Length+1];var uniqueMaterials=new Dictionary(StringComparer.Ordinal);var records=new List();for(int i=0;i<=mats.Length;i++){using var record=new BigWriter();WriteMaterial(record,i==0?default:mats[i-1],i-1);var bytes=record.Data;string key=System.Convert.ToHexString(bytes)+(options.StreamableTextures?":"+i:"");if(!uniqueMaterials.TryGetValue(key,out int id)){id=records.Count;uniqueMaterials.Add(key,id);records.Add(bytes);}materialRemap[i]=id;}materials.I(records.Count);foreach(var bytes in records)materials.Bytes(bytes); var primitives=new List();var meshList=Items("meshes");foreach(int i in active.Order())if(ns[i].TryGetProperty("mesh",out var mid)){int mesh=mid.GetInt32();if((uint)mesh>=meshList.Length)throw new InvalidDataException("Mesh reference.");if(meshList[mesh].TryGetProperty("weights",out _)||ns[i].TryGetProperty("weights",out _))throw new InvalidDataException("Morph weights unsupported.");foreach(var prim in Array(meshList[mesh],"primitives"))primitives.Add(Primitive(prim,i,Int(ns[i],"skin",-1),jointCounts,mats));} if(primitives.Count==0||primitives.Count>4096)throw new InvalidDataException("Model requires 1..4096 primitives.");meshes.I(primitives.Count);foreach(var p in primitives)meshes.Bytes(p);WriteClips(clips,ns); return Package.Write([nodes.Data,meshes.Data,materials.Data,textures.Data,skins.Data,clips.Data], options.CompileGxMaterials ? 2u : 1u); diff --git a/tools/DolphinDotNet.Assets/ModelConverter.cs b/tools/DolphinDotNet.Assets/ModelConverter.cs index 119dae53f..1a2ba47be 100644 --- a/tools/DolphinDotNet.Assets/ModelConverter.cs +++ b/tools/DolphinDotNet.Assets/ModelConverter.cs @@ -10,8 +10,13 @@ public sealed class ImportOptions public int TextureLimit { get; set; } = 256; /// Total mip levels including the base; zero retains the full chain. public int MaximumMipLevels { get; set; } + /// Export independent DNLT families and a material sidecar instead + /// of embedding permanently resident texture chains in the model. + public bool StreamableTextures {get;set;} + public StreamableTextureFormat StreamableFormat {get;set;}=StreamableTextureFormat.Auto; internal int MipLevels(int width,int height) { + if(StreamableTextures)return 1; // Only base pixels feed the DNLT encoder. int levels=1;for(int n=Math.Min(width,height);n>4;n/=2)levels++; return MaximumMipLevels==0?levels:Math.Min(levels,MaximumMipLevels); } @@ -26,7 +31,9 @@ public static void Convert(string input,string output,ImportOptions? options=nul { options??=new(); if(options.TextureLimit<4||options.TextureLimit>1024||(options.TextureLimit&(options.TextureLimit-1))!=0)throw new ArgumentException("Texture limit must be a power of two from 4 to 1024."); - if(options.MaximumMipLevels<0||options.MaximumMipLevels>9)throw new ArgumentException("Maximum mip levels must be 0 (full chain) or 1..9, including the base."); + int maximumLevels=options.StreamableTextures?11:9; + if(options.MaximumMipLevels<0||options.MaximumMipLevels>maximumLevels)throw new ArgumentException("Maximum mip levels must be 0 (full chain) or 1.."+maximumLevels+", including the base."); + if(!options.StreamableTextures&&options.StreamableFormat!=StreamableTextureFormat.Auto)throw new ArgumentException("Streamable format requires streamable model textures."); if(options.BakeNeutralStudio&&(options.CompileGxMaterials||options.ApproximateMaterials))throw new ArgumentException("Neutral studio baking is separate from GX mapping/approximation."); input=Path.GetFullPath(input);output=Path.GetFullPath(output);string ext=Path.GetExtension(input).ToLowerInvariant();string? temp=null; try @@ -45,6 +52,7 @@ public static void Convert(string input,string output,ImportOptions? options=nul } else if(ext is ".gj" or ".xj") { + if(options.StreamableTextures)throw new NotSupportedException("Streamable model sidecars currently require glTF/GLB or an Assimp import."); if(options.MaximumMipLevels!=0)throw new NotSupportedException("Mip-level limits apply to glTF/GLB and Assimp imports, not direct PSO packages."); if(options.BakeNeutralStudio)throw new InvalidDataException("Studio baking requires a static glTF/GLB or Assimp scene with UV0."); var native=PsoGjImport.Convert(input,options.ApproximateMaterials); @@ -57,8 +65,10 @@ public static void Convert(string input,string output,ImportOptions? options=nul } else if(ext is ".gltf" or ".glb")importer=new(input,options); else throw new ArgumentException("Supported inputs: FBX, OBJ, DAE, 3DS, STL, PLY, glTF, GLB, PSO GameCube GJ and Blue Burst XJ geometry."); + importer.StreamableOutput=output; var package=importer.Build();Directory.CreateDirectory(Path.GetDirectoryName(output)!);string staged=output+"."+Guid.NewGuid().ToString("N")+".tmp"; try{File.WriteAllBytes(staged,package);File.Move(staged,output,true);}finally{File.Delete(staged);} + if(options.StreamableTextures)importer.WriteStreamableSidecar(); File.WriteAllText(output+".deps.json",JsonSerializer.Serialize(importer.Dependencies.OrderBy(x=>x,StringComparer.Ordinal).Select(x=>new{path=x,sha256=System.Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(x)))}))); if(options.BakeNeutralStudio)NeutralStudioReport.Write(output,options.TextureLimit); } diff --git a/tools/DolphinDotNet.Assets/Program.cs b/tools/DolphinDotNet.Assets/Program.cs index 7945408bb..0d2f79b34 100644 --- a/tools/DolphinDotNet.Assets/Program.cs +++ b/tools/DolphinDotNet.Assets/Program.cs @@ -5,7 +5,7 @@ if (args.Length > 0 && args[0] == "gcft") { GameCubeAssetCommands.Run(args); return 0; } if (args.Length == 0 || args[0] == "--help") { - Console.WriteLine("dnd-assets firmware inspect INPUT\ndnd-assets gcft inspect INPUT | gcft extract ARCHIVE OUTPUT_DIR | gcft pack INPUT_DIR OUTPUT.arc | gcft bti INPUT.bti OUTPUT.png\ndnd-assets model INPUT.{glb,gltf,fbx,obj,dae,3ds,stl,ply,gj,xj} OUTPUT.dndmodel [--texture-limit N] [--mip-levels N] [--assimp PATH] [--allow-material-approximation] [--compile-gx-materials] [--bake-neutral-studio]\ndnd-assets audio INPUT.mp3 OUTPUT.adx [--loops PATH] [--loop NAME] [--sample-rate HZ] [--ffmpeg PATH]\ndnd-assets texture INPUT.png OUTPUT.dndtex [--mipmaps]\ndnd-assets texture INPUT.png OUTPUT.dnlod --streamable [--mipmaps] [--format auto|cmpr|rgba8] [--min-size N] [--levels 0,2,4] [--gutter N]\ndnd-assets texture --low LOW.png --high HIGH.png OUTPUT.dnlod --streamable --quality-pair\ndnd-assets font ATLAS.png OUTPUT.dndfont CELL_WIDTH CELL_HEIGHT [FIRST_CHARACTER] [CHARACTERS]\nFBX/OBJ/DAE/3DS/STL/PLY require Assimp CLI 5.3.x. PSO GJ/XJ geometry uses built-in .NET parsers; textured PSO materials currently require --allow-material-approximation. Outputs include a dependency manifest."); + Console.WriteLine("dnd-assets firmware inspect INPUT\ndnd-assets gcft inspect INPUT | gcft extract ARCHIVE OUTPUT_DIR | gcft pack INPUT_DIR OUTPUT.arc | gcft bti INPUT.bti OUTPUT.png\ndnd-assets model INPUT.{glb,gltf,fbx,obj,dae,3ds,stl,ply,gj,xj} OUTPUT.dndmodel [--texture-limit N] [--mip-levels N] [--assimp PATH] [--allow-material-approximation] [--compile-gx-materials] [--bake-neutral-studio] [--streamable-textures --streamable-format auto|rgba8|cmpr]\ndnd-assets audio INPUT.mp3 OUTPUT.adx [--loops PATH] [--loop NAME] [--sample-rate HZ] [--ffmpeg PATH]\ndnd-assets texture INPUT.png OUTPUT.dndtex [--mipmaps]\ndnd-assets texture INPUT.png OUTPUT.dnlod --streamable [--mipmaps] [--format auto|cmpr|rgba8] [--min-size N] [--levels 0,2,4] [--gutter N]\ndnd-assets texture --low LOW.png --high HIGH.png OUTPUT.dnlod --streamable --quality-pair\ndnd-assets font ATLAS.png OUTPUT.dndfont CELL_WIDTH CELL_HEIGHT [FIRST_CHARACTER] [CHARACTERS]\nFBX/OBJ/DAE/3DS/STL/PLY require Assimp CLI 5.3.x. PSO GJ/XJ geometry uses built-in .NET parsers; textured PSO materials currently require --allow-material-approximation. Outputs include a dependency manifest."); return 0; } if (args.Length >= 3 && args[0] == "audio") @@ -44,6 +44,8 @@ { case "--texture-limit": options.TextureLimit = int.Parse(args[++i]); break; case "--mip-levels": options.MaximumMipLevels = int.Parse(args[++i]); break; + case "--streamable-textures": options.StreamableTextures = true; break; + case "--streamable-format": options.StreamableFormat = args[++i].ToLowerInvariant() switch {"auto"=>StreamableTextureFormat.Auto,"rgba8"=>StreamableTextureFormat.Rgba8,"cmpr"=>StreamableTextureFormat.Cmpr,_=>throw new ArgumentException("Use auto, rgba8 or cmpr.")}; break; case "--assimp": options.Assimp = args[++i]; break; case "--allow-material-approximation": options.ApproximateMaterials = true; break; case "--compile-gx-materials": options.CompileGxMaterials = true; break; diff --git a/tools/DolphinDotNet.Assets/StreamableModels.cs b/tools/DolphinDotNet.Assets/StreamableModels.cs new file mode 100644 index 000000000..8d0680840 --- /dev/null +++ b/tools/DolphinDotNet.Assets/StreamableModels.cs @@ -0,0 +1,43 @@ +using System.Buffers.Binary; +using System.Security.Cryptography; +using System.Text.Json; +using DolphinDotNet.Imaging; + +namespace DolphinDotNet.Assets; + +internal sealed partial class GltfImport +{ + internal string StreamableOutput=""; + private readonly List streamedTextures=new(); + private readonly List streamedMaterials=new(); + private void ExportStreamableTextures(List payloads) + { + string directory=Path.GetDirectoryName(StreamableOutput)!; + string texturesDirectory=StreamableOutput+".textures";Directory.CreateDirectory(texturesDirectory); + for(int index=0;indexBinaryPrimitives.ReadInt32BigEndian(record.AsSpan(at,4)); + int w=Read(0),h=Read(4); + if(w<4||h<4||w>1024||h>1024||record.Length<28+w*h*4)throw new InvalidDataException("Invalid intermediate model image."); + using var image=new RasterImage(w,h); + for(int y=0;y1;n/=2)fullLevels++; + int[]? levels=options.MaximumMipLevels==0?null:Enumerable.Range(0,Math.Min(fullLevels,options.MaximumMipLevels)).ToArray(); + var asset=DolphinDotNet.Assets.StreamableTextures.Encode(image,new StreamableTextureOptions{Mipmaps=true,LogicalLevels=levels,Format=options.StreamableFormat}); + string hash=System.Convert.ToHexString(SHA256.HashData(asset.Bytes)).ToLowerInvariant(); + string file=Path.Combine(texturesDirectory,hash+".dnlod"); + File.WriteAllBytes(file,asset.Bytes);File.WriteAllText(file+".manifest.json",asset.Manifest); + streamedTextures.Add(new { textureIndex=index,family="textures/"+hash,file=Path.GetRelativePath(directory,file).Replace('\\','/'),sha256=hash,width=w,height=h,wrapS=Read(12),wrapT=Read(16),linear=Read(20)!=0 }); + } + } + internal void WriteStreamableSidecar() + { + var sidecar=new { version=1,model=Path.GetFileName(StreamableOutput),modelSha256=System.Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(StreamableOutput))).ToLowerInvariant(),embeddedTextureCount=0,textures=streamedTextures,materials=streamedMaterials }; + File.WriteAllText(StreamableOutput+".textures.json",JsonSerializer.Serialize(sidecar,new JsonSerializerOptions{WriteIndented=true})+"\n"); + } +} diff --git a/tools/DolphinDotNet.Assets/Textures.cs b/tools/DolphinDotNet.Assets/Textures.cs index f1116e86d..4c7c63e5e 100644 --- a/tools/DolphinDotNet.Assets/Textures.cs +++ b/tools/DolphinDotNet.Assets/Textures.cs @@ -9,7 +9,7 @@ private void WriteTextures(BigWriter output) { var textures=Items("textures");textureRemap=new int[textures.Length];var payloads=new List();int sourceIndex=0;var images=Items("images");var samplers=Items("samplers");var unique=new Dictionary(StringComparer.Ordinal); foreach(var tx in textures){using var writer=new BigWriter();int source=Int(tx,"source",-1);if((uint)source>=images.Length)throw new InvalidDataException("Missing texture image.");var image=images[source];byte[] data=image.TryGetProperty("uri",out var uri)?ReadUri(uri.GetString()!):View(Int(image,"bufferView",-1));using var decoded=RasterImage.Load(data);int w=4,h=4;while(w=samplers.Length)throw new InvalidDataException("Texture sampler.");var sampler=si<0?default:samplers[si];int wrapS=sampler.ValueKind==JsonValueKind.Undefined?10497:Int(sampler,"wrapS",10497),wrapT=sampler.ValueKind==JsonValueKind.Undefined?10497:Int(sampler,"wrapT",10497);int levels=options.MipLevels(w,h);writer.I(w);writer.I(h);writer.I(levels);writer.I(Wrap(wrapS));writer.I(Wrap(wrapT));writer.I(sampler.ValueKind==JsonValueKind.Undefined||Int(sampler,"magFilter",9729)!=9728?1:0);var payload=new List();for(int level=0;level>level,h>>level);for(int y=0;yvalue switch{10497=>1,33071=>0,33648=>2,_=>throw new InvalidDataException("Wrap mode.")}; // The target stores one UV set. Resolve the source texture coordinate set @@ -62,7 +62,8 @@ private void WriteMaterial(BigWriter w,JsonElement m,int sourceMaterialIndex) Console.Error.WriteLine($"Material {sourceMaterialIndex}: metallic/roughness PBR contributions approximated by simple diffuse shading."); } if(color.Length!=4||color.Any(x=>x<0||x>1)||cutoff<0||cutoff>1)throw new InvalidDataException("Material range.");int packed=texture<0?-1:textureRemap[texture];if(bakedMaterials.TryGetValue(sourceMaterialIndex,out int baked)){packed=baked;color=[1,1,1,1];}if(gxMaterials.TryGetValue(sourceMaterialIndex,out var gx))packed=gx.primary; - w.Floats(color);w.I(packed);w.I(mode);w.F(cutoff);w.I(two?1:0); - if(options.CompileGxMaterials){w.I(gxMaterials.TryGetValue(sourceMaterialIndex,out gx)?gx.secondary:-1);w.I(gxMaterials.TryGetValue(sourceMaterialIndex,out gx)?gx.combiner:0);} + if(options.StreamableTextures)streamedMaterials.Add(new { materialIndex=sourceMaterialIndex+1,primaryTexture=packed,secondaryTexture=gxMaterials.TryGetValue(sourceMaterialIndex,out var streamedGx)?streamedGx.secondary:-1,combiner=gxMaterials.TryGetValue(sourceMaterialIndex,out streamedGx)?streamedGx.combiner:0,color,mode,cutoff,doubleSided=two }); + w.Floats(color);w.I(options.StreamableTextures?-1:packed);w.I(mode);w.F(cutoff);w.I(two?1:0); + if(options.CompileGxMaterials){w.I(!options.StreamableTextures&&gxMaterials.TryGetValue(sourceMaterialIndex,out gx)?gx.secondary:-1);w.I(!options.StreamableTextures&&gxMaterials.TryGetValue(sourceMaterialIndex,out gx)?gx.combiner:0);} } } diff --git a/tools/DolphinDotNet.Compiler/NativeStorageBindings.cs b/tools/DolphinDotNet.Compiler/NativeStorageBindings.cs index bfaa2a56e..601f6d9cc 100644 --- a/tools/DolphinDotNet.Compiler/NativeStorageBindings.cs +++ b/tools/DolphinDotNet.Compiler/NativeStorageBindings.cs @@ -23,6 +23,7 @@ internal static class NativeStorageBindings ["Finish"]=("dnd_corpus_finish","iiii",false), ["ModelDrawModels"]=("dnd_model_draw_models","aai",false), ["ModelDrawMaterial"]=("dnd_model_draw_material","iaiiiifi",false), + ["ModelDrawMaterialPart"]=("dnd_model_draw_material_part","iaiiiiifi",false), ["ModelDrawAnimated"]=("dnd_model_draw_animated","iaa",false), ["ModelDrawAnimatedShapes"]=("dnd_model_draw_animated_shapes","iaaa",false), ["DolPrepare"]=("dnd_dol_prepare","a",false), @@ -287,7 +288,7 @@ internal static void Emit(StringBuilder b,ValueIrNativeStorage call) // Publication, allocation and every other texture/GX operation require // the application executor. Keep this list deliberately restrictive. bool detachedTextureCopy = call.Operation is "TextureStageArray" or "TextureStageBuffer" or "TextureStageBufferRange"; - if(call.Operation.StartsWith("Device",StringComparison.Ordinal)||call.Operation.StartsWith("Buffer",StringComparison.Ordinal)||call.Operation.StartsWith("Draw",StringComparison.Ordinal)||(!detachedTextureCopy && call.Operation.StartsWith("Texture",StringComparison.Ordinal))||call.Operation.StartsWith("Mesh",StringComparison.Ordinal)||call.Operation.StartsWith("Canvas",StringComparison.Ordinal)||call.Operation=="NativeObjectSize"||call.Operation.StartsWith("Graphics",StringComparison.Ordinal)||call.Operation.StartsWith("Input",StringComparison.Ordinal)||(call.Operation.StartsWith("Audio",StringComparison.Ordinal)&&call.Operation is not ("AudioInit" or "AudioBegin" or "AudioBeginMemory" or "AudioBeginSource" or "AudioStep" or "AudioDispose" or "AudioStat"))||call.Operation=="AssetCompatReport"||call.Operation is "ModelDrawModels" or "ModelDraw" or "ModelDrawEffect" or "ModelDrawMaterial" or "ModelFrameBegin" or "ModelFrameEnd" or "PlatformReset" or "HardwareProbe" or "HardwareId") + if(call.Operation.StartsWith("Device",StringComparison.Ordinal)||call.Operation.StartsWith("Buffer",StringComparison.Ordinal)||call.Operation.StartsWith("Draw",StringComparison.Ordinal)||(!detachedTextureCopy && call.Operation.StartsWith("Texture",StringComparison.Ordinal))||call.Operation.StartsWith("Mesh",StringComparison.Ordinal)||call.Operation.StartsWith("Canvas",StringComparison.Ordinal)||call.Operation=="NativeObjectSize"||call.Operation.StartsWith("Graphics",StringComparison.Ordinal)||call.Operation.StartsWith("Input",StringComparison.Ordinal)||(call.Operation.StartsWith("Audio",StringComparison.Ordinal)&&call.Operation is not ("AudioInit" or "AudioBegin" or "AudioBeginMemory" or "AudioBeginSource" or "AudioStep" or "AudioDispose" or "AudioStat"))||call.Operation=="AssetCompatReport"||call.Operation is "ModelDrawModels" or "ModelDraw" or "ModelDrawEffect" or "ModelDrawMaterial" or "ModelDrawMaterialPart" or "ModelFrameBegin" or "ModelFrameEnd" or "PlatformReset" or "HardwareProbe" or "HardwareId") b.AppendLine(" dnd_async_require_application_thread();"); if(call.Operation=="Publish") b.AppendLine(" extern void dnd_corpus_publish(int,int,int,int,DndString*);");