1// The CPU device: buffers and textures in memory, shaders run by the2// SPIR-V interpreter, triangles rasterized by raster.alloy. It follows3// WebGPU's rules (pixel centers at halves, the top-left fill rule, depth4// from 0 to 1, y up in clip space), so its images are the reference the5// GPU backends are compared with.67import std::string;8import std::vector;9import std::option;1011import gpu;12import commands;13import slots;14import shader::blob;15import shader::spirv;16import resources;17import interpreter;18import raster;19import pkg::alloy::window;2021pub type CpuPipeline = struct {22 pub program: u32,23 pub vertex: u64,24 pub fragment: u64,25 pub buffers: Vector<VertexLayout>,26 pub blend: Blend,27 pub topology: Topology,28 pub vertex_inputs: Vector<StageVariable>,29 pub vertex_outputs: Vector<StageVariable>,30 pub fragment_inputs: Vector<StageVariable>,31 // the memory cells of the built-ins and the color the stages use32 pub position: Option<u32>,33 pub vertex_index: Option<u32>,34 pub instance_index: Option<u32>,35 pub frag_coord: Option<u32>,36 pub color: Option<u32>,37};3839type CpuCompute = struct {40 program: u32,41 entry: u64,42 workgroup: [u32 : 3],43};4445type CpuBindGroup = struct {46 group: u32,47 bound: Vector<Bound>,48};4950// What a render pass has set.51type PassState = struct {52 target: Option<u32> = ::None,53 pipeline: Option<u32> = ::None,54 groups: Vector<Option<u32>> = Vector<Option<u32>>::empty(), // each group's bind group55 vertex_buffers: Vector<Option<VertexBufferCommand>> = Vector<Option<VertexBufferCommand>>::empty(),56 index_buffer: Option<IndexBufferCommand> = ::None,57 scissor: Scissor = Scissor { .x = 0, .y = 0, .width = 0, .height = 0 },58};5960// What a draw draws into, with what.61pub type Pass = struct {62 pub target: u32,63 pub pipeline: u32,64 pub scissor: Scissor,65};6667pub type CpuDevice : Driver = struct {68 pub resources: CpuResources = CpuResources::empty(),69 pub programs: Vector<Program> = Vector<Program>::empty(),70 shader_entries: Vector<u32> = Vector<u32>::empty(), // each shader's program71 pub pipelines: Vector<CpuPipeline> = Vector<CpuPipeline>::empty(),72 computes: Vector<CpuCompute> = Vector<CpuCompute>::empty(),73 groups: Vector<CpuBindGroup> = Vector<CpuBindGroup>::empty(),74 surfaces: Vector<Option<u32>> = Vector<Option<u32>>::empty(), // each surface's texture, once acquired75 released: Released = Released {},76 // what drawing and presenting reuse rather than make each time77 vertices: Vector<RasterVertex> = Vector<RasterVertex>::empty(),78 varyings: Vector<u32> = Vector<u32>::empty(),79 bound: Vector<Bound> = Vector<Bound>::empty(),80 frame: Vector<u32> = Vector<u32>::empty(),81};8283pub fn buffer(self c: &var CpuDevice, size: u64, usage: u32) -> Buffer {84 const index = c.released.place(::Buffer, &var c.resources.buffers, Vector<u8>::filled(0, size));85 return Buffer { .generation = 0, .index = index, .size = size };86}8788pub fn write_buffer(self c: &var CpuDevice, buffer: Buffer, offset: u64, bytes: &[u8]) {89 var target = &var c.resources.buffers.get_var(buffer.index to u64).items();90 target[offset..offset + bytes.length()] = bytes;91}9293pub fn read_buffer(self c: &var CpuDevice, buffer: Buffer) -> Vector<u8> {94 return Vector<u8>::from(&c.resources.buffers.get(buffer.index to u64).view());95}9697pub fn texture(self c: &var CpuDevice, d: &TextureDescriptor) -> Texture {98 const index = c.released.place(::Texture, &var c.resources.textures, CpuTexture {99 .width = d.width,100 .height = d.height,101 .pixels = Vector<u32>::filled(0, d.width to u64 * d.height to u64)102 });103 return Texture {104 .generation = 0,105 .index = index,106 .width = d.width,107 .height = d.height,108 .format = d.format109 };110}111112// Pixels are kept as RGBA, red in the low byte, whatever the format; one113// channel's are red, opaque.114pub fn write_texture(115 self c: &var CpuDevice,116 texture: Texture,117 x: u32,118 y: u32,119 width: u32,120 height: u32,121 bytes: &[u8]122) {123 var pixels = &var c.resources.textures.get_var(texture.index to u64).pixels.items();124 for ([..height to u64]) |row| {125 for ([..width to u64]) |column| {126 const k = (y to u64 + row) * texture.width to u64 + x to u64 + column;127 const at = row * width to u64 + column;128 pixels[k] = match (texture.format) {129 ::R8Unorm bytes[at] to u32 | 0xFF000000;130 ::Rgba8Unorm rgba(131 bytes[at * 4],132 bytes[at * 4 + 1],133 bytes[at * 4 + 2],134 bytes[at * 4 + 3]135 );136 ::Bgra8Unorm rgba(137 bytes[at * 4 + 2],138 bytes[at * 4 + 1],139 bytes[at * 4],140 bytes[at * 4 + 3]141 );142 };143 }144 }145}146147fn rgba(red: u8, green: u8, blue: u8, alpha: u8) -> u32 {148 return red to u32 | (green to u32 << 8) | (blue to u32 << 16) | (alpha to u32 << 24);149}150151pub fn read_texture(self c: &var CpuDevice, texture: Texture) -> Vector<u8> {152 var out = Vector<u8>::empty();153 for (c.resources.textures.get(texture.index to u64).pixels.view()) |p| {154 const red = (p & 0xFF) to u8;155 const green = ((p >> 8) & 0xFF) to u8;156 const blue = ((p >> 16) & 0xFF) to u8;157 const alpha = (p >> 24) to u8;158 match (texture.format) {159 ::R8Unorm {160 out.push(red);161 }162 ::Rgba8Unorm {163 out.append(&[red, green, blue, alpha]);164 }165 ::Bgra8Unorm {166 out.append(&[blue, green, red, alpha]);167 }168 }169 }170 return move out;171}172173pub fn sampler(self c: &var CpuDevice, d: &SamplerDescriptor) -> Sampler {174 const index = c.released.place(::Sampler, &var c.resources.samplers, CpuSampler {175 .linear = d.linear,176 .repeat = d.repeat177 });178 return Sampler { .generation = 0, .index = index };179}180181pub fn shader(self c: &var CpuDevice, compiled: &[u8]) -> Shader {182 const decoded = if (decode(&compiled) is ::Some |move d|) move d else {183 panic "not a shader #shader compiled";184 };185 // programs stay while pipelines run them186 c.programs.push(Program::decode(&decoded.spirv.view()));187 const program = c.programs.length() to u32 - 1;188 const index = c.released.place(::Shader, &var c.shader_entries, program);189 return Shader { .generation = 0, .index = index };190}191192pub fn render_pipeline(self c: &var CpuDevice, d: &RenderPipelineDescriptor) -> RenderPipeline {193 const program = c.shader_entries.get(d.shader.index to u64);194 const p = &c.programs.get(program to u64);195 const vertex = if (p.entry_index(&d.vertex.view()) is ::Some |e|) e else {196 panic "the shader has no such vertex entry point";197 };198 const fragment = if (p.entry_index(&d.fragment.view()) is ::Some |e|) e else {199 panic "the shader has no such fragment entry point";200 };201 var buffers = Vector<VertexLayout>::empty();202 for (d.buffers.view()) |&layout| {203 buffers.push(VertexLayout {204 .stride = layout.stride,205 .instanced = layout.instanced,206 .attributes = copy layout.attributes207 });208 }209 var pipeline = CpuPipeline {210 .program = program,211 .vertex = vertex,212 .fragment = fragment,213 .buffers = move buffers,214 .blend = d.blend,215 .topology = d.topology,216 .vertex_inputs = p.stage_variables(vertex, StorageClass::Input),217 .vertex_outputs = p.stage_variables(vertex, StorageClass::Output),218 .fragment_inputs = p.stage_variables(fragment, StorageClass::Input),219 .position = p.stage_builtin(vertex, StorageClass::Output, BuiltIn::Position),220 .vertex_index = p.stage_builtin(vertex, StorageClass::Input, BuiltIn::VertexIndex),221 .instance_index = p.stage_builtin(vertex, StorageClass::Input, BuiltIn::InstanceIndex),222 .frag_coord = p.stage_builtin(fragment, StorageClass::Input, BuiltIn::FragCoord),223 .color = p.stage_location(fragment, StorageClass::Output, 0)224 };225 const index = c.released.place(::RenderPipeline, &var c.pipelines, move pipeline);226 return RenderPipeline { .generation = 0, .index = index };227}228229pub fn compute_pipeline(self c: &var CpuDevice, shader: Shader, entry: &[u8]) -> ComputePipeline {230 const program = c.shader_entries.get(shader.index to u64);231 const p = &c.programs.get(program to u64);232 const index = if (p.entry_index(&entry) is ::Some |e|) e else {233 panic "the shader has no such compute entry point";234 };235 const compute = CpuCompute {236 .program = program,237 .entry = index,238 .workgroup = p.workgroup_of(index)239 };240 const at = c.released.place(::ComputePipeline, &var c.computes, compute);241 return ComputePipeline { .generation = 0, .index = at };242}243244pub fn bind_group(self c: &var CpuDevice, group: u32, bindings: &[Binding]) -> BindGroup {245 var bound = Vector<Bound>::empty();246 for (bindings) |&b| {247 var made = Bound { .group = group, .binding = b.binding, .index = 0, .offset = 0 };248 match (b.resource) {249 ::Buffer |buffer| {250 made.index = buffer.index;251 }252 ::BufferRange |range| {253 made.index = range.buffer.index;254 made.offset = range.offset to u32;255 }256 ::Texture |texture| {257 made.index = texture.index;258 }259 ::Sampler |sampler| {260 made.index = sampler.index;261 }262 }263 bound.push(made);264 }265 const index = c.released.place(::BindGroup, &var c.groups, CpuBindGroup {266 .group = group,267 .bound = move bound268 });269 return BindGroup { .generation = 0, .index = index, .group = group };270}271272/* --- Running commands --- */273274pub fn submit(self c: &var CpuDevice, encoder: &Encoder) {275 var state = PassState {};276 var compute = Option<u32>::None;277 for (encoder.commands.view()) |&command| {278 match (command) {279 ::BeginRenderPass |&pass| {280 state.target = ::Some(pass.target.index);281 state.scissor = Scissor {282 .x = 0,283 .y = 0,284 .width = pass.target.width,285 .height = pass.target.height286 };287 if (pass.clear is ::Some |color|) {288 const pixel = unorm(color.r) | (289 unorm(color.g) << 8290 ) | (unorm(color.b) << 16) | (unorm(color.a) << 24);291 for (292 c.resources.textures.get_var(pass.target.index to u64).pixels.items()293 ) |&var p| {294 p = pixel;295 }296 }297 }298 ::EndRenderPass {299 state.target = ::None;300 }301 ::SetPipeline |pipeline| {302 state.pipeline = ::Some(pipeline.index);303 }304 ::SetComputePipeline |pipeline| {305 compute = ::Some(pipeline.index);306 }307 ::SetBindGroup |group| {308 while (state.groups.length() <= group.group to u64) {309 state.groups.push(::None);310 }311 state.groups.get_var(group.group to u64) = ::Some(group.index);312 }313 ::SetVertexBuffer |&v| {314 while (state.vertex_buffers.length() <= v.slot to u64) {315 state.vertex_buffers.push(::None);316 }317 state.vertex_buffers.get_var(v.slot to u64) = ::Some(v);318 }319 ::SetIndexBuffer |&i| {320 state.index_buffer = ::Some(i);321 }322 ::SetScissor |s| {323 state.scissor = s;324 }325 ::Draw |&d| {326 c.draw(&state, &d, false);327 }328 ::DrawIndexed |&d| {329 c.draw(&state, &d, true);330 }331 ::Dispatch |size| {332 if (compute is ::Some |pipeline|) {333 c.dispatch(pipeline, &state, size);334 }335 }336 ::CopyBuffer |©_command| {337 const source = Vector<u8>::from(338 &c.resources.buffers.get(copy_command.source.index to u64).view()[339 copy_command.source_offset..copy_command.source_offset + copy_command.size340 ]341 );342 var target = &var c.resources.buffers.get_var(343 copy_command.destination.index to u64344 ).items();345 target[346 copy_command.destination_offset..copy_command.destination_offset + copy_command.size347 ] = source.view();348 }349 ::CopyTexture |©_command| {350 const source = Vector<u32>::from(351 &c.resources.textures.get(copy_command.source.index to u64).pixels.view()352 );353 var target = &var c.resources.textures.get_var(354 copy_command.destination.index to u64355 ).pixels.items();356 target[..] = source.view();357 }358 }359 }360}361362pub fn unorm(value: f32) -> u32 {363 const clamped = if (value < 0.0) 0.0 else if (value > 1.0) 1.0 else value;364 return (clamped * 255.0 + 0.5) to u32;365}366367// Binds the pass's bind groups to the program.368fn bind_groups(self c: &var CpuDevice, program: u32, state: &PassState) {369 var bound = move c.bound;370 bound.clear();371 for (state.groups.view()) |group| {372 if (group is ::Some |g|) {373 bound.append(&c.groups.get(g to u64).bound.view());374 }375 }376 c.programs.get_var(program to u64).bind(&bound.view());377 c.bound = move bound;378}379380fn draw(self c: &var CpuDevice, state: &PassState, d: &DrawCommand, indexed: bool) {381 const pass = if (state.target is ::Some |target| && state.pipeline is ::Some |pipeline|) Pass {382 .target = target,383 .pipeline = pipeline,384 .scissor = state.scissor385 } else {386 return;387 };388 const program = c.pipelines.get(pass.pipeline to u64).program;389 c.bind_groups(program, &state);390 var vertices = move c.vertices;391 var varyings = move c.varyings;392 for ([..d.instances to u64]) |instance| {393 vertices.clear();394 varyings.clear();395 for ([..d.count to u64]) |k| {396 var index = d.first to u64 + k;397 if (indexed) {398 index = (c.index_at(&state, index) to i64 + d.base_vertex to i64) to u64;399 }400 vertices.push(c.run_vertex(401 &pass,402 &state,403 index to u32,404 (instance + d.first_instance to u64) to u32,405 &var varyings406 ));407 }408 c.rasterize(&pass, &vertices.view(), &varyings.view());409 }410 c.vertices = move vertices;411 c.varyings = move varyings;412}413414fn index_at(self c: &CpuDevice, state: &PassState, k: u64) -> u32 {415 const indices = if (state.index_buffer is ::Some |i|) i else {416 panic "pkg::alloy::gpu: an indexed draw with no index buffer set";417 };418 const bytes = &c.resources.buffers.get(indices.buffer.index to u64).view();419 if (indices.wide) {420 const at = indices.offset + k * 4;421 return bytes[at] to u32 | (422 bytes[at + 1] to u32 << 8423 ) | (bytes[at + 2] to u32 << 16) | (bytes[at + 3] to u32 << 24);424 }425 const at = indices.offset + k * 2;426 return bytes[at] to u32 | (bytes[at + 1] to u32 << 8);427}428429// Runs the vertex stage for one vertex: its attributes fetched, its430// position and outputs kept.431fn run_vertex(432 self c: &var CpuDevice,433 pass: &Pass,434 state: &PassState,435 index: u32,436 instance: u32,437 varyings: &var Vector<u32>438) -> RasterVertex {439 const pipeline = &c.pipelines.get(pass.pipeline to u64);440 const vertex_entry = pipeline.vertex;441 var p = &var c.programs.get_var(pipeline.program to u64);442 if (pipeline.vertex_index is ::Some |at|) {443 p.memory.get_var(at to u64) = index;444 }445 if (pipeline.instance_index is ::Some |at|) {446 p.memory.get_var(at to u64) = instance;447 }448 for (pipeline.buffers.view(), [..pipeline.buffers.length()]) |&layout, slot| {449 const source = if (450 state.vertex_buffers.try_get(slot) is ::Some |&set| && set is ::Some |s|451 ) s else {452 continue;453 };454 const step = if (layout.instanced) instance else index;455 const base = source.offset + step to u64 * layout.stride to u64;456 const bytes = &c.resources.buffers.get(source.buffer.index to u64).view();457 for (layout.attributes.view()) |&attribute| {458 if (459 location_cells(&pipeline.vertex_inputs.view(), attribute.location) is ::Some |cells|460 ) {461 fetch(462 &bytes,463 base + attribute.offset to u64,464 attribute.format,465 &var p.memory.items()[cells to u64..]466 );467 }468 }469 }470 p.run(vertex_entry, &var c.resources);471 const position = if (pipeline.position is ::Some |at|) at to u64 else {472 panic "pkg::alloy::gpu: the vertex entry point gives no position";473 };474 const memory = &p.memory.view();475 const first = varyings.length() to u32;476 for (pipeline.vertex_outputs.view()) |&output| {477 varyings.append(&memory[output.memory to u64..(output.memory + output.cells) to u64]);478 }479 return RasterVertex {480 .x = memory[position] as f32,481 .y = memory[position + 1] as f32,482 .z = memory[position + 2] as f32,483 .w = memory[position + 3] as f32,484 .varyings = first485 };486}487488// The memory cell of the stage variable at the location.489pub fn location_cells(variables: &[StageVariable], location: u32) -> Option<u32> {490 for (variables) |&v| {491 if (v.location == location) {492 return ::Some(v.memory);493 }494 }495 return ::None;496}497498// Reads an attribute in its format into cells.499fn fetch(bytes: &[u8], at: u64, format: VertexFormat, cells: &var [u32]) {500 if (format is ::Unorm8x4) {501 for ([..4 to u64]) |k| {502 cells[k] = ((bytes[at + k] to f32) / 255.0) as u32;503 }504 return;505 }506 const count: u64 = match (format) {507 ::Float32, ::Uint32, ::Sint32 1;508 ::Float32x2 2;509 ::Float32x3 3;510 else 4;511 };512 for ([..count]) |k| {513 const b = at + k * 4;514 cells[k] = bytes[b] to u32 | (515 bytes[b + 1] to u32 << 8516 ) | (bytes[b + 2] to u32 << 16) | (bytes[b + 3] to u32 << 24);517 }518}519520fn dispatch(self c: &var CpuDevice, compute: u32, state: &PassState, size: [u32 : 3]) {521 const pipeline = c.computes.get(compute to u64);522 c.bind_groups(pipeline.program, &state);523 var p = &var c.programs.get_var(pipeline.program to u64);524 const entry = pipeline.entry;525 const global = p.stage_builtin(entry, StorageClass::Input, BuiltIn::GlobalInvocationId);526 const local = p.stage_builtin(entry, StorageClass::Input, BuiltIn::LocalInvocationId);527 const group_id = p.stage_builtin(entry, StorageClass::Input, BuiltIn::WorkgroupId);528 const local_index = p.stage_builtin(entry, StorageClass::Input, BuiltIn::LocalInvocationIndex);529 const groups = p.stage_builtin(entry, StorageClass::Input, BuiltIn::NumWorkgroups);530 const w = pipeline.workgroup;531 for ([..size[2] to u64]) |gz| {532 for ([..size[1] to u64]) |gy| {533 for ([..size[0] to u64]) |gx| {534 for ([..w[2] to u64]) |lz| {535 for ([..w[1] to u64]) |ly| {536 for ([..w[0] to u64]) |lx| {537 const g: [u32 : 3] = [gx to u32, gy to u32, gz to u32];538 const l: [u32 : 3] = [lx to u32, ly to u32, lz to u32];539 for ([..3 to u64]) |axis| {540 if (global is ::Some |at|) {541 p.memory.get_var(542 at to u64 + axis543 ) = g[axis] * w[axis] + l[axis];544 }545 if (local is ::Some |at|) {546 p.memory.get_var(at to u64 + axis) = l[axis];547 }548 if (group_id is ::Some |at|) {549 p.memory.get_var(at to u64 + axis) = g[axis];550 }551 if (groups is ::Some |at|) {552 p.memory.get_var(at to u64 + axis) = size[axis];553 }554 }555 if (local_index is ::Some |at|) {556 p.memory.get_var(557 at to u64558 ) = l[0] + l[1] * w[0] + l[2] * w[0] * w[1];559 }560 p.run(entry, &var c.resources);561 }562 }563 }564 }565 }566 }567}568569/* --- Surfaces --- */570571// Frees the object, its index taken again by the next of its kind: at572// once, since commands run as they are submitted.573pub fn release(self c: &var CpuDevice, kind: ObjectKind, index: u32) {574 match (kind) {575 ::Texture {576 for (c.surfaces.view()) |t| {577 if (t is ::Some |texture| && texture == index) {578 panic "pkg::alloy::gpu: a surface's texture goes with its surface";579 }580 }581 c.resources.textures.get_var(index to u64).pixels = Vector<u32>::empty();582 }583 ::Buffer {584 c.resources.buffers.get_var(index to u64) = Vector<u8>::empty();585 }586 ::BindGroup {587 c.groups.get_var(index to u64).bound = Vector<Bound>::empty();588 }589 }590 c.released.push(kind, index);591}592593// Frees the surface and its texture; the texture's index.594pub fn release_surface(self c: &var CpuDevice, surface: u32) -> Vector<u32> {595 var textures = Vector<u32>::empty();596 const acquired = c.surfaces.get(surface to u64);597 c.surfaces.get_var(surface to u64) = ::None;598 if (acquired is ::Some |texture|) {599 c.release(::Texture, texture);600 textures.push(texture);601 }602 c.released.push(::Surface, surface);603 return move textures;604}605606// The surface's texture, made or resized to the size.607pub fn acquire(self c: &var CpuDevice, surface: u32, width: u32, height: u32) -> Option<Texture> {608 if (width == 0 || height == 0) {609 return ::None;610 }611 const index = if (c.surfaces.get(surface to u64) is ::Some |texture|) texture else {612 const made = c.texture(&TextureDescriptor {613 .width = width,614 .height = height,615 .format = TextureFormat::Bgra8Unorm,616 .usage = TEXTURE_RENDER_TARGET | TEXTURE_COPY_SOURCE617 });618 c.surfaces.get_var(surface to u64) = ::Some(made.index);619 yield made.index;620 };621 var t = &var c.resources.textures.get_var(index to u64);622 if (t.width != width || t.height != height) {623 t.width = width;624 t.height = height;625 t.pixels = Vector<u32>::filled(0, width to u64 * height to u64);626 }627 return ::Some(Texture {628 .generation = 0,629 .index = index,630 .width = width,631 .height = height,632 .format = TextureFormat::Bgra8Unorm633 });634}635636// The surface's texture shown in the window, as 0xRRGGBB pixels.637pub fn present(self c: &var CpuDevice, surface: u32, window: &var Window) {638 const index = if (c.surfaces.get(surface to u64) is ::Some |texture|) texture else {639 return;640 };641 const t = &c.resources.textures.get(index to u64);642 const source = &t.pixels.view();643 if (c.frame.length() != source.length()) {644 c.frame = Vector<u32>::filled(0, source.length());645 }646 for (source, c.frame.items()) |p, &var pixel| {647 pixel = ((p & 0xFF) << 16) | (p & 0xFF00) | ((p >> 16) & 0xFF);648 }649 window.present(&c.frame.view(), Size { .width = t.width, .height = t.height });650}651652/* --- As the device's driver --- */653654pub fn device_name(self c: &CpuDevice) -> String => String::from(&"CPU");655656pub fn render_bind_group(657 self c: &var CpuDevice,658 pipeline: RenderPipeline,659 group: u32,660 bindings: &[Binding]661) -> BindGroup => c.bind_group(group, &bindings);662663pub fn compute_bind_group(664 self c: &var CpuDevice,665 pipeline: ComputePipeline,666 group: u32,667 bindings: &[Binding]668) -> BindGroup => c.bind_group(group, &bindings);669670// Its frames go into the window as a CPU frame, blue first.671pub fn window_surface(self c: &var CpuDevice, window: &Window) -> Result<Surface> {672 const index = c.released.place(::Surface, &var c.surfaces, Option<u32>::None);673 return ::Ok(Surface { .generation = 0, .index = index, .format = TextureFormat::Bgra8Unorm });674}675676pub fn show(self c: &var CpuDevice, surface: u32, window: &var Window) {677 c.present(surface, &var window);678}