Files
Thomas MartinandClaude Opus 5.5 0d5dd2d33f The game's own GIF packets, read natively at their send
Every GS packet the game builds itself is now read from the structures it
was built from, as a list of register writes, instead of parsing GIF tags:
Spr_draw's sprites, Screen_blur_draw, Gifreg_set_dma's tables, scroll_disp's
rain and mist layers, oniGsMoveImage, the effects' sprite arrays (add_scr_efc,
esp_sp00), StencilMapPolygon's pond and Md_draw_semi's semi-transparent parts.
ONI_NATIVE_GIF=0 keeps the packets, =compare checks both kick by kick:
identical on all 188 story states (126,821 sends, 19.5 million kicks).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-29 16:51:10 +01:00

2050 lines
99 KiB
C++

// Onimusha's VU1 path, natively. Md_tag_trans 0x130e40 starts VIF1's DMA on a part's chain (a source chain, the tags'
// upper halves sent to VIF1 as VIF codes): this walks the same chain, runs VIF1's commands on a VU1 state kept here
// (its 16 KB data memory, the double-buffer registers, the program in micro memory), runs the translated microprograms
// (oni_vu1_gen.py) where the chain starts them, and turns each GIF packet a program kicks (XGKICK) or the chain sends
// (DIRECT) into the frame's draws: screen-space triangles with the GS's Z, Q and the draw state the packet sets.
#include "oni_vu1.h"
#include "oni_native3d.h"
#include "oni_render.h"
#include "oni_tex.h"
#include "bozo/app/profiler.h"
#include "bozo/state.h"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <deque>
#include <mutex>
#include <thread>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <string>
#include <set>
#include <vector>
namespace oni::vu1
{
namespace
{
using bozo::render::Material;
using bozo::render::Vertex;
int trace()
{
static const int level = [] { const char *e = std::getenv("ONI_VU1_TRACE"); return e ? std::atoi(e) : 0; }();
return level;
}
// ---- The GS state the packets set, and the triangles they draw ----
struct GsVertex
{
float x, y, z, s, t, q, u, v, fog;
uint32_t rgba;
};
struct Gs
{
uint64_t prim = 0;
uint64_t tex0[2] = {}, tex1[2] = {}, clamp[2] = {}, alpha[2] = {}, test[2] = {}, zbuf[2] = {};
uint64_t fogcol = 0, texa = 0;
uint64_t frame[2] = {};
// SCISSOR_1 / _2: SCAX0, SCAX1, SCAY0, SCAY1 in the frame buffer's pixels (the field's lines); the whole field
// until the game sets it.
uint64_t scissor[2] = {0x00df0000027f0000ull, 0x00df0000027f0000ull};
uint64_t bitbltbuf = 0, trxpos = 0, trxreg = 0;
std::vector<uint8_t> image; // an IMAGE transfer's texels so far (TRXDIR started it)
bool imaging = false;
uint32_t rgba = 0x80808080u;
float s = 0, t = 0, q = 1.0f;
uint32_t uv = 0;
uint32_t fog = 0xff;
GsVertex queue[3];
int queued = 0; // vertices in the queue
int fanFirst = -1; // a fan's first vertex is kept in queue[0]
// The batch being built: the material it was built with and its triangles.
std::vector<Vertex> batch;
uint64_t batchKey[10] = {};
bool skip = false; // the batch is not drawn (it writes nothing the PC frame keeps, or reads an unknown target)
bool fromTarget = false; // the batch samples the shadow target: u, v from the position
bool fromPrevious = false; // the batch samples the previous frame (a display buffer read back)
bool batchOpen = false;
Material material;
std::shared_ptr<const bozo::render::Texture> texture;
uint64_t triangles = 0, batches = 0, missingTextures = 0, uploads = 0;
float lo[4] = {1e30f, 1e30f, 1e30f, 1e30f}, hi[4] = {-1e30f, -1e30f, -1e30f, -1e30f}; // x, y, z, q seen
} g_gs;
int64_t g_programNs = 0, g_chainNs = 0, g_kickNs = 0, g_cycles = 0; // time in the programs (their kicks included), in whole chains
constexpr uint32_t kShadowPage = 0xd2; // FRAME.FBP of the shadows' buffer
constexpr uint8_t kShadowImage = 3; // its renderer auxiliary image
uint32_t g_display = 0; // the display buffer (FRAME page 0 or 0x46) the frame is drawn into
std::set<uint32_t> g_targets; // off-screen targets' first blocks (FRAME.FBP x 32)
// The draws made from the packets, in their order, until the frame's end hands them to the renderer (drain: on the
// game's thread, after the room's picture and before the 2D).
struct PendingDraw
{
float clip[4]; // the GS's scissor on the frame (GS primitive coordinates)
Material material;
std::vector<Vertex> vertices;
std::shared_ptr<const bozo::render::Texture> texture;
};
std::vector<PendingDraw> g_pending;
void waitForWorker(); // (below: the chains' thread)
bool g_noDraw = false; // (the GIF comparison) the native side's kicks recorded, nothing drawn
void flush()
{
Gs &gs = g_gs;
if (g_noDraw) // (the comparison's native run: nothing handed on; the state is restored after it)
{
gs.batch.clear();
gs.batchOpen = false;
return;
}
if (gs.batchOpen && !gs.batch.empty() && !gs.skip)
{
// SCISSOR: x as it is, the field's lines doubled to the frame's (an event's cinema bars are outside it).
const uint64_t sc = gs.scissor[(gs.prim >> 9) & 1];
const bozo::render::Screen s = oni::render::screen();
if (trace() >= 3) // each drawn batch: its registers and its vertices' extent in the frame
{
float bx0 = 1e9f, by0 = 1e9f, bx1 = -1e9f, by1 = -1e9f, bz0 = 1e30f, bz1 = -1e30f;
for (const auto &v : gs.batch)
{
bx0 = std::min(bx0, v.x), bx1 = std::max(bx1, v.x);
by0 = std::min(by0, v.y), by1 = std::max(by1, v.y);
bz0 = std::min(bz0, v.z), bz1 = std::max(bz1, v.z);
}
const int c = (gs.prim >> 9) & 1;
std::printf("[oni:vu1] batch prim %03llx frame %llx tex0 %016llx alpha %llx test %llx zbuf %llx scissor %016llx: %zu vertices, (%.0f,%.0f)-(%.0f,%.0f) z %.0f..%.0f\n",
(unsigned long long)gs.prim, (unsigned long long)gs.frame[c], (unsigned long long)gs.tex0[c],
(unsigned long long)gs.alpha[c], (unsigned long long)gs.test[c], (unsigned long long)gs.zbuf[c], (unsigned long long)gs.scissor[c], gs.batch.size(), bx0, by0, bx1, by1, bz0, bz1);
}
const float x0 = static_cast<float>(sc & 0x7ff), x1 = static_cast<float>((sc >> 16) & 0x7ff) + 1.0f;
const float y0 = static_cast<float>((sc >> 32) & 0x7ff), y1 = static_cast<float>((sc >> 48) & 0x7ff) + 1.0f;
PendingDraw d{{s.originX + std::max(0.0f, x0), s.originY + std::max(0.0f, y0 * 2.0f),
s.originX + std::min(s.width, x1), s.originY + std::min(s.height, y1 * 2.0f)},
gs.material, std::move(gs.batch), gs.texture};
g_pending.push_back(std::move(d));
gs.batch = {};
++gs.batches;
}
else if (gs.batchOpen && !gs.batch.empty() && trace() >= 2)
std::printf("[oni:vu1] batch skipped: prim %03llx frame %llx tex0 %016llx alpha %llx test %llx zbuf %llx\n",
(unsigned long long)gs.prim, (unsigned long long)gs.frame[(gs.prim >> 9) & 1],
(unsigned long long)gs.tex0[(gs.prim >> 9) & 1], (unsigned long long)gs.alpha[(gs.prim >> 9) & 1],
(unsigned long long)gs.test[(gs.prim >> 9) & 1], (unsigned long long)gs.zbuf[(gs.prim >> 9) & 1]);
gs.batch.clear();
gs.batchOpen = false;
}
// The material from the GS registers of the primitive's context.
void openBatch()
{
Gs &gs = g_gs;
const int c = (gs.prim >> 9) & 1;
const uint64_t key[10] = {gs.prim & 0x7f8, gs.tex0[c], gs.tex1[c], gs.clamp[c], gs.alpha[c], gs.test[c], gs.zbuf[c], gs.fogcol,
gs.frame[c], gs.scissor[c]};
if (gs.batchOpen && std::equal(key, key + 10, gs.batchKey))
return;
flush();
std::copy(key, key + 10, gs.batchKey);
gs.skip = false;
gs.batchOpen = true;
Material m;
const bool tme = (gs.prim >> 4) & 1, fge = (gs.prim >> 5) & 1, abe = (gs.prim >> 6) & 1;
m.textured = tme;
gs.texture = nullptr;
if (tme)
{
const uint64_t tex0 = gs.tex0[c];
m.tex0 = tex0;
const uint32_t tfx = static_cast<uint32_t>(tex0 >> 35 & 3u);
m.textureFunction = tfx == 1 ? Material::TextureFunction::Decal
: tfx == 2 ? Material::TextureFunction::Highlight
: tfx == 3 ? Material::TextureFunction::Highlight2
: Material::TextureFunction::Modulate;
m.textureAlpha = (tex0 >> 34 & 1u) != 0;
gs.texture = oni::tex::fromTex0(tex0);
if (!gs.texture)
{
// Not uploaded: the frame or another target read back (the screen effects' passes), not drawn.
++gs.missingTextures;
gs.skip = true;
}
m.nearest = ((gs.tex1[c] >> 5) & 1u) == 0;
const uint32_t wms = gs.clamp[c] & 3u, wmt = (gs.clamp[c] >> 2) & 3u;
m.clampU = wms == 1;
m.clampV = wmt == 1;
m.useQ = ((gs.prim >> 8) & 1) == 0;
}
if (abe)
{
const uint64_t a = gs.alpha[c];
m.gsBlend = true;
m.blendA = a & 3;
m.blendB = (a >> 2) & 3;
m.blendC = (a >> 4) & 3;
m.blendD = (a >> 6) & 3;
m.blendFix = static_cast<uint8_t>(a >> 32);
// A 24-bit frame (FRAME.PSM 1) has no alpha: the GS reads its destination alpha as 0x80 (Ad: FIX 128).
if (m.blendC == 1 && ((gs.frame[c] >> 24) & 0x3fu) == 1u)
m.blendC = 2, m.blendFix = 0x80;
}
else
m.blend = Material::Blend::Opaque;
const uint64_t test = gs.test[c];
if (test & 1u)
{
m.alphaTest = true;
m.alphaFunc = static_cast<Material::AlphaFunc>((test >> 1) & 7u);
m.alphaRef = static_cast<uint8_t>(test >> 4);
}
const bool zte = (test >> 16) & 1u;
const uint32_t ztst = (test >> 17) & 3u;
m.depthTest = zte && ztst >= 2;
m.depthGreater = ztst == 3;
m.depthWrite = ((gs.zbuf[c] >> 32) & 1u) == 0;
// FRAME.FBMSK: a channel whose bits are all masked is not written.
const uint32_t fbmsk = static_cast<uint32_t>(gs.frame[c] >> 32);
m.colourMask = 0;
for (int k = 0; k < 4; ++k)
if (((fbmsk >> (8 * k)) & 0xffu) != 0xffu)
m.colourMask |= 1u << k;
if (m.colourMask == 0 && !m.depthWrite)
gs.skip = true;
// The frame is CT24 (FRAME.PSM 1): its alpha is not kept, a blend changes only the colour. On the PC the frame's
// alpha is what covers the backdrop (the room's picture under the 3D): a blended draw leaves it as it is.
if (abe && ((gs.frame[c] >> 24) & 0x3fu) == 1u)
m.colourMask &= 0x7u;
// An untextured primitive's colour is what the GS writes (bytes), not a 0x80-unit modulation.
m.directColour = !tme;
// FRAME.FBP: the display's two field buffers are pages 0 and 0x46 (640 x 224, 32 bits). A draw elsewhere goes
// to an off-screen target: the shadows' buffer at 0xd2 (cleared to grey, the shadow volumes counted in its
// colour against the scene's depth, graded to 0x14 where shadowed), read back by the pass that darkens the
// frame with it. Natively an auxiliary image of the renderer sharing the frame's depth (Material::frameDepth).
const uint32_t fbp = static_cast<uint32_t>(gs.frame[c] & 0x1ffu);
gs.fromTarget = false;
if (fbp >= 0x8cu)
{
if (fbp != kShadowPage)
gs.skip = true; // no other target is known
m.target = kShadowImage;
m.frameDepth = true;
g_targets.insert(fbp * 32u);
}
// A texture read from such a target: the target's image (u, v over the frame), or nothing (blocks an earlier
// scene uploaded to may still be kept).
if (tme && g_targets.count(static_cast<uint32_t>(gs.tex0[c] & 0x3fffu)))
{
if ((gs.tex0[c] & 0x3fffu) == kShadowPage * 32u)
{
gs.skip = false;
gs.fromTarget = true;
m.fromFrame = 1;
m.source = kShadowImage;
m.nearest = true;
m.useQ = false;
if (!gs.texture)
--gs.missingTextures;
gs.texture = nullptr;
}
else
gs.skip = true;
}
// A texture read from a display buffer (pages 0 and 0x46: blocks 0 and 0x8c0): the one the frame is drawn into
// is the frame so far (an effect copying the scene, into the shadows' target or over itself), the other the
// previous frame (Screen_blur_draw's motion blur); u, v the field's texels over the frame.
gs.fromPrevious = false;
// (A context whose FRAME the game never set (0: Screen_blur_draw's context 2) draws into the display buffer
// of the frame: it does not say which one that is; reading it as page 0 made the blur's copy of the previous
// frame the frame so far, and the cinema bars went under the blur in stage 2 room 30's event.)
if (fbp < 0x8cu && gs.frame[c] != 0)
g_display = fbp;
if (tme)
{
const uint32_t tbp = static_cast<uint32_t>(gs.tex0[c] & 0x3fffu);
if (tbp == 0u || tbp == 0x8c0u)
{
const bool current = tbp == g_display * 32u;
gs.skip = gs.skip && m.target && fbp != kShadowPage; // (an unknown target stays undrawn)
gs.fromPrevious = true;
m.fromFrame = 1;
m.source = current ? 0 : Material::kPreviousFrame;
m.nearest = current; // (source 0 and filtering: mip levels from the copy)
m.useQ = false;
if (!gs.texture)
--gs.missingTextures;
gs.texture = nullptr;
}
}
static const bool noBlur = std::getenv("ONI_NO_BLUR") != nullptr; // diagnostic: no draw reading a display buffer
if (noBlur && gs.fromPrevious)
gs.skip = true;
static const bool noShadows = [] { const char *e = std::getenv("ONI_SHADOWS"); return e && *e == '0'; }();
if (noShadows && (m.target || gs.fromTarget))
gs.skip = true;
static const bool noDepth = std::getenv("ONI_VU1_NODEPTH") != nullptr;
if (noDepth)
m.depthTest = false;
if (fge)
{
m.fog = true;
m.fogColour = static_cast<uint32_t>(gs.fogcol & 0xffffffu);
}
static const bool noTex = std::getenv("ONI_VU1_NOTEX") != nullptr; // diagnostic: vertex colours only
if (noTex && m.textured)
{
m.textured = false;
gs.texture = nullptr;
}
static const bool flat = std::getenv("ONI_VU1_FLAT") != nullptr; // diagnostic: plain opaque triangles
if (flat)
{
m = Material{};
m.textured = false;
m.blend = Material::Blend::Opaque;
m.depthTest = false;
gs.texture = nullptr;
}
gs.material = m;
}
Vertex toVertex(const GsVertex &g)
{
Gs &gs = g_gs;
const bozo::render::Screen s = oni::render::screen();
Vertex v;
v.x = g.x;
v.y = s.originY + (g.y - 1936.0f) * 2.0f; // the field's lines to the frame's
v.z = g.z;
v.rgba = g.rgba;
v.fog = g.fog / 255.0f;
const int c = (gs.prim >> 9) & 1;
if (gs.fromPrevious) // a display buffer (the frame so far or the previous one): its field texels over the frame
{
v.u = g.u / 640.0f;
v.v = g.v / 224.0f;
v.q = 1.0f;
}
else if (gs.fromTarget) // the shadow target, over the frame
{
v.u = (v.x - s.originX) / s.width;
v.v = (v.y - s.originY) / s.height;
v.q = 1.0f;
}
else if ((gs.prim >> 8) & 1) // FST: UV in texels
{
const float tw = static_cast<float>(1u << ((gs.tex0[c] >> 26) & 15u));
const float th = static_cast<float>(1u << ((gs.tex0[c] >> 30) & 15u));
v.u = g.u / tw;
v.v = g.v / th;
v.q = 1.0f;
}
else
{
const float q = g.q != 0.0f ? g.q : 1.0f;
v.u = g.s / q;
v.v = g.t / q;
v.q = q;
}
return v;
}
void triangle(const GsVertex &a, const GsVertex &b, const GsVertex &c)
{
Gs &gs = g_gs;
openBatch();
for (const GsVertex *g : {&a, &b, &c})
{
Vertex v = toVertex(*g);
static const bool flat = std::getenv("ONI_VU1_FLAT") != nullptr;
if (flat)
{
if ((gs.prim & 7u) == 6u)
return; // no sprites
const uint32_t h = static_cast<uint32_t>(gs.batches * 2654435761u);
v.rgba = 0x80000000u | (h & 0xffffffu);
v.q = 1.0f;
}
gs.batch.push_back(v);
const float f[4] = {v.x, v.y, v.z, v.q};
for (int k = 0; k < 4; ++k)
{
gs.lo[k] = std::min(gs.lo[k], f[k]);
gs.hi[k] = std::max(gs.hi[k], f[k]);
}
}
++gs.triangles;
}
// (ONI_NATIVE3D=compare) The vertices a chain kicks, recorded: the program's and the native path's.
struct Kick
{
uint32_t x, y, z, fog;
bool adc;
float s, t, q;
uint32_t rgba;
uint32_t prim = 0;
// (the GIF comparison) the draw state the kick is drawn with: its context's TEX0, ALPHA, TEST, ZBUF, FRAME; UV
uint64_t tex0 = 0, alpha = 0, test = 0, zbuf = 0, frame = 0;
uint32_t uv = 0;
};
std::vector<Kick> *g_record = nullptr;
// A vertex kick (XYZ2 / XYZF2): the primitive assembled as the GS does; adc: XYZ's ADC bit (queued, no draw).
void kickVertex(uint32_t x, uint32_t y, uint32_t z, uint32_t fog, bool adc)
{
Gs &gs = g_gs;
if (g_record)
{
const int c = (gs.prim >> 9) & 1;
g_record->push_back({x, y, z, fog, adc, gs.s, gs.t, gs.q, gs.rgba, static_cast<uint32_t>(gs.prim), gs.tex0[c], gs.alpha[c],
gs.test[c], gs.zbuf[c], gs.frame[c], gs.uv});
}
if (g_noDraw)
return; // (the comparison's native run: recorded only; the GS's state is restored after it)
GsVertex v{static_cast<float>(x) / 16.0f, static_cast<float>(y) / 16.0f, static_cast<float>(z), gs.s, gs.t, gs.q,
static_cast<float>(gs.uv & 0x3fff) / 16.0f, static_cast<float>((gs.uv >> 16) & 0x3fff) / 16.0f,
static_cast<float>(fog), gs.rgba};
const uint32_t type = gs.prim & 7u;
switch (type)
{
case 3: // triangles
gs.queue[gs.queued++] = v;
if (gs.queued == 3)
{
if (!adc)
triangle(gs.queue[0], gs.queue[1], gs.queue[2]);
gs.queued = 0;
}
break;
case 4: // strip
if (gs.queued == 3)
{
gs.queue[0] = gs.queue[1];
gs.queue[1] = gs.queue[2];
gs.queued = 2;
}
gs.queue[gs.queued++] = v;
if (gs.queued == 3 && !adc)
triangle(gs.queue[0], gs.queue[1], gs.queue[2]);
break;
case 5: // fan
if (gs.queued == 3)
{
gs.queue[1] = gs.queue[2];
gs.queued = 2;
}
gs.queue[gs.queued++] = v;
if (gs.queued == 3 && !adc)
triangle(gs.queue[0], gs.queue[1], gs.queue[2]);
break;
case 6: // sprite: two corners
gs.queue[gs.queued++] = v;
if (gs.queued == 2)
{
if (trace() >= 2)
{
const int c = (gs.prim >> 9) & 1;
std::printf("[oni:gif] sprite prim %03llx (%.0f,%.0f)-(%.0f,%.0f) z %.0f rgba %08x tex0 %016llx alpha %016llx test %llx zbuf %llx\n",
(unsigned long long)gs.prim, gs.queue[0].x, gs.queue[0].y, gs.queue[1].x, gs.queue[1].y,
gs.queue[1].z, gs.queue[1].rgba, (unsigned long long)gs.tex0[c], (unsigned long long)gs.alpha[c],
(unsigned long long)gs.test[c], (unsigned long long)gs.zbuf[c]);
}
if (!adc)
{
const GsVertex &a = gs.queue[0], &b = gs.queue[1];
GsVertex c = a, d = a;
c.x = b.x; c.s = b.s; c.u = b.u;
d.y = b.y; d.t = b.t; d.v = b.v;
c.rgba = d.rgba = b.rgba;
c.z = d.z = b.z;
triangle(a, c, d);
GsVertex e = b;
triangle(c, e, d);
}
gs.queued = 0;
}
break;
default: // points and lines: not drawn
gs.queued = 0;
break;
}
}
void setPrim(uint64_t value)
{
g_gs.prim = value & 0x7ff;
g_gs.queued = 0;
}
uint64_t g_unknownAd = 0;
const char *g_source = "?"; // what sends the packets being parsed (traces)
// A register write (A+D or REGLIST).
void writeRegister(uint32_t reg, uint64_t value)
{
Gs &gs = g_gs;
switch (reg)
{
case 0x00: setPrim(value); break;
case 0x01: gs.rgba = static_cast<uint32_t>(value); { uint32_t q = static_cast<uint32_t>(value >> 32); std::memcpy(&gs.q, &q, 4); } break;
case 0x02: { uint32_t s = static_cast<uint32_t>(value), t = static_cast<uint32_t>(value >> 32); std::memcpy(&gs.s, &s, 4); std::memcpy(&gs.t, &t, 4); } break;
case 0x03: gs.uv = static_cast<uint32_t>(value); break;
case 0x101: gs.rgba = static_cast<uint32_t>(value); break; // (native reading: a PACKED RGBAQ, which keeps Q)
case 0x04: kickVertex(value & 0xffff, (value >> 16) & 0xffff, (value >> 32) & 0xffffff, (value >> 56) & 0xff, false); break;
case 0x05: kickVertex(value & 0xffff, (value >> 16) & 0xffff, static_cast<uint32_t>(value >> 32), gs.fog, false); break;
case 0x06: gs.tex0[0] = value; break;
case 0x07: gs.tex0[1] = value; break;
case 0x08: gs.clamp[0] = value; break;
case 0x09: gs.clamp[1] = value; break;
case 0x0a: gs.fog = static_cast<uint32_t>(value >> 56); break;
case 0x0c: kickVertex(value & 0xffff, (value >> 16) & 0xffff, (value >> 32) & 0xffffff, (value >> 56) & 0xff, true); break;
case 0x0d: kickVertex(value & 0xffff, (value >> 16) & 0xffff, static_cast<uint32_t>(value >> 32), gs.fog, true); break;
case 0x14: gs.tex1[0] = value; break;
case 0x15: gs.tex1[1] = value; break;
case 0x3b: gs.texa = value; break;
case 0x3d: gs.fogcol = value; break;
case 0x42: gs.alpha[0] = value; break;
case 0x43: gs.alpha[1] = value; break;
case 0x47: gs.test[0] = value; break;
case 0x48: gs.test[1] = value; break;
case 0x50: gs.bitbltbuf = value; break;
case 0x51: gs.trxpos = value; break;
case 0x52: gs.trxreg = value; break;
case 0x53: // TRXDIR: host to local starts a transfer
gs.image.clear();
gs.imaging = (value & 3) == 0;
// Local to local: a copy between the kept images (Texmove_entry's texture scrolls).
if ((value & 3) == 2 && !oni::tex::copyLocal(gs.bitbltbuf, gs.trxpos, gs.trxreg) && trace())
std::printf("[oni:gif] local->local (%s) bitbltbuf %016llx trxpos %016llx trxreg %016llx not made\n", g_source,
(unsigned long long)gs.bitbltbuf, (unsigned long long)gs.trxpos, (unsigned long long)gs.trxreg);
break;
case 0x4c:
gs.frame[0] = value;
if (trace() >= 2)
std::printf("[oni:gif] FRAME_1 fbp %llx fbw %llu psm %llx fbmsk %08llx\n", (unsigned long long)(value & 0x1ff),
(unsigned long long)((value >> 16) & 0x3f), (unsigned long long)((value >> 24) & 0x3f),
(unsigned long long)(value >> 32));
break;
case 0x4d: gs.frame[1] = value; break;
case 0x4e: gs.zbuf[0] = value; break;
case 0x4f: gs.zbuf[1] = value; break;
case 0x3f: // TEXFLUSH
case 0x16: case 0x17: // TEX2
case 0x18: case 0x19: // XYOFFSET
case 0x1a: // PRMODECONT
case 0x1b: // PRMODE
case 0x1c: // TEXCLUT
case 0x22: // SCANMSK
case 0x34: case 0x35: case 0x36: case 0x37: // MIPTBP
break;
case 0x40:
gs.scissor[0] = value;
if (trace() >= 2)
std::printf("[oni:gif] SCISSOR_1 (%s) x %llu..%llu y %llu..%llu\n", g_source, (unsigned long long)(value & 0x7ff),
(unsigned long long)((value >> 16) & 0x7ff), (unsigned long long)((value >> 32) & 0x7ff),
(unsigned long long)((value >> 48) & 0x7ff));
break;
case 0x41: gs.scissor[1] = value; break;
case 0x44: case 0x45: case 0x46: // DIMX, DTHE, COLCLAMP
case 0x49: case 0x4a: case 0x4b: // PABE, FBA
case 0x54: // HWREG
case 0x60: // SIGNAL...
case 0x61: case 0x62: case 0x7f:
break;
default:
if (trace() && g_unknownAd++ < 32)
std::printf("[oni:gif] register 0x%02x = %016llx not handled\n", reg, (unsigned long long)value);
break;
}
}
// One GIF packet from qwords (get(i): the i-th qword); max: qwords available. Returns the qwords read.
template <typename Get>
uint32_t gifPacket(Get get, uint32_t max)
{
Gs &gs = g_gs;
uint32_t at = 0;
for (int guard = 0; guard < 4096 && at < max; ++guard)
{
uint64_t tag[2];
get(at++, tag);
const uint32_t nloop = tag[0] & 0x7fff;
const bool eop = (tag[0] >> 15) & 1;
const bool pre = (tag[0] >> 46) & 1;
const uint32_t flg = (tag[0] >> 58) & 3;
uint32_t nreg = (tag[0] >> 60) & 15;
if (!nreg)
nreg = 16;
if (trace() >= 5)
{
std::printf("[oni:gif] tag %016llx %016llx\n", (unsigned long long)tag[0], (unsigned long long)tag[1]);
for (uint32_t k = 0; k < std::min<uint32_t>(nreg * 2, max - at); ++k)
{
uint64_t q[2];
get(at + k, q);
std::printf("[oni:gif] %016llx %016llx\n", (unsigned long long)q[1], (unsigned long long)q[0]);
}
}
if (pre && flg == 0)
setPrim((tag[0] >> 47) & 0x7ff);
if (flg == 0)
{
for (uint32_t l = 0; l < nloop && at < max; ++l)
for (uint32_t r = 0; r < nreg && at < max; ++r)
{
uint64_t q[2];
get(at++, q);
const uint32_t reg = (tag[1] >> (4 * r)) & 15;
const uint32_t w0 = static_cast<uint32_t>(q[0]), w1 = static_cast<uint32_t>(q[0] >> 32);
const uint32_t w2 = static_cast<uint32_t>(q[1]), w3 = static_cast<uint32_t>(q[1] >> 32);
switch (reg)
{
case 0x0: setPrim(q[0]); break;
case 0x1: gs.rgba = (w0 & 0xff) | (w1 & 0xff) << 8 | (w2 & 0xff) << 16 | (w3 & 0xff) << 24; break;
case 0x2: std::memcpy(&gs.s, &w0, 4); std::memcpy(&gs.t, &w1, 4); std::memcpy(&gs.q, &w2, 4); break;
case 0x3: gs.uv = (w0 & 0x3fff) | (w1 & 0x3fff) << 16; break;
case 0x4: kickVertex(w0 & 0xffff, w1 & 0xffff, (w2 >> 4) & 0xffffff, (w3 >> 4) & 0xff, (w3 >> 15) & 1); break;
case 0x5: kickVertex(w0 & 0xffff, w1 & 0xffff, w2, gs.fog, (w3 >> 15) & 1); break;
case 0xa: gs.fog = (w3 >> 4) & 0xff; break;
case 0xc: kickVertex(w0 & 0xffff, w1 & 0xffff, (w2 >> 4) & 0xffffff, (w3 >> 4) & 0xff, true); break;
case 0xd: kickVertex(w0 & 0xffff, w1 & 0xffff, w2, gs.fog, true); break;
case 0xe: writeRegister(w2 & 0xff, q[0]); break;
case 0xf: break;
default: writeRegister(reg, q[0]); break; // TEX0, CLAMP: the register's own 64 bits
}
}
}
else if (flg == 1)
{
const uint32_t words = nloop * nreg;
for (uint32_t k = 0; k < words; k += 2)
{
if (at >= max)
break;
uint64_t q[2];
get(at++, q);
writeRegister((tag[1] >> (4 * (k % nreg))) & 15, q[0]);
if (k + 1 < words)
writeRegister((tag[1] >> (4 * ((k + 1) % nreg))) & 15, q[1]);
}
}
else
{
// IMAGE: texels for local memory, after TRXDIR; kept as an upload once the rectangle is complete.
for (uint32_t l = 0; l < nloop && at < max; ++l)
{
uint64_t q[2];
get(at++, q);
if (gs.imaging)
gs.image.insert(gs.image.end(), reinterpret_cast<const uint8_t *>(q), reinterpret_cast<const uint8_t *>(q) + 16);
}
if (gs.imaging)
{
const uint32_t psm = (gs.bitbltbuf >> 56) & 0x3f;
const uint32_t bpp = psm == 0 ? 32 : psm == 1 ? 24 : (psm == 2 || psm == 0xa) ? 16 : psm == 0x13 ? 8 : psm == 0x14 ? 4 : 32;
const uint64_t need = ((gs.trxreg & 0xfff) * ((gs.trxreg >> 32) & 0xfff) * bpp + 7) / 8;
if (gs.image.size() >= need)
{
oni::tex::upload(gs.bitbltbuf, gs.trxpos, gs.trxreg, gs.image.data(), gs.image.size());
++gs.uploads;
// Texels written over a target's block (the shadows' buffer, 0x1a40, which a room's water
// movie also uses: stage 3 room 7): until something is drawn into it again, a read of that
// block is the texture, not the target.
g_targets.erase(static_cast<uint32_t>((gs.bitbltbuf >> 32) & 0x3fffu));
gs.imaging = false;
gs.image.clear();
}
}
}
if (eop)
break;
}
return at;
}
// ---- VIF1 and VU1 ----
struct Vif
{
uint32_t base = 0, offset = 0, tops = 0, top = 0, itops = 0, itop = 0;
bool dbf = false;
uint32_t cl = 1, wl = 1, mode = 0, mask = 0;
uint32_t row[4] = {}, col[4] = {};
const Program *program = nullptr;
uint32_t extent = 0; // pairs uploaded from micro address 0
uint32_t next = 0; // MSCNT's pc
R5900Context regs;
alignas(16) uint8_t mem[16384] = {};
alignas(16) uint8_t micro[16384] = {};
uint64_t unknownPrograms = 0, runs = 0;
};
Vif &vif()
{
static Vif *v = new Vif;
return *v;
}
void kick(Vu1Io &io, uint32_t qword)
{
g_source = "vu1";
if (trace() >= 3)
std::printf("[oni:vu1] xgkick %03x\n", qword);
const auto t0 = std::chrono::steady_clock::now();
gifPacket([&](uint32_t i, uint64_t q[2]) { std::memcpy(q, quad(io, qword + i), 16); }, 1024);
g_kickNs += std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - t0).count();
}
// The native maths against the program's packet (ONI_NATIVE3D_COMPARE).
struct CompareStats
{
uint64_t batches = 0, vertices = 0, xyz = 0, adc = 0, rgba = 0, stq = 0, printed = 0;
} g_compare;
std::map<std::string, uint64_t> g_runs; // (ONI_NATIVE3D_COMPARE: each program's runs)
// (ONI_NATIVE3D_COMPARE: each queued model tag's OCW, from Md_draw_entry_clip; the chain being run's.)
std::map<uint32_t, uint32_t> g_models;
uint32_t g_ocw = 0;
void compareBatch(const char *name, const uint8_t *before, uint32_t top, uint32_t clip, const uint8_t *after)
{
std::vector<uint32_t> out;
uint32_t at = 0;
oni::native3d::modelBatch(*oni::native3d::program(name), before, top, clip, out, at);
CompareStats &c = g_compare;
++c.batches;
const uint32_t n = static_cast<uint32_t>(out.size() / 4 - 1) / 3;
// A vertex in no drawn triangle (ADC on it and on the next two: the guard band's outside, where 1/w magnifies
// the rounding) is not compared but for its ADC.
auto adcAt = [&](uint32_t k) { return k >= n || (out[4 * (1 + 3 * k) + 11] & 0x8000u) != 0; };
for (uint32_t k = 0; k < n; ++k)
{
const uint32_t *e = out.data() + 4 * (1 + 3 * k);
const bool hidden = adcAt(k) && adcAt(k + 1) && adcAt(k + 2);
uint32_t g[12];
for (int r = 0; r < 3; ++r)
std::memcpy(g + 4 * r, after + (((at + 1 + 3 * k + r) & 0x3ffu) << 4), 16);
++c.vertices;
bool bad = false;
auto f = [](uint32_t b) { float x; std::memcpy(&x, &b, 4); return x; };
for (int i = 0; i < 3 && !hidden; ++i)
if (std::abs(f(e[i]) - f(g[i])) > 1e-4f * std::max(1.0f, std::abs(f(g[i])))) { ++c.stq; bad = true; break; }
for (int i = 4; i < 7; ++i)
if (std::abs(static_cast<int32_t>(e[i]) - static_cast<int32_t>(g[i])) > 1) { ++c.rgba; bad = true; break; }
if ((e[7] & 0xff) != (g[7] & 0xff)) { ++c.rgba; bad = true; }
for (int i = 8; i < 11 && !hidden; ++i)
if (std::abs(static_cast<int32_t>(e[i]) - static_cast<int32_t>(g[i])) > 2) { ++c.xyz; bad = true; break; }
if ((e[11] & 0xffff) != (g[11] & 0xffff)) { ++c.adc; bad = true; }
if (bad && c.printed++ < 12)
{
std::printf("[oni:native3d] %s top %x vertex %u/%u:\n native", name, top, k, n);
for (int i = 0; i < 12; ++i) std::printf(" %08x", e[i]);
std::printf("\n vu1 ");
for (int i = 0; i < 12; ++i) std::printf(" %08x", g[i]);
std::printf("\n");
}
}
}
void run(Vif &v, uint32_t pc)
{
// MSCAL / MSCNT: the double buffer swaps, ITOP latched.
v.top = v.tops;
v.itop = v.itops;
if (v.dbf)
{
v.tops = v.base;
v.dbf = false;
}
else
{
v.tops = v.base + v.offset;
v.dbf = true;
}
if (!v.program)
{
++v.unknownPrograms;
return;
}
Vu1Io io;
io.mem = v.mem;
io.top = v.top;
io.itop = v.itop;
io.kick = kick;
// ONI_NATIVE3D_COMPARE=1: each batch of the programs oni_native3d.cpp has, also computed natively from the
// same memory and compared with what the program wrote (a diagnostic of the native maths).
static const bool compare = std::getenv("ONI_NATIVE3D_COMPARE") != nullptr;
const bool cmp = compare && oni::native3d::program(v.program->name) && pc != 0;
if (compare)
++g_runs[v.program->name];
// ONI_SHADOW_DUMP=1: the shadow program's batches, their inputs and what they kick (a diagnostic).
static const bool shadowDump = std::getenv("ONI_SHADOW_DUMP") != nullptr;
const bool dumpShadow = shadowDump && std::strcmp(v.program->name, "shadow") == 0 && pc != 0;
std::vector<Kick> shadowKicks;
if (dumpShadow)
{
static int batches = 0;
if (batches++ < 6)
{
auto f = [&](uint32_t q, int k) { float x; std::memcpy(&x, v.mem + ((q & 0x3ffu) << 4) + 4 * k, 4); return x; };
auto w = [&](uint32_t q, int k) { uint32_t x; std::memcpy(&x, v.mem + ((q & 0x3ffu) << 4) + 4 * k, 4); return x; };
const uint32_t top = io.top;
std::printf("[oni:shadow] batch at %x (pc %x): tag %08x %08x %08x %08x\n", top, pc, w(top, 0), w(top, 1), w(top, 2), w(top, 3));
for (int c = 0; c < 17; ++c)
std::printf("[oni:shadow] const %2d: %g %g %g %g | %08x %08x %08x %08x\n", c, f(c, 0), f(c, 1), f(c, 2), f(c, 3), w(c, 0), w(c, 1), w(c, 2), w(c, 3));
const uint32_t n = w(top, 0) & 0x7fff;
for (uint32_t k = 0; k < n; ++k)
{
float p[4] = {f(top + 1 + k, 0), f(top + 1 + k, 1), f(top + 1 + k, 2), f(top + 1 + k, 3)};
float c[4] = {};
for (int r = 0; r < 4; ++r)
c[r] = f(4, r) * p[0] + f(5, r) * p[1] + f(6, r) * p[2] + f(7, r) * p[3];
const float aw = std::abs(c[3]);
int fl = 0;
for (int a = 0; a < 3; ++a)
fl |= (c[a] > aw ? 1 : 0) << (2 * a) | (c[a] < -aw ? 2 : 0) << (2 * a);
std::printf("[oni:shadow] in %2u: %g %g %g %g clip %02x\n", k, p[0], p[1], p[2], p[3], fl);
}
g_record = &shadowKicks;
}
}
std::vector<uint8_t> before;
uint32_t clipBefore = 0;
if (cmp)
before.assign(v.mem, v.mem + sizeof v.mem), clipBefore = v.regs.vu0_clip_flags;
const auto t0 = std::chrono::steady_clock::now();
v.next = v.program->run(&v.regs, io, pc);
if (dumpShadow && g_record == &shadowKicks)
{
g_record = nullptr;
for (size_t k = 0; k < shadowKicks.size(); ++k)
{
const Kick &a = shadowKicks[k];
std::printf("[oni:shadow] kick %2zu: prim %03llx %x,%x,%x adc %d rgba %08x\n", k, (unsigned long long)g_gs.prim, a.x, a.y, a.z,
a.adc, a.rgba);
}
}
if (cmp)
compareBatch(v.program->name, before.data(), io.top, clipBefore, v.mem);
g_programNs += std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - t0).count();
++v.runs;
g_cycles += static_cast<int64_t>(io.cycles);
if (io.fault != ~0u)
std::fprintf(stderr, "[oni:vu1] %s: pc 0x%x not translated\n", v.program->name, io.fault);
if (trace() >= 2)
std::printf("[oni:vu1] run %s at %x -> %x (%llu cycles)\n", v.program->name, pc, v.next, (unsigned long long)io.cycles);
}
uint64_t fnv(const uint8_t *p, size_t n)
{
uint64_t h = 0xCBF29CE484222325ull;
for (size_t i = 0; i < n; ++i)
h = (h ^ p[i]) * 0x100000001B3ull;
return h;
}
// UNPACK: num elements of vn + 1 components of vl's width to VU memory from address (qwords).
uint32_t unpack(Vif &v, uint32_t cmd, uint32_t num, uint32_t imm, const uint32_t *words, uint32_t available)
{
const uint32_t vn = (cmd >> 2) & 3, vl = cmd & 3;
const bool masked = (cmd >> 4) & 1, usn = (imm >> 14) & 1, flg = (imm >> 15) & 1;
const uint32_t n = num ? num : 256;
uint32_t address = imm & 0x3ff;
if (flg)
address += v.tops;
const uint32_t bits = vl == 0 ? 32 : vl == 1 ? 16 : vl == 2 ? 8 : 16; // V4-5: 16 bits a vertex
const uint32_t components = vl == 3 ? 1 : vn + 1;
const uint32_t sizeWords = (n * components * bits + 31) / 32;
const uint8_t *data = reinterpret_cast<const uint8_t *>(words);
uint32_t element = 0;
auto read = [&](uint32_t index) -> uint32_t
{
const uint32_t byteAt = index * bits / 8;
if (byteAt + bits / 8 > available * 4)
return 0;
if (bits == 32)
{
uint32_t x;
std::memcpy(&x, data + byteAt, 4);
return x;
}
if (bits == 16)
{
uint16_t x;
std::memcpy(&x, data + byteAt, 2);
return usn ? x : static_cast<uint32_t>(static_cast<int32_t>(static_cast<int16_t>(x)));
}
const uint8_t x = data[byteAt];
return usn ? x : static_cast<uint32_t>(static_cast<int32_t>(static_cast<int8_t>(x)));
};
const uint32_t cl = v.cl ? v.cl : 1, wl = v.wl ? v.wl : 1;
for (uint32_t j = 0; j < n; ++j)
{
uint32_t qaddr, cycle;
bool fill = false;
if (wl <= cl)
{
qaddr = address + (j / wl) * cl + (j % wl);
cycle = j % wl;
}
else
{
qaddr = address + j;
cycle = j % wl;
fill = cycle >= cl;
}
uint32_t value[4] = {};
if (!fill)
{
if (vl == 3)
{
const uint32_t c = read(element++);
value[0] = (c & 0x1f) << 3;
value[1] = ((c >> 5) & 0x1f) << 3;
value[2] = ((c >> 10) & 0x1f) << 3;
value[3] = ((c >> 15) & 1) << 7;
}
else if (vn == 0)
{
const uint32_t c = read(element++);
value[0] = value[1] = value[2] = value[3] = c;
}
else
{
for (uint32_t k = 0; k <= vn; ++k)
value[k] = read(element++);
// V2: z, w are x, y again; V3: w is undefined (left as the next data's would leave it: x).
if (vn == 1)
{
value[2] = value[0];
value[3] = value[1];
}
}
}
uint8_t *q = v.mem + ((qaddr & 0x3ff) << 4);
for (uint32_t f = 0; f < 4; ++f)
{
const uint32_t m = masked ? (v.mask >> ((std::min(cycle, 3u) * 8) + f * 2)) & 3 : (fill ? 1u : 0u);
if (!masked && vn == 2 && f == 3 && vl != 3 && !fill)
continue; // V3's w: not written here
uint32_t out;
if (m == 0)
{
out = value[f];
if (v.mode == 1)
out += v.row[f];
else if (v.mode == 2)
out = v.row[f] = v.row[f] + value[f];
}
else if (m == 1)
out = v.row[f];
else if (m == 2)
out = v.col[std::min(cycle, 3u)];
else
continue;
std::memcpy(q + 4 * f, &out, 4);
}
}
return sizeWords;
}
uint64_t g_chains = 0, g_vifUnknown = 0;
// VIF1's commands over the chain's words (the tags' upper halves at qword offsets 2 and 3).
// w: the words VIF1 sees; grid: each one's place in the DMA's qwords (a tag's lower half is not VIF1's, but DIRECT's
// data starts on a qword of that grid).
void vifStream(Vif &v, const std::vector<uint32_t> &w, const std::vector<uint32_t> &grid)
{
size_t i = 0;
while (i < w.size())
{
const uint32_t code = w[i++];
const uint32_t cmd = (code >> 24) & 0x7f, num = (code >> 16) & 0xff, imm = code & 0xffff;
if (trace() >= 4)
std::printf("[oni:vif] %08x\n", code);
if (cmd >= 0x60)
{
i += unpack(v, cmd, num, imm, w.data() + i, static_cast<uint32_t>(w.size() - i));
continue;
}
switch (cmd)
{
case 0x00: case 0x06: case 0x07: case 0x10: case 0x11: case 0x13: break;
case 0x01: v.cl = imm & 0xff; v.wl = (imm >> 8) & 0xff; break;
case 0x02: v.offset = imm & 0x3ff; v.dbf = false; v.tops = v.base; break;
case 0x03: v.base = imm & 0x3ff; break;
case 0x04: v.itops = imm & 0x3ff; break;
case 0x05: v.mode = imm & 3; break;
case 0x14: case 0x15: run(v, (imm * 8) & 0x3fff); break;
case 0x17: run(v, v.next); break;
case 0x20: if (i < w.size()) v.mask = w[i++]; break;
case 0x30: for (int k = 0; k < 4 && i < w.size(); ++k) v.row[k] = w[i++]; break;
case 0x31: for (int k = 0; k < 4 && i < w.size(); ++k) v.col[k] = w[i++]; break;
case 0x4a:
{
const uint32_t n = num ? num : 256;
const uint32_t at = (imm * 8) & 0x3fff;
const size_t words = std::min<size_t>(2 * n, w.size() - i);
std::memcpy(v.micro + at, w.data() + i, std::min<size_t>(words * 4, sizeof v.micro - at));
i += 2 * n;
// The program in micro memory: the MPGs from address 0 on, known by its words' hash.
v.extent = at == 0 ? n : at == v.extent * 8 ? v.extent + n : 0;
v.program = nullptr;
if (v.extent)
{
const uint64_t h = fnv(v.micro, v.extent * 8);
for (size_t k = 0; k < kProgramCount; ++k)
if (kPrograms[k].hash == h && kPrograms[k].pairs == v.extent)
v.program = &kPrograms[k];
}
if (!v.program && trace())
std::printf("[oni:vif] MPG of %u pairs at %x: not a known program\n", n, at);
break;
}
case 0x50: case 0x51:
{
while (i < w.size() && (grid[i] & 3u))
++i; // DIRECT's data starts at a qword
const uint32_t n = imm ? imm : 65536;
const size_t avail = (w.size() - i) / 4;
const uint32_t* data = w.data() + i;
gifPacket([&](uint32_t k, uint64_t q[2]) { std::memcpy(q, data + 4 * k, 16); }, static_cast<uint32_t>(std::min<size_t>(n, avail)));
i += 4 * size_t(n);
break;
}
default:
if (g_vifUnknown++ < 16)
std::fprintf(stderr, "[oni:vif] VIF code %08x not handled\n", code);
return;
}
}
}
} // namespace
void state(bozo::state::Archive &a)
{
waitForWorker(); // (a frame boundary: nothing is pending)
using bozo::state::fields;
Vif &v = vif();
// VIF1's registers, VU1's (the vector, integer and special registers of the context holding them), its two
// memories and the program in micro memory (by its index in kPrograms).
fields(a, v.base, v.offset, v.tops, v.top, v.itops, v.itop, v.dbf, v.cl, v.wl, v.mode, v.mask, v.row, v.col, v.extent,
v.next);
a.raw(v.regs.vu0_vf, sizeof v.regs.vu0_vf);
a.raw(&v.regs.vu0_acc, sizeof v.regs.vu0_acc);
fields(a, v.regs.vi, v.regs.vu0_q_bits, v.regs.vu0_i_bits, v.regs.vu0_p_bits, v.regs.vu0_status, v.regs.vu0_mac,
v.regs.vu0_clip_flags);
a.raw(v.mem, sizeof v.mem);
a.raw(v.micro, sizeof v.micro);
int32_t program = v.program ? static_cast<int32_t>(v.program - kPrograms) : -1;
fields(a, program);
// The GS registers the packets set (a frame boundary: no primitive or transfer half done).
Gs &gs = g_gs;
fields(a, gs.prim, gs.tex0, gs.tex1, gs.clamp, gs.alpha, gs.test, gs.zbuf, gs.fogcol, gs.texa, gs.frame, gs.bitbltbuf,
gs.trxpos, gs.trxreg, gs.rgba, gs.s, gs.t, gs.q, gs.uv, gs.fog, g_targets);
if (a.loading())
{
v.program = program >= 0 && static_cast<size_t>(program) < kProgramCount ? &kPrograms[program] : nullptr;
gs.queued = 0;
gs.imaging = false;
gs.image.clear();
gs.batch.clear();
gs.batchOpen = false;
gs.texture = nullptr;
}
}
namespace
{
// A chain's data, copied when the game sends it (it may change its memory once the transfer is "done"), and
// run in order: VIF1's stream (with each word's place) or the GIF's.
// ---- Native models (docs/NATIVE_3D.md) ----
// A model as Md_draw_entry_clip queued it, gathered from the game's structures on the game's thread: its frame
// environment (a GIF packet of A+D writes: TEXFLUSH, TEX1, FOGCOL, CLAMP, RGBAQ), the clip and screen matrices
// (Gm), its lights (pLc, pLv) and joints (pWnmat), and each object the game linked into its chain (its program,
// its environment (TEST), its colour scale (Rgbf), each group's environment (TEX0, MIPTBP1, PRIM) and arrays).
struct NativeModel
{
struct Group
{
std::vector<uint8_t> env;
uint32_t count = 0;
std::vector<uint8_t> positions, normals, uvs, mats, weights;
};
struct Object
{
const oni::native3d::Program *program = nullptr;
std::vector<uint8_t> env;
oni::native3d::V4 scale{};
uint32_t fog = 0;
std::vector<Group> groups;
};
std::vector<uint8_t> frameEnv;
oni::native3d::M4 clip{}, screen{}, lightColour{}, lightDir{};
std::vector<float> joints;
std::vector<Object> objects;
std::string desc; // (the comparison) what was gathered
};
uint32_t g_nativeClip = 0; // the clip flags of the last vertices (the programs': kept from part to part)
oni::native3d::V4 g_nativeRecent[2] = {}; // the last two vertices' screen positions (the back-face programs')
// The shadows' two chains (shadow.c), read natively: SHADOW_VIF1DMA_TAG's (the GS's setup, the program's 17
// constants; the program itself is not needed) and Pd's (the GS's setup, each part's volume, the stencil's draw).
struct NativeShadow
{
struct Step
{
bool gif = false; // a GIF packet the chain sends (DIRECT); else a part (an UNPACK of its qwords)
std::vector<uint8_t> data;
};
std::vector<Step> steps;
std::vector<uint8_t> constants; // (the setup chain's)
};
std::vector<uint8_t> g_shadowConstants; // the last setup's (the chains' worker)
uint64_t g_shadowFans = 0; // (the comparison) triangles clipped into fans
std::vector<uint32_t> g_where; // (the comparison) each recorded native kick's object << 24 | group << 16 | vertex
struct Job
{
enum class Kind
{
Vif,
Gif,
Draw, // a frame draw made on the game's thread (the 2D, the room's picture), in its place among the others
Model, // a model drawn natively (with words: also the program's chain, compared)
Shadow, // a shadow chain read natively (with words: also the program's, compared)
} kind = Kind::Vif;
uint32_t tag = 0;
std::vector<uint32_t> words, grid;
std::vector<uint8_t> stream;
PendingDraw draw;
std::shared_ptr<NativeModel> model;
std::shared_ptr<NativeShadow> shadow; // (Kind::Shadow)
std::shared_ptr<std::vector<oni::native3d::GsOp>> ops; // (Kind::Gif) the send read natively
};
// A packet of the game's A+D blocks (its frame, object and group environments) applied to the GS state.
void applyEnv(const std::vector<uint8_t> &packet)
{
g_source = "model env";
gifPacket([&](uint32_t k, uint64_t q[2]) { std::memcpy(q, packet.data() + 16 * k, 16); },
static_cast<uint32_t>(packet.size() / 16));
}
// The model drawn: its environments, then each group's vertices 48 at a time (the chain's batches), each vertex's
// STQ, RGBA and XYZF2 kicked as the program's packet would kick them. record: only recorded (the comparison).
void drawModel(const NativeModel &m, std::vector<Kick> *record)
{
if (!record)
applyEnv(m.frameEnv);
oni::native3d::Constants k;
k.clip = m.clip, k.screen = m.screen, k.lightColour = m.lightColour, k.lightDir = m.lightDir;
k.joints = m.joints.data();
k.jointCount = static_cast<uint32_t>(m.joints.size() / 16);
std::vector<uint32_t> words;
if (record)
g_where.clear();
uint32_t objectIndex = 0;
for (const NativeModel::Object &o : m.objects)
{
const uint32_t groupBase = objectIndex++ << 24;
uint32_t groupIndex = 0;
if (!record)
applyEnv(o.env);
k.scale = o.scale, k.fog = o.fog;
for (const NativeModel::Group &g : o.groups)
{
const uint32_t where = groupBase | groupIndex++ << 16;
if (!record)
applyEnv(g.env);
for (uint32_t first = 0; first < g.count; first += 48)
{
oni::native3d::Batch b;
b.count = std::min<uint32_t>(48, g.count - first);
b.positions = g.positions.data() + 16 * first, b.normals = g.normals.data() + 12 * first;
b.uvs = g.uvs.data() + 4 * first, b.mats = g.mats.data() + 4 * first, b.weights = g.weights.data() + 2 * first;
words.resize(12 * b.count);
oni::native3d::drawBatch(*o.program, k, b, g_nativeClip, g_nativeRecent, words.data());
Gs &gs = g_gs;
for (uint32_t v = 0; v < b.count; ++v)
{
const uint32_t *w = words.data() + 12 * v;
float s, t, q;
std::memcpy(&s, w, 4), std::memcpy(&t, w + 1, 4), std::memcpy(&q, w + 2, 4);
const uint32_t rgba = (w[4] & 0xff) | (w[5] & 0xff) << 8 | (w[6] & 0xff) << 16 | (w[7] & 0xff) << 24;
const uint32_t x = w[8] & 0xffff, y = w[9] & 0xffff, z = (w[10] >> 4) & 0xffffff;
const uint32_t fog = (w[11] >> 4) & 0xff;
const bool adc = (w[11] >> 15) & 1;
if (record)
record->push_back({x, y, z, fog, adc, s, t, q, rgba}), g_where.push_back(where | (first + v));
else
{
gs.s = s, gs.t = t, gs.q = q, gs.rgba = rgba;
kickVertex(x, y, z, fog, adc);
}
}
}
}
}
}
// A shadow chain drawn natively (record: its kicks only recorded, the comparison).
void drawShadow(const NativeShadow &s, std::vector<Kick> *record)
{
g_source = "shadow";
if (!s.constants.empty())
g_shadowConstants = s.constants;
Gs &gs = g_gs;
std::vector<oni::native3d::GsOp> ops;
for (const NativeShadow::Step &step : s.steps)
{
if (step.gif)
{
std::vector<Kick> *saved = g_record;
g_record = record; // (the GIF packets' kicks are the GS's own: recorded as the program's are)
gifPacket([&](uint32_t k, uint64_t q[2]) { std::memcpy(q, step.data.data() + 16 * k, 16); },
static_cast<uint32_t>(step.data.size() / 16));
g_record = saved;
continue;
}
if (g_shadowConstants.size() < 17 * 16)
continue;
ops.clear();
uint64_t alpha = 0;
oni::native3d::shadowPart(g_shadowConstants.data(), step.data.data(), ops, alpha);
for (const oni::native3d::GsOp &op : ops)
{
using K = oni::native3d::GsOp::Kind;
if (op.kind == K::Prim)
{
if (record && (op.value & 7) == 5)
++g_shadowFans;
setPrim(op.value);
}
else if (op.kind == K::Register)
writeRegister(op.reg, op.value);
else if (record)
record->push_back({op.x, op.y, op.z, op.fog, op.adc, gs.s, gs.t, gs.q, gs.rgba, static_cast<uint32_t>(gs.prim)});
else
kickVertex(op.x, op.y, op.z, op.fog, op.adc);
}
}
}
// (ONI_NATIVE_GIF=compare) A send's packet against its native reading: every kick and its draw state.
struct GifCompare
{
uint64_t sends = 0, same = 0, kicks = 0, differ = 0, printed = 0, stateDiffer = 0;
} g_gifCompare;
void compareGif(const std::vector<Kick> &packet, const std::vector<Kick> &native, uint32_t tag)
{
GifCompare &c = g_gifCompare;
++c.sends;
bool all = packet.size() == native.size();
if (!all && c.printed++ < 8)
std::printf("[oni:gifnative] send %x: %zu kicks by the packet, %zu natively\n", tag, packet.size(), native.size());
for (size_t i = 0; i < std::min(packet.size(), native.size()); ++i)
{
const Kick &a = packet[i], &b = native[i];
++c.kicks;
const bool same = a.x == b.x && a.y == b.y && a.z == b.z && a.fog == b.fog && a.adc == b.adc && a.rgba == b.rgba &&
a.prim == b.prim && a.tex0 == b.tex0 && a.alpha == b.alpha && a.test == b.test && a.zbuf == b.zbuf &&
a.frame == b.frame && a.uv == b.uv && std::memcmp(&a.s, &b.s, 12) == 0;
if (!same)
{
all = false;
++c.differ;
if (c.printed++ < 8)
std::printf("[oni:gifnative] send %x kick %zu: packet %x,%x,%x rgba %08x prim %x tex0 %llx alpha %llx test %llx zbuf %llx uv %x"
" / native %x,%x,%x rgba %08x prim %x tex0 %llx alpha %llx test %llx zbuf %llx uv %x\n",
tag, i, a.x, a.y, a.z, a.rgba, a.prim, (unsigned long long)a.tex0, (unsigned long long)a.alpha,
(unsigned long long)a.test, (unsigned long long)a.zbuf, a.uv, b.x, b.y, b.z, b.rgba, b.prim,
(unsigned long long)b.tex0, (unsigned long long)b.alpha, (unsigned long long)b.test,
(unsigned long long)b.zbuf, b.uv);
if (c.printed <= 8)
std::printf("[oni:gifnative] fog %x/%x adc %d/%d frame %llx/%llx stq %08x %08x %08x / %08x %08x %08x\n", a.fog,
b.fog, a.adc, b.adc, (unsigned long long)a.frame, (unsigned long long)b.frame,
*reinterpret_cast<const uint32_t *>(&a.s), *reinterpret_cast<const uint32_t *>(&a.t),
*reinterpret_cast<const uint32_t *>(&a.q), *reinterpret_cast<const uint32_t *>(&b.s),
*reinterpret_cast<const uint32_t *>(&b.t), *reinterpret_cast<const uint32_t *>(&b.q));
}
}
if (all)
++c.same;
}
// (ONI_NATIVE3D=compare) The two paths' kicks against each other.
struct ModelCompare
{
uint64_t models = 0, same = 0, countDiffer = 0, kicks = 0, xyz = 0, adc = 0, rgba = 0, stq = 0, printed = 0;
} g_modelCompare;
void compareKicks(const std::vector<Kick> &vu, const std::vector<Kick> &native, uint32_t tag)
{
ModelCompare &c = g_modelCompare;
++c.models;
if (vu.size() != native.size())
{
++c.countDiffer;
if (c.printed++ < 8)
std::printf("[oni:native3d] model %x: %zu kicks by the program, %zu natively\n", tag, vu.size(), native.size());
return;
}
bool all = true;
for (size_t i = 0; i < vu.size(); ++i)
{
const Kick &a = vu[i], &b = native[i];
++c.kicks;
const bool hidden = a.adc && (i + 1 >= vu.size() || vu[i + 1].adc) && (i + 2 >= vu.size() || vu[i + 2].adc);
bool bad = false;
if (a.adc != b.adc) ++c.adc, bad = true;
if (!hidden && (std::abs(int(a.x) - int(b.x)) > 2 || std::abs(int(a.y) - int(b.y)) > 2 || std::abs(int(a.z) - int(b.z)) > 2))
++c.xyz, bad = true;
if (a.rgba != b.rgba) ++c.rgba, bad = true;
if (!hidden && (std::abs(a.s - b.s) > 1e-4f * std::max(1.0f, std::abs(a.s)) || std::abs(a.q - b.q) > 1e-4f * std::max(1.0f, std::abs(a.q))))
++c.stq, bad = true;
if (bad)
{
all = false;
if (c.printed++ < 8)
std::printf("[oni:native3d] (object %u group %u vertex %u)\n", g_where[i] >> 24, (g_where[i] >> 16) & 0xff, g_where[i] & 0xffff),
std::printf("[oni:native3d] model %x kick %zu: program %x,%x,%x adc %d rgba %08x stq %g,%g,%g / native %x,%x,%x adc %d rgba %08x stq %g,%g,%g\n",
tag, i, a.x, a.y, a.z, a.adc, a.rgba, a.s, a.t, a.q, b.x, b.y, b.z, b.adc, b.rgba, b.s, b.t, b.q);
}
}
if (all)
++c.same;
}
void gifStream(uint32_t tag, const std::vector<uint8_t> &stream)
{
g_source = "gif";
const uint32_t qwords = static_cast<uint32_t>(stream.size() / 16);
static const bool gifTrace = std::getenv("ONI_GIF_TRACE") != nullptr;
if (gifTrace)
{
std::printf("[oni:gifchain] tag %x: %u qwords\n", tag, qwords);
for (uint32_t q = 0, n = 0; q < qwords && n < 12; ++n)
{
uint64_t t[2];
std::memcpy(t, stream.data() + 16 * q, 16);
const uint32_t nloop = t[0] & 0x7fff, flg = (t[0] >> 58) & 3, nreg = ((t[0] >> 60) & 15) ? ((t[0] >> 60) & 15) : 16;
std::printf("[oni:gifchain] nloop %u flg %u pre %llu prim %03llx nreg %u regs %016llx\n", nloop, flg,
(unsigned long long)((t[0] >> 46) & 1), (unsigned long long)((t[0] >> 47) & 0x7ff), nreg,
(unsigned long long)t[1]);
q += 1 + (flg == 0 ? nloop * nreg : flg == 1 ? (nloop * nreg + 1) / 2 : nloop);
}
}
for (uint32_t at = 0; at < qwords;)
{
const uint32_t used = gifPacket([&](uint32_t i, uint64_t q[2]) { std::memcpy(q, stream.data() + 16 * (at + i), 16); },
qwords - at);
if (!used)
break;
at += used;
}
flush();
}
void execute(Job &job)
{
if (job.kind == Job::Kind::Draw)
g_pending.push_back(std::move(job.draw));
else if (job.kind == Job::Kind::Model)
{
++g_chains;
const auto t0 = std::chrono::steady_clock::now();
if (job.words.empty())
drawModel(*job.model, nullptr);
else
{
// The program's chain drawn, its kicks recorded; the native path recorded beside it, compared.
std::vector<Kick> vu, native;
const uint32_t clipBefore = g_nativeClip;
g_record = &vu;
vifStream(vif(), job.words, job.grid);
g_record = nullptr;
g_nativeClip = clipBefore;
drawModel(*job.model, &native);
const uint64_t before = g_modelCompare.same;
compareKicks(vu, native, job.tag);
static int said = 0; // a model that differs: what was gathered for it
if (g_modelCompare.same == before && said++ < 4)
std::printf("[oni:native3d] model %x gathered:%s\n", job.tag, job.model->desc.c_str());
}
flush();
g_chainNs += std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - t0).count();
}
else if (job.kind == Job::Kind::Shadow)
{
++g_chains;
if (job.words.empty())
drawShadow(*job.shadow, nullptr);
else
{
std::vector<Kick> vu, native;
g_record = &vu;
vifStream(vif(), job.words, job.grid);
g_record = nullptr;
// The comparison: the native reading recorded, its GS writes undone by the program's own after it.
const Gs saved = g_gs;
drawShadow(*job.shadow, &native);
g_gs.prim = saved.prim, g_gs.alpha[0] = saved.alpha[0], g_gs.alpha[1] = saved.alpha[1], g_gs.rgba = saved.rgba,
g_gs.q = saved.q, g_gs.queued = saved.queued;
compareKicks(vu, native, job.tag);
}
flush();
}
else if (job.kind == Job::Kind::Vif)
{
++g_chains;
const auto t0 = std::chrono::steady_clock::now();
vifStream(vif(), job.words, job.grid);
flush();
g_chainNs += std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - t0).count();
}
else if (job.ops)
{
auto apply = [&] {
g_source = "native gif";
for (const oni::native3d::GsOp &op : *job.ops)
writeRegister(op.reg, op.value);
};
if (job.stream.empty())
{
apply();
flush(); // (as the packet's stream ends: its kicks drawn before what follows)
}
else
{
// The comparison: the native writes on a copy of the GS's state (nothing drawn), then the packet.
std::vector<Kick> native, packet;
const Gs saved = g_gs;
g_noDraw = true;
g_record = &native;
apply();
g_record = nullptr;
g_noDraw = false;
const Gs afterNative = g_gs;
g_gs = saved;
g_record = &packet;
gifStream(job.tag, job.stream);
g_record = nullptr;
compareGif(packet, native, job.tag);
// The registers both leave (a send of register writes alone kicks nothing).
const Gs &a = g_gs, &b = afterNative;
const bool same = a.prim == b.prim && std::memcmp(a.tex0, b.tex0, sizeof a.tex0) == 0 &&
std::memcmp(a.tex1, b.tex1, sizeof a.tex1) == 0 && std::memcmp(a.clamp, b.clamp, sizeof a.clamp) == 0 &&
std::memcmp(a.alpha, b.alpha, sizeof a.alpha) == 0 && std::memcmp(a.test, b.test, sizeof a.test) == 0 &&
std::memcmp(a.zbuf, b.zbuf, sizeof a.zbuf) == 0 && std::memcmp(a.frame, b.frame, sizeof a.frame) == 0 &&
std::memcmp(a.scissor, b.scissor, sizeof a.scissor) == 0 && a.fogcol == b.fogcol && a.texa == b.texa &&
a.rgba == b.rgba && a.uv == b.uv && a.fog == b.fog;
if (!same)
{
++g_gifCompare.stateDiffer;
if (g_gifCompare.printed++ < 8)
std::printf("[oni:gifnative] send %x: the GS's registers differ after it\n", job.tag);
}
}
}
else
gifStream(job.tag, job.stream);
}
// The chains run on a thread of their own while the game goes on (the window: real time); nothing the game
// reads depends on them. Without it (the headless runner, ONI_VU1_THREAD=0) each runs when it is sent.
struct Worker
{
std::mutex mutex;
std::condition_variable wake, idle;
std::deque<Job> jobs;
bool busy = false;
void start()
{
std::thread([this] {
bozo::app::profiler::registerThread("vu1"); // (the Profiler tab, PS2X_PROFILE)
for (;;)
{
Job job;
{
std::unique_lock<std::mutex> lock(mutex);
wake.wait(lock, [this] { return !jobs.empty(); });
job = std::move(jobs.front());
jobs.pop_front();
busy = true;
}
execute(job);
{
std::lock_guard<std::mutex> lock(mutex);
busy = false;
if (jobs.empty())
idle.notify_all();
}
}
}).detach();
}
void push(Job &&job)
{
{
std::lock_guard<std::mutex> lock(mutex);
jobs.push_back(std::move(job));
}
wake.notify_one();
}
void wait()
{
std::unique_lock<std::mutex> lock(mutex);
idle.wait(lock, [this] { return jobs.empty() && !busy; });
}
};
std::atomic<bool> g_threaded{false};
Worker *g_worker = nullptr;
void submit(Job &&job)
{
if (g_threaded.load(std::memory_order_relaxed))
{
if (!g_worker)
{
g_worker = new Worker;
g_worker->start();
}
g_worker->push(std::move(job));
}
else
execute(job);
}
void waitForWorker()
{
if (g_worker)
g_worker->wait();
}
} // namespace
void setThreaded(bool on)
{
const char *e = std::getenv("ONI_VU1_THREAD");
g_threaded.store(e ? *e != '0' : on, std::memory_order_relaxed);
}
void queueDraw(const Material &material, const Vertex *vertices, uint32_t count,
std::shared_ptr<const bozo::render::Texture> texture)
{
Job job;
job.kind = Job::Kind::Draw;
job.draw.clip[0] = job.draw.clip[1] = job.draw.clip[2] = job.draw.clip[3] = 0.0f; // none
job.draw.material = material;
job.draw.vertices.assign(vertices, vertices + count);
job.draw.texture = std::move(texture);
submit(std::move(job));
}
void drain()
{
waitForWorker();
auto &r = bozo::render::Renderer::instance();
static const float kIdentity[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
// The GS's scissor: the frame (640 x 448 here, the fields' 224 lines doubled).
const bozo::render::Screen s = oni::render::screen();
(void)s;
for (PendingDraw &d : g_pending)
{
r.setClip(d.clip[0], d.clip[1], d.clip[2], d.clip[3]);
if (trace() >= 2 && &d == &g_pending.front())
std::printf("[oni:vu1] clip %.0f %.0f %.0f %.0f\n", d.clip[0], d.clip[1], d.clip[2], d.clip[3]);
static const bool order = std::getenv("ONI_DRAW_ORDER") != nullptr; // each draw of the frame, in order
if (order && !d.vertices.empty())
{
float x0 = 1e9f, y0 = 1e9f, x1 = -1e9f, y1 = -1e9f;
for (const auto &v : d.vertices)
x0 = std::min(x0, v.x), x1 = std::max(x1, v.x), y0 = std::min(y0, v.y), y1 = std::max(y1, v.y);
std::printf("[oni:draw] %s tex %016llx target %d source %d blend %d/%d%d%d%d fix %02x depth %d/%d rgba %08x: %zu vertices (%.0f,%.0f)-(%.0f,%.0f)\n",
d.material.textured ? "textured" : "flat", (unsigned long long)d.material.tex0, d.material.target,
d.material.source, static_cast<int>(d.material.blend), d.material.gsBlend ? 1 : 0, d.material.blendA,
d.material.blendB, d.material.blendC, d.material.blendFix, d.material.depthTest ? 1 : 0,
d.material.depthWrite ? 1 : 0, d.vertices.front().rgba, d.vertices.size(), x0, y0, x1, y1);
static const bool each = std::getenv("ONI_DRAW_ORDER")[0] == '2'; // ONI_DRAW_ORDER=2: and the vertices
if (each)
for (const auto &v : d.vertices)
std::printf("[oni:draw] (%.1f, %.1f, %.0f) uv %.4f %.4f q %.4f rgba %08x\n", v.x, v.y, v.z, v.u, v.v, v.q,
v.rgba);
}
r.draw(d.material, kIdentity, d.vertices.data(), static_cast<uint32_t>(d.vertices.size()), d.texture);
}
r.clearClip();
g_pending.clear();
}
namespace
{
// ONI_NATIVE_GIF: 1 a send read natively drawn from that reading (the default), 0 from its packet, compare both.
int nativeGifMode()
{
static const int mode = []
{
const char *e = std::getenv("ONI_NATIVE_GIF");
return !e ? 1 : std::strcmp(e, "compare") == 0 ? 2 : *e == '0' ? 0 : 1;
}();
return mode;
}
} // namespace
void runGifChain(uint8_t *ram, uint8_t *scratchpad, uint32_t tag, std::vector<oni::native3d::GsOp> *native)
{
const int mode = nativeGifMode();
std::shared_ptr<std::vector<oni::native3d::GsOp>> ops;
if (native && mode)
ops = std::make_shared<std::vector<oni::native3d::GsOp>>(std::move(*native));
if (ops && mode == 1)
{
Job job;
job.kind = Job::Kind::Gif;
job.tag = tag;
job.ops = std::move(ops);
submit(std::move(job));
return;
}
// A source chain to the GIF (PATH3, no TTE): the tags' data as one GIF stream.
std::vector<uint8_t> stream;
auto take = [&](uint32_t address, uint32_t qwc)
{
for (uint32_t k = 0; k < qwc; ++k)
{
const uint8_t *q = (address & 0x80000000u) ? scratchpad + ((address + 16 * k) & 0x3ff0)
: ram + ((address + 16 * k) & 0x1fffff0);
stream.insert(stream.end(), q, q + 16);
}
};
uint32_t stack[2] = {}, depth = 0, at = tag;
for (int guard = 0; guard < 65536; ++guard)
{
uint32_t t[4];
std::memcpy(t, (at & 0x80000000u) ? scratchpad + (at & 0x3ff0) : ram + (at & 0x1fffff0), 16);
const uint32_t qwc = t[0] & 0xffff, id = (t[0] >> 28) & 7, addr = t[1];
bool end = false;
switch (id)
{
case 0: take(addr, qwc); end = true; break;
case 1: take(at + 16, qwc); at += 16 + 16 * qwc; break;
case 2: take(at + 16, qwc); at = addr; break;
case 3: case 4: take(addr, qwc); at += 16; break;
case 5: take(at + 16, qwc); if (depth < 2) stack[depth++] = at + 16 + 16 * qwc; at = addr; break;
case 6: take(at + 16, qwc); if (depth) at = stack[--depth]; else end = true; break;
default: take(at + 16, qwc); end = true; break;
}
if (end)
break;
}
Job job;
job.kind = Job::Kind::Gif;
job.tag = tag;
job.stream = std::move(stream);
job.ops = std::move(ops); // (the comparison)
submit(std::move(job));
}
void runGifStream(std::vector<uint8_t> stream, uint32_t tag)
{
Job job;
job.kind = Job::Kind::Gif;
job.tag = tag;
job.stream = std::move(stream);
submit(std::move(job));
}
void runGifData(uint8_t *ram, uint8_t *scratchpad, uint32_t address, uint32_t qwc, std::vector<oni::native3d::GsOp> *native)
{
// A normal-mode transfer to the GIF (sceDmaSendN): qwc quadwords from address, one GIF stream; or its native
// reading (as runGifChain's).
const int mode = nativeGifMode();
std::shared_ptr<std::vector<oni::native3d::GsOp>> ops;
if (native && mode)
ops = std::make_shared<std::vector<oni::native3d::GsOp>>(std::move(*native));
if (ops && mode == 1)
{
Job job;
job.kind = Job::Kind::Gif;
job.tag = address;
job.ops = std::move(ops);
submit(std::move(job));
return;
}
std::vector<uint8_t> stream;
stream.reserve(static_cast<size_t>(qwc) * 16u);
for (uint32_t k = 0; k < qwc; ++k)
{
const uint8_t *q = (address & 0x80000000u) ? scratchpad + ((address + 16 * k) & 0x3ff0)
: ram + ((address + 16 * k) & 0x1fffff0);
stream.insert(stream.end(), q, q + 16);
}
Job job;
job.kind = Job::Kind::Gif;
job.tag = address;
job.stream = std::move(stream);
job.ops = std::move(ops); // (the comparison)
submit(std::move(job));
}
void noteModel(uint32_t tag, uint32_t ocw) { g_models[tag & 0x1ffffffu] = ocw; }
namespace
{
// ONI_NATIVE3D: 1 the models drawn natively (the default), 0 by the programs, compare both (the program's drawn).
int nativeMode()
{
static const int mode = []
{
const char *e = std::getenv("ONI_NATIVE3D");
if (!e)
return 1;
return std::strcmp(e, "compare") == 0 ? 2 : *e == '0' ? 0 : 1;
}();
return mode;
}
// A shadow chain's stream read as the game writes it (shadow.c: stencil_init, draw_parts, stencil_draw): its GIF
// packets (DIRECT), the setup's constants (an UNPACK of 17 qwords to 0), each part (an UNPACK of its qwords before
// its MSCNT); the program's own commands (MPG, MSCAL, BASE, OFFSET, FLUSH...) need nothing. Null for anything
// else (the chain then runs as before).
std::shared_ptr<NativeShadow> gatherShadow(const std::vector<uint32_t> &w, const std::vector<uint32_t> &grid, bool setup)
{
auto s = std::make_shared<NativeShadow>();
size_t i = 0;
while (i < w.size())
{
const uint32_t code = w[i++];
const uint32_t cmd = (code >> 24) & 0x7f, num = (code >> 16) & 0xff, imm = code & 0xffff;
switch (cmd)
{
case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07:
case 0x10: case 0x11: case 0x13: case 0x14: case 0x15: case 0x17:
break;
case 0x20: ++i; break; // STMASK
case 0x30: case 0x31: i += 4; break;
case 0x4a: i += 2 * static_cast<size_t>(num ? num : 256); break; // MPG
case 0x50: case 0x51:
{
while (i < w.size() && (grid[i] & 3u))
++i;
const size_t n = imm ? imm : 65536;
if (i + 4 * n > w.size())
return nullptr;
NativeShadow::Step step;
step.gif = true;
step.data.resize(16 * n);
std::memcpy(step.data.data(), w.data() + i, 16 * n);
s->steps.push_back(std::move(step));
i += 4 * n;
break;
}
case 0x6c: // UNPACK V4-32
{
const size_t n = num ? num : 256;
if (i + 4 * n > w.size() || (imm & 0x3ff) != 0)
return nullptr;
std::vector<uint8_t> data(16 * n);
std::memcpy(data.data(), w.data() + i, 16 * n);
i += 4 * n;
if (setup)
{
if (n != 17)
return nullptr;
s->constants = std::move(data);
}
else
{
NativeShadow::Step step;
step.data = std::move(data);
s->steps.push_back(std::move(step));
}
break;
}
default:
return nullptr;
}
}
if (setup && s->constants.empty())
return nullptr;
return s;
}
// A model the game queued (its OCW), gathered as native data; null when a part of it is not native yet (a
// program without native maths, a morphing object): then its chain runs as before.
std::shared_ptr<NativeModel> gatherModel(const uint8_t *ram, uint32_t ocw)
{
auto u32 = [&](uint32_t a) { uint32_t v; std::memcpy(&v, ram + (a & 0x1ffffffu), 4); return v; };
auto u16 = [&](uint32_t a) { uint16_t v; std::memcpy(&v, ram + (a & 0x1ffffffu), 2); return v; };
auto bytes = [&](uint32_t a, size_t n) { const uint8_t *p = ram + (a & 0x1ffffffu); return std::vector<uint8_t>(p, p + n); };
auto matrix = [&](uint32_t a) { oni::native3d::M4 m; std::memcpy(&m, ram + (a & 0x1ffffffu), 64); return m; };
auto packet = [&](uint32_t a) { return bytes(a, 16 * (1 + static_cast<size_t>(u16(a) & 0x7fff) * ((u32(a + 4) >> 28) ? (u32(a + 4) >> 28) : 16))); };
// The model work (OCW + 0x40): +0x50 objects, +0x51 joints, +0x58 pObj, +0x5c pMod, +0x64 pFenv, +0x74 pLv,
// +0x78 pLc, +0x8c pWnmat.
const uint32_t objects = ram[ocw + 0x90], joints = 43; // VU1 0-171, whatever the joint count: an attached part may name a slot past it
const uint32_t pObj = u32(ocw + 0x98), pMod = u32(ocw + 0x9c);
auto m = std::make_shared<NativeModel>();
m->frameEnv = packet(u32(ocw + 0xa4));
m->clip = matrix(0x27dc10), m->screen = matrix(0x27dc50); // Gm.Wc, Gm.Ws
m->lightColour = matrix(u32(ocw + 0xb8)), m->lightDir = matrix(u32(ocw + 0xb4));
m->joints.resize(16 * joints);
std::memcpy(m->joints.data(), ram + (u32(ocw + 0xcc) & 0x1ffffffu), 64 * joints);
// The objects in the chain's order: from the first's link (its pRef, the model's own tag), each link's
// address the head of the next one drawn (the game skips an object by linking past it).
uint32_t link = u32(pObj + 8);
const oni::native3d::Program *previous = nullptr;
const uint32_t again = u32(0x1f3d20); // Vu_move_type[20]: the program already in micro memory started again
for (uint32_t guard = 0; guard <= objects; ++guard)
{
const uint32_t head = u32(link + 4);
uint32_t i = 0;
while (i < objects && u32(pObj + 0x80 * i + 4) != head)
++i;
if (i == objects)
break;
const uint32_t o = pObj + 0x80 * i;
const uint32_t image = u32(head + 4);
const Program *vu = nullptr;
for (size_t p = 0; p < kProgramCount; ++p)
if (kPrograms[p].address == image)
vu = &kPrograms[p];
const oni::native3d::Program *program = vu ? oni::native3d::program(vu->name) : image == again ? previous : nullptr;
previous = program;
if (!program) // not native yet
{
static int said = 0;
if (nativeMode() == 2 && said++ < 8)
std::printf("[oni:native3d] model at OCW %x: object %u (%s%s) not native\n", ocw, i, vu ? vu->name : "?",
ram[o + 0x3f] ? ", morphing" : "");
return nullptr;
}
NativeModel::Object obj;
obj.program = program;
obj.env = packet(u32(o + 0x14));
std::memcpy(&obj.scale, ram + o + 0x20, 16);
obj.fog = u32(o + 0x2c) & 0xffff;
// Each group: its count from the model (@anon33's Num), its environment and its arrays where the game's own
// tags for it point (pGroup_tag: the environment's tag, then 0x90 a batch of 48: the header, then the
// positions', normals', UVs', matrices' and weights' tags at +0x30..+0x70). The game points them at the
// model's arrays, or at a morph's or a cloth's output, or at a copy whose strip flags hide a cut part
// (Md_mat_cut_off): whatever it sends is what is drawn.
const uint32_t groups = ram[o + 1], pGroup = u32(pMod + 8 + 8 * i + 4);
uint32_t gtag = u32(o + 0x18);
for (uint32_t g = 0; g < groups; ++g)
{
NativeModel::Group grp;
grp.count = u16(pGroup + 0x1c * g);
grp.env = packet(u32(gtag + 4));
const uint32_t batch = gtag + 0x10;
grp.positions = bytes(u32(batch + 0x34), 16 * grp.count);
grp.normals = bytes(u32(batch + 0x44), 12 * grp.count);
grp.uvs = bytes(u32(batch + 0x54), 4 * grp.count);
grp.mats = bytes(u32(batch + 0x64), 4 * grp.count);
grp.weights = bytes(u32(batch + 0x74), 2 * grp.count);
gtag = batch + 0x90 * ((grp.count + 47) / 48);
obj.groups.push_back(std::move(grp));
}
if (nativeMode() == 2)
{
char t[160];
std::snprintf(t, sizeof t, " [%zu: obj %u %s mime %02x groups %u head %x image %x]", m->objects.size(), i,
vu ? vu->name : "again", ram[o + 0x3f], groups, head, image);
m->desc += t;
}
m->objects.push_back(std::move(obj));
link = u32(o + 0xc); // pNext
}
return m;
}
} // namespace
void runChain(uint8_t *ram, uint8_t *scratchpad, uint32_t tag)
{
{
const auto m = g_models.find(tag & 0x1ffffffu);
g_ocw = m == g_models.end() ? 0 : m->second;
if (m != g_models.end())
g_models.erase(m);
}
std::shared_ptr<NativeModel> model;
if (nativeMode() && g_ocw)
model = gatherModel(ram, g_ocw);
{
static int said = 0;
if (nativeMode() == 2 && g_ocw && !model && said++ < 64) // (the comparison: a model left to its program)
std::printf("[oni:native3d] chain %x: OCW %x, not native\n", tag, g_ocw);
}
if (model && nativeMode() == 1)
{
Job job;
job.kind = Job::Kind::Model;
job.tag = tag;
job.model = std::move(model);
submit(std::move(job));
return;
}
// ONI_VU1=0: the models not drawn (a comparison).
static const bool on = [] { const char *e = std::getenv("ONI_VU1"); return !(e && *e == '0'); }();
if (!on)
return;
std::vector<uint32_t> words, grid; // the stream, and each word's place (a tag's VIF codes at offsets 2, 3)
uint32_t place = 0;
auto qwords = [&](uint32_t address, uint32_t count)
{
const bool spr = (address & 0x80000000u) != 0;
for (uint32_t k = 0; k < count * 4; ++k)
{
uint32_t x;
if (spr)
std::memcpy(&x, scratchpad + ((address + 4 * k) & 0x3fff), 4);
else
std::memcpy(&x, ram + ((address + 4 * k) & 0x1ffffff), 4);
words.push_back(x);
grid.push_back(place++);
}
};
uint32_t stack[2] = {}, depth = 0;
uint32_t at = tag;
for (int guard = 0; guard < 65536; ++guard)
{
uint32_t t[4];
if (at & 0x80000000u)
std::memcpy(t, scratchpad + (at & 0x3ff0), 16);
else
std::memcpy(t, ram + (at & 0x1fffff0), 16);
const uint32_t qwc = t[0] & 0xffff, id = (t[0] >> 28) & 7, addr = t[1];
static const bool chainDump = std::getenv("ONI_CHAIN_DUMP") != nullptr; // each tag of every chain (a diagnostic)
if (chainDump)
std::printf("[oni:chain] tag %08x id %u qwc %u addr %08x vif %08x %08x\n", at, id, qwc, addr, t[2], t[3]);
words.push_back(t[2]);
grid.push_back(place + 2);
words.push_back(t[3]);
grid.push_back(place + 3);
place += 4;
bool end = false;
switch (id)
{
case 0: qwords(addr, qwc); end = true; break; // refe
case 1: qwords(at + 16, qwc); at += 16 + 16 * qwc; break; // cnt
case 2: qwords(at + 16, qwc); at = addr; break; // next
case 3: case 4: qwords(addr, qwc); at += 16; break; // ref, refs
case 5: // call
qwords(at + 16, qwc);
if (depth < 2)
stack[depth++] = at + 16 + 16 * qwc;
at = addr;
break;
case 6: // ret
qwords(at + 16, qwc);
if (depth)
at = stack[--depth];
else
end = true;
break;
default: qwords(at + 16, qwc); end = true; break; // end
}
if (trace() >= 3)
std::printf("[oni:dma] tag %08x id %u qwc %u addr %08x vif %08x %08x\n", at, id, qwc, addr, t[2], t[3]);
if (end)
break;
}
// The shadows' chains (shadow.c: SHADOW_VIF1DMA_TAG 0x20e700, Pd 0x28fd00), read natively.
std::shared_ptr<NativeShadow> shadow;
static std::vector<uint32_t> s_setupWords, s_setupGrid; // the last setup chain's stream (a fallback's program)
if (nativeMode() && (tag == 0x20e700 || tag == 0x28fd00))
{
shadow = gatherShadow(words, grid, tag == 0x20e700);
if (tag == 0x20e700)
s_setupWords = words, s_setupGrid = grid;
else if (!shadow && nativeMode() == 1 && !s_setupWords.empty())
{
// Pd not read natively: the setup's stream first, for the program its parts need in VU1.
Job setupJob;
setupJob.words = s_setupWords;
setupJob.grid = s_setupGrid;
submit(std::move(setupJob));
}
}
if (shadow && nativeMode() == 1)
{
Job job;
job.kind = Job::Kind::Shadow;
job.tag = tag;
job.shadow = std::move(shadow);
submit(std::move(job));
return;
}
Job job;
job.words = std::move(words);
job.grid = std::move(grid);
if (shadow) // ONI_NATIVE3D=compare: both paths, compared
{
job.kind = Job::Kind::Shadow;
job.tag = tag;
job.shadow = std::move(shadow);
}
if (model) // ONI_NATIVE3D=compare: both paths, compared
{
job.kind = Job::Kind::Model;
job.tag = tag;
job.model = std::move(model);
}
submit(std::move(job));
}
void frameStats()
{
g_models.clear(); // (the frame boundary: every model the game queued this frame has been drawn)
Gs &gs = g_gs;
if (trace())
std::printf("[oni:vu1] frame: %llu chains, %llu runs, %llu triangles in %llu batches, %llu without texture, %llu unknown programs\n",
(unsigned long long)g_chains, (unsigned long long)vif().runs, (unsigned long long)gs.triangles,
(unsigned long long)gs.batches, (unsigned long long)gs.missingTextures,
(unsigned long long)vif().unknownPrograms);
if (trace() && gs.triangles)
std::printf("[oni:vu1] x %.1f..%.1f y %.1f..%.1f z %.0f..%.0f q %g..%g\n", gs.lo[0], gs.hi[0], gs.lo[1], gs.hi[1],
gs.lo[2], gs.hi[2], gs.lo[3], gs.hi[3]);
for (int k = 0; k < 4; ++k)
{
gs.lo[k] = 1e30f;
gs.hi[k] = -1e30f;
}
if (g_compare.batches)
std::printf("[oni:native3d] frame: %llu batches, %llu vertices; differ: xyz %llu, adc %llu, rgba %llu, stq %llu\n",
(unsigned long long)g_compare.batches, (unsigned long long)g_compare.vertices,
(unsigned long long)g_compare.xyz, (unsigned long long)g_compare.adc,
(unsigned long long)g_compare.rgba, (unsigned long long)g_compare.stq);
if (g_gifCompare.sends)
std::printf("[oni:gifnative] sends %llu, the same %llu; kicks %llu, differ %llu; registers differ after %llu\n",
(unsigned long long)g_gifCompare.sends, (unsigned long long)g_gifCompare.same, (unsigned long long)g_gifCompare.kicks,
(unsigned long long)g_gifCompare.differ, (unsigned long long)g_gifCompare.stateDiffer);
if (g_modelCompare.models)
std::printf("[oni:native3d] shadow fans %llu\n", (unsigned long long)g_shadowFans);
if (g_modelCompare.models)
std::printf("[oni:native3d] models: %llu, the same %llu; kick counts differ %llu; kicks %llu differ: xyz %llu, adc %llu, rgba %llu, stq %llu\n",
(unsigned long long)g_modelCompare.models, (unsigned long long)g_modelCompare.same,
(unsigned long long)g_modelCompare.countDiffer, (unsigned long long)g_modelCompare.kicks,
(unsigned long long)g_modelCompare.xyz, (unsigned long long)g_modelCompare.adc,
(unsigned long long)g_modelCompare.rgba, (unsigned long long)g_modelCompare.stq);
if (g_compare.batches)
{
std::string runs;
for (const auto &[name, count] : g_runs)
runs += " " + name + " " + std::to_string(count);
std::printf("[oni:native3d] runs:%s\n", runs.c_str());
}
if (trace())
std::printf("[oni:vu1] time: %.2f ms in chains, %.2f ms in programs (%.2f ms in kicks), %lld VU cycles\n", g_chainNs / 1e6, g_programNs / 1e6, g_kickNs / 1e6, (long long)g_cycles);
g_chainNs = g_programNs = g_kickNs = g_cycles = 0;
g_chains = 0;
vif().runs = 0;
gs.triangles = gs.batches = gs.missingTextures = 0;
}
} // namespace oni::vu1