diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c9812ea..0715ff1 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -49,6 +49,7 @@ jobs: python3 tools/lower/test_lower.py python3 tools/xbox/test_vp_encoder.py python3 tools/xbox/test_tex_convert.py + python3 tools/xbox/test_fog.py - uses: actions/upload-artifact@v4 with: diff --git a/CLAUDE.md b/CLAUDE.md index d2dc252..1c9c35e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -24,6 +24,7 @@ tools/xbox/docker/build.sh # -> build-xbox/xbe/default.xb XBOX_CFLAGS="-DXHW_PROF=1" tools/xbox/docker/build.sh # extra platform flags (switch table: docs/testing.md) python3 tools/xbox/test_tex_convert.py # host tests (tests/xbox/*.c) python3 tools/xbox/test_vp_encoder.py +python3 tools/xbox/test_fog.py # GX fog math (nv2a_fog.c) vs GX's fog factor python3 tools/lower/test_lower.py ``` diff --git a/docs/decisions.md b/docs/decisions.md index a6d32ba..ddda2a5 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -118,6 +118,20 @@ another homebrew's icon and name cached under that ID (`E:\UDATA\ffff0002\TitleImage.xbx`, `TitleMeta.xbx`). The script writes both files for 4D580001 next to `default.tbn`. +**GX fog per vertex, from GX's own registers** (`nv2a_fog.c`, +`docs/renderer.md`). The NV2A has no per-pixel depth fog: its fog unit +interpolates a factor the vertex program writes. The vertex program +computes GX's fog amount from each vertex's depth with the registers +`GXSetFog` would write (A and C cut to 11 mantissa bits, b_mag and +b_shift), and the fog unit passes it through (LINEAR, parameters 1, 1, 0); +the final combiner mixes that much fog colour into the colour. Rebuilding +the registers, not the textbook formula, matters for Melee: with its +0.1..16384 camera GX's b_mag rounding makes the fog depth ze up to 1.57 +times smaller at the far plane (thinner fog). The cost: GX evaluates fog per pixel, so a polygon spanning a long +depth range gets less fog mid-span than on the GameCube (up to ~23/255 on +long edges), and the EXP curves are linear between vertices. +`GXSetFogRangeAdj` is not applied. + **Vanilla gameplay.** melee-pc's UCF, free camera, frozen stadium, unlock-all, netplay, Slippi and launcher are off or not built. @@ -206,9 +220,10 @@ To sync a newer melee-pc: rendering on the console with BACK screenshots, not only in xemu. - **Performance.** Matches draw 13-30 fps on the console while the simulation keeps 60 ticks (`docs/roadmap.md`). -- **Rendering gaps**: no indirect texturing (water and reflections), no - fog, TEV swap tables only for the alpha broadcast; non-power-of-two - textures are resampled; the texture pool is short on busy stages. +- **Rendering gaps**: no indirect texturing (water and reflections), fog + per vertex (long polygons get less fog mid-span; no range adjustment), + TEV swap tables only for the alpha broadcast; non-power-of-two textures + are resampled; the texture pool is short on busy stages. - **Netplay** is not built; the online/LAN lobby returns to the menu. - **The demand-commit fault handler** relies on the Xbox kernel sending kernel-mode access violations on reserved memory to the thread's SEH diff --git a/docs/renderer.md b/docs/renderer.md index a60f439..ee1941d 100644 --- a/docs/renderer.md +++ b/docs/renderer.md @@ -17,6 +17,7 @@ game -> GX calls -> gx_state.c (XgxState, dirty bits) nv2a.c (state diff, pushbuffer, texture pool, vertex ring) nv2a_vp.c (vertex programs generated from the transform state) nv2a_rc.c (TEV -> register combiners) + nv2a_fog.c (GX fog -> vertex-program fog, final combiner) ``` Per draw, the back end rebuilds only what the front end's dirty groups @@ -160,6 +161,7 @@ Constant rows: | 70-109 `VPC_LIGHT` | 8 lights x 5 rows: position, direction, colour, angle attenuation, distance attenuation | | 110-121 `VPC_TEXGEN` | 4 units x 3 rows (s, t, q), post matrix folded in when there is no normalize | | 122-133 `VPC_POSTMTX` | 4 units x 3 rows, the post-transform matrix after normalize | +| 134-136 `VPC_FOG` | fog numerator, denominator and curve (see Fog) | Inputs: v0 position, v1 matrix index, v2 normal, v3/v4 colours 0/1, GX TEX0..6 -> v9..v15, TEX7 -> v8. The front end writes canonical vertices @@ -224,10 +226,89 @@ Current limits: work only in the movie recipe; - TEV swap tables: only the alpha broadcast (`AAAA`) is supported; - indirect texturing is ignored (some stage effects); -- fog is off; - destination alpha is missing at 720p (R5G6B5 has no alpha); - texture-matrix index attributes (TEXnMTXIDX) are ignored. +## Fog (`nv2a_fog.c`) + +GX applies fog after the last TEV stage, to the colour only: +`rgb = (rgb * (256 - F256) + fog * F256) >> 8` with F256 = F * 256. The +fog amount F comes from the pixel's 24-bit EFB depth Zs and the registers +`GXSetFog` writes: A and C cut to 11 mantissa bits, and for perspective fog +B as a 24-bit magnitude and a shift (libogc `GX_SetFog`, Dolphin's +`PixelShaderGen`): + +| fog | per pixel | +|---|---| +| perspective (`GX_FOG_PERSP_*`) | `ze = A * 2^24 / (b_mag - (Zs >> b_shift))`: eye depth / (end - start) when the fog's near and far are the projection's | +| orthographic (`GX_FOG_ORTHO_*`) | `ze = A * Zs / 2^24` | +| all | `x = clamp(ze - C, 0, 1)`; LIN `F = x`, EXP `1 - 2^(-8x)`, EXP2 `1 - 2^(-8x^2)`, REVEXP `2^(-8(1-x))`, REVEXP2 `2^(-8(1-x)^2)`; `GX_FOG_NONE`: off | + +The NV2A has no per-pixel depth fog. Its fog unit takes oFog.x from the +vertex program per vertex and interpolates the factor (xemu evaluates it +per vertex; `FOG_PARAMS` also goes to the transform engine). So: + +- **Vertex program.** F is computed per vertex from the vertex's own depth + with the same registers. Zs / 2^24 is `(a . P) / (w . P)` for the + view-space position P and the projection's depth and w rows (`VPC_PROJ` + + 2 and + 3), so `ze - C` is a ratio of two linear functions of P: rows + `VPC_FOG` and `VPC_FOG + 1`, built by `fog_setup` when the fog or the + projection changes. EXP and EXP2 clamp x and evaluate `2^(-8u)` with + `expp` (the REV types use 1 - x; the curve's constants are in + `VPC_FOG + 2`). `VpKey.fog` selects the variant (off, linear, exp, + exp2); fog makes a program 4 (LIN) to 10 (EXP2) instructions longer, so + a program already near the NV2A's 136 drops lights sooner. +- **Fog unit.** LINEAR, `FOG_PARAMS` (1, 1, 0): the linear mode computes + `p0 + p1 * oFog - 1` (nxdk's NV10 notes, xemu's `fogFactor -= 1.0`), so + the factor is F, clamped to 0..1 per pixel. nxdk_pgraph_tests' vertex + shader fog tests use the same setup; they also found that the gen mode + doesn't matter with a vertex program. The NV2A's EXP modes aren't used: + they are evaluated per vertex as well, and EXP's zero point measures + ~1.51 on hardware where the formula says 1.5. +- **Final combiner.** CW0 becomes A = FOG.a (the factor), B = FOG.rgb (the + fog colour, `SET_FOG_COLOR` is ABGR), C = PREV, D = 0; alpha (CW1's G) + is untouched. Without fog CW0 is what `nv2a_rc.c` compiled, and + unfogged vertex programs are the same as before (checked on 200000 + random keys). +- **State.** Fog is sent only when `GXSetFog` changed something + (`XGX_DIRTY_FOG`; `GXSetFog` returns early on equal values like the other + setters, as HSD calls it for every camera pass and particle kind) or the + projection changed while fog is on. + +Accuracy (`tools/xbox/test_fog.py`, against libogc's registers and +Dolphin's formula): at every vertex F is within 1/255 of what GX gives +within one of its own depth steps. With Melee's 0.1..16384 game camera GX +resolves fog coarsely: `b_mag - (Zs >> 2)` is 99 steps at depth 5000 and 41 +at the far plane, and b_mag rounds B up (8388638 / 2^23), which makes GX's +ze up to 1.57 times smaller at depth than the textbook formula (thinner +fog). The port reproduces both at the vertices. Between vertices the NV2A +interpolates F linearly in view space, which is exact for LIN fog while +b_mag's rounding is negligible (the test checks edges for most cameras). +With Melee's camera GX's denominator grows by ~57% from near to far, so a +polygon that spans a long depth range gets less fog mid-span than on the +GameCube: up to ~23/255 on an edge from depth 2000 to 14000 through a +narrow fog range. The EXP curves are also linear between vertices. + +`GXSetFogRangeAdj` (a horizontal correction toward radial distance, which +HSD sets when a fog has a FogAdj descriptor) is not applied. + +Melee sets fog in these places (`HSD_FogSet`), all compared best against +Dolphin: + +- stages: `Ground_801C1E94` loads the stage's fog descriptor (scaled by the + stage's `param->y`; its colour is also the clear colour) and + `Ground_801C1E2C` applies it for the stage's camera passes while + `stage_info.unk8C.b2` holds (set at stage load; Final Destination's + `grlast.c` clears it). The camera turns it off for its later passes + (`camera.c`); +- particles whose kind has `DispFog` (`psdisp.c`); +- the title screen (`ScTitle_fog`), the Classic and All-Star intros + (`gm_1832.c`, `gm_186E.c`), Tournament mode (`gmtou_*.c`), the 1P ending + (`gmregenddisp.c`), the staff roll, Adventure cutscenes (`vi0102`, + `vi0401`, `vi0501`, `vi0502`, `vi0801`, `vi1201v1`, `vi1201v2`) and the + trophy display (`ScMenDisplay_fog`, `tydisplay.c`; `toy.c`'s own white + fog is a debug-ROM feature). + ## Textures (`gx_tex.c`, `nv2a.c`) - GX textures are converted once and cached, keyed by data pointer, size, diff --git a/docs/roadmap.md b/docs/roadmap.md index 6a14101..45e1936 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -27,7 +27,9 @@ - [x] memory fit measured on hardware (boot.log `[MEM]`); disc-backed ARAM pages - [x] 4-CPU VS matches stable on hardware (Pokémon Stadium with transformations, Fountain of Dreams, Green Greens), audio, saves, 100% save file loads -- [ ] fog, indirect texturing, TEV swap tables beyond alpha broadcast +- [x] fog: every GX fog type, per vertex from GX's registers (`nv2a_fog.c`); not yet + compared with Dolphin on the console; no range adjustment +- [ ] indirect texturing, TEV swap tables beyond alpha broadcast - [ ] VS mode with 4 players on hardware at 60 fps - [x] movie frames decoded (`thp.c`) - [x] dashboard icon (`$$XTIMAGE` + `default.tbn`, own title ID 4D580001) @@ -63,7 +65,9 @@ Fixed on the console this round (details in `renderer.md`, 1. **Texture accuracy.** Fountain of Dreams' water and other reflections need indirect texturing (the NV2A's texture-shader bump modes may do - it); fog and TEV swap tables beyond the alpha broadcast. Item crates + it); TEV swap tables beyond the alpha broadcast. Fog is new: compare + stage backgrounds, the title screen and the Classic/All-Star intros + with Dolphin (`docs/renderer.md` lists where Melee uses it). Item crates still show the background through their dark gaps. Short black flashes remain on Stadium's floor. For each, take a console screenshot (BACK) and compare with xemu at the same scene (`docs/testing.md`). diff --git a/docs/testing.md b/docs/testing.md index 20f97f2..be67818 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -6,9 +6,10 @@ tools/lower/test_lower.py # disc_lower vs GCC scalar_storage_order (needs GCC 12+) tools/xbox/test_vp_encoder.py # vertex-program encoder vs nv2a-vsh (pip install nv2a-vsh) tools/xbox/test_tex_convert.py # native texture formats vs the GX decoder +tools/xbox/test_fog.py # GX fog on the NV2A vs GX's fog factor (libogc registers, Dolphin's formula) ``` -CI (`.github/workflows/build.yml`) runs all three after building +CI (`.github/workflows/build.yml`) runs all four after building `default.xbe`, and uploads the XBE with its link map. ## Running it @@ -246,7 +247,7 @@ report. | `-DXGX_EFB_GPU_COPY=0` | EFB copies read back on the CPU instead of drawn by the GPU | | `-DXGX_DEPTH_CULL=1` | cull pixels whose depth falls outside the clip range instead of clamping it (the pre-v15 behaviour) | | `-DXGX_DEBUG_EFBLOG` | log the first 200 EFB copies (source rect, size, format) as `[EFB]` lines | -| `-DXGX_DEBUG_TRACE` | log every draw (TEV stages, textures, texgens, blend) of the frame an autopad `SHOT` dumps, as `[DRAW]` lines | +| `-DXGX_DEBUG_TRACE` | log every draw (TEV stages, textures, texgens, blend, fog) of the frame an autopad `SHOT` dumps, as `[DRAW]` lines | | `-DXGX_DEBUG_NOMIP` | bind only the base level of every texture | | `-DXHW_FBDUMP_EVERY=` | screenshot every n presented frames | | `-DXGX_STATS_EVERY=` | `[NV2A]` / `[TEX]` stats period, in frames (default 600) | diff --git a/tests/xbox/test_fog.c b/tests/xbox/test_fog.c new file mode 100644 index 0000000..0eda236 --- /dev/null +++ b/tests/xbox/test_fog.c @@ -0,0 +1,336 @@ +/* test_fog.c - host check of GX fog on the NV2A (nv2a_fog.c): the fog amount + * the port's vertex program and fog unit produce, against a reference GX + * (libogc GX_SetFog's registers, Dolphin's per-pixel formula on the 24-bit + * EFB depth), for every fog type, perspective and orthographic, over a range + * of depths; LIN fog also along triangle edges (perspective-correct + * interpolation); and the final combiner's blend against GX's. Built and run + * by tools/xbox/test_fog.py. + * + * GX itself resolves perspective fog coarsely at depth: ze divides by + * b_mag - (Zs >> b_shift), a few hundred steps at Melee's stage depths with + * its 0.1..16384 camera. A vertex passes when the port's amount is within + * 1/255 of what GX gives over one step of that depth (Zs +- 2^b_shift). */ +#include +#include +#include +#include + +#define TOL (1.0 / 255.0) +/* Along an edge the port interpolates the vertex values linearly in view + * space (perspective-correct). GX's ze is linear there only up to b_mag's + * rounding of B (8388638 / 2^23): that bends ze by about 3.6e-6 * far / near + * over the camera's range, which is small for most cameras but 60% for + * Melee's 0.1..16384. Edges are checked where the bend is under 1%; for the + * others the worst difference is reported (docs/renderer.md). */ +#define EDGE_BEND_MAX 0.01 + +/* ---- reference GX ---- */ +typedef struct { + uint32_t a, b_mag, b_shift, c, proj, fsel; /* a, c: sign, exponent, 11 mantissa bits (BP 0xEE, 0xF1) */ +} GxFog; + +/* libogc GX_SetFog */ +static void gx_set_fog(uint32_t type, float startz, float endz, float nearz, float farz, GxFog* r) { + float A, B, B_mant, C, A_f; + uint32_t b_expn, b_m, proj = (type >> 3) & 1; + union { float f; uint32_t i; } v; + if (proj) { + if (farz == nearz || endz == startz) { + A_f = 0.0f; + C = 0.0f; + } else { + A = 1.0f / (endz - startz); + A_f = (farz - nearz) * A; + C = (startz - nearz) * A; + } + b_expn = 0; + b_m = 0; + } else { + if (farz == nearz || endz == startz) { + A = 0.0f; + B = 0.5f; + C = 0.0f; + } else { + A = (farz * nearz) / ((farz - nearz) * (endz - startz)); + B = farz / (farz - nearz); + C = startz / (endz - startz); + } + B_mant = B; + b_expn = 1; + while (B_mant > 1.0f) { + B_mant /= 2.0f; + b_expn++; + } + while (B_mant > 0.0f && B_mant < 0.5f) { + B_mant *= 2.0f; + b_expn--; + } + A_f = A / (1 << b_expn); + b_m = (uint32_t)(B_mant * 8388638.0f); + } + v.f = A_f; + r->a = v.i >> 12; + v.f = C; + r->c = v.i >> 12; + r->b_mag = b_m & 0xFFFFFF; + r->b_shift = b_expn & 0x1F; + r->proj = proj; + r->fsel = type & 7; +} + +static float gx_reg_float(uint32_t r20) { + union { float f; uint32_t i; } v; + v.i = r20 << 12; + return v.f; +} + +/* Dolphin PixelShaderGen WriteFog: the fog amount (0..1) at a pixel of EFB depth zs */ +static double gx_fog_amount(const GxFog* r, uint32_t zs) { + double ze, fog; + if (!r->fsel) return 0.0; + if (!r->proj) ze = gx_reg_float(r->a) * 16777216.0 / (double)((int32_t)r->b_mag - (int32_t)(zs >> r->b_shift)); + else ze = gx_reg_float(r->a) * (double)zs / 16777216.0; + fog = ze - gx_reg_float(r->c); + fog = fog < 0.0 ? 0.0 : fog > 1.0 ? 1.0 : fog; + switch (r->fsel) { + case 4: fog = 1.0 - exp2(-8.0 * fog); break; + case 5: fog = 1.0 - exp2(-8.0 * fog * fog); break; + case 6: fog = exp2(-8.0 * (1.0 - fog)); break; + case 7: fog = exp2(-8.0 * (1.0 - fog) * (1.0 - fog)); break; + } + return fog; +} + +/* GX's EFB depth of a view-space point: clip z/w (-1 near .. 0 far) through the viewport */ +static uint32_t gx_depth(const float p[4][4], float vn, float vf, const double P[4]) { + double z = 0, w = 0, d; + int c; + for (c = 0; c < 4; c++) { + z += p[2][c] * P[c]; + w += p[3][c] * P[c]; + } + d = (z / w * (vf - vn) + vf) * 16777215.0; + d = floor(d + 0.5); + return d < 0 ? 0u : d > 16777215.0 ? 16777215u : (uint32_t)d; +} + +/* ---- the port ---- */ +typedef struct { + float zrow[4], wrow[4], zmax; + FogSetup fs; +} Port; + +/* nv2a.c build_proj's depth and w rows, then fog_setup */ +static void port_setup(Port* pt, const float p[4][4], float vn, float vf, float zmax, uint32_t type, float s, float e, + float n, float f) { + int c; + pt->zmax = zmax; + for (c = 0; c < 4; c++) { + pt->zrow[c] = zmax * ((vf - vn) * p[2][c] + vf * p[3][c]); + pt->wrow[c] = p[3][c]; + } + fog_setup(type, s, e, n, f, pt->zrow, pt->wrow, zmax, &pt->fs); +} + +/* the vertex program's oFog.x (nv2a_vp.c), in float as the NV2A computes it */ +static float port_vertex(const Port* pt, const double P[4]) { + const FogSetup* fs = &pt->fs; + float num = 0, den = 0, y; + int c; + for (c = 0; c < 4; c++) { + num += fs->num[c] * (float)P[c]; + den += fs->den[c] * (float)P[c]; + } + y = num * (1.0f / den); + if (fs->kind == VPF_LIN) return y; + y = y < 0.0f ? 0.0f : y > 1.0f ? 1.0f : y; + if (fs->kind == VPF_EXP2) y = y * y; + return fs->curve[2] * exp2f(y * fs->curve[0]) + fs->curve[1]; +} + +/* the fog unit: LINEAR, FOG_PARAMS (1, 1, 0): p0 + p1 * oFog - 1, then clamped per pixel */ +static double port_factor(double ofog) { + double f = 1.0 + 1.0 * ofog - 1.0; + return f < 0.0 ? 0.0 : f > 1.0 ? 1.0 : f; +} + +/* ---- projections as HSD sets them (MTXPerspective / MTXOrtho, GXSetProjection) ---- */ +static void persp(float p[4][4], float fovy, float aspect, float n, float f) { + float c = 1.0f / tanf(fovy * 0.5f * 3.14159265f / 180.0f); + memset(p, 0, 64); + p[0][0] = c / aspect; + p[1][1] = c; + p[2][2] = -n / (f - n); + p[2][3] = -(f * n) / (f - n); + p[3][2] = -1.0f; +} + +static void ortho(float p[4][4], float t, float b, float l, float r, float n, float f) { + memset(p, 0, 64); + p[0][0] = 2.0f / (r - l); + p[0][3] = -(r + l) / (r - l); + p[1][1] = 2.0f / (t - b); + p[1][3] = -(t + b) / (t - b); + p[2][2] = -1.0f / (f - n); + p[2][3] = -f / (f - n); + p[3][3] = 1.0f; +} + +static int s_fail, s_checks; +static double s_worst, s_worst_bent, *s_worst_to = &s_worst; +static char s_worst_bent_what[160]; + +/* ref_lo..ref_hi: what GX gives (over one depth step for a vertex) */ +static double check_range(const char* what, double ref_lo, double ref_hi, double got, double tol) { + double e = got < ref_lo ? ref_lo - got : got > ref_hi ? got - ref_hi : 0.0; + s_checks++; + if (e > *s_worst_to) *s_worst_to = e; + if (e > tol) { + if (s_fail < 20) printf("FAIL %s: GX %.5f..%.5f port %.5f (off %.2f/255)\n", what, ref_lo, ref_hi, got, e * 255.0); + s_fail++; + } + return e; +} + +static void check(const char* what, double ref, double got, double tol) { check_range(what, ref, ref, got, tol); } + +/* GX's fog amount over the depths within one of its steps of zs (past the + * far plane too: the formula holds there, and it is the step's size) */ +static void gx_fog_range(const GxFog* r, uint32_t zs, double* lo, double* hi) { + int32_t step = r->proj ? 1 : 1 << r->b_shift, z; + *lo = 1.0; + *hi = 0.0; + for (z = (int32_t)zs - step; z <= (int32_t)zs + step; z++) { + double v; + if (z < 0) continue; + v = gx_fog_amount(r, (uint32_t)z); + if (v < *lo) *lo = v; + if (v > *hi) *hi = v; + } +} + +static const uint32_t k_types[] = { 0, 2, 4, 5, 6, 7 }; +static const char* const k_names[] = { "NONE", "?", "LIN", "?", "EXP", "EXP2", "REVEXP", "REVEXP2" }; + +/* one camera and one fog: every type, depths from near to far along a ray + * off the view axis, vertex by vertex; LIN also across triangles */ +static void run_case(int ortho_proj, float n, float f, float vn, float vf, float s, float e, float zmax) { + float p[4][4]; + unsigned ti; + int i; + if (ortho_proj) ortho(p, 240, -240, -320, 320, n, f); + else persp(p, 30.0f, 4.0f / 3.0f, n, f); + for (ti = 0; ti < 2 * sizeof k_types / sizeof k_types[0]; ti++) { + uint32_t type = k_types[ti % 6] | (ti >= 6 ? 8u : 0u); /* then the GX_FOG_ORTHO_* types */ + int matched = vn == 0.0f && vf == 1.0f && ortho_proj == (int)(type >> 3); + GxFog r; + Port pt; + double bend; + char what[160]; + gx_set_fog(type, s, e, n, f, &r); + port_setup(&pt, p, vn, vf, zmax, type, s, e, n, f); + if (pt.fs.kind != fog_kind(type) || (type & 7) == 0) { + check("fog off", 0.0, pt.fs.kind, 0.0); + continue; + } + for (i = 0; i <= 400; i++) { + /* view space looks down -z */ + double d = n + (f - n) * i / 400.0, P[4] = { 0.3 * d, -0.2 * d, -d, 1.0 }, lo, hi; + gx_fog_range(&r, gx_depth(p, vn, vf, P), &lo, &hi); + snprintf(what, sizeof what, "%s %s cam %g..%g vp %g..%g fog %g..%g depth %g", ortho_proj ? "ortho" : "persp", + k_names[type & 7], n, f, vn, vf, s, e, d); + check_range(what, lo, hi, port_factor(port_vertex(&pt, P)), TOL); + } + if (pt.fs.kind != VPF_LIN || !matched) continue; + bend = ortho_proj ? 0.0 : (8388638.0 / 8388608.0 - 1.0) * f / n; + /* a triangle edge from near the camera to the far plane: the vertex + * values interpolated perspective-correctly, clamped per pixel */ + for (i = 0; i < 16; i++) { + double d0 = n + (f - n) * (i % 4) / 8.0, d1 = n + (f - n) * (4 + i / 4) / 8.0; + double P0[4] = { -0.4 * d0, 0.1 * d0, -d0, 1 }, P1[4] = { 0.35 * d1, -0.3 * d1, -d1, 1 }; + double w0 = ortho_proj ? 1.0 : d0, w1 = ortho_proj ? 1.0 : d1; + double f0 = port_vertex(&pt, P0), f1 = port_vertex(&pt, P1); + int k; + for (k = 0; k <= 64; k++) { + double t = k / 64.0, q0 = (1 - t) / w0, q1 = t / w1, P[4], lo, hi, err, got; + int c; + for (c = 0; c < 4; c++) P[c] = (q0 * P0[c] + q1 * P1[c]) / (q0 + q1); + snprintf(what, sizeof what, "%s %s cam %g..%g fog %g..%g edge %g..%g at %g", ortho_proj ? "ortho" : "persp", + k_names[type & 7], n, f, s, e, d0, d1, t); + gx_fog_range(&r, gx_depth(p, vn, vf, P), &lo, &hi); + got = port_factor((q0 * f0 + q1 * f1) / (q0 + q1)); + if (bend < EDGE_BEND_MAX) { + check_range(what, lo, hi, got, TOL); + continue; + } + err = got < lo ? lo - got : got > hi ? got - hi : 0.0; + if (err > s_worst_bent) { + s_worst_bent = err; + snprintf(s_worst_bent_what, sizeof s_worst_bent_what, "%s", what); + } + } + } + } +} + +/* NV2A final combiner, unsigned identity/invert inputs: rgb = A*B + (1-A)*C + D */ +static double fc_input(uint32_t field, const double reg[16][4], int ch) { + double v = reg[field & 15][(field >> 4) & 1 ? 3 : ch]; + return (field >> 5) & 7 ? 1.0 - v : v; +} + +static double s_worst_fc; + +static void check_combiner(void) { + /* R0 = PREV (nv2a_rc.c's final combiner reads it through C) */ + uint32_t cw0 = fog_final_cw0(12u << 8); + int i; + s_worst_to = &s_worst_fc; + srand(1); + for (i = 0; i < 20000; i++) { + double reg[16][4] = { { 0 } }; + uint8_t prev[3], fog[3]; + double F = (rand() % 1001) / 1000.0; + int ch, ifog = (int)floor(F * 256.0 + 0.5); + for (ch = 0; ch < 3; ch++) { + prev[ch] = (uint8_t)(rand() & 255); + fog[ch] = (uint8_t)(rand() & 255); + reg[12][ch] = prev[ch] / 255.0; + reg[3][ch] = fog[ch] / 255.0; + } + reg[12][3] = 0.5; + reg[3][3] = F; /* FOG.a: the fog factor */ + for (ch = 0; ch < 3; ch++) { + double a = fc_input(cw0 >> 24, reg, ch), b = fc_input(cw0 >> 16, reg, ch), c = fc_input(cw0 >> 8, reg, ch), + d = fc_input(cw0, reg, ch); + double gx = (double)((prev[ch] * (256 - ifog) + fog[ch] * ifog) >> 8); + check("final combiner", gx / 255.0, a * b + (1.0 - a) * c + d, 1.5 / 255.0); + } + } +} + +int main(void) { + /* Melee's game camera is 0.1..16384 (cm/camera.c) */ + static const float cams[][2] = { { 0.1f, 16384 }, { 1, 1000 }, { 10, 30000 }, { 0.1f, 100 }, { 100, 5000 }, { 1, 16384 } }; + static const float fogs[][2] = { { 0, 1 }, { 0.3f, 0.7f }, { 0.05f, 0.5f }, { 0.6f, 0.95f }, { 0.8f, 0.2f } }; + unsigned c, k; + for (c = 0; c < sizeof cams / sizeof cams[0]; c++) + for (k = 0; k < sizeof fogs / sizeof fogs[0]; k++) { + float n = cams[c][0], f = cams[c][1]; + float s = n + (f - n) * fogs[k][0], e = n + (f - n) * fogs[k][1]; + run_case(0, n, f, 0.0f, 1.0f, s, e, 16777215.0f); + run_case(0, n, f, 0.0f, 1.0f, s, e, 65535.0f); /* 720p: Z16 */ + run_case(0, n, f, 0.1f, 0.9f, s, e, 16777215.0f); /* another depth range: per vertex only */ + run_case(1, n, f, 0.0f, 1.0f, s, e, 16777215.0f); + } + /* GXSetFog's odd cases: start == end, near == far */ + run_case(0, 1, 1000, 0.0f, 1.0f, 500, 500, 16777215.0f); + run_case(1, 1, 1000, 0.0f, 1.0f, 500, 500, 16777215.0f); + check_combiner(); + printf("%d checks, %d failed; fog amount: worst %.2f/255 beyond GX's own depth step; final combiner: worst " + "%.2f/255 off GX's 8-bit blend\n", + s_checks, s_fail, s_worst * 255.0, s_worst_fc * 255.0); + printf("not checked: LIN edges of cameras whose b_mag bends ze by 1%% or more, worst %.1f/255 (%s)\n", + s_worst_bent * 255.0, s_worst_bent_what); + return s_fail != 0; +} diff --git a/tools/xbox/test_fog.py b/tools/xbox/test_fog.py new file mode 100755 index 0000000..c53f6d7 --- /dev/null +++ b/tools/xbox/test_fog.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +"""Build and run tests/xbox/test_fog.c on the host: GX fog as the back end +maps it onto the NV2A (xbox/src/hw/nv2a_fog.c) against a reference GX fog +factor, for every fog type over a range of depths.""" +import os +import subprocess +import sys +import tempfile + +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + + +def main(): + cc = os.environ.get("CC", "cc") + with tempfile.TemporaryDirectory() as tmp: + exe = os.path.join(tmp, "test_fog") + # the test #includes nv2a_fog.c, as test_tex_convert.c does gx_tex.c + wrapper = os.path.join(tmp, "t.c") + with open(wrapper, "w") as f: + f.write('#include "%s"\n#include "%s"\n' % ( + os.path.join(ROOT, "xbox/src/hw/nv2a_fog.c"), + os.path.join(ROOT, "tests/xbox/test_fog.c"))) + cmd = [cc, "-O1", "-Wall", "-o", exe, wrapper, + "-I" + os.path.join(ROOT, "xbox/src/hw"), "-lm"] + r = subprocess.run(cmd) + if r.returncode: + return r.returncode + return subprocess.run([exe]).returncode + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/xbox/test_vp_encoder.py b/tools/xbox/test_vp_encoder.py index 58fe841..69fe089 100644 --- a/tools/xbox/test_vp_encoder.py +++ b/tools/xbox/test_vp_encoder.py @@ -31,6 +31,8 @@ dp3 oT1.x, v10, c111 mov oT2.zw, c4.xxxy rcp oFog.x, r11.y +expp r3.z, r3.y +mad oFog.x, r3.z, c136.z, c136.y """ HARNESS = r""" diff --git a/xbox/src/hw/nv2a.c b/xbox/src/hw/nv2a.c index 8729c56..0843bf4 100644 --- a/xbox/src/hw/nv2a.c +++ b/xbox/src/hw/nv2a.c @@ -29,6 +29,7 @@ #include #include +#include "nv2a_fog.h" #include "nv2a_rc.h" #include "nv2a_vp.h" #include "xgx.h" @@ -889,6 +890,19 @@ static void set_row(int r, float x, float y, float z, float w) { s_vc[r][3] = w; } +/* GX fog (nv2a_fog.h): what the fog rows, the vertex program's key and the + * final combiner were built from. The rows depend on the projection too. */ +static FogSetup s_fog; + +static void build_fog(const XgxState* st) { + fog_setup(st->fog_type, st->fog_start, st->fog_end, st->fog_near, st->fog_far, s_vc[VPC_PROJ + 2], + s_vc[VPC_PROJ + 3], s_zmax, &s_fog); + if (!s_fog.kind) return; + set_row(VPC_FOG, s_fog.num[0], s_fog.num[1], s_fog.num[2], s_fog.num[3]); + set_row(VPC_FOG + 1, s_fog.den[0], s_fog.den[1], s_fog.den[2], s_fog.den[3]); + set_row(VPC_FOG + 2, s_fog.curve[0], s_fog.curve[1], s_fog.curve[2], s_fog.curve[3]); +} + static void build_proj(const XgxState* st) { const float(*p)[4] = st->proj; float vx = (float)map_x(st->viewport[0]) , vy = (float)map_y(st->viewport[1]); @@ -904,6 +918,7 @@ static void build_proj(const XgxState* st) { s_vc[VPC_PROJ + 2][c] = s_zmax * ((vf - vn) * p[2][c] + vf * p[3][c]); s_vc[VPC_PROJ + 3][c] = p[3][c]; } + if (st->fog_type & 7) build_fog(st); } /* only the matrices the front end loaded since the last draw (posmtx_mask) */ @@ -1048,6 +1063,10 @@ static const RcProg* s_rc_sent; /* the program on the GPU, valid while s_r static uint32_t s_rc_sent_gen; static int s_rc_valid; static uint32_t s_rc_consts[RC_MAX_STAGES][2], s_rc_fconsts[2]; +static uint32_t s_rc_cw0; /* the final combiner's CW0 as sent, fog included */ + +/* the program's final combiner, blending toward the fog colour while fog is on */ +static uint32_t final_cw0(const RcProg* rp) { return s_fog.kind ? fog_final_cw0(rp->cw0) : rp->cw0; } /* FNV-1a over 32-bit words (the tail bytes one at a time) */ static uint32_t fnv(const void* p, size_t n) { @@ -1141,7 +1160,8 @@ static void emit_combiners(const XgxState* st, const RcProg* rp) { put1(NV097_SET_COMBINER_ALPHA_ICW + i * 4, rp->aicw[i]); put1(NV097_SET_COMBINER_ALPHA_OCW + i * 4, rp->aocw[i]); } - put1(NV097_SET_COMBINER_SPECULAR_FOG_CW0, rp->cw0); + s_rc_cw0 = final_cw0(rp); + put1(NV097_SET_COMBINER_SPECULAR_FOG_CW0, s_rc_cw0); put1(NV097_SET_COMBINER_SPECULAR_FOG_CW1, rp->cw1); s_rc_sent = rp; s_rc_sent_gen = s_rc_gen; @@ -1228,7 +1248,8 @@ static void emit_textures(const XgxState* st, const int unit_map[4], int nunits) /* ====================================================================== * Fixed-function pixel state * ====================================================================== */ -static int s_fixed[20]; +static int s_fixed[24]; +static int s_fog_force = 1; /* emit_fog regardless of XGX_DIRTY_FOG (GPU state reset) */ /* vertex attribute arrays and inline values last sent (emit_vertex_arrays) */ static uint32_t s_attr_shadow[16], s_attr_off_shadow[16]; static uint32_t s_default_mtx = 0xFFFFFFFFu; @@ -1236,6 +1257,7 @@ static int s_inline_col[2]; /* the inline colour holds our opaque white */ static void state_reset_shadows(void) { s_draw_force = XGX_DIRTY_ALL; + s_fog_force = 1; memset(s_fixed, 0xFF, sizeof s_fixed); memset(s_tex_shadow, 0xFF, sizeof s_tex_shadow); s_tex_prog = 0xFFFFFFFFu; @@ -1265,6 +1287,8 @@ static uint32_t blend_factor(uint32_t gx, int is_src) { } } +static void emit_fog(const XgxState* st); + static void emit_fixed(const XgxState* st) { int x0, y0, x1, y1; #ifdef XGX_DEBUG_NOZ @@ -1341,6 +1365,8 @@ static void emit_fixed(const XgxState* st) { SETF(17, NV097_SET_ALPHA_REF, ref); } } + /* the front end clears dirty after each draw: only a changed GXSetFog gets here */ + if ((st->dirty & XGX_DIRTY_FOG) || s_fog_force) emit_fog(st); } /* ====================================================================== @@ -1475,6 +1501,10 @@ static void trace_draw(uint32_t prim, uint32_t count, const XgxState* st, int ap for (i = 0; i < st->ntexgen && i < XGX_MAX_TEXGEN; i++) xhw_logf("[DRAW] tg%u type %u src %u mtx %u norm %u pt %u", i, st->texgen[i].type, st->texgen[i].src, st->texgen[i].mtx, st->texgen[i].normalize, st->texgen[i].pt_mtx); + if (st->fog_type & 7) + xhw_logf("[DRAW] fog type %u start %d end %d near %d far %d colour %02x%02x%02x", st->fog_type, + (int)st->fog_start, (int)st->fog_end, (int)st->fog_near, (int)st->fog_far, st->fog_color[0], + st->fog_color[1], st->fog_color[2]); } #endif @@ -1557,6 +1587,7 @@ static void derive_vk(const XgxState* st, const XgxLayout* layout) { if (c->amb_src && layout->off_col[i / 2] < 0) vk->chan[i].amb_vtx = 1; if (c->mat_src && layout->off_col[i / 2] < 0) vk->chan[i].mat_vtx = 1; } + vk->fog = fog_kind(st->fog_type); vk->ntex = (uint8_t)s_d_nunits; for (i = 0; i < s_d_nunits; i++) { const XgxTexGen* tg = &st->texgen[s_d_unit_tc[i] < XGX_MAX_TEXGEN ? s_d_unit_tc[i] : 0]; @@ -1567,6 +1598,39 @@ static void derive_vk(const XgxState* st, const XgxLayout* layout) { } } +/* GX fog changed (or the GPU state was reset): the fog rows, the vertex + * program's fog variant, the fog unit and the final combiner. The NV2A's fog + * unit runs LINEAR with FOG_PARAMS (1, 1, 0) (the linear mode subtracts 1: + * factor = p0 + p1 * oFog.x - 1), so its factor is the vertex program's F; + * the gen mode doesn't matter with a vertex program (nxdk_pgraph_tests). */ +static void emit_fog(const XgxState* st) { + s_fog_force = 0; + build_fog(st); + emit_vc(); /* the fog rows: this draw's emit_vc has run */ + SETF(18, NV097_SET_FOG_ENABLE, s_fog.kind != VPF_OFF); + if (s_fog.kind) { + SETF(19, NV097_SET_FOG_COLOR, fog_color_abgr(st->fog_color)); + if (s_fixed[20] != 1) { + put1(NV097_SET_FOG_MODE, NV097_SET_FOG_MODE_V_LINEAR); + put1(NV097_SET_FOG_GEN_MODE, NV097_SET_FOG_GEN_MODE_V_SPEC_ALPHA); + putf(NV097_SET_FOG_PARAMS, 1.0f); + putf(NV097_SET_FOG_PARAMS + 4, 1.0f); + putf(NV097_SET_FOG_PARAMS + 8, 0.0f); + s_fixed[20] = 1; + } + } + if (s_d_vk.fog != s_fog.kind) { /* derive_vk runs only for its own groups */ + s_d_vk.fog = s_fog.kind; + vp_select(&s_d_vk); + } + /* the combiner program on the GPU: a new one (DIRTY_UNITS) is sent after + * this with final_cw0 anyway */ + if (s_rc_valid && final_cw0(s_rc_sent) != s_rc_cw0) { + s_rc_cw0 = final_cw0(s_rc_sent); + put1(NV097_SET_COMBINER_SPECULAR_FOG_CW0, s_rc_cw0); + } +} + void xgx_draw(uint32_t prim, uint32_t count, const XgxLayout* layout, XgxState* st) { int i, pf; uint32_t first, d, lay; diff --git a/xbox/src/hw/nv2a_fog.c b/xbox/src/hw/nv2a_fog.c new file mode 100644 index 0000000..dc83053 --- /dev/null +++ b/xbox/src/hw/nv2a_fog.c @@ -0,0 +1,123 @@ +/* nv2a_fog.c - GX fog (GXSetFog) on the NV2A. + * + * GXSetFog turns (type, start, end, near, far) into BP registers: A and C as + * floats cut to 11 mantissa bits, and for perspective fog B as a 24-bit + * magnitude b_mag and a shift b_shift (libogc GX_SetFog). Per pixel the + * GameCube then takes the 24-bit depth Zs it writes to the EFB and computes + * (Dolphin's PixelShaderGen WriteFog) + * perspective: ze = A * 2^24 / (b_mag - (Zs >> b_shift)) eye depth / (end - start) + * orthographic: ze = A * Zs / 2^24 + * x = clamp(ze - C, 0, 1) + * F = x (LIN), 1 - 2^(-8x) (EXP), 1 - 2^(-8x^2) (EXP2), + * 2^(-8(1-x)) (REVEXP), 2^(-8(1-x)^2) (REVEXP2) + * and after the last TEV stage mixes F of the fog colour into the colour, + * not alpha: rgb = (rgb * (256 - F256) + fog * F256) >> 8, F256 = F * 256. + * + * The depth is a projective function of the view-space position P, + * Zs / 2^24 = (a . P) / (w . P) with a and w the projection's depth and w + * rows, so ze - C (1 - (ze - C) for the REV types) is a ratio of two linear + * functions of P, which the vertex program evaluates exactly per vertex. + * When the fog's near and far are the projection's (HSD passes the camera's) + * the denominator is a constant and y is linear in P: the rasterizer's + * perspective-correct interpolation then keeps LIN fog exact across a + * triangle. The exponential curves are exact at the vertices and + * interpolated between them, as the NV2A's own EXP modes are (it evaluates + * fog per vertex). GXSetFogRangeAdj's horizontal correction is not applied. */ +#include + +#include "nv2a_fog.h" + +enum { FC_FOG = 3 }; /* final combiner input: FOG (rgb: fog colour, alpha: fog factor) */ + +/* a float as a GX fog register keeps it: sign, exponent, 11 mantissa bits */ +static float gx_float11(float f) { + union { float f; uint32_t u; } c; + c.f = f; + c.u &= 0xFFFFF000u; + return c.f; +} + +static double pow2(int e) { + double r = 1.0; + for (; e > 0; e--) r *= 2.0; + for (; e < 0; e++) r *= 0.5; + return r; +} + +void fog_setup(uint32_t type, float startz, float endz, float nearz, float farz, const float zrow[4], + const float wrow[4], float zmax, FogSetup* out) { + int rev = (type & 7) >= 6, i; + double s = rev ? -1.0 : 1.0, a[4], k; + memset(out, 0, sizeof *out); + out->kind = fog_kind(type); + if (out->kind == VPF_OFF) return; + out->curve[0] = -8.0f; /* F = a + b * 2^(-8 y^n) */ + out->curve[1] = rev ? 0.0f : 1.0f; + out->curve[2] = rev ? 1.0f : -1.0f; + /* Zs / 2^24 = (a . P) / (wrow . P): the depth row in depth-buffer units, + * then GX's 24-bit depth over 2^24 */ + for (i = 0; i < 4; i++) a[i] = zrow[i] * (16777215.0 / 16777216.0) / zmax; + if (type & 8) { + /* orthographic: y = s (A Zs/2^24 - C) + rev */ + float A = 0.0f, C = 0.0f; + if (farz != nearz && endz != startz) { + float r = 1.0f / (endz - startz); + A = (farz - nearz) * r; + C = (startz - nearz) * r; + } + A = gx_float11(A); + C = gx_float11(C); + k = (rev ? 1.0 : 0.0) - s * C; + for (i = 0; i < 4; i++) { + out->num[i] = (float)(s * A * a[i] + k * wrow[i]); + out->den[i] = wrow[i]; + } + } else { + /* perspective: y = s (A 2^24 / (b_mag - Zs / 2^b_shift) - C) + rev + * = s Ah / (D - Zs/2^24) + k, Ah = A 2^b_shift, D = b_mag 2^(b_shift-24) */ + float A, B, C, B_mant; + int b_shift = 1; + uint32_t b_mag = 0; + double Ah, D; + if (farz == nearz || endz == startz) { + A = 0.0f; + B = 0.5f; + C = 0.0f; + } else { + A = (farz * nearz) / ((farz - nearz) * (endz - startz)); + B = farz / (farz - nearz); + C = startz / (endz - startz); + } + B_mant = B; + while (B_mant > 1.0f) { + B_mant /= 2.0f; + b_shift++; + } + while (B_mant > 0.0f && B_mant < 0.5f) { + B_mant *= 2.0f; + b_shift--; + } + if (B_mant > 0.0f) b_mag = (uint32_t)(B_mant * 8388638.0f) & 0xFFFFFFu; + A = gx_float11((float)(A / pow2(b_shift))); + C = gx_float11(C); + Ah = A * pow2(b_shift); + D = b_mag * pow2(b_shift - 24); + k = (rev ? 1.0 : 0.0) - s * C; + if (Ah == 0.0) { + /* ze = 0 everywhere (GXSetFog's odd case: near == far or start == end) */ + out->num[3] = (float)k; + out->den[3] = 1.0f; + return; + } + /* y = ((s Ah + k D) (w . P) - k (a . P)) / (D (w . P) - (a . P)) */ + for (i = 0; i < 4; i++) { + out->num[i] = (float)((s * Ah + k * D) * wrow[i] - k * a[i]); + out->den[i] = (float)(D * wrow[i] - a[i]); + } + } +} + +uint32_t fog_final_cw0(uint32_t cw0) { + /* rgb = A*B + (1-A)*C + D: A = FOG.a (the factor), B = FOG.rgb, C = PREV */ + return (uint32_t)(FC_FOG | 1 << 4) << 24 | (uint32_t)FC_FOG << 16 | (cw0 & 0xFF00u); +} diff --git a/xbox/src/hw/nv2a_fog.h b/xbox/src/hw/nv2a_fog.h new file mode 100644 index 0000000..bb627aa --- /dev/null +++ b/xbox/src/hw/nv2a_fog.h @@ -0,0 +1,55 @@ +/* nv2a_fog.h - GX fog (GXSetFog) on the NV2A (nv2a_fog.c). No pbkit here: + * tools/xbox/test_fog.py builds nv2a_fog.c on the host. */ +#ifndef NV2A_FOG_H +#define NV2A_FOG_H +#include + +#include "nv2a_vp.h" + +/* What the back end sends for one GXSetFog state. The vertex program + * (VpKey.fog = kind, rows VPC_FOG..VPC_FOG+2) computes GX's fog amount F per + * vertex from P, the view-space position (w = 1): + * y = (num . P) / (den . P) GX's clamp(ze - C) before the clamp + * VPF_LIN: F = y + * VPF_EXP: F = a + b * 2^(-8 y), y clamped to 0..1 + * VPF_EXP2: F = a + b * 2^(-8 y^2), y clamped to 0..1 + * with (-8, a, b, 0) in curve. The NV2A's fog unit runs in LINEAR mode with + * FOG_PARAMS (1, 1, 0), which makes the fog factor oFog.x itself, clamped to + * 0..1 per pixel, and the final combiner mixes F of the fog colour into the + * colour (fog_final_cw0). */ +typedef struct { + uint8_t kind; /* VPF_*; VPF_OFF: no fog */ + float num[4], den[4]; + float curve[4]; +} FogSetup; + +/* GXFogType -> VPF_*: bit 3 is orthographic, the low 3 bits the curve (0 off, + * 2 LIN, 4 EXP, 5 EXP2, 6 REVEXP, 7 REVEXP2; 1 and 3 are linear, as in Dolphin) */ +static inline uint8_t fog_kind(uint32_t type) { + switch (type & 7) { + case 0: return VPF_OFF; + case 4: case 6: return VPF_EXP; + case 5: case 7: return VPF_EXP2; + default: return VPF_LIN; + } +} + +/* type..farz: GXSetFog's arguments. zrow, wrow: the projection rows the + * vertex program's depth and w come from (nv2a.c VPC_PROJ + 2 and + 3: + * depth-buffer units, the viewport's depth range folded in); zmax: the + * depth buffer's maximum (2^24-1 or 65535). */ +void fog_setup(uint32_t type, float startz, float endz, float nearz, float farz, const float zrow[4], + const float wrow[4], float zmax, FogSetup* out); + +/* The final combiner's CW0 with fog: rgb = F * fog colour + (1 - F) * PREV, + * PREV being where cw0 (A = B = D = 0, C = PREV) read it. Alpha (CW1's G) is + * not touched. */ +uint32_t fog_final_cw0(uint32_t cw0); + +/* NV097_SET_FOG_COLOR: ABGR, red in the low byte. Alpha stays 0: the FOG + * register's alpha is the fog factor, and GX's fog colour has no alpha. */ +static inline uint32_t fog_color_abgr(const uint8_t rgba[4]) { + return (uint32_t)rgba[0] | (uint32_t)rgba[1] << 8 | (uint32_t)rgba[2] << 16; +} + +#endif diff --git a/xbox/src/hw/nv2a_vp.c b/xbox/src/hw/nv2a_vp.c index 3f250f6..1189301 100644 --- a/xbox/src/hw/nv2a_vp.c +++ b/xbox/src/hw/nv2a_vp.c @@ -151,6 +151,7 @@ static void arl(Gen* g, Src a) { const Src* s[3] = { &a, NULL, NULL }; Dst d = { #define MAD(d, a, b, c) mad(g, d, a, b, c) #define RCP(d, c) ilu(g, ILU_RCP, d, c) #define RSQ(d, c) ilu(g, ILU_RSQ, d, c) +#define EXPP(d, c) ilu(g, ILU_EXP, d, c) /* .z = 2^c (partial precision) */ #ifdef VP_HOST_TEST /* tools/xbox/test_vp_encoder.py: the same instructions as nv2a-vsh source */ @@ -172,6 +173,8 @@ void vp_test_program(VpProgram* p) { DP3(O(O_T0 + 1, MX), V(10), C(111)); MOV(O(O_T0 + 2, MZ | MW), sw(C(4), SWZ(0, 0, 0, 1))); RCP(O(O_FOG, MX), sw(R(11), YYYY)); + EXPP(T(3, MZ), sw(R(3), YYYY)); + MAD(O(O_FOG, MX), sw(R(3), ZZZZ), sw(C(136), ZZZZ), sw(C(136), YYYY)); } #endif @@ -341,6 +344,25 @@ void vp_generate(const VpKey* k, VpProgram* out) { MUL(O(O_POS, MXYZ), R(RCLIP), sw(R(RS), XXXX)); MOV(O(O_POS, MW), R(RCLIP)); + if (k->fog) { + /* GX fog from this vertex's depth (nv2a_fog.h): y = num.P / den.P, + * then the curve; the fog unit takes oFog.x as the factor */ + DP4(T(RS, MY), R(RPOS), C(VPC_FOG)); + DP4(T(RS, MZ), R(RPOS), C(VPC_FOG + 1)); + RCP(T(RS, MZ), sw(R(RS), ZZZZ)); + if (k->fog == VPF_LIN) { + MUL(O(O_FOG, MX), sw(R(RS), YYYY), sw(R(RS), ZZZZ)); + } else { + MUL(T(RS, MY), sw(R(RS), YYYY), sw(R(RS), ZZZZ)); + MAX(T(RS, MY), sw(R(RS), YYYY), K0()); + MIN(T(RS, MY), sw(R(RS), YYYY), K1()); + if (k->fog == VPF_EXP2) MUL(T(RS, MY), sw(R(RS), YYYY), sw(R(RS), YYYY)); + MUL(T(RS, MY), sw(R(RS), YYYY), sw(C(VPC_FOG + 2), XXXX)); + EXPP(T(RS, MZ), sw(R(RS), YYYY)); + MAD(O(O_FOG, MX), sw(R(RS), ZZZZ), sw(C(VPC_FOG + 2), ZZZZ), sw(C(VPC_FOG + 2), YYYY)); + } + } + if (needs_nrm) { DP3(T(RNRM, MX), V(VPI_NRM), CA(VPC_NRM)); DP3(T(RNRM, MY), V(VPI_NRM), CA(VPC_NRM + 1)); diff --git a/xbox/src/hw/nv2a_vp.h b/xbox/src/hw/nv2a_vp.h index c1fa876..e6a9989 100644 --- a/xbox/src/hw/nv2a_vp.h +++ b/xbox/src/hw/nv2a_vp.h @@ -12,7 +12,8 @@ #define VPC_LIGHT 70 /* 8 lights x 5 rows: pos, dir, colour, a, k */ #define VPC_TEXGEN 110 /* 4 units x 3 rows (s, t, q), post matrix folded in */ #define VPC_POSTMTX 122 /* 4 units x 3 rows: post-transform after normalize */ -#define VPC_COUNT 134 +#define VPC_FOG 134 /* 3 rows: fog numerator, denominator, curve (nv2a_fog.h) */ +#define VPC_COUNT 137 /* vertex inputs */ #define VPI_POS 0 @@ -26,6 +27,9 @@ static inline int vpi_tex(int n) { return n < 7 ? 9 + n : 8; } /* light attenuation variants the generator knows */ enum { VPL_OFF = 0, VPL_DIFFUSE, VPL_SPOT, VPL_SPEC }; +/* GX fog curves the generator writes oFog for (nv2a_fog.h) */ +enum { VPF_OFF = 0, VPF_LIN, VPF_EXP, VPF_EXP2 }; + typedef struct { uint8_t enable, amb_vtx, mat_vtx; uint8_t diff_fn; /* GXDiffuseFn */ @@ -47,7 +51,8 @@ typedef struct { uint8_t ntex; /* NV2A texture units fed, 0..4 */ VpTexGen tex[4]; uint8_t copy; /* EFB copy pass (nv2a.c): position and texcoord 0 as given */ - uint8_t pad[2]; + uint8_t fog; /* VPF_*: GX fog amount -> oFog.x */ + uint8_t pad; } VpKey; #define VP_MAX_INSNS 136 diff --git a/xbox/src/sdk/gx/gx_state.c b/xbox/src/sdk/gx/gx_state.c index b39f558..517c943 100644 --- a/xbox/src/sdk/gx/gx_state.c +++ b/xbox/src/sdk/gx/gx_state.c @@ -731,7 +731,13 @@ void GXEnableTexOffsets(GXTexCoordID coord, GXBool line, GXBool point) { (void)c void GXSetZTexture(GXZTexOp op, GXTexFmt fmt, u32 bias) { (void)op; (void)fmt; (void)bias; } void GXSetCoPlanar(GXBool on) { (void)on; } +/* Applied by the back end (nv2a_fog.c); HSD_FogSet calls this for every + * camera pass and particle kind, mostly with the values it already has. */ void GXSetFog(GXFogType type, f32 startz, f32 endz, f32 nearz, f32 farz, GXColor color) { + if (g_xgx.fog_type == (uint32_t)type && g_xgx.fog_start == startz && g_xgx.fog_end == endz && + g_xgx.fog_near == nearz && g_xgx.fog_far == farz && g_xgx.fog_color[0] == color.r && + g_xgx.fog_color[1] == color.g && g_xgx.fog_color[2] == color.b && g_xgx.fog_color[3] == color.a) + return; FLUSH(); g_xgx.fog_type = type; g_xgx.fog_start = startz; @@ -745,6 +751,7 @@ void GXSetFog(GXFogType type, f32 startz, f32 endz, f32 nearz, f32 farz, GXColor DIRTY(XGX_DIRTY_FOG); } +/* not applied: fog stays planar depth, without GX's horizontal correction */ void GXSetFogRangeAdj(GXBool enable, u16 center, GXFogAdjTable* table) { (void)enable; (void)center; (void)table; } /* SDK GXInitFogAdjTable: range adjustment is not applied, but the table must