ui

source of pkg::alloy::gpu

1// The GPU, the same way on every platform (PLAN.md, stage F2):2// an API in WebGPU's shape over Vulkan, Metal on macOS (F7b), WebGPU in3// the browser, and a CPU4// rasterizer that runs the same shaders, for tests and where no GPU is.5//6// The device owns every object it makes; the program holds handles,7// small values it copies freely, and gives them back with `release`8// (PLAN.md, F2 question 5): a handle used after its release9// faults.10// Commands are recorded into an encoder, then submitted.11//12// ```text13// const TRIANGLE = #shader(#read_file("triangle.wgsl"));14//15// var device = if (Device::open(Backend::Automatic) is ::Ok |move d|) move d else { ... };16// const shader = device.shader(&TRIANGLE);17// const pipeline = device.render_pipeline(&RenderPipelineDescriptor::simple(shader, TextureFormat::Rgba8Unorm));18// const target = device.texture(&TextureDescriptor::target(256, 256, TextureFormat::Rgba8Unorm));19// var encoder = Encoder::empty();20// encoder.begin_render_pass(target, ::Some(Color::black()));21// encoder.set_pipeline(pipeline);22// encoder.draw(3, 1);23// encoder.end_render_pass();24// device.submit(move encoder);25// const pixels = device.read_texture(target);26// ```27//28// ## How it was built29//30// Notes kept from each stage as it was finished, the sizes and numbers31// of their day; what changed since is in REVIEW.md and the history.32//33// **F2 so far** (2026-10-12):34// - `#shader` compiles WGSL while compiling into SPIR-V 1.335//   (`gpu/shader/`), which the CPU device interprets and rasterizes by36//   WebGPU's rules (`gpu/cpu/`).37// - Vulkan (`gpu/vulkan/`): `vk.alloy` the structures, numbers and38//   functions used, written by hand from the headers, which39//   `vulkan/layouts.alloy` checks them against through clang (sizes and40//   offsets from `-fdump-record-layouts-simple`, constants as static41//   assertions) rather than reading `vk.xml`: the same source of truth with42//   no XML to parse. `vulkan.alloy` the device: Vulkan 1.1 with dynamic43//   rendering and synchronization2 or 1.3, a discrete GPU first, writes44//   staged into the next submission, two submissions in flight, textures45//   resting in one layout between commands and full barriers after46//   passes, copies and dispatches. `Device::open(Automatic)` takes Vulkan47//   where it opens, else the CPU.48// - `tests/scenes.alloy` draws the five golden scenes and checks a compute49//   dispatch: the same on the CPU, on lavapipe, on biscuit's GTX 166050//   (`distrobox-host-exec`) and on the Windows desktop's RTX 4070 Ti over51//   SSH, within one level of each channel.52// - Surfaces: `device.surface(&window)`, then each frame `acquire` (a53//   texture of the window's size), commands, `present`. The window gives54//   its native objects (`window.target()`: the `wl_display` and55//   `wl_surface`, or the `HINSTANCE` and `HWND`) and learns of a frame56//   presented (`window.surface_presented()`), after which it neither draws57//   its own frame nor waits for the display: the swap chain, in FIFO mode,58//   paces redraws (the Wayland loop then handles the events already59//   there between frames). On Wayland the viewport or buffer scale is set60//   when the size changes, before any frame of that size, whoever commits61//   it. The CPU device's surface presents through `window.present`.62//   `samples/triangle.alloy` is the demo; `tests/surface.alloy` draws ten63//   frames and checks their pixels, under weston on lavapipe and in node's64//   page on the CPU. Not yet run where a person sees it: on biscuit's65//   desktop or the Windows desktop (`triangle.exe` and `surface.exe` are66//   in `.alloy\window-tests` there). NVIDIA's driver cannot present to a67//   headless weston, which offers no dmabuf.68// - WebGPU (`gpu/webgpu/`): `webgpu.web.js` opens the browser's device in69//   `prepare()`, which the web glue now awaits before `main` (spec 6.3),70//   and keeps the objects, the program holding their indices; shaders are71//   the WGSL `#shader` checked, carried in the blob for web builds. Each72//   entry point records the resources it uses (blob version 2), so a73//   pipeline's layout holds the shader's layout for each group its entry74//   points use and an empty one for a group below that they skip, as75//   WebGPU wants every group of a layout bound. Surfaces are the window's76//   canvas (`Target::Canvas`, marked `data-alloy-window`), whose 2D77//   context the window now makes only at its first `present`. WebGPU78//   cannot read back at once, so `read_texture` and `read_buffer` give79//   nothing there.80// - Tested on WebGPU in node through Dawn's package (`npm install --prefix81//   ~/.local/share/alloy/node-webgpu webgpu`, on lavapipe here):82//   `tests/web/webgpu.mjs` gives the fake page a WebGPU canvas, fails the83//   run on any WebGPU error, and reads back what the program drew once it84//   is done: the five scenes match the goldens, the compute dispatch85//   validates, and the surface test's canvas holds the triangle.86// - Objects are freed by `device.release(handle)` (question 5A). Each87//   handle carries its index's generation, which a release moves on, and88//   every use checks it, a released handle faulting in every build (std89//   has no way yet to tell a checked build). Indices are taken again by90//   the next object of their kind (`gpu/slots.alloy`), but for shaders,91//   whose pipelines keep reading their layouts. Vulkan frees an object once92//   the submissions made before its release have run, dropping writes to93//   it still waiting; WebGPU destroys buffers and textures, which it does94//   once the work submitted has run; the CPU frees at once. A surface's95//   textures go with it. The scenes release what each one made, so the96//   next ones draw over taken-again indices, and `tests/released.alloy`97//   must fault.98// - The Windows desktop ran `triangle.exe`, `surface.exe` and the demo in99//   its browser (the user, 2026-10-12: "All windows tests work100//   perfectly"). Left: the demo on biscuit's desktop.101//102// **The CPU device compiled** (2026-10-17; decisions/showcase.md,103// question 8A):104// - `cpu/interpreter.alloy` still decodes a module into ops, then compiles105//   each entry point into steps (`Step`: an `Action` and the registers it106//   reads and writes), which `run` goes through with no ids, types nor107//   operands looked up. Calls are inlined, parameters reading the108//   arguments' registers; a composite's part, a vector's leading109//   components and a pointer into memory by constants read registers110//   already there; composites of constants and such pointers are made111//   while compiling; a load or store through a variable's pointer is one112//   step on memory; a buffer's value reads the offsets its type's layout113//   gives; a part or a returned value used once is made where it goes; a114//   branch to the next block is dropped and one on a comparison made for115//   it alone is one step; the most frequent operations have steps of116//   their own. Closures were not used: a match over steps is what the117//   compiler makes fastest.118// - Every golden the same. The showcase's events screen, 1120 by 780,119//   from 14.7 to 2.0 s; its fourteen screens six at a time from 19.3 s120//   (99 s of CPU) to 2.7 s (14 s); `tests/widgets` from 21.4 to 3.3 s;121//   `bench/canvas.alloy cpu` a whole 1920x1080 frame of 10,000122//   primitives from 20.9 to 3.3 s, a frame around one node from 32 to123//   7.6 ms, a page of text from 3.0 to 0.46 s; `scripts/test.sh` from 18124//   to 9 minutes.125// - Size, as `scripts/bench.sh` builds them: the counter 1,907,088 bytes126//   natively (+14.9 KB) and 1,357,046 of wasm (+6.9 KB), hello world127//   1,658,880 (+14.4 KB) and 1,103,679 (+6.2 KB): past the budgets of128//   the counter and of hello world's wasm (showcase.md, question 16).129130import std::string;131import std::vector;132import std::option;133import std::process;134135import shader::compiler;136import shader::blob;137import shader::msl;138import commands;139import slots;140import cpu::device;141import vulkan::vulkan;142import metal::metal;143import webgpu::webgpu;144import pkg::alloy::window;145146// Compiles a WGSL module while compiling the program, for the device's147// `shader`: errors in it are the program's compile-time errors.148//149// ```text150// const TRIANGLE = #shader(#read_file("triangle.wgsl"));151// ```152exp macro shader(source: [u8]) -> [u8] {153    const compiled = compile(&source);154    if (compiled.error.length() != 0) {155        const message = f"WGSL: {compiled.error}";156        panic message.view();157    }158    const wgsl: &[u8] = if (target() == "web-wasm32") &source else &"";159    var msl = String::empty();160    if (target() == "macos-arm64" || target() == "macos-x86_64") {161        const written = write_msl(&compiled);162        if (written.error.length() != 0) {163            const message = f"WGSL to MSL: {written.error}";164            panic message.view();165        }166        msl = copy written.source;167    }168    const bytes = encode(&compiled, &wgsl, &msl.view());169    return copy bytes.view();170}171172// The MSL source the Metal device compiles for a WGSL module, on any173// target, for tools and tests (`#shader` keeps it on macOS only).174exp macro msl(source: [u8]) -> [u8] {175    const compiled = compile(&source);176    if (compiled.error.length() != 0) {177        const message = f"WGSL: {compiled.error}";178        panic message.view();179    }180    const written = write_msl(&compiled);181    if (written.error.length() != 0) {182        const message = f"WGSL to MSL: {written.error}";183        panic message.view();184    }185    const bytes = Vector<u8>::from(&written.source.view());186    return copy bytes.view();187}188189// The SPIR-V module `#shader` compiled, for tools such as spirv-val.190exp fn spirv_words(compiled: &[u8]) -> Vector<u32> {191    if (decode(&compiled) is ::Some |&d|) {192        return copy d.spirv;193    }194    return Vector<u32>::empty();195}196197// A value, or why there is none.198exp type Result<T> = enum {199    Ok: T,200    Error: String,201};202203// Which implementation a device uses.204exp type Backend = enum {205    // Vulkan on Linux and Windows, Metal on macOS, WebGPU in a browser,206    // the CPU where none is there207    Automatic,208    Vulkan,209    Metal,210    WebGpu,211    Cpu,212};213214exp type Device = struct {215    backend: Backend,216    driver: *var Driver,217    generations: Generations,218};219220// What a backend does for the device, called through one object: only221// the backends a target can open are built into its programs.222pub interface Driver {223    fn device_name(self: &) -> String;224    fn buffer(self: &var, size: u64, usage: u32) -> Buffer;225    fn write_buffer(self: &var, buffer: Buffer, offset: u64, bytes: &[u8]);226    fn texture(self: &var, d: &TextureDescriptor) -> Texture;227    fn write_texture(228        self: &var,229        texture: Texture,230        x: u32,231        y: u32,232        width: u32,233        height: u32,234        bytes: &[u8]235    );236    fn sampler(self: &var, d: &SamplerDescriptor) -> Sampler;237    fn shader(self: &var, compiled: &[u8]) -> Shader;238    fn render_pipeline(self: &var, d: &RenderPipelineDescriptor) -> RenderPipeline;239    fn compute_pipeline(self: &var, shader: Shader, entry: &[u8]) -> ComputePipeline;240    fn render_bind_group(241        self: &var,242        pipeline: RenderPipeline,243        group: u32,244        bindings: &[Binding]245    ) -> BindGroup;246    fn compute_bind_group(247        self: &var,248        pipeline: ComputePipeline,249        group: u32,250        bindings: &[Binding]251    ) -> BindGroup;252    fn submit(self: &var, encoder: &Encoder);253    // none on WebGPU, which reads back only in the browser's event loop254    fn read_texture(self: &var, texture: Texture) -> Vector<u8>;255    fn read_buffer(self: &var, buffer: Buffer) -> Vector<u8>;256    fn window_surface(self: &var, window: &Window) -> Result<Surface>;257    fn acquire(self: &var, surface: u32, width: u32, height: u32) -> Option<Texture>;258    // shows the surface's texture acquired, telling the window so259    fn show(self: &var, surface: u32, window: &var Window);260    fn release(self: &var, kind: ObjectKind, index: u32);261    // the surface's textures, released with it262    fn release_surface(self: &var, surface: u32) -> Vector<u32>;263}264265fn opened(backend: Backend, driver: *var Driver) -> Result<Device> {266    return ::Ok(Device {267        .backend = backend,268        .driver = move driver,269        .generations = Generations {}270    });271}272273// Opens a device: on the backend asked for, failing when it is not274// there, or the best one there for `Automatic`.275exp fn Device::open(backend: Backend) -> Result<Device> {276    if (backend is ::Cpu) {277        return opened(Backend::Cpu, new CpuDevice {});278    }279    if (target() == "linux-x86_64" || target() == "linux-aarch64" || target() == "windows-x86_64") {280        if (backend is ::Automatic || backend is ::Vulkan) {281            match (VulkanDevice::open()) {282                ::Ok |move v| {283                    return opened(Backend::Vulkan, new move v);284                }285                ::Error |move error| {286                    if (backend is ::Vulkan) {287                        return ::Error(move error);288                    }289                }290            }291        }292    }293    if (target() == "macos-arm64" || target() == "macos-x86_64") {294        if (backend is ::Automatic || backend is ::Metal) {295            match (MetalDevice::open()) {296                ::Ok |move m| {297                    return opened(Backend::Metal, new move m);298                }299                ::Error |move error| {300                    if (backend is ::Metal) {301                        return ::Error(move error);302                    }303                }304            }305        }306    }307    if (target() == "web-wasm32") {308        if (!(backend is ::Vulkan)) {309            match (WebGpuDevice::open()) {310                ::Ok |move w| {311                    return opened(Backend::WebGpu, new move w);312                }313                ::Error |move error| {314                    if (backend is ::WebGpu) {315                        return ::Error(move error);316                    }317                }318            }319        }320    }321    if (backend is ::Automatic) {322        return Device::open(Backend::Cpu);323    }324    return ::Error(String::from(&"this backend is not available here"));325}326327// The backend the device runs on: never `Automatic`.328exp fn backend(self device: &Device) -> Backend {329    return device.backend;330}331332// The GPU's name, or `CPU`.333exp fn name(self device: &Device) -> String => device.driver.device_name();334335/* --- Objects --- */336337// What a buffer may be used for: these combined with `|`.338exp const BUFFER_VERTEX: u32 = 1;339exp const BUFFER_INDEX: u32 = 2;340exp const BUFFER_UNIFORM: u32 = 4;341exp const BUFFER_STORAGE: u32 = 8;342exp const BUFFER_COPY_SOURCE: u32 = 16;343exp const BUFFER_COPY_DESTINATION: u32 = 32;344345// What a texture may be used for: these combined with `|`.346exp const TEXTURE_SAMPLED: u32 = 1;347exp const TEXTURE_RENDER_TARGET: u32 = 2;348exp const TEXTURE_COPY_SOURCE: u32 = 4;349exp const TEXTURE_COPY_DESTINATION: u32 = 8;350351exp type Buffer = struct {352    pub index: u32,353    pub generation: u32,354    exp size: u64,355};356357exp type TextureFormat = enum {358    Rgba8Unorm,359    Bgra8Unorm,360    R8Unorm, // one channel, as coverage for masks361};362363// The bytes a pixel of the format takes.364exp fn bytes_per_pixel(self format: &TextureFormat) -> u64 {365    return if (format is ::R8Unorm) 1 else 4;366}367368exp type Texture = struct {369    pub index: u32,370    pub generation: u32,371    exp width: u32,372    exp height: u32,373    exp format: TextureFormat,374};375376exp type TextureDescriptor = struct {377    exp width: u32,378    exp height: u32,379    exp format: TextureFormat,380    exp usage: u32,381};382383// A texture to render into and read back.384exp fn TextureDescriptor::target(385    width: u32,386    height: u32,387    format: TextureFormat388) -> TextureDescriptor {389    return TextureDescriptor {390        .width = width,391        .height = height,392        .format = format,393        .usage = TEXTURE_RENDER_TARGET | TEXTURE_COPY_SOURCE | TEXTURE_SAMPLED394    };395}396397exp type Sampler = struct {398    pub index: u32,399    pub generation: u32,400};401402exp type SamplerDescriptor = struct {403    exp linear: bool, // linear filtering, else nearest404    exp repeat: bool, // repeating coordinates, else clamped to the edge405};406407exp type Shader = struct {408    pub index: u32,409    pub generation: u32,410};411412exp type VertexFormat = enum {413    Float32,414    Float32x2,415    Float32x3,416    Float32x4,417    Uint32,418    Sint32,419    Unorm8x4,420};421422exp type VertexAttribute = struct {423    exp format: VertexFormat,424    exp offset: u32,425    exp location: u32,426};427428// A vertex buffer's layout: the distance between vertices, whether it429// steps once an instance rather than once a vertex, and its attributes.430exp type VertexLayout = struct {431    exp stride: u32,432    exp instanced: bool,433    exp attributes: Vector<VertexAttribute>,434};435436exp type Blend = enum {437    Replace,438    Alpha, // over what is there, by the color's alpha439    Premultiplied, // over what is there, the color already multiplied by its alpha440};441442exp type Topology = enum {443    Triangles,444    TriangleStrip,445};446447exp type RenderPipelineDescriptor = struct {448    exp shader: Shader,449    exp vertex: String, // the vertex entry point's name450    exp fragment: String,451    exp buffers: Vector<VertexLayout>,452    exp format: TextureFormat,453    exp blend: Blend,454    exp topology: Topology,455};456457// Entry points `vs` and `fs`, no vertex buffers, triangles, replacing.458exp fn RenderPipelineDescriptor::simple(459    shader: Shader,460    format: TextureFormat461) -> RenderPipelineDescriptor {462    return RenderPipelineDescriptor {463        .shader = shader,464        .vertex = String::from(&"vs"),465        .fragment = String::from(&"fs"),466        .buffers = Vector<VertexLayout>::empty(),467        .format = format,468        .blend = Blend::Replace,469        .topology = Topology::Triangles470    };471}472473exp type RenderPipeline = struct {474    pub index: u32,475    pub generation: u32,476};477478exp type ComputePipeline = struct {479    pub index: u32,480    pub generation: u32,481};482483// What a binding of a bind group holds.484exp type BindingResource = enum {485    Buffer: Buffer, // all of it486    BufferRange: BufferRange,487    Texture: Texture,488    Sampler: Sampler,489};490491exp type BufferRange = struct {492    exp buffer: Buffer,493    exp offset: u64,494    exp size: u64,495};496497exp type Binding = struct {498    exp binding: u32,499    exp resource: BindingResource,500};501502exp type BindGroup = struct {503    pub index: u32,504    pub generation: u32,505    exp group: u32,506};507508exp type Color = struct {509    exp r: f32,510    exp g: f32,511    exp b: f32,512    exp a: f32,513};514515exp fn Color::black() -> Color {516    return Color { .r = 0.0, .g = 0.0, .b = 0.0, .a = 1.0 };517}518519exp fn Color::rgb(r: f32, g: f32, b: f32) -> Color {520    return Color { .r = r, .g = g, .b = b, .a = 1.0 };521}522523exp fn Color::rgba(r: f32, g: f32, b: f32, a: f32) -> Color {524    return Color { .r = r, .g = g, .b = b, .a = a };525}526527exp fn Color::white() -> Color {528    return Color { .r = 1.0, .g = 1.0, .b = 1.0, .a = 1.0 };529}530531exp fn Color::transparent() -> Color {532    return Color { .r = 0.0, .g = 0.0, .b = 0.0, .a = 0.0 };533}534535/* --- Making and releasing objects --- */536537exp fn buffer(self device: &var Device, size: u64, usage: u32) -> Buffer {538    var made = device.driver.buffer(size, usage);539    made.generation = device.generations.stamp(::Buffer, made.index);540    return made;541}542543exp fn texture(self device: &var Device, descriptor: &TextureDescriptor) -> Texture {544    var made = device.driver.texture(&descriptor);545    made.generation = device.generations.stamp(::Texture, made.index);546    return made;547}548549exp fn sampler(self device: &var Device, descriptor: &SamplerDescriptor) -> Sampler {550    var made = device.driver.sampler(&descriptor);551    made.generation = device.generations.stamp(::Sampler, made.index);552    return made;553}554555// The shader `#shader` compiled.556exp fn shader(self device: &var Device, compiled: &[u8]) -> Shader {557    var made = device.driver.shader(&compiled);558    made.generation = device.generations.stamp(::Shader, made.index);559    return made;560}561562exp fn render_pipeline(563    self device: &var Device,564    descriptor: &RenderPipelineDescriptor565) -> RenderPipeline {566    device.check(descriptor.shader);567    var made = device.driver.render_pipeline(&descriptor);568    made.generation = device.generations.stamp(::RenderPipeline, made.index);569    return made;570}571572// A compute pipeline running the shader's entry point of that name.573exp fn compute_pipeline(self device: &var Device, shader: Shader, entry: &[u8]) -> ComputePipeline {574    device.check(shader);575    var made = device.driver.compute_pipeline(shader, &entry);576    made.generation = device.generations.stamp(::ComputePipeline, made.index);577    return made;578}579580// The resources the pipeline's shaders read at the group's bindings.581exp fn bind_group(582    self device: &var Device,583    pipeline: RenderPipeline,584    group: u32,585    bindings: &[Binding]586) -> BindGroup {587    device.check(pipeline);588    device.check_bindings(&bindings);589    var made = device.driver.render_bind_group(pipeline, group, &bindings);590    made.generation = device.generations.stamp(::BindGroup, made.index);591    return made;592}593594exp fn bind_group(595    self device: &var Device,596    pipeline: ComputePipeline,597    group: u32,598    bindings: &[Binding]599) -> BindGroup {600    device.check(pipeline);601    device.check_bindings(&bindings);602    var made = device.driver.compute_bind_group(pipeline, group, &bindings);603    made.generation = device.generations.stamp(::BindGroup, made.index);604    return made;605}606607// The window's surface, for frames drawn on this device.608exp fn surface(self device: &var Device, window: &Window) -> Result<Surface> {609    var made = device.driver.window_surface(&window);610    if (made is ::Ok |&var s|) {611        s.generation = device.generations.stamp(::Surface, s.index);612    }613    return move made;614}615616fn check(self device: &Device, buffer: Buffer) {617    device.generations.check(::Buffer, buffer.index, buffer.generation);618}619620fn check(self device: &Device, texture: Texture) {621    device.generations.check(::Texture, texture.index, texture.generation);622}623624fn check(self device: &Device, sampler: Sampler) {625    device.generations.check(::Sampler, sampler.index, sampler.generation);626}627628fn check(self device: &Device, shader: Shader) {629    device.generations.check(::Shader, shader.index, shader.generation);630}631632fn check(self device: &Device, pipeline: RenderPipeline) {633    device.generations.check(::RenderPipeline, pipeline.index, pipeline.generation);634}635636fn check(self device: &Device, pipeline: ComputePipeline) {637    device.generations.check(::ComputePipeline, pipeline.index, pipeline.generation);638}639640fn check(self device: &Device, group: BindGroup) {641    device.generations.check(::BindGroup, group.index, group.generation);642}643644fn check(self device: &Device, surface: Surface) {645    device.generations.check(::Surface, surface.index, surface.generation);646}647648fn check_bindings(self device: &Device, bindings: &[Binding]) {649    for (bindings) |&b| {650        match (b.resource) {651            ::Buffer |buffer| {652                device.check(buffer);653            }654            ::BufferRange |range| {655                device.check(range.buffer);656                within(range.offset, range.size, range.buffer.size);657            }658            ::Texture |texture| {659                device.check(texture);660            }661            ::Sampler |sampler| {662                device.check(sampler);663            }664        }665    }666}667668// Releases the buffer once the commands submitted before have run. A669// bind group holding it, or commands not yet submitted using it, must not670// be used after.671exp fn release(self device: &var Device, buffer: Buffer) => device.release_handle(672    ::Buffer,673    buffer.index,674    buffer.generation675);676677// Releases the texture as `release` does a buffer; a surface's textures678// go with their surface.679exp fn release(self device: &var Device, texture: Texture) => device.release_handle(680    ::Texture,681    texture.index,682    texture.generation683);684685exp fn release(self device: &var Device, sampler: Sampler) => device.release_handle(686    ::Sampler,687    sampler.index,688    sampler.generation689);690691// Releases the shader; the pipelines made from it stay.692exp fn release(self device: &var Device, shader: Shader) => device.release_handle(693    ::Shader,694    shader.index,695    shader.generation696);697698exp fn release(self device: &var Device, pipeline: RenderPipeline) => device.release_handle(699    ::RenderPipeline,700    pipeline.index,701    pipeline.generation702);703704exp fn release(self device: &var Device, pipeline: ComputePipeline) => device.release_handle(705    ::ComputePipeline,706    pipeline.index,707    pipeline.generation708);709710exp fn release(self device: &var Device, group: BindGroup) => device.release_handle(711    ::BindGroup,712    group.index,713    group.generation714);715716// Releases the surface and its textures, before its window closes.717exp fn release(self device: &var Device, surface: Surface) {718    device.check(surface);719    device.generations.retire(::Surface, surface.index);720    const textures = device.driver.release_surface(surface.index);721    for (textures.view()) |t| {722        device.generations.retire(::Texture, t);723    }724}725726fn release_handle(self device: &var Device, kind: ObjectKind, index: u32, generation: u32) {727    device.generations.check(kind, index, generation);728    device.generations.retire(kind, index);729    device.driver.release(kind, index);730}731732// Writes the bytes into the buffer at the offset, before the commands733// submitted next.734exp fn write_buffer(self device: &var Device, buffer: Buffer, offset: u64, bytes: &[u8]) {735    device.check(buffer);736    within(offset, bytes.length(), buffer.size);737    device.driver.write_buffer(buffer, offset, &bytes);738}739740// Writes the texture's pixels, in its format's order, row after row.741exp fn write_texture(self device: &var Device, texture: Texture, bytes: &[u8]) {742    device.write_texture_region(texture, 0, 0, texture.width, texture.height, &bytes);743}744745// Writes a rectangle of the texture's pixels, `width` by `height` from746// (x, y), row after row.747exp fn write_texture_region(748    self device: &var Device,749    texture: Texture,750    x: u32,751    y: u32,752    width: u32,753    height: u32,754    bytes: &[u8]755) {756    device.check(texture);757    if (x + width > texture.width || y + height > texture.height) {758        panic "pkg::alloy::gpu: a texture written past its edge";759    }760    if (bytes.length() < width to u64 * height to u64 * texture.format.bytes_per_pixel()) {761        panic "pkg::alloy::gpu: a texture written with fewer bytes than its pixels";762    }763    device.driver.write_texture(texture, x, y, width, height, &bytes);764}765766/* --- Surfaces --- */767768// A window's surface: textures to draw frames into, shown in the window769// one after another, paced by the display.770exp type Surface = struct {771    pub index: u32,772    pub generation: u32,773    exp format: TextureFormat, // the format of its textures, for pipelines drawing into them774};775776// The texture to draw the surface's next frame into, of the size, the777// window's; None when the window has no area. `present` shows it.778//779// ```text780// if (device.acquire(surface, window.size()) is ::Some |frame|) {781//     var encoder = Encoder::empty();782//     encoder.begin_render_pass(frame, ::Some(Color::black()));783//     ...784//     encoder.end_render_pass();785//     device.submit(move encoder);786//     device.present(surface, &var window);787// }788// ```789exp fn acquire(self device: &var Device, surface: Surface, size: Size) -> Option<Texture> {790    device.check(surface);791    var acquired = device.driver.acquire(surface.index, size.width, size.height);792    if (acquired is ::Some |&var t|) {793        t.generation = device.generations.stamp(::Texture, t.index);794    }795    return move acquired;796}797798// Shows the texture acquired in the window once the commands submitted799// have drawn it.800exp fn present(self device: &var Device, surface: Surface, window: &var Window) {801    device.check(surface);802    device.driver.show(surface.index, &var window);803}804805/* --- Commands --- */806807// Commands to submit to a device, recorded in order.808exp type Encoder = struct {809    pub commands: Vector<Command>,810};811812exp fn Encoder::empty() -> Encoder {813    return Encoder { .commands = Vector<Command>::empty() };814}815816// Starts drawing into the texture, cleared to the color first when one817// is given, else keeping what it holds.818exp fn begin_render_pass(self e: &var Encoder, target: Texture, clear: Option<Color>) {819    e.commands.push(Command::BeginRenderPass(RenderPassCommand {820        .target = target,821        .clear = clear822    }));823}824825exp fn end_render_pass(self e: &var Encoder) {826    e.commands.push(Command::EndRenderPass);827}828829exp fn set_pipeline(self e: &var Encoder, pipeline: RenderPipeline) {830    e.commands.push(Command::SetPipeline(pipeline));831}832833exp fn set_compute_pipeline(self e: &var Encoder, pipeline: ComputePipeline) {834    e.commands.push(Command::SetComputePipeline(pipeline));835}836837exp fn set_bind_group(self e: &var Encoder, group: BindGroup) {838    e.commands.push(Command::SetBindGroup(group));839}840841exp fn set_vertex_buffer(self e: &var Encoder, slot: u32, buffer: Buffer, offset: u64) {842    e.commands.push(Command::SetVertexBuffer(VertexBufferCommand {843        .slot = slot,844        .buffer = buffer,845        .offset = offset846    }));847}848849// Indices of 32 bits when `wide`, else of 16.850exp fn set_index_buffer(self e: &var Encoder, buffer: Buffer, offset: u64, wide: bool) {851    e.commands.push(Command::SetIndexBuffer(IndexBufferCommand {852        .buffer = buffer,853        .offset = offset,854        .wide = wide855    }));856}857858// Draws only inside the rectangle, until the pass ends.859exp fn set_scissor(self e: &var Encoder, x: u32, y: u32, width: u32, height: u32) {860    e.commands.push(Command::SetScissor(Scissor {861        .x = x,862        .y = y,863        .width = width,864        .height = height865    }));866}867868exp fn draw(self e: &var Encoder, vertices: u32, instances: u32) {869    e.draw_from(vertices, instances, 0, 0);870}871872exp fn draw_from(873    self e: &var Encoder,874    vertices: u32,875    instances: u32,876    first_vertex: u32,877    first_instance: u32878) {879    e.commands.push(Command::Draw(DrawCommand {880        .count = vertices,881        .instances = instances,882        .first = first_vertex,883        .base_vertex = 0,884        .first_instance = first_instance885    }));886}887888exp fn draw_indexed(889    self e: &var Encoder,890    indices: u32,891    instances: u32,892    first_index: u32,893    base_vertex: i32894) {895    e.commands.push(Command::DrawIndexed(DrawCommand {896        .count = indices,897        .instances = instances,898        .first = first_index,899        .base_vertex = base_vertex,900        .first_instance = 0901    }));902}903904// Runs the compute pipeline set over that many workgroups.905exp fn dispatch(self e: &var Encoder, x: u32, y: u32, z: u32) {906    e.commands.push(Command::Dispatch([x, y, z]));907}908909exp fn copy_buffer(910    self e: &var Encoder,911    source: Buffer,912    source_offset: u64,913    destination: Buffer,914    destination_offset: u64,915    size: u64916) {917    e.commands.push(Command::CopyBuffer(CopyCommand {918        .source = source,919        .source_offset = source_offset,920        .destination = destination,921        .destination_offset = destination_offset,922        .size = size923    }));924}925926// Copies a texture over another of its size and format: a surface's,927// say, from one the program keeps drawn. Outside render passes.928exp fn copy_texture(self e: &var Encoder, source: Texture, destination: Texture) {929    e.commands.push(Command::CopyTexture(TextureCopyCommand {930        .source = source,931        .destination = destination932    }));933}934935// Runs the encoder's commands, in order.936exp fn submit(self device: &var Device, encoder: Encoder) {937    device.check_commands(&encoder);938    device.driver.submit(&encoder);939}940941// Checks the commands as WebGPU's validation does, so no backend is given942// what it would run out of bounds or reject: live resources, passes943// begun and ended in turn, drawing and scissors inside one, scissors944// within its target, copies and dispatches outside one, buffer ranges945// within their buffers.946fn check_commands(self device: &Device, encoder: &Encoder) {947    var pass = Option<Texture>::None;948    for (encoder.commands.view()) |&command| {949        match (command) {950            ::BeginRenderPass |&begun| {951                device.check(begun.target);952                if (pass is ::Some) {953                    panic "pkg::alloy::gpu: a render pass begun inside another";954                }955                pass = ::Some(begun.target);956            }957            ::EndRenderPass {958                if (pass is ::None) {959                    panic "pkg::alloy::gpu: end_render_pass with no render pass begun";960                }961                pass = ::None;962            }963            ::SetPipeline |p| {964                device.check(p);965                in_pass(&pass);966            }967            ::SetComputePipeline |p| {968                device.check(p);969            }970            ::SetBindGroup |g| {971                device.check(g);972            }973            ::SetVertexBuffer |&b| {974                device.check(b.buffer);975                in_pass(&pass);976                within(b.offset, 0, b.buffer.size);977            }978            ::SetIndexBuffer |&i| {979                device.check(i.buffer);980                in_pass(&pass);981                within(i.offset, 0, i.buffer.size);982            }983            ::SetScissor |&r| {984                in_pass(&pass);985                if (pass is ::Some |t|) {986                    if (987                        r.x to u64 + r.width to u64 > t.width to u64988                        || r.y to u64 + r.height to u64 > t.height to u64989                    ) {990                        panic "pkg::alloy::gpu: a scissor outside the render pass's target";991                    }992                }993            }994            ::Draw, ::DrawIndexed {995                in_pass(&pass);996            }997            ::Dispatch {998                out_of_pass(&pass);999            }1000            ::CopyBuffer |&c| {1001                device.check(c.source);1002                device.check(c.destination);1003                out_of_pass(&pass);1004                within(c.source_offset, c.size, c.source.size);1005                within(c.destination_offset, c.size, c.destination.size);1006            }1007            ::CopyTexture |&c| {1008                device.check(c.source);1009                device.check(c.destination);1010                out_of_pass(&pass);1011                if (1012                    c.source.width != c.destination.width1013                    || c.source.height != c.destination.height1014                    || !(c.source.format == c.destination.format)1015                ) {1016                    panic "pkg::alloy::gpu: copy_texture between textures of different sizes or formats";1017                }1018            }1019        }1020    }1021    if (pass is ::Some) {1022        panic "pkg::alloy::gpu: a render pass not ended";1023    }1024}10251026fn in_pass(pass: &Option<Texture>) {1027    if (pass is ::None) {1028        panic "pkg::alloy::gpu: a draw, scissor, render pipeline or vertex or index buffer outside a render pass";1029    }1030}10311032fn out_of_pass(pass: &Option<Texture>) {1033    if (pass is ::Some) {1034        panic "pkg::alloy::gpu: a copy or dispatch inside a render pass";1035    }1036}10371038// Panics unless `length` bytes from `offset` lie within `size`.1039fn within(offset: u64, length: u64, size: u64) {1040    if (offset > size || length > size - offset) {1041        panic "pkg::alloy::gpu: a buffer range past the buffer's end";1042    }1043}10441045// The texture's pixels once every command submitted has run, in its1046// format's order, row after row; none on WebGPU, which only reads1047// back later, in the browser's event loop.1048exp fn read_texture(self device: &var Device, texture: Texture) -> Vector<u8> {1049    device.check(texture);1050    return device.driver.read_texture(texture);1051}10521053// The buffer's bytes once every command submitted has run; none on1054// WebGPU.1055exp fn read_buffer(self device: &var Device, buffer: Buffer) -> Vector<u8> {1056    device.check(buffer);1057    return device.driver.read_buffer(buffer);1058}