From 004a7eff196e1bfcf446ffc367b5ff1e31066cca Mon Sep 17 00:00:00 2001 From: Ed_ Date: Mon, 10 Aug 2026 14:13:02 -0400 Subject: [PATCH] WIP: not fully reviewed. Adds auto-register allocation + mips atom procs + wip resolve look at atoms + atom bundle... --- code/duffle/dsl.atom.h | 20 + code/duffle/gen/macs.h | 26 +- code/duffle/gen/offsets.h | 2 +- code/duffle/gp.atom.c | 22 +- code/duffle/gte.atom.c | 94 ++-- code/duffle/lottes_tape.h | 62 +-- code/duffle/math.atom.c | 12 +- code/duffle/pad.atom.c | 14 +- code/duffle/pad.h | 1 + code/hello_camera/gen/macs.h | 347 ++++++++++++ code/hello_camera/gen/offsets.h | 30 + code/hello_camera/hello_camera.atom.c | 761 ++++++++++++++++++++++++-- code/hello_camera/hello_camera.c | 237 ++++++-- code/hello_joypad/hello_joypad.atom.c | 20 +- code/hello_joypad/sio.tape.c | 4 +- scripts/passes/auto_reg.lua | 322 +++++++++++ scripts/passes/components.lua | 36 +- scripts/passes/emission_model.lua | 6 +- scripts/passes/scan_source.lua | 223 +++++++- scripts/passes/static_analysis.lua | 14 +- scripts/ps1_meta.lua | 6 + 21 files changed, 1991 insertions(+), 268 deletions(-) create mode 100644 scripts/passes/auto_reg.lua diff --git a/code/duffle/dsl.atom.h b/code/duffle/dsl.atom.h index 092515b..4d1f4a9 100644 --- a/code/duffle/dsl.atom.h +++ b/code/duffle/dsl.atom.h @@ -75,6 +75,26 @@ * ----------------------------------------------------------------------------*/ #define atom_reg /* atom_reg: opt the preceding enum entry into the DWARF registry */ +// ---------------------------------------------------------------------------- +// atom_auto_reg(atom, sym) — per-atom auto-allocated GPR binding. +// enum { +// atom_auto_reg(cube_g4_face, R_Fwdx), // expands to: R_Fwdx = R_Fwdx_Code /* atom_auto_reg: cube_g4_face */, +// atom_auto_reg(cube_g4_face, R_Eye_z) atom_type(S4), // atom_type chains after +// }; +// (The macro IS the entire enum entry — no separate LHS=RHS. The `atom` scope is +// preserved in a trailing C-comment on the RHS so the Lua scanner can recover +// it after preprocessing strips the macro form. R__Code is resolved from gen/auto_reg.h which the .c file #include's before the enum declaration.) +#define atom_auto_reg(atom, sym) sym = sym ## _Code /* atom_auto_reg: atom */ + +// ---------------------------------------------------------------------------- +// phase_auto_reg(phase, sym) — per-phase auto-allocated GPR binding. +// enum { +// phase_auto_reg(cube_g4, R_Temp0), // expands to: R_Temp0 = R_Temp0_Code /* phase_auto_reg: cube_g4 */, +// phase_auto_reg(cube_g4, R_Temp1), +// }; +// (Same macro-as-enum-entry form as atom_auto_reg above; the `phase` scope is preserved in a trailing C-comment on the RHS for the Lua scanner to recover.) +#define phase_auto_reg(phase, sym) sym = sym ## _Code /* phase_auto_reg: phase */ + /* ============================================================================ * atom_info : * MipsAtom_(cube_tri) atom_info( diff --git a/code/duffle/gen/macs.h b/code/duffle/gen/macs.h index 72dfd8b..520a0b6 100644 --- a/code/duffle/gen/macs.h +++ b/code/duffle/gen/macs.h @@ -175,13 +175,19 @@ WORD_COUNT(mac_gte_sqr_v3, 8) , shift_aright_var(r_dz, r_dz, r_shift) WORD_COUNT(mac_gte_gpf_scale, 13) -/* atom_dbg_skip */ -#define mac_normalize_v3s4(r_sx, r_sy, r_sz, r_sq_y, r_sq_z, r_recip_est, r_lzcr, r_shift, r_tmp) \ - gte_mv_to_data_r(r_sx, C2_IR1) \ +#define mac_normalize_v3s4(...) \ + load_word(r_src, R_TapePtr, O_(Binds_NormalizeV3S4,src)) /* pop src ptr (scratch addr) */ \ +, load_word(r_dst, R_TapePtr, O_(Binds_NormalizeV3S4,dst)) /* pop dst ptr (scratch addr) */ \ +, add_ui_self( R_TapePtr, S_(Binds_NormalizeV3S4)) \ +, load_word(r_sx, r_src, O_(V3_S4,x)) \ +, load_word(r_sy, r_src, O_(V3_S4,y)) \ +, load_word(r_sz, r_src, O_(V3_S4,z)) \ +, nop /* load-delay */ /* ── 48-word normalize body (preserved verbatim from ac_normalize_v3s4) ─────── */ /* Stage 1: mtc2 src → IR1/2/3, SQR fires (MAC1/2/3 = IR², IR ← MAC saturated) */ \ +, gte_mv_to_data_r(r_sx, C2_IR1) \ , gte_mv_to_data_r(r_sy, C2_IR2) \ , gte_mv_to_data_r(r_sz, C2_IR3) \ , nop \ -, gte_cmdw_sqr /* ─── Stage 2: mfc2 MAC1/2/3, sum, mtc2 LZCS ─── // Note: r_recip_est first used as the sum accumulator (= |v|²), which is also what LZCS needs. */ \ +, gte_cmdw_sqr /* Stage 2: mfc2 MAC1/2/3, sum, mtc2 LZCS */ \ , gte_mv_from_data_r(r_sq_y, C2_MAC1) /* r_sq_y = MAC1 = sx² */ \ , gte_mv_from_data_r(r_sq_z, C2_MAC2) /* r_sq_z = MAC2 = sy² */ \ , gte_mv_from_data_r(r_recip_est, C2_MAC3) /* r_recip_est = MAC3 = sz² */ \ @@ -191,7 +197,7 @@ WORD_COUNT(mac_gte_gpf_scale, 13) , gte_mv_to_data_r( r_recip_est, C2_LZCS) /* LZCS = |v|² */ \ , nop2 \ , gte_mv_from_data_r(r_lzcr, C2_LZCR) /* r_lzcr = LZCR (count of leading bits) */ \ -, nop /* MFC2→GPR load delay (1 slot) */ /* ─── Stage 3: compute shift amount, align |v|² to bit 24, lookup 1/|v| ─── // Matches libgte `bltz +0x10 ; nop ; b +0x14 ; sllv t4,v0,t3` pattern: // - bltz TAKEN → nop (BD), jump to srav_path; sllv SKIPPED // - bltz !TAKEN → nop (BD), b +0x14 jumps to aligned_done; sllv (BD of b) executes */ \ +, nop /* MFC2→GPR load delay (1 slot) */ /* Stage 3: compute shift amount, align |v|² to bit 24, lookup 1/|v| */ \ , and_i( r_lzcr, r_lzcr, -2) /* r_lzcr &= ~1 (force even for halving) */ \ , li_s( r_shift, 31) /* r_shift = 31 */ \ , sub_s( r_shift, r_shift, r_lzcr) /* r_shift = 31 - LZCR */ \ @@ -212,7 +218,7 @@ WORD_COUNT(mac_gte_gpf_scale, 13) , or_i_self( r_tmp, u4_lo(& gte_normalize_sqr_tbl)) /* ori */ \ , add_u( r_tmp, r_tmp, r_recip_est) /* r_tmp = sqrtbl base + byte offset (matches libgte 0x80016118: addu t5,t5,t4) */ \ , load_half( r_recip_est, r_tmp, 0) /* r_recip_est = sqrtbl[r_recip_est] = 1/|v| estimate */ \ -, nop /* retire load_half before MTC2 (matches libgte 0x80016120: nop) */ /* ─── Stage 4: mtc2 IR0..3, GPF (MAC = IR0*IR), mfc2 MAC, srav finalize ─── // Componentized equivalent: mac_gte_gpf_scale. */ \ +, nop /* retire load_half before MTC2 (matches libgte 0x80016120: nop) */ /* Stage 4: mtc2 IR0..3, GPF (MAC = IR0*IR), mfc2 MAC, srav finalize */ \ , gte_mv_to_data_r(r_recip_est, C2_IR0) /* IR0 = 1/|v| estimate */ \ , gte_mv_to_data_r(r_sx, C2_IR1) /* IR1 = src.x */ \ , gte_mv_to_data_r(r_sy, C2_IR2) /* IR2 = src.y */ \ @@ -224,8 +230,12 @@ WORD_COUNT(mac_gte_gpf_scale, 13) , gte_mv_from_data_r(r_sz, C2_MAC3) \ , shift_aright_var(r_sx, r_sx, r_shift) \ , shift_aright_var(r_sy, r_sy, r_shift) \ -, shift_aright_var(r_sz, r_sz, r_shift) -WORD_COUNT(mac_normalize_v3s4, 48) +, shift_aright_var(r_sz, r_sz, r_shift) /* ── I/O wrapper tail (~3 words) ───────────────────────────────────────────── */ \ +, store_word(r_sx, r_dst, O_(V3_S4,x)) \ +, store_word(r_sy, r_dst, O_(V3_S4,y)) \ +, store_word(r_sz, r_dst, O_(V3_S4,z)) /* ── atom_reads(R_TapePtr) atom_writes(R_TapePtr) ────────────────────────── */ \ +, mac_yield() +WORD_COUNT(mac_normalize_v3s4, 62) #define mac_gcmd_push(cmd, reg_transfer, reg_base, port) \ load_upper_i(reg_transfer, cmd >> 16) \ diff --git a/code/duffle/gen/offsets.h b/code/duffle/gen/offsets.h index f15733d..32af6aa 100644 --- a/code/duffle/gen/offsets.h +++ b/code/duffle/gen/offsets.h @@ -25,7 +25,7 @@ #pragma region duffle -// --- atom: ac_normalize_v3s4 (48 words) --- +// --- atom: normalize_v3s4 (62 words) --- #define _atom_offset_srav_path_aligned_done 6 #define _atom_offset_aligned_done_srav_path 1 diff --git a/code/duffle/gp.atom.c b/code/duffle/gp.atom.c index 012c759..80f7150 100644 --- a/code/duffle/gp.atom.c +++ b/code/duffle/gp.atom.c @@ -8,35 +8,35 @@ ATOM_FILE_DEBUGGER_LINE_MARKER(gp_atom_c); #pragma region MACs (Mips Atom Components) -FI_ Slice_MipsCode ac_gcmd_push(U4 cmd, U4 reg_transfer, U4 reg_base, U2 port) -MipsAtomComp_Proc_(ac_gcmd_push, { +FI_ Slice_MipsCode ac_gcmd_push(MipsAtomBuilder_R ab, U4 cmd, U4 reg_transfer, U4 reg_base, U2 port) +MipsAtomComp_Proc_(ac_gcmd_push, ab, { load_upper_i(reg_transfer, cmd >> 16), or_i_self( reg_transfer, cmd & 0xFFFF), store_word( reg_transfer, reg_base, port), }) -FI_ Slice_MipsCode ac_store_rgb8(U1 rr, U1 rg, U1 rb, U4 base, U4 offset) atom_dbg_skip MipsAtomComp_Proc_(ac_store_rgb8, { +FI_ Slice_MipsCode ac_store_rgb8(MipsAtomBuilder_R ab, U1 rr, U1 rg, U1 rb, U4 base, U4 offset) atom_dbg_skip MipsAtomComp_Proc_(ac_store_rgb8, ab, { store_byte(rr, base, offset + O_(RGB8,r)), store_byte(rg, base, offset + O_(RGB8,g)), - store_byte(rb, base, offset + O_(RGB8,b)), + store_byte(rb, base, offset + O_(RGB8,b)), }) -FI_ Slice_MipsCode ac_pack_color_word(U4 r_base, U4 off, U4 cmd, U1 r, U1 g, U1 b) -atom_dbg_skip MipsAtomComp_Proc_(ac_pack_color_word, { +FI_ Slice_MipsCode ac_pack_color_word(MipsAtomBuilder_R ab, U4 r_base, U4 off, U4 cmd, U1 r, U1 g, U1 b) +atom_dbg_skip MipsAtomComp_Proc_(ac_pack_color_word, ab, { load_upper_i(R_AT, (cmd) << 8 | (b)), or_i_self( R_AT, ((g) << 8) | (r)), store_word( R_AT, r_base, (off)), }) -FI_ Slice_MipsCode ac_format_f3_color(U4 r_base, U1 r, U1 g, U1 b) -atom_dbg_skip MipsAtomComp_Proc_(ac_format_f3_color, { mac_pack_color_word(r_base, O_(Poly_F3,color), gp0_cmd_poly_f3, r, g, b) }) +FI_ Slice_MipsCode ac_format_f3_color(MipsAtomBuilder_R ab, U4 r_base, U1 r, U1 g, U1 b) +atom_dbg_skip MipsAtomComp_Proc_(ac_format_f3_color, ab, { mac_pack_color_word(r_base, O_(Poly_F3,color), gp0_cmd_poly_f3, r, g, b) }) -FI_ Slice_MipsCode ac_format_g4_color(U4 r_prim_cursor, +FI_ Slice_MipsCode ac_format_g4_color(MipsAtomBuilder_R ab, U4 r_prim_cursor, U1 r0, U1 g0, U1 b0, U1 r1, U1 g1, U1 b1, U1 r2, U1 g2, U1 b2, U1 r3, U1 g3, U1 b3) -MipsAtomComp_Proc_(ac_format_g4_color, { +MipsAtomComp_Proc_(ac_format_g4_color, ab, { mac_pack_color_word(r_prim_cursor, O_(Poly_G4,c0), gp0_cmd_poly_g4, r0,g0,b0), mac_pack_color_word(r_prim_cursor, O_(Poly_G4,c1), 0, r1,g1,b1), mac_pack_color_word(r_prim_cursor, O_(Poly_G4,c2), 0, r2,g2,b2), @@ -44,7 +44,7 @@ MipsAtomComp_Proc_(ac_format_g4_color, { }) /* Words: 11; Correctly inserts a primitive into the Ordering Table linked list. */ -I_ Slice_MipsCode ac_insert_ot_tag(U4 r_ot_base, U4 r_prim_cursor, U4 poly_size) MipsAtomComp_Proc_(ac_insert_ot_tag, { +I_ Slice_MipsCode ac_insert_ot_tag(MipsAtomBuilder_R ab, U4 r_ot_base, U4 r_prim_cursor, U4 poly_size) MipsAtomComp_Proc_(ac_insert_ot_tag, ab, { shift_lleft( R_T1, R_T1, S_(U4)/2), // T1 = otz * S_(U4) (otz arg is implicit R_T1) add_u_self( R_T1, r_ot_base), // T1 = & OrderingTable[OTZ] load_word( R_AT, R_T1, O_(PolyTag,code)), // AT = old_ot_head diff --git a/code/duffle/gte.atom.c b/code/duffle/gte.atom.c index a65dc98..cb007ce 100644 --- a/code/duffle/gte.atom.c +++ b/code/duffle/gte.atom.c @@ -11,7 +11,7 @@ ATOM_FILE_DEBUGGER_LINE_MARKER(gte_atom_c); #pragma region MACs (Mips Atom Components) /* Words: 3; Loads 3 S2 indices from the face array */ -FI_ Slice_MipsCode ac_load_tri_indices(U4 r_face_cusor, U4 r_i0, U4 r_i1, U4 r_i2) atom_dbg_skip MipsAtomComp_Proc_(ac_load_tri_indices, { +FI_ Slice_MipsCode ac_load_tri_indices(MipsAtomBuilder_R ab, U4 r_face_cusor, U4 r_i0, U4 r_i1, U4 r_i2) atom_dbg_skip MipsAtomComp_Proc_(ac_load_tri_indices, ab, { load_half_u(r_i0, r_face_cusor, 0 * S_(S2)), load_half_u(r_i1, r_face_cusor, 1 * S_(S2)), load_half_u(r_i2, r_face_cusor, 2 * S_(S2)), @@ -19,14 +19,14 @@ FI_ Slice_MipsCode ac_load_tri_indices(U4 r_face_cusor, U4 r_i0, U4 r_i1, U4 r_i /* Words: 3; Stores the 3 transformed (V2_S2 screen) vertices to the F3. * PIPELINE: post-RTPT (SXY0=v0.screen, SXY1=v1.screen, SXY2=v2.screen). */ -FI_ Slice_MipsCode ac_gte_store_f3(U4 r_primitive_cursor) atom_dbg_skip MipsAtomComp_Proc_(ac_gte_store_f3, { +FI_ Slice_MipsCode ac_gte_store_f3(MipsAtomBuilder_R ab, U4 r_primitive_cursor) atom_dbg_skip MipsAtomComp_Proc_(ac_gte_store_f3, ab, { gte_sw(C2_SXY0, r_primitive_cursor, O_(Poly_F3,p0)), gte_sw(C2_SXY1, r_primitive_cursor, O_(Poly_F3,p1)), gte_sw(C2_SXY2, r_primitive_cursor, O_(Poly_F3,p2)), }) /* Words: 18; Translates indices to vertex addresses and pushes them to GTE */ -I_ Slice_MipsCode ac_gte_load_tri_verts(U4 r_vert_base, U4 r_v0, U4 r_v1, U4 r_v2) atom_dbg_skip MipsAtomComp_Proc_(ac_gte_load_tri_verts, { +I_ Slice_MipsCode ac_gte_load_tri_verts(MipsAtomBuilder_R ab, U4 r_vert_base, U4 r_v0, U4 r_v1, U4 r_v2) atom_dbg_skip MipsAtomComp_Proc_(ac_gte_load_tri_verts, ab, { shift_lleft(R_AT, r_v0, v3s2_byteoff), add_u_self(R_AT, r_vert_base), load_word(R_V0, R_AT, O_(V3_S2,x)), load_word(R_V1, R_AT, O_(V3_S2,z)), gte_mv_to_data_r(R_V0, C2_VXY0), gte_mv_to_data_r(R_V1, C2_VZ0), shift_lleft(R_AT, r_v1, v3s2_byteoff), add_u_self(R_AT, r_vert_base), load_word(R_V0, R_AT, O_(V3_S2,x)), load_word(R_V1, R_AT, O_(V3_S2,z)), gte_mv_to_data_r(R_V0, C2_VXY1), gte_mv_to_data_r(R_V1, C2_VZ1), shift_lleft(R_AT, r_v2, v3s2_byteoff), add_u_self(R_AT, r_vert_base), load_word(R_V0, R_AT, O_(V3_S2,x)), load_word(R_V1, R_AT, O_(V3_S2,z)), gte_mv_to_data_r(R_V0, C2_VXY2), gte_mv_to_data_r(R_V1, C2_VZ2), @@ -34,10 +34,10 @@ I_ Slice_MipsCode ac_gte_load_tri_verts(U4 r_vert_base, U4 r_v0, U4 r_v1, U4 r_v /* Words: 3; Stores the 3 transformed (V2_S2 screen) vertices of the * G4 triangle portion to p0/p1/p2. - * PIPELINE: post-RTPT, pre-RTPS (SXY0=v0.screen, SXY1=v1.screen, SXY2=v2.screen). + * PIPELINE: post-RTPT, pre-RTPS (SXY0=v0.screen, SXY1=v1.screen, SXY2=v2.screen). * MUST be called BEFORE V3-RTPS, otherwise SXY0/1/2 get overwritten with v3 * (RTPS writes only to SXY2, but to keep the three registers aligned with v0/v1/v2 you must store before RTPS). */ -FI_ Slice_MipsCode ac_gte_store_g4_p012(U4 r_primitive_cursor) atom_dbg_skip MipsAtomComp_Proc_(ac_gte_store_g4_p012, { +FI_ Slice_MipsCode ac_gte_store_g4_p012(MipsAtomBuilder_R ab, U4 r_primitive_cursor) atom_dbg_skip MipsAtomComp_Proc_(ac_gte_store_g4_p012, ab, { gte_sw(C2_SXY0, r_primitive_cursor, O_(Poly_G4,p0)), gte_sw(C2_SXY1, r_primitive_cursor, O_(Poly_G4,p1)), gte_sw(C2_SXY2, r_primitive_cursor, O_(Poly_G4,p2)), @@ -47,13 +47,13 @@ FI_ Slice_MipsCode ac_gte_store_g4_p012(U4 r_primitive_cursor) atom_dbg_skip Mip * PIPELINE: post-RTPS (SXY2 holds v3.screen because RTPS writes its single-vertex result to SXY2; * SXY0 still holds v0.screen from the earlier RTPT. */ -FI_ Slice_MipsCode ac_gte_store_g4_p3(U4 r_primitive_cursor) atom_dbg_skip MipsAtomComp_Proc_(ac_gte_store_g4_p3, { gte_sw(C2_SXY2, r_primitive_cursor, O_(Poly_G4,p3)) }) +FI_ Slice_MipsCode ac_gte_store_g4_p3(MipsAtomBuilder_R ab, U4 r_primitive_cursor) atom_dbg_skip MipsAtomComp_Proc_(ac_gte_store_g4_p3, ab, { gte_sw(C2_SXY2, r_primitive_cursor, O_(Poly_G4,p3)) }) /* ─── STAGE 1 of normalize: SQR + mfc2 MAC1/2/3 ─── * Emits squared magnitude per component (in MAC1/2/3) into caller-provided scratch regs. * Stage 2 of normalize consumes these directly. * Words: 8. Clobbers: IR1/2/3, MAC1/2/3. Uses gte_cmdw_sqr (sf=0, lm=1). */ -FI_ Slice_MipsCode ac_gte_sqr_v3(U4 r_sx, U4 r_sy, U4 r_sz, U4 r_sq_x, U4 r_sq_y, U4 r_sq_z) atom_dbg_skip MipsAtomComp_Proc_(ac_gte_sqr_v3, { +FI_ Slice_MipsCode ac_gte_sqr_v3(MipsAtomBuilder_R ab, U4 r_sx, U4 r_sy, U4 r_sz, U4 r_sq_x, U4 r_sq_y, U4 r_sq_z) atom_dbg_skip MipsAtomComp_Proc_(ac_gte_sqr_v3, ab, { gte_mv_to_data_r(r_sx, C2_IR1), gte_mv_to_data_r(r_sy, C2_IR2), gte_mv_to_data_r(r_sz, C2_IR3), @@ -68,7 +68,7 @@ FI_ Slice_MipsCode ac_gte_sqr_v3(U4 r_sx, U4 r_sy, U4 r_sz, U4 r_sq_x, U4 r_sq_y * (typically (31 - LZCR)/2), multiplies IR0*IR[i] via GPF and shifts right to produce the normalized output. * Used standalone for "scale vector by scalar". * Words: 11. Clobbers: IR0..3, MAC1..3. Uses gte_cmdw_gpf (sf=0, lm=0). */ -FI_ Slice_MipsCode ac_gte_gpf_scale(U4 r_sx, U4 r_sy, U4 r_sz, U4 r_recip_est, U4 r_shift, U4 r_dx, U4 r_dy, U4 r_dz) atom_dbg_skip MipsAtomComp_Proc_(ac_gte_gpf_scale, { +FI_ Slice_MipsCode ac_gte_gpf_scale(MipsAtomBuilder_R ab, U4 r_sx, U4 r_sy, U4 r_sz, U4 r_recip_est, U4 r_shift, U4 r_dx, U4 r_dy, U4 r_dz) atom_dbg_skip MipsAtomComp_Proc_(ac_gte_gpf_scale, ab, { gte_mv_to_data_r(r_recip_est, C2_IR0), gte_mv_to_data_r(r_sx, C2_IR1), gte_mv_to_data_r(r_sy, C2_IR2), @@ -97,8 +97,7 @@ FI_ Slice_MipsCode ac_gte_gpf_scale(U4 r_sx, U4 r_sy, U4 r_sz, U4 r_recip_est, U * Octave 1 (entries 48- 95): mantissa in [0x10000, 0x20000) output ~[0.707, 0.500] * Octave 2 (entries 96-143): mantissa in [0x20000, 0x40000) output ~[0.500, 0.354] * Octave 3 (entries144-191): mantissa in [0x40000, 0x80000) output ~[0.354, 0.251] - * Within each octave, 8 sub-entries interpolate over the 8 fractional bits of the - * mantissa (the byte `(0x80 | (i mod 8))` for the lower-byte of the aligned value). + * Within each octave, 8 sub-entries interpolate over the 8 fractional bits of the mantissa (the byte `(0x80 | (i mod 8))` for the lower-byte of the aligned value). * Sampling the first value of each octave: * [0] 0x1000 = 1.0000 ; 1 / sqrt(1.0000) * [48] 0x0e4f = 0.8940 ; 1 / sqrt(1.2500) @@ -177,32 +176,45 @@ internal S2 const gte_normalize_sqr_tbl[192] align_(2) = { * Pipeline: clobbers IR0..3, MAC1..3, LZCS, LZCR. * Words: ~35 (pending re-gen; matches libgte 0x800160a0..0x8001615c at +/- 0-2 words for BD-slot reshuffling). * Sqrtbl: hardcoded to 0x800185B4 (libgte msc02.rel.data). Note: swapped to local. */ -I_ Slice_MipsCode ac_normalize_v3s4(U4 r_sx, U4 r_sy, U4 r_sz, U4 r_sq_y, U4 r_sq_z, U4 r_recip_est, U4 r_lzcr, U4 r_shift, U4 r_tmp) -atom_dbg_skip MipsAtomComp_Proc_(ac_normalize_v3s4, { - /* 9-arg signature — must be on one line so the metaprogram captures the full arg list. - * r_sx, r_sy, r_sz : in/out — src components, overwritten with normalized - * r_sq_y, r_sq_z : scratch — MAC2, MAC3 → die after stage 2 accumulate (r_sq_y may alias r_lzcr post-stage-2) - * r_recip_est : ≡ r_sqmag — multi-purpose (|v|² → shift-input → sqrtbl entry) - * r_lzcr : LZCR value (alive across stage 3 srav path) - * r_shift : (31 - LZCR & ~1) / 2 — final srav amount (stages 3-4) - * r_tmp : scratch — shift count, branch target, lookup addr, table base - * - * GPR ccount peak: 9. - * Pipeline: clobbers IR0..3, MAC1..3, LZCS, LZCR. - * Words: ~35 (pending re-gen; matches libgte 0x800160a0..0x8001615c at +/- 0-2 words). - * - * Sqrtbl address: link-time constant `>e_normalize_sqrtbl`, split via >>16 and &0xFFFF. */ - // ─── Stage 1: mtc2 src → IR1/2/3, SQR fires (MAC1/2/3 = IR², IR ← MAC saturated) ─── - // Componentized equivalent: mac_gte_sqr_v3(r_sx, r_sy, r_sz, r_sq_x, r_sq_y, r_sq_z). - // We inline for GPR-pressure reasons (see file-level comment). +/* ─── Binds_NormalizeV3S4 — declared here so the MipsAtom_Proc_ body can reference + * O_(Binds_NormalizeV3S4,*). Inlined at the proc-call site; not exposed in gen/macs.h. */ +typedef Struct_(Binds_NormalizeV3S4) { + U4 src; /* V3_S4* (scratch address — read from tape) */ + U4 dst; /* V3_S4* (scratch address — write to tape) */ +}; + +/* NOTE: The bundle-specific scratchpad offset schema was intentionally kept out of this file. + * gte.atom.c is the GENERIC GTE primitives file — it exposes only the parameter-style normalize_v3s4_proc for any future caller. */ +I_ void normalize_v3s4_proc( + MipsAtomBuilder_R ab + , U4 r_src /* GPR code: scratch base carrier (wave-context, e.g., R_T4) */ + , U4 r_dst /* GPR code: scratch dst pointer carrier (wave-context, e.g., R_T5) */ + , U4 r_sx, U4 r_sy, U4 r_sz /* GPR codes: src.x/y/z scratch (atom-local) */ + , U4 r_sq_y, U4 r_sq_z /* GPR codes: MAC1/2 scratch (atom-local) */ + , U4 r_recip_est /* GPR code: |v|² sum + shift-input + sqrtbl[index] (atom-local) */ + , U4 r_lzcr /* GPR code: LZCR value (atom-local) */ + , U4 r_shift /* GPR code: final srav amount (atom-local) */ + , U4 r_tmp /* GPR code: scratch (shift count, branch target, lookup addr, table base) */ +) +/* MipsAtom_Proc_ wrapper: declares the static MipsCode[] body, then calls atombuilder_unroll(ab, ...) to copy the encoded instructions into the caller's MipsAtomBuilder arena. */ +MipsAtom_Proc_(normalize_v3s4, ab, { + /* ── I/O wrapper (~10 words: 3 bind-pop + 3 src-load + 1 nop + 3 dst-store) ─── */ + load_word(r_src, R_TapePtr, O_(Binds_NormalizeV3S4,src)), /* pop src ptr (scratch addr) */ + load_word(r_dst, R_TapePtr, O_(Binds_NormalizeV3S4,dst)), /* pop dst ptr (scratch addr) */ + add_ui_self( R_TapePtr, S_(Binds_NormalizeV3S4)), + load_word(r_sx, r_src, O_(V3_S4,x)), + load_word(r_sy, r_src, O_(V3_S4,y)), + load_word(r_sz, r_src, O_(V3_S4,z)), + nop, /* load-delay */ + + /* ── 48-word normalize body (preserved verbatim from ac_normalize_v3s4) ─────── */ + // Stage 1: mtc2 src → IR1/2/3, SQR fires (MAC1/2/3 = IR², IR ← MAC saturated) gte_mv_to_data_r(r_sx, C2_IR1), gte_mv_to_data_r(r_sy, C2_IR2), gte_mv_to_data_r(r_sz, C2_IR3), nop, gte_cmdw_sqr, - - // ─── Stage 2: mfc2 MAC1/2/3, sum, mtc2 LZCS ─── - // Note: r_recip_est first used as the sum accumulator (= |v|²), which is also what LZCS needs. + // Stage 2: mfc2 MAC1/2/3, sum, mtc2 LZCS gte_mv_from_data_r(r_sq_y, C2_MAC1), /* r_sq_y = MAC1 = sx² */ gte_mv_from_data_r(r_sq_z, C2_MAC2), /* r_sq_z = MAC2 = sy² */ gte_mv_from_data_r(r_recip_est, C2_MAC3), /* r_recip_est = MAC3 = sz² */ @@ -213,11 +225,7 @@ atom_dbg_skip MipsAtomComp_Proc_(ac_normalize_v3s4, { nop2, gte_mv_from_data_r(r_lzcr, C2_LZCR), /* r_lzcr = LZCR (count of leading bits) */ nop, /* MFC2→GPR load delay (1 slot) */ - - // ─── Stage 3: compute shift amount, align |v|² to bit 24, lookup 1/|v| ─── - // Matches libgte `bltz +0x10 ; nop ; b +0x14 ; sllv t4,v0,t3` pattern: - // - bltz TAKEN → nop (BD), jump to srav_path; sllv SKIPPED - // - bltz !TAKEN → nop (BD), b +0x14 jumps to aligned_done; sllv (BD of b) executes + // Stage 3: compute shift amount, align |v|² to bit 24, lookup 1/|v| and_i( r_lzcr, r_lzcr, -2), /* r_lzcr &= ~1 (force even for halving) */ li_s( r_shift, 31), /* r_shift = 31 */ sub_s( r_shift, r_shift, r_lzcr), /* r_shift = 31 - LZCR */ @@ -226,7 +234,7 @@ atom_dbg_skip MipsAtomComp_Proc_(ac_normalize_v3s4, { branch_lt_zero(r_tmp, atom_offset(srav_path, aligned_done)), nop, jump_rel( atom_offset(aligned_done, srav_path)), shift_lleft_var(r_recip_est, r_recip_est, r_tmp), /* BD-slot of branch_equal: r_recip_est = |v|² << (LZCR - 24) */ - atom_label(srav_path) /* SRAV path: |v|² is small (top bit < bit 24) */ +atom_label(srav_path) /* SRAV path: |v|² is small (top bit < bit 24) */ li_s( r_tmp, 24), sub_s( r_tmp, r_tmp, r_lzcr), /* r_tmp = 24 - LZCR */ shift_aright_var(r_recip_est, r_recip_est, r_tmp), /* r_recip_est = |v|² >> (24 - LZCR) */ @@ -240,9 +248,7 @@ atom_label(aligned_done) /* Both paths converge h add_u( r_tmp, r_tmp, r_recip_est), /* r_tmp = sqrtbl base + byte offset (matches libgte 0x80016118: addu t5,t5,t4) */ load_half( r_recip_est, r_tmp, 0), /* r_recip_est = sqrtbl[r_recip_est] = 1/|v| estimate */ nop, /* retire load_half before MTC2 (matches libgte 0x80016120: nop) */ - - // ─── Stage 4: mtc2 IR0..3, GPF (MAC = IR0*IR), mfc2 MAC, srav finalize ─── - // Componentized equivalent: mac_gte_gpf_scale. + // Stage 4: mtc2 IR0..3, GPF (MAC = IR0*IR), mfc2 MAC, srav finalize gte_mv_to_data_r(r_recip_est, C2_IR0), /* IR0 = 1/|v| estimate */ gte_mv_to_data_r(r_sx, C2_IR1), /* IR1 = src.x */ gte_mv_to_data_r(r_sy, C2_IR2), /* IR2 = src.y */ @@ -255,6 +261,14 @@ atom_label(aligned_done) /* Both paths converge h shift_aright_var(r_sx, r_sx, r_shift), shift_aright_var(r_sy, r_sy, r_shift), shift_aright_var(r_sz, r_sz, r_shift), + + /* ── I/O wrapper tail (~3 words) ───────────────────────────────────────────── */ + store_word(r_sx, r_dst, O_(V3_S4,x)), + store_word(r_sy, r_dst, O_(V3_S4,y)), + store_word(r_sz, r_dst, O_(V3_S4,z)), + + /* ── atom_reads(R_TapePtr) atom_writes(R_TapePtr) ────────────────────────── */ + mac_yield() }) #pragma endregion MACs (Mips Atom Components) diff --git a/code/duffle/lottes_tape.h b/code/duffle/lottes_tape.h index 8953c42..b01a416 100644 --- a/code/duffle/lottes_tape.h +++ b/code/duffle/lottes_tape.h @@ -118,25 +118,20 @@ typedef U4 const MipsAtom; // Underlying type to an array of mips asm words that // MipsCode ac_X[] align_(4) = { body }; #define MipsAtomComp_(sym) MipsCode sym [] align_(4) = -// Used for components with value-args (e.g., ac_format_f3_color). -// FI_ Slice_MipsCode ac_X(args) MipsAtomComp_Proc_(ac_X, { body }) +// Used for components with value-args (mandatory `ab` (atom-builder) arg). +// FI_ void ac_X(MipsAtomBuilder_R ab, args) MipsAtomComp_Proc_(ac_X, ab, { body }) // expands to: -// FI_ Slice_MipsCode ac_X(args) { MipsCode ac_X[] align_(4) = { body }; return slice_from_array(MipsCode, ac_X); } -#define MipsAtomComp_Proc_(sym, ...) { MipsCode sym [] align_(4) = __VA_ARGS__; return slice_from_array(MipsCode, sym); } - -// Used for components with value-args (e.g., ac_format_f3_color). -// FI_ Slice_MipsCode ac_X(args) MipsAtomComp_Proc_(ac_X, { body }) -// expands to: -// FI_ Slice_MipsCode ac_X(args) { MipsCode ac_X[] align_(4) = { body }; return slice_from_array(MipsCode, ac_X); } -// #define MipsAtomComp_Proc_(sym, abuilder, ...) { MipsCode sym [] align_(4) = __VA_ARGS__; atombuilder_unroll(abuilder, slice_from_array(MipsCode, sym)); } +// FI_ void ac_X(MipsAtomBuilder_R ab, args) { +// MipsCode ac_X[] align_(4) = { body }; +// atombuilder_unroll(ab, slice_from_array(MipsCode, ac_X)); +// } +// The body must NOT include mac_yield() (the parent atom yields). +// Inline-only callers (the generated `mac_` aliases) skip this arg via metaprogram filtering; +// escape callers (ac_ invoked as a function) pass a long-lived builder. +#define MipsAtomComp_Proc_(sym, ab, ...) { MipsCode sym [] align_(4) = __VA_ARGS__; atombuilder_unroll(ab, slice_from_array(MipsCode, sym)); } /* Line-table anchor: gcc only adds a file to the .debug_line file table when the contains line-numbered content. - Files containing only: - - `MipsAtomComp_` static-array declarations, or - - `MipsAtomComp_Proc_` (force-inline) function bodies whose line info gets - attributed to the call site at the include point are otherwise omitted from the file table, - which breaks the DWARF injection when it tries to resolve atom-component provenance paths. - + Files containing only atoms and atom components. Place `ATOM_FILE_LINE_MARKER();` once at file scope in any `.atom.c` that defines atoms. The macro expands to a file-scope `internal U4 const` declaration keeps the file in the line table. The constant is in `.rodata` and unreferenced; the linker may eliminate it. @@ -234,7 +229,6 @@ atom_dbg_skip MipsAtomComp_(ac_yield_tail) { add_ui_self(R_TapePtr, S_(MipsCode)), jump_reg( R_AtomJmp), nop, }; - #pragma endregion Macro Atom Components #pragma region Mips Atom Builder @@ -249,45 +243,29 @@ typedef Relative_(FArena) Struct_(MipsAtomBuilder) { U4 start; U4 capacity; U4 u FI_ void atombuilder_unroll(MipsAtomBuilder_R ab, Slice_MipsCode code) { assert(ab->capacity - ab->used - code.len); - mem_copy(ab->start, u4_(code.ptr), code.len); + U4* dest = (U4*)ab->start + ab->used; /* write at next-available slot (arena accumulation) */ + mem_copy(u4_(dest), u4_(code.ptr), code.len); mem_bump(ab->start, ab->capacity, & ab->used, code.len); } #define atombuilder_unroll_mac(ab, mac) atombuilder_unroll(ab, slice_arg_from_array(Slice_MipsCode, mac)) // When done authoring, utilize this to cap-off the atom (if not utilizing a MipsAtom_Proc). FI_ void atombuilder_end(MipsAtomBuilder_R ab) { - mem_copy(ab->start, u4_(ac_yield), S_(ac_yield)); + U4* dest = (U4*)ab->start + ab->used; /* write at next-available slot */ + mem_copy(u4_(dest), u4_(ac_yield), S_(ac_yield)); mem_bump(ab->start, ab->capacity, & ab->used, S_(ac_yield)); } #define mipsatom_from_builder(ab) C_(MipsAtom*, (ab).start) + +// tb_emit_builder(tb, ab) — emit the builder's atom into the tape and advance tb->used. +// Thin wrapper around tb_emit(tb, mipsatom_from_builder(ab[0])). +// Equivalent to tb_emit(tb, code_) for runtime-built atoms. +FI_ void tb_emit_builder(TapeBuilder_R tb, MipsAtomBuilder_R ab) { tb_emit(tb, mipsatom_from_builder(ab[0])); } #pragma endregion Mips Atom Builder #pragma region Mips Atom Procs -#if 0 -typedef Struct_(Binds_SyncPrimitiveArena) { U4 used; U4 cursor; }; -FI_ void sync_prim_arean_proc_demo(MipsAtomBuilder_R ab, U4 r_extra, U4 add_amnt_extra) -MipsAtom_Proc_(sync_primitive_arena_proc_demo, ab, atom_info(atom_bind(Binds_SyncPrimitiveArena) - , atom_reads( R_TapePtr, R_PrimCursor) - , atom_writes(R_TapePtr) -){ - load_word(R_AT, R_TapePtr, O_(Binds_SyncPrimitiveArena,used)), - load_word(R_T0, R_TapePtr, O_(Binds_SyncPrimitiveArena,cursor)), - add_ui_self( R_TapePtr, S_(Binds_SyncPrimitiveArena)), - /* Calculate byte offset and store directly back to RAM */ - sub_u( R_T0, R_PrimCursor, R_T0), // R_T0 = R_PrimCursor - binds.cursor - store_word(R_T0, R_AT, 0), // R_AT[0] = R_T0 - add_ui_self(r_extra, add_amnt_extra), // extra op for demonstration purposes. - mac_yield() -}) - -void demo_make_make_and_emit_atom(TapeBuilder* tb, MipsAtomBuilder* ab){ - sync_prim_arean_proc_demo(ab, R_T4, 4); - tb_emit(tb, mipsatom_from_builder(ab[0])); -} -#endif - #pragma endregion Mips Atom Procs #pragma region Baked Mips Atoms diff --git a/code/duffle/math.atom.c b/code/duffle/math.atom.c index 68ee017..6c0c4ea 100644 --- a/code/duffle/math.atom.c +++ b/code/duffle/math.atom.c @@ -9,35 +9,35 @@ ATOM_FILE_DEBUGGER_LINE_MARKER(math_atom_c); #pragma region MACs (Mips Atom Component) -FI_ Slice_MipsCode ac_load_v2s2(U4 rs_x, U4 rs_y, U4 r_base, U4 offset) atom_dbg_skip MipsAtomComp_Proc_(ac_load_v2s2, { +FI_ Slice_MipsCode ac_load_v2s2(MipsAtomBuilder_R ab, U4 rs_x, U4 rs_y, U4 r_base, U4 offset) atom_dbg_skip MipsAtomComp_Proc_(ac_load_v2s2, ab, { load_half( rs_x, r_base, O_(V3_S2,x)), load_half( rs_y, r_base, O_(V3_S2,y)), }) -FI_ Slice_MipsCode ac_store_v2s2(U4 rt_x, U4 rt_y, U4 base, U4 offset) atom_dbg_skip MipsAtomComp_Proc_(ac_store_v2s2, { +FI_ Slice_MipsCode ac_store_v2s2(MipsAtomBuilder_R ab, U4 rt_x, U4 rt_y, U4 base, U4 offset) atom_dbg_skip MipsAtomComp_Proc_(ac_store_v2s2, ab, { store_half(rt_x, base, offset + O_(V2_S2,x)), store_half(rt_y, base, offset + O_(V2_S2,y)), }) -FI_ Slice_MipsCode ac_load_v3s4(U4 rs_x, U4 rs_y, U4 rs_z, U4 r_base, U4 offset) atom_dbg_skip MipsAtomComp_Proc_(ac_load_v3s4, { +FI_ Slice_MipsCode ac_load_v3s4(MipsAtomBuilder_R ab, U4 rs_x, U4 rs_y, U4 rs_z, U4 r_base, U4 offset) atom_dbg_skip MipsAtomComp_Proc_(ac_load_v3s4, ab, { load_word( rs_x, r_base, O_(V3_S4,x)), load_word( rs_y, r_base, O_(V3_S4,y)), load_word( rs_z, r_base, O_(V3_S4,z)), }) -FI_ Slice_MipsCode ac_store_v3s4(U4 rt_x, U4 rt_y, U4 rt_z, U4 base, U4 offset) atom_dbg_skip MipsAtomComp_Proc_(ac_store_v3s4, { +FI_ Slice_MipsCode ac_store_v3s4(MipsAtomBuilder_R ab, U4 rt_x, U4 rt_y, U4 rt_z, U4 base, U4 offset) atom_dbg_skip MipsAtomComp_Proc_(ac_store_v3s4, ab, { store_word(rt_x, base, offset + O_(V3_S4,x)), store_word(rt_y, base, offset + O_(V3_S4,y)), store_word(rt_z, base, offset + O_(V3_S4,z)), }) -FI_ Slice_MipsCode ac_sub_v3s4(U4 rds_x, U4 rds_y, U4 rds_z, U4 rt_x, U4 rt_y, U4 rt_z) atom_dbg_skip MipsAtomComp_Proc_(ac_sub_v3s4, { +FI_ Slice_MipsCode ac_sub_v3s4(MipsAtomBuilder_R ab, U4 rds_x, U4 rds_y, U4 rds_z, U4 rt_x, U4 rt_y, U4 rt_z) atom_dbg_skip MipsAtomComp_Proc_(ac_sub_v3s4, ab, { sub_s(rds_x, rds_x, rt_x), sub_s(rds_y, rds_y, rt_y), sub_s(rds_z, rds_z, rt_z), }) -FI_ Slice_MipsCode ac_store_rects2(U4 rt_x, U4 rt_y, U4 rt_width, U4 rt_height, U4 base, U4 offset) atom_dbg_skip MipsAtomComp_Proc_(ac_store_rects2, { +FI_ Slice_MipsCode ac_store_rects2(MipsAtomBuilder_R ab, U4 rt_x, U4 rt_y, U4 rt_width, U4 rt_height, U4 base, U4 offset) atom_dbg_skip MipsAtomComp_Proc_(ac_store_rects2, ab, { store_half(rt_x, base, offset + O_(Rect_S2,x)), store_half(rt_y, base, offset + O_(Rect_S2,y)), store_half(rt_width, base, offset + O_(Rect_S2,width)), diff --git a/code/duffle/pad.atom.c b/code/duffle/pad.atom.c index e698eb3..4167273 100644 --- a/code/duffle/pad.atom.c +++ b/code/duffle/pad.atom.c @@ -11,18 +11,18 @@ ATOM_FILE_DEBUGGER_LINE_MARKER(pad_atom_c); #pragma region MACs (Mips Atom Components) -FI_ Slice_MipsCode ac_pad_set_centered_axes(U4 r_state, U4 r_scratch) atom_dbg_skip MipsAtomComp_Proc_(ac_pad_set_centered_axes, { +FI_ Slice_MipsCode ac_pad_set_centered_axes(MipsAtomBuilder_R ab, U4 r_state, U4 r_scratch) atom_dbg_skip MipsAtomComp_Proc_(ac_pad_set_centered_axes, ab, { load_upper_i(r_scratch, (PadAxis_Centered_Word >> 16) & 0xFFFF), or_i_self( r_scratch, PadAxis_Centered_Word & 0xFFFF), store_word( r_scratch, r_state, O_(PadState,axes)), }) -FI_ Slice_MipsCode ac_pad_set_id_byte(U1 r_state, U1 r_id, U1 id_value) atom_dbg_skip MipsAtomComp_Proc_(ac_pad_set_id_byte, { +FI_ Slice_MipsCode ac_pad_set_id_byte(MipsAtomBuilder_R ab, U1 r_state, U1 r_id, U1 id_value) atom_dbg_skip MipsAtomComp_Proc_(ac_pad_set_id_byte, ab, { add_ui( r_id, R_0, id_value), store_byte(r_id, r_state, O_(PadState,id)), }) -FI_ Slice_MipsCode ac_pad_set_status(U4 r_tmp, U1 r_state, U4 pad_status) atom_dbg_skip MipsAtomComp_Proc_(ac_pad_set_status, { +FI_ Slice_MipsCode ac_pad_set_status(MipsAtomBuilder_R ab, U4 r_tmp, U1 r_state, U4 pad_status) atom_dbg_skip MipsAtomComp_Proc_(ac_pad_set_status, ab, { add_ui( r_tmp, R_0, pad_status), store_word(r_tmp, r_state, O_(PadState,status)), }) @@ -30,7 +30,7 @@ FI_ Slice_MipsCode ac_pad_set_status(U4 r_tmp, U1 r_state, U4 pad_status) atom_d /* Invert r_buttons (active-low → active-high) and store to PadState.buttons. * r_buttons must already be loaded (the caller is responsible for filling the load-delay slot of * the preceding load_half_u with an instruction that doesn't read r_buttons). */ -FI_ Slice_MipsCode ac_pad_store_inverted_buttons(U1 r_buttons, U1 r_pad_state) atom_dbg_skip MipsAtomComp_Proc_(ac_pad_store_inverted_buttons, { +FI_ Slice_MipsCode ac_pad_store_inverted_buttons(MipsAtomBuilder_R ab, U1 r_buttons, U1 r_pad_state) atom_dbg_skip MipsAtomComp_Proc_(ac_pad_store_inverted_buttons, ab, { nor_u( r_buttons, r_buttons, R_0), store_half( r_buttons, r_pad_state, O_(PadState, buttons)), }) @@ -93,7 +93,7 @@ atom_label(disconnected) /* === Disconnected body. */ mac_pad_set_status(R_T4, R_PadState, PadStatus_Disconnected), store_half( R_0, R_PadState, O_(PadState,buttons)), mac_pad_set_centered_axes(R_PadState, R_T4), - mac_pad_set_id_byte( R_PadState, R_RawId, PadRawStatus_Timeout), + mac_pad_set_id_byte(R_PadState, R_RawId, PadRawStatus_Timeout), jump_rel(atom_offset(disconnected, snap_end)), /* BD-slot: load next atom's entry point (replaces the nop). * Always jumps to snap_end, where mac_yield_tail() transfers control to R_AtomJmp without re-loading it. */ @@ -111,7 +111,7 @@ atom_label(pending) /* === Pending body (status=0, id=0 — pre-IRQ-empty buffer store_half( R_0, R_PadState, O_(PadState,buttons)), mac_pad_set_centered_axes(R_PadState, R_T4), store_byte(R_RawId, R_PadState, O_(PadState,id)), - jump_rel(atom_offset(pending, snap_end)), + jump_rel(atom_offset(pending, snap_end)), mac_yield_load(), atom_label(id_dispatch) /* === Case 3-6: ID dispatch */ @@ -181,7 +181,7 @@ atom_label(try_unsupported) /* === Case 7: Unsupported — fall through from the store_word(R_T4, R_PadState, O_(PadState,status)), store_half(R_0, R_PadState, O_(PadState,buttons)), mac_pad_set_centered_axes(R_PadState, R_T4), - mac_pad_set_id_byte( R_PadState, R_RawId, PadUnknownId_Sentinel), + mac_pad_set_id_byte(R_PadState, R_RawId, PadUnknownId_Sentinel), /* Fall through to snap_end. */ atom_label(no_jump_fallthrough) diff --git a/code/duffle/pad.h b/code/duffle/pad.h index 87a9301..e530094 100644 --- a/code/duffle/pad.h +++ b/code/duffle/pad.h @@ -1,6 +1,7 @@ #ifdef INTELLISENSE_DIRECTIVES # pragma once # include "dsl.h" +# include "math.h" #endif /* PSX button bit positions — 1:1 with PSX-SPX docs at docs/psx-spx/docs/controllersandmemorycards.md:405-421. diff --git a/code/hello_camera/gen/macs.h b/code/hello_camera/gen/macs.h index d6e52b7..3f6e2a8 100644 --- a/code/hello_camera/gen/macs.h +++ b/code/hello_camera/gen/macs.h @@ -39,3 +39,350 @@ WORD_COUNT(mac_put_disp_env, 5) , mac_gcmd_push(gp0_word_nop(), reg_transfer, reg_base, port) WORD_COUNT(mac_put_draw_env, 16) +#define mac_resolve_look_at__input_and_sub(...) \ + load_word(r_target_ptr, R_TapePtr, O_(Binds_ResolveLookAtSub,target)) \ +, load_word(r_eye_ptr, R_TapePtr, O_(Binds_ResolveLookAtSub,eye)) \ +, load_word(r_up_in_ptr, R_TapePtr, O_(Binds_ResolveLookAtSub,up_in)) \ +, add_ui_self( R_TapePtr, S_(Binds_ResolveLookAtSub)) \ +, load_word(r_scratch, R_TapePtr, O_(Binds_ResolveLookAtScratch,scratch_base)) \ +, add_ui_self( R_TapePtr, S_(Binds_ResolveLookAtScratch)) /* Stage eye.x/y/z into the scratchpad (atom 6 reads these for the translation + * column). Reuse r_tmp0/r_tmp1/r_tmp2. Offsets via O_(ResolveLookAtScratch,*). */ \ +, load_word(r_tmp0, r_eye_ptr, O_(P3_S4,x)) \ +, load_word(r_tmp1, r_eye_ptr, O_(P3_S4,y)) \ +, load_word(r_tmp2, r_eye_ptr, O_(P3_S4,z)) \ +, nop /* load-delay */ \ +, store_word(r_tmp0, r_scratch, O_(ResolveLookAtScratch,eye.x)) \ +, store_word(r_tmp1, r_scratch, O_(ResolveLookAtScratch,eye.y)) \ +, store_word(r_tmp2, r_scratch, O_(ResolveLookAtScratch,eye.z)) /* Stage up_in.x/y/z into the scratchpad (atom 2 reads these for the outer + * product with uz). Reuse r_tmp0/r_tmp1/r_tmp2. */ \ +, load_word(r_tmp0, r_up_in_ptr, O_(V3_S4,x)) \ +, load_word(r_tmp1, r_up_in_ptr, O_(V3_S4,y)) \ +, load_word(r_tmp2, r_up_in_ptr, O_(V3_S4,z)) \ +, nop /* load-delay */ \ +, store_word(r_tmp0, r_scratch, O_(ResolveLookAtScratch,up_in.x)) \ +, store_word(r_tmp1, r_scratch, O_(ResolveLookAtScratch,up_in.y)) \ +, store_word(r_tmp2, r_scratch, O_(ResolveLookAtScratch,up_in.z)) /* Compute fwd = target - eye. */ \ +, load_word(r_tmp0, r_target_ptr, O_(P3_S4,x)) \ +, load_word(r_tmp1, r_target_ptr, O_(P3_S4,y)) \ +, load_word(r_tmp2, r_target_ptr, O_(P3_S4,z)) \ +, load_word(r_tmp3, r_eye_ptr, O_(P3_S4,x)) \ +, load_word(R_AT, r_eye_ptr, O_(P3_S4,y)) \ +, load_word(R_V0, r_eye_ptr, O_(P3_S4,z)) \ +, nop /* load-delay */ \ +, sub_u(r_tmp0, r_tmp0, r_tmp3) \ +, sub_u(r_tmp1, r_tmp1, R_AT) \ +, sub_u(r_tmp2, r_tmp2, R_V0) /* Store fwd.x/y/z (atom 1 reads these as the normalize src). */ \ +, store_word(r_tmp0, r_scratch, O_(ResolveLookAtScratch,fwd.x)) \ +, store_word(r_tmp1, r_scratch, O_(ResolveLookAtScratch,fwd.y)) \ +, store_word(r_tmp2, r_scratch, O_(ResolveLookAtScratch,fwd.z)) \ +, mac_yield() +WORD_COUNT(mac_resolve_look_at__input_and_sub, 34) + +#define mac_resolve_look_at__cross_uz_up_in_to_right(...) \ + add_si(r_g, r_scratch, O_(ResolveLookAtScratch,uz)) /* r_g = &uz */ \ +, add_si(r_h, r_scratch, O_(ResolveLookAtScratch,up_in)) /* r_h = &up_in */ \ +, add_si(r_f, r_scratch, O_(ResolveLookAtScratch,right)) /* r_f = &right (out) */ \ +, nop /* Load a (uz).x/y/z into r_a/r_b/r_c. */ \ +, load_word(r_a, r_g, O_(V3_S4,x)) \ +, load_word(r_b, r_g, O_(V3_S4,y)) \ +, load_word(r_c, r_g, O_(V3_S4,z)) \ +, nop /* Load b (up_in).x/y/z into r_d + R_AT/R_V0 (hardcoded; reusing the + * body's last two loads is fine because the load-delay slot is the nop + * after the third load, and mtc2 below doesn't read these regs). */ \ +, load_word(r_d, r_h, O_(V3_S4,x)) \ +, load_word(R_AT, r_h, O_(V3_S4,y)) \ +, load_word(R_V0, r_h, O_(V3_S4,z)) \ +, nop /* mtc2 a → IR1/2/3, b → D1/2/3 (VXY0/VZ0/VXY1). */ \ +, gte_mv_to_data_r(r_a, C2_IR1) \ +, gte_mv_to_data_r(r_b, C2_IR2) \ +, gte_mv_to_data_r(r_c, C2_IR3) \ +, gte_mv_to_data_r(r_d, C2_VXY0) /* D1 = b.x */ \ +, gte_mv_to_data_r(R_AT, C2_VZ0) /* D2 = b.y */ \ +, gte_mv_to_data_r(R_V0, C2_VXY1) /* D3 = b.z */ \ +, nop2 /* MTC2 retirement (CPU→COP2 2-slot delay) */ \ +, gte_cmdw_outer_product /* OP fires; MAC1/2/3 = a × b */ /* mfc2 MAC1/2/3 → r_a/r_b/r_c (out.x/y/z). */ \ +, gte_mv_from_data_r(r_a, C2_MAC1) \ +, gte_mv_from_data_r(r_b, C2_MAC2) \ +, gte_mv_from_data_r(r_c, C2_MAC3) \ +, nop /* MFC2 retirement */ /* Store out.x/y/z to r_f (out ptr = scratch+32). */ \ +, store_word(r_a, r_f, O_(V3_S4,x)) \ +, store_word(r_b, r_f, O_(V3_S4,y)) \ +, store_word(r_c, r_f, O_(V3_S4,z)) \ +, mac_yield() +WORD_COUNT(mac_resolve_look_at__cross_uz_up_in_to_right, 29) + +#define mac_resolve_look_at__cross_uz_ux_to_up(...) \ + add_si(r_g, r_scratch, O_(ResolveLookAtScratch,uz)) /* r_g = &uz */ \ +, add_si(r_h, r_scratch, O_(ResolveLookAtScratch,ux)) /* r_h = &ux */ \ +, add_si(r_f, r_scratch, O_(ResolveLookAtScratch,up)) /* r_f = &up (out) */ \ +, nop /* Load a (uz).x/y/z into r_a/r_b/r_c. */ \ +, load_word(r_a, r_g, O_(V3_S4,x)) \ +, load_word(r_b, r_g, O_(V3_S4,y)) \ +, load_word(r_c, r_g, O_(V3_S4,z)) \ +, nop /* Load b (ux).x/y/z into r_d + R_AT/R_V0. */ \ +, load_word(r_d, r_h, O_(V3_S4,x)) \ +, load_word(R_AT, r_h, O_(V3_S4,y)) \ +, load_word(R_V0, r_h, O_(V3_S4,z)) \ +, nop /* mtc2 a → IR1/2/3, b → D1/2/3 (VXY0/VZ0/VXY1). */ \ +, gte_mv_to_data_r(r_a, C2_IR1) \ +, gte_mv_to_data_r(r_b, C2_IR2) \ +, gte_mv_to_data_r(r_c, C2_IR3) \ +, gte_mv_to_data_r(r_d, C2_VXY0) \ +, gte_mv_to_data_r(R_AT, C2_VZ0) \ +, gte_mv_to_data_r(R_V0, C2_VXY1) \ +, nop2 \ +, gte_cmdw_outer_product \ +, gte_mv_from_data_r(r_a, C2_MAC1) \ +, gte_mv_from_data_r(r_b, C2_MAC2) \ +, gte_mv_from_data_r(r_c, C2_MAC3) \ +, nop \ +, store_word(r_a, r_f, O_(V3_S4,x)) \ +, store_word(r_b, r_f, O_(V3_S4,y)) \ +, store_word(r_c, r_f, O_(V3_S4,z)) \ +, mac_yield() +WORD_COUNT(mac_resolve_look_at__cross_uz_ux_to_up, 29) + +#define mac_resolve_look_at__normalize_fwd_to_uz(...) \ + add_si(r_a, r_scratch, O_(ResolveLookAtScratch,fwd)) /* r_a = &fwd */ \ +, add_si(r_b, r_scratch, O_(ResolveLookAtScratch,uz)) /* r_b = &uz */ \ +, nop /* Load src.x/y/z from r_a into r_e/r_f/r_i. */ \ +, load_word(r_e, r_a, O_(V3_S4,x)) \ +, load_word(r_f, r_a, O_(V3_S4,y)) \ +, load_word(r_i, r_a, O_(V3_S4,z)) \ +, nop /* load-delay */ /* Stage 1: mtc2 src → IR1/2/3, SQR fires. */ \ +, gte_mv_to_data_r(r_e, C2_IR1) \ +, gte_mv_to_data_r(r_f, C2_IR2) \ +, gte_mv_to_data_r(r_i, C2_IR3) \ +, nop \ +, gte_cmdw_sqr /* Stage 2: mfc2 MAC1/2/3, sum, mtc2 LZCS. */ \ +, gte_mv_from_data_r(r_d, C2_MAC1) \ +, gte_mv_from_data_r(r_g, C2_MAC2) \ +, gte_mv_from_data_r(r_recip_est, C2_MAC3) \ +, nop \ +, add_u(r_recip_est, r_recip_est, r_g) \ +, add_u(r_recip_est, r_recip_est, r_d) \ +, gte_mv_to_data_r(r_recip_est, C2_LZCS) \ +, nop2 \ +, gte_mv_from_data_r(r_h, C2_LZCR) \ +, nop /* Stage 3: compute shift amount, align |v|² to bit 24. */ \ +, and_i( r_h, r_h, -2) \ +, li_s( r_shift, 31) \ +, sub_s( r_shift, r_shift, r_h) \ +, shift_aright(r_shift, r_shift, 1) \ +, add_si( r_a, r_h, -24) /* r_a = LZCR - 24 (overlapping with r_recip_est; src ptr no longer needed) */ \ +, branch_lt_zero(r_a, atom_offset(srav_path_fwd_to_uz, aligned_done_fwd_to_uz)) \ +, nop \ +, jump_rel(atom_offset(aligned_done_fwd_to_uz, srav_path_fwd_to_uz)) \ +, shift_lleft_var(r_recip_est, r_recip_est, r_a) \ +, atom_label(srav_path_fwd_to_uz) \ +, li_s( r_a, 24) \ +, sub_s( r_a, r_a, r_h) \ +, shift_aright_var(r_recip_est, r_recip_est, r_a) \ +, atom_label(aligned_done_fwd_to_uz) /* r_recip_est holds |v|² aligned to bit 24. */ \ +, add_si( r_recip_est, r_recip_est, -64) \ +, shift_lleft(r_recip_est, r_recip_est, 1) \ +, load_upper_i(r_a, u4_hi(& gte_normalize_sqr_tbl)) \ +, or_i_self(r_a, u4_lo(& gte_normalize_sqr_tbl)) \ +, add_u(r_a, r_a, r_recip_est) \ +, load_half(r_recip_est, r_a, 0) \ +, nop /* Stage 4: GPF + srav finalize. */ \ +, gte_mv_to_data_r(r_recip_est, C2_IR0) \ +, gte_mv_to_data_r(r_e, C2_IR1) \ +, gte_mv_to_data_r(r_f, C2_IR2) \ +, gte_mv_to_data_r(r_i, C2_IR3) \ +, nop2 \ +, gte_cmdw_gpf \ +, gte_mv_from_data_r(r_e, C2_MAC1) \ +, gte_mv_from_data_r(r_f, C2_MAC2) \ +, gte_mv_from_data_r(r_i, C2_MAC3) \ +, shift_aright_var(r_e, r_e, r_shift) \ +, shift_aright_var(r_f, r_f, r_shift) \ +, shift_aright_var(r_i, r_i, r_shift) /* Store result.x/y/z to r_b (dst ptr = scratch+16). */ \ +, store_word(r_e, r_b, O_(V3_S4,x)) \ +, store_word(r_f, r_b, O_(V3_S4,y)) \ +, store_word(r_i, r_b, O_(V3_S4,z)) \ +, mac_yield() +WORD_COUNT(mac_resolve_look_at__normalize_fwd_to_uz, 59) + +#define mac_resolve_look_at__normalize_right_to_ux(...) \ + add_si(r_a, r_scratch, O_(ResolveLookAtScratch,right)) /* r_a = &right */ \ +, add_si(r_b, r_scratch, O_(ResolveLookAtScratch,ux)) /* r_b = &ux */ \ +, nop \ +, load_word(r_e, r_a, O_(V3_S4,x)) \ +, load_word(r_f, r_a, O_(V3_S4,y)) \ +, load_word(r_i, r_a, O_(V3_S4,z)) \ +, nop \ +, gte_mv_to_data_r(r_e, C2_IR1) \ +, gte_mv_to_data_r(r_f, C2_IR2) \ +, gte_mv_to_data_r(r_i, C2_IR3) \ +, nop \ +, gte_cmdw_sqr \ +, gte_mv_from_data_r(r_d, C2_MAC1) \ +, gte_mv_from_data_r(r_g, C2_MAC2) \ +, gte_mv_from_data_r(r_recip_est, C2_MAC3) \ +, nop \ +, add_u(r_recip_est, r_recip_est, r_g) \ +, add_u(r_recip_est, r_recip_est, r_d) \ +, gte_mv_to_data_r(r_recip_est, C2_LZCS) \ +, nop2 \ +, gte_mv_from_data_r(r_h, C2_LZCR) \ +, nop \ +, and_i( r_h, r_h, -2) \ +, li_s( r_shift, 31) \ +, sub_s( r_shift, r_shift, r_h) \ +, shift_aright(r_shift, r_shift, 1) \ +, add_si( r_a, r_h, -24) \ +, branch_lt_zero(r_a, atom_offset(srav_path_right_to_ux, aligned_done_right_to_ux)) \ +, nop \ +, jump_rel(atom_offset(aligned_done_right_to_ux, srav_path_right_to_ux)) \ +, shift_lleft_var(r_recip_est, r_recip_est, r_a) \ +, atom_label(srav_path_right_to_ux) \ +, li_s( r_a, 24) \ +, sub_s( r_a, r_a, r_h) \ +, shift_aright_var(r_recip_est, r_recip_est, r_a) \ +, atom_label(aligned_done_right_to_ux) \ +, add_si( r_recip_est, r_recip_est, -64) \ +, shift_lleft(r_recip_est, r_recip_est, 1) \ +, load_upper_i(r_a, u4_hi(& gte_normalize_sqr_tbl)) \ +, or_i_self(r_a, u4_lo(& gte_normalize_sqr_tbl)) \ +, add_u(r_a, r_a, r_recip_est) \ +, load_half(r_recip_est, r_a, 0) \ +, nop \ +, gte_mv_to_data_r(r_recip_est, C2_IR0) \ +, gte_mv_to_data_r(r_e, C2_IR1) \ +, gte_mv_to_data_r(r_f, C2_IR2) \ +, gte_mv_to_data_r(r_i, C2_IR3) \ +, nop2 \ +, gte_cmdw_gpf \ +, gte_mv_from_data_r(r_e, C2_MAC1) \ +, gte_mv_from_data_r(r_f, C2_MAC2) \ +, gte_mv_from_data_r(r_i, C2_MAC3) \ +, shift_aright_var(r_e, r_e, r_shift) \ +, shift_aright_var(r_f, r_f, r_shift) \ +, shift_aright_var(r_i, r_i, r_shift) \ +, store_word(r_e, r_b, O_(V3_S4,x)) \ +, store_word(r_f, r_b, O_(V3_S4,y)) \ +, store_word(r_i, r_b, O_(V3_S4,z)) \ +, mac_yield() +WORD_COUNT(mac_resolve_look_at__normalize_right_to_ux, 59) + +#define mac_resolve_look_at__normalize_up_to_uy(...) \ + add_si(r_a, r_scratch, O_(ResolveLookAtScratch,up)) /* r_a = &up */ \ +, add_si(r_b, r_scratch, O_(ResolveLookAtScratch,uy)) /* r_b = &uy */ \ +, nop \ +, load_word(r_e, r_a, O_(V3_S4,x)) \ +, load_word(r_f, r_a, O_(V3_S4,y)) \ +, load_word(r_i, r_a, O_(V3_S4,z)) \ +, nop \ +, gte_mv_to_data_r(r_e, C2_IR1) \ +, gte_mv_to_data_r(r_f, C2_IR2) \ +, gte_mv_to_data_r(r_i, C2_IR3) \ +, nop \ +, gte_cmdw_sqr \ +, gte_mv_from_data_r(r_d, C2_MAC1) \ +, gte_mv_from_data_r(r_g, C2_MAC2) \ +, gte_mv_from_data_r(r_recip_est, C2_MAC3) \ +, nop \ +, add_u(r_recip_est, r_recip_est, r_g) \ +, add_u(r_recip_est, r_recip_est, r_d) \ +, gte_mv_to_data_r(r_recip_est, C2_LZCS) \ +, nop2 \ +, gte_mv_from_data_r(r_h, C2_LZCR) \ +, nop \ +, and_i( r_h, r_h, -2) \ +, li_s( r_shift, 31) \ +, sub_s( r_shift, r_shift, r_h) \ +, shift_aright(r_shift, r_shift, 1) \ +, add_si( r_a, r_h, -24) \ +, branch_lt_zero(r_a, atom_offset(srav_path_up_to_uy, aligned_done_up_to_uy)) \ +, nop \ +, jump_rel(atom_offset(aligned_done_up_to_uy, srav_path_up_to_uy)) \ +, shift_lleft_var(r_recip_est, r_recip_est, r_a) \ +, atom_label(srav_path_up_to_uy) \ +, li_s( r_a, 24) \ +, sub_s( r_a, r_a, r_h) \ +, shift_aright_var(r_recip_est, r_recip_est, r_a) \ +, atom_label(aligned_done_up_to_uy) \ +, add_si( r_recip_est, r_recip_est, -64) \ +, shift_lleft(r_recip_est, r_recip_est, 1) \ +, load_upper_i(r_a, u4_hi(& gte_normalize_sqr_tbl)) \ +, or_i_self(r_a, u4_lo(& gte_normalize_sqr_tbl)) \ +, add_u(r_a, r_a, r_recip_est) \ +, load_half(r_recip_est, r_a, 0) \ +, nop \ +, gte_mv_to_data_r(r_recip_est, C2_IR0) \ +, gte_mv_to_data_r(r_e, C2_IR1) \ +, gte_mv_to_data_r(r_f, C2_IR2) \ +, gte_mv_to_data_r(r_i, C2_IR3) \ +, nop2 \ +, gte_cmdw_gpf \ +, gte_mv_from_data_r(r_e, C2_MAC1) \ +, gte_mv_from_data_r(r_f, C2_MAC2) \ +, gte_mv_from_data_r(r_i, C2_MAC3) \ +, shift_aright_var(r_e, r_e, r_shift) \ +, shift_aright_var(r_f, r_f, r_shift) \ +, shift_aright_var(r_i, r_i, r_shift) \ +, store_word(r_e, r_b, O_(V3_S4,x)) \ +, store_word(r_f, r_b, O_(V3_S4,y)) \ +, store_word(r_i, r_b, O_(V3_S4,z)) \ +, mac_yield() +WORD_COUNT(mac_resolve_look_at__normalize_up_to_uy, 59) + +#define mac_resolve_look_at__populate_and_translate(...) \ + load_word(r_look_at, R_TapePtr, O_(Binds_ResolveLookAtPopAndTrans,look_at)) \ +, add_ui_self( R_TapePtr, S_(Binds_ResolveLookAtPopAndTrans)) /* Compute the 4 scratch pointers in their dedicated GPRs. */ \ +, add_si(r_pux, r_scratch, O_(ResolveLookAtScratch,ux)) /* r_pux = &ux */ \ +, add_si(r_puy, r_scratch, O_(ResolveLookAtScratch,uy)) /* r_puy = &uy */ \ +, add_si(r_puz, r_scratch, O_(ResolveLookAtScratch,uz)) /* r_puz = &uz */ \ +, add_si(r_peye, r_scratch, O_(ResolveLookAtScratch,eye)) /* r_peye = &eye */ \ +, nop /* ── m[0] = (S2)ux ── */ \ +, load_word(r_tmp0, r_pux, O_(V3_S4,x)) \ +, load_word(r_tmp1, r_pux, O_(V3_S4,y)) \ +, load_word(r_tmp2, r_pux, O_(V3_S4,z)) \ +, nop \ +, store_half(r_tmp0, r_look_at, O_(MT3_S2S4,m[0][0])) \ +, store_half(r_tmp1, r_look_at, O_(MT3_S2S4,m[0][1])) \ +, store_half(r_tmp2, r_look_at, O_(MT3_S2S4,m[0][2])) /* ── m[1] = (S2)uy ── */ \ +, load_word(r_tmp0, r_puy, O_(V3_S4,x)) \ +, load_word(r_tmp1, r_puy, O_(V3_S4,y)) \ +, load_word(r_tmp2, r_puy, O_(V3_S4,z)) \ +, nop \ +, store_half(r_tmp0, r_look_at, O_(MT3_S2S4,m[1][0])) \ +, store_half(r_tmp1, r_look_at, O_(MT3_S2S4,m[1][1])) \ +, store_half(r_tmp2, r_look_at, O_(MT3_S2S4,m[1][2])) /* ── m[2] = (S2)uz ── */ \ +, load_word(r_tmp0, r_puz, O_(V3_S4,x)) \ +, load_word(r_tmp1, r_puz, O_(V3_S4,y)) \ +, load_word(r_tmp2, r_puz, O_(V3_S4,z)) \ +, nop \ +, store_half(r_tmp0, r_look_at, O_(MT3_S2S4,m[2][0])) \ +, store_half(r_tmp1, r_look_at, O_(MT3_S2S4,m[2][1])) \ +, store_half(r_tmp2, r_look_at, O_(MT3_S2S4,m[2][2])) /* ── Translation column t[i] = R * (-eye) ───────────────────────────── + * pos = -eye: load eye.x/y/z from r_peye, negate via sub_u from R_0. */ \ +, load_word(r_tmp0, r_peye, O_(P3_S4,x)) \ +, load_word(r_tmp1, r_peye, O_(P3_S4,y)) \ +, load_word(r_tmp2, r_peye, O_(P3_S4,z)) \ +, nop \ +, sub_u(r_tmp0, R_0, r_tmp0) /* pos.x = -eye.x */ \ +, sub_u(r_tmp1, R_0, r_tmp1) \ +, sub_u(r_tmp2, R_0, r_tmp2) /* mtc2 IR1/2/3 = pos (for MVMVA — input vector registers). */ \ +, gte_mv_to_data_r(r_tmp0, C2_IR1) \ +, gte_mv_to_data_r(r_tmp1, C2_IR2) \ +, gte_mv_to_data_r(r_tmp2, C2_IR3) \ +, nop2 /* MVMVA: MAC1/2/3 = R * IR with cv=0 (no TR vector), mx=0 (rotation matrix), + * sf=0 (no shift), v=0 (V0 = IR1/2/3, no far-plane clipping). The pre-set + * rotation matrix is the one set by the preceding set_gte_world atom. + * gte_cmdw_mvmva is parameterless and defaults to cv=0/mx=0/sf=0/v=0. */ \ +, gte_cmdw_mvmva \ +, nop /* GTE interlock */ /* mfc2 MAC1/2/3 → r_tmp0/r_tmp1/r_tmp2 (sign-extended into 32-bit GPRs). + * MAC1/2/3 hold R*v with no TR add and no perspective divide — exactly the + * 3 distinct world-space translation values we need for t[0..2]. */ \ +, gte_mv_from_data_r(r_tmp0, C2_MAC1) \ +, gte_mv_from_data_r(r_tmp1, C2_MAC2) \ +, gte_mv_from_data_r(r_tmp2, C2_MAC3) \ +, nop \ +, store_word(r_tmp0, r_look_at, O_(MT3_S2S4,t[0])) \ +, store_word(r_tmp1, r_look_at, O_(MT3_S2S4,t[1])) \ +, store_word(r_tmp2, r_look_at, O_(MT3_S2S4,t[2])) \ +, mac_yield() +WORD_COUNT(mac_resolve_look_at__populate_and_translate, 50) + diff --git a/code/hello_camera/gen/offsets.h b/code/hello_camera/gen/offsets.h index 2e95a28..cac639d 100644 --- a/code/hello_camera/gen/offsets.h +++ b/code/hello_camera/gen/offsets.h @@ -8,6 +8,36 @@ #pragma region hello_camera +// --- atom: resolve_look_at__normalize_fwd_to_uz (62 words) --- + +#define _atom_offset_srav_path_fwd_to_uz_aligned_done_fwd_to_uz 6 +#define _atom_offset_aligned_done_fwd_to_uz_srav_path_fwd_to_uz 1 + +enum { + atom_offset_srav_path_fwd_to_uz_aligned_done_fwd_to_uz = _atom_offset_srav_path_fwd_to_uz_aligned_done_fwd_to_uz, + atom_offset_aligned_done_fwd_to_uz_srav_path_fwd_to_uz = _atom_offset_aligned_done_fwd_to_uz_srav_path_fwd_to_uz, +}; + +// --- atom: resolve_look_at__normalize_right_to_ux (62 words) --- + +#define _atom_offset_srav_path_right_to_ux_aligned_done_right_to_ux 6 +#define _atom_offset_aligned_done_right_to_ux_srav_path_right_to_ux 1 + +enum { + atom_offset_srav_path_right_to_ux_aligned_done_right_to_ux = _atom_offset_srav_path_right_to_ux_aligned_done_right_to_ux, + atom_offset_aligned_done_right_to_ux_srav_path_right_to_ux = _atom_offset_aligned_done_right_to_ux_srav_path_right_to_ux, +}; + +// --- atom: resolve_look_at__normalize_up_to_uy (62 words) --- + +#define _atom_offset_srav_path_up_to_uy_aligned_done_up_to_uy 6 +#define _atom_offset_aligned_done_up_to_uy_srav_path_up_to_uy 1 + +enum { + atom_offset_srav_path_up_to_uy_aligned_done_up_to_uy = _atom_offset_srav_path_up_to_uy_aligned_done_up_to_uy, + atom_offset_aligned_done_up_to_uy_srav_path_up_to_uy = _atom_offset_aligned_done_up_to_uy_srav_path_up_to_uy, +}; + // --- atom: pad_input_cube_rotation (60 words) --- #define _atom_offset_dpad_left_exit_dpad_left 6 diff --git a/code/hello_camera/hello_camera.atom.c b/code/hello_camera/hello_camera.atom.c index b8a0648..f0cbca8 100644 --- a/code/hello_camera/hello_camera.atom.c +++ b/code/hello_camera/hello_camera.atom.c @@ -24,8 +24,8 @@ ATOM_FILE_DEBUGGER_LINE_MARKER(hello_joypad_atom_c); #pragma region MACs (Mips Atom components) -FI_ Slice_MipsCode ac_put_disp_env(U4 reg_transfer, U4 reg_base, U2 port) -MipsAtomComp_Proc_(ac_put_disp_env, { +FI_ Slice_MipsCode ac_put_disp_env(MipsAtomBuilder_R ab, U4 reg_transfer, U4 reg_base, U2 port) +MipsAtomComp_Proc_(ac_put_disp_env, ab, { // Emits 5 GP0 commands for buffer 0 (display_area = (0,0,320,240)). // Sequence per libpsyx PutDispEnv: DrawArea TL → DrawArea BR → Mask → DrawArea TL → DrawArea BR mac_gcmd_push(gp0_word_draw_area_top_left_origin, reg_transfer, reg_base, port), @@ -35,8 +35,8 @@ MipsAtomComp_Proc_(ac_put_disp_env, { mac_gcmd_push(gp0_word_draw_area_bottom_right_320x240, reg_transfer, reg_base, port), }) -FI_ Slice_MipsCode ac_put_draw_env(U4 reg_transfer, U4 reg_base, U2 port) -MipsAtomComp_Proc_(ac_put_draw_env, { +FI_ Slice_MipsCode ac_put_draw_env(MipsAtomBuilder_R ab, U4 reg_transfer, U4 reg_base, U2 port) +MipsAtomComp_Proc_(ac_put_draw_env, ab, { /* * ORIGIN: each code word corresponds to the EXACT value libpsyx's PutDrawEnv function would compute for the same DrawEnv settings. * References: @@ -90,6 +90,676 @@ MipsAtomComp_Proc_(ac_put_draw_env, { #pragma endregion MACs +#pragma region Atom Procs +// Modular Atoms + +enum { + /* Wave-context GPR carrier for the resolve_look_at bundle: the scratch base. + * Set by atom 0 (popped from tape), read by atoms 1-6 (used as pointer base). + * Type is U4* — this holds the scratch base address (smem.scratchpad value). + * + * Other wave-context carriers (R_ResolveUzPtr / UxPtr / UyPtr) used in the + * prior design were dropped: the new chain atoms compute their src/dst + * addresses internally from R_ResolveScratch + hardcoded_offset. */ + R_ResolveScratch = R_T4 atom_reg atom_type(U4*), +#define R_ResolveScratch_Code R_T4_Code +}; +typedef Struct_(Binds_ResolveLookAt) { + MT3_S2S4* look_at; + P3_S4* eye; + P3_S4* target; + V3_S4* up_in; +}; + +/* Per-atom bind-pop structs for the resolve_look_at bundle. + * Atom 0 (input_and_sub) is the ONLY atom that touches the C-side pointers + + * scratch base. Atoms 1-6 use scratch + hardcoded offsets internally. + * Field types are U4 (raw pointer value) because the structs are populated + * by the frame-time bundle helper with the literal C-side pointer values. */ +typedef Struct_(Binds_ResolveLookAtScratch) { + U4 scratch_base; /* U4 (scratch base address — populated by helper with u4_(smem.scratchpad)) */ +}; + +/* ─── ResolveLookAtScratch — offset schema for the resolve_look_at bundle's + * scratchpad slots (PS1 hardware scratchpad at 0x1F800000). + * + * Each slot is 16 bytes: V3_S4 is already 16 bytes (4 × S4 = x/y/z/pad). + * The struct fields are contiguous — slot i starts at offset i*16. + * Used by the assembly via O_(ResolveLookAtScratch, fld.x/y/z) which resolves + * to a compile-time byte offset. NOT a runtime struct — the struct is purely + * a schema for offsets; the assembly uses `r_scratch + O_(...)` to compute + * slot addresses at runtime. + * + * Slot producers/consumers (referenced by the resolve_look_at chain atoms): + * + * +0 fwd atom 0 writes (target - eye); atom 1 (normalize) reads + * +16 uz atom 1 writes (normalize fwd); atoms 2 + 4 read (cross operands) + * +32 right atom 2 writes (cross uz x up_in); atom 3 (normalize) reads + * +48 ux atom 3 writes (normalize right); atoms 4 + 6 read + * +64 up atom 4 writes (cross uz x ux); atom 5 (normalize) reads + * +80 uy atom 5 writes (normalize up); atom 6 reads + * +96 eye atom 0 stages (C-side input); atom 6 reads (translation column) + * +112 target reserved (currently written nowhere — kept for symmetry w/ eye) + * +128 up_in atom 0 stages (C-side input); atom 2 reads (cross operand) + * + * Fields use P3_S4 (point) for eye/target (RGA: affine point, implicit weight 1); + * V3_S4 (vector) for fwd/uz/right/ux/up/uy/up_in (RGA: Euclidean vector). P3_S4 + * is a storage alias of V3_S4 (see math.h comment: "Storage alias of V3_S4. + * Use P3_S4 when the value is a point.") — both are 16 bytes. + * + * Moved from gte.atom.c (Task 12.11): gte.atom.c is the GENERIC GTE primitives + * file and must not know about any specific atom bundle's scratch layout. */ +typedef Struct_(ResolveLookAtScratch) { + V3_S4 fwd; /* offset +0 (16 bytes — 4 S4 fields incl. internal pad) */ + V3_S4 uz; /* offset +16 (16 bytes) */ + V3_S4 right; /* offset +32 (16 bytes) */ + V3_S4 ux; /* offset +48 (16 bytes) */ + V3_S4 up; /* offset +64 (16 bytes) */ + V3_S4 uy; /* offset +80 (16 bytes) */ + P3_S4 eye; /* offset +96 (16 bytes; storage alias of V3_S4) */ + P3_S4 target; /* offset +112 (16 bytes; storage alias of V3_S4) */ + V3_S4 up_in; /* offset +128 (16 bytes) */ +}; + +/* ─── resolve_look_at bundle chain atoms (Task 5) ──────────────────────────── + * 7 unique atom procs in the resolve_look_at bundle (4 chain atoms + 3 normalize + * variants). All 7 are runtime-built MipsAtom_Proc_ atoms: each function declares + * a static MipsCode[] body, then calls atombuilder_unroll() to append it to the + * caller's MipsAtomBuilder arena. Task 6's resolve_look_at_init() uses this pattern + * to pre-build the bundle into the static arena (smem.resolve_look_at_arena). + * + * Atom roster (positions 0-6 in the bundle): + * Atom 0: resolve_look_at__input_and_sub (chain atom) + * Atom 1: resolve_look_at__normalize_fwd_to_uz (normalize wrapper) + * Atom 2: resolve_look_at__cross_uz_up_in_to_right (chain atom) + * Atom 3: resolve_look_at__normalize_right_to_ux (normalize wrapper) + * Atom 4: resolve_look_at__cross_uz_ux_to_up (chain atom) + * Atom 5: resolve_look_at__normalize_up_to_uy (normalize wrapper) + * Atom 6: resolve_look_at__populate_and_translate (chain atom) + * + * The 3 normalize wrappers are CHAIN-SPECIFIC — they hardcode src/dst scratch + * offsets in the body (computed via r_scratch + O_(ResolveLookAtScratch, fld)). + * The generic normalize_v3s4_proc (in gte.atom.c) takes src/dst as GPR parameters + * and is NOT used by this bundle. (Layering rule: gte.atom.c contains only + * generic GTE primitives; bundle-specific code lives in this file.) + * + * The 3 normalize procs were moved from gte.atom.c to this file in Task 12.11 + * (user feedback: "normalize is not supposed to be aware of a specific scratch + * for one atom bundle"). The procs were renamed to resolve_look_at__normalize_*_proc + * to make their bundle-specific nature clear. + * + * Lua metaprogram support (Task 12.10): the metaprogram auto-emits + * `atom_offset__X__Y` defs in gen/offsets.h for each atom_label/atom_offset pair + * in the body. The 3 normalize procs each have internal branches (srav_path / + * aligned_done variants) and get their per-proc-instance defs (e.g., + * `atom_offset_srav_path_fwd_to_uz_aligned_done_fwd_to_uz`). + */ + +typedef Struct_(Binds_ResolveLookAtSub) { + U4 target; /* U4 (C-side P3_S4* — read by atom 0 directly; NOT a scratchpad address) */ + U4 eye; /* U4 (C-side P3_S4* — read by atom 0 directly; staged into scratchpad by atom 0) */ + U4 up_in; /* U4 (C-side V3_S4* — read by atom 0 directly; staged into scratchpad by atom 0) */ +}; + +/* Atom 0 in the bundle: input_and_sub. Stages C-side inputs into the scratchpad + * and computes fwd = target - eye. + * + * Inputs (C-side pointers popped from the tape; NOT scratchpad addresses): + * r_target_ptr : P3_S4* (C-side struct; atom 0 reads target.x/y/z directly) + * r_eye_ptr : P3_S4* (C-side struct; staged into scratchpad at +96/+100/+104) + * r_up_in_ptr : V3_S4* (C-side struct; staged into scratchpad at +128/+132/+136) + * + * Wave-context output: + * r_scratch : R_ResolveScratch (R_T4) — scratch base, read by atoms 1-6 + * + * Bind-pop layout: + * Binds_ResolveLookAtSub = 12 bytes (target + eye + up_in ptrs) + * Binds_ResolveLookAtScratch = 4 bytes (scratch_base) + * + * Staging work: + * * Stage eye.x/y/z → scratch+96/+100/+104 (for atom 6's translation column) + * * Stage up_in.x/y/z → scratch+128/+132/+136 (for atom 2's outer-product operand) + * * Compute fwd = target - eye, store fwd.x/y/z → scratch+0/+4/+8 (for atom 1) + * + * GPR codes (assigned by resolve_look_at_init): + * r_target_ptr : R_T0 + * r_eye_ptr : R_T1 + * r_up_in_ptr : R_T2 + * r_scratch : R_T4 (R_ResolveScratch; wave-context carrier) + * r_tmp0 : R_T3 (stage eye/up_in + load eye.y) + * r_tmp1 : R_T5 (stage eye/up_in + load eye.z) + * r_tmp2 : R_T6 (stage eye/up_in + load target.x) + * r_tmp3 : R_T7 (stage eye/up_in + load target.y) + * R_AT : hardcoded (load eye.y / eye.z / target.z) + * R_V0 : hardcoded (load eye.z / target.z) + * + * Pool cost: 8 GPRs + R_T4 (carrier) + R_AT + R_V0 (hardcoded) = 11 GPRs. + */ +I_ void resolve_look_at__input_and_sub_proc(MipsAtomBuilder_R ab + , U4 r_target_ptr + , U4 r_eye_ptr + , U4 r_up_in_ptr + , U4 r_scratch + , U4 r_tmp0, U4 r_tmp1, U4 r_tmp2, U4 r_tmp3 +) MipsAtom_Proc_(resolve_look_at__input_and_sub, ab, { + /* Pop the 3 C-side pointers + scratch_base from the tape. */ + load_word(r_target_ptr, R_TapePtr, O_(Binds_ResolveLookAtSub,target)), + load_word(r_eye_ptr, R_TapePtr, O_(Binds_ResolveLookAtSub,eye)), + load_word(r_up_in_ptr, R_TapePtr, O_(Binds_ResolveLookAtSub,up_in)), + add_ui_self( R_TapePtr, S_(Binds_ResolveLookAtSub)), + load_word(r_scratch, R_TapePtr, O_(Binds_ResolveLookAtScratch,scratch_base)), + add_ui_self( R_TapePtr, S_(Binds_ResolveLookAtScratch)), + + /* Stage eye.x/y/z into the scratchpad (atom 6 reads these for the translation + * column). Reuse r_tmp0/r_tmp1/r_tmp2. Offsets via O_(ResolveLookAtScratch,*). */ + load_word(r_tmp0, r_eye_ptr, O_(P3_S4,x)), + load_word(r_tmp1, r_eye_ptr, O_(P3_S4,y)), + load_word(r_tmp2, r_eye_ptr, O_(P3_S4,z)), + nop, /* load-delay */ + store_word(r_tmp0, r_scratch, O_(ResolveLookAtScratch,eye.x)), + store_word(r_tmp1, r_scratch, O_(ResolveLookAtScratch,eye.y)), + store_word(r_tmp2, r_scratch, O_(ResolveLookAtScratch,eye.z)), + + /* Stage up_in.x/y/z into the scratchpad (atom 2 reads these for the outer + * product with uz). Reuse r_tmp0/r_tmp1/r_tmp2. */ + load_word(r_tmp0, r_up_in_ptr, O_(V3_S4,x)), + load_word(r_tmp1, r_up_in_ptr, O_(V3_S4,y)), + load_word(r_tmp2, r_up_in_ptr, O_(V3_S4,z)), + nop, /* load-delay */ + store_word(r_tmp0, r_scratch, O_(ResolveLookAtScratch,up_in.x)), + store_word(r_tmp1, r_scratch, O_(ResolveLookAtScratch,up_in.y)), + store_word(r_tmp2, r_scratch, O_(ResolveLookAtScratch,up_in.z)), + + /* Compute fwd = target - eye. */ + load_word(r_tmp0, r_target_ptr, O_(P3_S4,x)), + load_word(r_tmp1, r_target_ptr, O_(P3_S4,y)), + load_word(r_tmp2, r_target_ptr, O_(P3_S4,z)), + load_word(r_tmp3, r_eye_ptr, O_(P3_S4,x)), + load_word(R_AT, r_eye_ptr, O_(P3_S4,y)), + load_word(R_V0, r_eye_ptr, O_(P3_S4,z)), + nop, /* load-delay */ + sub_u(r_tmp0, r_tmp0, r_tmp3), + sub_u(r_tmp1, r_tmp1, R_AT), + sub_u(r_tmp2, r_tmp2, R_V0), + + /* Store fwd.x/y/z (atom 1 reads these as the normalize src). */ + store_word(r_tmp0, r_scratch, O_(ResolveLookAtScratch,fwd.x)), + store_word(r_tmp1, r_scratch, O_(ResolveLookAtScratch,fwd.y)), + store_word(r_tmp2, r_scratch, O_(ResolveLookAtScratch,fwd.z)), + + mac_yield() +}) + +/* Atoms 2 + 4 in the bundle: out = a × b (GTE outer product on IR/D vectors). + * No bind pop — the three operand pointers (a, b, out) are derived in-body + * from r_scratch + hardcoded_offset. Each atom has its own variant because + * the offsets are baked into the body and each atom uses unique GPRs. + * + * GTE register layout (per PSX-SPX + duffle gte.h): + * IR1/2/3 = a.x/y/z (mtc2) + * VXY0 = b.x (mtc2) + * VZ0 = b.y (mtc2) + * VXY1 = b.z (mtc2) + * OP = outer product + * MAC1/2/3 = out.x/y/z (mfc2) + * + * Pool cost: r_scratch (R_T4 carrier) + 7 body GPRs + R_AT + R_V0 (hardcoded) = 10 GPRs. + */ + +/* Atom 2: cross uz × up_in → right. */ +I_ void resolve_look_at__cross_uz_up_in_to_right_proc(MipsAtomBuilder_R ab + , U4 r_scratch + , U4 r_a, U4 r_b, U4 r_c /* load a.x/y/z; result out.x/y/z */ + , U4 r_d /* load b.x */ + , U4 r_f, U4 r_g, U4 r_h /* r_f = &right (out ptr), r_g = &uz, r_h = &up_in */ +) MipsAtom_Proc_(resolve_look_at__cross_uz_up_in_to_right, ab, { + /* Compute the three scratch pointers from r_scratch. */ + add_si(r_g, r_scratch, O_(ResolveLookAtScratch,uz)), /* r_g = &uz */ + add_si(r_h, r_scratch, O_(ResolveLookAtScratch,up_in)), /* r_h = &up_in */ + add_si(r_f, r_scratch, O_(ResolveLookAtScratch,right)), /* r_f = &right (out) */ + nop, + + /* Load a (uz).x/y/z into r_a/r_b/r_c. */ + load_word(r_a, r_g, O_(V3_S4,x)), + load_word(r_b, r_g, O_(V3_S4,y)), + load_word(r_c, r_g, O_(V3_S4,z)), + nop, + + /* Load b (up_in).x/y/z into r_d + R_AT/R_V0 (hardcoded; reusing the + * body's last two loads is fine because the load-delay slot is the nop + * after the third load, and mtc2 below doesn't read these regs). */ + load_word(r_d, r_h, O_(V3_S4,x)), + load_word(R_AT, r_h, O_(V3_S4,y)), + load_word(R_V0, r_h, O_(V3_S4,z)), + nop, + + /* mtc2 a → IR1/2/3, b → D1/2/3 (VXY0/VZ0/VXY1). */ + gte_mv_to_data_r(r_a, C2_IR1), + gte_mv_to_data_r(r_b, C2_IR2), + gte_mv_to_data_r(r_c, C2_IR3), + gte_mv_to_data_r(r_d, C2_VXY0), /* D1 = b.x */ + gte_mv_to_data_r(R_AT, C2_VZ0), /* D2 = b.y */ + gte_mv_to_data_r(R_V0, C2_VXY1), /* D3 = b.z */ + nop2, /* MTC2 retirement (CPU→COP2 2-slot delay) */ + + gte_cmdw_outer_product, /* OP fires; MAC1/2/3 = a × b */ + + /* mfc2 MAC1/2/3 → r_a/r_b/r_c (out.x/y/z). */ + gte_mv_from_data_r(r_a, C2_MAC1), + gte_mv_from_data_r(r_b, C2_MAC2), + gte_mv_from_data_r(r_c, C2_MAC3), + nop, /* MFC2 retirement */ + + /* Store out.x/y/z to r_f (out ptr = scratch+32). */ + store_word(r_a, r_f, O_(V3_S4,x)), + store_word(r_b, r_f, O_(V3_S4,y)), + store_word(r_c, r_f, O_(V3_S4,z)), + + mac_yield() +}) + +/* Atom 4: cross uz × ux → up. */ +I_ void resolve_look_at__cross_uz_ux_to_up_proc(MipsAtomBuilder_R ab + , U4 r_scratch + , U4 r_a, U4 r_b, U4 r_c /* load a.x/y/z; result out.x/y/z */ + , U4 r_d /* load b.x */ + , U4 r_f, U4 r_g, U4 r_h /* r_f = &up (out ptr), r_g = &uz, r_h = &ux */ +) MipsAtom_Proc_(resolve_look_at__cross_uz_ux_to_up, ab, { + /* Compute the three scratch pointers from r_scratch. */ + add_si(r_g, r_scratch, O_(ResolveLookAtScratch,uz)), /* r_g = &uz */ + add_si(r_h, r_scratch, O_(ResolveLookAtScratch,ux)), /* r_h = &ux */ + add_si(r_f, r_scratch, O_(ResolveLookAtScratch,up)), /* r_f = &up (out) */ + nop, + + /* Load a (uz).x/y/z into r_a/r_b/r_c. */ + load_word(r_a, r_g, O_(V3_S4,x)), + load_word(r_b, r_g, O_(V3_S4,y)), + load_word(r_c, r_g, O_(V3_S4,z)), + nop, + + /* Load b (ux).x/y/z into r_d + R_AT/R_V0. */ + load_word(r_d, r_h, O_(V3_S4,x)), + load_word(R_AT, r_h, O_(V3_S4,y)), + load_word(R_V0, r_h, O_(V3_S4,z)), + nop, + + /* mtc2 a → IR1/2/3, b → D1/2/3 (VXY0/VZ0/VXY1). */ + gte_mv_to_data_r(r_a, C2_IR1), + gte_mv_to_data_r(r_b, C2_IR2), + gte_mv_to_data_r(r_c, C2_IR3), + gte_mv_to_data_r(r_d, C2_VXY0), + gte_mv_to_data_r(R_AT, C2_VZ0), + gte_mv_to_data_r(R_V0, C2_VXY1), + nop2, + + gte_cmdw_outer_product, + gte_mv_from_data_r(r_a, C2_MAC1), + gte_mv_from_data_r(r_b, C2_MAC2), + gte_mv_from_data_r(r_c, C2_MAC3), + nop, + store_word(r_a, r_f, O_(V3_S4,x)), + store_word(r_b, r_f, O_(V3_S4,y)), + store_word(r_c, r_f, O_(V3_S4,z)), + + mac_yield() +}) + +/* Atoms 1, 3, 5 in the bundle: chain-specific normalize wrappers around the + * generic normalize_v3s4_proc (gte.atom.c). The generic proc takes src/dst as + * GPR parameters; these wrappers HARDCODE src/dst via r_scratch + O_(ResolveLookAtScratch, fld) + * so the C-side bundle helper doesn't need to push scratchpad addresses via + * tb_data between atoms. (Task 12.8 fix: eliminate magic offsets.) + * + * The 4-stage normalize body (SQR → mfc2 → LZCS → GPF → srav) is identical to + * the generic version (GPR-renamed); cycle counts match. The only per-atom + * difference is the (src, dst) scratch offsets and the per-proc atom_label + * suffixes (srav_path_fwd_to_uz, srav_path_right_to_ux, srav_path_up_to_uy) so + * the per-proc-instance offsets are emitted disjointly in gen/offsets.h. + * + * GPR pool (10 free regs: R_T0..R_T3, R_T5..R_T7, R_V0, R_V1, R_AT; R_T4 reserved for R_ResolveScratch): + * r_a : src ptr (overlaps with r_recip_est carrier after the 3 src-loads) + * r_b : dst ptr (saved throughout) + * r_e/r_f/r_i : src.x/y/z → result.x/y/z (preserved across stages 1-2 via r_d/r_g/r_recip_est scratch) + * r_d/r_g : MAC1/2 scratch (dead after stage 2) + * r_h : LZCR (saved across stages 3-4) + * r_recip_est : |v|² accumulator + sqrtbl[index] + 1/|v| (saved throughout) + * r_shift : final srav amount (saved across stages 3-4) + * + * The Lua metaprogram (Task 12.10) auto-emits: + * - `mac_resolve_look_at__normalize__to_` alias in gen/macs.h + * - `atom_offset__srav_path__to___aligned_done__to_` defs in gen/offsets.h + */ + +/* Atom 1: normalize fwd (scratch+0) → uz (scratch+16). */ +I_ void resolve_look_at__normalize_fwd_to_uz_proc(MipsAtomBuilder_R ab + , U4 r_scratch + , U4 r_a, U4 r_b /* src/dst scratch pointers */ + , U4 r_e, U4 r_f, U4 r_i /* src.x/y/z → result.x/y/z */ + , U4 r_d, U4 r_g /* MAC1/2 scratch (dead after stage 2) */ + , U4 r_h /* LZCR */ + , U4 r_recip_est + , U4 r_shift +) MipsAtom_Proc_(resolve_look_at__normalize_fwd_to_uz, ab, { + /* Compute src/dst pointers from r_scratch. */ + add_si(r_a, r_scratch, O_(ResolveLookAtScratch,fwd)), /* r_a = &fwd */ + add_si(r_b, r_scratch, O_(ResolveLookAtScratch,uz)), /* r_b = &uz */ + nop, + + /* Load src.x/y/z from r_a into r_e/r_f/r_i. */ + load_word(r_e, r_a, O_(V3_S4,x)), + load_word(r_f, r_a, O_(V3_S4,y)), + load_word(r_i, r_a, O_(V3_S4,z)), + nop, /* load-delay */ + + /* Stage 1: mtc2 src → IR1/2/3, SQR fires. */ + gte_mv_to_data_r(r_e, C2_IR1), + gte_mv_to_data_r(r_f, C2_IR2), + gte_mv_to_data_r(r_i, C2_IR3), + nop, gte_cmdw_sqr, + + /* Stage 2: mfc2 MAC1/2/3, sum, mtc2 LZCS. */ + gte_mv_from_data_r(r_d, C2_MAC1), + gte_mv_from_data_r(r_g, C2_MAC2), + gte_mv_from_data_r(r_recip_est, C2_MAC3), + nop, + add_u(r_recip_est, r_recip_est, r_g), + add_u(r_recip_est, r_recip_est, r_d), + gte_mv_to_data_r(r_recip_est, C2_LZCS), + nop2, + gte_mv_from_data_r(r_h, C2_LZCR), + nop, + + /* Stage 3: compute shift amount, align |v|² to bit 24. */ + and_i( r_h, r_h, -2), + li_s( r_shift, 31), + sub_s( r_shift, r_shift, r_h), + shift_aright(r_shift, r_shift, 1), + add_si( r_a, r_h, -24), /* r_a = LZCR - 24 (overlapping with r_recip_est; src ptr no longer needed) */ + branch_lt_zero(r_a, atom_offset(srav_path_fwd_to_uz, aligned_done_fwd_to_uz)), nop, + jump_rel(atom_offset(aligned_done_fwd_to_uz, srav_path_fwd_to_uz)), + shift_lleft_var(r_recip_est, r_recip_est, r_a), + atom_label(srav_path_fwd_to_uz) + li_s( r_a, 24), + sub_s( r_a, r_a, r_h), + shift_aright_var(r_recip_est, r_recip_est, r_a), + atom_label(aligned_done_fwd_to_uz) + /* r_recip_est holds |v|² aligned to bit 24. */ + add_si( r_recip_est, r_recip_est, -64), + shift_lleft(r_recip_est, r_recip_est, 1), + load_upper_i(r_a, u4_hi(& gte_normalize_sqr_tbl)), + or_i_self(r_a, u4_lo(& gte_normalize_sqr_tbl)), + add_u(r_a, r_a, r_recip_est), + load_half(r_recip_est, r_a, 0), + nop, + + /* Stage 4: GPF + srav finalize. */ + gte_mv_to_data_r(r_recip_est, C2_IR0), + gte_mv_to_data_r(r_e, C2_IR1), + gte_mv_to_data_r(r_f, C2_IR2), + gte_mv_to_data_r(r_i, C2_IR3), + nop2, + gte_cmdw_gpf, + gte_mv_from_data_r(r_e, C2_MAC1), + gte_mv_from_data_r(r_f, C2_MAC2), + gte_mv_from_data_r(r_i, C2_MAC3), + shift_aright_var(r_e, r_e, r_shift), + shift_aright_var(r_f, r_f, r_shift), + shift_aright_var(r_i, r_i, r_shift), + + /* Store result.x/y/z to r_b (dst ptr = scratch+16). */ + store_word(r_e, r_b, O_(V3_S4,x)), + store_word(r_f, r_b, O_(V3_S4,y)), + store_word(r_i, r_b, O_(V3_S4,z)), + + mac_yield() +}) + +/* Atom 3: normalize right (scratch+32) → ux (scratch+48). */ +I_ void resolve_look_at__normalize_right_to_ux_proc(MipsAtomBuilder_R ab + , U4 r_scratch + , U4 r_a, U4 r_b + , U4 r_e, U4 r_f, U4 r_i + , U4 r_d, U4 r_g + , U4 r_h + , U4 r_recip_est + , U4 r_shift +) MipsAtom_Proc_(resolve_look_at__normalize_right_to_ux, ab, { + add_si(r_a, r_scratch, O_(ResolveLookAtScratch,right)), /* r_a = &right */ + add_si(r_b, r_scratch, O_(ResolveLookAtScratch,ux)), /* r_b = &ux */ + nop, + load_word(r_e, r_a, O_(V3_S4,x)), + load_word(r_f, r_a, O_(V3_S4,y)), + load_word(r_i, r_a, O_(V3_S4,z)), + nop, + gte_mv_to_data_r(r_e, C2_IR1), + gte_mv_to_data_r(r_f, C2_IR2), + gte_mv_to_data_r(r_i, C2_IR3), + nop, gte_cmdw_sqr, + gte_mv_from_data_r(r_d, C2_MAC1), + gte_mv_from_data_r(r_g, C2_MAC2), + gte_mv_from_data_r(r_recip_est, C2_MAC3), + nop, + add_u(r_recip_est, r_recip_est, r_g), + add_u(r_recip_est, r_recip_est, r_d), + gte_mv_to_data_r(r_recip_est, C2_LZCS), + nop2, + gte_mv_from_data_r(r_h, C2_LZCR), + nop, + and_i( r_h, r_h, -2), + li_s( r_shift, 31), + sub_s( r_shift, r_shift, r_h), + shift_aright(r_shift, r_shift, 1), + add_si( r_a, r_h, -24), + branch_lt_zero(r_a, atom_offset(srav_path_right_to_ux, aligned_done_right_to_ux)), nop, + jump_rel(atom_offset(aligned_done_right_to_ux, srav_path_right_to_ux)), + shift_lleft_var(r_recip_est, r_recip_est, r_a), + atom_label(srav_path_right_to_ux) + li_s( r_a, 24), + sub_s( r_a, r_a, r_h), + shift_aright_var(r_recip_est, r_recip_est, r_a), + atom_label(aligned_done_right_to_ux) + add_si( r_recip_est, r_recip_est, -64), + shift_lleft(r_recip_est, r_recip_est, 1), + load_upper_i(r_a, u4_hi(& gte_normalize_sqr_tbl)), + or_i_self(r_a, u4_lo(& gte_normalize_sqr_tbl)), + add_u(r_a, r_a, r_recip_est), + load_half(r_recip_est, r_a, 0), + nop, + gte_mv_to_data_r(r_recip_est, C2_IR0), + gte_mv_to_data_r(r_e, C2_IR1), + gte_mv_to_data_r(r_f, C2_IR2), + gte_mv_to_data_r(r_i, C2_IR3), + nop2, + gte_cmdw_gpf, + gte_mv_from_data_r(r_e, C2_MAC1), + gte_mv_from_data_r(r_f, C2_MAC2), + gte_mv_from_data_r(r_i, C2_MAC3), + shift_aright_var(r_e, r_e, r_shift), + shift_aright_var(r_f, r_f, r_shift), + shift_aright_var(r_i, r_i, r_shift), + store_word(r_e, r_b, O_(V3_S4,x)), + store_word(r_f, r_b, O_(V3_S4,y)), + store_word(r_i, r_b, O_(V3_S4,z)), + mac_yield() +}) + +/* Atom 5: normalize up (scratch+64) → uy (scratch+80). */ +I_ void resolve_look_at__normalize_up_to_uy_proc(MipsAtomBuilder_R ab + , U4 r_scratch + , U4 r_a, U4 r_b + , U4 r_e, U4 r_f, U4 r_i + , U4 r_d, U4 r_g + , U4 r_h + , U4 r_recip_est + , U4 r_shift +) MipsAtom_Proc_(resolve_look_at__normalize_up_to_uy, ab, { + add_si(r_a, r_scratch, O_(ResolveLookAtScratch,up)), /* r_a = &up */ + add_si(r_b, r_scratch, O_(ResolveLookAtScratch,uy)), /* r_b = &uy */ + nop, + load_word(r_e, r_a, O_(V3_S4,x)), + load_word(r_f, r_a, O_(V3_S4,y)), + load_word(r_i, r_a, O_(V3_S4,z)), + nop, + gte_mv_to_data_r(r_e, C2_IR1), + gte_mv_to_data_r(r_f, C2_IR2), + gte_mv_to_data_r(r_i, C2_IR3), + nop, gte_cmdw_sqr, + gte_mv_from_data_r(r_d, C2_MAC1), + gte_mv_from_data_r(r_g, C2_MAC2), + gte_mv_from_data_r(r_recip_est, C2_MAC3), + nop, + add_u(r_recip_est, r_recip_est, r_g), + add_u(r_recip_est, r_recip_est, r_d), + gte_mv_to_data_r(r_recip_est, C2_LZCS), + nop2, + gte_mv_from_data_r(r_h, C2_LZCR), + nop, + and_i( r_h, r_h, -2), + li_s( r_shift, 31), + sub_s( r_shift, r_shift, r_h), + shift_aright(r_shift, r_shift, 1), + add_si( r_a, r_h, -24), + branch_lt_zero(r_a, atom_offset(srav_path_up_to_uy, aligned_done_up_to_uy)), nop, + jump_rel(atom_offset(aligned_done_up_to_uy, srav_path_up_to_uy)), + shift_lleft_var(r_recip_est, r_recip_est, r_a), + atom_label(srav_path_up_to_uy) + li_s( r_a, 24), + sub_s( r_a, r_a, r_h), + shift_aright_var(r_recip_est, r_recip_est, r_a), + atom_label(aligned_done_up_to_uy) + add_si( r_recip_est, r_recip_est, -64), + shift_lleft(r_recip_est, r_recip_est, 1), + load_upper_i(r_a, u4_hi(& gte_normalize_sqr_tbl)), + or_i_self(r_a, u4_lo(& gte_normalize_sqr_tbl)), + add_u(r_a, r_a, r_recip_est), + load_half(r_recip_est, r_a, 0), + nop, + gte_mv_to_data_r(r_recip_est, C2_IR0), + gte_mv_to_data_r(r_e, C2_IR1), + gte_mv_to_data_r(r_f, C2_IR2), + gte_mv_to_data_r(r_i, C2_IR3), + nop2, + gte_cmdw_gpf, + gte_mv_from_data_r(r_e, C2_MAC1), + gte_mv_from_data_r(r_f, C2_MAC2), + gte_mv_from_data_r(r_i, C2_MAC3), + shift_aright_var(r_e, r_e, r_shift), + shift_aright_var(r_f, r_f, r_shift), + shift_aright_var(r_i, r_i, r_shift), + store_word(r_e, r_b, O_(V3_S4,x)), + store_word(r_f, r_b, O_(V3_S4,y)), + store_word(r_i, r_b, O_(V3_S4,z)), + mac_yield() +}) + +typedef Struct_(Binds_ResolveLookAtPopAndTrans) { + U4 look_at; /* U4 (MT3_S2S4* — destination matrix address) */ +}; +/* Atom 6 in the bundle: write look_at->m[][] from ux/uy/uz, then compute + * the translation column t[] = R * (-eye). + * + * GPR codes (assigned by resolve_look_at_init): + * r_look_at : MT3_S2S4* (popped from tape; output matrix destination) + * r_pux : pointer to ux (offset O_(ResolveLookAtScratch,ux)) + * r_puy : pointer to uy (offset O_(ResolveLookAtScratch,uy)) + * r_puz : pointer to uz (offset O_(ResolveLookAtScratch,uz)) + * r_peye : pointer to eye (offset O_(ResolveLookAtScratch,eye)) + * r_tmp0/1/2 : atom-local scratch (load + MVMVA + store temps) + * + * The 4 pointer regs (r_pux/r_puy/r_puz/r_peye) are DEDICATED — they hold the scratch addresses for the entire body. + * They are computed in-body via `add_si(r_px, r_scratch, O_(ResolveLookAtScratch, field))` so no tape-data pointer is needed. + * + * Struct layout (per duffle/math.h): + * MT3_S2S4 { A3x3_S2 m; A3_S4 t; } → m[][] is S2 packed (9 × 2 = 18 bytes at offset 0) + * t[0/1/2] is S4 (3 × 4 = 12 bytes at offset 18) + * + * Translation column: GTE MVMVA with the world rotation matrix pre-set (helper emits set_gte_world before the bundle, per the bundle design). + * MVMVA computes R * pos (with cv=0/mx=0/sf=0/v=0); MAC1/2/3 = R * (-eye). + * Pool cost: r_look_at (1) + r_scratch (R_T4 carrier) + 4 ptr regs + 3 tmp regs = 9 GPRs. + */ +I_ void resolve_look_at__populate_and_translate_proc(MipsAtomBuilder_R ab + , U4 r_look_at + , U4 r_scratch + , U4 r_pux, U4 r_puy, U4 r_puz, U4 r_peye /* 4 dedicated pointer regs */ + , U4 r_tmp0, U4 r_tmp1, U4 r_tmp2 /* 3 atom-local scratch regs */ +) MipsAtom_Proc_(resolve_look_at__populate_and_translate, ab, { + /* Pop look_at* (the matrix output) — advance R_TapePtr by 4 bytes. */ + load_word(r_look_at, R_TapePtr, O_(Binds_ResolveLookAtPopAndTrans,look_at)), + add_ui_self( R_TapePtr, S_(Binds_ResolveLookAtPopAndTrans)), + + /* Compute the 4 scratch pointers in their dedicated GPRs. */ + add_si(r_pux, r_scratch, O_(ResolveLookAtScratch,ux)), /* r_pux = &ux */ + add_si(r_puy, r_scratch, O_(ResolveLookAtScratch,uy)), /* r_puy = &uy */ + add_si(r_puz, r_scratch, O_(ResolveLookAtScratch,uz)), /* r_puz = &uz */ + add_si(r_peye, r_scratch, O_(ResolveLookAtScratch,eye)), /* r_peye = &eye */ + nop, + + /* ── m[0] = (S2)ux ── */ + load_word(r_tmp0, r_pux, O_(V3_S4,x)), + load_word(r_tmp1, r_pux, O_(V3_S4,y)), + load_word(r_tmp2, r_pux, O_(V3_S4,z)), + nop, + store_half(r_tmp0, r_look_at, O_(MT3_S2S4,m[0][0])), + store_half(r_tmp1, r_look_at, O_(MT3_S2S4,m[0][1])), + store_half(r_tmp2, r_look_at, O_(MT3_S2S4,m[0][2])), + + /* ── m[1] = (S2)uy ── */ + load_word(r_tmp0, r_puy, O_(V3_S4,x)), + load_word(r_tmp1, r_puy, O_(V3_S4,y)), + load_word(r_tmp2, r_puy, O_(V3_S4,z)), + nop, + store_half(r_tmp0, r_look_at, O_(MT3_S2S4,m[1][0])), + store_half(r_tmp1, r_look_at, O_(MT3_S2S4,m[1][1])), + store_half(r_tmp2, r_look_at, O_(MT3_S2S4,m[1][2])), + + /* ── m[2] = (S2)uz ── */ + load_word(r_tmp0, r_puz, O_(V3_S4,x)), + load_word(r_tmp1, r_puz, O_(V3_S4,y)), + load_word(r_tmp2, r_puz, O_(V3_S4,z)), + nop, + store_half(r_tmp0, r_look_at, O_(MT3_S2S4,m[2][0])), + store_half(r_tmp1, r_look_at, O_(MT3_S2S4,m[2][1])), + store_half(r_tmp2, r_look_at, O_(MT3_S2S4,m[2][2])), + + /* ── Translation column t[i] = R * (-eye) ───────────────────────────── + * pos = -eye: load eye.x/y/z from r_peye, negate via sub_u from R_0. */ + load_word(r_tmp0, r_peye, O_(P3_S4,x)), + load_word(r_tmp1, r_peye, O_(P3_S4,y)), + load_word(r_tmp2, r_peye, O_(P3_S4,z)), + nop, + sub_u(r_tmp0, R_0, r_tmp0), /* pos.x = -eye.x */ + sub_u(r_tmp1, R_0, r_tmp1), + sub_u(r_tmp2, R_0, r_tmp2), + + /* mtc2 IR1/2/3 = pos (for MVMVA — input vector registers). */ + gte_mv_to_data_r(r_tmp0, C2_IR1), + gte_mv_to_data_r(r_tmp1, C2_IR2), + gte_mv_to_data_r(r_tmp2, C2_IR3), + nop2, + + /* MVMVA: MAC1/2/3 = R * IR with cv=0 (no TR vector), mx=0 (rotation matrix), + * sf=0 (no shift), v=0 (V0 = IR1/2/3, no far-plane clipping). The pre-set + * rotation matrix is the one set by the preceding set_gte_world atom. + * gte_cmdw_mvmva is parameterless and defaults to cv=0/mx=0/sf=0/v=0. */ + gte_cmdw_mvmva, + nop, /* GTE interlock */ + + /* mfc2 MAC1/2/3 → r_tmp0/r_tmp1/r_tmp2 (sign-extended into 32-bit GPRs). + * MAC1/2/3 hold R*v with no TR add and no perspective divide — exactly the + * 3 distinct world-space translation values we need for t[0..2]. */ + gte_mv_from_data_r(r_tmp0, C2_MAC1), + gte_mv_from_data_r(r_tmp1, C2_MAC2), + gte_mv_from_data_r(r_tmp2, C2_MAC3), + nop, + store_word(r_tmp0, r_look_at, O_(MT3_S2S4,t[0])), + store_word(r_tmp1, r_look_at, O_(MT3_S2S4,t[1])), + store_word(r_tmp2, r_look_at, O_(MT3_S2S4,t[2])), + + mac_yield() +}) + +#pragma endregion Atom Procs + #pragma region Baked Atoms enum { @@ -129,7 +799,7 @@ internal MipsAtom_(screen_env_init) atom_info(atom_phase(screen_init) store_word(R_0, R_ScreenBuf, O_(DrawEnv,texture_window.width) + OA_(DoubleBuffer,draw,1)), /* draw[0].texture_page = 10 (gp0_tpage_default). C11 SetDefDrawEnv at C11_only.elf:0x8001273C writes the same 0x0A. . */ - add_ui(R_T0, R_0, gp0_tpage_default), + add_ui(R_T0, R_0, gp0_tpage_default), store_half(R_T0, R_ScreenBuf, O_(DrawEnv,texture_page) + OA_(DoubleBuffer,draw,0)), store_half(R_T0, R_ScreenBuf, O_(DrawEnv,texture_page) + OA_(DoubleBuffer,draw,1)), @@ -144,7 +814,7 @@ internal MipsAtom_(screen_env_init) atom_info(atom_phase(screen_init) store_byte(R_T0, R_ScreenBuf, O_(DrawEnv,enable_auto_clear) + OA_(DoubleBuffer,draw,1)), /* draw[0].initial_bg_color = (r=7, g=7, b=7). */ - add_ui(R_T0, R_0, 7), + add_ui(R_T0, R_0, 7), mac_store_rgb8(R_T0,R_T0,R_T0, R_ScreenBuf, O_(DrawEnv,initial_bg_color) + OA_(DoubleBuffer,draw,0)), mac_store_rgb8(R_T0,R_T0,R_T0, R_ScreenBuf, O_(DrawEnv,initial_bg_color) + OA_(DoubleBuffer,draw,1)), @@ -181,9 +851,9 @@ internal MipsAtom_(gp_screen_init) atom_info(atom_phase(screen_init), atom_reads }; typedef Struct_(Binds_PadApplyInput) { - PadState* state; - V3_S2* cube_rot; - V3_S2* floor_rot; + PadState* state; + V3_S2* cube_rot; + V3_S2* floor_rot; }; enum { R_PadStateT5 = R_T5 atom_reg, @@ -345,55 +1015,40 @@ atom_label(exit_circle_z) mac_yield_tail(), }; +/* Scratchpad layout for the resolve_look_at bundle. + * The chain atoms communicate entirely via the wave-context GPR carrier + * R_ResolveScratch (R_T4) + hardcoded offsets into smem.scratchpad + * (PS1 hardware scratchpad at 0x1F800000). + * + * Atom 0 (input_and_sub) STAGES the C-side inputs (eye, up_in) into the scratchpad; + * AT THE SAME TIME it computes fwd = target - eye and stores it at scratch+0. + * Atoms 1-6 then read/write specific scratchpad offsets internally using + * `r_scratch + hardcoded_offset` — no tape-data pointers are passed between atoms. + * + * +0 fwd (atom 0 writes; atom 1 reads) + * +16 uz (atom 1 writes; atoms 2 + 4 read) + * +32 right (atom 2 writes; atom 3 reads) + * +48 ux (atom 3 writes; atoms 4 + 6 read) + * +64 up (atom 4 writes; atom 5 reads) + * +80 uy (atom 5 writes; atom 6 reads) + * +96 eye (atom 0 stages from C-side pointer; atom 6 reads) + * +128 up_in (atom 0 stages from C-side pointer; atom 2 reads) + * + * No struct view is required — the C-side bundle helper passes only C-side + * pointers (target, eye, up_in, look_at) and the scratch base address; + * the assembly hardcodes all inter-slot offsets. The original Task 12.7 magic + * offsets `& smem.scratchpad[N]` in the C-side helper were eliminated by this + * redesign; the user feedback was: "you didn't have to use magic offsets into + * the scratchpad memory. those are harcoded." */ + enum { R_LookAt = R_T0 atom_reg atom_type(MT3_S2S4*), R_CamEye = R_T1 atom_reg atom_type(P3_S4*), R_CamTarget = R_T2 atom_reg atom_type(P3_S4*), R_WorldUp = R_T3 atom_reg atom_type(V3_S4*), - - R_LkAt_Fwdx = R_T4 atom_reg atom_type(V3_S4*), - R_LkAt_Fwdy = R_T5 atom_reg atom_type(V3_S4*), - R_LkAt_Fwdz = R_T6 atom_reg atom_type(V3_S4*), - R_Eye_x = R_T7 atom_reg atom_type(V3_S4*), - R_Eye_y = R_T8 atom_reg atom_type(V3_S4*), - R_Eye_z = R_V0 atom_reg atom_type(V3_S4*), - - R_LkAt_Up = R_T5 atom_reg atom_type(V3_S4*), - R_LkAt_Right = R_T6 atom_reg atom_type(V3_S4*), - - R_AxisX = R_T7 atom_reg atom_type(V3_S4*), - R_AxisY = R_T8 atom_reg atom_type(V3_S4*), - R_AxisZ = R_T7 atom_reg atom_type(V3_S4*), }; -typedef Struct_(Binds_ResolveLookAt) { - MT3_S2S4* look_at; - P3_S4* eye; - P3_S4* target; - V3_S4* up_in; -}; -internal MipsAtom_(resolve_look_at) atom_info(atom_bind(Binds_ResolveLookAt)) { - load_word(R_LookAt, R_TapePtr, O_(Binds_ResolveLookAt,look_at)), - load_word(R_CamEye, R_TapePtr, O_(Binds_ResolveLookAt,eye)), - load_word(R_CamTarget, R_TapePtr, O_(Binds_ResolveLookAt,target)), - load_word(R_WorldUp, R_TapePtr, O_(Binds_ResolveLookAt,up_in)), - add_ui_self( R_TapePtr, S_(Binds_ResolveLookAt)), - // load look_at and eye, then subtract (get direction), then normalize to unit vector. - mac_load_v3s4(R_LkAt_Fwdx, R_LkAt_Fwdy, R_LkAt_Fwdz, R_LookAt, 0), - mac_load_v3s4(R_Eye_x, R_Eye_y, R_Eye_z, R_CamEye, 0), - mac_sub_v3s4( R_LkAt_Fwdx, R_LkAt_Fwdy, R_LkAt_Fwdz, - R_Eye_x, R_Eye_y, R_Eye_z), - // ac_normalize_v3s4(9 args): in-place normalize direction → unit vector. - // Reg-aliasing across the 4 stages: R_T7 = r_sq_y → r_lzcr, R_T8 = r_sq_z → r_shift, - // R_V0 = r_recip_est (always), R_V1 = r_tmp. r_sx/r_sy/r_sz = R_LkAt_Fwdx/y/z (in-place). - // mac_normalize_v3s4(R_LkAt_Fwdx, R_LkAt_Fwdy, R_LkAt_Fwdz, - // R_T7, R_T8, - // R_V0, - // R_T7, R_T8, R_V1), - - mac_yield(), -}; enum { R_PrimCursor = R_T7 atom_reg atom_type(U4*), /* VRAM output cursor (primitive buffer) */ @@ -443,7 +1098,7 @@ MipsAtom_(cube_g4_face) atom_info(atom_phase(cube_g4), gte_mv_from_data_r(R_T0, C2_MAC0), nop, branch_le_zero(R_T0, atom_offset(cull, cube_g4_face_exit)), /* BD-slot: write the prim tag (R_0=0; overwrites the legacy tag word in the prim_buffer). - * If branch IS taken (face culled), the body is skipped and this 0-tag is stranded — + * If branch IS taken (face culled), the body is skipped and this 0-tag is stranded — * harmless because the OT entry that points to this prim is created later. */ store_word(R_0, R_PrimCursor, O_(Poly_G4, tag)), shift_lleft(R_AT, R_T3, v3s2_byteoff), add_u(R_AT, R_AT, R_VertBase), @@ -501,14 +1156,14 @@ MipsAtom_(floor_f3_face) atom_info(atom_phase(floor_f3) , atom_reads( R_PrimCursor, R_FaceCursor, R_VertBase, R_OtBase) , atom_writes(R_PrimCursor, R_FaceCursor) ) { - mac_load_tri_indices( R_FaceCursor, R_T0, R_T1, R_T2), + mac_load_tri_indices(R_FaceCursor, R_T0, R_T1, R_T2), mac_gte_load_tri_verts(R_VertBase, R_T0, R_T1, R_T2), nop2, gte_cmdw_rotate_translate_perspective_triple, // 2 nops retire the final cpu -> gte writes before RTPT gte_cmdw_nclip, /* Culling (Branch forward if Backface) */ gte_mv_from_data_r(R_T0, C2_MAC0), - nop, branch_le_zero(R_T0, atom_offset(culling, floor_f3_face_exit)), nop, // required gte -> cpu load-delay slot. + nop, branch_le_zero(R_T0, atom_offset(culling, floor_f3_face_exit)), nop, // required gte -> cpu load-delay slot. /* Format Primitive */ mac_gte_store_f3(R_PrimCursor), diff --git a/code/hello_camera/hello_camera.c b/code/hello_camera/hello_camera.c index 235fc36..b98d8d4 100644 --- a/code/hello_camera/hello_camera.c +++ b/code/hello_camera/hello_camera.c @@ -51,9 +51,10 @@ #include "hello_camera.atom.c" #pragma endregion Hello Joypad TUs -enum { - Scratchpad_Len = 1024, - MemTape_Len = 512, +enum { + Scratchpad_Len = 1024, + MemTape_Len = 512, + ResolveLookAtArena_Words = 512, }; typedef Struct_(SMemory) { PrimitiveArena primitives; @@ -75,6 +76,17 @@ typedef Struct_(SMemory) { PadState pad[2]; U4_V scratchpad; // d-cache + + /* resolve_look_at bundle: pre-built atom arena + atom-refs. + * (Task 12.5 fix: moved from file-scope globals to smem fields. + * Task 12.7 fix: dropped the ResolveLookAtScratch struct-as-view; the + * C-side helper uses `& smem.scratchpad[N]` at hardcoded offsets directly. + * Task 12.8 fix: chain atoms use r_scratch + offset internally; no C-side magic offsets anywhere. + * Task 12.11 fix: ResolveLookAtScratch offset schema moved to hello_camera.atom.c — gte.atom.c + * is the GENERIC GTE primitives file and must not know about the resolve_look_at bundle's scratch layout.) */ + U4 resolve_look_at_arena[ResolveLookAtArena_Words]; /* ~2 KB; bumped from 420 per Task 4 subagent */ + MipsAtom* resolve_look_at_atom_addrs[7]; + MipsAtomBuilder resolve_look_at_ab_static; }; global SMemory smem; extern SMemory smem; @@ -119,6 +131,159 @@ resolve_look_at_c11(MT3_S2S4* look_at, P3_S4* eye, P3_S4* target, V3_S4* up_in) trans_m3s2( look_at, & off); } +/* Pre-build all 7 chain atoms of the resolve_look_at bundle into the static arena. + * Called ONCE from main() before the frame loop. + * After this returns, the smem.resolve_look_at_atom_addrs[] array contains valid MIPS atom pointers + * for the frame-time bundle helper to emit via tb_emit(tb, captured_addr). + * + * 7 atoms are within hello_camera.atom.c: + * 0: resolve_look_at__input_and_sub_proc + * 1: resolve_look_at__normalize_fwd_to_uz_proc + * 2: resolve_look_at__cross_uz_up_in_to_right_proc + * 3: resolve_look_at__normalize_right_to_ux_proc + * 4: resolve_look_at__cross_uz_ux_to_up_proc + * 5: resolve_look_at__normalize_up_to_uy_proc + * 6: resolve_look_at__populate_and_translate_proc + * + * (gte.atom.c contains only normalize_v3s4_proc — bundle-specific scratch layout is no longer exposed to the GTE primitives file.) + * + * GPR pool per atom: 10 free GPRs (R_T0..R_T3 + R_T5..R_T7 + R_V0 + R_V1 + R_AT). + * R_T4 is reserved as the wave-context carrier (R_ResolveScratch). + */ +internal void resolve_look_at_init(void) { + /* Wrap the static arena in a MipsAtomBuilder. */ + MipsAtomBuilder_R ab = & smem.resolve_look_at_ab_static; + ab->start = u4_(smem.resolve_look_at_arena); + ab->capacity = ResolveLookAtArena_Words; + ab->used = 0; + + /* Atom 0: resolve_look_at__input_and_sub — stages eye/up_in into scratchpad, + * computes fwd = target - eye; binds R_ResolveScratch (R_T4) as the wave-context carrier for atoms 1-6. + * The body hardcodes R_AT and R_V0 as eye.y/eye.z temps (the existing sub_u(eye.x, eye.y, eye.z) chain from the prior Task 12.7 design). */ + smem.resolve_look_at_atom_addrs[0] = (MipsAtom*)u4_v(ab->start + ab->used * sizeof(U4)); + resolve_look_at__input_and_sub_proc(ab, + R_T0, /* r_target_ptr (popped from tape) */ + R_T1, /* r_eye_ptr (popped from tape) */ + R_T2, /* r_up_in_ptr (popped from tape) */ + R_ResolveScratch, /* r_scratch (wave-context carrier; popped from tape) */ + R_T3, /* r_tmp0 */ + R_T5, /* r_tmp1 */ + R_T6, /* r_tmp2 */ + R_T7); /* r_tmp3 */ + + /* Atom 1: resolve_look_at__normalize_fwd_to_uz — src=scratch+0, dst=scratch+16 (HARDCODED in body). + * GPR pool: r_scratch (R_T4 carrier) + 10 body GPRs = 11. + * r_a/r_b (R_T0/R_T1) : src/dst pointers (r_a overlaps r_recip_est after the loads) + * r_e/r_f/r_i (R_T2/R_T3/R_T5) : src.x/y/z → result.x/y/z + * r_d/r_g (R_T6/R_T7) : MAC1/2 scratch (dead after stage 2) + * r_h (R_V0) : LZCR + * r_recip_est (R_V1), r_shift (R_AT) : saved throughout */ + smem.resolve_look_at_atom_addrs[1] = (MipsAtom*)u4_v(ab->start + ab->used * sizeof(U4)); + resolve_look_at__normalize_fwd_to_uz_proc(ab, + R_ResolveScratch, /* r_scratch (wave-context carrier; src/dst base) */ + R_T0, R_T1, /* r_a, r_b (src/dst ptrs) */ + R_T2, R_T3, R_T5, /* r_e, r_f, r_i (src components) */ + R_T6, R_T7, /* r_d, r_g (MAC scratch) */ + R_V0, /* r_h (LZCR) */ + R_V1, /* r_recip_est */ + R_AT); /* r_shift */ + + /* Atom 2: resolve_look_at__cross_uz_up_in_to_right — a=scratch+16, b=scratch+128, + * out=scratch+32 (HARDCODED in body). GPR pool: r_scratch + 7 body + R_AT + R_V0 = 10. */ + smem.resolve_look_at_atom_addrs[2] = (MipsAtom*)u4_v(ab->start + ab->used * sizeof(U4)); + resolve_look_at__cross_uz_up_in_to_right_proc(ab, + R_ResolveScratch, /* r_scratch (wave-context carrier; src/dst base) */ + R_T0, R_T1, R_T2, /* r_a, r_b, r_c (a.x/y/z → out.x/y/z) */ + R_T3, /* r_d (b.x) */ + R_T5, /* r_f (out ptr = scratch+32) */ + R_T6, /* r_g (a ptr = scratch+16) */ + R_T7); /* r_h (b ptr = scratch+128) */ + + /* Atom 3: resolve_look_at__normalize_right_to_ux — src=scratch+32, dst=scratch+48 (HARDCODED). */ + smem.resolve_look_at_atom_addrs[3] = (MipsAtom*)u4_v(ab->start + ab->used * sizeof(U4)); + resolve_look_at__normalize_right_to_ux_proc(ab, + R_ResolveScratch, + R_T0, R_T1, + R_T2, R_T3, R_T5, + R_T6, R_T7, + R_V0, + R_V1, + R_AT); + + /* Atom 4: resolve_look_at__cross_uz_ux_to_up — a=scratch+16, b=scratch+48, out=scratch+64 (HARDCODED). */ + smem.resolve_look_at_atom_addrs[4] = (MipsAtom*)u4_v(ab->start + ab->used * sizeof(U4)); + resolve_look_at__cross_uz_ux_to_up_proc(ab, + R_ResolveScratch, + R_T0, R_T1, R_T2, + R_T3, + R_T5, /* r_f (out ptr = scratch+64) */ + R_T6, /* r_g (a ptr = scratch+16) */ + R_T7); /* r_h (b ptr = scratch+48) */ + + /* Atom 5: resolve_look_at__normalize_up_to_uy — src=scratch+64, dst=scratch+80 (HARDCODED). */ + smem.resolve_look_at_atom_addrs[5] = (MipsAtom*)u4_v(ab->start + ab->used * sizeof(U4)); + resolve_look_at__normalize_up_to_uy_proc(ab, + R_ResolveScratch, + R_T0, R_T1, + R_T2, R_T3, R_T5, + R_T6, R_T7, + R_V0, + R_V1, + R_AT); + + /* Atom 6: resolve_look_at__populate_and_translate — write look_at->m[][] from ux/uy/uz (computed from r_scratch+offset internally), + then compute translation column t[] = R * (-eye). GPR pool: r_look_at + r_scratch + 4 ptr regs + 3 tmp regs = 9. */ + smem.resolve_look_at_atom_addrs[6] = (MipsAtom*)u4_v(ab->start + ab->used * sizeof(U4)); + resolve_look_at__populate_and_translate_proc(ab, + R_T0, /* r_look_at (popped from tape; MT3_S2S4*) */ + R_ResolveScratch, /* r_scratch (wave-context carrier) */ + R_T1, R_T3, R_T5, R_T7, /* r_pux, r_puy, r_puz, r_peye */ + R_T2, R_T6, R_V0); /* r_tmp0, r_tmp1, r_tmp2 */ + + /* Sanity check: arena didn't overflow. */ + assert(ab->used <= ResolveLookAtArena_Words); +} + +/* Emit the resolve_look_at bundle into the tape. Called once per frame from update(). + * The 7 chain atoms are pre-built at init time (resolve_look_at_init) and referenced by address via smem.resolve_look_at_atom_addrs[]. + * Per-frame work: 7 tb_emit (atom pointer emissions) + 5 tb_data (C-side pointers for atom 0 + look_at for atom 6). + * + * Binds_ contract (the field-name labels are for human readability): + * Atom 0 input_and_sub target(4) eye(4) up_in(4) scratch_base(4) = 4 words + * Atoms 1-5 (no tape data — atom uses r_scratch + offset internally) + * Atom 6 populate_and_translate look_at(4) = 1 word + * ---- + * 5 tb_data words total per frame. + */ +I_ void resolve_look_at( + TapeBuilder_R tb + , MT3_S2S4* look_at + , P3_S4* eye + , P3_S4* target + , V3_S4* up_in +){ + /* Atom 0: input_and_sub — stages eye/up_in into scratchpad + computes fwd. */ + tb_emit(tb, smem.resolve_look_at_atom_addrs[0]); { + tb_data(tb, u4_(target)); /* Binds_ResolveLookAtSub.target (C-side P3_S4*) */ + tb_data(tb, u4_(eye)); /* Binds_ResolveLookAtSub.eye (C-side P3_S4*) */ + tb_data(tb, u4_(up_in)); /* Binds_ResolveLookAtSub.up_in (C-side V3_S4*) */ + tb_data(tb, u4_(smem.scratchpad)); /* Binds_ResolveLookAtScratch.scratch_base */ + } + + /* Atoms 1-5: NO tb_data — each chain atom uses r_scratch + hardcoded_offset internally (no tape-data pointers between atoms). + Context carrier R_ResolveScratch (R_T4) is preserved across atoms. */ + tb_emit(tb, smem.resolve_look_at_atom_addrs[1]); { } + tb_emit(tb, smem.resolve_look_at_atom_addrs[2]); { } + tb_emit(tb, smem.resolve_look_at_atom_addrs[3]); { } + tb_emit(tb, smem.resolve_look_at_atom_addrs[4]); { } + tb_emit(tb, smem.resolve_look_at_atom_addrs[5]); { } + + /* Atom 6: populate_and_translate — only output pointer is the matrix destination. */ + tb_emit(tb, smem.resolve_look_at_atom_addrs[6]); { + tb_data(tb, u4_(look_at)); /* Binds_ResolveLookAtPopAndTrans.look_at (MT3_S2S4*) */ + } +} + FI_ void camera_look_at_c11(Camera* c, P3_S4* target, V3_S4* up_in) { resolve_look_at_c11(& c->look_at, & c->pos, target, up_in); } GCC_OPTIMIZATION_DISABLE @@ -172,71 +337,19 @@ void update(PrimitiveArena* pa, U4* ordering_buf) S4 flag; //???? // Camera Look at - if (0) + if (1) { camera_look_at_c11(& smem.cam, & smem.cube.pos, & v3s4(0, -fp_one, 0)); } // Camera look at (Tape) - if (1) { MT3_S2S4* look_at = & smem.cam.look_at; P3_S4* eye = & smem.cam.pos; - V3_S4* up_in = & v3s4(0, -fp_one, 0); - - V3_S4 right, up, forward; - V3_S4 ux, uy, uz; - V3_S4 pos, off; + V3_S4* up_in = & v3s4(0, -fp_one, 0); tb.used = 0; tb_scope_run(& tb) { - // tb_emit_bundle(resolve_look_at); - { - tb_emit_(resolve_look_at); { - tb_data_(look_at, & smem.cam.look_at); - tb_data_(eye, & smem.cam.pos); - tb_data_(target, & smem.cube.pos); - tb_data_(up_in, up_in); - // tb_emit(a_normalize_v3s4(/*Todo: resolve dependent register allocation*/)); - // tb_data_(fwd_out); - } - #if 0 - { - tb_emit_(resolve_look_at__resolve_right); { - //... - tb_emit_(a_normalize_v3s4(...)); - tb_data_(right_out); - } - tb_emit(resolve_look_at__resolve_up); { - //... - tb_emit_(ac_normalize_v3s4(...)); - tb_data_(up_out); - } - tb_emit(world_to_cam_expand_mt3_s2s4(...)); { - tb_data(look_at, & smem.cam.look_at); - } - tb_emit_(resolve_look_at__final); { - } - } - #endif - } + resolve_look_at(& tb, & smem.cam.look_at, & smem.cam.pos, & smem.cube.pos, & v3s4(0, -fp_one, 0)); } - - // forward = target[0]; sub_v3s4(& forward, eye[0]); // RGA(Lengyel): Affine point - point = zero-weight direction. - // normalize_v3s4(& forward, & uz); // RGA(Lengyel): Normalize the direction bulk. Not finite-point unitization. - - cross_v3s4(& uz, up_in, & right); normalize_v3s4(& right, & ux); // RGA(Lengyel): Complement(Wedge(forward, up_in)) -> right axis. - cross_v3s4(& uz, & ux, & up); normalize_v3s4(& up, & uy); // RGA(Lengyel): Complement(Wedge(forward, right)) -> up axis. - - // RGA(Lengyel): matrix expansion of the world-to-camera rotation (basis rows). - look_at->m[0][0] = ux.x; look_at->m[0][1] = ux.y; look_at->m[0][2] = ux.z; - look_at->m[1][0] = uy.x; look_at->m[1][1] = uy.y; look_at->m[1][2] = uy.z; - look_at->m[2][0] = uz.x; look_at->m[2][1] = uz.y; look_at->m[2][2] = uz.z; - - pos = eye[0]; mul_v3s4(& pos, v3s4(-1,-1,-1)); // RGA(Lengyel): -eye in world coordinates (spatial bulk only; implicit weight is dropped). - - // RGA(Lengyel): R * (-eye) -- full matrix translation column. - // Motor translator would store half this displacement in m.xyz; GTE consumes full column. - mul_m3s2_v3s4(look_at, & pos, & off); - trans_m3s2( look_at, & off); } // Draw cube @@ -273,7 +386,7 @@ void update(PrimitiveArena* pa, U4* ordering_buf) tb_data(& tb, u4_(& pa->used)); tb_data(& tb, prim_base); } - tape_run(tb_slice(tb)); + tape_run_a02_s07(tb_slice(tb));// Fire off the tape (bigger-clobber variant). // smem.cube.rot.y += 30; } @@ -315,7 +428,7 @@ void update(PrimitiveArena* pa, U4* ordering_buf) tb_data(& tb, u4_(& pa->used)); tb_data(& tb, prim_base); } - tape_run(tb_slice(tb));// Fire off the tape. + tape_run_a02_s07(tb_slice(tb));// Fire off the tape (bigger-clobber variant). // C-side state (pa->used) has already been updated by the tape! // smem.floor.rot.y += 5; @@ -365,6 +478,10 @@ int main(void) reset_graph(0); /* Direct BIOS: poll both ports during VBlank. */ pad_bios_init_start(& smem.pad_raw[0], & smem.pad_raw[1]); + + /* Pre-build the resolve_look_at bundle atoms into the static arena. */ + resolve_look_at_init(); + /* Pinned registers for the GPU init atom. */ register U4* io_base_addr rgcc(R_IO_BaseAddr) = u4_r(IO_BASE_ADDR); register DoubleBuffer* screen_buf rgcc(R_ScreenBuf) = & smem.screen_buf; diff --git a/code/hello_joypad/hello_joypad.atom.c b/code/hello_joypad/hello_joypad.atom.c index e276f96..0518ba1 100644 --- a/code/hello_joypad/hello_joypad.atom.c +++ b/code/hello_joypad/hello_joypad.atom.c @@ -24,8 +24,8 @@ ATOM_FILE_DEBUGGER_LINE_MARKER(hello_joypad_atom_c); #pragma region MACs (Mips Atom components) -FI_ Slice_MipsCode ac_put_disp_env(U4 reg_transfer, U4 reg_base, U2 port) -MipsAtomComp_Proc_(ac_put_disp_env, { +FI_ Slice_MipsCode ac_put_disp_env(MipsAtomBuilder_R ab, U4 reg_transfer, U4 reg_base, U2 port) +MipsAtomComp_Proc_(ac_put_disp_env, ab, { // Emits 5 GP0 commands for buffer 0 (display_area = (0,0,320,240)). // Sequence per libpsyx PutDispEnv: DrawArea TL → DrawArea BR → Mask → DrawArea TL → DrawArea BR mac_gcmd_push(gp0_word_draw_area_top_left_origin, reg_transfer, reg_base, port), @@ -35,8 +35,8 @@ MipsAtomComp_Proc_(ac_put_disp_env, { mac_gcmd_push(gp0_word_draw_area_bottom_right_320x240, reg_transfer, reg_base, port), }) -FI_ Slice_MipsCode ac_put_draw_env(U4 reg_transfer, U4 reg_base, U2 port) -MipsAtomComp_Proc_(ac_put_draw_env, { +FI_ Slice_MipsCode ac_put_draw_env(MipsAtomBuilder_R ab, U4 reg_transfer, U4 reg_base, U2 port) +MipsAtomComp_Proc_(ac_put_draw_env, ab, { /* * ORIGIN: each code word corresponds to the EXACT value libpsyx's PutDrawEnv function would compute for the same DrawEnv settings. * References: @@ -116,7 +116,7 @@ internal MipsAtom_(screen_env_init) atom_info(atom_phase(screen_init) store_word(R_0, R_ScreenBuf, O_(DisplayEnv,vinterlace) + OA_(DoubleBuffer,display,1)), mac_store_rects2(R_0, R_ScreenY, R_ScreenX, R_ScreenY, R_ScreenBuf, O_(DrawEnv,clip_area) + OA_(DoubleBuffer,draw,0)), /* draw[0].clip_area = (0, 240, 320, 240). C11's SetDefDrawEnv writes clip.y = y_arg. */ - mac_store_v2s2( R_0, R_ScreenY, R_ScreenBuf, O_(DrawEnv,drawing_offset[0]) + OA_(DoubleBuffer,draw,0)), /* draw[0].drawing_offset[0] = (0, 240); C11 passes y_arg as ofs. */ + mac_store_v2s2(R_0, R_ScreenY, R_ScreenBuf, O_(DrawEnv,drawing_offset[0]) + OA_(DoubleBuffer,draw,0)), /* draw[0].drawing_offset[0] = (0, 240); C11 passes y_arg as ofs. */ mac_store_v2s2(R_ScreenX, R_ScreenY, R_ScreenBuf, O_(DrawEnv,clip_area.width) + OA_(DoubleBuffer,draw,1)), @@ -129,7 +129,7 @@ internal MipsAtom_(screen_env_init) atom_info(atom_phase(screen_init) store_word(R_0, R_ScreenBuf, O_(DrawEnv,texture_window.width) + OA_(DoubleBuffer,draw,1)), /* draw[0].texture_page = 10 (gp0_tpage_default). C11 SetDefDrawEnv at C11_only.elf:0x8001273C writes the same 0x0A. . */ - add_ui(R_T0, R_0, gp0_tpage_default), + add_ui(R_T0, R_0, gp0_tpage_default), store_half(R_T0, R_ScreenBuf, O_(DrawEnv,texture_page) + OA_(DoubleBuffer,draw,0)), store_half(R_T0, R_ScreenBuf, O_(DrawEnv,texture_page) + OA_(DoubleBuffer,draw,1)), @@ -144,7 +144,7 @@ internal MipsAtom_(screen_env_init) atom_info(atom_phase(screen_init) store_byte(R_T0, R_ScreenBuf, O_(DrawEnv,enable_auto_clear) + OA_(DoubleBuffer,draw,1)), /* draw[0].initial_bg_color = (r=7, g=7, b=7). */ - add_ui(R_T0, R_0, 7), + add_ui(R_T0, R_0, 7), mac_store_rgb8(R_T0,R_T0,R_T0, R_ScreenBuf, O_(DrawEnv,initial_bg_color) + OA_(DoubleBuffer,draw,0)), mac_store_rgb8(R_T0,R_T0,R_T0, R_ScreenBuf, O_(DrawEnv,initial_bg_color) + OA_(DoubleBuffer,draw,1)), @@ -228,7 +228,7 @@ MipsAtom_(cube_g4_face) atom_info(atom_phase(cube_g4), gte_mv_from_data_r(R_T0, C2_MAC0), nop, branch_le_zero(R_T0, atom_offset(cull, cube_g4_face_exit)), /* BD-slot: write the prim tag (R_0=0; overwrites the legacy tag word in the prim_buffer). - * If branch IS taken (face culled), the body is skipped and this 0-tag is stranded — + * If branch IS taken (face culled), the body is skipped and this 0-tag is stranded — * harmless because the OT entry that points to this prim is created later, only on the body path. */ store_word(R_0, R_PrimCursor, O_(Poly_G4, tag)), shift_lleft(R_AT, R_T3, v3s2_byteoff), add_u(R_AT, R_AT, R_VertBase), @@ -286,14 +286,14 @@ MipsAtom_(floor_f3_face) atom_info(atom_phase(floor_f3) , atom_reads( R_PrimCursor, R_FaceCursor, R_VertBase, R_OtBase) , atom_writes(R_PrimCursor, R_FaceCursor) ) { - mac_load_tri_indices( R_FaceCursor, R_T0, R_T1, R_T2), + mac_load_tri_indices(R_FaceCursor, R_T0, R_T1, R_T2), mac_gte_load_tri_verts(R_VertBase, R_T0, R_T1, R_T2), nop2, gte_cmdw_rotate_translate_perspective_triple, // 2 nops retire the final cpu -> gte writes before RTPT gte_cmdw_nclip, /* Culling (Branch forward if Backface) */ gte_mv_from_data_r(R_T0, C2_MAC0), - nop, branch_le_zero(R_T0, atom_offset(culling, floor_f3_face_exit)), nop, // required gte -> cpu load-delay slot. + nop, branch_le_zero(R_T0, atom_offset(culling, floor_f3_face_exit)), nop, // required gte -> cpu load-delay slot. /* Format Primitive */ mac_gte_store_f3(R_PrimCursor), diff --git a/code/hello_joypad/sio.tape.c b/code/hello_joypad/sio.tape.c index 22144eb..fe36861 100644 --- a/code/hello_joypad/sio.tape.c +++ b/code/hello_joypad/sio.tape.c @@ -24,8 +24,8 @@ * Emits 9 instructions (status/buttons/axes/attempt stores plus the * two-instruction zero-extended buttons load). */ -FI_ Slice_MipsCode ac_pad_sio_write_pad_state(U4 status_val, U4 state_ptr_reg, U4 scratch_reg) -MipsAtomComp_Proc_(ac_pad_sio_write_pad_state, { +FI_ Slice_MipsCode ac_pad_sio_write_pad_state(MipsAtomBuilder_R ab, U4 status_val, U4 state_ptr_reg, U4 scratch_reg) +MipsAtomComp_Proc_(ac_pad_sio_write_pad_state, ab, { add_ui(scratch_reg, R_0, status_val), store_word(scratch_reg, state_ptr_reg, O_(PadState,status)), /* FIX 2026-08-02: buttons = 0x0000FFFF = "no buttons pressed" in diff --git a/scripts/passes/auto_reg.lua b/scripts/passes/auto_reg.lua new file mode 100644 index 0000000..129f489 --- /dev/null +++ b/scripts/passes/auto_reg.lua @@ -0,0 +1,322 @@ +--- passes/auto_reg.lua — Per-phase automatic GPR allocator + gen/auto_reg.h emitter. +--- +--- Reads the per-source + corpus-level `atom_auto_regs` + `phase_auto_regs` registries populated by `passes/scan_source.lua`. +--- Runs a deterministic first-fit allocator in the `R_T0..R_T7 + R_V0..R_V1` pool (10 physical GPRs). +--- Emits one `#define R__Code R_Tn_Code` per marker into per-directory `gen/auto_reg.h`. +--- +--- User-pinned GPRs (added 2026-08-10): The corpus's `register_alias_registry` is consulted to +--- exclude GPRs the user has pinned via `atom_reg` + `_Code` defs (e.g. wave-context carriers like +--- `R_ResolveScratch = R_T4 atom_reg`). These GPRs are unavailable to EVERY atom's source pool, +--- not just to atoms in the same phase — wave-context carriers are preserved across atoms by the +--- wave-context discipline and must never be reallocated. +--- Per-atom body parsing also catches alias references (R_) and hardcoded R_Tn references, +--- so the user can write either `R_T4` or `R_ResolveScratch` in an atom body and the pass will +--- exclude R_T4 from that atom's pool. +--- +--- Conflict detection: If the user hardcodes `R_Tn` in an atom body that shares a phase with an auto-reg that picked `R_Tn`, +--- emit `phase_register_clash` as an info finding (no build stop). Should be unreachable after the +--- user-pinning + body-parsing fix above; kept as a defensive safety net. +--- +--- Pool exhaustion: if a phase declares more `R_` mappings than the 10-register pool can hold, +--- emit `phase_register_pool_exhausted` as a build-stopping error. +--- +--- @class AutoRegResult +--- @field outputs table[] -- {kind=, path=} entries +--- @field errors table[] -- {line=, msg=} entries (build-stops) +--- @field warnings table[] -- {line=, msg=} entries (build-continues) + +local _bootstrap_dir = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "./" +local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua") + +-- The fixed allocation pool: 10 physical GPRs whose `R__Code` macros exist in mips.h (lines 92-107). +-- Each pool entry is the PHYSICAL GPR ident (R_T0 etc.); +-- `gpr .. "_Code"` resolves to the matching `R_Tn_Code` constant the source code references via `#define R_Load_Code R_T0_Code`. +-- Excluded: R_AT (assembler temp per lottes_tape.h:86), R_T8 (deferred to ac_yield_load pattern), +-- R_T9 (R_TapePtr; owned by the tape runtime). +local POOL = { + "R_T0", "R_T1", "R_T2", "R_T3", + "R_T4", "R_T5", "R_T6", "R_T7", + "R_V0", "R_V1", +} + +-- Map from integer MIPS GPR code (the `code` field on AliasEntry) to the physical GPR ident +-- in POOL. The standard MIPS O32 ABI register numbering matches mips.h's R_*_Code #defines +-- (mips.h:92-123). Only the POOL entries matter for auto_reg — non-pool aliases are out of scope. +local INT_CODE_TO_POOL_GPR = { + [2] = "R_V0", [3] = "R_V1", + [8] = "R_T0", [9] = "R_T1", [10] = "R_T2", [11] = "R_T3", + [12] = "R_T4", [13] = "R_T5", [14] = "R_T6", [15] = "R_T7", +} + +-- Stable sort for deterministic allocation order. +local function stable_sort_keys(tbl) + local keys = {} + for k in pairs(tbl) do keys[#keys + 1] = k end + table.sort(keys) + return keys +end + +-- Allocate one phase's auto-reg mappings. +-- Returns (allocated_map, errors). On pool exhaustion, errors is populated and the function halts. +local function allocate_phase(phase_label, decls) + -- Deep-copy POOL into a fresh sequence table. The original `table.unpack and table.unpack(POOL) or { unpack(POOL) }` + -- idiom wraps the unpacked values in a single inner table under LuaJIT 5.1 (`table.unpack` is nil; the `or` returns one value), + -- which corrupts the pool into `{ {R_T0, R_T1, ...} }` — making `table.remove(pool, 1)` return the inner table on iteration. + local pool = {} + for i = 1, #POOL do pool[i] = POOL[i] end + local result = {} + local errors = {} + for _, sym in ipairs(stable_sort_keys(decls)) do + local next_gpr = table.remove(pool, 1) + if not next_gpr then + errors[#errors + 1] = { + line = 0, + msg = string.format( + "phase_register_pool_exhausted: phase '%s' requested symbol '%s' but the pool has no remaining registers (max 10 per phase: R_T0..R_T7 + R_V0..R_V1). Split the phase or use hardcoded GPRs." + , phase_label, sym), + } + return result, errors + end + result[sym] = next_gpr + end + return result, errors +end + +-- Build two projections from corpus.register_alias_registry: +-- user_pinned -- { [physical_gpr_ident] = true } -- GPRs unavailable to auto_reg globally +-- -- (wave-context carriers, file-scope pinned aliases) +-- alias_to_gpr -- { [alias_ident] = physical_gpr_ident } -- for body parsing +-- Both projections are derived from the same set of entries: every AliasEntry in +-- register_alias_registry has `has_atom_reg = true` (only those entries are added to the +-- registry; see passes/scan_source.lua parse_enum_entry). Each entry's `code` is the integer +-- MIPS GPR number (0..31); INT_CODE_TO_POOL_GPR translates it back to the physical GPR ident. +-- Aliases whose `code` points to a non-POOL GPR (e.g. R_S0, R_T8, R_K1) are ignored — they +-- don't affect the auto_reg pool, and they're already excluded from POOL above. +local function build_user_pins(corpus) + local user_pinned = {} + local alias_to_gpr = {} + if not corpus.register_alias_registry then + return user_pinned, alias_to_gpr + end + for alias_name, alias_entry in pairs(corpus.register_alias_registry) do + if alias_entry.has_atom_reg and alias_entry.code then + local gpr = INT_CODE_TO_POOL_GPR[alias_entry.code] + if gpr then + user_pinned[gpr] = true + alias_to_gpr[alias_name] = gpr + end + end + end + return user_pinned, alias_to_gpr +end + +-- Find every physical GPR referenced in the atom body, via EITHER: +-- (a) a hardcoded physical GPR ident (R_T\d+|R_V\d+|R_A\d+|R_S\d+) — the existing regex; +-- (b) an alias ident (R_) resolved via alias_to_gpr back to its physical GPR ident. +-- Returns { [physical_gpr_ident] = count }. The clash-detection and source-pool-exclusion logic +-- only needs the presence of each GPR (boolean test), but keeping the count preserves the +-- original find_hardcoded_rn shape so callers can switch without churn. +-- The alias pattern is sorted lexicographically to keep the regex deterministic. +local function find_used_gprs(body_text, alias_to_gpr) + local found = {} + -- (a) Hardcoded physical GPRs (R_T0..R_T7, R_V0..R_V1, R_A0..R_A3, R_S0..R_S7). + for gpr in body_text:gmatch("(R_T%d+|R_V%d+|R_A%d+|R_S%d+)") do + found[gpr] = (found[gpr] or 0) + 1 + end + -- (b) Alias references (R_) resolved to physical GPRs via the registry. + -- Sorted by name so the regex is byte-stable across runs. + if alias_to_gpr and next(alias_to_gpr) then + local aliases = {} + for alias_name in pairs(alias_to_gpr) do + aliases[#aliases + 1] = alias_name + end + table.sort(aliases) + local pattern = "(" .. table.concat(aliases, "|") .. ")" + for alias_name in body_text:gmatch(pattern) do + local gpr = alias_to_gpr[alias_name] + if gpr and not found[gpr] then + found[gpr] = 1 + end + end + end + return found +end + +-- Emit one gen/auto_reg.h header per directory. +local function emit_auto_reg_h(out_dir, dir, sources, mappings) + if not mappings or next(mappings) == nil then return end + local out_path = out_dir .. "/" .. "auto_reg.h" + duffle.ensure_dir(out_dir) + local lines = { + "#ifdef INTELLISENSE_DIRECTIVES", + "#pragma once", + "#endif", + "// Auto-generated by ps1_meta.lua (passes/auto_reg.lua) — DO NOT EDIT", + "// Directory: " .. dir:gsub("/", "\\"), + } + for _, src in ipairs(sources) do + lines[#lines + 1] = "// source: " .. src.path + end + lines[#lines + 1] = "// Per-phase register allocations resolved by the lua pass." + lines[#lines + 1] = "// R__Code = for every marker in this directory." + lines[#lines + 1] = "" + for _, sym in ipairs(stable_sort_keys(mappings)) do + local gpr = mappings[sym] + local gpr_code = gpr .. "_Code" + lines[#lines + 1] = "#define " .. sym .. "_Code " .. gpr_code + end + lines[#lines + 1] = "" + duffle.write_file_lf(out_path, table.concat(lines, "\n") .. "\n") + print(" -> " .. out_path) + return out_path +end + +-- ════════════════════════════════════════════════════════════════════════════ +-- Pass entry +-- ════════════════════════════════════════════════════════════════════════════ + +local M = {} + +--- @param ctx PassCtx +--- @return AutoRegResult +function M.run(ctx) + local outputs = {} + local errors = {} + local warnings = {} + + local corpus = ctx.shared and ctx.shared.corpus + if type(corpus) ~= "table" then + error("auto_reg.run requires ctx.shared.corpus", 0) + end + + -- 0. Build the user-pinned GPR exclusion set + alias-to-GPR resolution map. + -- Wave-context carriers (e.g. `R_ResolveScratch = R_T4 atom_reg` in + -- hello_camera.atom.c) MUST NOT be allocated to any auto-reg marker — they're + -- preserved across atoms by the wave-context discipline. The corpus's + -- register_alias_registry is the source of truth for these opt-in pins. + -- Body references to those aliases (via alias_to_gpr) are also excluded on a + -- per-atom basis in step 2 below. + local user_pinned, alias_to_gpr = build_user_pins(corpus) + + -- 1. Allocate phase pools first (phase declarations take precedence over per-atom declarations). + local phase_allocations = {} + for phase_label, decls in pairs(corpus.phase_auto_regs or {}) do + local mapping, errs = allocate_phase(phase_label, decls) + for sym, gpr in pairs(mapping) do + phase_allocations[phase_label] = phase_allocations[phase_label] or {} + phase_allocations[phase_label][sym] = gpr + end + for _, e in ipairs(errs) do + errors[#errors + 1] = e + end + end + + -- 2. Allocate per-atom auto-regs. If the atom scope matches a phase, reuse the phase pool. + -- Otherwise, allocate a private pool for the atom. + -- The phase membership is in `corpus.atom_phases[phase_label].atoms` (an array of atom names declared via `atom_phase()` in the atom's `atom_info` line). + -- Build a reverse map `atom_name -> phase_label` so the lookup is O(1) per atom scope. + local atom_name_to_phase = {} + for phase_label, entry in pairs(corpus.atom_phases or {}) do + for _, atom_name in ipairs(entry.atoms or {}) do + atom_name_to_phase[atom_name] = phase_label + end + end + + local atom_allocations = {} + for atom_scope, decls in pairs(corpus.atom_auto_regs or {}) do + local phase_label = atom_name_to_phase[atom_scope] + -- Build the atom's source pool: start with the full POOL, subtract: + -- (a) every GPR already committed (phase allocations + prior atom allocations) + -- (b) every USER-PINNED GPR (wave-context carriers + file-scope pinned aliases) + -- (c) every GPR referenced in the atom's body — either hardcoded R_X or alias R_Xxx + -- (the latter resolved via alias_to_gpr; this catches cases where the user + -- wrote R_ResolveScratch instead of R_T4 directly) + -- Atoms whose scope matches a phase share the global pool with the phase allocations; + -- the original `source_pool = phase_allocations[phase_label]` form used the phase + -- allocation MAP as a pool, but that map has no array part, so `table.remove(source_pool, 1)` + -- returned nil and every atom-with-phase marker errored with `phase_register_pool_exhausted`. + local used = {} + for _, m in pairs(phase_allocations) do for _, gpr in pairs(m) do used[gpr] = true end end + for _, m in pairs(atom_allocations) do for _, gpr in pairs(m) do used[gpr] = true end end + -- (c) Body references — scan the atom body for hardcoded + alias-resolved GPRs. + -- Folded into `used` so the source_pool exclusion is a single check. + local atom = corpus.atoms_by_name and corpus.atoms_by_name[atom_scope] + if atom and atom.body then + local body_used = find_used_gprs(atom.body, alias_to_gpr) + for gpr in pairs(body_used) do used[gpr] = true end + end + local source_pool = {} + for _, gpr in ipairs(POOL) do + -- Exclude (a) prior commitments, (b) USER-PINNED GPRs (wave-context carriers + -- declared via atom_reg + _Code defs, preserved across atoms globally). + if not used[gpr] and not user_pinned[gpr] then + source_pool[#source_pool + 1] = gpr + end + end + local result = {} + for _, sym in ipairs(stable_sort_keys(decls)) do + local next_gpr = table.remove(source_pool, 1) + if not next_gpr then + errors[#errors + 1] = { + line = 0, + msg = string.format("phase_register_pool_exhausted: atom '%s' requested symbol '%s' but no free registers remain in its scope pool." + , atom_scope, sym), + } + else + result[sym] = next_gpr + end + end + atom_allocations[atom_scope] = result + end + + -- 3. Conflict-with-hardcoded detection (defensive — should be unreachable now). + -- The source_pool exclusion in step 2 (b) + (c) already accounts for both user-pinned GPRs + -- and body-referenced GPRs (hardcoded R_Tn OR alias R_). An auto-reg allocation that + -- matched an existing body reference would be impossible by construction. This warning is kept + -- as a defensive safety net for cases the body scanner might miss (e.g. macros that expand to + -- register references the scanner cannot resolve). + -- For each resolved (scope, sym) -> R_Tn mapping, scan the atom body source for used GPRs. + for atom_scope, decls in pairs(atom_allocations) do + local atom = corpus.atoms_by_name and corpus.atoms_by_name[atom_scope] + if atom and atom.body then + local used_in_body = find_used_gprs(atom.body, alias_to_gpr) + for sym, allocated_gpr in pairs(decls) do + if used_in_body[allocated_gpr] and used_in_body[allocated_gpr] > 0 then + warnings[#warnings + 1] = { + line = atom.line or 0, + msg = string.format("phase_register_clash: atom '%s' has hardcoded '%s' in its body AND an auto-reg marker '%s' that was allocated to '%s' (same phase). Resolve by removing the hardcoded reference or renaming the auto-reg." + , atom_scope, allocated_gpr, sym, allocated_gpr), + } + end + end + end + end + + -- 4. Emit per-directory gen/auto_reg.h. + -- For each source directory that has atom_auto_regs or phase_auto_regs entries, emit one header. + local sources_by_dir = corpus.sources_by_dir or {} + for dir, sources in pairs(sources_by_dir) do + local per_dir_mappings = {} + for _, src in ipairs(sources) do + -- Collect every (sym -> gpr) entry that originated from a source in this directory. + -- `src.scan.atom_auto_regs` is keyed by ATOM SCOPE NAME; `pairs(t)` iterates KEYS so `scope_name` here is the scope ident (e.g. "cube_g4_face"). + -- The previous `for _, scan_atom_auto` form silently assigned the VALUE (a `{sym = sym}` table) to the variable, which made `atom_allocations[scan_atom_auto]` a table-indexed lookup that never resolved. + for scope_name in pairs(src.scan and src.scan.atom_auto_regs or {}) do + for sym, gpr in pairs(atom_allocations[scope_name] or {}) do + per_dir_mappings[sym] = gpr + end + end + for scope_name in pairs(src.scan and src.scan.phase_auto_regs or {}) do + for sym, gpr in pairs(phase_allocations[scope_name] or {}) do + per_dir_mappings[sym] = gpr + end + end + end + local out_dir = dir .. "/gen" + local out_path = emit_auto_reg_h(out_dir, dir, sources, per_dir_mappings) + if out_path then outputs[#outputs + 1] = { auto_reg_h = out_path } end + end + return { outputs = outputs, errors = errors, warnings = warnings } +end + +return M diff --git a/scripts/passes/components.lua b/scripts/passes/components.lua index 8a81f7c..06bc21d 100644 --- a/scripts/passes/components.lua +++ b/scripts/passes/components.lua @@ -3,7 +3,7 @@ --- Ownership: `corpus.word_counts`, `corpus.components`, and `corpus.component_body_index`. --- Scanner owns `declaration_comment` and `debug_skip` on each declaration record; this pass projects both forward. --- ---- Reads the pre-scanned SourceScan payload from `duffle.scan_source` for `MipsAtomComp_(ac_X)` and `MipsAtomComp_Proc_(ac_X, { body })` declarations, +--- Reads the pre-scanned SourceScan payload from `duffle.scan_source` for `MipsAtomComp_(ac_X)`, `MipsAtomComp_Proc_(ac_X, { body })`, and `MipsAtom_Proc_(X, ab, { body })` declarations, --- then resolves the function-args string from the preceding `FI_ Slice_MipsCode ac_X(...)` declaration via a backward walk. --- --- Emits one `gen/macs.h` per *immediate source directory* with `#define mac_X(sig) \` macros plus `WORD_COUNT(mac_X, N)` entries for downstream offset computation. @@ -76,7 +76,7 @@ local MACS_FILENAME = "macs.h" --- @field args string|nil -- Function-args string (function form only) --- @field line integer -- Source line of the declaration --- @field comment string|nil -- Scanner-owned `declaration_comment`; the components pass reads it from the scanner record ---- @field kind string -- "comp_bare" | "comp_proc" +--- @field kind string -- "comp_bare" | "comp_proc" | "atom_proc" --- @field debug_skip boolean -- Mirror of `a.debug_skip` (scanner-owned); true iff a bare `atom_dbg_skip` marker immediately preceded the declaration -- ════════════════════════════════════════════════════════════════════════════ @@ -200,8 +200,16 @@ end local function project_components(source, scan) local out = {} for _, a in ipairs(scan.atoms) do - if a.kind == "comp_bare" or a.kind == "comp_proc" then - local args = find_function_args_for(source, a.raw_name, a.ident_pos) + if a.kind == "comp_bare" or a.kind == "comp_proc" or a.kind == "atom_proc" then + -- `MipsAtom_Proc_` atoms have no `FI_ Slice_MipsCode ac_X(...)` function-decl prelude + -- (the macro sits inside a wrapping `I_ void (...)` body), so the function-args + -- lookup is meaningless; signature defaults to `...` (variadic-ignored). + -- The `mac_` alias expansion discards the `ab` (atom-builder) arg the same way + -- `MipsAtomComp_Proc_` components do. + local args = nil + if a.kind ~= "atom_proc" then + args = find_function_args_for(source, a.raw_name, a.ident_pos) + end -- Comment ownership: scan_source.lua stamps `declaration_comment` on the record by walking backward past any associated bare marker. -- The pass reads `declaration_comment` directly. local comment = a.declaration_comment or "" @@ -213,7 +221,7 @@ local function project_components(source, scan) body_tokens = a.body_tokens, args = args, comment = comment, - kind = a.kind, -- "comp_bare" | "comp_proc"; provenance emitter reads this. + kind = a.kind, -- "comp_bare" | "comp_proc" | "atom_proc"; provenance emitter reads this. debug_skip = a.debug_skip == true, } end @@ -475,12 +483,26 @@ local function split_comment_lines(s) end --- Determine the macro signature: function-args list (function form) or variadic-ignored (bare form). +--- For `MipsAtomComp_Proc_` components, the leading `ab` (atom-builder) arg is dropped: +--- the generated `mac_` macros are inline-expansion aliases for baked atoms; their bodies +--- don't reference `ab` (the builder is only consumed by the procedural `atombuilder_unroll` line +--- that `MipsAtomComp_Proc_` appends after the body). Inline callers therefore don't need to thread +--- a builder context. --- @param args_str string|nil --- @return string local function signature_from_args(args_str) local arg_names = extract_arg_names(args_str) if arg_names and #arg_names > 0 then - return table.concat(arg_names, ", ") + -- Drop the leading `ab` (atom-builder) first arg if present. + -- Convention: `MipsAtomComp_Proc_` components always declare `ab` as the first function-arg + -- (type `MipsAtomBuilder_R`), mirroring the macro signature in `lottes_tape.h`. + if arg_names[1] == "ab" then + table.remove(arg_names, 1) + end + if #arg_names > 0 then + return table.concat(arg_names, ", ") + end + return "..." -- `ab` was the only arg; fall through to variadic end return "..." end @@ -646,7 +668,7 @@ end --- @field name string -- bare name (without ac_/mac_ prefix) --- @field line integer -- definition source line (line of `MipsAtomComp_(ac_X)` / `MipsAtomComp_Proc_(ac_X, ...)`) --- @field path string -- absolute source path of the definition ---- @field kind string -- "comp_bare" | "comp_proc" +--- @field kind string -- "comp_bare" | "comp_proc" | "atom_proc" --- @field debug_skip boolean -- mirror of the scanner-owned `a.debug_skip`; consumers read this directly --- (internal) Populate `corpus.components` with this source's components-by-name map. diff --git a/scripts/passes/emission_model.lua b/scripts/passes/emission_model.lua index 4081b2c..7d60291 100644 --- a/scripts/passes/emission_model.lua +++ b/scripts/passes/emission_model.lua @@ -188,11 +188,11 @@ function M.run(ctx) if type(corpus.source_order) ~= "table" then error("emission_model: ctx.shared.corpus.source_order is required", 0) end -- Project once, collect errors + warnings for one atom. - -- Kind must be one of: atom | raw_atom | comp_bare | comp_proc. + -- Kind must be one of: atom | atom_proc | raw_atom | comp_bare | comp_proc. local function process_atom(atom, src) if not (atom and atom.body) then return end local kind = atom.kind - if kind ~= "atom" and kind ~= "raw_atom" and kind ~= "comp_bare" and kind ~= "comp_proc" then + if kind ~= "atom" and kind ~= "atom_proc" and kind ~= "raw_atom" and kind ~= "comp_bare" and kind ~= "comp_proc" then return end local proj = project_atom(atom, src, corpus) @@ -215,7 +215,7 @@ function M.run(ctx) end -- Walk `corpus.source_order`; within each source, visit atoms followed by raw_atoms. - -- Recognized kinds (atom | raw_atom | comp_bare | comp_proc) each receive the atom.paths projection via duffle.project_emission. + -- Recognized kinds (atom | atom_proc | raw_atom | comp_bare | comp_proc) each receive the atom.paths projection via duffle.project_emission. -- Components are macros inlined into atom bodies; focused tests and isolated component analyses consume atom.paths directly. for _, src in ipairs(corpus.source_order) do local scan = src.scan or {} diff --git a/scripts/passes/scan_source.lua b/scripts/passes/scan_source.lua index 3765b43..d3f4784 100644 --- a/scripts/passes/scan_source.lua +++ b/scripts/passes/scan_source.lua @@ -3,6 +3,7 @@ --- Single source-walk pass that produces the fat `SourceScan` payload consumed by all downstream passes. Walks each corpus source record once, --- extracting every construct type the metaprograms need: --- MipsAtom_ (kind = "atom", with optional atom_info inner) +--- MipsAtom_Proc_ (kind = "atom_proc", body inside last {}) --- MipsAtomComp_ (kind = "comp_bare") --- MipsAtomComp_Proc_ (kind = "comp_proc", body inside last {}) --- atom_dbg_skip — bare whole-atom/component debug-step marker; following declaration disambiguates @@ -34,7 +35,7 @@ local parse_enum_int_literal -- ════════════════════════════════════════════════════════════════════════════ --- @class SourceScan ---- @field atoms AtomEntry[] -- MipsAtom_ + MipsAtomComp_ + MipsAtomComp_Proc_ +--- @field atoms AtomEntry[] -- MipsAtom_ + MipsAtom_Proc_ + MipsAtomComp_ + MipsAtomComp_Proc_ --- @field raw_atoms AtomEntry[] -- MipsCode code_ { body } (offsets pass only) --- @field binds BindsEntry[] -- typedef Struct_(Binds_X) { fields } (fields pre-parsed) --- @field atom_infos AtomInfoEntry[] -- MipsAtom_(name) atom_info(...) (sub-calls pre-parsed) @@ -55,7 +56,7 @@ local parse_enum_int_literal --- @field args string|nil -- Trimmed args inside the `(...)` (nil when has_parens is false) --- @field pending boolean -- true while awaiting the following declaration --- @field superseded_by_marker_line integer|nil -- set when a newer marker bumped this one out of the pending slot ---- @field target_kind string|nil -- "atom" | "comp_bare" | "comp_proc" | "unrelated" once observed (nil if no declaration ever followed) +--- @field target_kind string|nil -- "atom" | "atom_proc" | "comp_bare" | "comp_proc" | "unrelated" once observed (nil if no declaration ever followed) --- @field proc_prelude boolean|nil -- true after the marker crossed an `FI_` prelude and awaits `MipsAtomComp_Proc_` --- @class RegTypeDefault @@ -111,7 +112,7 @@ local parse_enum_int_literal --- @field name string -- Atom name (for components: without ac_ prefix) --- @field body string -- Brace-delimited body (without the braces) --- @field body_off integer -- Char offset of body[1] in source ---- @field kind string -- "atom" | "comp_bare" | "comp_proc" | "raw_atom" +--- @field kind string -- "atom" | "atom_proc" | "comp_bare" | "comp_proc" | "raw_atom" --- @field raw_name string -- Un-stripped name (for components: with ac_ prefix) --- @field ident_pos integer -- Position of the MipsAtom_/MipsAtomComp_ ident start --- @field after_paren integer -- Position past the closing paren @@ -268,7 +269,7 @@ end --- marker_kind == "atom_dbg_skip" AND is_bare == true --- Any other spelling or shape (parenthesized form, legacy name) is recorded as a raw marker for annotation validation but never stamps `debug_skip`. --- @param out SourceScan ---- @param target_kind string|nil -- "atom" | "comp_bare" | "comp_proc" | "unrelated" once observed +--- @param target_kind string|nil -- "atom" | "atom_proc" | "comp_bare" | "comp_proc" | "unrelated" once observed --- @return boolean|nil -- true iff the marker is the positive bare form local function attach_debug_skip_marker(out, target_kind) local markers = out.debug_skip_markers @@ -799,6 +800,11 @@ local BYTE_x = 0x78 -- 'x' local BYTE_X = 0x58 -- 'X' local BYTE_OPEN_BRACE = 0x7B -- '{' local BYTE_CLOSE_BRACE= 0x7D -- '}' +local BYTE_SLASH = 0x2F -- '/' +local BYTE_STAR = 0x2A -- '*' +local BYTE_SPACE = 0x20 -- ' ' +local BYTE_TAB = 0x09 -- '\t' +local BYTE_CR = 0x0D -- '\r' -- Maximum chain depth when resolving `R_*_Code` symbol RHS references. -- Eight hops is enough for any production chain (R_TapePtr_Code -> R_T8_Code -> ...). @@ -822,6 +828,44 @@ local function hex_digit_value(b) return nil end +-- Read one trailing C-comment that appears immediately after `pos` in `body`, +-- skipping horizontal whitespace and newlines first. Used by `parse_enum_entry` to +-- recover the `atom_auto_reg:` / `phase_auto_reg:` scope annotation embedded by +-- the `atom_auto_reg` / `phase_auto_reg` macros' RHS expansion +-- (`R_ = R__Code /* atom_auto_reg: */`). +-- Handles both block (`/* ... */`) and line (`// ...`) forms. +-- Returns the comment text (without delimiters), or nil if no comment is adjacent. +local function read_trailing_cmt_after(body, pos) + local body_len = #body + while pos <= body_len do + local b = body:byte(pos) + if b == BYTE_SPACE or b == BYTE_TAB or b == BYTE_NEWLINE or b == BYTE_CR then + pos = pos + 1 + elseif b == BYTE_SLASH then + local b2 = body:byte(pos + 1) + if b2 == BYTE_STAR then + -- Block comment /* ... */ + local i = pos + 2 + while i < body_len do + if body:byte(i) == BYTE_STAR and body:byte(i + 1) == BYTE_SLASH then + return body:sub(pos + 2, i - 1) + end + i = i + 1 + end + return nil -- unterminated; treat as no comment + elseif b2 == BYTE_SLASH then + -- Line comment // ... (strip the trailing newline) + local end_pos = duffle.find_byte(body, BYTE_NEWLINE, pos + 2) or (body_len + 1) + return body:sub(pos + 2, end_pos - 1) + end + return nil + else + return nil + end + end + return nil +end + --- Parse a decimal/negative-decimal/hex integer literal starting at byte position `start`. --- Returns (value, end_pos) on success, or (nil, start) on failure / no match. --- Accepts: 12, -1, 0, 0x10, 0X1F, -0x10. @@ -1128,6 +1172,46 @@ local function parse_dbg_skip_marker(source, pos, ident_end, line_of, out) return marker_end end +--- Parse `atom_auto_reg(, R_)` and `phase_auto_reg(, R_)` markers. +--- +--- The macros expand to `sym = sym##_Code` per their definition in dsl.atom.h. +--- After preprocessing, the marker renders as a full enum entry of the form `R_ = R__Code,`. +--- This parser detects the macro invocation site, extracts `(scope_name, sym)`, and stores it +--- in the per-source table (atom_auto_regs or phase_auto_regs) under the scope's name. +--- +--- @param source string +--- @param pos integer +--- @param ident_end integer +--- @param line_of fun(pos: integer): integer +--- @param out SourceScan +--- @return integer +local function parse_auto_reg_marker(source, pos, ident_end, line_of, out) + local marker_kind = source:sub(pos, ident_end - 1) -- "atom_auto_reg" or "phase_auto_reg" + local scope_kind = marker_kind == "atom_auto_reg" and "atom" or "phase" + + local inner, after_paren = read_parens_after(source, ident_end) + if not inner then return after_paren end + + local args = duffle.split_top_level_commas(inner) + local scope_name = args[1] and duffle.trim(args[1]) or nil + local sym = args[2] and duffle.trim(args[2]) or nil + + -- Filter: only accept `R_` form (matches `^R_[%w_]+$`). + if scope_name and sym and sym:match("^R_[%w_]+$") then + if scope_kind == "atom" then + out.atom_auto_regs = out.atom_auto_regs or {} + out.atom_auto_regs[scope_name] = out.atom_auto_regs[scope_name] or {} + out.atom_auto_regs[scope_name][sym] = sym + else + out.phase_auto_regs = out.phase_auto_regs or {} + out.phase_auto_regs[scope_name] = out.phase_auto_regs[scope_name] or {} + out.phase_auto_regs[scope_name][sym] = sym + end + end + + return after_paren +end + -- Parse `atom_dbg_reg_default(R_X, ...)`; -- the second argument may be a `Type` or `Type*`/`Type**` chain. Records in `out.types[R_X]`. local function parse_atom_dbg_reg_default(source, pos, ident_end, line_of, out) @@ -1282,6 +1366,49 @@ local function parse_mips_atom_comp_proc(source, pos, ident_end, line_of, out) return after_paren end +--- Parse: `MipsAtom_Proc_(, , { })` — body is inside the LAST `{` in args. +--- Per Task 12.10: full support for the runtime-proc atom form. Registers the atom +--- with kind `"atom_proc"` so offsets.lua / components.lua can emit +--- * `mac_` aliases in `gen/macs.h` (the components pass) +--- * `atom_offset__X__Y` defs in `gen/offsets.h` (the offsets pass) +--- The atom name is the FIRST ident of the args (the second arg `ab` is the +--- atom-builder, not the name). Unlike `MipsAtomComp_Proc_`, there is no `ac_` +--- prefix on the symbol — `MipsAtom_Proc_` is the runtime-proc wrapper, so the +--- symbol IS the bare atom name (e.g. `normalize_v3s4`, not `ac_normalize_v3s4`). +--- @param source string +--- @param pos integer +--- @param ident_end integer +--- @param line_of fun(pos: integer): integer +--- @param out SourceScan +--- @return integer +local function parse_mips_atom_proc(source, pos, ident_end, line_of, out) + local inner, after_paren, open_paren = read_parens_after(source, ident_end) + if not inner then return after_paren end + + -- Find the LAST `{` in inner (the body brace, not any potential embedded braces in expressions). + local last_brace_pos = nil + for search_pos = #inner, 1, -1 do + if inner:sub(search_pos, search_pos) == "{" then last_brace_pos = search_pos; break end + end + if not last_brace_pos then return after_paren end + + -- Use duffle.read_braces to find the matching close brace. + -- Uses `read_balanced` for delimiter-depth tracking. + -- If close_pos is past the end of inner, the brace didn't match (malformed input); skip. + local body, close_pos = duffle.read_braces(inner, last_brace_pos) + if close_pos > #inner + 1 then return after_paren end + + -- The atom name is the FIRST ident of the args (matches MipsAtomComp_Proc_'s "first ident" rule). + -- MipsAtom_Proc_ has no `ac_` prefix; `strip_ac_prefix` is a no-op for unprefixed names. + local raw_name = inner:match("^%s*([%w_]+)") or "?" + local name = strip_ac_prefix(raw_name) + -- Position of body[1] in source = open_paren + 1 (start of inner) + last_brace_pos + 1 (past '{'). + local body_off = open_paren + 2 + last_brace_pos + register_atom(out, "atom_proc", line_of(pos), name, body, body_off, raw_name, pos, after_paren, source) + + return after_paren +end + --- Parse: `MipsCode code_ { }` (raw atom form — offsets pass only). --- @param source string --- @param pos integer @@ -1602,6 +1729,16 @@ local function parse_enum_entry(source, body, body_offset, line_of, out, entry_n local value, value_end = parse_enum_value(body, after_ws, out) if value == nil then return value_start end + -- Capture the trailing C-comment (if any) before `skip_ws_and_cmt` discards it. + -- The `atom_auto_reg(, )` macro expands to `R_ = R__Code /* atom_auto_reg: */`, + -- so the scope name lives in the comment after the RHS value. Routes through `out.atom_entry_comments` + -- for downstream `parse_enum` to split into `out.atom_auto_regs` / `out.phase_auto_regs`. + local trailing_cmt = read_trailing_cmt_after(body, value_end) + if trailing_cmt then + out.atom_entry_comments = out.atom_entry_comments or {} + out.atom_entry_comments[entry_name] = trailing_cmt + end + local after_value = duffle.skip_ws_and_cmt(body, value_end) local has_atom_reg, end_after_atom_reg = check_bare_atom_reg(body, after_value) @@ -1657,15 +1794,24 @@ local function parse_enum_body(source, body, body_offset, line_of, out) else local entry_name, name_end = duffle.read_ident(body, pos) if entry_name then - local after_name = duffle.skip_ws_and_cmt(body, name_end) - if body:byte(after_name) == BYTE_EQUAL then - local new_pos = parse_enum_entry( - source, body, body_offset, line_of, out, - entry_name, pos, after_name + 1 - ) - if new_pos > pos then pos = new_pos else pos = after_name + 1 end + -- In-enum `atom_auto_reg(, R_)` / `phase_auto_reg(, R_)` markers: + -- the C preprocessor expands them to `R_ = R__Code /* atom_auto_reg: */`, + -- but the metaprogram reads source-as-written so we must dispatch the parser here too. + -- Mirrors the top-level `DECL_PARSERS` entry for `atom_auto_reg` / `phase_auto_reg`. + if entry_name == "atom_auto_reg" or entry_name == "phase_auto_reg" then + local new_pos = parse_auto_reg_marker(body, pos, name_end, line_of, out) + if new_pos > pos then pos = new_pos else pos = name_end end else - pos = name_end + local after_name = duffle.skip_ws_and_cmt(body, name_end) + if body:byte(after_name) == BYTE_EQUAL then + local new_pos = parse_enum_entry( + source, body, body_offset, line_of, out, + entry_name, pos, after_name + 1 + ) + if new_pos > pos then pos = new_pos else pos = after_name + 1 end + else + pos = name_end + end end else pos = pos + 1 @@ -1695,6 +1841,25 @@ local function parse_enum(source, pos, ident_end, line_of, out) if not body then return after_brace end parse_enum_body(source, body, body_off, line_of, out) + -- Route `atom_auto_reg:` / `phase_auto_reg:` markers discovered in trailing C-comments + -- into the per-source `atom_auto_regs` / `phase_auto_regs` projections. + -- Pattern matches the RHS expansion `R_ = R__Code /* _auto_reg: */` + -- emitted by the `atom_auto_reg` / `phase_auto_reg` macros in dsl.atom.h. + for entry_name, cmt_text in pairs(out.atom_entry_comments or {}) do + local atom_scope = cmt_text:match("atom_auto_reg:%s*([%w_]+)") + if atom_scope then + out.atom_auto_regs = out.atom_auto_regs or {} + out.atom_auto_regs[atom_scope] = out.atom_auto_regs[atom_scope] or {} + out.atom_auto_regs[atom_scope][entry_name] = entry_name + end + local phase_scope = cmt_text:match("phase_auto_reg:%s*([%w_]+)") + if phase_scope then + out.phase_auto_regs = out.phase_auto_regs or {} + out.phase_auto_regs[phase_scope] = out.phase_auto_regs[phase_scope] or {} + out.phase_auto_regs[phase_scope][entry_name] = entry_name + end + end + return after_brace end @@ -1708,12 +1873,18 @@ end local DECL_PARSERS = { MipsAtom_ = parse_mips_atom, + MipsAtom_Proc_ = parse_mips_atom_proc, MipsAtomComp_ = parse_mips_atom_comp, MipsAtomComp_Proc_ = parse_mips_atom_comp_proc, -- `atom_dbg_skip` is the only debug-skip parser entry. Every other -- identifier follows the ordinary unrelated-token path; there is no alias. atom_dbg_skip = parse_dbg_skip_marker, atom_dbg_reg_default = parse_atom_dbg_reg_default, + -- `atom_auto_reg(atom, R_)` and `phase_auto_reg(phase, R_)` populate per-source + -- `out.atom_auto_regs` / `out.phase_auto_regs`; the cross-source merge lands in + -- `corpus.atom_auto_regs` / `corpus.phase_auto_regs` (first-wins). + atom_auto_reg = parse_auto_reg_marker, + phase_auto_reg = parse_auto_reg_marker, MipsCode = parse_mips_code, typedef = parse_typedef_binds, _Pragma = parse_pragma_macro, @@ -1748,6 +1919,14 @@ local function scan_source(source, source_file, code_macros, code_macro_bodies) debug_skip_markers = {}, types = {}, atom_views = {}, + -- Per-source projection for `atom_auto_reg(, R_)` markers. + -- Each entry is keyed by atom_name; the inner table maps `R_` -> `R_` (raw LHS sym). + -- Merged cross-source into `corpus.atom_auto_regs` (first-wins). + atom_auto_regs = {}, + -- Per-source projection for `phase_auto_reg(, R_)` markers. + -- Each entry is keyed by phase_label; the inner table maps `R_` -> `R_` (raw LHS sym). + -- Merged cross-source into `corpus.phase_auto_regs` (first-wins). + phase_auto_regs = {}, line_of = line_of, -- Source-derived register-alias registry (atom_reg opt-in entries). -- Keys are full R_* idents (never stripped); see parse_enum / parse_enum_body. @@ -1987,6 +2166,8 @@ local function merge_corpus_registries(corpus) corpus.atom_ctxs = corpus.atom_ctxs or {} corpus.atom_phases = corpus.atom_phases or {} corpus.atom_infos = corpus.atom_infos or {} + corpus.atom_auto_regs = corpus.atom_auto_regs or {} + corpus.phase_auto_regs = corpus.phase_auto_regs or {} corpus.collisions = corpus.collisions or {} -- Replace the existing corpus collections with empty tables so a re-run on the same corpus produces identical state (deterministic merge). @@ -2030,7 +2211,7 @@ local function merge_corpus_registries(corpus) corpus.collisions, "binds", bind_shape) end - -- atoms_by_name: MipsAtom_(name) + MipsAtomComp_(name) + MipsAtomComp_Proc_(name). + -- atoms_by_name: MipsAtom_(name) + MipsAtom_Proc_(name) + MipsAtomComp_(name) + MipsAtomComp_Proc_(name). -- Each atom carries `{line, name, body, body_off, kind, raw_name, ...}`. -- Duplicate atom names across sources are first-wins + collision; see the atom_infos block below for the evidence list. for _, atom_entry in ipairs(scan.atoms or {}) do @@ -2065,6 +2246,22 @@ local function merge_corpus_registries(corpus) corpus.collisions, "phase", phase_shape) end + -- atom_auto_regs: keyed by atom scope name; each carries a `{R_ = R_}` map. + -- Per-source entries are simple inner maps (no body / no shape comparison); first-wins suffices. + for atom_scope, syms in pairs(scan.atom_auto_regs or {}) do + if corpus.atom_auto_regs[atom_scope] == nil then + corpus.atom_auto_regs[atom_scope] = syms + end + end + + -- phase_auto_regs: keyed by phase label; each carries a `{R_ = R_}` map. + -- Per-source entries are simple inner maps (no body / no shape comparison); first-wins suffices. + for phase_label, syms in pairs(scan.phase_auto_regs or {}) do + if corpus.phase_auto_regs[phase_label] == nil then + corpus.phase_auto_regs[phase_label] = syms + end + end + -- atom_infos: ALWAYS append every record in source/declaration order. -- Duplicates are preserved so the annotation pass can flag them via `check_unique_annotation`; -- The merge is purely order-preserving. diff --git a/scripts/passes/static_analysis.lua b/scripts/passes/static_analysis.lua index c28db0e..6b53934 100644 --- a/scripts/passes/static_analysis.lua +++ b/scripts/passes/static_analysis.lua @@ -1474,8 +1474,9 @@ end local function check_load_delay_slots(atom, pipe_ctx, findings) -- The load-delay check applies to every atom and component body, including debug-skipped components (`ac_*` and `atom_dbg_skip MipsAtom_(...)`). -- The `atom_dbg_skip` marker controls debugger stepping, not instruction safety. + -- `atom_proc` atoms have full bodies with loads that need delay slots, so the check applies to them too. local p = atom.paths or {} - if atom.kind ~= "atom" then return end + if atom.kind ~= "atom" and atom.kind ~= "atom_proc" then return end local events = p.word_events or {} if #events == 0 then return end @@ -1579,6 +1580,8 @@ local function check_mac_yield_uniformity(atom, pipe_ctx, findings) if is_runtime_helper(atom) then return end -- Per-kind semantics: -- MipsAtom_ (baked atom): exactly 1 mac_yield at the end of the body. Control transfer is the atom's job. + -- MipsAtom_Proc_ (runtime-proc atom): exactly 1 mac_yield at the end of the body. Same as baked atom; + -- the proc IS the atom; the runtime call to `atombuilder_unroll` doesn't introduce a parent atom. -- MipsAtomComp_ (bare static-array component): ZERO mac_yield. -- The component is invoked from inside an atom body; the parent atom does the yield. -- MipsAtomComp_Proc_ (procedural component): ZERO mac_yield. @@ -1602,7 +1605,7 @@ local function check_mac_yield_uniformity(atom, pipe_ctx, findings) return atom.line + line_in_body[tokens[idx].rel] end - if atom.kind == "atom" then + if atom.kind == "atom" or atom.kind == "atom_proc" then -- Baked atom: exactly 1 yield at the end. if count == 0 then findings[#findings + 1] = { @@ -1647,6 +1650,7 @@ local function check_mac_yield_uniformity(atom, pipe_ctx, findings) -- The parent atom does the yield. -- A yield inside a component would either be dead code (bare) or prematurely terminate the function (proc). -- Both are bugs. + -- `atom_proc` atoms are NOT components; they're runtime-proc atoms that own their own yield (handled in the `if` branch above). if count > 0 then findings[#findings + 1] = { atom = atom.name, @@ -1678,7 +1682,7 @@ end --- Per-atom. Runtime-helper atoms (`debug_skip`) are exempt. --- Takes `(atom, pipe_ctx, findings)`; `pipe_ctx` is unused. local function check_yield_load_tail_pairing(atom, _pipe_ctx, findings) - if atom.kind ~= "atom" then return end + if atom.kind ~= "atom" and atom.kind ~= "atom_proc" then return end if is_runtime_helper(atom) then return end local tokens = atom.paths.tokens @@ -1897,9 +1901,9 @@ end --- - Atoms containing a `mac_(...)` call whose `name` is not registered in `pipe_ctx.components_by_name` emit a "new macro; --- Not in corpus.components" advisory — the auto-derivation returned nil for that name. --- ---- Applies only to `kind = "atom"` (baked atoms). Components don't emit full primitives. +--- Applies only to `kind = "atom"` or `kind = "atom_proc"` (full-atom bodies). Components don't emit full primitives. local function check_gpu_portstore_shape(atom, pipe_ctx, findings) - if atom.kind ~= "atom" then return end + if atom.kind ~= "atom" and atom.kind ~= "atom_proc" then return end local tokens = atom.paths.tokens local line_in_body = atom.paths.line_in_body local tc = atom.paths.tok_class diff --git a/scripts/ps1_meta.lua b/scripts/ps1_meta.lua index 35dc8bf..fa32783 100644 --- a/scripts/ps1_meta.lua +++ b/scripts/ps1_meta.lua @@ -118,6 +118,12 @@ local PASSES = { kind = "header-output", deps = {"scan-source", "word-counts"}, }, + auto_reg = { + module = "passes.auto_reg", + kind = "header-output", + deps = {"components"}, + groups = { "pre-link" }, + }, ["emission-model"] = { module = "passes.emission_model", kind = "validation",