1// Runs the SPIR-V the shader compiler writes, one invocation at a time,2// for the CPU device. The module is decoded once: every instruction into3// an Op, every result id given fixed cells (32-bit words) in a4// register file, every variable fixed cells in memory, composites5// flattened, since shaders do not recurse. A pointer is three cells: its6// space (memory, a buffer, a texture or sampler handle), the buffer or7// handle's index, and the offset, in cells in memory and in bytes in8// buffers, where values are laid out by their decorations. The ops are9// then compiled into steps naming registers, types' sizes and branches'10// targets found, which a run goes through reading nothing else.1112import std::string;13import std::vector;14import std::option;15import std::math;1617import shader::spirv;18import resources;1920// The first cell of an id with no registers, or of a label not seen: it21// faults when read.22const UNSET: u32 = 0xFFFFFFFF;2324// a pointer's space, its first cell25const SPACE_MEMORY: u32 = 0;26const SPACE_BUFFER: u32 = 1;27const SPACE_HANDLE: u32 = 2;2829type TypeKind = enum {30 Void,31 Bool,32 Int,33 Float,34 Vector,35 Matrix,36 Array,37 RuntimeArray,38 Struct,39 Pointer,40 Function,41 Image,42 Sampler,43 SampledImage,44};4546type TypeInfo = struct {47 kind: TypeKind = ::Void,48 element: u32 = 0, // the element, column or pointee type id49 count: u32 = 0, // vector size, matrix columns, array length, struct members50 cells: u32 = 0,51 first: u32 = 0, // a struct's first member in `members`52 stride: u32 = 0, // an array's or matrix's stride in buffers53 signed: bool = false,54};5556type Member = struct {57 ty: u32,58 cell: u32, // its first cell within its struct59 offset: u32 = 0, // its offset in buffers60};6162type Op = struct {63 opcode: Opcode,64 ty: u32,65 result: u32,66 first: u32, // its first operand in `operands`67 count: u32,68 callee: u32 = 0, // a call's function, its index in `functions`69};7071type Variable = struct {72 id: u32,73 ty: u32, // the pointee74 storage: StorageClass,75 memory: u32, // its cells in memory76 location: Option<u32> = ::None,77 builtin: Option<BuiltIn> = ::None,78 group: Option<u32> = ::None,79 binding: Option<u32> = ::None,80};8182type FunctionInfo = struct {83 id: u32,84 start: u32, // its first op, the entry label's85 end: u32 = 0, // past its last op86 parameters: u32, // its first in `parameter_ids`87 parameter_count: u32 = 0,88};8990pub type Entry = struct {91 pub name: String,92 pub function: u32, // the entry function's id93 pub interface_ids: Vector<u32>, // its Input and Output variables94 pub workgroup: [u32 : 3] = [1, 1, 1],95 start: u32 = 0, // its first step96};9798// An Input or Output variable of an entry point, at a location.99pub type StageVariable = struct {100 pub location: u32,101 pub memory: u32, // its first cell in memory102 pub cells: u32,103 pub interpolated: bool, // a float's, which the rasterizer interpolates104};105106// A resource the next run uses at a group and binding.107pub type Bound = struct {108 pub group: u32,109 pub binding: u32,110 pub index: u32, // in the device's buffers, textures or samplers111 pub offset: u32, // a buffer binding's first byte112};113114pub type Program = struct {115 types: Vector<TypeInfo>, // by id116 members: Vector<Member>,117 registers_of: Vector<u32>, // each id's first register118 value_types: Vector<u32>, // each id's type119 ops: Vector<Op>,120 operands: Vector<u32>,121 labels: Vector<u32>, // each label id's op122 functions: Vector<FunctionInfo>,123 parameter_ids: Vector<u32>,124 variables: Vector<Variable>,125 pub entries: Vector<Entry>,126 // by id: values set when compiled, constants and pointers into memory127 fixed: Vector<bool>,128 steps: Vector<Step>,129 levels: Vector<Level>, // access chains' indices130 layouts: Vector<u32>, // loads' and stores' cells in buffers131 zeros: u32, // ZEROS registers of zero132 own: Vector<u32>, // each id's first register before compiling133 uses: Vector<u32>, // by id, the ops naming it134 made: Vector<u32>, // by id, the one step making it, or UNSET135 // the state of a run136 registers: Vector<u32>,137 pub memory: Vector<u32>,138};139140/* --- Decoding --- */141142pub fn Program::decode(words: &[u32]) -> Program {143 const bound = words[3] to u64;144 var p = Program {145 .types = Vector<TypeInfo>::filled(TypeInfo {}, bound),146 .members = Vector<Member>::empty(),147 .registers_of = Vector<u32>::filled(UNSET, bound),148 .value_types = Vector<u32>::filled(0, bound),149 .ops = Vector<Op>::empty(),150 .operands = Vector<u32>::empty(),151 .labels = Vector<u32>::filled(UNSET, bound),152 .functions = Vector<FunctionInfo>::empty(),153 .parameter_ids = Vector<u32>::empty(),154 .variables = Vector<Variable>::empty(),155 .entries = Vector<Entry>::empty(),156 .fixed = Vector<bool>::filled(false, bound),157 .steps = Vector<Step>::empty(),158 .levels = Vector<Level>::empty(),159 .layouts = Vector<u32>::empty(),160 .zeros = 0,161 .registers = Vector<u32>::empty(),162 .memory = Vector<u32>::empty(),163 .own = Vector<u32>::empty(),164 .uses = Vector<u32>::empty(),165 .made = Vector<u32>::empty()166 };167 const list = if (instructions(&words) is ::Some |move l|) move l else {168 panic "pkg::alloy::gpu: a SPIR-V instruction of no words";169 };170 // decorations come before the types they decorate: applied once all171 // are there172 var decorations = Vector<Instruction>::empty();173 for (list.view()) |&i| {174 const w = &words[i.at..i.end];175 const opcode = i.opcode;176 match (opcode) {177 ::Nop, ::Capability, ::ExtInstImport, ::MemoryModel, ::Name, ::MemberName,178 ::SelectionMerge, ::LoopMerge {179 // nothing a run needs180 }181 ::FunctionEnd {182 p.functions.get_var(p.functions.length() - 1).end = p.ops.length() to u32;183 }184 ::ExecutionMode {185 if (w[1] == ExecutionMode::LocalSize to u32) {186 for (p.entries.items()) |&var e| {187 if (e.function == w[0]) {188 e.workgroup = [w[2], w[3], w[4]];189 }190 }191 }192 }193 ::Decorate, ::MemberDecorate {194 decorations.push(i);195 }196 ::EntryPoint {197 var name = word_text(&w[2..]);198 const name_words = (name.length() / 4 + 1) to u64;199 p.entries.push(Entry {200 .name = move name,201 .function = w[1],202 .interface_ids = Vector<u32>::from(&w[2 + name_words..])203 });204 }205 ::TypeVoid, ::TypeBool, ::TypeInt, ::TypeFloat, ::TypeVector, ::TypeMatrix, ::TypeImage,206 ::TypeSampler, ::TypeSampledImage, ::TypeArray, ::TypeRuntimeArray, ::TypeStruct,207 ::TypePointer, ::TypeFunction {208 p.declare_type(opcode, &w);209 }210 ::ConstantTrue, ::ConstantFalse, ::Constant, ::ConstantComposite, ::ConstantNull {211 p.declare_constant(opcode, &w);212 }213 ::Variable {214 p.declare_variable(&w);215 // a Function variable runs, for its initializer216 if (p.functions.length() > 0) {217 p.add_op(opcode, w[0], w[1], &w[2..]);218 }219 }220 ::Function {221 // its entry label is the next op222 p.functions.push(FunctionInfo {223 .id = w[1],224 .start = p.ops.length() to u32,225 .parameters = p.parameter_ids.length() to u32226 });227 p.give_registers(w[1], w[0]);228 }229 ::FunctionParameter {230 p.parameter_ids.push(w[1]);231 p.functions.get_var(p.functions.length() - 1).parameter_count += 1;232 p.give_registers(w[1], w[0]);233 }234 ::Label {235 p.labels.get_var(w[0] to u64) = p.ops.length() to u32;236 p.add_op(opcode, 0, w[0], &w[1..]);237 }238 ::Store, ::Branch, ::BranchConditional, ::Return, ::ReturnValue, ::Kill {239 p.add_op(opcode, 0, 0, &w);240 }241 ::ExtInst {242 if (Glsl::from(w[3]) is ::None) {243 panic "pkg::alloy::gpu: a GLSL.std.450 instruction it does not run";244 }245 p.give_registers(w[1], w[0]);246 p.add_op(opcode, w[0], w[1], &w[2..]);247 }248 else {249 p.give_registers(w[1], w[0]);250 p.add_op(opcode, w[0], w[1], &w[2..]);251 }252 }253 }254 for (decorations.view()) |&d| {255 p.decorate(d.opcode, &words[d.at..d.end]);256 }257 p.resolve_calls();258 p.zeros = p.registers.length() to u32;259 for ([..ZEROS]) {260 p.registers.push(0);261 }262 p.compile();263 return move p;264}265266// Which function each call calls, found once.267fn resolve_calls(self p: &var Program) {268 for (p.ops.items()) |&var op| {269 if (op.opcode is ::FunctionCall) {270 const callee = p.operands.get(op.first to u64);271 for ([..p.functions.length()]) |k| {272 if (p.functions.get(k).id == callee) {273 op.callee = k to u32;274 }275 }276 }277 }278}279280fn add_op(self p: &var Program, opcode: Opcode, ty: u32, result: u32, operands: &[u32]) {281 p.ops.push(Op {282 .opcode = opcode,283 .ty = ty,284 .result = result,285 .first = p.operands.length() to u32,286 .count = operands.length() to u32287 });288 p.operands.append(&operands);289}290291fn give_registers(self p: &var Program, id: u32, ty: u32) {292 p.value_types.get_var(id to u64) = ty;293 const cells = p.types.get(ty to u64).cells;294 p.registers_of.get_var(id to u64) = p.registers.length() to u32;295 for ([..cells to u64]) {296 p.registers.push(0);297 }298}299300fn declare_type(self p: &var Program, opcode: Opcode, w: &[u32]) {301 var t = p.types.get(w[0] to u64);302 match (opcode) {303 ::TypeBool {304 t.kind = ::Bool;305 t.cells = 1;306 }307 ::TypeInt {308 t.kind = ::Int;309 t.cells = 1;310 t.signed = w[2] == 1;311 }312 ::TypeFloat {313 t.kind = ::Float;314 t.cells = 1;315 }316 ::TypeVector, ::TypeMatrix {317 t.kind = if (opcode is ::TypeVector) TypeKind::Vector else TypeKind::Matrix;318 t.element = w[1];319 t.count = w[2];320 t.cells = t.count * p.types.get(w[1] to u64).cells;321 if (opcode is ::TypeVector) {322 t.stride = 4;323 }324 }325 ::TypeArray {326 t.kind = ::Array;327 t.element = w[1];328 t.count = p.registers.get(p.register(w[2]));329 t.cells = t.count * p.types.get(w[1] to u64).cells;330 }331 ::TypeRuntimeArray {332 t.kind = ::RuntimeArray;333 t.element = w[1];334 }335 ::TypeStruct {336 t.kind = ::Struct;337 t.count = (w.length() - 1) to u32;338 t.first = p.members.length() to u32;339 var cells: u32 = 0;340 for (w[1..]) |member| {341 p.members.push(Member { .ty = member, .cell = cells });342 cells += p.types.get(member to u64).cells;343 }344 t.cells = cells;345 }346 ::TypePointer {347 t.kind = ::Pointer;348 t.element = w[2];349 t.cells = 3;350 }351 ::TypeFunction {352 t.kind = ::Function;353 }354 ::TypeImage {355 t.kind = ::Image;356 t.cells = 1;357 }358 ::TypeSampler {359 t.kind = ::Sampler;360 t.cells = 1;361 }362 ::TypeSampledImage {363 t.kind = ::SampledImage;364 t.cells = 2;365 }366 }367 p.types.get_var(w[0] to u64) = t;368}369370fn declare_constant(self p: &var Program, opcode: Opcode, w: &[u32]) {371 p.give_registers(w[1], w[0]);372 p.fixed.get_var(w[1] to u64) = true;373 const at = p.register(w[1]);374 match (opcode) {375 ::ConstantTrue {376 p.registers.get_var(at) = 1;377 }378 ::Constant {379 p.registers.get_var(at) = w[2];380 }381 ::ConstantComposite {382 var out = at;383 for (w[2..]) |part| {384 const from = p.register(part);385 const cells = p.cells_of(part);386 for ([..cells]) |k| {387 p.registers.get_var(out + k) = p.registers.get(from + k);388 }389 out += cells;390 }391 }392 }393}394395fn declare_variable(self p: &var Program, w: &[u32]) {396 p.give_registers(w[1], w[0]);397 const pointee = p.types.get(w[0] to u64).element;398 const memory = p.memory.length() to u32;399 const storage = if (StorageClass::from(w[2]) is ::Some |s|) s else {400 panic "pkg::alloy::gpu: a SPIR-V storage class it does not know";401 };402 if (!storage.is_resource()) {403 for ([..p.types.get(pointee to u64).cells to u64]) {404 p.memory.push(0);405 }406 const at = p.register(w[1]);407 p.registers.get_var(at) = SPACE_MEMORY;408 p.registers.get_var(at + 2) = memory;409 p.fixed.get_var(w[1] to u64) = true;410 }411 p.variables.push(Variable { .id = w[1], .ty = pointee, .storage = storage, .memory = memory });412}413414fn decorate(self p: &var Program, opcode: Opcode, w: &[u32]) {415 if (opcode is ::MemberDecorate) {416 const member = (p.types.get(w[0] to u64).first + w[1]) to u64;417 if (Decoration::from(w[2]) is ::Some |decoration|) {418 match (decoration) {419 ::Offset {420 p.members.get_var(member).offset = w[3];421 }422 ::MatrixStride {423 p.types.get_var(p.members.get(member).ty to u64).stride = w[3];424 }425 }426 }427 return;428 }429 const decoration = if (Decoration::from(w[1]) is ::Some |d|) d else {430 return;431 };432 if (decoration is ::ArrayStride) {433 p.types.get_var(w[0] to u64).stride = w[2];434 return;435 }436 for (p.variables.items()) |&var v| {437 if (v.id == w[0]) {438 match (decoration) {439 ::Location {440 v.location = ::Some(w[2]);441 }442 ::BuiltIn {443 v.builtin = BuiltIn::from(w[2]);444 }445 ::DescriptorSet {446 v.group = ::Some(w[2]);447 }448 ::Binding {449 v.binding = ::Some(w[2]);450 }451 }452 }453 }454}455456/* --- What the rasterizer reaches --- */457458// The entry's Input or Output variables at a location.459pub fn stage_variables(460 self p: &Program,461 entry: u64,462 storage: StorageClass463) -> Vector<StageVariable> {464 var out = Vector<StageVariable>::empty();465 for (p.variables.view()) |&v| {466 if (467 v.storage == storage468 && v.location is ::Some |location|469 && p.in_interface(entry, v.id)470 ) {471 out.push(StageVariable {472 .location = location,473 .memory = v.memory,474 .cells = p.types.get(v.ty to u64).cells,475 .interpolated = p.scalar_kind(v.ty) is ::Float476 });477 }478 }479 return move out;480}481482// The memory cell of the entry's variable at the location.483pub fn stage_location(484 self p: &Program,485 entry: u64,486 storage: StorageClass,487 location: u32488) -> Option<u32> {489 for (p.variables.view()) |&v| {490 if (491 v.storage == storage492 && v.location is ::Some |l|493 && l == location494 && p.in_interface(entry, v.id)495 ) {496 return ::Some(v.memory);497 }498 }499 return ::None;500}501502// The memory cell of the entry's built-in variable.503pub fn stage_builtin(504 self p: &Program,505 entry: u64,506 storage: StorageClass,507 builtin: BuiltIn508) -> Option<u32> {509 for (p.variables.view()) |&v| {510 if (511 v.storage == storage512 && v.builtin is ::Some |b|513 && b == builtin514 && p.in_interface(entry, v.id)515 ) {516 return ::Some(v.memory);517 }518 }519 return ::None;520}521522pub fn workgroup_of(self p: &Program, entry: u64) -> [u32 : 3] => p.entries.get(entry).workgroup;523524fn in_interface(self p: &Program, entry: u64, id: u32) -> bool {525 for (p.entries.get(entry).interface_ids.view()) |i| {526 if (i == id) {527 return true;528 }529 }530 return false;531}532533fn scalar_kind(self p: &Program, ty: u32) -> TypeKind {534 const t = p.types.get(ty to u64);535 return match (t.kind) {536 ::Vector, ::Matrix, ::Array p.scalar_kind(t.element);537 else t.kind;538 };539}540541// Points the resource variables at the bound resources.542pub fn bind(self p: &var Program, bound: &[Bound]) {543 for (p.variables.view()) |&v| {544 if (v.group is ::Some |group| && v.binding is ::Some |binding|) {545 for (bound) |&b| {546 if (b.group == group && b.binding == binding) {547 const at = p.register(v.id);548 const handle = v.storage is ::UniformConstant;549 p.registers.get_var(at) = if (handle) SPACE_HANDLE else SPACE_BUFFER;550 p.registers.get_var(at + 1) = b.index;551 p.registers.get_var(at + 2) = b.offset;552 }553 }554 }555 }556}557558pub fn entry_index(self p: &Program, name: &[u8]) -> Option<u64> {559 for ([..p.entries.length()]) |k| {560 if (p.entries.get(k).name.view() == name) {561 return ::Some(k);562 }563 }564 return ::None;565}566567/* --- Compiling --- */568569// What a step does. Its operands are registers (first registers of570// values), found when compiled, so a run reads no ids, types nor operands.571type Action = enum {572 // a[k] op b[k] into out[k] for each of `cells`573 FAdd,574 FSub,575 FMul,576 FDiv,577 Component, // another operation on each component, `more` its opcode578 Copy, // `cells` registers from a579 Load, // through the pointer in a: `cells` cells of memory, a handle, or the buffer layout of `c` offsets at `more`580 Store, // b through the pointer in a, as Load581 LoadMemory, // `cells` cells of memory from a582 StoreMemory, // b into `cells` cells of memory at a583 Chain, // the pointer in a moved by b cells in memory or c bytes in buffers, and by the `cells` levels at `more`584 Initialize, // a function variable's initializer a into memory at `out`585 Sample, // the sampled image a at the coordinates b586 Glsl, // the instruction `more` on a, b and c587 // the most frequent GLSL instructions588 FMin,589 FMax,590 FAbs,591 FClamp,592 Length,593 Select, // b or c by a, `more` 1 when a is a scalar594 Dot,595 Scale, // a times the scalar b596 MatrixTimesVector, // `more` columns of `cells` rows597 VectorTimesMatrix,598 MatrixTimesMatrix, // `more` columns, `cells` rows, `c` the inner size599 Any,600 All,601 Zero,602 Jump, // to step a603 Branch, // to step b when a, else c604 // a comparison of the scalars a and b, then to step `out` when it605 // holds, else c606 BranchFEqual,607 BranchFLess,608 BranchFGreater,609 BranchFLessEqual,610 BranchFGreaterEqual,611 Return,612 Kill,613};614615// An action: `out` its result's first register, a, b and c its616// operands', `cells` how many it takes, `more` what else it needs.617type Step = struct {618 action: Action,619 out: u32 = 0,620 a: u32 = 0,621 b: u32 = 0,622 c: u32 = 0,623 cells: u32 = 0,624 more: u32 = 0,625};626627// An access chain's index that is not a constant: its register, and the628// cells or bytes an element takes in memory and in buffers.629type Level = struct {630 index: u32,631 memory: u32,632 buffer: u32,633};634635// The cells a missing GLSL argument reads, all zero.636const ZEROS: u64 = 16;637638// What compiling a function keeps: where its result goes when it is639// inlined, the steps branching to its ops, and those going to its end.640type Compiling = struct {641 result: Option<[u32 : 2]> = ::None, // a register and cells642 end: u32, // past its last op643 branches: Vector<u32> = Vector<u32>::empty(),644 returns: Vector<u32> = Vector<u32>::empty(),645 previous: u32 = 0, // the previous op's first step646};647648// Calls nest at most this deep: SPIR-V does not recurse.649const DEPTH: u32 = 32;650651// Each entry point's function as steps, the functions it calls inlined.652fn compile(self p: &var Program) {653 p.own = copy p.registers_of;654 p.uses = Vector<u32>::filled(0, p.registers_of.length());655 p.made = Vector<u32>::filled(UNSET, p.registers_of.length());656 for (p.operands.view()) |id| {657 if (p.uses.try_get(id to u64) is ::Some) {658 p.uses.get_var(id to u64) += 1;659 }660 }661 for ([..p.entries.length()]) |k| {662 const id = p.entries.get(k).function;663 var function: u64 = 0;664 for ([..p.functions.length()]) |f| {665 if (p.functions.get(f).id == id) {666 function = f;667 }668 }669 p.entries.get_var(k).start = p.steps.length() to u32;670 p.compile_function(function, ::None, 0);671 }672}673674// The function's ops as steps, each op starting where its first step is675// (labels make none); `result` where an inlined one's value goes.676fn compile_function(self p: &var Program, function: u64, result: Option<[u32 : 2]>, depth: u32) {677 if (depth > DEPTH) {678 panic "pkg::alloy::gpu: a shader's calls nest too deep";679 }680 const info = p.functions.get(function);681 var compiling = Compiling { .result = result, .end = info.end };682 var first = Vector<u32>::empty();683 for ([info.start..info.end]) |k| {684 if (k > info.start) {685 compiling.previous = first.get(first.length() - 1);686 }687 const before = p.steps.length();688 first.push(before to u32);689 const op = p.ops.get(k to u64);690 p.compile_op(&op, k, &var compiling, depth);691 // one step making the whole value, which parts made in place are not692 if (op.result != 0) {693 const one = p.steps.length() == before + 1 && p.steps.get(before).writes_out()694 && p.steps.get(before).out == p.at(op.result)695 && !(op.opcode is ::CompositeConstruct || op.opcode is ::VectorShuffle);696 p.made.get_var(op.result to u64) = if (one) before to u32 else UNSET;697 }698 }699 first.push(p.steps.length() to u32);700 for (compiling.branches.view()) |k| {701 const s = &var p.steps.items()[k to u64];702 match (s.action) {703 ::Jump {704 s.a = step_at(&first.view(), &info, s.a);705 }706 ::Branch {707 s.b = step_at(&first.view(), &info, s.b);708 s.c = step_at(&first.view(), &info, s.c);709 }710 else {711 s.out = step_at(&first.view(), &info, s.out);712 s.c = step_at(&first.view(), &info, s.c);713 }714 }715 }716 for (compiling.returns.view()) |k| {717 p.steps.items()[k to u64].a = p.steps.length() to u32;718 }719}720721// A branch on a comparison the op before made for it alone, made one722// step with it; whether it was.723fn fused(self p: &var Program, op: &Op, index: u32, compiling: &var Compiling) -> bool {724 const condition = p.operand(&op, 0);725 if (726 p.ops.get(index to u64 - 1).result != condition727 || p.uses.get(condition to u64) != 1728 || p.steps.length() to u32 != compiling.previous + 1729 ) {730 return false;731 }732 const last = compiling.previous;733 const s = &var p.steps.items()[last to u64];734 if (!(s.action is ::Component) || s.cells != 1 || s.out != p.at(condition)) {735 return false;736 }737 s.action = match (s.more to Opcode) {738 ::FOrdEqual Action::BranchFEqual;739 ::FOrdLessThan Action::BranchFLess;740 ::FOrdGreaterThan Action::BranchFGreater;741 ::FOrdLessThanEqual Action::BranchFLessEqual;742 ::FOrdGreaterThanEqual Action::BranchFGreaterEqual;743 else {744 return false;745 }746 };747 s.out = p.labels.get(p.operand(&op, 1) to u64);748 s.c = p.labels.get(p.operand(&op, 2) to u64);749 compiling.branches.push(last);750 return true;751}752753// The step the function's op starts at, from each op's first step; a754// label of another function, or not seen, faults when taken.755fn step_at(first: &[u32], function: &FunctionInfo, op: u32) -> u32 {756 return if (757 op >= function.start758 && op <= function.end759 ) first[(op - function.start) to u64] else UNSET;760}761762// The op, the `index`th, of the function being compiled.763fn compile_op(self p: &var Program, op: &Op, index: u32, compiling: &var Compiling, depth: u32) {764 // an inlined function's value made again in its own registers765 if (op.result != 0 && !(op.opcode is ::Variable)) {766 p.registers_of.get_var(op.result to u64) = p.own.get(op.result to u64);767 p.fixed.get_var(op.result to u64) = false;768 }769 // what most steps take: the result's registers and cells, the first770 // operands' registers (the first's for a missing second), the opcode771 const out = p.at(op.result);772 const a = if (op.count > 0) p.at(p.operand(&op, 0)) else out;773 const b = if (op.count > 1) p.at(p.operand(&op, 1)) else a;774 var s = Step {775 .action = ::Component,776 .out = out,777 .a = a,778 .b = b,779 .cells = p.cells_of(op.result) to u32,780 .more = op.opcode to u32781 };782 match (op.opcode) {783 ::Label {784 return;785 }786 ::Branch {787 // to the next block, run next anyway788 const target = p.labels.get(p.operand(&op, 0) to u64);789 if (target == index + 1) {790 return;791 }792 compiling.branches.push(p.steps.length() to u32);793 s = Step { .action = ::Jump, .a = target };794 }795 ::BranchConditional {796 if (p.fused(&op, index, &var compiling)) {797 return;798 }799 compiling.branches.push(p.steps.length() to u32);800 s.action = ::Branch;801 s.b = p.labels.get(p.operand(&op, 1) to u64);802 s.c = p.labels.get(p.operand(&op, 2) to u64);803 }804 ::Return, ::ReturnValue {805 s.action = ::Return;806 if (compiling.result is ::Some |result|) {807 // inlined: its value into the call's, then on after the call808 if (op.opcode is ::ReturnValue) {809 p.move_cells(result[0], p.operand(&op, 0), result[1] to u64);810 }811 if (index + 1 == compiling.end) {812 return;813 }814 compiling.returns.push(p.steps.length() to u32);815 s.action = ::Jump;816 }817 }818 ::Kill {819 s.action = ::Kill;820 }821 ::FunctionCall {822 // inlined, its parameters read from the arguments823 const function = p.functions.get(op.callee to u64);824 for ([..function.parameter_count to u64]) |k| {825 const parameter = p.parameter_ids.get(function.parameters to u64 + k);826 const argument = p.operand(&op, (k + 1) to u32);827 p.alias(parameter, p.at(argument));828 p.fixed.get_var(parameter to u64) = p.fixed.get(argument to u64);829 }830 p.compile_function(op.callee to u64, ::Some([out, s.cells]), depth + 1);831 return;832 }833 ::Variable {834 // a function variable's initializer835 if (op.count < 2) {836 return;837 }838 s.action = ::Initialize;839 s.out = p.registers.get(out to u64 + 2);840 s.a = b;841 s.cells = p.cells_of(p.operand(&op, 1)) to u32;842 }843 ::Load, ::Store {844 const load = op.opcode is ::Load;845 const value = if (load) op.result else p.operand(&op, 1);846 s.cells = p.cells_of(value) to u32;847 if (p.fixed.get(p.operand(&op, 0) to u64)) {848 s.action = if (load) Action::LoadMemory else Action::StoreMemory;849 s.a = p.registers.get(a to u64 + 2);850 } else {851 s.action = if (load) Action::Load else Action::Store;852 const layout = p.buffer_layout(p.value_types.get(value to u64));853 s.more = layout[0];854 s.c = layout[1];855 }856 }857 ::AccessChain {858 if (!p.chain(&op, &var s)) {859 return;860 }861 }862 ::CompositeConstruct {863 p.construct(&op, out);864 return;865 }866 ::CompositeExtract {867 var ty = p.value_types.get(p.operand(&op, 0) to u64);868 var from = a;869 for ([1..op.count]) |k| {870 const index = p.operand(&op, k);871 const t = p.types.get(ty to u64);872 if (t.kind is ::Struct) {873 const member = p.members.get((t.first + index) to u64);874 from += member.cell;875 ty = member.ty;876 } else {877 ty = t.element;878 from += index * p.types.get(ty to u64).cells;879 }880 }881 p.alias(op.result, from);882 p.fixed.get_var(op.result to u64) = p.fixed.get(p.operand(&op, 0) to u64);883 return;884 }885 ::VectorShuffle {886 p.shuffle(&op, out, a, b);887 return;888 }889 ::SampledImage {890 p.copy_cells(out, a, 1);891 p.copy_cells(out + 1, b, 1);892 return;893 }894 ::ImageSampleImplicitLod, ::ImageSampleExplicitLod {895 s.action = ::Sample;896 }897 ::ExtInst {898 // GLSL.std.450's: the instruction, then its arguments899 s.more = p.operand(&op, 1);900 s.action = match (s.more to Glsl) {901 ::FMin Action::FMin;902 ::FMax Action::FMax;903 ::FAbs Action::FAbs;904 ::FClamp Action::FClamp;905 ::Length Action::Length;906 else Action::Glsl;907 };908 s.a = p.at(p.operand(&op, 2));909 s.b = if (op.count > 3) p.at(p.operand(&op, 3)) else p.zeros;910 s.c = if (op.count > 4) p.at(p.operand(&op, 4)) else p.zeros;911 if ((s.more to Glsl) is ::Length || (s.more to Glsl) is ::Distance) {912 s.cells = p.cells_of(p.operand(&op, 2)) to u32;913 }914 }915 ::Select {916 s.action = ::Select;917 s.c = p.at(p.operand(&op, 2));918 s.more = if (p.cells_of(p.operand(&op, 0)) == 1) 1 else 0;919 }920 ::Dot, ::Any, ::All {921 s.action = match (op.opcode) {922 ::Dot Action::Dot;923 ::Any Action::Any;924 else Action::All;925 };926 s.cells = p.cells_of(p.operand(&op, 0)) to u32;927 }928 ::VectorTimesScalar, ::MatrixTimesScalar {929 s.action = ::Scale;930 }931 ::VectorTimesMatrix, ::MatrixTimesVector, ::MatrixTimesMatrix {932 p.matrix_step(&op, &var s);933 }934 ::DPdx, ::DPdy, ::Fwidth {935 // one fragment at a time has no neighbours: no change seen936 s.action = ::Zero;937 }938 ::FAdd {939 s.action = ::FAdd;940 }941 ::FSub {942 s.action = ::FSub;943 }944 ::FMul {945 s.action = ::FMul;946 }947 ::FDiv {948 s.action = ::FDiv;949 }950 else {951 // on each component of scalars and vectors952 }953 }954 p.steps.push(s);955}956957// A composite: of constants made now, else its parts moved in.958fn construct(self p: &var Program, op: &Op, out: u32) {959 var fixed = true;960 for ([..op.count]) |k| {961 fixed = fixed && p.fixed.get(p.operand(&op, k) to u64);962 }963 var at = out;964 for ([..op.count]) |k| {965 const part = p.operand(&op, k);966 const cells = p.cells_of(part);967 if (fixed) {968 for ([..cells]) |c| {969 p.registers.get_var(at to u64 + c) = p.registers.get(p.register(part) + c);970 }971 } else {972 p.move_cells(at, part, cells);973 }974 at += cells to u32;975 }976 p.fixed.get_var(op.result to u64) = fixed;977}978979// Components in order are a part of a vector, the rest copied.980fn shuffle(self p: &var Program, op: &Op, out: u32, a: u32, b: u32) {981 const a_count = p.cells_of(p.operand(&op, 0)) to u32;982 var froms = Vector<u32>::empty();983 for ([2..op.count]) |k| {984 const index = p.operand(&op, k);985 froms.push(if (index < a_count) a + index else b + index - a_count);986 }987 var together = true;988 for ([1..froms.length()]) |k| {989 together = together && froms.get(k) == froms.get(0) + k to u32;990 }991 if (together) {992 p.alias(op.result, froms.get(0));993 p.fixed.get_var(op.result to u64) = p.fixed.get(p.operand(&op, 0) to u64)994 && p.fixed.get(p.operand(&op, 1) to u64);995 return;996 }997 for (froms.view(), [..froms.length()]) |from, k| {998 p.copy_cells(out + k to u32, from, 1);999 }1000}10011002// Reads the id's value from registers another value has (a part of a1003// composite or a vector, an inlined call's argument), which are not1004// written while the id is used: a register is written only where its1005// value is made, which comes before whatever uses it.1006fn alias(self p: &var Program, id: u32, register: u32) {1007 p.registers_of.get_var(id to u64) = register;1008}10091010// The id's first register, as a step keeps it; UNSET for a literal1011// past the ids.1012fn at(self p: &Program, id: u32) -> u32 {1013 return if (p.registers_of.try_get(id to u64) is ::Some |r|) r else UNSET;1014}10151016fn copy_cells(self p: &var Program, out: u32, from: u32, cells: u64) {1017 p.steps.push(Step { .action = ::Copy, .out = out, .a = from, .cells = cells to u32 });1018}10191020// The id's value into the registers at `out`: made there by the step1021// making it when nothing else reads it, else copied.1022fn move_cells(self p: &var Program, out: u32, id: u32, cells: u64) {1023 const made = p.made.get(id to u64);1024 if (made != UNSET && p.uses.get(id to u64) == 1) {1025 p.steps.get_var(made to u64).out = out;1026 p.made.get_var(id to u64) = UNSET;1027 return;1028 }1029 p.copy_cells(out, p.at(id), cells);1030}10311032// Whether the step writes its value into the registers at `out`.1033fn writes_out(self s: &Step) -> bool => match (s.action) {1034 ::Store, ::StoreMemory, ::Initialize, ::Jump, ::Branch, ::BranchFEqual, ::BranchFLess,1035 ::BranchFGreater, ::BranchFLessEqual, ::BranchFGreaterEqual, ::Return, ::Kill false;1036 else true;1037};10381039// An access chain: struct members and constant indices summed now, the1040// other indices kept as levels; whether it needs a step, which one into1041// memory by constants does not, its pointer made now.1042fn chain(self p: &var Program, op: &Op, s: &var Step) -> bool {1043 var ty = p.types.get(p.value_types.get(p.operand(&op, 0) to u64) to u64).element;1044 var memory: u32 = 0;1045 var buffer: u32 = 0;1046 const first = p.levels.length() to u32;1047 for ([1..op.count]) |k| {1048 const id = p.operand(&op, k);1049 const t = p.types.get(ty to u64);1050 if (t.kind is ::Struct) {1051 const index = p.registers.get(p.register(id));1052 const member = p.members.get((t.first + index) to u64);1053 memory += member.cell;1054 buffer += member.offset;1055 ty = member.ty;1056 } else {1057 ty = t.element;1058 const cells = p.types.get(ty to u64).cells;1059 if (p.fixed.get(id to u64)) {1060 const index = p.registers.get(p.register(id));1061 memory += index * cells;1062 buffer += index * t.stride;1063 } else {1064 p.levels.push(Level { .index = p.at(id), .memory = cells, .buffer = t.stride });1065 }1066 }1067 }1068 if (p.fixed.get(p.operand(&op, 0) to u64) && p.levels.length() to u32 == first) {1069 const from = s.a to u64;1070 const out = s.out to u64;1071 p.registers.get_var(out) = p.registers.get(from);1072 p.registers.get_var(out + 1) = p.registers.get(from + 1);1073 p.registers.get_var(out + 2) = p.registers.get(from + 2) + memory;1074 p.fixed.get_var(op.result to u64) = true;1075 return false;1076 }1077 s.action = ::Chain;1078 s.b = memory;1079 s.c = buffer;1080 s.cells = p.levels.length() to u32 - first;1081 s.more = first;1082 return true;1083}10841085// The byte offsets of a type's cells in buffers, as decorated, added to1086// `layouts`: the first and how many.1087fn buffer_layout(self p: &var Program, ty: u32) -> [u32 : 2] {1088 const first = p.layouts.length() to u32;1089 p.lay_out(ty, 0);1090 return [first, p.layouts.length() to u32 - first];1091}10921093fn lay_out(self p: &var Program, ty: u32, offset: u32) {1094 const t = p.types.get(ty to u64);1095 match (t.kind) {1096 ::Struct {1097 for ([..t.count to u64]) |k| {1098 const member = p.members.get(t.first to u64 + k);1099 p.lay_out(member.ty, offset + member.offset);1100 }1101 }1102 ::Array, ::Matrix {1103 const stride = p.stride_of(&t);1104 for ([..t.count]) |k| {1105 p.lay_out(t.element, offset + k * stride);1106 }1107 }1108 else {1109 for ([..t.cells]) |k| {1110 p.layouts.push(offset + k * 4);1111 }1112 }1113 }1114}11151116// An array's or matrix's stride in buffers: decorated, or its elements'1117// size.1118fn stride_of(self p: &Program, t: &TypeInfo) -> u32 {1119 return if (t.stride == 0) p.types.get(t.element to u64).cells * 4 else t.stride;1120}11211122// A matrix product: `cells` rows, `more` columns, `c` the inner size.1123fn matrix_step(self p: &var Program, op: &Op, s: &var Step) {1124 const ta = p.types.get(p.value_types.get(p.operand(&op, 0) to u64) to u64);1125 const tb = p.types.get(p.value_types.get(p.operand(&op, 1) to u64) to u64);1126 match (op.opcode) {1127 ::MatrixTimesVector {1128 s.action = ::MatrixTimesVector;1129 s.cells = p.types.get(ta.element to u64).count;1130 s.more = ta.count;1131 }1132 ::VectorTimesMatrix {1133 s.action = ::VectorTimesMatrix;1134 s.cells = p.types.get(tb.element to u64).count;1135 s.more = tb.count;1136 }1137 else {1138 s.action = ::MatrixTimesMatrix;1139 s.cells = p.types.get(ta.element to u64).count;1140 s.c = ta.count;1141 s.more = tb.count;1142 }1143 }1144}11451146/* --- Running --- */11471148fn float(cell: u32) -> f32 => cell as f32;11491150fn bits(x: f32) -> u32 => x as u32;11511152// The id's first register.1153fn register(self p: &Program, id: u32) -> u64 => p.registers_of.get(id to u64) to u64;11541155fn cells_of(self p: &Program, id: u32) -> u64 => p.types.get(1156 p.value_types.get(id to u64) to u641157).cells to u64;11581159fn operand(self p: &Program, op: &Op, k: u32) -> u32 => p.operands.get((op.first + k) to u64);11601161// Runs the entry point once; false when a fragment was discarded.1162pub fn run(self p: &var Program, entry: u64, resources: &var CpuResources) -> bool {1163 var at = p.entries.get(entry).start to u64;1164 const steps = &p.steps.view();1165 var r = &var p.registers.items();1166 var memory = &var p.memory.items();1167 while (true) {1168 const s = &steps[at];1169 at += 1;1170 const out = s.out to u64;1171 const a = s.a to u64;1172 const b = s.b to u64;1173 const cells = s.cells to u64;1174 match (s.action) {1175 // the most frequent with a scalar's path of their own1176 ::FAdd {1177 if (cells == 1) {1178 r[out] = bits(float(r[a]) + float(r[b]));1179 } else {1180 for ([..cells]) |k| {1181 r[out + k] = bits(float(r[a + k]) + float(r[b + k]));1182 }1183 }1184 }1185 ::FSub {1186 if (cells == 1) {1187 r[out] = bits(float(r[a]) - float(r[b]));1188 } else {1189 for ([..cells]) |k| {1190 r[out + k] = bits(float(r[a + k]) - float(r[b + k]));1191 }1192 }1193 }1194 ::FMul {1195 if (cells == 1) {1196 r[out] = bits(float(r[a]) * float(r[b]));1197 } else {1198 for ([..cells]) |k| {1199 r[out + k] = bits(float(r[a + k]) * float(r[b + k]));1200 }1201 }1202 }1203 ::FDiv {1204 for ([..cells]) |k| {1205 r[out + k] = bits(float(r[a + k]) / float(r[b + k]));1206 }1207 }1208 ::Component {1209 const opcode = s.more to Opcode;1210 for ([..cells]) |k| {1211 r[out + k] = component(opcode, r[a + k], r[b + k]);1212 }1213 }1214 ::Copy {1215 if (cells == 1) {1216 r[out] = r[a];1217 } else {1218 r[out..out + cells] = r[a..a + cells];1219 }1220 }1221 ::Load {1222 const offset = r[a + 2] to u64;1223 match (r[a]) {1224 SPACE_MEMORY {1225 r[out..out + cells] = memory[offset..offset + cells];1226 }1227 SPACE_HANDLE {1228 r[out] = r[a + 1];1229 }1230 else {1231 const bytes = &resources.buffers.get(r[a + 1] to u64).view();1232 const layout = &p.layouts.view()[s.more to u64..(s.more + s.c) to u64];1233 for (layout, [..layout.length()]) |place, k| {1234 const at_byte = offset + place to u64;1235 r[out + k] = if (1236 at_byte + 4 <= bytes.length()1237 ) word(&bytes, at_byte) else 0;1238 }1239 }1240 }1241 }1242 ::Store {1243 const offset = r[a + 2] to u64;1244 match (r[a]) {1245 SPACE_MEMORY {1246 memory[offset..offset + cells] = r[b..b + cells];1247 }1248 SPACE_BUFFER {1249 const bytes = &var resources.buffers.get_var(r[a + 1] to u64).items();1250 const layout = &p.layouts.view()[s.more to u64..(s.more + s.c) to u64];1251 for (layout, [..layout.length()]) |place, k| {1252 const at_byte = offset + place to u64;1253 if (at_byte + 4 <= bytes.length()) {1254 put_word(&var bytes, at_byte, r[b + k]);1255 }1256 }1257 }1258 }1259 }1260 ::LoadMemory {1261 if (cells == 1) {1262 r[out] = memory[a];1263 } else {1264 r[out..out + cells] = memory[a..a + cells];1265 }1266 }1267 ::StoreMemory {1268 if (cells == 1) {1269 memory[a] = r[b];1270 } else {1271 memory[a..a + cells] = r[b..b + cells];1272 }1273 }1274 ::Chain {1275 const space = r[a];1276 var offset = r[a + 2];1277 const levels = &p.levels.view()[s.more to u64..(s.more + s.cells) to u64];1278 if (space == SPACE_MEMORY) {1279 offset += s.b;1280 for (levels) |&level| {1281 offset += r[level.index to u64] * level.memory;1282 }1283 } else {1284 offset += s.c;1285 for (levels) |&level| {1286 offset += r[level.index to u64] * level.buffer;1287 }1288 }1289 r[out] = space;1290 r[out + 1] = r[a + 1];1291 r[out + 2] = offset;1292 }1293 ::Initialize {1294 memory[out..out + cells] = r[a..a + cells];1295 }1296 ::Sample {1297 sample(&var r, &s, &resources);1298 }1299 ::Glsl {1300 glsl(&var r, &s);1301 }1302 ::FMin {1303 for ([..cells]) |k| {1304 const x = float(r[a + k]);1305 const y = float(r[b + k]);1306 r[out + k] = bits(if (y < x) y else x);1307 }1308 }1309 ::FMax {1310 for ([..cells]) |k| {1311 const x = float(r[a + k]);1312 const y = float(r[b + k]);1313 r[out + k] = bits(if (y > x) y else x);1314 }1315 }1316 ::FAbs {1317 for ([..cells]) |k| {1318 r[out + k] = r[a + k] & 0x7FFFFFFF;1319 }1320 }1321 ::FClamp {1322 const c = s.c to u64;1323 for ([..cells]) |k| {1324 const x = float(r[a + k]);1325 const low = float(r[b + k]);1326 const high = float(r[c + k]);1327 r[out + k] = bits(if (x < low) low else if (x > high) high else x);1328 }1329 }1330 ::Length {1331 var sum: f32 = 0.0;1332 for ([..cells]) |k| {1333 const d = float(r[a + k]);1334 sum += d * d;1335 }1336 r[out] = bits(sqrt(sum));1337 }1338 ::Select {1339 const scalar = s.more == 1;1340 const c = s.c to u64;1341 for ([..cells]) |k| {1342 const condition = r[a + if (scalar) 0 else k];1343 r[out + k] = if (condition != 0) r[b + k] else r[c + k];1344 }1345 }1346 ::Dot {1347 var sum: f32 = 0.0;1348 for ([..cells]) |k| {1349 sum += float(r[a + k]) * float(r[b + k]);1350 }1351 r[out] = bits(sum);1352 }1353 ::Scale {1354 const scale = float(r[b]);1355 for ([..cells]) |k| {1356 r[out + k] = bits(float(r[a + k]) * scale);1357 }1358 }1359 ::MatrixTimesVector, ::VectorTimesMatrix, ::MatrixTimesMatrix {1360 matrix(&var r, &s);1361 }1362 ::Any, ::All {1363 const any = s.action is ::Any;1364 var result = !any;1365 for ([..cells]) |k| {1366 const v = r[a + k] != 0;1367 result = if (any) result || v else result && v;1368 }1369 r[out] = truth(result);1370 }1371 ::Zero {1372 for ([..cells]) |k| {1373 r[out + k] = 0;1374 }1375 }1376 ::Jump {1377 at = a;1378 }1379 ::Branch {1380 at = if (r[a] != 0) b else s.c to u64;1381 }1382 ::BranchFEqual {1383 at = if (float(r[a]) == float(r[b])) out else s.c to u64;1384 }1385 ::BranchFLess {1386 at = if (float(r[a]) < float(r[b])) out else s.c to u64;1387 }1388 ::BranchFGreater {1389 at = if (float(r[a]) > float(r[b])) out else s.c to u64;1390 }1391 ::BranchFLessEqual {1392 at = if (float(r[a]) <= float(r[b])) out else s.c to u64;1393 }1394 ::BranchFGreaterEqual {1395 at = if (float(r[a]) >= float(r[b])) out else s.c to u64;1396 }1397 ::Return {1398 return true;1399 }1400 ::Kill {1401 return false;1402 }1403 }1404 }1405}14061407// The little-endian word at the byte.1408fn word(bytes: &[u8], at: u64) -> u32 {1409 return bytes[at] to u32 | (bytes[at + 1] to u32 << 8) | (bytes[at + 2] to u32 << 16) | (1410 bytes[at + 3] to u32 << 241411 );1412}14131414fn put_word(bytes: &var [u8], at: u64, word: u32) {1415 bytes[at] = (word & 0xFF) to u8;1416 bytes[at + 1] = ((word >> 8) & 0xFF) to u8;1417 bytes[at + 2] = ((word >> 16) & 0xFF) to u8;1418 bytes[at + 3] = (word >> 24) to u8;1419}14201421fn component(opcode: Opcode, x: u32, y: u32) -> u32 {1422 const xi = x as i32;1423 const yi = y as i32;1424 return match (opcode) {1425 ::FAdd bits(float(x) + float(y));1426 ::FSub bits(float(x) - float(y));1427 ::FMul bits(float(x) * float(y));1428 ::FDiv bits(float(x) / float(y));1429 ::FRem bits(float(x) - float(y) * trunc(float(x) / float(y)));1430 ::FNegate x ^ 0x80000000;1431 ::IAdd x +% y;1432 ::ISub x -% y;1433 ::IMul x *% y;1434 ::SNegate 0 -% x;1435 ::UDiv if (y == 0) x else x / y;1436 ::UMod if (y == 0) 0 else x % y;1437 ::SDiv if (yi == 0 || (yi == -1 && x == 0x80000000)) x else (xi / yi) as u32;1438 ::SRem if (yi == 0 || yi == -1) 0 else (xi % yi) as u32;1439 ::BitwiseAnd, ::LogicalAnd x & y;1440 ::BitwiseOr, ::LogicalOr x | y;1441 ::BitwiseXor x ^ y;1442 ::Not ~x;1443 ::LogicalNot truth(x == 0);1444 ::ShiftLeftLogical x << (y & 31);1445 ::ShiftRightLogical x >> (y & 31);1446 ::ShiftRightArithmetic (xi >> (y & 31) as i32) as u32;1447 ::ConvertFToS (saturated(float(x), -2147483648.0, 2147483520.0) to i32) as u32;1448 ::ConvertFToU saturated(float(x), 0.0, 4294967040.0) to u32;1449 ::ConvertSToF bits(xi to f32);1450 ::ConvertUToF bits(x to f32);1451 ::Bitcast x;1452 ::LogicalEqual, ::IEqual truth(x == y);1453 ::LogicalNotEqual, ::INotEqual truth(x != y);1454 ::UGreaterThan truth(x > y);1455 ::SGreaterThan truth(xi > yi);1456 ::UGreaterThanEqual truth(x >= y);1457 ::SGreaterThanEqual truth(xi >= yi);1458 ::ULessThan truth(x < y);1459 ::SLessThan truth(xi < yi);1460 ::ULessThanEqual truth(x <= y);1461 ::SLessThanEqual truth(xi <= yi);1462 ::FOrdEqual truth(float(x) == float(y));1463 ::FOrdNotEqual truth(float(x) != float(y) && !is_nan(float(x)) && !is_nan(float(y)));1464 ::FOrdLessThan truth(float(x) < float(y));1465 ::FOrdGreaterThan truth(float(x) > float(y));1466 ::FOrdLessThanEqual truth(float(x) <= float(y));1467 ::FOrdGreaterThanEqual truth(float(x) >= float(y));1468 else 0;1469 };1470}14711472fn truth(b: bool) -> u32 => if (b) 1 else 0;14731474// The float clamped into what an integer conversion takes, NaN as 0.1475fn saturated(x: f32, low: f32, high: f32) -> f32 {1476 if (is_nan(x)) {1477 return 0.0;1478 }1479 return if (x < low) low else if (x > high) high else x;1480}14811482fn matrix(r: &var [u32], s: &Step) {1483 const a = s.a to u64;1484 const b = s.b to u64;1485 const out = s.out to u64;1486 const rows = s.cells to u64;1487 const columns = s.more to u64;1488 match (s.action) {1489 ::MatrixTimesVector {1490 // the columns weighted by the vector's components1491 var result: [f32 : 4] = [0.0 : 4];1492 for ([..columns]) |column| {1493 const weight = float(r[b + column]);1494 for ([..rows]) |row| {1495 result[row] += float(r[a + column * rows + row]) * weight;1496 }1497 }1498 for ([..rows]) |row| {1499 r[out + row] = bits(result[row]);1500 }1501 }1502 ::VectorTimesMatrix {1503 // the vector's dot product with each column1504 for ([..columns]) |column| {1505 var sum: f32 = 0.0;1506 for ([..rows]) |row| {1507 sum += float(r[a + row]) * float(r[b + column * rows + row]);1508 }1509 r[out + column] = bits(sum);1510 }1511 }1512 else {1513 const inner = s.c to u64;1514 for ([..columns]) |column| {1515 for ([..rows]) |row| {1516 var sum: f32 = 0.0;1517 for ([..inner]) |k| {1518 sum += float(r[a + k * rows + row]) * float(r[b + column * inner + k]);1519 }1520 r[out + column * rows + row] = bits(sum);1521 }1522 }1523 }1524 }1525}15261527fn glsl(r: &var [u32], s: &Step) {1528 const instruction = s.more to Glsl;1529 const out = s.out to u64;1530 const count = s.cells to u64;1531 const x = s.a to u64;1532 const y = s.b to u64;1533 match (instruction) {1534 ::Length, ::Distance {1535 var sum: f32 = 0.0;1536 for ([..count]) |k| {1537 var d = float(r[x + k]);1538 if (instruction is ::Distance) {1539 d -= float(r[y + k]);1540 }1541 sum += d * d;1542 }1543 r[out] = bits(sqrt(sum));1544 }1545 ::Normalize {1546 var sum: f32 = 0.0;1547 for ([..count]) |k| {1548 sum += float(r[x + k]) * float(r[x + k]);1549 }1550 const length = sqrt(sum);1551 for ([..count]) |k| {1552 r[out + k] = bits(float(r[x + k]) / length);1553 }1554 }1555 ::Cross {1556 const a: [f32 : 3] = [float(r[x]), float(r[x + 1]), float(r[x + 2])];1557 const b: [f32 : 3] = [float(r[y]), float(r[y + 1]), float(r[y + 2])];1558 r[out] = bits(a[1] * b[2] - a[2] * b[1]);1559 r[out + 1] = bits(a[2] * b[0] - a[0] * b[2]);1560 r[out + 2] = bits(a[0] * b[1] - a[1] * b[0]);1561 }1562 ::Reflect {1563 var d: f32 = 0.0;1564 for ([..count]) |k| {1565 d += float(r[x + k]) * float(r[y + k]);1566 }1567 for ([..count]) |k| {1568 r[out + k] = bits(float(r[x + k]) - 2.0 * d * float(r[y + k]));1569 }1570 }1571 else {1572 const z = s.c to u64;1573 for ([..count]) |k| {1574 r[out + k] = glsl_component(instruction, r[x + k], r[y + k], r[z + k]);1575 }1576 }1577 }1578}15791580fn glsl_component(instruction: Glsl, a: u32, b: u32, c: u32) -> u32 {1581 const x = float(a);1582 const y = float(b);1583 const z = float(c);1584 return match (instruction) {1585 ::RoundEven bits(round_even(x));1586 ::Trunc bits(trunc(x));1587 ::FAbs a & 0x7FFFFFFF;1588 ::SAbs if ((a as i32) < 0) 0 -% a else a;1589 ::FSign bits(if (x > 0.0) 1.0 else if (x < 0.0) -1.0 else 0.0);1590 ::Floor bits(floor(x));1591 ::Ceil bits(ceil(x));1592 ::Fract bits(x - floor(x));1593 ::Sin bits(sin(x));1594 ::Cos bits(cos(x));1595 ::Tan bits(tan(x));1596 ::Asin bits(asin(x));1597 ::Acos bits(acos(x));1598 ::Atan bits(atan(x));1599 ::Atan2 bits(atan2(x, y));1600 ::Pow bits(pow(x, y));1601 ::Exp bits(exponential(x));1602 ::Log bits(log(x));1603 ::Exp2 bits(exp2(x));1604 ::Log2 bits(log2(x));1605 ::Sqrt bits(sqrt(x));1606 ::InverseSqrt bits(1.0 / sqrt(x));1607 ::FMin bits(if (y < x) y else x);1608 ::FMax bits(if (y > x) y else x);1609 ::UMin if (b < a) b else a;1610 ::UMax if (b > a) b else a;1611 ::SMin if ((b as i32) < (a as i32)) b else a;1612 ::SMax if ((b as i32) > (a as i32)) b else a;1613 ::FClamp bits(if (x < y) y else if (x > z) z else x);1614 ::UClamp if (a < b) b else if (a > c) c else a;1615 ::SClamp if ((a as i32) < (b as i32)) b else if ((a as i32) > (c as i32)) c else a;1616 ::FMix bits(x + (y - x) * z);1617 ::Step bits(if (y < x) 0.0 else 1.0);1618 ::SmoothStep bits(smooth_step(x, y, z));1619 ::Fma bits(fma(x, y, z));1620 else 0;1621 };1622}16231624// Rounded to the nearest integer, halfway values to the even one.1625fn round_even(x: f32) -> f32 {1626 const r = round(x);1627 return if (abs(x - trunc(x)) == 0.5 && (r * 0.5) != trunc(r * 0.5)) r - copysign(1.0, x) else r;1628}16291630fn smooth_step(low: f32, high: f32, x: f32) -> f32 {1631 var t = (x - low) / (high - low);1632 t = if (t < 0.0) 0.0 else if (t > 1.0) 1.0 else t;1633 return t * t * (3.0 - 2.0 * t);1634}16351636/* --- Textures --- */16371638fn sample(r: &var [u32], s: &Step, resources: &CpuResources) {1639 const image = s.a to u64;1640 const texture = &resources.textures.get(r[image] to u64);1641 const sampler = resources.samplers.get(r[image + 1] to u64);1642 const coordinates = s.b to u64;1643 const u = float(r[coordinates]);1644 const v = float(r[coordinates + 1]);1645 var color: [f32 : 4] = [0.0 : 4];1646 if (sampler.linear) {1647 // the four texels around the point, weighted by distance1648 const x = u * texture.width to f32 - 0.5;1649 const y = v * texture.height to f32 - 0.5;1650 const x0 = floor(x);1651 const y0 = floor(y);1652 const fx = x - x0;1653 const fy = y - y0;1654 const weights: [f32 : 4] = [1655 (1.0 - fx) * (1.0 - fy),1656 fx * (1.0 - fy),1657 (1.0 - fx) * fy,1658 fx * fy1659 ];1660 const xs: [i64 : 4] = [x0 to i64, x0 to i64 + 1, x0 to i64, x0 to i64 + 1];1661 const ys: [i64 : 4] = [y0 to i64, y0 to i64, y0 to i64 + 1, y0 to i64 + 1];1662 for (weights, xs, ys) |weight, tx, ty| {1663 const texel = texture.texel(&sampler, tx, ty);1664 for ([..4 to u64]) |c| {1665 color[c] += weight * ((texel >> (c * 8) to u32) & 0xFF) to f32 / 255.0;1666 }1667 }1668 } else {1669 const texel = texture.texel(1670 &sampler,1671 floor(u * texture.width to f32) to i64,1672 floor(v * texture.height to f32) to i641673 );1674 for ([..4 to u64]) |c| {1675 color[c] = ((texel >> (c * 8) to u32) & 0xFF) to f32 / 255.0;1676 }1677 }1678 const out = s.out to u64;1679 for ([..4 to u64]) |c| {1680 r[out + c] = bits(color[c]);1681 }1682}16831684// The texel at x, y, repeated or clamped to the edge outside the texture.1685fn texel(self texture: &CpuTexture, sampler: &CpuSampler, x: i64, y: i64) -> u32 {1686 const w = texture.width to i64;1687 const h = texture.height to i64;1688 var tx = x;1689 var ty = y;1690 if (sampler.repeat) {1691 tx = ((tx % w) + w) % w;1692 ty = ((ty % h) + h) % h;1693 } else {1694 tx = if (tx < 0) 0 else if (tx >= w) w - 1 else tx;1695 ty = if (ty < 0) 0 else if (ty >= h) h - 1 else ty;1696 }1697 return texture.pixels.get((ty * w + tx) to u64);1698}