Skip to content

VU microprograms

This is a specification of the PS2 vertex pipeline: the 21 VU0 and VU1 microprograms the renderer uploads, which the port's SDL_GPU renderer follows. All of it comes from the .vutext section of HITMAN3.ELF (0x00478540 to 0x00499b80) and from the C++ that builds the VIF chains. tools/vu_disasm.py produces the listings this document quotes:

python3 tools/vu_disasm.py --list                 # programs, sizes, entry points
python3 tools/vu_disasm.py SnowDraw --eq          # one program, each instruction also as an equation
python3 tools/vu_disasm.py --eq --out build/vu    # every program as build/vu/<name>.vsm

Addresses in this document are VU instruction indices inside a program (the listing's first column). Every program is uploaded at VU micro address 0, so the index is also the VU micro address and the MSCAL argument that starts it. VU data addresses are quadword addresses (VU1 data memory is 0x000 to 0x3ff). TOP is the double-buffered input address the VU reads with xtop; TOPS+n in a VIF code means an unpack with the FLG bit.

Confidence markers: sure means read from instructions and cross-checked with matched C++; derived means read from instructions only; unsure gives the reason.

Summary

Program Unit Bytes / instr. Entry points (MSCAL index) C++ users Shader family
SnowDraw VU1 9576 / 1197 SnowDraw_Begin 0x000, DropDraw_Begin 0x083, PartDraw_Begin 0x15b, XPartDraw_Begin 0x1d3, GeneralSpriteDraw 0x30a, GeneralSpriteDraw2 0x356, InitDrop 0x3bc, InitSnow 0x3c9, InitGeneralSprite2 0x3d5, InitGeneralSprite 0x3e0, Particle_init 0x448 ZOldViewPS2::DrawSprites, CreateSpriteCameraChain, DrawSpritesArray, DrawSpritesArrayUV, DrawSpritesArrayRaw, DrawSpritesBox, DrawSpritesBoxScale, DrawSpritesParticles, AddParticlesHeader; ZOldDrawPS2::AddPrimSpriteChainStart sprites, particles and HUD
VColClip VU1 13960 / 1745 jump table: 0 InitRegs, 2 InitPODRegs, 4 GenDrawStrips, 6 InitTexRegs, 8 DrawStrips ZOldViewPS2::AddDrawStripsProgram, SetupMaterial, PrimInstanceCreate; ZOldDrawPS2::AddPrimStripChainStart, AddPrimToDMAChain, AddPrimChunksToDMAChain static and clipped geometry
VColClip_Wired VU1 4616 / 577 0 InitRegs_Wired, 2 InitPODRegs_Wired, 4 and 8 DrawStrips, 6 InitTexRegs AddDrawStripsProgram when m_lMode == RENDERMODE_WIREFRAME lines (debug wireframe)
VColClipBone VU1 12048 / 1506 0 InitRegsBone, 6 InitTexRegs, 0x0a InitPODRegsBone, 0x0c and 0x0e end, 0x10 and 0x12 branch to DrawStripsBone, 0x0c Prettylights, 0x0e Toggle, 0x10 MiniDeform, 0x12 DrawStrips (2, 4, 8 are traps) SetupMaterial (material types 1 and 5), ZOldDrawPS2::AddBonePrimToDMAChain, AddBonePrimStripChainStart, ZOldViewPS2::DrawArrays skinned geometry
VLineClip VU1 10368 / 1296 0 InitRegs, 2 InitPODRegs, 4 GenDrawStrips, 6 InitTexRegs, 8 DrawStrips SetupMaterial (material types 3 and 4) lines
VU_dot3render VU1 12768 / 1596 0 init_program, 2 init_mesh, 4 draw_mesh, 6 init_texture ZOldViewPS2::Dot3InitProgram, DrawDot3Pass, DrawNormalMapped, PrimInstanceCreate (type 6) dot3 normal maps
newlight VU0 1392 / 174 dot3_omni_seg1/2, dot3_spot_seg1/2, dot3_sqspot_seg1/2, dot3_env_seg1/2, dot3_dirl_seg1/2 copied to VU0 micro memory by ZOldDrawPS2::UpdateLight; used by ComputeDot3Lighting dot3 normal maps (CPU side)
VUWaterRender VU1 9696 / 1212 0 InitDest, 2 InitGlobals, 4 and 8 DrawPatch, 6 InitTexRegs ZOldViewPS2::DrawWater, BeginWaterMirrors, DrawWaterPatches, SetupMaterial; ZOldDrawPS2::PrimInstanceCreateWaterPatch water and mirrors
VU_GrassDraw VU1 4656 / 582 0 (end), 2 InitObject, 4 DrawPatch, 6 InitTexRegs SetupMaterial (material 9), ZOldDrawPS2::PrimInstanceCreateScatter grass
VUStaticShadowDraw VU1 6200 / 775 0 InitRegs, 2 InitPODRegs, 4 FlushOutBuffer ZOldViewPS2::DrawStaticShadows, DrawShadowsOfType, PrimInstanceCreate (type 10) projected and static shadows
VUStaticShadowDrawTex VU1 5368 / 671 0 InitRegs, 2 InitPODRegs, 4 FlushOutBuffer, 6 InitTex same as above, textured shadows projected and static shadows
VProjClip VU1 15000 / 1875 0 InitRegsBone, 2 InitProjObject, 4 GenDrawStrips, 6 InitGifRegs, 8 DrawProjObject, 0x0a InitPODRegsBone, 0x0c and 0x0e end, 0x10 and 0x12 branch to DrawStripsBone, InitProjProgram 0x602 ZOldViewPS2::DrawShadowReceivers, ZOldDrawPS2::BeginShadows and GenerateCasterTexture projected and static shadows
VU_SplashDraw VU1 2624 / 328 VU_SplashDraw_Start 0x000, VU_SplashDraw_Init 0x137 ZOldViewPS2::DrawRainSplashesInit, DrawRoomRainSplashes, DrawRainSplashesFinalize rain splashes
VUScrPass VU1 5336 / 667 sprite_XxY_ST 0x000, sprite_XxY_Noise 0x035, sprite_64x16_UV 0x09e, sprite_64x16_ST 0x0c2, VUInitScrPass 0x0e6, IndexFetch 0x0e9, IndexFetchInitRegs 0x212, DrawShimmer 0x21d Z2DFunctions (z2dfunctions.cpp), ZPostFilterPS2 screen passes
VU_LoaderSeq VU1 1008 / 126 0x000 loader_sequence_player_ps2.cpp sprites and HUD (loading screens)
VLightTest VU0 4040 / 505 VLightTest_Begin 0x000, InitLightRegs 0x19c ZRenderPS2::PrepareLightChainBuild, ZOldDrawPS2::UpdateLight CPU or compute: per-vertex light colours for static geometry
MatMulMat VU0 208 / 26 0x000 (second routine at 0x00d) BoneMatFixPS2.cpp (VU0ExecBoneMats) CPU: bone matrices
MatToParent VU0 616 / 77 0x000, Init 0x02a, SlowExec 0x02d, MulMats 0x040 BoneParentMatPS2.cpp CPU: bone matrices
VClipBone_Coded VU1 10096 / 1262 0x000 none found unused (debug colour coding)
VClipBone_Wired VU1 6264 / 783 0x000 none found unused (debug wireframe)
VU_LoadScreen VU1 848 / 106 0x000 none found unused

"None found" means a scan of .text for lui/addiu pairs and of .data/.rodata for 32-bit words found no reference to the label; the hits for VClipBone_Begin_Coded and VU_LoadScreen_Init are the same addresses as VColClipBone_End and VUWaterRender_End.

Shared facts

Labels and loading

The VU labels are ELF symbols in section .vutext with st_other 0xeb (PROTECTED with other bits 0xe8). The 82 global ones mark program boundaries and C++-visible entry points; 1,149 local labels plus a .vu.1 marker per program are the assembler's labels (several names, such as GetClipPlane or InitPODRegs_End, repeat in each program). A local *_End label at a program's first address belongs to the previous program. Labels named EXPL_*vcl* and __v_tmp_vcl_* show that VU_GrassDraw, VU_SplashDraw and VU_dot3render were written in Sony's VCL and are software-pipelined.

ZDMAChain::AddMicroProgram (matched) uploads [begin, end) with MPG codes at address 0. The C++ computes entry indices as (label - begin + 7) / 8, so iGeneralExecute = 0x30a. Most VU1 programs start with a jump table of b instructions two slots apart, so MSCAL 0, 2, 4, 6, ... select an entry. VU registers persist between MSCALs; programs keep state in VI registers (vi02 is always the output buffer) and in VU memory above the double buffers. VIF1 swaps the double buffer (TOPS) on every MSCAL; VColClipBone's Toggle entry (0x4ef) is an empty program used only for that swap.

Matrices

IOI's ZMatrix is float m0[3][3]; V3 p0;, stored row by row, and vmmul (src/engine/zstdlib/_ps2/zmathps2asm.cpp) computes v.x*m0[2] + v.y*m0[1] + v.z*m0[0]: row 2 is the X axis and row 0 the Z axis. A ZMatrix unpacked as V3-32 ×4 to addresses a..a+3 gives mem[a+2] = X axis, mem[a+1] = Y axis, mem[a] = Z axis, mem[a+3] = position. Every program that reads one follows that order (for example InitGeneralSprite 0x3e1 to 0x3e4 loads vf04 = mem[2], vf05 = mem[1], vf06 = mem[0], vf07 = mem[3] and multiplies a point as vf04*x + vf05*y + vf06*z + vf07). Sure.

4×4 matrices (M44) are Sony column-major: mem[a] is the column multiplied by x, mem[a+3] the translation column.

Camera data (ZCameraViewEntryPS2, zoldviewps2.h)

The formulas below are from CalcTransferMatrixAndClipPlanes and ZCameraViewEntry::CalcCameraToView. Where a VU program depends on them, its instructions agree.

  • mCameraToView44 = ioiFpuViewScreenMatrix(scrz = fScreenX * Pers, ax = fAspectX, ay = -fAspectY, cx, cy, zmin = ZBufferMin, zmax = ZBufferMax, near, far). For a camera-space point: X = ax*scrz*x + cx*z, Y = ay*scrz*y + cy*z, Z = (cz/dz)*z + az*(zmax-zmin)/dz, W = z, with az = far*near, cz = zmin*far - zmax*near, dz = far - near. After division X/W and Y/W are GS primitive coordinates centred on 2048 (cx, cy ≈ 2048 plus the viewport centre offset), camera +y is screen up, and Z/W is zmax at the near plane and zmin at the far plane (reversed depth). Sure (matched code).
  • m_TransferMatrixAndPlanes[40] (0x190): the root→screen M44 (CameraToView × RootToCamera) followed by six planes. The planes are near, far and four side planes built from 0.9/Pers * 2048/fScreenX (and Y), which is the 4096-wide GS coordinate range and not the viewport: the side planes are a guard band. ...NoFar sets the far plane distance to 1e6; ...Local variants are in camera space.
  • m_TransferMatrixHomogeneousScaleBias[28] (0x120): mHProj = RootToCamera44 × ViewScreen(pers, ax, ay, 0, 0, zmin = 1, zmax = -1, near, far), then vOffset = (cx, cy, (zbmax-zbmin)/2, 0), vScale = (256, -256, -(zbmax-zbmin)/2, 1), then the last projection column. Programs that use it (water, dot3, static shadows, particles' sibling paths) project into a canonical clip space and map to the screen with screen = clip.xyz / clip.w * vScale + vOffset. These programs map directly onto GPU clip space.
  • m_Setup[8] (0xa0): [0..3] = translation column of mCameraToView44 ((0, 0, az*(zmax-zmin)/dz, 0)), [4] = 6 (number of clip planes, as an integer), [5] = 0, [6] = fFogScale = -255/(fogFar - fogNear), [7] = fFogAdd = 255*fogFar/(fogFar - fogNear). Fog is therefore fogAdd + W*fogScale = 255*(fogFar - W)/(fogFar - fogNear): 255 at or before the fog near distance (after clamping), 0 at fog far.
  • m_RootToCamera44 (0xc0) and m_RootToCamera at 0x10 in ZCameraViewEntry or the identity m_Reset at 0x560: the camera rotation for billboards.
  • m_SpriteClipSetup[12] (0x520): [0..3] = 1/left, 1/bottom, 1/right, 1/top of the viewport in GS coordinates (left = cx - w/2, bottom = cy + h/2 - 1, right = cx + w/2 - 1, top = cy - h/2), [4..7] = left, top, right, bottom unscaled, [8] = 50, [9] = 10000, [10], [11] = mCameraToView44[0], [5].
  • m_TransferEyePos (0x100) = camera position in root space, w = 1; m_TransferWFog (0x110) = (255/(near-far), -255*far/(near-far), 255, 254) for the fog ranges (GetFogNear/Far).

VIF input conventions

  • VIF codes in a DMA tag's upper half run in order: low word first. AddRefPacket(src, n, (code2 << 32) | code1).
  • UNPACK 0x6v: v & 0xc = components (0x0 S, 0x4 V2, 0x8 V3, 0xc V4), v & 3 = width (0 32-bit, 1 16-bit, 2 8-bit, 3 V4-5 = RGBA5551). Bit 4 of the command is MASK. In the immediate, bit 15 is FLG (address relative to TOPS), bit 14 is USN (zero-extend), bits 0 to 9 the address. NUM 0 means 256.
  • STCYCL 0x0102 (CL=2, WL=1) writes one quadword and skips one, so two unpacks interleave at stride 2. STROW loads the 4-word row register from the next 4 data words.
  • Mesh vertex and UV blocks in .PRM are complete VIF packets: words 0 to 3 are the STROW data, word 7 is an UNPACK V4-8 or V4-16 (signed, FLG) of N elements at N+3 (vertices) or N+4 (UVs), and the data follows (ZPrimControlPS2::UnpackVertices, matched). Words 4 and 5 are zero. Word 6 is STMOD 2 for vertex packets and zero for UV packets.
  • Colours unpack as V4-8 unsigned (each byte to a 32-bit integer 0..255, byte 0 to x) or V4-5 for 16-bit colours ((c & 0x1f) << 3, ((c >> 5) & 0x1f) << 3, ((c >> 10) & 0x1f) << 3, (c >> 15) << 7).

GIF output conventions

  • Every program writes PACKED-mode GIF packets into VU memory and sends them with xgkick. The GIF tag comes from the C++ (ZPS2Setup::CalcGifTags, ZOldDrawPS2::CalcGSRegs); the VU only writes NLOOP and EOP into its first word (0x8000 | count, built with iaddiu vi, vi00, 0x4000; iadd vi, vi, vi).
  • ST packed writes S, T and Q. Programs write (s/W, t/W, 1/W) for perspective-correct mapping, or (s, t, 1) for affine screen-space quads. RGBAQ packed uses the low 8 bits of each word; Q is not written.
  • XYZF2 packed: x and y are 12.4 fixed point (ftoi4 of the screen position), z bits 4 to 27 hold 24-bit Z, w bits 4 to 11 hold the fog factor F, and w bit 15 is ADC. With ADC set the vertex is written as XYZF3 and enters the vertex queue without a drawing kick: this is how programs suppress a triangle or a sprite and how a 4-vertex strip per quad restarts. XYZ2 packed has a 32-bit z.
  • Because ftoi4 multiplies all four fields by 16, Z/W lands in the 24-bit XYZF2 z field unchanged and fog*16 lands in F. Programs that output XYZ2 (no fog) pre-scale the Z row by 1/16 (VColClip 0x4b9 to 0x4be).
  • Colours use 0x80 = 1.0 (GS modulate and alpha). Sprite and box colours are built on the CPU as 7-bit values ((c >> 17) & 0x7f, ...), so they are already 0x80-based.

Reading the listings

  • The instruction after a branch or jump (delay slot) always executes. The instruction after one with the E bit also executes, then the program stops.
  • loi sets I for the following instructions; the upper half of the same pair still sees the old I.
  • div and sqrt reach Q after 7 cycles, rsqrt after 13; code before the next waitq may read the previous Q. Software-pipelined loops rely on this.
  • fmand, fsand and fcget read the MAC, status and clip flags of the FMAC instruction issued four slots earlier. MAC flag bits: 0 to 3 zero (w, z, y, x), 4 to 7 sign (w, z, y, x). Clip flags per test: bit 0 x > +|w|, 1 x < -|w|, 2 y > +|w|, 3 y < -|w|, 4 z > +|w|, 5 z < -|w|; each clipw shifts the previous result up by 6.
  • iaddiu immediates are unsigned 15-bit; iaddiu vi13, vi08, 0x7ffb with vi08 = 5 builds 0x8000, the ADC bit. mfir sign-extends, so 0x8000 becomes 0xffff8000 (ADC set, F = 0).
  • Integer output of the colour pipeline sometimes uses the float-bits trick: 2^23 + x (I = 8388608 or 8388863 = 2^23 + 255) has x in its low mantissa bits, which RGBAQ reads directly.

1. SnowDraw: sprites and particles

One program serves every sprite type. DrawSprites uploads it, then per primitive calls the primitive draw entry's chain (built by AddPrimSpriteChainStart), the texture registers, the instance chain (built by CreateSpriteCameraChain via PrimInstanceCreate) that ends in the init MSCAL, and finally the type's draw function.

Inputs common to the sprite types (absolute VU addresses, no double buffering)

VU Content Source
0x000 to 0x003 object ZMatrix (V3-32 ×4: Z axis, Y axis, X axis, position) ZOverrideMatrix::m_TransferMatrix, SPRITE_VIF_UNPACK_MATRIX = 0x68040000
0x004 to 0x007 root→screen M44 first 4 quadwords of m_TransferMatrixAndPlanes (or ...Local), 0x6c040004
0x008 sprite GIF tag AddPrimSpriteChainStart, VIF_UNPACK_SPRITE_GIF_TAG = 0x6c010008
0x009 to 0x00c camera ZMatrix (root→camera, or m_Reset = identity for local transfer) SPRITE_VIF_UNPACK_CAMERA = 0x68040009
0x014 m_SpriteClipSetup[0..3] ([4..7] for box-scale) 0x6c010014
0x015 to 0x01a A+D packet: GIF tag plus material GS registers pRegsDest from CalcGSRegs, VIF_UNPACK_SPRITE_GS_REGS = 0x6c060015
0x01b to 0x01f texture registers (m_GifSetRegs[2..6]) SPRITE_VIF_UNPACK_REGS = 0x6c05001b
0x016 optional TEST_1 override with destination-alpha test (| 0xc000) SPRITE_VIF_UNPACK_TEST

The per-batch data uses the VIF double buffer set by SPRITE_VIF_BASE_GENERAL (BASE 0, OFFSET 0x200) or SPRITE_VIF_BASE_BOX (OFFSET 0x138).

GIF tags (AddPrimSpriteChainStart, matched): types ARRAY (1), BOX (3) and UV (5) use m_GifTagRegsSprite / m_GifTagRegsTextureSprite (PRIM = SPRITE, IIP, PRE, TME if textured, ABE if CalcGSRegs says alpha, NREG = 6: ST, RGBAQ, XYZF2, ST, RGBAQ, XYZF2, no FGE). BOX_SCALE (4) and RAW (6) use m_GifTagStrip (PRIM = TRISTRIP, IIP, TME, PRE, NREG = 3: ST, RGBAQ, XYZF2). PARTICLE (7) uses m_GifTagStripParticle (TRISTRIP, TME, NREG = 9: ST, RGBAQ, XYZ2, then ST, XYZ2 three times) with registers at TOPS+0x12 and the tag at TOPS+9.

InitGeneralSprite (0x3e0, MSCAL iGeneralInit)

  1. vf19 = mem[0x14] (the 1/edge clip constants).
  2. Object axes in camera space (0x3ed to 0x3f5): cx = C·O.X, cy = C·O.Y, cz = C·O.Z, where C is the camera ZMatrix rotation at 0x009 to 0x00b and O the object rotation. Each is normalised with erleng (0x3f6 to 0x3ff).
  3. vf30 = -(cx.x, cy.x, cz.x) and vf31 = -(cx.y, cy.y, cz.y) (0x400 to 0x407): minus the camera right and up axes expressed in object coordinates (rows of the normalised object→camera rotation).
  4. Combined object→screen matrix (0x408 to 0x414): vf04 = T·O.X, vf05 = T·O.Y, vf06 = T·O.Z, vf07 = T·O.P + T.w with T = root→screen at 0x004.
  5. Copy the GIF tag at 0x008 to both output buffers 0x0b5 and 0x2b5, set vi02 = 0x0b5, xgkick 0x015 (the GS register packet).

Sure.

GeneralSpriteDraw (0x30a, MSCAL iGeneralExecute): SPRITETYPE_ARRAY and SPRITETYPE_ARRAY_UV

Input per batch (DrawSpritesArray/DrawSpritesArrayUV, matched):

  • TOP+0 = (count, 0xb, near, far) with near = 0x409fff00 (≈ 5.0) and far = 0x49742400 (1e6), V4-32 at TOPS+0.
  • TOP+7 + 3i = VU1GenSprite (3 quadwords, V4-32): Position.xyz, fScale, UVLowerLeft, UVUpperRight, Color[0], Color[1], Color[2], fScale1.
    • ARRAY: fScale = fScale1 = SSpriteArrayElement::fScale * 0.5, UVs (0,0) and (1,1). fAngle is not sent: plain sprites never rotate.
    • UV: fScale = fScale[1] * 0.5 (half height), fScale1 = fScale[0] * 0.5 (half width), UVs from the element.
    • Colour: textured sprites send R = (c >> 17) & 0x7f, G = (c >> 9) & 0x7f, Color[2] = (c >> 26) << 12 | ((c >> 1) & 0x7f); untextured ARRAY sprites send 8-bit channels and (c >> 25) << 12 | (c & 0xff).

Per sprite (loop at 0x311):

  1. Alpha (0x315 to 0x319): A = int(itof12(Color[2])), i.e. Color[2] >> 12; it is stored over fScale1 in VU memory so the colour quadword becomes (R, G, A<<12 | B, A), which RGBAQ reads as (R, G, B, A).
  2. Corners in object space (0x31a to 0x31d): d = vf31*fScale + vf30*fScale1 = -(up*fScale + right*fScale1); corner A = p - d = p + up*fScale + right*fScale1 (screen top-right), corner B = p + d (screen bottom-left).
  3. A' = M·A, B' = M·B with the combined matrix; Q = 1/A'.w (0x325). Both corners share the same W, and the program reuses that Q for B.
  4. Viewport overlap test (0x327 to 0x338): (A'.x / left, A'.y / bottom) and (B'.x / right, B'.y / top) against |W|. The sprite is kept only if A is right of the left edge and not below the bottom edge, and B is left of or on the right edge and below the top edge: the screen rectangle overlaps the viewport. Sprites wholly off screen are skipped; partly visible ones are drawn.
  5. Depth test (0x33a to 0x33f): kept only if near < W <= far (sign flags of near - W and far - W).
  6. Output, 6 quadwords per kept sprite at vi02+1: ST(A) = (UR.u/W, UR.v/W, 1/W), RGBA, XYZF2(A) = ftoi4(A'.xyz/W), w = 0, ST(B) = (LL.u/W, LL.v/W, 1/W), RGBA, XYZF2(B). The upper-right UV goes on the top-right corner.
  7. Draw_Gen (0x34a): NLOOP = kept count with EOP, xgkick vi02, then vi02 = (vi02 + 0x200) & 0x3ff.

Port notes: a GS SPRITE is a screen-aligned rectangle; Z and colour come from the second vertex and texture coordinates interpolate linearly (Q is equal at both corners, so the mapping is affine). Sprite size in world units is O3x3·(right*fScale1 + up*fScale), so the object matrix's scale scales sprites. Sure.

InitGeneralSprite2 / GeneralSpriteDraw2 (0x3d5 / 0x356): SPRITETYPE_ARRAY_RAW

GlobalInit (0x41e) builds the same combined matrix but leaves the camera axes unnormalised (vf31 = -(up) - (right), unused by raw sprites). The tag goes to 0x108 and 0x308.

Input (DrawSpritesArrayRaw, matched): TOP+0 = (count, 9, near, far); from TOP+7, 12 quadwords per sprite: four VU1RawCorner (Position xyzw, UV, Color as 7-bit RGBA ints). The CPU computes the corner positions (p + vertex[k] * fScale, corner order 0, 1, 3, 2) and the colours, and reorders the UVs to match.

Per sprite (0x35c): transform the four corners with the combined matrix, Q = 1/W of corner 0, then output 4 vertices (ST = (u, v, 1) affine, RGBA, XYZF2 = ftoi4(xyz*Q)) with ADC on corners 0 and 1 (mfir.w vf01, vi09 with vi09 = 0x8000, 0x393 to 0x394). NLOOP = 4 × count (0x3b1, 0x3b2), so the GS sees one 4-vertex strip per quad. All four corners are divided by corner 0's W.

Culling: only W(corner 3) < near drops a sprite (0x38b to 0x390). The code also computes a screen bounding box and clip flags against fixed bounds 1728, 2271, 2367, 1824 (2048 ± 320 by 2048 ± 224) at 0x371 to 0x386, but never branches on them. Sure.

Raw sprites are the HUD and overlay path (ingamemap.h, hm3weapons.h, hm3overlaycameraclass.h produce SSpriteArrayElementRaw), drawn through the overlay camera.

Checking the listings by emulation

The three sections below were settled by running the microcode in a small VU1 interpreter built on vu_disasm.py's decoder (not committed). It ran the real init and draw entries on chosen VU memory and decoded the GIF packets from xgkick. It models register stalls, Q after 7 or 13 cycles, P after the EFU latency, MAC flags four cycles after issue, round-toward-zero arithmetic, and max/mini as sign-magnitude integer compares that pass raw bits through. Three details matter for these programs:

  • VU arithmetic truncates. PartDraw computes frac(|a|) as ((-2^23 - |a|) + 2^23) + |a|; with round-to-nearest the result leaves the polynomial's range and quads shrink for half the angles.
  • max vfA, vfB, vfB is a move of integer data (DropDraw swaps the colour through vf04 that way).
  • opmula ACC, a, b then opmsub d, b, a is d = a × b: both instructions multiply fs.yzx * ft.zxy.

Every formula below was checked against that interpreter on randomised inputs (200 particles per particle program, 240 box sprites per box program): the same sprites are culled and the corners agree to 1/16 pixel. Sure unless stated.

InitSnow / SnowDraw_Begin (0x3c9 / 0x000): SPRITETYPE_ARRAY_BOX

Input (DrawSpritesBox, matched): the elements as 2 quadwords each, V4-32 at absolute 0x270 (SPRITE_ARRAY_VIF_UNPACK_BASE; more than 100 sprites use two references). Per box: TOP+0 = (count, lMask, fNear, fFar), TOP+1..8 = the eight V3 vectors of SSpriteBox in declaration order (vCornerBot0, vCornerBot1, vCornerTop0, vCornerTop1, then the four vDirection*; 6 quadwords, 0x68088001), TOP+9 = colour (R, G, B, A) 7-bit ((c >> 17) & 0x7f, (c >> 9) & 0x7f, (c >> 1) & 0x7f, c >> 26), then MSCAL 0. BASE is 0 and OFFSET 0x138, so the first buffer overlaps the constants at 0x000 to 0x00c after GlobalInit has read them into registers.

GlobalInit (0x41e) builds the object→screen matrix (vf04..vf07) and the object axes in camera space without normalising them: vf20 = O.X·C, vf21 = O.Y·C, vf22 = O.Z·C with C the camera rotation at 0x009. right = (vf20.x, vf21.x, vf22.x), up = (vf20.y, ...), view = (vf20.z, ...) are the camera axes in object coordinates, scaled by the object matrix's inverse scale.

Per element e0 = (fx, fy, fz, size), e1 = (fULeft, fURight, lMask1, lMask2):

  • L_k = corner_k + direction_k * fx for the four corner/direction pairs; a = L_Bot0 + (L_Bot1 - L_Bot0) * fz, b = L_Top0 + (L_Top1 - L_Top0) * fz, P = a + (b - a) * fy (0x020 to 0x038).
  • A = P + (up + right) * size (screen top right), B = P - (up + right) * size; both are transformed and divided by A's W.
  • Kept only if fNear < W <= fFar, the masks pass, and the sprite lies entirely inside the viewport: left < B.x, A.x <= right, top < A.y, B.y <= bottom (clip flags against m_SpriteClipSetup[0..3]). Partly visible flakes are dropped.
  • Mask test: (lMask1 & lMask) == lMask1 and (lMask2 & (lMask >> 16)) == lMask2, each on the low 16 bits.
  • Output is a GS SPRITE: A gets ST = (fULeft, 0), B gets (fURight, 1) (affine, both divided by the same Q), colour TOP+9 on both, Z from B. The texture is mirrored horizontally on screen. A culled sprite is still emitted with ADC on B.
  • XYZF2's w word of A holds A's W float bits; the sprite tag has no FGE, so no fog.

InitDrop / DropDraw_Begin (0x3bc / 0x083): SPRITETYPE_ARRAY_BOX_SCALE (rain streaks)

Same box inputs with TOP+0.z = 100.0 (SPRITE_BOX_SCALE_RADIUS), elements SSpriteArrayElementBoxDirection (3 quadwords) at 0x270, clip setup m_SpriteClipSetup[4..7] = (left, top, right, bottom) copied to TOP+10. InitDrop keeps vf31 = view, the camera Z axis in object coordinates. The program runs in passes of at most 25 elements (TestForMoreDropRuns, state in the w words of TOP+0, TOP+5, TOP+6), first writing object-space quads into the output buffer (deform_loop), then projecting them in place (proj_loop).

  • P0 = blend(p), P1 = blend(p + vDirection) with the box blend above; D = P1 - P0.
  • n = normalize(D × view) * size (opmula/opmsub, erleng).
  • Vertices, one 4-vertex strip per element: P0 - n with ST (fULeft, 0), P0 + n with (fULeft, 1), P1 - n with (fURight, 0), P1 + n with (fURight, 1), colour TOP+9, ADC on the first two. Each vertex is divided by its own W and writes ST * Q, so texture mapping along the streak is perspective-correct.
  • Kept only if the smallest W of the four vertices satisfies 100 < W <= fFar, the screen bounding box of the four vertices overlaps the viewport (min.x <= right, min.y <= bottom, max.x >= left, max.y >= top), and the masks pass. Otherwise ADC is set on the last two vertices.
  • The strip tag (m_GifTagStrip) has no FGE: no fog.

Particle_init / PartDraw_Begin / XPartDraw_Begin (0x448 / 0x15b / 0x1d3): SPRITETYPE_ARRAY_PARTICLE

Particle data is in root space (camera space for local transfer); the object matrix uploaded to 0x000 is never read. The double buffers are BASE 0, OFFSET 0x1ef (SPRITE_VIF_BASE_OFFSET_PARTICLE).

Particle_init input, all TOPS-relative: +0..3 root→screen M44 (z row scaled by 1/16 because the output register is XYZ2), +4 = (vScaledGravity, fFriction), +5 = (fAngleSpeed * 651.8986, fAngleSpeedVel * 651.8986, fAngleSpeedAcc * 325.9493, FrameTime) (4096 angle units per turn), +6 = (fScale, fScaleVel, fScaleAcc / 2, fMotionStretch), +7..8 = m_SpriteClipSetup[4..11], +9 the GIF tag (m_GifTagStripParticle: TRISTRIP, TME, no IIP, no FGE; ST, RGBAQ, XYZ2, then ST, XYZ2 three times), +10..17 the eight colour keys (pfColorTable, floats already in 0x80 = 1.0 units), +18..28 the A+D GS register packet, +29..32 the motion-stretch matrix. These come from AddParticlesHeader (checked against its assembly) and AddPrimSpriteChainStart. It stores constants at 0x3de to 0x3f2 (the last colour key twice, at 0x3ed and 0x3ee), kicks the register packet, and pre-fills both output buffers (vi02 = TOP + 0x7d, second at +0x1ef) with STQ (1,1,1), (0,1,1), (1,0,1), (0,0,1) per quad and ADC on the first two vertices (dst_st_make, 0x49a).

Per packet (DrawSpritesParticles, matched): TOP+0.x = count (an UNPACK V4-8 whose data word is the next DMA tag's first VIF word), and from TOP+2, 3 quadwords per particle: (vC1, fStartTime), (vC2, rate) from ParticleCalc with rate = 7 / ((fEndTime - fStartTime) * 4096) in round-toward-zero EE arithmetic, and the S-16 start angle int(fStartAngle * 651.8986) & 0xfff in all four fields.

Per particle, with t = FrameTime - fStartTime and k = fFriction:

  • Position vC1 + g*t + vC2*exp(-k*t) (eexp 0x19c), transformed by the root→screen matrix; W is the camera depth.
  • Size s = fScale + fScaleVel*t + (fScaleAcc/2)*t², half extent h = s * fx / 2 with fx = mCameraToView44[0]; the y extent is scaled by aspect = -mCameraToView44[5] / mCameraToView44[0].
  • Colour c = key[i] + (key[i+1] - key[i]) * f, with 7t/life = i + f, truncated, low 8 bits per channel. Past the end of life the index runs off the table (the CPU removes those particles first).
  • Two half-axes e1, e2 in clip units. Corners c ± e1 ± e2 in the order +e1+e2 (ST 1,1), -e1+e2 (0,1), +e1-e2 (1,0), -e1-e2 (0,0), divided by W; the GS draws triangles 1-2-3 and 2-3-4 of each strip.
  • PartDraw: angle in turns a = angle12/4096 + sign * (A t + B t² + C t³)/4096 with A, B, C the three angle-speed terms from +5 and sign = -1 when the lowest mantissa bit of rate is set (a pseudo-random spin direction per particle; the template's m_bRandomRotationDir does not reach the VU). e1 = h * (cos 2πa, aspect * sin 2πa), e2 = h * (-sin 2πa, aspect * cos 2πa). Sine and cosine come from the 9th-order polynomial on the folded angle | frac(|a|) - 0.5 | - 0.25.
  • XPartDraw (DrawSpritesParticles picks it when fMotionStretch != 0; AddParticlesHeader uploads the matrix only when it is positive): velocity g - k*vC2*exp(-k*t), rotated into camera space by the matrix at +29 (LocalToRoot × RootToCamera without translations, or LocalToRoot for local transfer); d = its normalised camera xy direction, q = |v_xy|², stretch = 1 + fMotionStretch² * q. e1 = h * (d.y, aspect * d.x) across the motion, e2 = h * stretch * (d.x, -aspect * d.y) along it. A particle with no xy velocity collapses to a point. No rotation.
  • Kept only if every corner lies inside the 0 to 4095.9375 GS coordinate range and 50 <= W <= 10000 (m_SpriteClipSetup[8..9]); the viewport edges loaded from +7 are overwritten and unused. A culled particle gets ADC on its last two vertices.
  • No fog: the tag has no FGE, and fog_loop (0x1b7 to 0x1cc) is dead code; both programs branch from fog (0x1b5) straight to part_kick.
  • PartDraw is software-pipelined three particles deep and writes the first three iterations to a scratch slot (fix_Ptr); XPartDraw is a plain nop-padded loop that reads directly.

2. VColClip: static strips

Program flow

MSCAL Label When Work
0 InitRegs 0x58b after upload (AddDrawStripsProgram) vi02 = 0x10b, clear the ST offset at 0x3c6
6 InitTexRegs 0x448 texture switch (TEXTURE_VIF_TEXTURED = ITOP 1 + MSCAL 6) if ITOP ≠ 0, copy TOP+25..30 (texture A+D packet) to the output buffer and kick it; store TOP+24.xy (ST offset) at 0x3c6
2 InitPODRegs 0x460 before the first chunk of a primitive (first VIF code of the chunk chain) per-object constants, see below
8 DrawStrips 0x008 each chunk, plain primitives lighting/colour passes, then FastDraw or DrawClip
4 GenDrawStrips 0x151 each chunk when draw mode has 0x40, 0x1000 or 0x200000, or the primitive has morph keys as 8 plus wobble, environment map, morph and alpha effect

Double buffering: VIF_OFFSET_BASE = BASE 0, OFFSET 0x1db, so TOPS alternates 0x000 and 0x1db. Output GIF buffers are 0x10b and 0x2e6 (vi02 toggles at 0x0b9 to 0x0bd), inside the upper part of each input half. Per-object state lives at 0x3b6 to 0x3d8.

Per-primitive input (TOPS-relative unless noted)

From PrimInstanceCreate (constants verified against the original asm at 0x2ad900 to 0x2ad96c) and AddPrimStripChainStart / AddPrimToDMAChain:

TOPS+ Content VIF code
3..6 object ZMatrix (Z, Y, X, position) 0x68048003 V3-32 ×4
7..10 root→screen M44 0x6c0a8007 V4-32 ×10, with ITOP 0
11..16 six clip planes (root space) same unpack
19, 20 GIF tags: strip tag and clipped-triangle tag 0x6c028013
23 (fBias scale, fZOffset, 0, VU1 control flags) 0x6c018017
24 material diffuse colour, V4-8 unsigned (byte 0 → x) 0x6e01c018
25..30 A+D packet: tag plus material GS registers 0x6c068019
33..39 direct lights: dir0, col0, dir1, col1, dir2, col2, ambient (ITOP = 1 marks them present) 0x6c078021, ITOP 1
43, 44 m_Setup[0..3], m_Setup[4..7] 0x6c06802b V4-32 ×6
45..48 m_RootToCamera44 same unpack
49, 50 normal planes (whole-primitive backface planes) 0x6c028031
51..53 angle/distance alpha fade constants 0x6c038033
54, 55 wobble constants and dynamic phase 0x6c018036, 0x6c018037
56..59 rigid bone ZMatrix (pack type 8) 0x68048038

Control flags (TOPS+23.w, kept at 0x3c6.w; meanings from the VU code, draw-mode sources from CalcStripChainStartValues):

Bit Effect in the VU Draw-mode source
0x1 fog on: output XYZF2; off: Z row × 1/16 for XYZ2 (0x4b8 to 0x4be) not PRIMDRAWMODE_NO_FOG (0x100000)
0x2 screen-space backface culling (BackFaceCull 0x0c2) PRIMDRAWMODE_ONE_SIDED (0x4000000)
0x4 environment mapping (Apply_EnvMapping 0x27a) PRIMDRAWMODE_SHARED_VERTICES (0x1000)
0x8 morph keys (Apply_MegaMorph 0x18c) lKeys
0x10 directional lighting; set by the VU when ITOP ≠ 0 at 0x546 direct lights sent
0x20 normal-plane cull of the whole primitive (0x523 to 0x538, 0x2c5) normal planes present
0x40 zero the Z row of the transfer matrix (0x48e to 0x496) unsure
0x80 skip Apply_VertexColors unsure
0x100 "plane align": replace the object rotation with the camera rows TOP+45..47 (billboard): object rows Z, Y, X (TOPS+3..5) become the camera's forward, up and right axes in root space, rows 0, 1 and 2 of m_RootToCamera44 transposed (0x49c to 0x4a6); the position stays. The port's PlaneAlignedMatrix (zoldviewsdl.cpp) 0x10000000
0x400 angle/distance alpha effect (Apply_AlphaEffect 0x20d); the port draws its distance ramps and, for equal angles, opacity 1 (StripsAngleBlendFade, pc-data.md: Plane align) PRIMDRAWMODE_ANGLE_BLEND (0x40)
0x800 wobble (wobble 0x235) PRIMDRAWMODE_WOBBLE (0x200000)
0x1000 multiply the object matrix by the rigid bone TOP+56..59 pack type 8
0x8000 ST offset; set by the VU when the offset at 0x3c6.xy is non-zero (0x465 to 0x46d) texture attribute

InitPODRegs (0x460): per-object constants

  • vf29 = float(diffuse) / 32768 → 0x3b8 (colour scale).
  • Optional rigid-bone multiply (0x472 to 0x486) and plane align (0x497 to 0x4a6).
  • Depth bias (0x4a8 to 0x4b3): with s = TOP+23.x (from BiasToScale), the transfer matrix becomes T' = s·T except the projection's constant Z term: T'.col3 = m_Setup[0..3] + s·(T.col3 - m_Setup[0..3]). Then X'/W' = X/W and Z'/W' = cz/dz + c/(s·W): the object's depth (and fog, which uses W') is computed as if it were s times farther away. Derived.
  • Z offset (0x4b4 to 0x4c9, only if TOP+23.y ≠ 0): the Z constant term is rescaled by d/(d - zoffset), where d is the camera depth of the object origin. Derived; intent unsure.
  • Final matrix vf04..vf07 = T'·O (X, Y, Z, position columns) → 0x3b9 to 0x3bc. Planes are transposed into object space (LoadPlanes 0x4e3) → 0x3bd to 0x3c4; the plane count m_Setup[4] = 6 is at 0x3c5.x; GIF tags → 0x3b6, 0x3b7.
  • Lights (do_lgtbuf 0x539): the three directions are transformed into object space and scaled by 1/64 → 0x3d0 to 0x3d2; colours and ambient → 0x3d3 to 0x3d6.
  • Copies TOP+25..30 to the output buffer and kicks the GS registers (0x577 to 0x584).

Per-chunk input

From AddPrimChunksToDMAChain (matched), for a chunk of N vertices:

TOPS+ Content
0 (N, nStrips, m_fVertexScale, fUVScale)
1 bounding sphere (x, y, z, r) in object space
3 .. N+2 light colours, V4-8 unsigned (from VLightTest on VU0, or g_WhiteChunk)
N+3+2i vertex i: (x, y, z, nz) integers
N+4+2i UV i: (u, v, nx, ny) integers
3N+3+i vertex colour i, V4-8 unsigned or V4-5
4N+3 .. strip lengths, one signed byte per strip (V4-8, four per quadword)
5N+7+2i, 5N+8+2i, 7N+7+i morph key positions, UVs and colours (only with keys)

Per-vertex math (FastDraw 0x024)

  1. M = (vf04·vs, vf05·vs, vf06·vs, vf07) with vs = m_fVertexScale; the W row of all four columns is divided by fUVScale (0x028 to 0x031).
  2. clip = M·(x, y, z, 1) on the integer coordinates.
  3. Q = 1/clip.w. Because the W row was divided by fUVScale, Q = fUVScale/W.
  4. STQ = (u·Q, v·Q, Q_uv·Q) with Q_uv = 1/fUVScale (0x032), giving (u·uvs/W, v·uvs/W, 1/W).
  5. screen = (X/W, Y/W, Z/W) and fog = fogAdd + W·fogScale (0x059: vf31.xyz = 1/W, vf31.w = fogScale·fUVScale, vf30 = (0, 0, 0, fogAdd)).
  6. z = max(z, 0), fog = clamp(fog, 0, 255) (0x05d maxx.zw, 0x063 minii.w with I = 255).
  7. XYZF2 = ftoi4(screen, fog); colour = mem[TOP+3+i] after the colour passes below.

So: position = integer × m_fVertexScale, UV = integer × fUVScale (plus the ST offset when flag 0x8000 is set, Apply_StOffs 0x1c7: uv' = uv·fUVScale + offset), perspective-correct texturing, reversed 24-bit depth, linear fog in camera depth. Sure.

Colour

Apply_VertexColors (0x1e2), per vertex: out = int(L · C · D) per channel, where L = light colour with its alpha forced to 127 (mfir.w vf30, vi10 with vi10 = 0x7f), C = vertex colour and D = diffuse / 32768. With C = 0x80 (1.0) and D = 0xff: out ≈ L·0x80·0xff/32768 ≈ L, so L = 0x80 is 1.0 (g_WhiteChunk holds 0x80808080 for unlit prims), 255 is about 2.0, and 0x80 vertex colour means 1.0. Environment colours are the light's bytes halved (ModifyEnvironmentLight) times its multiplier, so a white environment light at multiplier 1 gives 127.5, the unlit brightness. Alpha is 127·C.a·D.a/32768 (≈ 0x7f for C.a = 0x80, D.a = 0xff). The result overwrites the light colour in place. Sure for the arithmetic; the byte order of lDiffuseColor (R or B in byte 0) is unsure because it depends on how the PRM stores it.

Apply_DirLighting (0x11b, flag 0x10) runs first and replaces L: n = (UV.z, UV.w, vertex.w) (integers, the directions carry the 1/64 scale), d_k = max(0, L_k·n) for three lights, L = min(255, ambient + Σ col_k·d_k), alpha = ambient alpha. Sure. (UnpackVertices uses 1/63 for the CPU-side decode of nz.)

Strips and culling

  • Each strip gets its own GIF tag: the template at 0x3b7 with NLOOP = strip length (0x093 to 0x099); the last tag gets EOP (KickFast 0x0af). Strips are 3 quadwords per vertex: ST, RGBAQ, XYZF2.
  • BackFaceCull (0x0c2, flag 0x2) walks the finished GIF data, computes the screen-space cross product of consecutive edges (opmula/opmsub on the 12.4 positions / 16), alternates the operand order for odd and even triangles, and sets ADC on the third vertex of a culled triangle. The winding that is culled is unsure: the code sets ADC when the sign flag of the cross product's z is clear (0x0d9, 0x0dc to 0x0df); confirm the front-face orientation against a reference capture.
  • DrawClip (0x2bc) tests the chunk's bounding sphere against the planes: outside any plane skips the chunk, inside all goes to FastDraw, otherwise the clipping path. With flag 0x20 set (normal planes say the primitive faces away) the chunk is skipped at 0x2c7.
  • The clipping path (SingleClipLoop 0x2fd, VColDrawAndClipTri_Begin 0x58e) clips triangles that cross the near, far or guard-band planes and emits them as separate triangles with the tag at 0x3b6. A GPU does this itself; the port only has to keep the far plane (depth beyond far is clipped, not depth-tested).

Optional passes in GenDrawStrips

Pass Address Summary Confidence
wobble 0x235 displaces positions and UVs with a sine of time and position using TOP+54..55 (m_fWobbleUSpeed, VSpeed, position amplitude, normal amplitude, period × 2π) structure derived, formula unsure
environment map 0x27a reflects the eye vector (camera position in object space, 0x3cf) about the vertex normal, normalises (rsqrt/eleng), writes UV = 0.5 + r.xy·k scaled to the 1/4096 ST scale; the header's UV scale is replaced unsure about k
morph 0x18c blends key positions/UVs/colours by a weight unsure
alpha effect 0x20d alpha from view angle and distance with the constants at 51..53 (AddPrimToDMAChain: angle fade, near/far fades, opacities) unsure

VColClip_Wired

Debug wireframe (m_lMode == RENDERMODE_WIREFRAME). It walks the same strip data, emits each triangle edge as a line (WriteEdgesLoop 0x096, ClipDrawEdges 0x100), and has its own Decomp loop (0x18f) that decodes the vertex data. Port as a line-list pipeline over the same vertex buffer. Derived at the label level.

3. VColClipBone: skinned geometry and arrays

Inputs

AddBonePrimToDMAChain (matched) and PrimInstanceCreate (original constants at 0x2ad7f4 to 0x2ad85c):

Address Content VIF code
TOPS+2..5 object ZMatrix 0x68048002
TOPS+6..15 root→screen M44 plus planes 0x6c0a8006
TOPS+18, 19 GIF tags: strip and clipped triangles (AddBonePrimStripChainStart) VIF_UNPACK_STRIP_START = 0x6c038012 V4-32 ×3
TOPS+20 (fBias scale, diffuse byte 0 / 2, byte 1 / 2, byte 2 / 2) same unpack
TOPS+21..27 direct lights 0x6c078015
TOPS+28, 29 bounding box 0x6c02801c
TOPS+30..35 GS register A+D packet 0x6c06801e
TOPS+42, 43 m_Setup 0x6c02802a
absolute 0x388 + 4b bone b: four V3 rows 0x68000388 V3-32, no FLG
per chunk TOPS+0 (N, nStrips, vertex scale, UV scale) 0x6c018000
per chunk TOPS+2 weight table header: group offsets and counts per influence count 0x6e00c002 V4-8 unsigned
per chunk TOPS+3.. weight records, V4-8 unsigned same unpack
per chunk TOPS+0x5d+2i, +0x5e+2i vertex and UV (prebuilt packets; UnpackKeyVertices uses base 0x5d for bones) prebuilt
per chunk TOPS+2N+0x5d strip lengths VIFCODE_UNPACK_STRIPS

Up to 30 bone matrices fit (0x388 to 0x3ff). The bone matrices are not in IOI order: row 0 multiplies x, row 1 y, row 2 z, row 3 is the translation (Reload1 0x4d9 loads vf16..vf19 = mem[0x388+b..+3], used as vf19 + vf16·x + vf17·y + vf18·z). They come from DeformBones(), prepared on VU0 by MatMulMat/MatToParent. Sure for the VU side.

Flow

Without HQ lights each chunk ends in MSCAL 0x12 (DrawStrips): BonesDeform then the draw. With HQ lights: MSCAL 0x10 (MiniDeform = BonesDeform only), the light block unpacked to TOPS+2 behind MSCAL 0x0e (Toggle, which only swaps the double buffer back), then MSCAL 0x0c (Prettylights: point lights, then the draw at DeformDone).

BonesDeform (0x3fa)

Vertices are grouped by influence count; four software-pipelined loops handle one to four bones (VertBn_Mat1 0x408, Mat2 0x446, Mat3 0x467, Mat4 0x490).

  • Position = integer × vertex scale (vf31.z = scale · 15.9375 · 0.0627451 = scale), UV = integer × UV scale.
  • One bone: p' = B·p, normal n' = B3x3·(UV.z, UV.w, vertex.w) on the integer (×63) normal, written back over the vertex in place as vertex (p'.x, p'.y, p'.z, n'.x) and UV (u, v, n'.z, n'.y); the draw reads the normal from those slots. Sure.
  • Two bones (Mat2): records (vertex offset, bone A, weight byte, bone B); wA = w/255, wB = (255 - w)/255 (I = 15.9375 = 255/16 and 0.0627451 = 16/255 at 0x437, 0x438); p' = wA·A·p + wB·B·p, same for the normal.
  • Three bones (Mat3 0x467): two quadwords (vertex offset, weight A, weight B, slot A), (slot B, slot C, -, -); bone C gets 255 - wA - wB. Four bones (Mat4 0x490): (vertex offset, weight A, weight B, weight C), (slot A, slot B, slot C, slot D); bone D gets the remainder. Weights are itof4 sixteenths subtracted from 15.9375 and rescaled by 16/255, so every vertex blends Σ w_i/255 · B_i. Sure (traced; matches the decoder's parse).

Draw (DeformDone 0x014)

Same output as VColClip (ST, RGBAQ, XYZF2 strips, tags per strip, near/far fog, clip path SingleLayerClip when the box test at 0x380.x says so) with the combined matrix from InitPODRegsBone (0x222: T·O with the bias scale of TOP+20.x). Lighting is per vertex on the deformed normals: d_k = max(0, L_k·n) for three directional lights (0x381 to 0x383), rgb = min(255, ambient + Σ col_k·d_k) (0x384 to 0x387), produced through the 2^23 float trick, alpha from the ambient w. Sure for the structure; pipelined. InitPODRegsBone (0x280 to 0x29a) transposes the three DirectLights() directions, scales them by 1/64 and dots them with the object matrix axes (object space); it multiplies the three colours and the ambient by TOP+20.yzw / 128, the prim diffuse bytes 0, 1, 2 each shifted right by one. The ambient w is 64.0 (CalcBoneLightSources, checked against the original constant at 0x596128), so skinned vertices have GS alpha 0x40. Bone prims upload no vertex colours. Sure.

Prettylights (0x4f2) runs after MiniDeform on the deformed chunk, with the HQ light block that CreatePrettyLightsBuffer builds (unpacked to TOP+2 between the two MSCALs; Toggle only swaps the buffer back). Settled against a simulation of the program (see "Checking the light programs" below); every term below matches the VU output to within float rounding:

  • FixNormals packs the deformed normal (63 per unit) as q = int(clamp(2047.5 + 32.5·n, 0, 4095)) for x and y and keeps z/64, so the lights see n = ((q_x - 2048)/2048, (q_y - 2048)/2048, n_z/64).
  • The block starts with four environment quadwords X, Y, Z, B and acc = B + X·(n_x+1)/2 + Y·(n_y+1)/2 + Z·n_z, which is (c3 + amb)/2 + (c3 - amb)/2·(d·n) with c3, amb and d from CalcBoneLightSources. A counter quadword (omni, spot, square-spot counts as integers) follows, then the lights. All colours in the block are in B, G, R order.
  • Omni (light type 1, two quadwords: position and fLightConst1, colour × multiplier and -fInverseFarMinusNear): acc += colour · clamp(const1 - d·inv, 0, 1) · max(0, n·l), l the unit vector to the light.
  • Spot (type 0, four quadwords: position, axis m0[0], colour from lTransferColorAndFallOff × multiplier, (-fScale, fLightConst1, 1/(cosHot - cosFall), -cosFall/(cosHot - cosFall))): the same distance and N·L terms times smoothstep(clamp(-(axis·l)·a + b, 0, 1)) with smoothstep(s) = s²(3 - 2s) (the -1.5 and -2 constants).
  • Square spot (type 2, five quadwords): the program multiplies the three stored vectors as columns, p = side·d.x + up·d.y + axis·d.z with d = vertex - light (the C++ scales component 0 of each vector by 1/tan(fall') and component 1 by aspect/tan(fall')), and uses smoothstep(f_x·f_y) with f = clamp((1 - |p.xy/p.z|)/(1 - hot), 0, 1); zero behind the light.
  • ColorDistrib writes the B, G, R accumulators into the deformed normal slots (UV.z, UV.w, vertex.w, which the draw reads as n'.z, n'.y, n'.x), and Prettylights replaces the three directional lights at 0x381 to 0x387 with identity directions, colours TOP+1.xyz on the diagonal and zero ambient. InitPODRegsBone stored TOP+1.xyz = (diffuse byte >> 1)/128 per channel, so the draw outputs min(255, s_c · max(0, acc_c)) per channel with the ambient alpha (0x40). Sure.

Arrays (DrawArrays, material type 1)

Instanced geometry reuses this program. Per SInstance (ObjectToWorldMatrix, pBones, pLightInfo), DrawArrays uploads the instance matrix to TOPS+2 as the object matrix, m_Setup and the root→screen matrix and planes, calls the prim's chain (GIF tags, bias, diffuse), uploads pLightInfo (seven quadwords, same layout as DirectLights()) to TOPS+21 and a fixed 200-unit box to TOPS+28, runs MSCAL 0x0a, uploads the first copy-bones pair of the palette from pBones + offset·3/4 to 0x388, and calls the instance chain past its first four quadwords (lights, box, flush and the first copy-bones packet). Arrays therefore use one copy-bones pair. Sure (read from ZOldViewPS2::DrawArrays).

4. Other VU1 programs

VLineClip: lines (material types 3 and 4)

A copy of VColClip (same jump table, InitPODRegs, colour passes, fog, FastDraw, BackFaceCull) whose clip path is VLineDrawAndClip_Begin (0x47e): edges are clipped plane by plane (ClpEdgeLoop 0x487) instead of triangles. CalcGSRegs gives wire prims a line-strip tag for strips and a line tag for clipped edges, and every strip gets its own GIF tag, so each strip of N vertices draws N - 1 segments. Derived. The SDL decoder emits these as line lists.

VU_dot3render + newlight (VU0): normal maps

PrimInstanceCreate type 6 (original constants): object matrix V3 at TOPS+3, m_TransferMatrixHomogeneousScaleBias (7 quadwords) at TOPS+7, eye position at TOPS+25, optional normal planes at TOPS+14, flags at TOPS+28. The program works in homogeneous clip space. draw_mesh (0x008) runs calc_to_light (0x08e, light vectors per vertex), calc_half_vectors (0x0d7), transform_to_tangentspace (0x133) and apply_vertex_colors (0x1ae), then renders two or four passes (regs_two_pass, four_pass_ready) whose vertex colours carry the tangent-space light (or half) vector, and a specular pass (process_spec_x 0x293). The GS combines the passes with the normal map through CLUT index tricks (PrepareDot3IndexPass, TextureSwitchInDot3Pass). The light colours and directions per primitive come from VU0's newlight segments (omni, spot, square spot, environment and directional; ABS symbols DOT3_OMNI_SEG1 = 0x000 to DOT3_DIRL_SEG2 = 0x530 are their byte offsets) driven by ComputeDot3Lighting (calclightdot3.cpp).

What the passes compute (DrawNormalMapped, DrawDot3Pass, calclightdot3.cpp, palettes in Z2DFunctions::Init):

  • Per vertex, on the CPU and VU0 (UpdateLight → ComputeDot3Lighting → FlushLightBuffer), in object space: one light direction and one colour. The environment light (ZGeomDrawEntry::Environment(), an SPrimLightEnvironmentPS2) enters as d = -(RootToObj · m0[0]), c1 = vAmbientColor · fMultiplier / 128, c2 = vDirectionColor · fMultiplier / 128. The dot3_env segment (non-directional) gives colour (c1 + c2)/2 + (c2 - c1)/2 · (d·n) and direction n + (d - n) · max(0, d·n); the dot3_dirl segment (bIsDirectional) gives colour c1 + (c2 - c1) · max(0, d·n) and direction n · lum(c1) + d · lum(c2) · max(0, d·n). The non-directional program normalises this direction and scales it by the luminance of the resulting colour. Omni and spot lights from the geom's light list add colour · att · cone · max(0, n·l) to the colour and l · lum(colour) · att · cone · max(0, n·l) to the direction, with colour = diffuse bytes × multiplier / 255, att = clamp(fLightConst1 - d·(fInverseFarMinusNear or fScale), 0, 1) and for spots cone = smoothstep(clamp((-(axis·l) - cosFall)·fLightConst2, 0, 1)) (simulated, exact). Then colour is clamped to 2; for prims with a normal map the direction is normalised and the colour multiplied by min(1/clamp(n·dir, 0, 1), 1.3, 2/max(colour)), so a flat normal map reproduces the vertex colour. Direction and colour are packed as dir/2 + 1/2 and colour/2 bytes. Derived from the C++ (drafts) and the newlight listing.
  • transform_to_tangentspace turns the direction into (T·L, B·L, N·L); calc_half_vectors adds the normalised eye vector for specular. apply_vertex_colors multiplies the packed light colour by the vertex colour and the material colour.
  • "Make dots" passes draw the normal map through CLUTs 0 to 4 into the temp buffer (vertex colours carry the tangent-space vector, CLUT 3 and 4 hold max(0, n - 128) and max(0, 128 - n), see docs/development/port/textures.md), and the index passes copy the result through m_ILP_Palette (max(0, N·L), 0x80 = 1) or m_ILP_Palette_pow ((N·H)^16) into the frame's alpha.
  • Diffuse passes draw the diffuse texture with ALPHA_1 = Cs·Ad (0x98, normal-mapped) or Cs (0xa8, no normal map or fDisableDot3AtDistSq exceeded); specular passes add the specular map scaled the same way. CLAMP_1 is 0 (repeat) in every pass and TEST_1 has no alpha test. Derived; the CLUT arithmetic of the make-dots passes was not traced bit for bit.

The SDL view (zoldviewdot3sdl.cpp, dot3.hlsl) keeps the same structure with one texture per pass: per-vertex lighting on the CPU with the environment light formulas above, then per primitive a dots pass that writes max(0, N·L) from the normal map (decoded as (n - 128)/127) into the frame's alpha and the depth buffer, a diffuse pass blended Cs·Ad, and for specular maps a (N·H)^16 dots pass (with the vertex normal when there is no normal map) and an additive specular pass. The lights come from the geom's light list as ZOldDrawPS2::UpdateLight gathers it. Approximations: square spots in the dot3 path use the per-axis model of VLightTest (not simulated), the normal map's alpha w is ignored, process_spec_x's sphere-map specular for prims without a normal map is replaced by the vertex-normal (N·H)^16 term, and fog is applied to the diffuse pass as for plain strips.

VUWaterRender: water and mirrors

Primitive type 11 (PrimInstanceCreate, original constants): m_TransferEyePos and the following 7 quadwords (fog, homogeneous projection, offset, scale) at TOPS+0..7, the water scales (1/xpow2, 1/ypow2, X, Y) at TOPS+8, four GIF tags at TOPS+9..12 (m_pNormalGifTags or m_pWireGifTags), the first five quadwords of the SWaterPatchInst at TOPS+13..17 (segments and sizes, position and ripple count, colour 0, colour 1, draw mode with reflect, refract and Fresnel-min scales), the sine waves (P, A, Q, R) at TOPS+18..21 and two quadwords per ripple from TOPS+22, then FLUSH + MSCAL 4 (DrawPatch). InitGlobals and InitLocals copy these to 0x3be..0x3d3 (projection columns, offset, scale, eye, W fog, scales, tags, patch, waves) and the ripples to 0x3d4; InitLocals also stores sin/cos of P * segX and Q * segZ at 0x3ba..0x3bd. Draw mode 0x20 (the mirror mask pass) replaces the grid by one quad.

  • Grid: row by row, two rows interleaved at 3 quadwords per vertex so the buffer reads as a triangle strip. Position (x, y + sum A sin(Px + Qz + R), z), normal (-sum A P cos, 1, -sum A Q cos) (not normalised), UV (i / xsegs, j / zsegs); the sines are advanced by rotation with the stored step values. Sure.
  • UpdateRipples (0x0c9): for each ripple and each vertex with d < radius from the centre, A' = A (1 - d / radius), y += A' sin(phase + f d) and normal.xz += dir * A' f cos(phase + f d) (added, not subtracted). Derived.
  • FresnelReflection (0x148, any non-zero draw mode): v = pos - eye, c = 1 - |v . n| / |v|, Fresnel = min + (1 - min) c^4 into normal.w; UV becomes 0.5 + n.xy (v . n / |v|) reflectScale - v.xy / 2|v| (with n.y = 1), an environment lookup. fFresnelMax is unused. Derived.
  • PatchDrawCULL (draw mode bit 0 clear): STQ = UV / W, colour int(colour 0 * 128), W fog. PatchDrawCULLProjective (bit 0): ST from the screen position into the top half of the temp buffer plus normal.xz * reflectScale, Q = 1. PatchDrawCTX2 (bit 1) resends the positions on context 2 with ST into the bottom half (the frame copy) plus normal.xz * refractScale, colour 1 and alpha = Fresnel. Derived.
  • SetupMaterial for water copies the temp buffer squashed into its top half and the frame squashed into its bottom half, then sets ALPHA_1 = Cs, ALPHA_2 = (Cd - Cs) As + Cs, TEST GEQUAL on both contexts, ZBUF_2 masked and region clamps to each half. With a texture, InitTexRegs replaces TEX0_1 by the patch texture. Sure (matched C++).
  • Every water patch on the disc is textured with draw mode 2 (environment UVs, refraction pass), so the projective and mirror-group paths are unused. The SDL view (zoldviewwatersdl.cpp) follows the textured path.

The mirror target for mirror groups is rendered by BeginWaterMirrors / DrawMirror with the normal programs; plain mirrors (ZOldDrawIdListMirror) use the strip programs only, with destination-alpha masking (zoldviewmirrorsdl.cpp does the same with a stencil mask).

VU_GrassDraw: grass

PrimInstanceCreateScatter uploads the program constants to 0x3e0 (sprite GIF tag with ST, RGBAQ, XYZF2, ST, XYZF2; tile and vertex bank addresses; width, height, random height; draw distance and 0.0025; baseline and object count; scale; colour A and billboard count; colour B), the eight master tile headers (V4-32: object counts of the two triangles of a cell and the first object) and the objects (V3-8: barycentric x and y and the random height, with the distribution byte masked into w), then per sub-grid of up to 8x8 cells a header (start position, lStopX | lStopZ << 4) and the TileFlexVertexPS2_t vertices (position delta and master tile id, RGB and a size weight). PrimInstanceCreate adds the object matrix at 0x3e8, the root-to-screen matrix at 0x3eb, the root clip planes at 0x3ef and m_ScatterLightPS2 at 0x3f5.

  • InitObject (0x1bb) converts colours and objects to floats over 255, scales width and height by the camera focal lengths (cammisc), and moves the camera and the four scatter lights into object space.
  • DrawPatch (0x013), first loop: positions accumulate delta * scale + baseline from the left neighbour (from the row above for the first column); colour = vertex RGB / 255 * campos.w + sum light colour (1 - clamp((d - near) * invRange)), times 128 and clamped; alpha = (1 - clamp((distance - fDrawDist) * 0.0025)) * 64. Light distances use the integer inverse square root trick (0x5f3759df).
  • Second loop: per cell with a master tile id below 8, non-zero summed fade alpha and a frustum test, rinit with the first vertex's x, then for the two triangles (top-left, below, right) and (below, below-right, right) each object is placed by barycentric weights; size weight, colour and fade interpolate the same way; colour is tinted by A r + B (1 - r) with r from rnext; the billboard is a GS sprite from (x - w/2, y - h) to (x + w/2, y) in screen space with h = (H + z RH) * weight, UVs from the table built in uvloop (t / types to (t + 1) / types, mirrored for entries 4 to 7) and V from 1/128 to 127/128. GS state: TEST = alpha GREATER than lAlphaRef with AFAIL FB_ONLY and depth GREATER, ALPHA 0x44, fog. Derived.

VUStaticShadowDraw and VUStaticShadowDrawTex: static shadows

DrawShadowsOfType (matched) uploads the program, sets alpha on or off through ITOP before MSCAL 0, transfers each shadow primitive's instance chain with DIRECT, then MSCAL 4 (FlushOutBuffer). The instance chain (PrimInstanceCreate type 10, original constants) puts m_TransferMatrixHomogeneousScaleBias (projection, offset, scale) at TOPS+0..5, (m_fFogScale, m_fFogAdd) at TOPS+6 (V2-32), the shadow colour at TOPS+11 (V4-8; grey 0x808080 for lerp shadows, lDiffuseColor otherwise), then calls the mesh chain from PrimInstanceCreateStaticShadow: for textured shadows the 12 floats at lTempHeader as V3-32 ×4 at TOPS+7..10, then MSCAL 2 (InitPODRegs) and the raw stream at uVifStreamPrim (iSizeOfVifStream bytes). There is no object matrix: shadow meshes are in root space. Here m_fFogScale = -1/(fogFar - fogNear) and m_fFogAdd = fogFar/(fogFar - fogNear), so the fog term is a fade, 1 at the fog near distance and 0 at the far one. Sure (matched C++ and instructions).

  • InitRegs (MSCAL 0) kicks PRIM = 0x0c (Gouraud triangle strip), or 0x4c with ITOP ≠ 0 (alpha blending on); the Tex program uses 0x1c/0x5c (textured). Strip GIF tags have NREG 2 (RGBAQ, XYZ2), or 3 (ST, RGBAQ, XYZ2) for Tex; true-clipped triangles go out as fans (0x0d/0x4d). Sure.
  • Stream batches (docs/development/port/prim-decode.md, static shadow meshes): STROW origin, TOPS+0 = (index count, vertex scale), TOPS+1 = bounding sphere, TOPS+2+i = (x, y, z, intensity), TOPS+0x82 = index bytes, then MSCAL 8 (DrawStrips). Sure (all 1,726 meshes on the disc give lNumTriangles).
  • Per vertex: clip = P·(x, y, z, 1)·scale, colour = int(vf27 · I · fade) with vf27 = colour/128 (Tex: /256), I the intensity byte and fade = clamp(fogAdd + fogScale·W, 0, 1); XYZ2 has no fog. The RGBAQ alpha holds the program's clip bookkeeping (1 or 0x3f); Tex writes alpha 0x40. Tex writes STQ = (s, t, q)/W with (s, t, q) = x·P0 + y·P1 + z·P2 + P3 from the lTempHeader floats; s/q and t/q lie in [0, 1] for every textured mesh in M00. Derived.
  • ADC (no triangle) is set when the index byte has bit 7, when any vertex of the triangle is outside the frustum (those are redrawn by pickup_trueclips/true_clip as fans), or when the screen-space signed area of the triangle is negative: the cross product alternates its operand order with the index position in the batch (the four entries of the unrolled loop), so the test is a consistent back-face cull. In the strip decoder's winding the culled set is the back faces. Derived; the culled side agrees with the shadows the M00 captures show on the house.
  • process_spherecheck (0x28e) tests the batch sphere against the six frustum planes built in InitPODRegs and picks the clipping or non-clipping loop, or skips the batch.

DrawStaticShadows (matched) groups the layer's entries:

  • Lerp (bIsLerp) shadows darken the frame towards a colour. ChooseShadowColors keeps the first two distinct lerp colours and averages all others into a third; the colours are sorted ascending and colour c gets byte c of the temp buffer (FRAME mask ~(0xff << 8c)). The temp buffer is cleared to (0, 0, 0, 0x80); Z test GEQUAL against the frame's Z, Z writes off.
  • Untextured lerp shadows add into their byte (ALPHA_1 = Cd + Cs·FIX, FIX 0x80, COLCLAMP on), or overwrite it when the scene sets PS2_DisableStaticShadowAdditive (ITOP 0, no blending; M00 does).
  • Textured lerp shadows draw twice with Tex: Cd − Cs, then Cd + Cs, each clamped, which leaves max(Cd, Cs). With MODULATE the value is texel · I · fade / 256. The textures are white shapes on black (Wheel_shadow_01, tree_shadow_06).
  • The merge reads each byte as an 8-bit index through m_LinearAPalette (alpha = index, RGB 0x80) with vertex colour (R, G, B, 0x40), so As = index/2 and the frame becomes lerp(Cd, colour, index/256).
  • Non-lerp shadows are drawn straight into the frame with Cd + Cs: they brighten (light pools), with colour lDiffuseColor/128 · I · fade (times the texel for textured ones).
  • With PS2_EnableStaticShadowSeamsFixup the untextured lerp result is dilated by one pixel into neighbouring uncovered pixels (alpha still 0x80) and those pixels are faded through g_uShadowDialationFadePalette indexed by a Z-buffer byte. M00 does not enable it.

Both shadow paths discard front faces (SHADOW_CULL_FRONT_FACES). A decoded triangle whose winding agrees with its normals is a back face in the pipeline.

VProjClip: projected (dynamic) shadows

Used by DrawShadowReceivers and BeginShadows and GenerateCasterTexture, uploaded as [VProjClip_Begin, GetClipPlane_End). Casters (InitCastRegs 0x23a, cast_draw 0x1b3) are drawn flat into a shadow texture from the light's view (ioiFpuViewScreenMatrix with a light projection, zolddrawps2.cpp:3020), with bone deformation for characters (DrawStripsBone, BonesDeform). Receivers (DrawProjObject 0x195, do_receiver) get projective texture coordinates from the light matrix (gen_TxCrds 0x2e3, proj_loop) and light attenuation (Apply_Light 0x344: omni, spot, square spot). Port as a shadow-map pass plus a receiver shader with projective lookup. Structure derived.

VU_SplashDraw: rain splashes

DrawRoomRainSplashes sends visible triangles (ZSplashTriangle: three points with seeds) and VU_SplashDraw_Init (0x137) sets constants (0x3eb to 0x3f6). triloop (0x00b) picks splash positions inside each triangle from the seeds, frameloop (0x02a) selects the animation frame, and the VCL loop (0x08b) emits textured quads per splash. Structure derived.

VUScrPass: screen passes

Used by Z2DFunctions and the post filters. Each sprite_* entry reads TOP+0 = start position and steps, TOP+1 = texture start and steps, TOP+2 = column and row counts, TOP+3 = colour or flags, and emits a grid of screen-aligned SPRITEs (double-buffered output at 0x004 and 0x204 or 0x000 and 0x200): sprite_XxY_ST (ST × 1/16384), sprite_64x16_UV (12.4 UV), sprite_64x16_ST, sprite_XxY_Noise (random offsets per row/column). IndexFetch builds page lists for CLUT-based colour remapping (the curves filter reads the frame buffer as an 8-bit texture through a palette). DrawShimmer (0x21d) draws displaced strips for the heat shimmer. The port implements these as explicit full-screen passes; the VU only tiles the screen. Derived.

Details the port's post filter (postfiltersdl.cpp) reproduces:

  • sprite_XxY_Noise (0x035) reads six quadwords at 0x3fa (CreateVU1CopyChainNoise): start and step positions, row and column counts, the vertex count (nX+1)(nY+1), the UV scale, the noise colour, five seeds and the minimum and maximum. For every grid vertex it advances the random register R: alpha = int(64 × lerp(min, max, r)), then a UV offset in [0, 1) from further rnext/rxor steps. Each 64×64 cell is a Gouraud triangle strip with ST from 1/128 + offset to + scale × 127/128 (the 64×64 noise texture repeats), RGB = int(colour × 128), and the alpha of its four corner vertices. With the post filter's 0x44 blend the result is lerp(frame, n × colour, n × alpha / 128) for noise value n. Sure.
  • DrawShimmer reads (texU, texV), the strip GIF tag, (2048 − W/2, 2048 − H/2, W, H) and (32, ys, offset, uscale × 32), then 32 row seeds. It builds a grid of ceil(W/32)+3 by ceil(H/ys)+3 vertices starting one cell up and left, shifted down by offset. Row r re-seeds R with seed r & 31; every vertex moves by ((seed − 1.5) × amp, (rnext − 1.5) × amp) while its ST stays on the regular grid, and consecutive rows form triangle strips. Sure.
  • IndexFetch sprites carry Z = 0xffff (word 2 of the page-list header), so CopyZBufGToDrawA's GEQUAL test only writes the Z palette alpha where Z24 ≤ 0xffff; nearer pixels keep the FillDraw value, which is the palette entry for G = 0xff. Sure.

VU_LoaderSeq: loading screen sequence

Kicks the packet at mem[1].z, then for each picture finds the two keyframes around the current time (find_keys 0x015, time at mem[0].x), interpolates position and parameters (compute_blend 0x02d), and draws textured quads (draw_texture 0x04e). Plain 2D. Derived.

5. VU0 programs

  • VLightTest (0x000) and InitLightRegs (0x19c): per-vertex light colours for static primitives with lighting enabled (CheckPrimLightEnabled), run from m_pLightChain (ZVifChain0) when the geom's BASEGEOM_LightDirty is set. InitLightRegs reads the geom's root matrix (0..2), environment direction and colours (4..6), the light quadword pairs (7 + 2i, copied to 0xe8) and the light count and 2-bit types at 0xe7. UnpackVerts turns the vertex packets (positions × scale, normals n/64) into the in-place layout, the Calc* loops accumulate, and PackColors writes R | G << 8 | B << 16 per vertex (clamped to 255) to 0x80 + address/4, which AddPrimChunksToDMAChain later unpacks at TOPS+3 as the light colour L of Apply_VertexColors. PrimInstanceCreate also gives a light buffer, filled with 0x7f7f7f, to strips, wire strips and splines whose geom has BASEGEOM_DynamicLit (0x8000); PrimCreate builds m_pLightChain only when CheckPrimLightEnabled holds, so those buffers keep 0x7f7f7f. Settled against a simulation (sure unless noted), with n and positions in object space and d·n using the environment direction m0[0] transformed by the transposed root matrix:
    • environment, non-directional: L = (dir + amb)/2 + (amb - dir)/2 · (d·n); directional: L = amb + (dir - amb) · max(0, -d·n), with dir = vDirectionColor × multiplier and amb = vAmbientColor × multiplier;
    • omni (type 1): L += vTransferColor × multiplier · clamp(fLightConst1 - dist·fInverseFarMinusNear, 0, 1) · max(0, n·l);
    • spot (type 0): the colour is the transfer half-bytes × multiplier clamped to 255, the axis is the C++'s byte-packed m0[0] ((byte - 127.5)/128, rotated into object space and normalised), the falloff cosine is the packed byte (b + 127.5)/255, and the cone term is smoothstep(clamp((-(axis·l) - cosFall)·fLightConst2, 0, 1));
    • square spot (type 2): light-space coordinates against the packed m0[0] and m0[2] axes, f = clamp((1 - |x/z|/tan_x)/(1 - hot), 0, 1) per axis with tan_x = tan(fall)·sqrt(aspect) and tan_y = tan_x/aspect, and smoothstep(f_x)·smoothstep(f_y). Approximate: 297 of 300 random samples match, the rest differ by up to 14/255 near the edges (the program derives the tangents from the packed angle bytes with its own sine series).
  • Light types: the engine enum names LIGHTTYPE_OMNI (0) and LIGHTTYPE_SPOT (1) are the other way round from the data. Type 1 lights carry SPrimLightOmniPS2 fields (ZOMNILIGHT modifies them through ModifyOmniLight) and are the point lights of CalcOmni; type 0 lights carry SPrimLightSpotPS2 fields and are the cones of CalcSpot. The disc has 2,263 type 1, 570 type 0 and 305 type 2 lights over all scenes. The port names them LIGHT_POINT, LIGHT_CONE and LIGHT_SQUARE (lightssdl.h).
  • Checking the light programs. The lighting survey used a Python interpreter built on vu_disasm.py's decoder: pair semantics, FMAC stalls, Q latency (7 for div/sqrt, 13 for rsqrt, waitq stalling the pair), MAC flags read four cycles late, and bit-preserving abs/max/mini on integer data. Harnesses replay the VIF data of ZOldDrawPS2::UpdateLight, the EE vcallms loops of calclightdot3.cpp (the newlight segments are pipelined across calls, four vertices deep) and the HQ block of CreatePrettyLightsBuffer, and fit the formulas above on random inputs.
  • newlight has five native C++ lighting routines in src/engine/drawing/old/_ps2/calclightdot3.cpp. The SDL renderer shares their per-vertex calculations. The square spot applies smoothstep to the product of the two clipped edge factors. The direction weight has a floor of 0.0001 for omni lights and 0.0002 for spotlights before multiplication by luminance.
  • MatMulMat (0x000 to 0x00c and its twin 0x00d to 0x019, which VU0ExecBoneMats alternates to pipeline two bones): for bone B (a ZBone, loaded so vf01..vf04 = X, Y, Z axes and position) and inverse bind matrix I (12 floats, IOI order), it writes DeformBones()[i] in VU1 row order: vmmul(I.m0[2], B), vmmul(I.m0[1], B), vmmul(I.m0[0], B), vmmul(I.p0, B) + B.p0, where vmmul(v, M) = v.x·M.m0[2] + v.y·M.m0[1] + v.z·M.m0[0]. The packing mr32 moves of each routine store the previous bone's result. The native implementation is in src/engine/drawing/old/_ps2/BoneMatFixPS2.cpp.
  • MatToParent: Init (0x02a) sets constants; SlowExec (0x02d) turns the local bone's quaternion (x, y, z, w) and position (words 0 to 6 of the bone slot) into the column-vector rotation matrix with s = 2/|q|²; MulMats (0x040) multiplies it by the parent (vf01..vf04 = parent X, Y, Z axes and position) so the child X axis is R00·PX + R10·PY + R20·PZ (Y and Z alike, columns 1 and 2) and the position PX·p.x + PY·p.y + PZ·p.z + Pp. VU0ExecParentBoneMatsSafe stores the result back over the slot as a ZBone (m0[0] = Z axis, m0[2] = X axis) for bones 1 to n-1, with byte offsets into the bone array from the prim's lParentBones list. The native implementation is in src/engine/drawing/old/_ps2/BoneParentMatPS2.cpp.

Open items

  • The water, grass and dot3 constants still need a trace on the original renderer.
  • Backface winding in VColClip/VLineClip/VColClipBone, the exact square-spot tangent of VLightTest, particle physics, wobble, environment map scale and dot3 pass encoding need a full trace or a PCSX2 comparison before they are final; the water and grass formulas above are read from the listings and have not been compared with PCSX2.
  • The diffuse colour byte order still needs a check against a disc file.