diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9cfc6a8f2..6cd53407b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -4,7 +4,7 @@ on: push: branches: [main] pull_request: - branches: [main, feature/model-import-compatibility-phase1, codex/asset-throughput, codex/texture-stage-timings, feature/iso-defrag-planning-and-evacuation] + branches: [main, feat/streamable-texture-assets, feature/model-import-compatibility-phase1, codex/asset-throughput, codex/texture-stage-timings, feature/iso-defrag-planning-and-evacuation] workflow_dispatch: permissions: diff --git a/docs/streamable-textures.md b/docs/streamable-textures.md index 577d178f2..c060c01cb 100644 --- a/docs/streamable-textures.md +++ b/docs/streamable-textures.md @@ -66,3 +66,46 @@ 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. + +## Detached runtime uploads + +`DetachedTextureUpload.Create(width, height, format, nativeBytes, crc32)` owns +one private allocation, charged through `StagedBytes`. Between frames, read at +most your configured chunk budget into a reusable aligned `NativeBuffer`, then +await `StageChunkAsync(source, sourceOffset, destinationOffset, count)`. Chunks +must be sequential, contiguous and 32-byte aligned. Both allocations stay held +until the service copy and application continuation finish. Do not mutate raw +addresses while held; normal buffer writes and storage reads reject reuse. + +`CompletedBytes` observes the completed task and incremental native-source CRC. +`Seal()` rejects missing bytes or a checksum mismatch. `TryPublish` invalidates +the GX texture cache on the application executor and transfers one immutable +`Texture2D` to the caller. No copy or global GPU wait occurs at publication. +The owner no longer counts the allocation after transfer; the caller counts +`Texture2D.NativeBytes` as active, and later as retired. + +On cancellation, await `AbortAsync()` before reusing either allocation. +`Dispose()` refuses a running copy; it cancels queued work but never frees +memory under a worker. Failed uploads cannot publish. No whole-image managed +staging array or permanent second texture is required. Existing +`StreamingTexture` keeps its fixed-size front/back contract. + +Compose authored animation with each level's static usable rectangle using +`authored.Then(levelMapping)`. `UvTransform.Then` preserves a complete affine +matrix, including nonuniform gutters after rotation; no geometry rebuild or +lossy decomposition into scale/rotation is necessary. + +Record the final reader using `GraphicsDevice.InsertFence()`. Once the texture +is removed from all draw bindings, `Texture2D.TryDisposeAfterFence(fence)` frees +it only when that fence completes, without another GPU wait. A fence cannot +protect later submissions: resolve and pin immediately before drawing, and +never submit a retired texture. Normal `Dispose()` retains its conservative +existing behavior. + +Run `python3 scripts/ci_detached_textures.py` for native range/lifetime tests +and Debug/Release managed AOT with GC stress. Build +`tests/fixtures/DetachedTextures` and run +`python3 scripts/dolphin_detached_textures.py Game.dol --logs out/fresh-capture` +for repeated RGBA8/CMPR resolution changes and independent pixel-patch checks. +The fixture uses two explicitly counted 32-KiB source buffers, with at most one +detached destination per lane. Emulator timings are not console measurements. diff --git a/include/dnd_draw.h b/include/dnd_draw.h index 2e3bb8e60..fa0f4673b 100644 --- a/include/dnd_draw.h +++ b/include/dnd_draw.h @@ -75,6 +75,12 @@ int dnd_texture_package(DndArray *package,int linear); int dnd_texture_ipl_font(DndArray *metadata,int linear); int dnd_texture_sampler(int token,int wrap_s,int wrap_t,int min_filter,int mag_filter,float lod_bias); int dnd_texture_allocate_native(int width,int height,int format,int linear); +int dnd_texture_allocate_detached(int width,int height,int format,int linear); +int dnd_texture_upload_hold(int token); +int dnd_texture_upload_unhold(int token); +int dnd_texture_stage_buffer_range(int texture_token,int buffer_token,int source_offset,int destination_offset,int count); +/* Caller supplies the final reader fence; successful release never waits on GX. */ +int dnd_texture_release_completed(int token,int fence); int dnd_texture_update_native(int token,DndArray *payload,int source_offset,int count); int dnd_texture_update_buffer(int texture_token,int buffer_token,int source_offset,int count); /* CPU-only staging to a texture allocation that is NOT referenced by in-flight GX diff --git a/scripts/ci_detached_textures.py b/scripts/ci_detached_textures.py new file mode 100644 index 000000000..2fc038b32 --- /dev/null +++ b/scripts/ci_detached_textures.py @@ -0,0 +1,12 @@ +"""Exercise native lifetime guards and the managed owner through actual AOT.""" +from pathlib import Path +import tempfile +import sys +from ci_graphics_phase_one import main,run +if __name__=='__main__': + with tempfile.TemporaryDirectory(prefix='dnd-detached-') as folder: + binary=Path(folder)/'ranges' + dead='-Wl,-dead_strip' if sys.platform=='darwin' else '-Wl,--gc-sections' + run('cc','-std=c11','-Wall','-Wextra','-Werror','-O1','-ffunction-sections','-fdata-sections','-Iinclude','tests/detached_texture_test.c','source/draw_resources.c',dead,'-lm','-o',binary) + run(binary) + main('DetachedTextureUploadSmoke','detached_texture_host.c') diff --git a/scripts/ci_test_suite.py b/scripts/ci_test_suite.py index c87f3fdbf..1d55db50a 100644 --- a/scripts/ci_test_suite.py +++ b/scripts/ci_test_suite.py @@ -145,6 +145,7 @@ def main(area): if source=="audio_formats_test":run(binary,tmp) else:run(binary) elif area=="graphics": + run("python3","scripts/ci_detached_textures.py") # DetachedTextureUploadSmoke (Debug/Release AOT + GC stress) run("python3","scripts/ci_display.py") # DisplayConfigurationSmoke run("python3","scripts/ci_graphics_phase_one.py") run("python3","scripts/ci_graphics_phase_two.py") diff --git a/scripts/dolphin_detached_textures.py b/scripts/dolphin_detached_textures.py new file mode 100644 index 000000000..01e165e9d --- /dev/null +++ b/scripts/dolphin_detached_textures.py @@ -0,0 +1,27 @@ +"""RGBA8/CMPR pixel consistency under repeated detached resolution swaps.""" +import argparse +from pathlib import Path +from dolphin_texture_test import FRAME_BYTES,run +def validate_capture(raw): + if len(raw)%FRAME_BYTES or len(raw)//FRAME_BYTES<60:raise AssertionError('Insufficient complete frames') + publications=[] + for start in range(len(raw)-30*FRAME_BYTES,len(raw),FRAME_BYTES): + rgb=raw[start:start+FRAME_BYTES] + for left in (32,352): + for dx,dy,color in ((64,64,(255,0,0)),(192,64,(0,255,0)),(64,192,(255,0,255)),(192,192,(0,255,255))): + at=((80+dy)*640+left+dx)*3 + if max(abs(a-b) for a,b in zip(rgb[at:at+3],color))>12:raise AssertionError('Corrupt or missing detached pixels') + fields=[] + for k in range(6): + value=0 + for bit in range(16): + at=(404*640+32+(k*16+bit)*6+2)*3 + if sum(rgb[at:at+3])>384:value|=1<detached&&!r->holds){release(r);return 0;} if(dnd_device_active() || r->holds) r->pending=true; - else { dnd_draw_backend_wait(); release(r); } + else { if(!r->detached)dnd_draw_backend_wait(); release(r); } return 0; } void dnd_draw_collect(void) { for(int i=0;iio_busy || !array_range(array,index,count) || offset<0 || offset>r->bytes || (size_t)count*array->element_size>(size_t)(r->bytes-offset)) return -1; + if(dnd_raw_depth() || dnd_device_active() || !r || r->io_busy || (write&&r->holds) || !array_range(array,index,count) || offset<0 || offset>r->bytes || (size_t)count*array->element_size>(size_t)(r->bytes-offset)) return -1; void *p=(unsigned char*)array->data+(size_t)index*array->element_size; if(write) memcpy(r->data+offset,p,(size_t)count*array->element_size); else memcpy(p,r->data+offset,(size_t)count*array->element_size); @@ -222,6 +223,41 @@ int dnd_texture_allocate_native(int w,int h,int format,int linear) { dnd_draw_backend_flush(r->data,bytes,2); return token; } +/* The detached target is private until publication. No GX command/cache + * invalidation is needed to allocate it; CPU staging flushes exact ranges. */ +int dnd_texture_allocate_detached(int w,int h,int format,int linear) { + dnd_async_require_application_thread(); + int bytes=texture_size(w,h,format); + if(dnd_device_active()||dnd_raw_depth()||bytes<0||(linear!=0&&linear!=1))return 0; + int token=create(TEXTURE,bytes,32);Resource *r=find(token,TEXTURE);if(!r)return 0; + r->width=w;r->height=h;r->format=format;r->linear=linear;r->detached=true;return token; +} +int dnd_texture_upload_hold(int token) { + dnd_async_require_application_thread();Resource *r=find(token,TEXTURE); + if(!r||!r->detached||r->holds)return -1; + r->holds++;return 0; +} +int dnd_texture_upload_unhold(int token) { + dnd_async_require_application_thread();int index=(token&1023)-1; + if(token<=0||index<0||index>=SLOTS)return -1; + Resource *r=&slots[index]; + if(r->kind!=TEXTURE||r->generation!=(token>>10)||!r->detached||r->holds<=0)return -1; + if(--r->holds==0&&r->pending)release(r); + return 0; +} +int dnd_texture_stage_buffer_range(int token,int buffer_token,int source_offset,int destination_offset,int count) { + int index=(token&1023)-1;if(token<=0||index<0||index>=SLOTS)return -1;Resource *r=&slots[index]; + if(r->kind!=TEXTURE||r->generation!=(token>>10)||!r->detached||r->holds<=0||source_offset<0||destination_offset<0||count<=0|| + ((source_offset|destination_offset|count)&31)||destination_offset!=r->staged_bytes||destination_offset>r->bytes||count>r->bytes-destination_offset)return -1; + uint64_t address=dnd_buffer_held_address(buffer_token,source_offset,count);if(!address)return -1; + memcpy(r->data+destination_offset,(const void*)(uintptr_t)address,(size_t)count); + dnd_draw_backend_flush(r->data+destination_offset,count,0);r->staged_bytes+=count;return 0; +} +int dnd_texture_release_completed(int token,int fence) { + dnd_async_require_application_thread();Resource *r=find(token,TEXTURE); + if(dnd_raw_depth()||!r||r->detached||r->holds||fence<=0||!dnd_device_fence_completed(fence))return -1; + release(r);return 0; +} int dnd_texture_update_native(int token,DndArray *payload,int source_offset,int count) { Resource *r=find(token,TEXTURE); if(dnd_device_active() || dnd_raw_depth() || !r || !payload || @@ -269,7 +305,9 @@ int dnd_texture_stage_buffer(int token,int buffer_token,int offset,int count) { } int dnd_texture_publish_staged(int token) { dnd_async_require_application_thread(); - if(dnd_raw_depth() || dnd_device_pass()==3 || !find(token,TEXTURE))return -1; + Resource *r=find(token,TEXTURE); + if(dnd_raw_depth() || dnd_device_pass()==3 || !r || r->holds || (r->detached&&r->staged_bytes!=r->bytes))return -1; + r->detached=false; /* The backend issues GX_InvalidateTexAll only; no GPU completion wait. */ dnd_draw_backend_publish_texture(); return 0; @@ -383,7 +421,7 @@ int dnd_texture_sampler(int token,int wrap_s,int wrap_t,int min_filter,int mag_f } static bool texture(int token,DndDrawTexture *out) { memset(out,0,sizeof(*out));if(!token)return true; - Resource *r=find(token,TEXTURE);if(!r)return false; + Resource *r=find(token,TEXTURE);if(!r||r->detached)return false; *out=(DndDrawTexture){r->data,(uint32_t)r->bytes,r->width,r->height,r->format,r->linear!=0,r->levels,r->sampler_set,r->wrap_s,r->wrap_t,r->min_filter,r->mag_filter,r->lod_bias};return true; } int dnd_texture_resolve(int token,DndDrawTexture *out){return texture(token,out)?0:-1;} diff --git a/src/DolphinDotNet.GameCube/Dolphin/Graphics/DetachedTextureUpload.cs b/src/DolphinDotNet.GameCube/Dolphin/Graphics/DetachedTextureUpload.cs new file mode 100644 index 000000000..5d796d2f4 --- /dev/null +++ b/src/DolphinDotNet.GameCube/Dolphin/Graphics/DetachedTextureUpload.cs @@ -0,0 +1,90 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace Dolphin.Graphics; + +/// One private single-level allocation. Queue sequential aligned native +/// chunks between frames; the service executor copies/flushes CPU memory only. +/// A failed/cancelled upload cannot publish or invalidate the visible fallback. +public sealed class DetachedTextureUpload : IDisposable +{ + private Texture2D? texture; + private readonly CancellationTokenSource cancellation=new CancellationTokenSource(); + private readonly uint expectedCrc; + private Task? pending; + private int completed,pendingBytes; + private uint crc,pendingCrc; + private bool failed,sealedUpload,aborting,disposed; + public int ExpectedBytes {get;} + public int CompletedBytes {get{Check();Observe();return completed;}} + public int StagedBytes=>texture==null?0:ExpectedBytes; + public bool HasPendingCopy=>pending!=null&&!pending.IsCompleted; + private DetachedTextureUpload(Texture2D target,int bytes,uint checksum){texture=target;ExpectedBytes=bytes;expectedCrc=checksum;} + private static void Application(){if(!Dolphin.Threading.Tasks.Scheduler.IsApplicationThread)throw new InvalidOperationException("Use the application executor for upload ownership and publication.");} + private void Check(){Application();if(disposed)throw new ObjectDisposedException("DetachedTextureUpload");} + public static DetachedTextureUpload Create(int width,int height,NativeTextureFormat format,int expectedNativeBytes,uint expectedCrc32) + { + Application();var target=Texture2D.CreateDetached(width,height,format); + if(target.NativeBytes!=expectedNativeBytes){target.Dispose();throw new ArgumentException("Native payload size differs from texture allocation.");} + return new DetachedTextureUpload(target,expectedNativeBytes,expectedCrc32); + } + private void Observe() + { + if(pending==null)return;if(!pending.IsCompleted)throw new InvalidOperationException("Wait for the pending chunk before reusing its range."); + var work=pending;pending=null; + try{work.GetAwaiter().GetResult();completed+=pendingBytes;crc=pendingCrc;} + catch{failed=true;throw;} + } + /// Source ownership is retained through cancellation and completion. + /// A held source cannot be overwritten through NativeBuffer.Write. Chunks + /// must be contiguous, nonoverlapping, 32-byte aligned and complete. + public Task StageChunkAsync(NativeBuffer source,int sourceOffset,int destinationOffset,int count,CancellationToken cancellationToken=default) + { + Check();Observe();if(texture==null||failed||aborting||sealedUpload)throw new InvalidOperationException("Upload no longer accepts chunks."); + if(source==null)throw new ArgumentNullException("source");source.GetAddress(0); + if(sourceOffset<0||destinationOffset!=completed||count<=0||((sourceOffset|destinationOffset|count)&31)!=0||sourceOffset>source.Length||count>source.Length-sourceOffset||count>ExpectedBytes-completed)throw new ArgumentOutOfRangeException("count"); + cancellationToken.ThrowIfCancellationRequested();cancellation.Token.ThrowIfCancellationRequested(); + pendingCrc=source.ComputeCrc32(sourceOffset,count,crc);pendingBytes=count; + if(NativeGraphics.BufferHold(source.Token)<0)throw new InvalidOperationException("Cannot hold source storage."); + if(NativeGraphics.TextureUploadHold(texture.Token)<0){NativeGraphics.BufferUnhold(source.Token);throw new InvalidOperationException("Cannot hold detached destination.");} + try{pending=Copy(texture.Token,source.Token,sourceOffset,destinationOffset,count,cancellation.Token,cancellationToken);return pending;} + catch{NativeGraphics.TextureUploadUnhold(texture.Token);NativeGraphics.BufferUnhold(source.Token);throw;} + } + private static async Task Copy(int target,int source,int sourceOffset,int destinationOffset,int count,CancellationToken stop,CancellationToken token) + { + try{ + await Task.Run(()=>{ + token.ThrowIfCancellationRequested();stop.ThrowIfCancellationRequested(); + if(NativeGraphics.TextureStageBufferRange(target,source,sourceOffset,destinationOffset,count)<0)throw new InvalidOperationException("Detached range copy failed."); + }); + }finally{NativeGraphics.TextureUploadUnhold(target);NativeGraphics.BufferUnhold(source);} + } + public void Seal() + { + Check();Observe();if(failed||aborting||texture==null)throw new InvalidOperationException("Upload cannot be sealed."); + if(completed!=ExpectedBytes)throw new InvalidOperationException("Upload has missing ranges."); + if(crc!=expectedCrc){failed=true;throw new InvalidDataException("Detached texture payload CRC mismatch.");} + sealedUpload=true; + } + public bool TryPublish(out Texture2D? published) + { + Check();published=null;if(aborting||failed||!sealedUpload||texture==null||HasPendingCopy)return false;Observe(); + texture.PublishDetached();published=texture;texture=null;return true; + } + /// Cancel queued work, join any started CPU copy, then release the + /// never-visible destination. Source and destination remain held until join. + public async Task AbortAsync() + { + Check();aborting=true;cancellation.Cancel();var work=pending; + if(work!=null)try{await work;}catch(Exception){}pending=null; + texture?.Dispose();texture=null;disposed=true;cancellation.Dispose(); + } + public void Dispose() + { + if(disposed)return;Application();aborting=true;cancellation.Cancel(); + if(HasPendingCopy)throw new InvalidOperationException("Await AbortAsync before disposing a running copy."); + if(pending!=null){try{Observe();}catch(Exception){}}texture?.Dispose();texture=null;disposed=true;cancellation.Dispose(); + } +} diff --git a/src/DolphinDotNet.GameCube/Dolphin/Graphics/GpuFence.cs b/src/DolphinDotNet.GameCube/Dolphin/Graphics/GpuFence.cs index 3dce29d61..52b75b732 100644 --- a/src/DolphinDotNet.GameCube/Dolphin/Graphics/GpuFence.cs +++ b/src/DolphinDotNet.GameCube/Dolphin/Graphics/GpuFence.cs @@ -5,6 +5,7 @@ public readonly struct GpuFence { private readonly int value; internal GpuFence(int value){this.value=value;} + internal int Value=>value; public bool IsValid=>value!=0; public bool IsCompleted=>IsValid && NativeGraphics.DeviceFenceCompleted(value)!=0; } diff --git a/src/DolphinDotNet.GameCube/Dolphin/Graphics/NativeGraphics.cs b/src/DolphinDotNet.GameCube/Dolphin/Graphics/NativeGraphics.cs index 658333451..dc18bde3e 100644 --- a/src/DolphinDotNet.GameCube/Dolphin/Graphics/NativeGraphics.cs +++ b/src/DolphinDotNet.GameCube/Dolphin/Graphics/NativeGraphics.cs @@ -68,6 +68,11 @@ internal static class NativeGraphics internal static int TextureSampler(int token,int wrapS,int wrapT,int minFilter,int magFilter,float lodBias) => throw Unsupported(); internal static int TextureDimension(int token,int axis) => throw Unsupported(); internal static int TextureAllocateNative(int width,int height,int format,int linear) => throw Unsupported(); + internal static int TextureAllocateDetached(int width,int height,int format,int linear)=>throw Unsupported(); + internal static int TextureUploadHold(int token)=>throw Unsupported(); + internal static int TextureUploadUnhold(int token)=>throw Unsupported(); + internal static int TextureStageBufferRange(int textureToken,int bufferToken,int sourceOffset,int destinationOffset,int count)=>throw Unsupported(); + internal static int TextureReleaseCompleted(int token,int fence)=>throw Unsupported(); internal static int TextureUpdateNative(int token,byte[] pixels,int sourceOffset,int count) => throw Unsupported(); internal static int TextureUpdateFromBuffer(int textureToken,int bufferToken,int sourceOffset,int count) => throw Unsupported(); internal static int TextureStageArray(int textureToken,byte[] pixels,int offset,int count) => throw Unsupported(); diff --git a/src/DolphinDotNet.GameCube/Dolphin/Graphics/RenderSettings.cs b/src/DolphinDotNet.GameCube/Dolphin/Graphics/RenderSettings.cs index c9b44e265..5e2e6b2c9 100644 --- a/src/DolphinDotNet.GameCube/Dolphin/Graphics/RenderSettings.cs +++ b/src/DolphinDotNet.GameCube/Dolphin/Graphics/RenderSettings.cs @@ -37,6 +37,20 @@ public UvTransform(Vector2 offset,Vector2 scale,float rotationDegrees=0) a=co*scale.X;b=si*scale.X;c=-si*scale.Y;d=co*scale.Y;x=offset.X;y=offset.Y;set=true; } public Vector2 Transform(Vector2 value)=>set?new Vector2(a*value.X+c*value.Y+x,b*value.X+d*value.Y+y):value; + private UvTransform(float a,float b,float c,float d,float x,float y) + { + GraphicsMath.Finite(a);GraphicsMath.Finite(b);GraphicsMath.Finite(c);GraphicsMath.Finite(d);GraphicsMath.Finite(x);GraphicsMath.Finite(y); + this.a=a;this.b=b;this.c=c;this.d=d;this.x=x;this.y=y;set=true; + } + /// Apply this transform, then after. Preserves the full affine + /// matrix, including rotated animation followed by nonuniform atlas gutters. + public UvTransform Then(UvTransform after) + { + if(!set)return after;if(!after.set)return this; + return new UvTransform(after.a*a+after.c*b,after.b*a+after.d*b, + after.a*c+after.c*d,after.b*c+after.d*d, + after.a*x+after.c*y+after.x,after.b*x+after.d*y+after.y); + } internal void Write(float[] values,int at){values[at]=set?a:1;values[at+1]=set?b:0;values[at+2]=set?c:0;values[at+3]=set?d:1;values[at+4]=set?x:0;values[at+5]=set?y:0;} } public enum LightKind { Directional,Point,Spot } diff --git a/src/DolphinDotNet.GameCube/Dolphin/Graphics/Texture2D.cs b/src/DolphinDotNet.GameCube/Dolphin/Graphics/Texture2D.cs index cd5d9cf08..d82a1db0c 100644 --- a/src/DolphinDotNet.GameCube/Dolphin/Graphics/Texture2D.cs +++ b/src/DolphinDotNet.GameCube/Dolphin/Graphics/Texture2D.cs @@ -46,6 +46,20 @@ public static Texture2D FromPng(byte[] png,bool linear=false) } /// Create a GX-tiled, uncompressed-or-CMPR texture ready for repeated /// full-image replacement. Input bytes must use native GX tile order. + internal static Texture2D CreateDetached(int width,int height,NativeTextureFormat format) + { + int token=NativeGraphics.TextureAllocateDetached(width,height,(int)format,1); + if(token==0)throw new InvalidOperationException("Detached texture dimensions, format, frame or native budget."); + return new Texture2D(token); + } + /// Free an immutable texture after its final GPU reader fence is + /// complete, without a redundant global GPU wait. Do not submit it again. + public bool TryDisposeAfterFence(GpuFence finalReader) + { + if(disposed)return true; + if(!finalReader.IsValid||!finalReader.IsCompleted)return false; + GraphicsDevice.Check(NativeGraphics.TextureReleaseCompleted(Token,finalReader.Value),"Invalid final-reader fence or texture retirement state.");disposed=true;return true; + } public static Texture2D CreateNative(int width,int height,NativeTextureFormat format,bool linear=true) { if(format!=NativeTextureFormat.I4 && format!=NativeTextureFormat.I8 && diff --git a/tests/DetachedTextureUploadSmoke/DetachedTextureUploadSmoke.csproj b/tests/DetachedTextureUploadSmoke/DetachedTextureUploadSmoke.csproj new file mode 100644 index 000000000..fc5e92fdd --- /dev/null +++ b/tests/DetachedTextureUploadSmoke/DetachedTextureUploadSmoke.csproj @@ -0,0 +1 @@ +Exenet8.0enable diff --git a/tests/DetachedTextureUploadSmoke/Program.cs b/tests/DetachedTextureUploadSmoke/Program.cs new file mode 100644 index 000000000..4b1b8cb0f --- /dev/null +++ b/tests/DetachedTextureUploadSmoke/Program.cs @@ -0,0 +1,80 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Dolphin.Graphics; +using Dolphin.Formats; +using Scheduler = Dolphin.Threading.Tasks.Scheduler; + +internal static class Program +{ + private readonly struct CrcField + { + internal readonly uint Value; + internal CrcField(uint value){Value=value;} + } + private static void Check(bool value){if(!value)throw new Exception("Detached upload assertion failed.");} + private static void Drain(Task work){for(int i=0;i<10000&&!work.IsCompleted;i++)Scheduler.Pump(1);Check(work.IsCompleted);work.GetAwaiter().GetResult();} + private static int Main() + { + var animation=new UvTransform(new Vector2(.2f,-.3f),new Vector2(2,3),37); + var gutter=new UvTransform(new Vector2(.1f,.2f),new Vector2(.7f,.5f)); + var point=new Vector2(.3f,.8f);var expected=gutter.Transform(animation.Transform(point)); + var actual=animation.Then(gutter).Transform(point); + Check(Math.Abs(expected.X-actual.X)<.00001f&&Math.Abs(expected.Y-actual.Y)<.00001f); + Check(BitConverter.Int32BitsToSingle(0x3fc00000)==1.5f&&float.IsNaN(BitConverter.Int32BitsToSingle(0x7fc00000))); + var reference=new CrcField(0xcbf43926u); + uint calculated=StreamableTextureDescriptor.ComputeCrc32(new byte[]{49,50,51,52,53,54,55,56,57},0,9); + Check(reference.Value==calculated); + if(reference.Value!=calculated)return 9; + Check(unchecked((int)reference.Value)<0&&~reference.Value==0x340bc6d9u); + var bytes=new byte[256];for(int i=0;i +#include +extern intptr_t dnd_aot_entry(DndManagedHeap *heap); +int main(void){static unsigned char storage[2*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,"detached result=%ld error=%s\n",(long)result,dnd_exception_message());return 1;}assert(!dnd_device_active()&&!dnd_draw_live()&&!dnd_draw_total_bytes());puts("Detached upload AOT/GC: range/CRC/cancellation/drain/source disposal/fence retirement passed.");return 0;} diff --git a/tests/detached_texture_test.c b/tests/detached_texture_test.c new file mode 100644 index 000000000..e99ced2e1 --- /dev/null +++ b/tests/detached_texture_test.c @@ -0,0 +1,62 @@ +#include "dnd_draw.h" +#include +#include +#include +#include +static bool frame,application=true; +static int waits,publishes,flushes,completed; +bool dnd_device_active(void){return frame;} +int dnd_device_pass(void){return 0;} +int dnd_raw_depth(void){return 0;} +int dnd_device_fence_completed(int fence){return fence>0&&fence<=completed;} +void dnd_async_require_application_thread(void){assert(application);} +void dnd_draw_backend_wait(void){waits++;} +void dnd_draw_backend_publish_texture(void){assert(application);publishes++;} +void dnd_draw_backend_flush(void *p,int n,int mode){assert(p&&n>0);if(!application)assert(mode==0);flushes++;} +void dnd_draw_backend_2d(int w,int h){(void)w;(void)h;} +void dnd_exception_throw(DndExceptionKind kind,const char *message){(void)kind;(void)message;abort();} +static DndArray *bytes(int n){DndArray *a=calloc(1,sizeof(*a)+(size_t)n);assert(a);a->length=n;a->element_size=1;for(int i=0;idata[i]=(unsigned char)(i*37+11);return a;} +int main(void){ + const int chunk=32768,total=1024*1024; + int source=dnd_buffer_create(chunk,32),target=dnd_texture_allocate_detached(512,512,6,1);assert(source&&target); + assert(dnd_draw_total_bytes()==chunk+total);DndDrawTexture texture; + assert(dnd_texture_resolve(target,&texture)<0);assert(dnd_texture_publish_staged(target)<0); + DndArray *data=bytes(chunk);assert(dnd_buffer_write(source,0,data,0,chunk)==0); + assert(dnd_texture_stage_buffer_range(target,source,0,0,chunk)<0); + int before=waits; + for(int offset=0;offsetdata[i%chunk]); + assert(dnd_texture_release_completed(target,0)<0&&dnd_texture_release_completed(target,9)<0); + completed=9;assert(dnd_texture_release_completed(target,9)==0&&waits==before); + assert(dnd_draw_total_bytes()==chunk);assert(dnd_texture_resolve(target,&texture)<0); + int aborted=dnd_texture_allocate_detached(4,4,6,1);assert(aborted); + assert(dnd_texture_upload_hold(aborted)==0&&dnd_buffer_hold(source)==0); + assert(dnd_draw_release(aborted)==0); /* held, never freed under the worker */ + application=false;assert(dnd_texture_stage_buffer_range(aborted,source,0,0,64)==0);application=true; + assert(dnd_texture_publish_staged(aborted)<0);assert(dnd_texture_upload_unhold(aborted)==0&&dnd_buffer_unhold(source)==0); + assert(dnd_draw_total_bytes()==chunk&&waits==before); + aborted=dnd_texture_allocate_detached(8,8,14,1);frame=true;assert(dnd_draw_release(aborted)==0);frame=false; + assert(dnd_draw_total_bytes()==chunk&&waits==before); + int held_source=dnd_buffer_create(64,32);aborted=dnd_texture_allocate_detached(4,4,6,1); + assert(dnd_buffer_hold(held_source)==0&&dnd_texture_upload_hold(aborted)==0&&dnd_draw_release(held_source)==0); + application=false;assert(dnd_texture_stage_buffer_range(aborted,held_source,0,0,64)==0);application=true; + assert(dnd_texture_upload_unhold(aborted)==0&&dnd_buffer_unhold(held_source)==0); + assert(dnd_draw_release(aborted)==0&&dnd_draw_release(source)==0);free(data); + assert(dnd_draw_total_bytes()==0&&dnd_draw_live()==0&&flushes>0); + puts("Detached texture ranges: holds, 1-MiB chunking, no GX staging/waits, publication, abort and fence retirement passed");return 0; +} diff --git a/tests/fixtures/DetachedTextures/DetachedTextures.csproj b/tests/fixtures/DetachedTextures/DetachedTextures.csproj new file mode 100644 index 000000000..540d1bace --- /dev/null +++ b/tests/fixtures/DetachedTextures/DetachedTextures.csproj @@ -0,0 +1 @@ +Exenet8.0enable diff --git a/tests/fixtures/DetachedTextures/Program.cs b/tests/fixtures/DetachedTextures/Program.cs new file mode 100644 index 000000000..dc4511bdb --- /dev/null +++ b/tests/fixtures/DetachedTextures/Program.cs @@ -0,0 +1,77 @@ +using System; +using System.Threading.Tasks; +using Dolphin.Formats; +using Dolphin.Graphics; +using Scheduler=Dolphin.Threading.Tasks.Scheduler; + +internal static class Program +{ + private static readonly byte[] chunk=new byte[32768]; + private static void Fill(int width,int format,int offset,int count) + { + for(int i=0;i=width/2,bottom=y>=width/2; + byte r=(byte)(right?0:255),g=(byte)(right?255:0),b=(byte)(bottom?255:0); + chunk[i]=at%64<32?(at%2==0?(byte)255:r):(at%2==0?g:b); + } + else + { + int tile=at/32;x=tile%(width/8)*8+(at%32/8%2)*4;y=tile/(width/8)*8+(at%32/16)*4; + int color=(x>=width/2?0x07e0:0xf800)|(y>=width/2?31:0); + int p=at%8;chunk[i]=(byte)(p==0||p==2?color>>8:p==1||p==3?color:0); + } + } + } + private sealed class Lane + { + internal readonly int Format; + internal readonly NativeBuffer Staging=NativeBuffer.Allocate(chunk.Length); + internal Texture2D? Active,Retired; + internal GpuFence LastFence,RetiredFence; + internal DetachedTextureUpload? Upload; + internal Task? Copy; + internal int Width=8,Offset,Publications,LastChange; + internal Lane(int format){Format=format;} + internal void Pump(int frame) + { + if(Retired!=null&&Retired.TryDisposeAfterFence(RetiredFence))Retired=null; + if(Copy!=null){if(!Copy.IsCompleted)return;Copy.GetAwaiter().GetResult();Copy=null;} + if(Upload==null) + { + if(Active!=null&&frame-LastChange<90)return; + Width=Active==null||Width!=8?8:256;Offset=0; + int bytes=StreamableTextureDescriptor.NativeByteCount(Width,Width,Format);uint crc=0; + for(int at=0;atIntrinsicKind.NativeStorage, + ("System.BitConverter","Int32BitsToSingle") when parameterCount==1&¶meterTypes[0]=="Int32"=>IntrinsicKind.NativeStorage, ("Dolphin.Numerics.NativeNumeric",_)=>IntrinsicKind.NativeStorage, ("Dolphin.Text.NativeText",_)=>IntrinsicKind.NativeStorage, ("System.String",".ctor") when (parameterCount is 1 or 3&¶meterTypes.FirstOrDefault()=="Char[]")||(parameterCount==2&¶meterTypes.FirstOrDefault()=="Char")=>IntrinsicKind.StringFromChars, diff --git a/tools/DolphinDotNet.Compiler/MetadataResolver.cs b/tools/DolphinDotNet.Compiler/MetadataResolver.cs index b78f7de44..821a53254 100644 --- a/tools/DolphinDotNet.Compiler/MetadataResolver.cs +++ b/tools/DolphinDotNet.Compiler/MetadataResolver.cs @@ -40,7 +40,7 @@ internal static MethodModel Specialize(MetadataReader md,CompilationModel model, var matches=m.Methods.Values.Where(x=>x.Key.TypeName=="Dolphin.Text.StringOps"&&x.Key.Name==name&&!x.Key.Signature.Contains("|g:",StringComparison.Ordinal)&&m.Assemblies[x.AssemblyName].Metadata.GetMethodDefinition(x.Handle).GetGenericParameters().Count==sig.GenericParameterCount&&x.ParameterCount==parameters.Length&&IoParametersMatch(m,x,adjusted)).ToArray(); if(matches.Length==1)return matches[0]; throw new NotSupportedException($"Unsupported String overload {n}."); - }if(t=="Dolphin.Threading.Tasks.Task"&&n=="Delay")return Find(m,"Dolphin.Timing.Time","DelayAsync",signature,incoming);var facade=t switch { "System.Array" when incoming?.GenericParameterCount>0=>"Dolphin.Collections.ArrayOps", "System.Byte" or "System.SByte" or "System.Int16" or "System.UInt16" or "System.Boolean" or "System.Int32" or "System.UInt32" or "System.Int64" or "System.UInt64" or "System.Single" or "System.Double" when n is "Parse" or "TryParse" or "IsNaN" or "IsInfinity" or "IsPositiveInfinity" or "IsNegativeInfinity" or "IsFinite"=>"Dolphin.Numerics."+t.Substring(7), "System.Collections.Generic.EqualityComparer`1"=>"Dolphin.Collections.EqualityComparer`1", "System.Collections.Generic.Comparer`1"=>"Dolphin.Collections.Comparer`1", "System.Nullable"=>"Dolphin.Collections.Nullable", "System.IO.File"=>"Dolphin.IO.File", "System.IO.Directory"=>"Dolphin.IO.Directory", "System.IO.Path"=>"Dolphin.IO.Path", "System.IO.Stream"=>"Dolphin.IO.Stream", "System.IO.MemoryStream"=>"Dolphin.IO.MemoryStream", "System.IO.FileStream"=>"Dolphin.IO.FileStream", "System.IO.DirectoryInfo"=>"Dolphin.IO.DirectoryInfo", _=>null };if(facade is not null&&m.Types.ContainsKey(facade)){var bytes=Convert.FromHexString(signature);var at=1;if((bytes[0]&0x10)!=0)at++;var count=bytes[at];var matches=m.Methods.Values.Where(x=>x.Key.TypeName==facade&&x.Key.Name==n&&!x.Key.Signature.Contains("|g:",StringComparison.Ordinal)&&x.ParameterCount==count&&(incoming is null||IoParametersMatch(m,x,incoming.Value))).ToArray();if(matches.Length==1)return matches[0];throw new NotSupportedException($"Unsupported System.IO overload {t}::{n} ({count} parameters).");}var exact=m.Methods.Values.Where(x=>x.Key.TypeName==t&&x.Key.Name==n&&x.Key.Signature==signature).ToArray();if(exact.Length==1)return exact[0];if(m.Types.TryGetValue(t,out var tm)&&tm.BaseType is {} parent&&m.Types.ContainsKey(parent)&&n!=".ctor"&&!m.Methods.Values.Any(x=>x.Key.TypeName==t&&x.Key.Name==n))return Find(m,parent,n,signature,incoming);var candidates=m.Methods.Values.Where(x=>x.Key.TypeName==t&&x.Key.Name==n&&!x.Key.Signature.Contains("|g:",StringComparison.Ordinal)&&!x.Key.Signature.Contains("|contract:",StringComparison.Ordinal)&&(incoming is null || (x.ParameterCount==incoming.Value.ParameterTypes.Length&&IoParametersMatch(m,x,incoming.Value)))).ToArray();return candidates.Length==1?candidates[0]:throw new NotSupportedException($"DND1003: Unsupported, missing, or ambiguous API {t}::{n} [{signature}]. Closed-world AOT requires a managed implementation or Dolphin intrinsic. Remove reflection, dynamic loading, host-only APIs and unregistered P/Invoke; see docs/system-api.md.");} + }if(t=="Dolphin.Threading.Tasks.Task"&&n=="Delay")return Find(m,"Dolphin.Timing.Time","DelayAsync",signature,incoming);var facade=t switch { "System.BitConverter" when n=="Int32BitsToSingle"=>"Dolphin.Numerics.BitConverter", "System.Array" when incoming?.GenericParameterCount>0=>"Dolphin.Collections.ArrayOps", "System.Byte" or "System.SByte" or "System.Int16" or "System.UInt16" or "System.Boolean" or "System.Int32" or "System.UInt32" or "System.Int64" or "System.UInt64" or "System.Single" or "System.Double" when n is "Parse" or "TryParse" or "IsNaN" or "IsInfinity" or "IsPositiveInfinity" or "IsNegativeInfinity" or "IsFinite"=>"Dolphin.Numerics."+t.Substring(7), "System.Collections.Generic.EqualityComparer`1"=>"Dolphin.Collections.EqualityComparer`1", "System.Collections.Generic.Comparer`1"=>"Dolphin.Collections.Comparer`1", "System.Nullable"=>"Dolphin.Collections.Nullable", "System.IO.File"=>"Dolphin.IO.File", "System.IO.Directory"=>"Dolphin.IO.Directory", "System.IO.Path"=>"Dolphin.IO.Path", "System.IO.Stream"=>"Dolphin.IO.Stream", "System.IO.MemoryStream"=>"Dolphin.IO.MemoryStream", "System.IO.FileStream"=>"Dolphin.IO.FileStream", "System.IO.DirectoryInfo"=>"Dolphin.IO.DirectoryInfo", _=>null };if(facade is not null&&m.Types.ContainsKey(facade)){var bytes=Convert.FromHexString(signature);var at=1;if((bytes[0]&0x10)!=0)at++;var count=bytes[at];var matches=m.Methods.Values.Where(x=>x.Key.TypeName==facade&&x.Key.Name==n&&!x.Key.Signature.Contains("|g:",StringComparison.Ordinal)&&x.ParameterCount==count&&(incoming is null||IoParametersMatch(m,x,incoming.Value))).ToArray();if(matches.Length==1)return matches[0];throw new NotSupportedException($"Unsupported System.IO overload {t}::{n} ({count} parameters).");}var exact=m.Methods.Values.Where(x=>x.Key.TypeName==t&&x.Key.Name==n&&x.Key.Signature==signature).ToArray();if(exact.Length==1)return exact[0];if(m.Types.TryGetValue(t,out var tm)&&tm.BaseType is {} parent&&m.Types.ContainsKey(parent)&&n!=".ctor"&&!m.Methods.Values.Any(x=>x.Key.TypeName==t&&x.Key.Name==n))return Find(m,parent,n,signature,incoming);var candidates=m.Methods.Values.Where(x=>x.Key.TypeName==t&&x.Key.Name==n&&!x.Key.Signature.Contains("|g:",StringComparison.Ordinal)&&!x.Key.Signature.Contains("|contract:",StringComparison.Ordinal)&&(incoming is null || (x.ParameterCount==incoming.Value.ParameterTypes.Length&&IoParametersMatch(m,x,incoming.Value)))).ToArray();return candidates.Length==1?candidates[0]:throw new NotSupportedException($"DND1003: Unsupported, missing, or ambiguous API {t}::{n} [{signature}]. Closed-world AOT requires a managed implementation or Dolphin intrinsic. Remove reflection, dynamic loading, host-only APIs and unregistered P/Invoke; see docs/system-api.md.");} private static bool IoParametersMatch(CompilationModel model,MethodModel method,MethodSignature incoming) { if(method.Handle.IsNil)return method.ParameterCount==incoming.ParameterTypes.Length; var md=model.Assemblies[method.AssemblyName].Metadata; diff --git a/tools/DolphinDotNet.Compiler/NativeStorageBindings.cs b/tools/DolphinDotNet.Compiler/NativeStorageBindings.cs index fe4feb5a1..bfaa2a56e 100644 --- a/tools/DolphinDotNet.Compiler/NativeStorageBindings.cs +++ b/tools/DolphinDotNet.Compiler/NativeStorageBindings.cs @@ -107,6 +107,11 @@ internal static class NativeStorageBindings ["TextureUpdateNative"]=("dnd_texture_update_native","iaii",false), ["TextureUpdateFromBuffer"]=("dnd_texture_update_buffer","iiii",false), ["TextureStageArray"]=("dnd_texture_stage_array","iaii",false), + ["TextureAllocateDetached"]=("dnd_texture_allocate_detached","iiii",false), + ["TextureUploadHold"]=("dnd_texture_upload_hold","i",false), + ["TextureUploadUnhold"]=("dnd_texture_upload_unhold","i",false), + ["TextureStageBufferRange"]=("dnd_texture_stage_buffer_range","iiiii",false), + ["TextureReleaseCompleted"]=("dnd_texture_release_completed","ii",false), ["TextureStageBuffer"]=("dnd_texture_stage_buffer","iiii",false), ["TexturePublishStaged"]=("dnd_texture_publish_staged","i",false), ["MeshDraw"]=("dnd_mesh_draw_effect","iiaiifi",false), @@ -281,7 +286,7 @@ internal static void Emit(StringBuilder b,ValueIrNativeStorage call) // Only CPU-side staging copies are safe on the service executor. // Publication, allocation and every other texture/GX operation require // the application executor. Keep this list deliberately restrictive. - bool detachedTextureCopy = call.Operation is "TextureStageArray" or "TextureStageBuffer"; + bool detachedTextureCopy = call.Operation is "TextureStageArray" or "TextureStageBuffer" or "TextureStageBufferRange"; if(call.Operation.StartsWith("Device",StringComparison.Ordinal)||call.Operation.StartsWith("Buffer",StringComparison.Ordinal)||call.Operation.StartsWith("Draw",StringComparison.Ordinal)||(!detachedTextureCopy && call.Operation.StartsWith("Texture",StringComparison.Ordinal))||call.Operation.StartsWith("Mesh",StringComparison.Ordinal)||call.Operation.StartsWith("Canvas",StringComparison.Ordinal)||call.Operation=="NativeObjectSize"||call.Operation.StartsWith("Graphics",StringComparison.Ordinal)||call.Operation.StartsWith("Input",StringComparison.Ordinal)||(call.Operation.StartsWith("Audio",StringComparison.Ordinal)&&call.Operation is not ("AudioInit" or "AudioBegin" or "AudioBeginMemory" or "AudioBeginSource" or "AudioStep" or "AudioDispose" or "AudioStat"))||call.Operation=="AssetCompatReport"||call.Operation is "ModelDrawModels" or "ModelDraw" or "ModelDrawEffect" or "ModelDrawMaterial" or "ModelFrameBegin" or "ModelFrameEnd" or "PlatformReset" or "HardwareProbe" or "HardwareId") b.AppendLine(" dnd_async_require_application_thread();"); if(call.Operation=="Publish") diff --git a/tools/DolphinDotNet.Compiler/ValueCBackend.cs b/tools/DolphinDotNet.Compiler/ValueCBackend.cs index 4221f5f83..5c44eb6b9 100644 --- a/tools/DolphinDotNet.Compiler/ValueCBackend.cs +++ b/tools/DolphinDotNet.Compiler/ValueCBackend.cs @@ -314,7 +314,10 @@ string ArgumentName(int index) { case ValueIrCopyObject x:b.AppendLine($" memcpy((void*)v{x.Destination.Id}, (void*)v{x.Source.Id}, {(x.Size>0?x.Size:ValueTypeSize(x.TypeName,model))}u);");break; case ValueIrFloatConstant x:b.AppendLine(x.Single?$" {{uint32_t bits=0x{unchecked((uint)x.Bits):x}u;float value;memcpy(&value,&bits,4);v{x.Result.Id}=value;}}":$" {{uint64_t bits=UINT64_C(0x{unchecked((ulong)x.Bits):x});double value;memcpy(&value,&bits,8);v{x.Result.Id}=value;}}");break; case ValueIrConvert x:var cast=x.Opcode switch {0x67=>"int8_t",0x68=>"int16_t",0x69=>"int32_t",0x6a=>"int64_t",0x6b=>"float",0x6c=>"double",0x6d=>"uint32_t",0x6e=>"uint64_t",0xd1=>"uint16_t",0xd2=>"uint8_t",_=>CType(x.Result.Kind)};b.AppendLine(x.Opcode==0x76?$" v{x.Result.Id} = (double)({(x.Value.Kind==IrValueKind.I8?"uint64_t":"uint32_t")})v{x.Value.Id};":x.Value.Kind==IrValueKind.I4&&x.Opcode is 0x6a or 0x6e?$" v{x.Result.Id} = ({cast})({(x.Opcode==0x6e?"uint32_t":"int32_t")})v{x.Value.Id};":$" v{x.Result.Id} = ({cast})v{x.Value.Id};");break; - case ValueIrUnary x:b.AppendLine($" v{x.Result.Id}={(x.Operation=="not"?"~":"-")}v{x.Value.Id};");break; + case ValueIrUnary x: + b.AppendLine(x.Value.Kind==IrValueKind.I4 + ?$" v{x.Result.Id}=(int32_t)({(x.Operation=="not"?"~":"-")}(uint32_t)v{x.Value.Id});" + :$" v{x.Result.Id}={(x.Operation=="not"?"~":"-")}v{x.Value.Id};");break; case ValueIrBinary x: { var unsigned = x.Operation.EndsWith(".un", StringComparison.Ordinal); @@ -342,8 +345,12 @@ string ArgumentName(int index) { else { var unsignedType=x.Left.Kind==IrValueKind.I8?"uint64_t":x.Left.Kind==IrValueKind.I4?"uint32_t":"uintptr_t"; - var left = unsigned ? $"({unsignedType})v{x.Left.Id}" : $"v{x.Left.Id}"; - var right = unsigned ? $"({unsignedType})v{x.Right.Id}" : $"v{x.Right.Id}"; + // I4 stack values have exactly 32 significant bits, + // even when uint fields were zero-extended into a + // 64-bit host intptr_t and arithmetic sign-extended. + bool i4=x.Left.Kind==IrValueKind.I4&&x.Right.Kind==IrValueKind.I4; + var left = unsigned ? $"({unsignedType})v{x.Left.Id}" : i4?$"(int32_t)v{x.Left.Id}":$"v{x.Left.Id}"; + var right = unsigned ? $"({unsignedType})v{x.Right.Id}" : i4?$"(int32_t)v{x.Right.Id}":$"v{x.Right.Id}"; b.AppendLine($" v{x.Result.Id} = {left} {op} {right};"); } break; @@ -643,8 +650,9 @@ private static void EmitTerminator(StringBuilder b,ValueIrMethod method,ValueIrB var floating = IsFloating(x.Left) || (x.Right is { } operand && IsFloating(operand)); var unsignedInteger = x.Unsigned && !floating; var unsignedType=x.Left.Kind==IrValueKind.I8?"uint64_t":x.Left.Kind==IrValueKind.I4?"uint32_t":"uintptr_t"; - var left = unsignedInteger ? $"({unsignedType})v{x.Left.Id}" : $"v{x.Left.Id}"; - var right = x.Right is { } rv ? (unsignedInteger ? $"({unsignedType})v{rv.Id}" : $"v{rv.Id}") : "0"; + bool i4=x.Left.Kind==IrValueKind.I4&&(x.Right==null||x.Right.Value.Kind==IrValueKind.I4); + var left = unsignedInteger ? $"({unsignedType})v{x.Left.Id}" : i4?$"(int32_t)v{x.Left.Id}":$"v{x.Left.Id}"; + var right = x.Right is { } rv ? (unsignedInteger ? $"({unsignedType})v{rv.Id}" : i4?$"(int32_t)v{rv.Id}":$"v{rv.Id}") : "0"; var op=x.Comparison switch{ValueIrComparison.NonZero=>"!=",ValueIrComparison.Equal=>"==",ValueIrComparison.NotEqual=>"!=",ValueIrComparison.GreaterThan=>">",ValueIrComparison.GreaterOrEqual=>">=",ValueIrComparison.LessThan=>"<",ValueIrComparison.LessOrEqual=>"<=",_=>throw new InvalidDataException()}; var condition = floating ? FloatingComparison(left, right, op, x.Unsigned) : $"{left} {op} {right}"; b.AppendLine($" if ({condition}) {{");