diff --git a/DolphinDotNet.sln b/DolphinDotNet.sln index 5b62ab643..bf682f586 100644 --- a/DolphinDotNet.sln +++ b/DolphinDotNet.sln @@ -83,6 +83,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DisplayConfigurationSmoke", EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HardwareAssetCompatibilityPolicyTests", "tests\HardwareAssetCompatibilityPolicyTests\HardwareAssetCompatibilityPolicyTests.csproj", "{8A1D0B64-59B7-44F6-A0A9-4AD8FC000016}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StreamableTextureTests", "tests\StreamableTextureTests\StreamableTextureTests.csproj", "{8A1D0B64-59B7-44F6-A0A9-4AD8FC000090}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -177,6 +179,10 @@ Global {8A1D0B64-59B7-44F6-A0A9-4AD8FC000016}.Debug|Any CPU.Build.0 = Debug|Any CPU {8A1D0B64-59B7-44F6-A0A9-4AD8FC000016}.Release|Any CPU.ActiveCfg = Release|Any CPU {8A1D0B64-59B7-44F6-A0A9-4AD8FC000016}.Release|Any CPU.Build.0 = Release|Any CPU + {8A1D0B64-59B7-44F6-A0A9-4AD8FC000090}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8A1D0B64-59B7-44F6-A0A9-4AD8FC000090}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8A1D0B64-59B7-44F6-A0A9-4AD8FC000090}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8A1D0B64-59B7-44F6-A0A9-4AD8FC000090}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -204,6 +210,7 @@ Global {8A1D0B64-59B7-44F6-A0A9-4AD8FC000014} = {8A1D0B64-59B7-44F6-A0A9-4AD8FC000068} {8A1D0B64-59B7-44F6-A0A9-4AD8FC000015} = {8A1D0B64-59B7-44F6-A0A9-4AD8FC000068} {8A1D0B64-59B7-44F6-A0A9-4AD8FC000016} = {8A1D0B64-59B7-44F6-A0A9-4AD8FC000068} + {8A1D0B64-59B7-44F6-A0A9-4AD8FC000090} = {8A1D0B64-59B7-44F6-A0A9-4AD8FC000068} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {8A1D0B64-59B7-44F6-A0A9-4AD8FC0003E7} diff --git a/docs/streamable-textures.md b/docs/streamable-textures.md new file mode 100644 index 000000000..577d178f2 --- /dev/null +++ b/docs/streamable-textures.md @@ -0,0 +1,68 @@ +# Independently streamable texture levels + +DNLT v1 (`.dnlod`) stores independently checksummed GX-native images. Level 0 is +the finest; physical payload order is coarsest first. A header/index read is +sufficient to discover levels; image payloads are validated separately, after +bounded reads. This format does not change DNTX v1/v2 or `StreamingTexture`. + +```sh +dnd-assets texture grass.png grass.dnlod --streamable --mipmaps --format cmpr +dnd-assets texture grass.png grass.dnlod --streamable --mipmaps --format rgba8 --min-size 8 +dnd-assets texture grass.png grass.dnlod --streamable --mipmaps --levels 0,2,4 --gutter 4 +dnd-assets texture --low grass_low.png --high grass_high.png grass.dnlod --streamable --quality-pair +``` + +`--format auto` (default) uses CMPR for opaque/binary-alpha images and RGBA8 for +smooth alpha. Explicit CMPR rejects smooth alpha rather than making it opaque. +Mips use premultiplied-aware box filtering in byte/sRGB space. Binary CMPR mip +coverage retains the nearest representable number of opaque texels, with stable +raster-order ties. CMPR encoding is deterministic RGB565 endpoint quantization +and nearest-palette matching; it is not a perceptual/high-effort compressor. + +`--min-size` is a power-of-two cutoff for the largest dimension; short axes +clamp at 1. `--levels` preserves the original mip exponents and must lie above +the cutoff. A low/high pair has exactly HIGH (0) and LOW (1), accepts independent +non-power-of-two dimensions and never synthesizes intermediate images. Without +`--mipmaps`, a standalone streamable image has one entry and flags 0. + +`--gutter` extrudes 0–16 border pixels around each independently stored image. +The index includes per-level source-normalized scale/offset mappings. These +identify a finite positive usable rectangle within the native image; source +mip dimensions (native dimensions times UV scale) must follow the authored +half-size progression. Compose these mappings with authored/scrolled material +UVs instead of modifying mesh geometry. Guttered native dimensions must still +fit the 1024-texel limit. Native padding replicates edge texels. + +The tool also writes `OUTPUT.manifest.json`: deterministic level dimensions, +byte ranges, CRC32, UV mappings, format/alpha decisions and source RGBA hashes. +CLI manifests additionally include the encoded source-file SHA-256 hashes. + +## Binary contract + +All metadata is little endian. The 64-byte header is: magic `DNLT`, version 1, +flags (1 mip chain, 2 sparse mips, 4 quality pair), logical full width/height, +default GX format, entry count, initial coarse entry index, table offset (64), +first data offset, file length, metadata CRC32, optional UV-table offset and +length, then eight zero-reserved bytes. Flags 0 describe one standalone image; +valid mip flag combinations are 1 and 3; quality pair is 4. + +Each 32-byte table entry is logical LOD (u32), native width/height (u16 each), +GX format (u32: 6 RGBA8 or 14 CMPR), zero flags, offset, padded native byte count, +payload CRC32 and zero reserved. Table order is increasing logical LOD. The +optional UV table follows immediately: float32 scaleU, scaleV, offsetU, offsetV +for each entry. Metadata CRC32 covers both tables, excluding the header/padding. +An absent UV table means identity. Payloads are contiguous, 32-byte aligned and +ordered from coarsest to finest; total file length is bounded to 16 MiB. +RGBA8 uses 4×4, 64-byte tiles; CMPR uses 8×8, 32-byte tiles, including tiny mips. + +`Dolphin.Formats.StreamableTextureDescriptor.GetMetadataBytes(header, fileLength)` +validates a 64-byte header before a bounded metadata read. `Read(prefix, +fileLength)` validates metadata without touching payloads and returns an +immutable descriptor. `GetLevel` returns independent native ranges, logical +exponents and UV mappings. Validate each payload using its CRC, or incrementally +with `ComputeCrc32(..., initial)`, before GPU publication. Descriptor parsing +never allocates GPU resources and never implicitly reads a complete file. + +Run `dotnet run --project tests/StreamableTextureTests -c Release` for independent +BTI pixel decoding, coverage/filtering, sparse/pair/gutter cases, corrupt-header +and truncation checks, fuzz inputs and DNTX compatibility checks. diff --git a/scripts/ci_test_suite.py b/scripts/ci_test_suite.py index 9ea55420e..c87f3fdbf 100644 --- a/scripts/ci_test_suite.py +++ b/scripts/ci_test_suite.py @@ -152,6 +152,7 @@ def main(area): build("tests/GraphicsPhaseOneSmoke/GraphicsPhaseOneSmoke.csproj") build("tests/GraphicsPhaseTwoSmoke/GraphicsPhaseTwoSmoke.csproj") test("tests/TextureStreamingTests") + test("tests/StreamableTextureTests") test("tests/EffectCompilerTests") with tempfile.TemporaryDirectory() as tmp: run("dotnet","run","--project","tests/ModelAssetTests","-c","Release","--",tmp) diff --git a/src/DolphinDotNet.Core/Dolphin/Formats/StreamableTextureDescriptor.cs b/src/DolphinDotNet.Core/Dolphin/Formats/StreamableTextureDescriptor.cs new file mode 100644 index 000000000..1b7fb7979 --- /dev/null +++ b/src/DolphinDotNet.Core/Dolphin/Formats/StreamableTextureDescriptor.cs @@ -0,0 +1,116 @@ +using System; +using System.IO; + +namespace Dolphin.Formats; + +[Flags] +public enum StreamableTextureFlags { None=0, MipChain=1, SparseLevels=2, QualityPair=4 } + +/// Static source-normalized UV mapping for one independently stored image. +public readonly struct TextureLodUv +{ + public readonly float ScaleU,ScaleV,OffsetU,OffsetV; + public TextureLodUv(float scaleU,float scaleV,float offsetU,float offsetV) + {ScaleU=scaleU;ScaleV=scaleV;OffsetU=offsetU;OffsetV=offsetV;} + public static TextureLodUv Identity=>new TextureLodUv(1,1,0,0); +} + +public readonly struct StreamableTextureLevel +{ + public readonly int LogicalLod,Width,Height,Format,Offset,Length; + public readonly uint Crc32; + public readonly TextureLodUv Uv; + internal StreamableTextureLevel(int lod,int width,int height,int format,int offset,int length,uint crc,TextureLodUv uv) + {LogicalLod=lod;Width=width;Height=height;Format=format;Offset=offset;Length=length;Crc32=crc;Uv=uv;} +} + +/// Immutable, header/index-only DNLT v1 descriptor. Reading this type never +/// reads a payload or allocates GPU resources. DNTX v1/v2 are separate formats. +public sealed class StreamableTextureDescriptor +{ + public const int HeaderBytes=64,EntryBytes=32,MaximumLevels=11,MaximumFileBytes=16*1024*1024; + private readonly StreamableTextureLevel[] levels; + public int Width {get;} + public int Height {get;} + public int DefaultFormat {get;} + public int FileLength {get;} + public int MetadataBytes {get;} + public int CoarseIndex=>levels.Length-1; + public int Count=>levels.Length; + public StreamableTextureFlags Flags {get;} + public bool IsQualityPair=>(Flags&StreamableTextureFlags.QualityPair)!=0; + private StreamableTextureDescriptor(int width,int height,int format,int fileLength,int metadataBytes,StreamableTextureFlags flags,StreamableTextureLevel[] levels) + {Width=width;Height=height;DefaultFormat=format;FileLength=fileLength;MetadataBytes=metadataBytes;Flags=flags;this.levels=levels;} + public StreamableTextureLevel GetLevel(int index) + {if(index<0||index>=levels.Length)throw new ArgumentOutOfRangeException("index");return levels[index];} + private static void Need(bool valid,string reason){if(!valid)throw new InvalidDataException("DNLT: "+reason);} + private static uint U32(byte[] b,int at) + {return (uint)(b[at]|b[at+1]<<8|b[at+2]<<16|b[at+3]<<24);} + private static int Int(byte[] b,int at) + {uint value=U32(b,at);Need(value<=int.MaxValue,"integer overflow");return (int)value;} + private static int U16(byte[] b,int at)=>b[at]|b[at+1]<<8; + private static float Float(byte[] b,int at)=>Dolphin.Numerics.BitConverter.Int32BitsToSingle((int)U32(b,at)); + private static bool Finite(float x)=>!float.IsNaN(x)&&!float.IsInfinity(x); + public static uint ComputeCrc32(byte[] bytes,int offset,int count,uint initial=0) + { + if(bytes==null)throw new ArgumentNullException("bytes"); + if(offset<0||count<0||offset>bytes.Length||count>bytes.Length-offset)throw new ArgumentOutOfRangeException("count"); + uint crc=~initial;for(int i=offset;i>1)^((crc&1)!=0?0xedb88320u:0);}return ~crc; + } + public static int NativeByteCount(int width,int height,int format) + { + Need(width>0&&height>0&&width<=1024&&height<=1024,"native dimensions"); + Need(format==6||format==14,"unsupported GX format"); + return format==6?((width+3)/4)*((height+3)/4)*64:((width+7)/8)*((height+7)/8)*32; + } + /// Validate the fixed header before issuing the bounded metadata read. + public static int GetMetadataBytes(byte[] header,int actualFileLength=-1) + { + if(header==null)throw new ArgumentNullException("header");Need(header.Length>=HeaderBytes,"truncated header"); + Need(U32(header,0)==0x544c4e44&&Int(header,4)==1,"magic/version"); + int flags=Int(header,8),count=Int(header,24),uv=Int(header,48),uvBytes=Int(header,52),length=Int(header,40); + Need((flags==0||flags==1||flags==3||flags==4)&&count>0&&count<=MaximumLevels,"flags/level count"); + Need(flags!=4||count==2,"quality pair count");Need(flags!=0||count==1,"single-image count"); + int tableEnd=HeaderBytes+count*EntryBytes; + Need(Int(header,32)==HeaderBytes&&Int(header,28)==count-1,"index/coarse entry"); + Need((uv==0&&uvBytes==0)||(uv==tableEnd&&uvBytes==count*16),"UV table range"); + int metadata=tableEnd+uvBytes,data=(metadata+31)&~31; + Need(Int(header,36)==data&&length>=data&&length<=MaximumFileBytes&&(length&31)==0,"data/file bounds"); + Need(actualFileLength<0||length==actualFileLength,"declared file length"); + Need(U32(header,56)==0&&U32(header,60)==0,"reserved header fields"); + int width=Int(header,12),height=Int(header,16);NativeByteCount(width,height,Int(header,20)); + if((flags&1)!=0)Need((width&(width-1))==0&&(height&(height-1))==0,"mip logical dimensions must be powers of two"); + return metadata; + } + public static StreamableTextureDescriptor Read(byte[] prefix,int actualFileLength=-1) + { + int metadata=GetMetadataBytes(prefix,actualFileLength);Need(prefix.Length>=metadata,"truncated metadata"); + int count=Int(prefix,24),width=Int(prefix,12),height=Int(prefix,16),uvOffset=Int(prefix,48),flags=Int(prefix,8); + Need(ComputeCrc32(prefix,HeaderBytes,metadata-HeaderBytes)==U32(prefix,44),"metadata checksum"); + int maxLod=0,largest=Math.Max(width,height);while(largest>1){maxLod++;largest/=2;} + var levels=new StreamableTextureLevel[count];int previous=-1; + for(int i=0;iprevious&&lod=Int(prefix,36)&&offset<=Int(prefix,40)&&length<=Int(prefix,40)-offset,"payload bounds"); + var uv=uvOffset==0?TextureLodUv.Identity:new TextureLodUv(Float(prefix,uvOffset+i*16),Float(prefix,uvOffset+i*16+4),Float(prefix,uvOffset+i*16+8),Float(prefix,uvOffset+i*16+12)); + Need(Finite(uv.ScaleU)&&Finite(uv.ScaleV)&&Finite(uv.OffsetU)&&Finite(uv.OffsetV),"nonfinite UV transform"); + Need(uv.ScaleU>0&&uv.ScaleV>0&&uv.OffsetU>=0&&uv.OffsetV>=0&&uv.ScaleU+uv.OffsetU<=1.00001f&&uv.ScaleV+uv.OffsetV<=1.00001f,"UV usable rectangle"); + if((flags&1)!=0){ + Need(lod<=maxLod,"logical mip exponent"); + Need(Math.Abs(w*uv.ScaleU-Math.Max(1,width>>lod))<.02f&&Math.Abs(h*uv.ScaleV-Math.Max(1,height>>lod))<.02f,"mip half-size progression"); + }else Need(lod==i&&(i!=0||(Math.Abs(w*uv.ScaleU-width)<.02f&&Math.Abs(h*uv.ScaleV-height)<.02f)),"HIGH/LOW quality pair"); + levels[i]=new StreamableTextureLevel(lod,w,h,format,offset,length,U32(prefix,at+24),uv); + } + if(flags==1){Need(count==maxLod+1,"incomplete full mip chain");for(int i=0;i=0;i--){Need(levels[i].Offset==cursor,"coarse-first payload order or overlap");cursor+=levels[i].Length;} + Need(cursor==Int(prefix,40),"trailing or missing payload bytes"); + return new StreamableTextureDescriptor(width,height,Int(prefix,20),cursor,metadata,(StreamableTextureFlags)flags,levels); + } + /// Check a complete payload, or pass chunk results incrementally to + /// ComputeCrc32 and compare with GetLevel(index).Crc32 before publication. + public bool ValidatePayload(int index,byte[] bytes,int offset=0) + {var level=GetLevel(index);return ComputeCrc32(bytes,offset,level.Length)==level.Crc32;} +} diff --git a/tests/StreamableTextureTests/Program.cs b/tests/StreamableTextureTests/Program.cs new file mode 100644 index 000000000..b106d87f3 --- /dev/null +++ b/tests/StreamableTextureTests/Program.cs @@ -0,0 +1,46 @@ +using System.Buffers.Binary; +using Dolphin.Formats; +using DolphinDotNet.Assets; +using DolphinDotNet.Imaging; + +int checks=0; +void Check(bool value,string label){checks++;if(!value)throw new Exception(label);} +void Reject(Action action,string label){bool rejected=false;try{action();}catch(InvalidDataException){rejected=true;}Check(rejected,label);} +void Invalid(Action action,string label){bool rejected=false;try{action();}catch(ArgumentException){rejected=true;}Check(rejected,label);} +void Put(byte[] b,int at,int value)=>BinaryPrimitives.WriteInt32LittleEndian(b.AsSpan(at,4),value); +int Int(byte[] b,int at)=>BinaryPrimitives.ReadInt32LittleEndian(b.AsSpan(at,4)); +void MetadataCrc(byte[] b){int n=StreamableTextureDescriptor.GetMetadataBytes(b);Put(b,44,(int)StreamableTextureDescriptor.ComputeCrc32(b,64,n-64));} +byte[] Rgba(StreamableTextureAsset asset,int level) +{ + var d=StreamableTextureDescriptor.Read(asset.Bytes);var l=d.GetLevel(level);byte[] bti=new byte[32+l.Length];bti[0]=(byte)l.Format;BinaryPrimitives.WriteUInt16BigEndian(bti.AsSpan(2),(ushort)l.Width);BinaryPrimitives.WriteUInt16BigEndian(bti.AsSpan(4),(ushort)l.Height);bti[0x18]=1;BinaryPrimitives.WriteInt32BigEndian(bti.AsSpan(0x1c),32);Array.Copy(asset.Bytes,l.Offset,bti,32,l.Length);return BtiTexture.Read(bti).Rgba; +} +using var rectangular=new RasterImage(8,2,new Rgba32(240,80,16,255)); +var rgba=StreamableTextures.Encode(rectangular,new(){Mipmaps=true,Format=StreamableTextureFormat.Rgba8});var desc=StreamableTextureDescriptor.Read(rgba.Bytes); +Check(desc.Count==4&&desc.GetLevel(3).Width==1&&desc.GetLevel(3).Height==1,"rectangular mip chain clamps each axis"); +Check(desc.GetLevel(desc.CoarseIndex).Offset==Int(rgba.Bytes,36),"coarsest payload is physically first"); +for(int i=0;iStreamableTextures.Encode(alpha,new(){Format=StreamableTextureFormat.Cmpr}),"explicit CMPR rejects smooth alpha"); +using var binary=new RasterImage(8,8,new Rgba32(255,0,0,255));for(int y=0;y<8;y++)for(int x=0;x<4;x++)binary[x,y]=new Rgba32(0,0,255,0); +var coverage=StreamableTextures.Encode(binary,new(){Mipmaps=true,Format=StreamableTextureFormat.Cmpr});var cd=StreamableTextureDescriptor.Read(coverage.Bytes);for(int i=0;ipixels[n*4+3]==255);Check(Math.Abs(covered-l.Width*l.Height*.5)<=.5,"binary alpha coverage retained");} +Invalid(()=>StreamableTextures.Encode(high,new(){Mipmaps=true}),"NPOT full mip source rejected");Invalid(()=>StreamableTextures.Encode(rectangular,new(){Mipmaps=true,LogicalLevels=new[]{0,0}}),"duplicate sparse entries rejected"); +foreach(int at in new[]{0,4,8,24,28,32,36,40,44,48,52,56,60}){var broken=(byte[])rgba.Bytes.Clone();Put(broken,at,-1);Reject(()=>StreamableTextureDescriptor.Read(broken),"corrupt fixed-header field rejected");} +foreach(int at in new[]{64,68,72,76,80,84,92}){var broken=(byte[])rgba.Bytes.Clone();Put(broken,at,-1);MetadataCrc(broken);Reject(()=>StreamableTextureDescriptor.Read(broken),"bad indexed entry rejected with valid metadata CRC");} +var invalidUv=(byte[])gutter.Bytes.Clone();Put(invalidUv,Int(invalidUv,48),0x7fc00000);MetadataCrc(invalidUv);Reject(()=>StreamableTextureDescriptor.Read(invalidUv),"NaN UV rejected"); +var corrupt=(byte[])rgba.Bytes.Clone();corrupt[desc.GetLevel(0).Offset]^=1;var intact=StreamableTextureDescriptor.Read(corrupt);Check(!intact.ValidatePayload(0,corrupt,intact.GetLevel(0).Offset),"corrupted payload never passes level validation"); +Reject(()=>StreamableTextureDescriptor.Read(prefix,rgba.Bytes.Length+32),"actual/declared file length mismatch"); +for(int i=0;iStreamableTextureDescriptor.Read(prefix[..i],rgba.Bytes.Length),"all truncated metadata prefixes rejected"); +var random=new Random(7319);for(int i=0;i<2000;i++){var fuzz=(byte[])rgba.Bytes.Clone();int at=random.Next(desc.MetadataBytes);fuzz[at]^=(byte)(1<Exenet8.0enableenable diff --git a/tools/DolphinDotNet.Assets/Program.cs b/tools/DolphinDotNet.Assets/Program.cs index a794d6900..7945408bb 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 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]\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") @@ -28,6 +28,7 @@ AudioConverter.Convert(args[1], args[2], sidecar, loop, rate, ffmpeg); return 0; } + if(args.Length>0&&args[0]=="texture"&&Array.IndexOf(args,"--streamable")>=0){StreamableTextureCommand.Run(args);return 0;} if(args.Length>=3&&(args[0]=="texture"||args[0]=="font")) { using var image=DolphinDotNet.Imaging.RasterImage.Load(File.ReadAllBytes(args[1])); diff --git a/tools/DolphinDotNet.Assets/StreamableTextureCommand.cs b/tools/DolphinDotNet.Assets/StreamableTextureCommand.cs new file mode 100644 index 000000000..05256d137 --- /dev/null +++ b/tools/DolphinDotNet.Assets/StreamableTextureCommand.cs @@ -0,0 +1,34 @@ +using System.Security.Cryptography; +using System.Text.Json; +using System.Text.Json.Nodes; +using DolphinDotNet.Imaging; +namespace DolphinDotNet.Assets; + +internal static class StreamableTextureCommand +{ + internal static void Run(string[] args) + { + var options=new StreamableTextureOptions();var positional=new List();string? low=null,high=null;bool pair=false; + for(int i=1;i=args.Length)throw new ArgumentException("Missing value for "+args[i-1]);return args[i];} + switch(args[i]){ + case "--streamable":break; + case "--mipmaps":options.Mipmaps=true;break; + case "--quality-pair":pair=true;break; + case "--low":low=Value();break;case "--high":high=Value();break; + case "--min-size":options.MinimumSize=int.Parse(Value());break; + case "--gutter":options.Gutter=int.Parse(Value());break; + case "--levels":options.LogicalLevels=Value().Split(',').Select(int.Parse).ToArray();break; + case "--format":options.Format=Value() switch {"auto"=>StreamableTextureFormat.Auto,"rgba8"=>StreamableTextureFormat.Rgba8,"cmpr"=>StreamableTextureFormat.Cmpr,_=>throw new ArgumentException("Format must be auto, rgba8 or cmpr.")};break; + default:if(args[i].StartsWith("--",StringComparison.Ordinal))throw new ArgumentException("Unknown texture option "+args[i]);positional.Add(args[i]);break; + } + } + if(pair?(low==null||high==null||positional.Count!=1):(low!=null||high!=null||positional.Count!=2))throw new ArgumentException("Use texture INPUT OUTPUT --streamable [--mipmaps], or texture --low LOW --high HIGH OUTPUT --streamable --quality-pair."); + string input=pair?high!:positional[0],output=positional[pair?0:1];byte[] source=File.ReadAllBytes(input);using var image=RasterImage.Load(source,true); + byte[]? lowSource=low==null?null:File.ReadAllBytes(low);using var lowImage=lowSource==null?null:RasterImage.Load(lowSource,true); + var asset=StreamableTextures.Encode(image,options,lowImage);var manifest=JsonNode.Parse(asset.Manifest)!.AsObject(); + manifest["sourceFileSha256"]=Convert.ToHexString(SHA256.HashData(source)).ToLowerInvariant(); + if(lowSource!=null)manifest["lowFileSha256"]=Convert.ToHexString(SHA256.HashData(lowSource)).ToLowerInvariant(); + File.WriteAllBytes(output,asset.Bytes);File.WriteAllText(output+".manifest.json",manifest.ToJsonString(new JsonSerializerOptions{WriteIndented=true})+"\n"); + } +} diff --git a/tools/DolphinDotNet.Assets/StreamableTextures.cs b/tools/DolphinDotNet.Assets/StreamableTextures.cs new file mode 100644 index 000000000..9eacf3755 --- /dev/null +++ b/tools/DolphinDotNet.Assets/StreamableTextures.cs @@ -0,0 +1,140 @@ +using System.Buffers.Binary; +using System.Security.Cryptography; +using System.Text.Json; +using Dolphin.Formats; +using DolphinDotNet.Imaging; + +namespace DolphinDotNet.Assets; + +public enum StreamableTextureFormat { Auto, Rgba8, Cmpr } +public sealed class StreamableTextureOptions +{ + public bool Mipmaps {get;set;} + public int MinimumSize {get;set;}=1; + public int[]? LogicalLevels {get;set;} + public int Gutter {get;set;} + public StreamableTextureFormat Format {get;set;}=StreamableTextureFormat.Auto; +} +public sealed class StreamableTextureAsset +{ + public byte[] Bytes {get;} + public string Manifest {get;} + internal StreamableTextureAsset(byte[] bytes,string manifest){Bytes=bytes;Manifest=manifest;} +} + +/// Deterministic independent GX image levels. DNTX authoring is unchanged. +public static class StreamableTextures +{ + private sealed record Level(int Lod,int Width,int Height,byte[] Bytes,TextureLodUv Uv); + private static void Put(byte[] bytes,int at,int value)=>BinaryPrimitives.WriteInt32LittleEndian(bytes.AsSpan(at,4),value); + private static void Float(byte[] bytes,int at,float value)=>Put(bytes,at,BitConverter.SingleToInt32Bits(value)); + private static bool PowerOfTwo(int x)=>x>0&&(x&(x-1))==0; + private static void Dimensions(RasterImage image) + {if(image.Width>1024||image.Height>1024)throw new ArgumentException("Streamable textures are limited to 1024 texels per axis.");} + private static bool SmoothAlpha(RasterImage image) + {for(int y=0;y=128)count++;return count;} + private static string Hash(RasterImage image) + { + byte[] pixels=new byte[image.Width*image.Height*4];int at=0; + for(int y=0;y0&&above+histogram[threshold]threshold||(p.A==threshold&&ties-->0); + image[x,y]=new Rgba32(p.R,p.G,p.B,opaque?(byte)255:(byte)0); + } + } + public static StreamableTextureAsset Encode(RasterImage high,StreamableTextureOptions? options=null,RasterImage? low=null) + { + ArgumentNullException.ThrowIfNull(high);options??=new StreamableTextureOptions();Dimensions(high);if(low!=null)Dimensions(low); + if(options.Gutter<0||options.Gutter>16||!PowerOfTwo(options.MinimumSize)||options.MinimumSize>1024||!Enum.IsDefined(options.Format))throw new ArgumentException("Invalid streamable texture options."); + if(low!=null&&(options.Mipmaps||options.LogicalLevels!=null||options.MinimumSize!=1))throw new ArgumentException("Quality pairs do not synthesize intermediate mips."); + if(options.Mipmaps&&(!PowerOfTwo(high.Width)||!PowerOfTwo(high.Height)))throw new ArgumentException("Mip dimensions must be powers of two."); + if(!options.Mipmaps&&(options.LogicalLevels!=null||options.MinimumSize!=1))throw new ArgumentException("Mip selection requires --mipmaps."); + bool smooth=SmoothAlpha(high)||(low!=null&&SmoothAlpha(low)); + if(smooth&&options.Format==StreamableTextureFormat.Cmpr)throw new ArgumentException("CMPR cannot preserve smooth alpha; choose RGBA8 or auto."); + int format=options.Format==StreamableTextureFormat.Rgba8||smooth?6:14; + var levels=new List();int flags=low!=null?4:options.Mipmaps?1:0; + int fullCount=1,edge=Math.Max(high.Width,high.Height);while(edge>1){edge/=2;fullCount++;} + if(options.MinimumSize>Math.Max(high.Width,high.Height))throw new ArgumentException("Minimum size exceeds the source."); + int[]? selected=options.LogicalLevels; + if(selected!=null){if(selected.Length==0||selected.Distinct().Count()!=selected.Length||selected.Any(l=>l<0||l>=fullCount))throw new ArgumentException("Invalid sparse logical levels.");selected=selected.OrderBy(l=>l).ToArray();} + RasterImage current=high;int lod=0,covered=Opaque(high),sourcePixels=high.Width*high.Height; + try{ + while(true){ + if(selected==null||Array.IndexOf(selected,lod)>=0)levels.Add(Pack(current,lod,format,options.Gutter)); + if(low!=null){levels.Add(Pack(low,1,format,options.Gutter));break;} + if(!options.Mipmaps||current.Width==1&¤t.Height==1||Math.Max(current.Width,current.Height)<=options.MinimumSize)break; + var next=Half(current);if(format==14)Coverage(next,covered,sourcePixels); + if(current!=high)current.Dispose();current=next;lod++; + } + }finally{if(current!=high)current.Dispose();} + if(levels.Count==0||selected!=null&&levels.Count!=selected.Length)throw new ArgumentException("Sparse levels lie below the minimum-size cutoff."); + if(options.Mipmaps&&(levels.Count!=fullCount||levels.Where((level,index)=>level.Lod!=index).Any()))flags|=2; + int metadata=64+levels.Count*32+(options.Gutter==0?0:levels.Count*16),dataOffset=(metadata+31)&~31; + int total=dataOffset+levels.Sum(l=>l.Bytes.Length);byte[] bytes=new byte[total]; + Put(bytes,0,0x544c4e44);Put(bytes,4,1);Put(bytes,8,flags);Put(bytes,12,high.Width);Put(bytes,16,high.Height);Put(bytes,20,format);Put(bytes,24,levels.Count);Put(bytes,28,levels.Count-1);Put(bytes,32,64);Put(bytes,36,dataOffset);Put(bytes,40,total); + int uvOffset=options.Gutter==0?0:64+levels.Count*32;Put(bytes,48,uvOffset);Put(bytes,52,uvOffset==0?0:levels.Count*16); + int at=dataOffset; + for(int i=levels.Count-1;i>=0;i--){ + var level=levels[i];int entry=64+i*32;Put(bytes,entry,level.Lod);BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(entry+4),(ushort)level.Width);BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(entry+6),(ushort)level.Height);Put(bytes,entry+8,format);Put(bytes,entry+16,at);Put(bytes,entry+20,level.Bytes.Length);Put(bytes,entry+24,(int)StreamableTextureDescriptor.ComputeCrc32(level.Bytes,0,level.Bytes.Length)); + if(uvOffset!=0){int u=uvOffset+i*16;Float(bytes,u,level.Uv.ScaleU);Float(bytes,u+4,level.Uv.ScaleV);Float(bytes,u+8,level.Uv.OffsetU);Float(bytes,u+12,level.Uv.OffsetV);} + level.Bytes.CopyTo(bytes,at);at+=level.Bytes.Length; + } + Put(bytes,44,(int)StreamableTextureDescriptor.ComputeCrc32(bytes,64,metadata-64)); + var descriptor=StreamableTextureDescriptor.Read(bytes,total); + string manifest=JsonSerializer.Serialize(new{format="DNLT",version=1,logicalWidth=high.Width,logicalHeight=high.Height,gxFormat=format,qualityPair=low!=null,alphaDecision=smooth?"rgba8-smooth-alpha":format==14?"cmpr-binary-alpha-coverage":"rgba8",gutter=options.Gutter,sourceRgbaSha256=Hash(high),lowRgbaSha256=low==null?null:Hash(low),levels=Enumerable.Range(0,descriptor.Count).Select(i=>{var l=descriptor.GetLevel(i);return new{logicalLod=l.LogicalLod,width=l.Width,height=l.Height,offset=l.Offset,bytes=l.Length,crc32=l.Crc32,scaleU=l.Uv.ScaleU,scaleV=l.Uv.ScaleV,offsetU=l.Uv.OffsetU,offsetV=l.Uv.OffsetV};})},new JsonSerializerOptions{WriteIndented=true})+"\n"; + return new StreamableTextureAsset(bytes,manifest); + } + private static Level Pack(RasterImage image,int lod,int format,int gutter) + { + int w=image.Width+2*gutter,h=image.Height+2*gutter;byte[] bytes=new byte[StreamableTextureDescriptor.NativeByteCount(w,h,format)]; + Rgba32 Pixel(int x,int y)=>image[Math.Clamp(x-gutter,0,image.Width-1),Math.Clamp(y-gutter,0,image.Height-1)]; + int at=0; + if(format==6){ + for(int y=0;y(ushort)((p.R>>3)<<11|(p.G>>2)<<5|(p.B>>3)); + private static Rgba32 Color(int c)=>new((byte)(((c>>11)&31)*255/31),(byte)(((c>>5)&63)*255/63),(byte)((c&31)*255/31),255); + private static int Distance(Rgba32 a,Rgba32 b)=>(a.R-b.R)*(a.R-b.R)+(a.G-b.G)*(a.G-b.G)+(a.B-b.B)*(a.B-b.B); + private static void Compress(Rgba32[] pixels,byte[] output,int at) + { + bool transparent=false;int low=65535,high=0,covered=0; + foreach(var p in pixels){if(p.A==0){transparent=true;continue;}int c=Color(p);low=Math.Min(low,c);high=Math.Max(high,c);covered++;} + if(covered==0){low=high=0;transparent=true;} + int c0=transparent?low:high,c1=transparent?high:low; + if(!transparent&&c0==c1){if(c0<65535)c0++;else c1--;} + var a=Color(c0);var b=Color(c1);var palette=new[]{a,b,new Rgba32((byte)((a.R*(transparent?1:2)+b.R)/(transparent?2:3)),(byte)((a.G*(transparent?1:2)+b.G)/(transparent?2:3)),(byte)((a.B*(transparent?1:2)+b.B)/(transparent?2:3)),255),new Rgba32((byte)((a.R+b.R*2)/3),(byte)((a.G+b.G*2)/3),(byte)((a.B+b.B*2)/3),255)}; + uint bits=0;foreach(var p in pixels){int choice=3;if(p.A!=0){choice=0;int distance=Distance(p,palette[0]);for(int i=1;i<(transparent?3:4);i++){int d=Distance(p,palette[i]);if(d