1// Triangles into pixels for the CPU device, by WebGPU's rules: clipped2// against the near plane, mapped to the target with y down, covered3// where a pixel's center is inside by the top-left rule (edges in fixed4// point, 8 bits under the pixel), outputs interpolated with perspective5// (integers flat, from the first vertex), the fragment stage run per6// pixel and its color blended into the target.78import std::vector;9import std::option;1011import gpu;12import commands;13import shader::spirv;14import resources;15import interpreter;16import device;1718const SUBPIXEL: f32 = 256.0;1920pub type RasterVertex = struct {21 pub x: f32,22 pub y: f32,23 pub z: f32,24 pub w: f32,25 pub varyings: u32, // its first cell in the draw's varyings26};2728// Draws the vertices' triangles, as the pipeline's topology groups them.29pub fn rasterize(self c: &var CpuDevice, pass: &Pass, vertices: &[RasterVertex], varyings: &[u32]) {30 const strip = c.pipelines.get(pass.pipeline to u64).topology is ::TriangleStrip;31 if (vertices.length() < 3) {32 return;33 }34 const count = if (strip) vertices.length() - 2 else vertices.length() / 3;35 for ([..count]) |k| {36 if (strip) {37 // every other triangle of a strip turns the other way38 if (k % 2 == 0) {39 c.triangle(&pass, &[vertices[k], vertices[k + 1], vertices[k + 2]], &varyings);40 } else {41 c.triangle(&pass, &[vertices[k + 1], vertices[k], vertices[k + 2]], &varyings);42 }43 } else {44 c.triangle(45 &pass,46 &[vertices[k * 3], vertices[k * 3 + 1], vertices[k * 3 + 2]],47 &varyings48 );49 }50 }51}5253// A triangle clipped against the near plane (z >= 0), then each piece of54// the polygon left drawn.55fn triangle(self c: &var CpuDevice, pass: &Pass, v: &[RasterVertex], varyings: &[u32]) {56 const outside = (57 if (v[0].z < 0.0) 1 else 058 ) + (if (v[1].z < 0.0) 1 else 0) + (if (v[2].z < 0.0) 1 else 0);59 if (outside == 0) {60 c.fill(&pass, &v, &varyings);61 return;62 }63 if (outside == 3) {64 return;65 }66 // the polygon's vertices on the near side, new ones where its edges67 // cross the plane, their outputs mixed in a list of their own68 const cells = c.varying_cells(&pass);69 var clipped = Vector<RasterVertex>::empty();70 var mixed = Vector<u32>::from(&varyings);71 for ([..3 to u64]) |k| {72 const a = v[k];73 const b = v[(k + 1) % 3];74 if (a.z >= 0.0) {75 clipped.push(a);76 }77 if ((a.z >= 0.0) != (b.z >= 0.0)) {78 const t = a.z / (a.z - b.z);79 const first = mixed.length() to u32;80 for ([..cells]) |cell| {81 const x = varyings[a.varyings to u64 + cell] as f32;82 const y = varyings[b.varyings to u64 + cell] as f32;83 mixed.push((x + (y - x) * t) as u32);84 }85 clipped.push(RasterVertex {86 .x = a.x + (b.x - a.x) * t,87 .y = a.y + (b.y - a.y) * t,88 .z = 0.0,89 .w = a.w + (b.w - a.w) * t,90 .varyings = first91 });92 }93 }94 const list = &clipped.view();95 for ([1..list.length() - 1]) |k| {96 c.fill(&pass, &[list[0], list[k], list[k + 1]], &mixed.view());97 }98}99100fn varying_cells(self c: &CpuDevice, pass: &Pass) -> u64 {101 var total: u64 = 0;102 for (c.pipelines.get(pass.pipeline to u64).vertex_outputs.view()) |&output| {103 total += output.cells to u64;104 }105 return total;106}107108type Screen = struct {109 x: i64, // in 1/256 pixels110 y: i64,111 z: f32,112 inverse_w: f32,113};114115fn to_screen(v: &RasterVertex, width: u32, height: u32) -> Screen {116 const inverse_w = 1.0 / v.w;117 const x = (v.x * inverse_w * 0.5 + 0.5) * width to f32;118 const y = (0.5 - v.y * inverse_w * 0.5) * height to f32;119 return Screen {120 .x = (x * SUBPIXEL + 0.5) to i64,121 .y = (y * SUBPIXEL + 0.5) to i64,122 .z = v.z * inverse_w,123 .inverse_w = inverse_w124 };125}126127// How far the point is to the left of the edge from a to b, times two.128fn edge(ax: i64, ay: i64, bx: i64, by: i64, px: i64, py: i64) -> i64 {129 return (bx - ax) * (py - ay) - (by - ay) * (px - ax);130}131132// Whether pixels exactly on the edge from a to b belong to the triangle:133// top and left edges, for a triangle whose area is positive in y-down134// coordinates.135fn top_left(ax: i64, ay: i64, bx: i64, by: i64) -> bool {136 return (by == ay && bx > ax) || by < ay;137}138139fn fill(self c: &var CpuDevice, pass: &Pass, v: &[RasterVertex], varyings: &[u32]) {140 const texture = &c.resources.textures.get(pass.target to u64);141 const width = texture.width;142 const height = texture.height;143 var s0 = to_screen(&v[0], width, height);144 var s1 = to_screen(&v[1], width, height);145 var s2 = to_screen(&v[2], width, height);146 var order: [u64 : 3] = [0, 1, 2];147 var area = edge(s0.x, s0.y, s1.x, s1.y, s2.x, s2.y);148 if (area == 0) {149 return;150 }151 if (area < 0) {152 const swap = s1;153 s1 = s2;154 s2 = swap;155 order = [0, 2, 1];156 area = -area;157 }158 // the pixels the triangle may cover, within the scissor159 const scissor = pass.scissor;160 var min_x = min3(s0.x, s1.x, s2.x) / 256;161 var max_x = (max3(s0.x, s1.x, s2.x) + 255) / 256;162 var min_y = min3(s0.y, s1.y, s2.y) / 256;163 var max_y = (max3(s0.y, s1.y, s2.y) + 255) / 256;164 min_x = clamp_i64(min_x, scissor.x to i64, (scissor.x + scissor.width) to i64);165 max_x = clamp_i64(max_x, scissor.x to i64, (scissor.x + scissor.width) to i64);166 min_y = clamp_i64(min_y, scissor.y to i64, (scissor.y + scissor.height) to i64);167 max_y = clamp_i64(max_y, scissor.y to i64, (scissor.y + scissor.height) to i64);168 const bias0: i64 = if (top_left(s1.x, s1.y, s2.x, s2.y)) 0 else -1;169 const bias1: i64 = if (top_left(s2.x, s2.y, s0.x, s0.y)) 0 else -1;170 const bias2: i64 = if (top_left(s0.x, s0.y, s1.x, s1.y)) 0 else -1;171 const screens: [Screen : 3] = [s0, s1, s2];172 for ([min_y..max_y]) |py| {173 const cy = py * 256 + 128;174 for ([min_x..max_x]) |px| {175 const cx = px * 256 + 128;176 const e0 = edge(s1.x, s1.y, s2.x, s2.y, cx, cy);177 const e1 = edge(s2.x, s2.y, s0.x, s0.y, cx, cy);178 const e2 = edge(s0.x, s0.y, s1.x, s1.y, cx, cy);179 if (e0 + bias0 >= 0 && e1 + bias1 >= 0 && e2 + bias2 >= 0) {180 const weights: [f32 : 3] = [181 e0 to f32 / area to f32,182 e1 to f32 / area to f32,183 e2 to f32 / area to f32184 ];185 c.fragment(&pass, &v, &order, &screens, &weights, px to u32, py to u32, &varyings);186 }187 }188 }189}190191fn min3(a: i64, b: i64, c: i64) -> i64 {192 const m = if (a < b) a else b;193 return if (m < c) m else c;194}195196fn max3(a: i64, b: i64, c: i64) -> i64 {197 const m = if (a > b) a else b;198 return if (m > c) m else c;199}200201fn clamp_i64(x: i64, low: i64, high: i64) -> i64 {202 return if (x < low) low else if (x > high) high else x;203}204205// One pixel: the fragment stage's inputs interpolated, the stage run, its206// color blended into the target.207fn fragment(208 self c: &var CpuDevice,209 pass: &Pass,210 v: &[RasterVertex],211 order: &[u64 : 3],212 screens: &[Screen : 3],213 weights: &[f32 : 3],214 px: u32,215 py: u32,216 varyings: &[u32]217) {218 const pipeline = &c.pipelines.get(pass.pipeline to u64);219 const fragment_entry = pipeline.fragment;220 const blend = pipeline.blend;221 const color_cells = pipeline.color;222 // perspective: each vertex's weight over its w, then normalized223 var perspective: [f32 : 3] = [0.0 : 3];224 var total: f32 = 0.0;225 for ([..3 to u64]) |k| {226 perspective[k] = weights[k] * screens[k].inverse_w;227 total += perspective[k];228 }229 for ([..3 to u64]) |k| {230 perspective[k] = perspective[k] / total;231 }232 var p = &var c.programs.get_var(pipeline.program to u64);233 if (pipeline.frag_coord is ::Some |cell|) {234 const at = cell to u64;235 p.memory.get_var(at) = (px to f32 + 0.5) as u32;236 p.memory.get_var(at + 1) = (py to f32 + 0.5) as u32;237 p.memory.get_var(at + 2) = (238 weights[0] * screens[0].z + weights[1] * screens[1].z + weights[2] * screens[2].z239 ) as u32;240 p.memory.get_var(at + 3) = total as u32;241 }242 // each fragment input from the vertex output at its location243 const outputs = &pipeline.vertex_outputs.view();244 for (pipeline.fragment_inputs.view()) |&input| {245 const offset = if (varying_offset(&outputs, input.location) is ::Some |o|) o else {246 continue;247 };248 const target = input.memory to u64;249 for ([..input.cells to u64]) |cell| {250 if (input.interpolated) {251 var value: f32 = 0.0;252 for ([..3 to u64]) |n| {253 value += perspective[n] * (254 varyings[v[order[n]].varyings to u64 + offset + cell] as f32255 );256 }257 p.memory.get_var(target + cell) = value as u32;258 } else {259 p.memory.get_var(target + cell) = varyings[v[0].varyings to u64 + offset + cell];260 }261 }262 }263 if (!p.run(fragment_entry, &var c.resources)) {264 return;265 }266 const at_color = if (color_cells is ::Some |cell|) cell to u64 else {267 return;268 };269 const memory = &p.memory.view();270 const color: [f32 : 4] = [271 memory[at_color] as f32,272 memory[at_color + 1] as f32,273 memory[at_color + 2] as f32,274 memory[at_color + 3] as f32275 ];276 var target = &var c.resources.textures.get_var(pass.target to u64);277 const at = (py to u64) * target.width to u64 + px to u64;278 target.pixels.get_var(at) = blended(target.pixels.get(at), &color, blend);279}280281// Where the output at the location starts among a vertex's varyings.282fn varying_offset(outputs: &[StageVariable], location: u32) -> Option<u64> {283 var offset: u64 = 0;284 for (outputs) |&output| {285 if (output.location == location) {286 return ::Some(offset);287 }288 offset += output.cells to u64;289 }290 return ::None;291}292293fn blended(old: u32, color: &[f32 : 4], blend: Blend) -> u32 {294 var out: [f32 : 4] = [color[0], color[1], color[2], color[3]];295 if (!(blend is ::Replace)) {296 const alpha = clamp01(color[3]);297 for ([..4 to u64]) |k| {298 const destination = ((old >> (k * 8) to u32) & 0xFF) to f32 / 255.0;299 // color by the source's alpha unless premultiplied; alpha300 // always by one301 const source_factor = if (k == 3 || blend is ::Premultiplied) 1.0 else alpha;302 out[k] = clamp01(color[k]) * source_factor + destination * (1.0 - alpha);303 }304 }305 return unorm(out[0]) | (unorm(out[1]) << 8) | (unorm(out[2]) << 16) | (unorm(out[3]) << 24);306}307308fn clamp01(x: f32) -> f32 {309 return if (x < 0.0) 0.0 else if (x > 1.0) 1.0 else x;310}