diff --git a/.github/workflows/nuget-preview.yml b/.github/workflows/nuget-preview.yml index e911eb5..eebae3b 100644 --- a/.github/workflows/nuget-preview.yml +++ b/.github/workflows/nuget-preview.yml @@ -26,6 +26,14 @@ jobs: version: ${{ steps.version.outputs.version }} steps: - uses: actions/checkout@v4 + - id: sdk + run: echo "revision=$(cat .sdk-revision)" >> "$GITHUB_OUTPUT" + - uses: actions/checkout@v4 + if: github.event_name == 'pull_request' + with: + repository: capz/DolphinDotNet + ref: ${{ steps.sdk.outputs.revision }} + path: vendor/sdk - uses: actions/setup-dotnet@v4 with: dotnet-version: '8.0.x' @@ -35,7 +43,11 @@ jobs: - id: version run: echo "version=0.1.0-preview.${GITHUB_RUN_NUMBER}.${GITHUB_RUN_ATTEMPT}" >> "$GITHUB_OUTPUT" - name: Pack against the published SDK + if: github.event_name != 'pull_request' run: python3 eng/pack.py --version '${{ steps.version.outputs.version }}' + - name: Verify the exact pinned SDK before its release + if: github.event_name == 'pull_request' + run: python3 eng/pack.py --sdk-source vendor/sdk --version '${{ steps.version.outputs.version }}' - name: Verify relocated packages and external consumers run: python3 tests/nuget_consumer.py --workspace "$RUNNER_TEMP/external engine consumer" --native - uses: actions/upload-artifact@v4 @@ -44,6 +56,7 @@ jobs: path: | out/packages/*.nupkg out/packages/packages.json + out/packages/sdk-feed/*.nupkg if-no-files-found: error publish: if: startsWith(github.ref, 'refs/tags/nuget-preview-') || (github.event_name == 'workflow_dispatch' && inputs.publish && github.ref == 'refs/heads/main') @@ -70,6 +83,7 @@ jobs: env: NUGET_API_KEY: ${{ steps.nuget-login.outputs.NUGET_API_KEY }} run: | + python3 -c 'import json; assert not json.load(open("packages/packages.json")).get("sdkSourcePreview"), "Publish the pinned SDK before distributing engine packages"' test -n "$NUGET_API_KEY" dotnet nuget push packages/Capz.Hypercube.Core.*.nupkg --source https://api.nuget.org/v3/index.json --api-key "$NUGET_API_KEY" --skip-duplicate dotnet nuget push packages/Capz.Hypercube.GameCube.*.nupkg --source https://api.nuget.org/v3/index.json --api-key "$NUGET_API_KEY" --skip-duplicate diff --git a/.github/workflows/progressive-textures.yml b/.github/workflows/progressive-textures.yml index f2aba39..3abc9cd 100644 --- a/.github/workflows/progressive-textures.yml +++ b/.github/workflows/progressive-textures.yml @@ -5,8 +5,16 @@ permissions: jobs: contracts: runs-on: ubuntu-24.04 + timeout-minutes: 25 steps: - uses: actions/checkout@v4 + - id: sdk + run: echo "revision=$(cat .sdk-revision)" >> "$GITHUB_OUTPUT" + - uses: actions/checkout@v4 + with: + repository: capz/DolphinDotNet + ref: ${{ steps.sdk.outputs.revision }} + path: vendor/sdk - uses: actions/setup-dotnet@v4 with: dotnet-version: 8.0.x @@ -14,6 +22,44 @@ jobs: with: python-version: '3.12' - run: python3 tests/progressive_fixtures.py - - run: python3 -m unittest discover -s tests -p test_progressive_textures.py + - run: python3 -m unittest discover -s tests -p 'test_progressive*.py' - run: dotnet run --project tests/TextureFamilies.Tests -c Debug - run: dotnet run --project tests/TextureFamilies.Tests -c Release + - run: python3 tools/test_progressive_runtime.py + dolphin: + runs-on: ubuntu-24.04 + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + configuration: [Debug, Release] + steps: + - uses: actions/checkout@v4 + - id: sdk + run: echo "revision=$(cat .sdk-revision)" >> "$GITHUB_OUTPUT" + - uses: actions/checkout@v4 + with: + repository: capz/DolphinDotNet + ref: ${{ steps.sdk.outputs.revision }} + path: vendor/sdk + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: 8.0.x + - run: tools/build_progressive.sh + env: + CONFIGURATION: ${{ matrix.configuration }} + - run: docker build -t hypercube-progressive -f tools/Dockerfile.dolphin . + - run: >- + docker run --rm --init --shm-size=1g + --mount "type=bind,src=$PWD,dst=/work" -w /work hypercube-progressive + python3 tools/progressive_validation.py out/native-progressive-${{ matrix.configuration }}/Game.dol + --disc out/progressive/textures.iso --logs out/dolphin-progressive-${{ matrix.configuration }} --seconds 60 + - uses: actions/upload-artifact@v4 + if: always() + with: + name: progressive-${{ matrix.configuration }} + path: | + out/dolphin-progressive-${{ matrix.configuration }}/results.json + out/dolphin-progressive-${{ matrix.configuration }}/states.json + out/dolphin-progressive-${{ matrix.configuration }}/*.png + out/dolphin-progressive-${{ matrix.configuration }}/*.log diff --git a/.github/workflows/validation.yml b/.github/workflows/validation.yml index 6c8471c..87e33bc 100644 --- a/.github/workflows/validation.yml +++ b/.github/workflows/validation.yml @@ -18,10 +18,12 @@ jobs: configuration: [Debug, Release] steps: - uses: actions/checkout@v4 + - id: sdk + run: echo "revision=$(cat .sdk-revision)" >> "$GITHUB_OUTPUT" - uses: actions/checkout@v4 with: repository: capz/DolphinDotNet - ref: f5dbd0a69c762708875890b5be73116f64589e4b + ref: ${{ steps.sdk.outputs.revision }} path: vendor/sdk - uses: actions/setup-dotnet@v4 with: diff --git a/.sdk-revision b/.sdk-revision index 0fca589..2918621 100644 --- a/.sdk-revision +++ b/.sdk-revision @@ -1 +1 @@ -858577c63aaf191fce7c83fd4308075d3775f43a +dd8a187b9c35d526b479511846a92bef5873fb29 diff --git a/docs/measurements/progressive/coarse.png b/docs/measurements/progressive/coarse.png new file mode 100644 index 0000000..e5992b5 Binary files /dev/null and b/docs/measurements/progressive/coarse.png differ diff --git a/docs/measurements/progressive/fine-dual-uv.png b/docs/measurements/progressive/fine-dual-uv.png new file mode 100644 index 0000000..4384cf0 Binary files /dev/null and b/docs/measurements/progressive/fine-dual-uv.png differ diff --git a/docs/measurements/progressive/phase-four-dolphin.json b/docs/measurements/progressive/phase-four-dolphin.json new file mode 100644 index 0000000..36ccedd --- /dev/null +++ b/docs/measurements/progressive/phase-four-dolphin.json @@ -0,0 +1,54 @@ +{ + "platform": "Dolphin", + "hardwarePerformanceClaim": false, + "sampledFrames": 325, + "last": { + "magic": 18516, + "phase": 10, + "frame": 1945, + "publications": 8, + "crcFailures": 1, + "failures": 2, + "stale": 25, + "active32": 0, + "upload32": 0, + "retired32": 0, + "aram32": 0, + "coarseMask": 15, + "deferred": 2, + "retirements": 8, + "frame99ms": 17, + "aramHits": 25, + "detailMask": 0, + "peakKiB": 652, + "audioActive": 1, + "coarseReady": 5, + "detailReady": 7, + "coarseMeanMs": 164, + "detailMeanMs": 203, + "maxPumpUs": 2378, + "storageKiB": 1190, + "coldKiB": 14, + "uploadedKiB": 1171, + "cancelled": 26, + "frame95ms": 17, + "readBufferKiB": 0, + "poolBytes": 0, + "checksum": 17474 + }, + "coarsePixelFrames": 5, + "fineDualUvPixelFrames": 9, + "pixelPatches": 12, + "audio": [ + { + "file": "ID-Game_2026-11-11_12-17-39_dspdump1.wav", + "seconds": 32.675180050788896, + "activeWindows": 327, + "longestQuietMs": 0 + } + ], + "implementationRevision": "334e80307cb9b54f6009aa4e1286c5083a2fc4d8", + "sdkRevision": "dd8a187b9c35d526b479511846a92bef5873fb29", + "dolSha256": "30a1d1bd7bc3dc24ade989a04e5d173f82a4f070d2eb4189aff2c833aa579cb6", + "packSha256": "1ad90536c358b56ed773c9f822231fc0026b8765608460a723ba404d131bfcad" +} diff --git a/docs/progressive-textures.md b/docs/progressive-textures.md index 07570a0..a8a1e3d 100644 --- a/docs/progressive-textures.md +++ b/docs/progressive-textures.md @@ -68,3 +68,110 @@ Run `python3 tests/progressive_fixtures.py`, `python3 -m unittest discover -s tests -p test_progressive_textures.py` and `dotnet run --project tests/TextureFamilies.Tests -c Release` for format, corruption, alpha-preserving native import, selection and request-churn checks. + +## Streaming and draw ownership + +```csharp +using var source = new PackedAssetSource("dvd:/materials.hcp"); +using var lods = new TextureLodStreamer(source.Catalog, source.Assets, + budgetBytes: 2 * 1024 * 1024); +var grass = lods.Get("terrain/grass", TextureQualityPolicy.DistanceMip); +var draw = new StreamedMaterialBinding(lods, authoredMaterial, grass); + +// Each frame, between GPU submissions: +lods.BeginFrame(frame, completedFrame); +lods.Demand(grass, TextureFootprint.Project(width, height, distance, radius, + fovDegrees, viewportHeight, repeatsU, repeatsV)); +lods.Pump(uploadBudgetBytes: 32768, cpuBudgetUs: 1000); +device.BeginFrame(clear); +renderer.Begin3D(camera); +draw.Draw(renderer, meshWithNormalizedUvs, transform, frame); +renderer.End3D(); +lods.EndFrame(device.InsertFence()); +device.EndFrame(); +``` + +Resolve/pin at actual submission; keep bindings in queued commands and resolve +when executing them. `SortKey()` includes both family identities and resident +generations; refresh it each frame and combine it with effect/blend/material +state. A stale `ResolvedTextureLod` fails `Pin`. The binding copies its shared +template's state into a private material and composes authored animation before +the resident level's usable UV rectangle for both texture slots. The complete +affine matrix preserves rotated animation with unequal U/V gutters. + +Geometry uses normalized source UVs. Repeated standalone textures should have +no atlas gutter; a padded atlas rectangle expects coordinates within that +rectangle (split tiled geometry at repeat boundaries). GX repeat wraps the +whole physical image. `TerrainUv` exposes the old tile mapping for normalized +terrain meshes without baking a selected texture level into geometry. + +Every family becomes usable at coarse first. An upgrade is queued only after +the coarse image was pinned into a submitted frame. One private destination is +read in bounded native chunks, staged by the SDK service executor, checked by +incremental CRC, and published on the application executor. Cancellation joins +reads, copies and ARAM users before reusing the staging buffer or freeing the +destination. A superseded scheduler generation cannot publish. Budget rejection, +CRC failure and short reads preserve the old image and use scheduler retry +backoff. GPU fences, rather than promotion-time GPU waits, retire old images. + +`ActiveBytes`, `UploadBytes`, `ReadBufferBytes`, `RetiredBytes`, `PoolBytes`, +`PhysicalBytes` and `AramBytes` are separate counters. Standalone streams own a +32-KiB native read buffer; a world-integrated stream shares the existing 128-KiB +buffer. The physical cap includes transient destination, retired images and +placeholder. ARAM has its own cap and is not GX-visible memory. `PeakBytes` +records physical texture peaks; counts include the minimum native tile padding. +The byte budget bounds each chunk; the CPU budget bounds issuing more work. +A single native allocation, CRC slice or copy cannot be preempted. + +The optional ARAM tier retains complete records that fit a single read chunk; +larger images remain on storage. In-flight stores/fetches cannot be evicted. +`StrictReleaseColdCopies` removes superseded cold copies as well as MEM1 images. +`TrimUnwanted` frees undemanded images after their final fence. Shutdown calls +`Stop()` while continuing application pumping and completed frame fences, then +`Dispose()`; disposal refuses outstanding transfer/GPU ownership. Explicit trim +and final fences reduce unwanted image, read-buffer, placeholder and ARAM bytes +to zero. + +## Shared world scheduling + +An HCPK v2 `PackedWorld` exposes `WorldStreamer.TextureLods`. Use the world's +`BeginDemand`, `Pump`, `Frame` and `CompletedFrame`, and forward each submitted +frame fence through `WorldStreamer.EndFrame`. Family demand shares the existing +`ResourceScheduler`, `AssetStream`, staging buffer and `AramCache`. Gameplay and +collision can preempt between large texture chunks. Missing visible coarse +images precede upgrades; upgrade ties use projected error before FIFO age. + +`WorldStreamer(..., normalizedTextureUvs: true)` opts dynamic terrain geometry +into normalized tile/atlas coordinates; use streamed material mappings at draw +time. Permanent v1 fallback meshes retain their original mapping. The v1-only +fixed-size `TexturePool`, validation path and its historical accounting remain +unchanged. A v2 world's `PhysicalBytes`/`PeakPhysicalBytes` also count permanent +world meshes and textures plus shared staging. Promotions never evict a demanded +family's fallback simply to obtain replacement headroom. + +## Validation and SDK availability + +The SDK source pin includes the reviewed streamable assets and detached-upload +PRs. Build source checkouts using `.sdk-revision`. Before that SDK revision has +a public NuGet release, `python3 eng/pack.py --sdk-source vendor/sdk --version +0.1.0-preview.local.1` creates an exact-revision SDK dependency feed for isolated +consumer validation. Its manifest marks these as source-preview artifacts; +publication refuses them. Public engine distribution requires publishing the +pinned SDK and updating `DolphinDotNetPackageVersion` first. + +`python3 tools/test_progressive_runtime.py` executes standalone and mixed-world +scenarios in Debug and Release through actual SDK AOT, native storage/graphics, +ARAM and GC stress. It covers coarse presentation, CRC/short-read failures, +generation churn, both material slots, pressure rejection, physical accounting, +collision preemption during >128-KiB upgrades, and complete shutdown. The +standalone path permits only five resource-cleanup waits and the AOT device +shutdown wait, with none during texture replacement. + +`tools/build_progressive.sh` builds the PowerPC fixture and data ISO. +`python3 tools/progressive_validation.py Game.dol --disc textures.iso --logs +out/fresh-capture --seconds 60` checks independent coarse/fine pixel patches, +rotated gutter UVs in both texture slots, request reversal, live DSP audio, +failure/retirement counters, and zero bytes after final trim. It records p95/p99 +frame times and readiness latency as emulator observations, with an explicit +`hardwarePerformanceClaim: false` marker. Real GameCube SD2SP2/disc/audio pressure +and latency gates still require physical-console captures. diff --git a/eng/pack.py b/eng/pack.py index 57eed08..059a4d3 100644 --- a/eng/pack.py +++ b/eng/pack.py @@ -11,7 +11,7 @@ IDS=('Capz.Hypercube.Core','Capz.Hypercube.GameCube') def run(*args):subprocess.run(args,cwd=ROOT,check=True) -def inspect(package,identity,version): +def inspect(package,identity,version,sdk_version=None): with ZipFile(package) as z: root=ET.fromstring(z.read(identity+'.nuspec'));metadata=next(e for e in root if e.tag.endswith('metadata')) def value(name):return next(e.text for e in metadata if e.tag.endswith('}'+name) or e.tag==name) @@ -22,20 +22,28 @@ def value(name):return next(e.text for e in metadata if e.tag.endswith('}'+name) assert not any(e.startswith('DolphinDotNet') for e in dependencies) if identity==IDS[0] else True if identity==IDS[1]: assert dependencies[IDS[0]]==version,dependencies - sdk=ET.parse(ROOT/'Directory.Build.props').find('.//DolphinDotNetPackageVersion').text + sdk=sdk_version or ET.parse(ROOT/'Directory.Build.props').find('.//DolphinDotNetPackageVersion').text assert dependencies['DolphinDotNet.GameCube']=='['+sdk+']',dependencies assert not any(n.startswith('lib/') and '/DolphinDotNet.' in n for n in z.namelist()) return dependencies def main(): - p=argparse.ArgumentParser(description=__doc__);p.add_argument('--version',required=True);p.add_argument('--output',type=Path,default=ROOT/'out/packages');args=p.parse_args() + p=argparse.ArgumentParser(description=__doc__);p.add_argument('--version',required=True);p.add_argument('--output',type=Path,default=ROOT/'out/packages');p.add_argument('--sdk-source',type=Path,help='Build a test-only dependency feed from the exact pinned SDK before it is published');args=p.parse_args() if not re.fullmatch(r'0\.\d+\.\d+(?:-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?',args.version):p.error('Use a 0.x.y stable or preview NuGet version') output=args.output.resolve();output.mkdir(parents=True,exist_ok=True) commit=subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True).strip() + sdk_revision=(ROOT/'.sdk-revision').read_text().strip();sdk_version=ET.parse(ROOT/'Directory.Build.props').find('.//DolphinDotNetPackageVersion').text;extra=[] + if args.sdk_source: + sdk_root=args.sdk_source.resolve();actual=subprocess.check_output(['git','rev-parse','HEAD'],cwd=sdk_root,text=True).strip() + if actual!=sdk_revision:p.error('SDK checkout must match .sdk-revision exactly') + if subprocess.check_output(['git','status','--porcelain','--untracked-files=no'],cwd=sdk_root,text=True).strip():p.error('Pinned SDK must have no tracked changes') + sdk_version='0.1.0-preview.source.'+sdk_revision[:12];sdk_feed=output/'sdk-feed' + subprocess.run(['python3',str(sdk_root/'eng/pack.py'),'--version',sdk_version,'--output',str(sdk_feed)],cwd=sdk_root,check=True) + extra=['-p:DolphinDotNetPackageVersion='+sdk_version,'-p:RestoreAdditionalProjectSources='+str(sdk_feed)] for identity in IDS: project=ROOT/'src'/identity.removeprefix('Capz.')/(identity.removeprefix('Capz.')+'.csproj') - run('dotnet','pack',str(project),'-c','Release','-o',str(output),'-p:Version='+args.version,'-p:PackageVersion='+args.version,'-p:RepositoryCommit='+commit,'-p:ContinuousIntegrationBuild=true','-p:HypercubeUsePublishedSdk=true') - inspect(output/(identity+'.'+args.version+'.nupkg'),identity,args.version) - (output/'packages.json').write_text(json.dumps({'version':args.version,'commit':commit,'packages':list(IDS)},indent=2)+'\n') + run('dotnet','pack',str(project),'-c','Release','-o',str(output),'-p:Version='+args.version,'-p:PackageVersion='+args.version,'-p:RepositoryCommit='+commit,'-p:ContinuousIntegrationBuild=true','-p:HypercubeUsePublishedSdk=true',*extra) + inspect(output/(identity+'.'+args.version+'.nupkg'),identity,args.version,sdk_version) + (output/'packages.json').write_text(json.dumps({'version':args.version,'commit':commit,'packages':list(IDS),'sdkVersion':sdk_version,'sdkRevision':sdk_revision,'sdkSourcePreview':bool(args.sdk_source)},indent=2)+'\n') print('Engine packages and NuGet dependency metadata verified') if __name__=='__main__':main() diff --git a/samples/ProgressiveTextures/Program.cs b/samples/ProgressiveTextures/Program.cs new file mode 100644 index 0000000..4a4f39a --- /dev/null +++ b/samples/ProgressiveTextures/Program.cs @@ -0,0 +1,21 @@ +using Dolphin.Storage; +using Dolphin.Memory; +using System.Threading.Tasks; +using Dolphin.Audio; + +internal static class Program +{ + static int Main() + { + if(!Aram.Initialize(2*1024*1024))throw new System.Exception("ARAM initialization failed."); + string path=Storage.MountDisc()?"dvd:/world.hcp":"sd:/hypercube/textures.hcp"; + if(!System.IO.File.Exists(path)) + { + Storage.Mount(StorageDevice.SdSerialPort2);path="sd:/hypercube/textures.hcp"; + } + var tone=new byte[8000];for(int i=0;ivoice.IsPlaying); + while(true){scenario.Step();Task.Delay(1).GetAwaiter().GetResult();} + } +} diff --git a/samples/ProgressiveTextures/ProgressiveTextures.csproj b/samples/ProgressiveTextures/ProgressiveTextures.csproj new file mode 100644 index 0000000..8de90ed --- /dev/null +++ b/samples/ProgressiveTextures/ProgressiveTextures.csproj @@ -0,0 +1 @@ +falseExe diff --git a/samples/ProgressiveTextures/TextureRuntimeScenario.cs b/samples/ProgressiveTextures/TextureRuntimeScenario.cs new file mode 100644 index 0000000..10aff5e --- /dev/null +++ b/samples/ProgressiveTextures/TextureRuntimeScenario.cs @@ -0,0 +1,160 @@ +using System; +using Dolphin.Graphics; +using Dolphin.Timing; +using Hypercube; +using Hypercube.GameCube; +using Scheduler=Dolphin.Threading.Tasks.Scheduler; + +// Shared by the console inspection scene and the Debug/Release host AOT test. +internal sealed class TextureRuntimeScenario : IDisposable +{ + private readonly PackedAssetSource source; + private TextureLodStreamer textures; + private readonly GraphicsDevice device=GraphicsDevice.Default; + private readonly Draw2D overlay; + private readonly Renderer renderer=new Renderer(); + private readonly Camera camera=new Camera(); + private readonly Mesh quad; + private readonly GxEffect multiply; + private readonly Transform left=new Transform{LocalPosition=new Vector3(-2,0,0),LocalScale=new Vector3(3,3,1)}; + private readonly Transform right=new Transform{LocalPosition=new Vector3(2,0,0),LocalScale=new Vector3(3,3,1)}; + private readonly StreamedMaterialTexture[] bindings; + private readonly StreamedMaterialBinding primary,dual; + private readonly int[] fields=new int[32]; + private readonly Func? audioPlaying; + private ResolvedTextureLod firstLease; + private int frame,phase,phaseFrame,coarseMask,crcFailures,failures,stale,publications,deferred,peak,retirements,aramHits; + private bool stopped,disposed,shortInjected; + private long previousAt; + private int coarseReadyCount,detailReadyCount,maxPumpUs,storageBytes,coldBytes,uploadedBytes,cancelled; + private long coarseUs,detailUs; + public readonly FrameMetrics Frames=new FrameMetrics(); + public bool Done=>phase==10; + private static void Check(bool value,string message){if(!value)throw new InvalidOperationException(message);} + private static VertexPositionNormalColorTexture V(float x,float y,float u,float v)=>new VertexPositionNormalColorTexture(new Vector3(x,y,0),new Vector3(0,0,1),Color32.White,new Vector2(u,v)); + internal TextureRuntimeScenario(string path,Func? audioPlaying=null) + { + this.audioPlaying=audioPlaying; + source=new PackedAssetSource(path);textures=new TextureLodStreamer(source.Catalog,source.Assets){UseAram=true}; + bindings=new[]{textures.Get("terrain/rgba",TextureQualityPolicy.CoarseOnly),textures.Get("objects/cmpr",TextureQualityPolicy.CoarseOnly),textures.Get("faces/pair",TextureQualityPolicy.CoarseOnly),textures.Get("single",TextureQualityPolicy.CoarseOnly)}; + var rotation=new UvTransform(new Vector2(1,0),new Vector2(1,1),90); + var material=new Material{Cull=CullMode.None,TextureTransform=rotation,SecondaryTextureTransform=rotation,DepthTest=false,DepthWrite=false}; + var program=new TevProgramBuilder();program.AddStage(TevInput.Zero,TevInput.Raster,TevInput.Texture,TevInput.Zero);program.AddStage(TevInput.Zero,TevInput.Previous,TevInput.SecondaryTexture,TevInput.Zero);multiply=program.CreateEffect(); + var two=new Material{Cull=CullMode.None,TextureTransform=rotation,SecondaryTextureTransform=rotation,DepthTest=false,DepthWrite=false,Effect=multiply}; + primary=new StreamedMaterialBinding(textures,material,bindings[0]);dual=new StreamedMaterialBinding(textures,two,bindings[1],bindings[0]); + quad=Mesh.Create(new[]{V(-.5f,.5f,0,0),V(.5f,.5f,1,0),V(.5f,-.5f,1,1),V(-.5f,.5f,0,0),V(.5f,-.5f,1,1),V(-.5f,-.5f,0,1)}); + overlay=new Draw2D(device);camera.LookAt(new Vector3(0,0,5),Vector3.Zero,new Vector3(0,1,0));camera.SetOrthographic(8,6,.1f,100); + } + private bool AllReady(bool detail) + {for(int i=0;i=30) + {bindings[0].Policy=TextureQualityPolicy.FullQuality;textures.CorruptNextChunk=true;Next(2);} + else if(phase==2&&textures.ChecksumFailures>0) + { + Check(textures.Resolve(bindings[0]).Texture==firstLease.Texture,"CRC failure evicted fallback."); + textures.ShortNextRead=true;shortInjected=true;Next(3); + } + else if(phase==3&&textures.DetailReady(1)) + { + Check(shortInjected&&textures.Failures>=2,"Short read or CRC failure was not isolated."); + Check(!textures.Pin(firstLease,frame),"Stale raw texture lease remained valid."); + for(int i=0;i=60)Next(5);} + else if(phase==5) + { + camera.LookAt(new Vector3((float)Math.Sin(frame*.1)*2,(float)Math.Cos(frame*.07),5),Vector3.Zero,new Vector3(0,1,0)); + bindings[0].Policy=(frame-phaseFrame)%4<2?TextureQualityPolicy.CoarseOnly:TextureQualityPolicy.FullQuality; + Check(textures.CoarseReady(1),"Camera reversal lost visible fallback."); + if(frame-phaseFrame>=100){bindings[0].Policy=TextureQualityPolicy.FullQuality;camera.LookAt(new Vector3(0,0,5),Vector3.Zero,new Vector3(0,1,0));Next(6);} + } + else if(phase==6&&AllReady(true)&&frame-phaseFrame>=60) + { + Check(textures.StaleUploads>0&&textures.Cancellations>0,"Churn did not drain stale work."); + int active=0;for(int i=0;i0,"ARAM retention did not retain cold copies."); + textures.StrictReleaseColdCopies=true;Next(7); + } + else if(phase==8&&textures.Deferred>0&&frame-phaseFrame>=60) + {Check(textures.ResidentIndex(1)==bindings[0].Family.CoarseIndex,"Pressure evicted coarse to start a promotion.");Next(9);} + } + if(phase==7||phase==9) + { + if(textures.Stop()) + { + textures.Cold.Trim();Check(textures.Cold.Bytes==0,"Cold copies survived strict trim.");Snapshot();textures.Dispose();Check(textures.PhysicalBytes==0,"Native bytes survived final fence/trim.");stopped=true; + if(phase==7) + { + textures=new TextureLodStreamer(source.Catalog,source.Assets,128*1024){StrictReleaseColdCopies=true};stopped=false; + textures.BeginFrame(frame,Math.Max(0,frame-1)); + bindings[0]=textures.Get("terrain/rgba",TextureQualityPolicy.FullQuality);Next(8); + } + else Next(10); + } + } + device.BeginFrame(new Color32(24,28,36)); + if(phase<7) + {renderer.Begin3D(camera);primary.Draw(renderer,quad,left,frame);dual.Draw(renderer,quad,right,frame);renderer.End3D();} + overlay.Begin(); + if(phase<7) + { + for(int i=2;i>5]|=1u<<(i&31); @@ -55,12 +56,13 @@ private int FirstFree() return -1; } private void Missing(int slot){states[slot]=ResourceState.Missing;freeMasks[slot>>5]|=1u<<(slot&31);} - public int Demand(int id, ResourcePriority priority) + public int Demand(int id, ResourcePriority priority,int projectedError=0) { if(ValidateIdsOnly)catalog.ValidateId(id);else catalog.Get(id); int found = Find(id); if (found >= 0) { + importance[found]=references[found]==0?projectedError:Math.Max(importance[found],projectedError); if (references[found] == 0 || (int)priority < priorities[found]) priorities[found] = (int)priority; references[found]++; if(states[found]==ResourceState.Resident)touched[found]=++order; @@ -77,6 +79,7 @@ public int Demand(int id, ResourcePriority priority) ids[i] = id; lookup[id]=i; states[i] = ResourceState.Queued; priorities[i] = (int)priority; freeMasks[i>>5]&=~(1u<<(i&31)); references[i] = 1; touched[i] = ++order; generations[i] = nextGeneration++; + importance[i]=projectedError; retries[i] = 0; return i; } Rejected++; return -1; @@ -103,13 +106,31 @@ public void CancelUnneeded() } // Records must be adjacent/near-adjacent in the pack. One logical read can // satisfy several independently resident pages, regardless of draw size. - public int BeginBatch(int now, int maxBytes, int maxRecords, int[] slots, out int offset, out int length) + private bool Earlier(int a,int b)=>b<0||priorities[a]importance[b]||importance[a]==importance[b]&&touched[a]0&&retries[i]<=now&& + catalog.Get(ids[i]).Kind!=excludedKind&&Earlier(i,first))first=i; + return first; + } + public void BeginRecord(int slot,int now) + { + if((states[slot]!=ResourceState.Queued&&states[slot]!=ResourceState.Failed)||references[slot]==0||retries[slot]>now)throw new InvalidOperationException("Resource is not eligible for a read."); + states[slot]=ResourceState.Reading; + } + public void RetireResident(int slot) + { + if(states[slot]!=ResourceState.Resident)throw new InvalidOperationException("Resource is not resident."); + ResidentBytes-=pins[slot];pins[slot]=0;references[slot]=0;states[slot]=ResourceState.Retiring;generations[slot]=nextGeneration++;Evicted++; + } + public int BeginBatch(int now, int maxBytes, int maxRecords, int[] slots, out int offset, out int length,int excludedKind=0) { if (maxBytes < 32 || maxRecords < 1 || maxRecords > slots.Length) throw new ArgumentOutOfRangeException("maxBytes"); offset = length = 0; int first = -1; for (int i = 0; i < ids.Length; i++) if ((states[i] == ResourceState.Queued || states[i] == ResourceState.Failed) && - references[i] > 0 && retries[i] <= now && catalog.Get(ids[i]).Length <= maxBytes && - (first < 0 || priorities[i] < priorities[first] || priorities[i] == priorities[first] && touched[i] < touched[first])) first = i; + references[i] > 0 && retries[i] <= now && catalog.Get(ids[i]).Kind!=excludedKind&&catalog.Get(ids[i]).Length <= maxBytes && Earlier(i,first)) first = i; if (first < 0) return 0; var initial = catalog.Get(ids[first]); offset = initial.Offset; length = initial.Length; slots[0] = first; states[first] = ResourceState.Reading; int count = 1; @@ -118,7 +139,7 @@ public int BeginBatch(int now, int maxBytes, int maxRecords, int[] slots, out in { int next = -1, end = offset + length; for (int i = 0; i < ids.Length; i++) if ((states[i] == ResourceState.Queued || states[i] == ResourceState.Failed) && - references[i] > 0 && retries[i] <= now && priorities[i] <= priorities[first]) + references[i] > 0 && retries[i] <= now && priorities[i] <= priorities[first]&&catalog.Get(ids[i]).Kind!=excludedKind) { var r = catalog.Get(ids[i]); if (r.Offset >= end && r.Offset - end <= 32 && r.Length <= maxBytes - (r.Offset - offset) && @@ -130,12 +151,11 @@ public int BeginBatch(int now, int maxBytes, int maxRecords, int[] slots, out in } return count; } - public int RequiredBatchBytes(int now,int configured) + public int RequiredBatchBytes(int now,int configured,int excludedKind=0) { int first=-1; for(int i=0;i0&&retries[i]<=now&&(first<0||priorities[i]0&&retries[i]<=now&&catalog.Get(ids[i]).Kind!=excludedKind&&Earlier(i,first))first=i; if(first<0)return configured; int bytes=catalog.Get(ids[first]).Length; return bytes>configured?bytes:configured; diff --git a/src/Hypercube.GameCube/AramCache.cs b/src/Hypercube.GameCube/AramCache.cs index d03ad19..5f77c2b 100644 --- a/src/Hypercube.GameCube/AramCache.cs +++ b/src/Hypercube.GameCube/AramCache.cs @@ -9,27 +9,44 @@ public sealed class AramCache : IDisposable { private readonly AramBuffer?[] buffers; private readonly int[] touched; + private readonly Task?[] transfers; private int order; public int Bytes {get;private set;} public int Hits,Stores,Evictions; public int Budget {get;} - public AramCache(int records,int budget){buffers=new AramBuffer?[records+1];touched=new int[records+1];Budget=budget;} - public bool Has(int id)=>buffers[id]!=null; + public AramCache(int records,int budget){if(records<1||budget<0)throw new ArgumentOutOfRangeException("records");buffers=new AramBuffer?[records+1];transfers=new Task?[records+1];touched=new int[records+1];Budget=budget;} + private bool Ready(int id) + { + var task=transfers[id];if(task==null)return true;if(!task.IsCompleted)return false; + transfers[id]=null; + try{task.GetAwaiter().GetResult();}catch(Exception){if(buffers[id]!=null){Bytes-=buffers[id]!.Length;buffers[id]!.Dispose();buffers[id]=null;}} + return true; + } + public bool Has(int id)=>Ready(id)&&buffers[id]!=null; + public bool Drop(int id) + { + if(!Ready(id))return false;if(buffers[id]==null)return true; + Bytes-=buffers[id]!.Length;buffers[id]!.Dispose();buffers[id]=null;Evictions++;return true; + } + public int Trim() + {int before=Bytes;for(int i=1;iFetchRange(id,0,target,targetOffset,bytes); + public Task FetchRange(int id,int sourceOffset,NativeBuffer target,int targetOffset,int bytes) { - if(buffers[id]==null)throw new InvalidOperationException("ARAM cache miss."); + if(!Has(id))throw new InvalidOperationException("ARAM cache miss or busy transfer."); touched[id]=++order;Hits++; - return AramTransferQueue.CopyToMainAsync(buffers[id]!,0,target,targetOffset,(bytes+31)&~31); + return transfers[id]=AramTransferQueue.CopyToMainAsync(buffers[id]!,sourceOffset,target,targetOffset,(bytes+31)&~31); } public Task? Store(int id,NativeBuffer source,int sourceOffset,int bytes,int[] protectedIds,int count) { - if(buffers[id]!=null)return null; + if(!Ready(id)||buffers[id]!=null)return null; int size=(bytes+31)&~31; if(size>Budget)return null; while(Bytes+size>Budget) { int victim=-1; - for(int i=1;iBounded header/index bootstrap only. Native payloads are always +/// read asynchronously through Assets, including levels larger than staging. +public sealed class PackedAssetSource : IDisposable +{ + public AssetCatalog Catalog {get;} + public AssetStream Assets {get;} + internal static AssetCatalog ReadCatalog(FileStream file) + { + var first=new byte[32];ReadExact(file,first,0,32); + int version=Binary.I32(first,4);byte[] header=first; + if(version==2){header=new byte[64];Array.Copy(first,header,32);ReadExact(file,header,32,32);} + int size=AssetCatalog.MetadataBytes(header);var metadata=new byte[size];ReadExact(file,metadata,0,size); + return new AssetCatalog(header,metadata,file.Length); + } + private static void ReadExact(FileStream file,byte[] bytes,int offset,int count) + {while(count>0){int n=file.Read(bytes,offset,count);if(n==0)throw new EndOfStreamException();offset+=n;count-=n;}} + public PackedAssetSource(string path) + { + using(var file=new FileStream(path,FileMode.Open,FileAccess.Read,FileShare.Read))Catalog=ReadCatalog(file); + Assets=new AssetStream(path); + } + public void Dispose()=>Assets.Dispose(); +} diff --git a/src/Hypercube.GameCube/PackedWorld.cs b/src/Hypercube.GameCube/PackedWorld.cs index 46990af..b07ed5a 100644 --- a/src/Hypercube.GameCube/PackedWorld.cs +++ b/src/Hypercube.GameCube/PackedWorld.cs @@ -21,6 +21,7 @@ public sealed class PackedWorld : IDisposable public readonly SceneTree Tree = new SceneTree(); public readonly float[] NodeMinY=new float[85],NodeMaxY=new float[85]; public int ParentMeshCount, ParentTriangles; + public int NativeBytes {get;private set;} public float MinY=-1, MaxY=3; public bool VerifiedOccluder,ProfileDecode; public long DecodeUs,CreateUs; @@ -31,11 +32,7 @@ public PackedWorld(string path) { Assets=new AssetStream(path); bootstrap=new FileStream(path,FileMode.Open,FileAccess.Read,FileShare.Read); - var header=new byte[32];ReadExact(bootstrap,header,32); - int count=Binary.I32(header,8); - if(count<1||count>4096)throw new IOException("Pack record count exceeds validation bound."); - var table=new byte[count*64];ReadExact(bootstrap,table,table.Length); - Catalog=new AssetCatalog(header,table,bootstrap.Length); + Catalog=PackedAssetSource.ReadCatalog(bootstrap);int count=Catalog.Count; Patches=new Mesh?[count+1];TriangleCounts=new int[count+1];VertexCounts=new int[count+1]; for(int i=0;i<85;i++){NodeMinY[i]=100;NodeMaxY[i]=-100;} for(int tile=0;tile<2;tile++) @@ -44,6 +41,7 @@ public PackedWorld(string path) var bytes=ReadPayload(r); var texture=Texture2D.CreateNative(r.Width,r.Width,NativeTextureFormat.Cmpr,true); texture.ReplaceNative(bytes);CoarseTextures[tile]=texture; + NativeBytes+=texture.NativeBytes; } int native=0; for(int id=1;id<=count;id++) @@ -63,6 +61,7 @@ public PackedWorld(string path) if(y>NodeMaxY[r.Cell])NodeMaxY[r.Cell]=y; } native+=mesh.NativeBytes; + NativeBytes+=mesh.NativeBytes; if(native>1024*1024)throw new IOException("Coarse patch hierarchy exceeds its 1 MiB native budget."); } else if(r.Kind==5) @@ -81,7 +80,7 @@ private byte[] ReadPayload(AssetRecord r) { if(r.Length>16384)throw new IOException("Bootstrap payload exceeds its managed scratch limit."); var bytes=Scratch;bootstrap.Seek(r.Offset,SeekOrigin.Begin);ReadExact(bootstrap,bytes,r.Length); - if(Binary.Crc(bytes,0,r.Length)!=r.Checksum)throw new IOException("Bootstrap asset checksum mismatch."); + if(Binary.Crc(bytes,0,r.Length)!=r.Checksum)throw new IOException("Bootstrap asset checksum mismatch for record "+r.Id+" at "+r.Offset+" length "+r.Length); return bytes; } private static void ReadExact(FileStream stream,byte[] bytes,int count) @@ -89,7 +88,7 @@ private static void ReadExact(FileStream stream,byte[] bytes,int count) int done=0; while(doneGeneration-sensitive texture sort identity, refreshed each frame. +/// Material state (effect/blend/etc.) remains part of the application's key. +public readonly struct TextureDrawKey +{ + public readonly int PrimaryFamily,PrimaryGeneration,SecondaryFamily,SecondaryGeneration; + internal TextureDrawKey(ResolvedTextureLod primary,ResolvedTextureLod secondary) + {PrimaryFamily=primary.FamilyId;PrimaryGeneration=primary.Generation;SecondaryFamily=secondary.FamilyId;SecondaryGeneration=secondary.Generation;} +} + +/// Resolve and pin at actual submission. Owns no texture allocations; +/// separate bindings can share the template and logical families safely. +public sealed class StreamedMaterialBinding +{ + private readonly TextureLodStreamer textures; + private readonly Material resolved=new Material(); + public Material Template {get;} + public StreamedMaterialTexture? Primary {get;} + public StreamedMaterialTexture? Secondary {get;} + public StreamedMaterialBinding(TextureLodStreamer textures,Material template,StreamedMaterialTexture? primary,StreamedMaterialTexture? secondary=null) + {this.textures=textures;Template=template??throw new ArgumentNullException("template");Primary=primary;Secondary=secondary;} + public TextureDrawKey SortKey()=>new TextureDrawKey(Primary==null?default:textures.Resolve(Primary),Secondary==null?default:textures.Resolve(Secondary)); + public static UvTransform Compose(TextureUv level,UvTransform authored) + =>authored.Then(new UvTransform(new Vector2(level.OffsetU,level.OffsetV),new Vector2(level.ScaleU,level.ScaleV))); + public static UvTransform TerrainUv(AssetRecord level) + {if(level.Kind!=1)throw new ArgumentException("Expected a v1 terrain texture.");return new UvTransform(new Vector2(4f/level.Width,4f/level.Width),new Vector2((float)level.Useful/level.Width,(float)level.Useful/level.Width));} + /// Use the returned material immediately; queued commands should + /// retain this binding and resolve during execution, not cache this material. + public Material PrepareForDraw(int frame) + { + var source=Template;var m=resolved; + m.Texture=source.Texture;m.SecondaryTexture=source.SecondaryTexture;m.Effect=source.Effect;m.Color=source.Color; + m.Blend=source.Blend;m.Lighting=source.Lighting;m.Cull=source.Cull;m.DepthTest=source.DepthTest;m.DepthWrite=source.DepthWrite; + m.AlphaCutoff=source.AlphaCutoff;m.TextureCoordinates=source.TextureCoordinates;m.Sampler=source.Sampler;m.SecondarySampler=source.SecondarySampler; + m.TextureTransform=source.TextureTransform;m.SecondaryTextureTransform=source.SecondaryTextureTransform; + if(Primary!=null) + { + var p=textures.Resolve(Primary);if(!textures.Pin(p,frame))throw new InvalidOperationException("Stale primary texture lease."); + m.Texture=p.Texture;m.TextureTransform=Compose(p.Uv,source.TextureTransform); + } + if(Secondary!=null) + { + var p=textures.Resolve(Secondary);if(!textures.Pin(p,frame))throw new InvalidOperationException("Stale secondary texture lease."); + m.SecondaryTexture=p.Texture;m.SecondaryTextureTransform=Compose(p.Uv,source.SecondaryTextureTransform); + } + return m; + } + public void Draw(Renderer renderer,Mesh mesh,Transform transform,int frame)=>renderer.DrawMesh(mesh,PrepareForDraw(frame),transform); +} diff --git a/src/Hypercube.GameCube/TextureLodStreamer.cs b/src/Hypercube.GameCube/TextureLodStreamer.cs new file mode 100644 index 0000000..c072405 --- /dev/null +++ b/src/Hypercube.GameCube/TextureLodStreamer.cs @@ -0,0 +1,310 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Dolphin.Graphics; +using Dolphin.Storage; +using Dolphin.Timing; + +namespace Hypercube.GameCube; + +public readonly struct ResolvedTextureLod +{ + public readonly Texture2D Texture; + public readonly int FamilyId,LogicalLevel,Generation; + public readonly TextureUv Uv; + internal ResolvedTextureLod(Texture2D texture,int family,int logical,int generation,TextureUv uv) + {Texture=texture;FamilyId=family;LogicalLevel=logical;Generation=generation;Uv=uv;} +} + +/// Single resident image per shared family, one detached destination +/// across this stream, and fence-retired old images. The optional shared policy, +/// source/cache/buffer let WorldStreamer arbitrate gameplay before each chunk. +public sealed class TextureLodStreamer : IDisposable +{ + private readonly AssetCatalog catalog; + private readonly AssetStream assets; + private readonly NativeBuffer staging; + private readonly bool ownPolicy,ownBuffer,ownCache; + private readonly Func? externalBytes; + private readonly Func? reclaim; + private readonly Texture2D?[] active,retired; + private readonly int[] resident,activeSlots,generations,requested,usedFrame; + private readonly GpuFence[] lastUse,retireFences; + private readonly long[] firstDemand; + private readonly int[] protectedIds; + private readonly Texture2D placeholder; + private GpuFence submittedFence; + private DetachedTextureUpload? upload; + private CancellationTokenSource? cancellation; + private Task? read; + private Task? copy,store; + private int slot=-1,tag,familyId,levelIndex,offset,chunkBytes,chunkOffset; + private bool cached,cacheAttempted,stopping,disposed; + private long began; + public readonly ResourceScheduler Policy; + public readonly TextureFamilyDemand Demands; + public readonly AramCache Cold; + public bool UseAram,StrictReleaseColdCopies; + public bool CorruptNextChunk,ShortNextRead; + public int Frame {get;private set;} + public int CompletedFrame {get;private set;} + public int ActiveBytes {get;private set;} + public int RetiredBytes {get;private set;} + public int UploadBytes=>upload?.StagedBytes??0; + public int ReadBufferBytes=>!disposed&&ownBuffer?staging.Length:0; + public int StagingBytes=>ReadBufferBytes+UploadBytes; + public int PoolBytes=>disposed?0:placeholder.NativeBytes; + public int PhysicalBytes=>ActiveBytes+RetiredBytes+StagingBytes+PoolBytes; + public int AramBytes=>Cold.Bytes; + public int PeakBytes,Publications,Cancellations,StaleUploads,Failures,ChecksumFailures,Deferred,Retirements,StorageBytes,ColdReadBytes,UploadedBytes,ReadOperations,Preemptions; + public int CoarseReadyCount,DetailReadyCount,MaxPumpUs; + public long CoarseLatencyUs,DetailLatencyUs; + public bool OwnsStaging=>read!=null||copy!=null||store!=null; + public bool HasTransfer=>upload!=null||OwnsStaging; + public TextureLodStreamer(AssetCatalog catalog,AssetStream assets,int budgetBytes=2*1024*1024, + ResourceScheduler? policy=null,AramCache? cold=null,NativeBuffer? stagingBuffer=null, + Func? externalPhysicalBytes=null,Func? reclaimUnneeded=null) + { + if(catalog.FamilyCount==0)throw new ArgumentException("Pack has no texture families."); + this.catalog=catalog;this.assets=assets;externalBytes=externalPhysicalBytes;reclaim=reclaimUnneeded; + ownPolicy=policy==null;Policy=policy??new ResourceScheduler(catalog,256,budgetBytes); + ownCache=cold==null;Cold=cold??new AramCache(catalog.Count,256*1024); + ownBuffer=stagingBuffer==null;staging=stagingBuffer??NativeBuffer.Allocate(32768); + int n=catalog.FamilyCount+1;active=new Texture2D?[n];resident=new int[n];activeSlots=new int[n];generations=new int[n];requested=new int[n]; + usedFrame=new int[n];lastUse=new GpuFence[n];firstDemand=new long[n];retired=new Texture2D?[Policy.Capacity];retireFences=new GpuFence[Policy.Capacity];protectedIds=new int[n]; + for(int i=0;inew StreamedMaterialTexture(catalog.Family(name),quality); + public void BeginFrame(int frame,int completedFrame) + { + if(disposed||stopping)throw new InvalidOperationException("Texture stream is stopping."); + if(frameframe||completedFrameDemands.Demand(binding,footprint,priority); + public void DemandKnownLod(StreamedMaterialTexture binding,int logicalLevel,ResourcePriority priority=ResourcePriority.Visible)=>Demands.DemandKnownLod(binding,logicalLevel,priority); + public bool CoarseReady(int family)=>active[family]!=null; + public bool DetailReady(int family)=>active[family]!=null&&resident[family]==Demands.TargetIndex(family); + public int ResidentIndex(int family)=>resident[family]; + public void PrepareDemand() + { + for(int id=1;id=0)Policy.Demand(Policy.Id(activeSlots[id]),priority<=ResourcePriority.Visible?ResourcePriority.Coarse:priority); + // A newly ready coarse image must reach an actual submitted frame + // before a full-quality consumer can enqueue a costly replacement. + if(index>=0&&index!=resident[id]&&(active[id]==null||lastUse[id].IsValid)) + { + if(active[id]==null&&priority<=ResourcePriority.Visible)priority=ResourcePriority.Coarse; + else if(active[id]!=null&&priorityValidate the lease immediately BEFORE submitting its draw. EndFrame + /// supplies the actual GPU fence for every family used in that frame. + public bool Pin(ResolvedTextureLod resolved,int submittedFrame) + { + int id=resolved.FamilyId; + if(id<1||id>=active.Length||submittedFrame!=Frame||resolved.Generation!=generations[id]||resolved.Texture!=(active[id]??placeholder))return false; + usedFrame[id]=Frame;if(activeSlots[id]>=0)Policy.Pin(activeSlots[id],Frame);return true; + } + public void EndFrame(GpuFence fence) + { + if(!fence.IsValid)throw new ArgumentException("Missing submitted frame fence.");submittedFence=fence; + for(int i=1;i=0&&familyId==id&&levelIndex==k))Cold.Drop(family.GetLevel(k).RecordId); + } + Collect();return before-PhysicalBytes; + } + // WorldStreamer's completed-frame eviction path can reclaim this image + // immediately only when its actual final GPU fence has also completed. + internal bool Evict(int candidate,ResourcePriority incoming) + { + for(int id=1;idslot>=0&&!stopping&&Policy.Generation(slot)==tag&&Policy.State(slot)==ResourceState.Reading&&requested[familyId]==Policy.Id(slot); + private bool Room(int bytes,ResourcePriority priority) + { + while(PhysicalBytes+(externalBytes?.Invoke()??0)+bytes>Policy.BudgetBytes) + { + int before=PhysicalBytes;TrimUnwanted();if(PhysicalBytes=0&&Evict(victim,priority))continue; + } + return false; + } + return true; + } + private bool Start() + { + int next=Policy.NextQueued(Frame);if(next<0||catalog.Get(Policy.Id(next)).Kind!=6)return false; + var record=catalog.Get(Policy.Id(next));int id=record.Group;var family=catalog.Family(id);int index=-1; + for(int k=0;k ReadCold(int record,int sourceOffset,int bytes) + {await Cold.FetchRange(record,sourceOffset,staging,0,bytes);return bytes;} + public void Pump(int uploadBudgetBytes=32768,int cpuBudgetUs=1000,bool allowStart=true) + { + if(disposed)throw new ObjectDisposedException("TextureLodStreamer"); + if(uploadBudgetBytes<0||cpuBudgetUs<0)throw new ArgumentOutOfRangeException("uploadBudgetBytes"); + long start=Clock.Timestamp; + try{PumpWork(uploadBudgetBytes,cpuBudgetUs,allowStart,start);} + finally{int cost=(int)(Clock.Timestamp-start);if(cost>MaxPumpUs)MaxPumpUs=cost;PeakBytes=Math.Max(PeakBytes,PhysicalBytes+(externalBytes?.Invoke()??0));} + } + private void PumpWork(int budget,int cpuBudget,bool allowStart,long start) + { + Collect();if(ownPolicy){PrepareDemand();Policy.CancelUnneeded();} + if(slot<0){if(stopping||!allowStart||budget<32||!Start())return;} + bool current=Current();if(!current)cancellation!.Cancel(); + if(store!=null) + {if(!store.IsCompleted)return;try{store.GetAwaiter().GetResult();}catch(Exception){Cold.Drop(Policy.Id(slot));}store=null;} + if(copy!=null) + { + if(!copy.IsCompleted)return; + try{copy.GetAwaiter().GetResult();offset=upload!.CompletedBytes;UploadedBytes+=chunkBytes;} + catch(Exception){copy=null;if(read==null){Discard(current);return;}throw;} + copy=null; + } + if(read!=null) + { + if(!read.IsCompleted)return; + int actual=0;try{actual=read.GetAwaiter().GetResult();}catch(Exception){read=null;Discard(current);return;}read=null; + if(cached)ColdReadBytes+=actual;else StorageBytes+=actual; + if(!current){Discard(false);return;} + if(ShortNextRead){ShortNextRead=false;actual--;} + if(actual!=chunkBytes){Discard(true);return;} + if(CorruptNextChunk){CorruptNextChunk=false;var one=new byte[1];staging.Read(one);one[0]^=128;staging.Write(one);} + try{copy=upload!.StageChunkAsync(staging,0,offset,chunkBytes,cancellation!.Token);}catch(Exception){Discard(true);}return; + } + if(!current){Discard(false);return;} + var record=catalog.Get(Policy.Id(slot)); + if(offset==record.Length) + { + try{upload!.Seal();}catch(InvalidDataException){ChecksumFailures++;Discard(true);return;} + if(!cacheAttempted) + { + cacheAttempted=true; + if(UseAram&&chunkOffset==0&&chunkBytes==record.Length) + { + protectedIds[0]=record.Id; + store=Cold.Store(record.Id,staging,0,record.Length,protectedIds,1);if(store!=null)return; + } + } + if(!Policy.Complete(slot,tag,true,Frame)){Discard(false);return;} + if(!Policy.CanPublish(slot,record.Length)){Policy.Defer(slot,Frame);upload!.Dispose();upload=null;cancellation!.Dispose();cancellation=null;slot=-1;Deferred++;return;} + if(!upload!.TryPublish(out var texture))throw new InvalidOperationException("Validated texture did not publish."); + if(active[familyId]!=null)Retire(familyId); + active[familyId]=texture;resident[familyId]=levelIndex;activeSlots[familyId]=slot;generations[familyId]++;lastUse[familyId]=default; + ActiveBytes+=record.Length;Policy.Publish(slot,record.Length);Publications++; + long latency=Clock.Timestamp-(firstDemand[familyId]==0?began:firstDemand[familyId]); + if(levelIndex==catalog.Family(familyId).CoarseIndex){CoarseReadyCount++;CoarseLatencyUs+=latency;} + if(levelIndex==Demands.TargetIndex(familyId)){DetailReadyCount++;DetailLatencyUs+=Clock.Timestamp-began;} + upload.Dispose();upload=null;cancellation!.Dispose();cancellation=null;slot=-1;return; + } + if(!allowStart||budget<32||cpuBudget>0&&Clock.Timestamp-start>=cpuBudget)return; + int queued=Policy.NextQueued(Frame); + if(queued>=0&&Policy.Priority(queued)=0&&Policy.State(slot)!=ResourceState.Retiring)Policy.Cancel(Policy.Id(slot)); + Pump(0,0,false);TrimUnwanted();return !HasTransfer&&ActiveBytes==0&&RetiredBytes==0; + } + public void Dispose() + { + if(disposed)return;if(!Stop())throw new InvalidOperationException("Pump Stop and complete frame fences before disposal."); + if(submittedFence.IsValid){if(!placeholder.TryDisposeAfterFence(submittedFence))throw new InvalidOperationException("Placeholder GPU readers remain.");} + else placeholder.Dispose(); + if(ownCache)Cold.Dispose();if(ownBuffer)staging.Dispose();disposed=true; + } +} diff --git a/src/Hypercube.GameCube/WorldStreamer.cs b/src/Hypercube.GameCube/WorldStreamer.cs index d289380..6331261 100644 --- a/src/Hypercube.GameCube/WorldStreamer.cs +++ b/src/Hypercube.GameCube/WorldStreamer.cs @@ -13,15 +13,16 @@ public sealed class WorldStreamer : IDisposable public readonly ResourceScheduler Policy; public readonly TexturePool Textures=new TexturePool(); public readonly AramCache Cold; + public readonly TextureLodStreamer? TextureLods; public readonly CellReadiness Cells=new CellReadiness(); private readonly AssetCatalog catalog; private readonly PackedWorld world; private readonly AssetStream stream; private readonly NativeBuffer staging=NativeBuffer.Allocate(131072); - private readonly Mesh?[] meshes=new Mesh?[ResourceCapacity]; - private readonly NativeBuffer?[] collisionBuffers=new NativeBuffer?[ResourceCapacity]; - private readonly int[] textureSlots=new int[ResourceCapacity],owned=new int[ResourceCapacity]; - private readonly int[] triangleCounts=new int[ResourceCapacity]; + private readonly Mesh?[] meshes; + private readonly NativeBuffer?[] collisionBuffers; + private readonly int[] textureSlots,owned; + private readonly int[] triangleCounts; private readonly float[] heights=new float[216]; private readonly int[] heightMasks=new int[24]; private readonly int[] batch=new int[8],tags=new int[8],batchIds=new int[8]; @@ -42,21 +43,30 @@ public sealed class WorldStreamer : IDisposable public int ReadLatencyCalls,MaxReadLatencyUs; // Zero time budget retains legacy behavior. A single native call cannot be preempted. public int ChecksumBytesPerPump=8192,CreatesPerPump=4,PumpBudgetUs; + public int TextureUploadBudgetBytes=32768,TextureCpuBudgetUs=1000; + public bool NormalizedTextureUvs {get;} public long PumpUs; public int PumpCalls; public int ReadOperations,StorageBytes,AramBytes,Failures,ChecksumFailures,ShortReads,Corruptions,Delays,Batches,MaxBatch, MultiplePublications,CancelledUploads,UploadedBytes,ChecksumUs,MaxUploadUs,MaxPumpUs,MeshTriangles,Deferred,Publications; - public int PhysicalBytes=>Textures.PhysicalBytes+otherBytes; + public int PhysicalBytes=>Textures.PhysicalBytes+otherBytes+(TextureLods==null?0:world.NativeBytes+staging.Length+TextureLods.PhysicalBytes); + public int PeakPhysicalBytes {get;private set;} public int Active=>count; - public WorldStreamer(PackedWorld world,string path,int budgetBytes=384*1024) + public WorldStreamer(PackedWorld world,string path,int budgetBytes=384*1024,bool normalizedTextureUvs=false) { this.world=world;scratch=world.Scratch;catalog=world.Catalog;stream=world.Assets; - Policy=new ResourceScheduler(catalog,ResourceCapacity,budgetBytes); + int capacity=catalog.FamilyCount==0?ResourceCapacity:256; + Policy=new ResourceScheduler(catalog,capacity,budgetBytes); + meshes=new Mesh?[capacity];collisionBuffers=new NativeBuffer?[capacity];textureSlots=new int[capacity];owned=new int[capacity];triangleCounts=new int[capacity]; Cold=new AramCache(catalog.Count,256*1024); + NormalizedTextureUvs=normalizedTextureUvs; + if(catalog.FamilyCount>0)TextureLods=new TextureLodStreamer(catalog,stream,budgetBytes,Policy,Cold,staging, + ()=>world.NativeBytes+Textures.PhysicalBytes+otherBytes+staging.Length,ReclaimForTextureLod); for(int i=0;iPolicy.BeginDemand(); + public void BeginDemand(){Policy.BeginDemand();TextureLods?.BeginFrame(Frame,CompletedFrame);} + public void EndFrame(GpuFence fence)=>TextureLods?.EndFrame(fence); private void Demand(int id,ResourcePriority priority) { if(recordDemandPlan)demandPlan!.Add(id,priority); @@ -64,7 +74,7 @@ private void Demand(int id,ResourcePriority priority) // Slot capacity is independent of byte capacity. Reclaim an unneeded // resident even when the byte budget itself still has room. int victim=Policy.EvictionCandidate(CompletedFrame,priority); - if(victim>=0){Release(victim,priority);Policy.Demand(id,priority);} + if(victim>=0&&Release(victim,priority))Policy.Demand(id,priority); } public void DemandCell(int cell,int lod,bool raw=false) { @@ -126,14 +136,20 @@ public float Ground(int cell,float x,float z) float a=heights[at]*(1-fx)+heights[at+1]*fx,b=heights[at+3]*(1-fx)+heights[at+4]*fx; return a*(1-fz)+b*fz; } - private void Release(int slot,ResourcePriority incoming) + private bool Release(int slot,ResourcePriority incoming) { var r=catalog.Get(Policy.Id(slot)); + if(r.Kind==6)return TextureLods!=null&&TextureLods.Evict(slot,incoming); if(textureSlots[slot]>=0){Textures.Unbind(textureSlots[slot]);textureSlots[slot]=-1;} if(meshes[slot]!=null){meshes[slot]!.Dispose();meshes[slot]=null;otherBytes-=owned[slot];} if(collisionBuffers[slot]!=null) {collisionBuffers[slot]!.Dispose();collisionBuffers[slot]=null;otherBytes-=owned[slot];Cells.CollisionMissing(r.Cell);} - owned[slot]=0;Policy.Evict(slot,CompletedFrame,incoming); + owned[slot]=0;Policy.Evict(slot,CompletedFrame,incoming);return true; + } + private bool ReclaimForTextureLod(ResourcePriority priority) + { + if(Textures.TrimFree()>0)return true; + int victim=Policy.EvictionCandidate(CompletedFrame,priority);return victim>=0&&Release(victim,priority); } private bool Room(int extra,ResourcePriority priority) { @@ -142,7 +158,7 @@ private bool Room(int extra,ResourcePriority priority) if(Textures.TrimFree()>0)continue; int victim=Policy.EvictionCandidate(CompletedFrame,priority); if(victim<0)return false; - Release(victim,priority); + if(!Release(victim,priority))return false; } return true; } @@ -151,7 +167,7 @@ private bool TextureRoom(AssetRecord record,ResourcePriority priority) while(PhysicalBytes+Textures.ExtraBytes(record)>Policy.BudgetBytes) { int victim=Policy.EvictionCandidate(CompletedFrame,priority); - if(victim>=0){Release(victim,priority);continue;} + if(victim>=0&&Release(victim,priority))continue; if(Textures.TrimFree()>0)continue; return false; } @@ -159,9 +175,9 @@ private bool TextureRoom(AssetRecord record,ResourcePriority priority) } private void Queue() { - int limit=Policy.RequiredBatchBytes(Frame,ReadBatchBytes); + int limit=Policy.RequiredBatchBytes(Frame,ReadBatchBytes,6); if(limit>131040)throw new IOException("Asset exceeds the bounded native staging size."); - count=Policy.BeginBatch(Frame,limit,MaxBatchRecords,batch,out batchOffset,out batchLength); + count=Policy.BeginBatch(Frame,limit,MaxBatchRecords,batch,out batchOffset,out batchLength,6); if(count==0)return; // A large record may exceed the requested coalescing size; SDK reads it // in bounded chunks. Adjacent small records still share one logical read. @@ -215,7 +231,7 @@ private void StartRecord(int i) { int tile=(r.Cell/6/Group)*((6+Group-1)/Group)+(r.Cell%6/Group); var texture=catalog.Get(catalog.Texture(Format,Group,r.Mip,tile)); - meshes[slot]=world.DecodeMesh(scratch,r,texture,Group); + meshes[slot]=world.DecodeMesh(scratch,r,texture,Group,NormalizedTextureUvs); bytes=meshes[slot]!.NativeBytes;triangleCounts[slot]=Binary.U16(scratch,6)/3;MeshTriangles+=triangleCounts[slot]; } else @@ -238,13 +254,24 @@ public void Pump() { int elapsed=(int)(Clock.Timestamp-pumpAt);PumpUs+=elapsed;PumpCalls++; if(elapsed>MaxPumpUs)MaxPumpUs=elapsed; + PeakPhysicalBytes=Math.Max(PeakPhysicalBytes,PhysicalBytes); } } private void PumpWork(long pumpAt) { int publishedBefore=Publications; + TextureLods?.PrepareDemand(); Policy.CancelUnneeded(); - if(count==0){if(!stopping)Queue();return;} + if(count==0) + { + if(TextureLods!=null) + { + TextureLods.UseAram=UseAram; + TextureLods.Pump(stopping?0:TextureUploadBudgetBytes,TextureCpuBudgetUs,!stopping); + if(TextureLods.OwnsStaging)return; + } + if(!stopping)Queue();return; + } if(actualRead<0) { if(reading==null||!reading.IsCompleted||FrameExe diff --git a/tests/WorldTextureLodRuntime/Program.cs b/tests/WorldTextureLodRuntime/Program.cs new file mode 100644 index 0000000..29e26a0 --- /dev/null +++ b/tests/WorldTextureLodRuntime/Program.cs @@ -0,0 +1,54 @@ +using System; +using Dolphin.Graphics; +using Dolphin.Memory; +using Dolphin.Storage; +using Hypercube; +using Hypercube.GameCube; +using Scheduler=Dolphin.Threading.Tasks.Scheduler; + +internal static class Program +{ + private static void Check(bool value,string message){if(!value)throw new Exception(message);} + static int Main() + { + Check(Aram.Initialize(2*1024*1024)&&Storage.Mount(StorageDevice.SdSerialPort2),"Storage/ARAM unavailable."); + using var world=new PackedWorld("sd:/world-mixed.hcp"); + using var stream=new WorldStreamer(world,"sd:/world-mixed.hcp",2*1024*1024,true){UseAram=true}; + var lods=stream.TextureLods!;var binding=lods.Get("terrain/rgba",TextureQualityPolicy.FullQuality); + var late=lods.Get("objects/cmpr",TextureQualityPolicy.CoarseOnly); + var device=GraphicsDevice.Default;using var draw=new Draw2D(device); + bool preempted=false,lateRequested=false,lateReady=false,done=false,stopping=false;int frame=0; + while(!done) + { + Scheduler.Pump(16); + if(!stopping) + { + stream.Frame=frame;stream.CompletedFrame=Math.Max(0,frame-1);stream.BeginDemand();stream.DemandCollision(0); + lods.Demand(binding,new TextureFootprint(2048,2048)); + if(lods.UploadBytes>131072){stream.DemandCollision(1);lateRequested=true;} + if(lateRequested)lods.Demand(late,new TextureFootprint(128,128)); + stream.Pump(); + if(frame==0)Check(stream.Policy.State(stream.Policy.Find(world.Catalog.Collision(0)))==ResourceState.Reading&&!lods.HasTransfer,"Gameplay did not precede missing coarse texture."); + if(lods.UploadBytes>131072&&stream.Ready(world.Catalog.Collision(1)))preempted=true; + if(lods.CoarseReady(late.Family.Id)&&!lods.DetailReady(binding.Family.Id))lateReady=true; + if(lods.DetailReady(binding.Family.Id)) + { + Check(preempted,"Chunked promotion blocked gameplay/collision preemption."); + Check(lateReady,"A late visible coarse family was blocked behind a detached upgrade."); + Check(stream.PhysicalBytes<=stream.Policy.BudgetBytes&&world.NativeBytes>0,"World/staging/permanent residency not counted."); + Check(stream.NormalizedTextureUvs,"Normalized UV opt-in lost.");stopping=true; + } + } + else done=stream.Stop(); + device.BeginFrame(Color32.Black);draw.Begin(); + if(!stopping) + { + var p=lods.Resolve(binding);Check(lods.Pin(p,frame),"Stale world texture lease.");draw.DrawTexture(p.Texture,new RectF(32,32,256,256),Color32.White); + if(lateRequested){var q=lods.Resolve(late);Check(lods.Pin(q,frame),"Stale late family lease.");draw.DrawTexture(q.Texture,new RectF(320,32,256,256),Color32.White);} + } + draw.End();stream.EndFrame(device.InsertFence());device.EndFrame(); + Check(++frame<3000,"World texture integration timed out."); + } + return 0; + } +} diff --git a/tests/WorldTextureLodRuntime/WorldTextureLodRuntime.csproj b/tests/WorldTextureLodRuntime/WorldTextureLodRuntime.csproj new file mode 100644 index 0000000..86817ed --- /dev/null +++ b/tests/WorldTextureLodRuntime/WorldTextureLodRuntime.csproj @@ -0,0 +1 @@ +Exe diff --git a/tests/nuget_consumer.py b/tests/nuget_consumer.py index e1f5dbb..df4c235 100644 --- a/tests/nuget_consumer.py +++ b/tests/nuget_consumer.py @@ -17,6 +17,9 @@ def main(): work=(args.workspace or Path(tempfile.mkdtemp(prefix='hypercube nuget '))).resolve() if work.exists() and any(work.iterdir()):p.error('Consumer workspace must be empty') work.mkdir(parents=True,exist_ok=True);feed=work/'relocated feed';feed.mkdir() + manifest_path=args.feed/'packages.json';manifest=json.loads(manifest_path.read_text()) if manifest_path.is_file() else {} + if manifest.get('sdkSourcePreview'): + for package in (args.feed/'sdk-feed').glob('*.nupkg'):shutil.copy2(package,feed) ids=['Capz.Hypercube.Core']+([] if args.core_only else ['Capz.Hypercube.GameCube']);versions={} for identity in ids: packages=list(args.feed.glob(identity+'.*.nupkg')) @@ -34,7 +37,7 @@ def run(*cmd,cwd=work):subprocess.run(cmd,cwd=cwd,env=env,check=True) class Program {static void Main(){var q=new OpaqueDrawQueue(2);q.TryAdd(1,2,0xffffffff,DrawPose.Identity);q.Group();if(q.At(0).Mesh!=1)throw new Exception();var c=new CameraFrustum(0,0,0,0,0,-1,0,1,0,60,1,1,20);if(!c.Sphere(0,0,-5,1))throw new Exception();var r=new ResourceLeases(1,1,4);r.Register(1,4);var l=r.Acquire(1);r.Release(l);if(r.RemoveUnused(0)!=0)throw new Exception();Console.WriteLine("External Core NuGet consumer passed");}} ''') run('dotnet','run','--project',str(core),'-c','Release') - sdk=ET.parse(ROOT/'Directory.Build.props').find('.//DolphinDotNetPackageVersion').text + sdk=manifest.get('sdkVersion') or ET.parse(ROOT/'Directory.Build.props').find('.//DolphinDotNetPackageVersion').text if not args.core_only: app=work/'GameCube';app.mkdir() (app/'GameCube.csproj').write_text('') diff --git a/tests/test_progressive_validation.py b/tests/test_progressive_validation.py new file mode 100644 index 0000000..de802cb --- /dev/null +++ b/tests/test_progressive_validation.py @@ -0,0 +1,29 @@ +import copy +from pathlib import Path +import sys +import unittest +sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tools')) +from progressive_validation import FIELDS,validate_rows + +class ProgressiveAcceptance(unittest.TestCase): + def rows(self): + row=dict.fromkeys(FIELDS,0) + row.update(magic=0x4854,phase=10,coarseMask=15,crcFailures=1,failures=2,stale=1,deferred=1,cancelled=1,aramHits=1,audioActive=1) + return [dict(row,frame=600+i) for i in range(20)] + def test_complete_zero_copy_trim_and_live_audio(self): + proof=validate_rows(self.rows());self.assertFalse(proof['hardwarePerformanceClaim']);self.assertEqual(proof['platform'],'Dolphin') + def test_each_residency_tier_must_drain(self): + for key in ('active32','upload32','retired32','aram32','readBufferKiB','poolBytes'): + rows=self.rows();rows[-1][key]=1 + with self.subTest(tier=key),self.assertRaises(AssertionError):validate_rows(rows) + def test_fault_paths_and_progress_cannot_be_skipped(self): + for key in ('crcFailures','failures','stale','deferred','cancelled','aramHits','coarseMask'): + rows=self.rows();rows[-1][key]=0 + with self.subTest(gate=key),self.assertRaises(AssertionError):validate_rows(rows) + rows=self.rows() + for row in rows:row['frame']=1 + with self.assertRaises(AssertionError):validate_rows(rows) + def test_audio_cannot_stop_mid_stream(self): + rows=self.rows();rows[2]['audioActive']=0 + with self.assertRaises(AssertionError):validate_rows(rows) +if __name__=='__main__':unittest.main() diff --git a/tests/texture_lod_host.c b/tests/texture_lod_host.c new file mode 100644 index 0000000..6f4b7bb --- /dev/null +++ b/tests/texture_lod_host.c @@ -0,0 +1,32 @@ +#include "dnd_draw.h" +#include "dnd_storage.h" +#include "dnd_aram.h" +#include +#include +extern intptr_t dnd_aot_entry(DndManagedHeap *heap); +int texture_host_waits,texture_host_draws,texture_host_publishes; +void dnd_console_write_line(const char *text){puts(text);} +void dnd_console_write_managed_line(DndString *text){(void)text;} +void dnd_draw_backend_options(const float *p,int scene){(void)p;(void)scene;} +int main(void) +{ + static unsigned char storage[4*1024*1024];DndManagedHeap heap; + dnd_managed_heap_init(&heap,storage,sizeof(storage));dnd_gc_set_stress(true); + intptr_t result=dnd_aot_entry(&heap); + if(result||dnd_exception_pending()){ + fprintf(stderr,"Texture LOD AOT result=%ld: %s\n",(long)result,dnd_exception_message()); + DndException *e=(DndException*)dnd_exception_object();if(e&&e->message){for(uint32_t i=0;imessage->length;i++)fputc(e->message->chars[i],stderr);fputc('\n',stderr);}return 1; + } + assert(dnd_draw_total_bytes()==0&&dnd_draw_live()==0&&dnd_fs_open_handles()==0&&dnd_aram_stat(1)==0); +#ifdef HYPERCUBE_WORLD_RUNTIME + assert(texture_host_draws>5&&texture_host_publishes>=2); +#else + assert(texture_host_draws>100&&texture_host_publishes>=8); + /* Only two staging buffers, three scene resources, and the AOT device + shutdown may wait. + All texture replacement and fence retirement paths must avoid waits. */ + assert(texture_host_waits==6); +#endif + printf("Texture LOD AOT/GC: coarse/fine, sparse/pair, CRC/short read, cancellation drain, leases, pressure, ARAM, zero-byte trim; draws=%d publications=%d cleanup-waits=%d\n",texture_host_draws,texture_host_publishes,texture_host_waits); + return 0; +} diff --git a/tests/world_progressive_fixtures.py b/tests/world_progressive_fixtures.py new file mode 100644 index 0000000..d4b5938 --- /dev/null +++ b/tests/world_progressive_fixtures.py @@ -0,0 +1,13 @@ +"""Mix the unchanged validation world and generic families in HCPK v2.""" +from pathlib import Path +from progressive_fixtures import build +from hypercube import pack +def mixed(root='out/progressive'): + root=Path(root);families=build(root);original=root/'world-v1.hcp' + pack.build(original,root/'world-v1.json',resolution=12);raw=original.read_bytes();count=pack.HEADER.unpack_from(raw)[2];builder=pack.Builder() + for i in range(count): + r=pack.RECORD.unpack_from(raw,32+i*64) + builder.add(r[1],raw[r[2]:r[2]+r[3]],fmt=r[5],group=r[6],mip=r[7],cell=r[8],parent=r[9],width=r[10],useful=r[11],material=r[12],variant=r[13]) + builder.import_textures([(f['name'],root/f'{i}.dnlod') for i,f in enumerate(families.families)]) + builder.write(root/'world-mixed.hcp');pack.inspect(root/'world-mixed.hcp') +if __name__=='__main__':mixed() diff --git a/tools/build_progressive.sh b/tools/build_progressive.sh new file mode 100755 index 0000000..abb0c8b --- /dev/null +++ b/tools/build_progressive.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +configuration="${CONFIGURATION:-Release}" +sdk_root="${DOLPHIN_DOTNET_ROOT:-$PWD/vendor/sdk}" +sdk_root="$(cd "$sdk_root" && pwd)" +native_output="$PWD/out/native-progressive-$configuration" +python3 tests/progressive_fixtures.py +python3 -c 'import sys;sys.path.insert(0,"tools");from hypercube import disc;disc.build("out/progressive/textures.iso","out/progressive/textures.hcp")' +dotnet build "$sdk_root/tools/DolphinDotNet.Compiler" -c Release -m:1 +dotnet build samples/ProgressiveTextures -c "$configuration" -p:DolphinDotNetRoot="$sdk_root" -p:DndBuildNative=false -m:1 +dotnet "$sdk_root/tools/DolphinDotNet.Compiler/bin/Release/net8.0/DolphinDotNet.Compiler.dll" --bundle "samples/ProgressiveTextures/bin/$configuration/net8.0/ProgressiveTextures.dll" "$native_output" +native_args=() +if [[ -n "${LIBOGC2_SOURCE:-}" ]]; then native_args+=(--mount "type=bind,src=$LIBOGC2_SOURCE,dst=/upstream" -e DND_EXI_SOURCE_DIR=/upstream); fi +if [[ -n "${CA_CERT_FILE:-}" ]]; then native_args+=(--mount "type=bind,src=$CA_CERT_FILE,dst=/tmp/dnd-ca.pem,readonly" -e GIT_SSL_CAINFO=/tmp/dnd-ca.pem -e SSL_CERT_FILE=/tmp/dnd-ca.pem); fi +docker run --rm --init --user "$(id -u):$(id -g)" --mount "type=bind,src=$native_output,dst=/work" "${native_args[@]}" -w /work ghcr.io/extremscorner/libogc2@sha256:13bb658d3f18903816617223f5d7c6f776d3db3ea806aae67f8d35a7a69d4c85 make -j2 DND_MANAGED_HEAP_BYTES=2097152 diff --git a/tools/progressive_validation.py b/tools/progressive_validation.py new file mode 100644 index 0000000..81b9e8b --- /dev/null +++ b/tools/progressive_validation.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Rendered progressive streaming, both texture slots, affine gutters and audio.""" +import argparse +import json +import os +from pathlib import Path +import signal +import subprocess +import time +from dolphin_validation import SIZE,ffmpeg,audio_proof +FIELDS=('magic','phase','frame','publications','crcFailures','failures','stale','active32','upload32','retired32','aram32','coarseMask','deferred','retirements','frame99ms','aramHits','detailMask','peakKiB','audioActive','coarseReady','detailReady','coarseMeanMs','detailMeanMs','maxPumpUs','storageKiB','coldKiB','uploadedKiB','cancelled','frame95ms','readBufferKiB','poolBytes','checksum') +def telemetry(rgb): + if len(rgb)!=SIZE:raise ValueError('Incomplete frame') + fields=[] + for k in range(32): + value=0 + for bit in range(16): + at=((436+k//16*10)*640+32+((k%16)*16+bit)*2)*3 + pixel=rgb[at:at+3] + if max(pixel)-min(pixel)>12:raise ValueError('Corrupt telemetry raster') + if sum(pixel)>384:value|=1<12:raise AssertionError(f'UV/pixel discontinuity at {x},{y}: {tuple(rgb[at:at+3])}, expected {color}') +def validate_rows(rows): + if len(rows)<10 or rows[-1]['phase']!=10 or len({r['frame'] for r in rows[-10:]})<5:raise AssertionError('Stress scenario did not complete and sustain frames') + final=rows[-1] + if final['coarseMask']!=15 or final['crcFailures']<1 or final['failures']<2 or final['stale']<1 or final['deferred']<1 or final['cancelled']<1 or final['aramHits']<1:raise AssertionError(f'Incomplete failure/pressure/ARAM coverage: {final}') + if any(final[k]!=0 for k in ('active32','upload32','retired32','aram32','readBufferKiB','poolBytes')):raise AssertionError('Unwanted allocations survived final fences and explicit trim') + if any(r['audioActive']!=1 for r in rows):raise AssertionError('Audio stopped during stress') + return dict(platform='Dolphin',hardwarePerformanceClaim=False,sampledFrames=len(rows),last=final) +def validate(video,root): + rows=[];coarse=fine=0;invalid=0;images={} + with (root/'decode.log').open('wb') as log: + decoder=subprocess.Popen(['ffmpeg','-threads','1','-v','error','-i',str(video),'-vf','fps=10,scale=640:480:flags=neighbor','-f','rawvideo','-pix_fmt','rgb24','-'],stdout=subprocess.PIPE,stderr=log) + try: + while True: + rgb=decoder.stdout.read(SIZE) + if not rgb:break + if len(rgb)!=SIZE:raise AssertionError('Incomplete decoded frame') + try:row=telemetry(rgb) + except ValueError:invalid+=1;continue + invalid=0;rows.append(row) + if row['phase']==1: + for x,y in ((100,180),(220,180),(100,300),(220,300)):patch(rgb,x,y,(255,0,0)) + coarse+=1;images['coarse']=rgb + if row['phase']==4 and row['detailMask']==15: + for shift in (0,320): + for x,y,color in ((100,180,(0,255,0)),(220,180,(0,255,255)),(100,300,(255,0,0)),(220,300,(255,0,255))):patch(rgb,x+shift,y,color) + fine+=1;images['fine-dual-uv']=rgb + if decoder.wait()!=0:raise AssertionError('Frame decoder failed') + finally: + if decoder.poll() is None:decoder.kill();decoder.wait() + (root/'states.json').write_text(json.dumps(rows,indent=2)+'\n') + if invalid>3 or coarse<2 or fine<3:raise AssertionError(f'Missing sustained coarse/fine pixel evidence ({coarse}, {fine}, trailing invalid {invalid})') + proof=validate_rows(rows);proof.update(coarsePixelFrames=coarse,fineDualUvPixelFrames=fine,pixelPatches=12) + for name,rgb in images.items():ffmpeg(['-f','rawvideo','-pix_fmt','rgb24','-s','640x480','-i','pipe:0','-frames:v','1','-y',str(root/(name+'.png'))],root/'encode.log',input=rgb) + return proof +def run(args): + if not 10<=args.seconds<=300:raise ValueError('Use a bounded 10–300 second capture') + root=args.logs.resolve();root.mkdir(parents=True,exist_ok=False);config=root/'user/Config';config.mkdir(parents=True) + (config/'Dolphin.ini').write_text(f'[Core]\nGFXBackend = OGL\nCPUCore = 1\nCPUThread = False\nDSPHLE = False\nDefaultISO = {args.disc.resolve()}\n[DSP]\nDSPThread = False\nBackend = No Audio Output\nDumpAudio = True\n[Movie]\nDumpFrames = True\nDumpFramesSilent = True\n') + (config/'GFX.ini').write_text('[Settings]\nSafeTextureCacheColorSamples = 0\nDumpFormat = avi\nDumpCodec = ffv1\nDumpEncoder = ffv1\nDumpPixelFormat = bgr0\n') + (config/'Logger.ini').write_text('[Options]\nWriteToFile = True\nVerbosity = 3\n[Logs]\nBOOT = True\nCORE = True\nPOWERPC = True\nOSREPORT = True\n') + env=dict(os.environ,SDL_AUDIODRIVER='dummy',LP_NUM_THREADS='2',LIBGL_ALWAYS_SOFTWARE='1',DOLPHIN_EMU_USERPATH=str(root/'user')) + with (root/'stdout.log').open('w') as log: + process=subprocess.Popen(['xvfb-run','-a',args.binary,'--user',str(root/'user'),'--exec',str(args.dol.resolve())],env=env,stdout=log,stderr=subprocess.STDOUT,start_new_session=True) + try: + deadline=time.monotonic()+args.seconds + while time.monotonic()data&&t->width==4&&t->height==4);const unsigned char *p=t->data;assert(p[0]==0&&p[1]==0);','assert(t->data&&t->width>0&&t->height>0);') + backend=backend.replace('graphics_draws++;','texture_host_draws++;graphics_draws++;').replace('void dnd_draw_backend_wait(void){}','void dnd_draw_backend_wait(void){texture_host_waits++;}').replace('void dnd_draw_backend_publish_texture(void){}','void dnd_draw_backend_publish_texture(void){texture_host_publishes++;}') + backend='extern int texture_host_waits,texture_host_draws,texture_host_publishes;\n'+backend + (work/'backend.c').write_text(backend) + sources=['managed_runtime','async_runtime','numeric','text','draw_resources','graphics_device','performance','model_transform','model_graphics','model','model_animation','storage','contiguous_write','file_optimize','file_extents','verified_copy','timing','stw','gc_stw','bcl','aram'] + env={**os.environ,'DND_ASYNC_MANUAL':'1','DND_STORAGE_ROOT':str(work)} + for project,config in [(p,c) for p in projects for c in configurations]: + run('dotnet','build',f'tests/{project}','-c',config,f'-p:DolphinDotNetRoot={SDK}') + generated=work/(project+config+'.c');exe=work/(project+config) + run('dotnet',SDK/'tools/DolphinDotNet.Compiler/bin/Release/net8.0/DolphinDotNet.Compiler.dll','--aot',f'tests/{project}/bin/{config}/net8.0/{project}.dll',generated) + dead='-Wl,-dead_strip' if sys.platform=='darwin' else '-Wl,--gc-sections' + defines=['-DHYPERCUBE_WORLD_RUNTIME'] if project=='WorldTextureLodRuntime' else [] + run('cc','-std=c11','-O1','-D_DEFAULT_SOURCE','-D_DARWIN_C_SOURCE','-DDND_GRAPHICS_TEST',*defines,'-ffunction-sections','-fdata-sections','-pthread',f'-I{SDK}/include',generated,'tests/texture_lod_host.c',work/'backend.c',*[SDK/f'source/{s}.c' for s in sources],dead,'-lm','-o',exe) + run(exe,env=env) +if __name__=='__main__': + p=argparse.ArgumentParser(description=__doc__);p.add_argument('--project',choices=['TextureLodRuntime','WorldTextureLodRuntime']);p.add_argument('--configuration',choices=['Debug','Release']);a=p.parse_args() + main([a.project] if a.project else ['TextureLodRuntime','WorldTextureLodRuntime'],[a.configuration] if a.configuration else ['Debug','Release'])