Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ UnitFrames_Media/Libs/
/.build/
/.proof/
/.proof-art/
/scripts/portrait-capture/node_modules/
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ luajit tests/run.lua workbench -t "preview"
Every change that can affect what a frame, preview or Workbench panel looks like ships with UI proof rendered by `wowproof`: in the pull request and, when working in Beluga, in the chat and on the task.

1. Pick the scenarios in `tests/proof/units.lua` and `tests/proof/workbench.lua` that show the change. When none does (a new setting, state or layout), add one: a name plus a `build` that configures through `Config:SetUnitValue` and feeds sample values. Prefer one scenario per state the change touches (like `player-idle` beside `player`) over one busy frame.
2. Render and look at them with `bash scripts/proof.sh <filters>` before claiming the change works. Dashed placeholders mean missing art or an atlas the generated table lacks, not a bug. 3D portraits show a static race portrait as a stand-in; mention them if they hide the change.
2. Render and look at them with `bash scripts/proof.sh <filters>` before claiming the change works. Dashed placeholders mean missing art or an atlas the generated table lacks, not a bug. 3D portraits show a pre-rendered capture of the mocked player (Classic preset, from `UF_PROOF_PORTRAITS`), or a static race portrait where that folder isn't reachable, such as CI; mention them if they hide the change.
3. When opening or updating the pull request, run `bash scripts/proof-publish.sh --out .beluga/scratch/proof <filters>`. It renders the scenarios, commits the PNGs to the orphan `ui-proof` branch under `<branch>/` (it never touches the working tree or the current branch) and prints a `### UI proof` Markdown section with images pinned to that commit. Paste that section into the PR body (`gh pr create --body-file` or `gh pr edit --body-file`). Re-run it after visual changes in review; old links keep showing the earlier images. `--dry-run` skips the push.
4. In Beluga, show the same PNGs in the answer as Markdown images with their absolute paths under `.beluga/scratch/proof/`, and attach each one to the worktree's task with `task_attach_proof` (kind `image`).
5. Proof shows mocked rendering only. Still list what needs in-game verification (see Verification above): combat, secret values, taint, Edit Mode and live unit changes.
Expand Down
28 changes: 27 additions & 1 deletion DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -288,14 +288,40 @@ stands in a picture for the unit the model shows, keeping the model's alpha,
model alpha and dead/ghost desaturation. Proof renders Forever's **Classic**
experience preset (original "SD" character models) by default;
`UF_PROOF_PRESET=enhanced` renders the HD one. For each preset it first looks
for an in-game capture of the default portrait,
for a capture of the default portrait,
`<preset>/<Sex>-<Race>.png` (`Pet`/`Monster` for non-players), in the private
folder `UF_PROOF_PORTRAITS` (default `nas:/volume1/Game/unit-frames/proof-portraits`,
fetched over `ssh` into `.proof-art/portraits/`; also a local folder or an
HTTPS URL; skipped when `CI` is set or `UF_PROOF_ART_FETCH=0`). Captures are
Blizzard art: keep them in that folder, never in the repo. Without a capture
it falls back to Blizzard's static HD portrait
(`Interface\CharacterFrame\TemporaryPortrait-Male-<race>`) from the mirror.

`scripts/portrait-capture` renders the Classic captures: the 1.12 character
model through [classic-wow-model-viewer](https://github.com/JollyGrin/turtle-wow-model-viewer)
(MIT, three.js) in Playwright's headless Chromium shell (SwiftShader). It
replicates the client's `SetPortraitZoom(1)` view rather than inventing one:
the field of view and viewing direction come from the portrait camera (type 0)
of the pinned build's own M2 (`--m2`, human male 119940, fetched from Wago),
frozen at the first frame of Stand. The library's Stand pose leans the head
forward where Forever's doesn't, so the camera aims at the posed head (skinned
vertices) and `TURN`, `HEAD_SHARE` and `CENTER_DROP` in `capture.mjs` are
calibrated against an in-game player frame. The model is bald (hairstyle
geoset 1, as the library's default hair leaves a scalp gap), on a transparent
background matted from a black and a white render. It needs Node, ImageMagick
and a headless shell under
`~/.cache/ms-playwright` (`npx playwright install chromium-headless-shell`,
or `CHROME=<path>`). The model files come from the library's demo CDN
(`--cdn` or `PORTRAIT_CDN` for another), so render once and store the result
with the other captures:

```sh
cd scripts/portrait-capture && npm ci
node capture.mjs human male /tmp/Male-Human.png # --hair N, --size 256
ssh nas 'cat > /volume1/Game/unit-frames/proof-portraits/classic/Male-Human.png' < /tmp/Male-Human.png
rm -rf ../../.proof-art/portraits # re-fetch on the next proof run
```

Previews always show the player's own model (the portrait driver's sample is
`"player"`), so every sample portrait is the mocked Human. `player-dead`,
`focus-portrait` and `pet-portrait` cover the portraits that are off by
Expand Down
138 changes: 138 additions & 0 deletions scripts/portrait-capture/capture.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import { chromium } from "playwright-core";
import { execFileSync } from "node:child_process";
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
import { homedir, tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";

const ROOT = path.dirname(fileURLToPath(import.meta.url));
const VIEWER = "classic-wow-model-viewer/dist/index.js";
const DEFAULT_CDN = "https://jollygrin.github.io/turtle-wow-model-viewer";
const DEFAULT_BUILD = "1.60.1.70862";
const CASC = "https://wago.tools/api/casc";
const MODELS = { "human-male": 119940 };
const PORTRAIT_CAMERA = 0;
const CAMERA_SIZE = 116;
const NECK = 1.8;
const HEAD_SHARE = 0.55;
const CENTER_DROP = 0.13;
const TURN = 10;
const BROWSERS = path.join(homedir(), ".cache", "ms-playwright");
const TYPES = { ".js": "text/javascript", ".html": "text/html" };

const usage = () => {
console.error("usage: node capture.mjs <race> <male|female> <out.png> [--hair N] [--size N] [--turn DEG] [--m2 FileDataID] [--build B] [--cdn URL]");
process.exit(1);
};

const parseArgs = (argv) => {
const [race, gender, out, ...rest] = argv;
if (!race || !gender || !out) usage();
const options = {
race, gender, out, hair: 1, size: 256, turn: TURN, m2: MODELS[`${race}-${gender}`], build: DEFAULT_BUILD,
cdn: process.env.PORTRAIT_CDN ?? DEFAULT_CDN,
};
for (let index = 0; index < rest.length; index += 2) {
const key = rest[index].replace(/^--/, "");
if (!(key in options) || rest[index + 1] === undefined) usage();
options[key] = ["hair", "size", "m2", "turn"].includes(key) ? Number(rest[index + 1]) : rest[index + 1];
}
if (!options.m2) {
console.error(`no client model known for ${race}-${gender}: pass --m2 <FileDataID>`);
process.exit(1);
}
return options;
};

const findChrome = () => {
if (process.env.CHROME) return process.env.CHROME;
const shells = existsSync(BROWSERS) ? readdirSync(BROWSERS).filter((name) => name.startsWith("chromium_headless_shell-")).sort() : [];
for (const shell of shells.reverse()) {
for (const build of readdirSync(path.join(BROWSERS, shell))) {
const binary = path.join(BROWSERS, shell, build, "chrome-headless-shell");
if (existsSync(binary)) return binary;
}
}
return undefined;
};

const portraitCamera = async (fileDataId, build) => {
const response = await fetch(`${CASC}/${fileDataId}?version=${build}`);
if (!response.ok) throw new Error(`model ${fileDataId}: HTTP ${response.status}`);
const file = Buffer.from(await response.arrayBuffer());
const header = file.indexOf("MD20");
if (header < 0) throw new Error(`model ${fileDataId} is not an M2`);
const m2 = file.subarray(header);
const vector = (offset) => [m2.readFloatLE(offset), m2.readFloatLE(offset + 4), m2.readFloatLE(offset + 8)];
const firstKey = (track) => {
const animations = m2.readUInt32LE(track + 12), keys = m2.readUInt32LE(track + 16);
if (!animations || !m2.readUInt32LE(keys)) return undefined;
return m2.readFloatLE(m2.readUInt32LE(keys + 4));
};
const count = m2.readUInt32LE(272), cameras = m2.readUInt32LE(276);
for (let index = 0; index < count; index++) {
const camera = cameras + index * CAMERA_SIZE;
if (m2.readUInt32LE(camera) !== PORTRAIT_CAMERA) continue;
return {
far: m2.readFloatLE(camera + 4),
near: m2.readFloatLE(camera + 8),
position: vector(camera + 32),
target: vector(camera + 64),
fov: firstKey(camera + 96),
};
}
throw new Error(`model ${fileDataId} has no portrait camera`);
};

const withHairstyle = (source, hair) => {
const patched = source.replace("a.groups,\n 5,", `a.groups,\n ${hair},`);
if (patched === source) throw new Error(`${VIEWER} changed: can't set the hairstyle`);
return patched;
};

const serve = (page, hair) => page.route("http://capture/**", (route) => {
const pathname = new URL(route.request().url()).pathname;
const file = path.join(ROOT, pathname);
if (!file.startsWith(ROOT) || !existsSync(file)) return route.fulfill({ status: 404 });
const body = pathname.endsWith(VIEWER) ? withHairstyle(readFileSync(file, "utf8"), hair) : readFileSync(file);
return route.fulfill({ body, contentType: TYPES[path.extname(file)] ?? "application/octet-stream" });
});

const options = parseArgs(process.argv.slice(2));
const camera = await portraitCamera(options.m2, options.build);
const browser = await chromium.launch({
executablePath: findChrome(),
args: ["--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--ignore-gpu-blocklist"],
});
const work = mkdtempSync(path.join(tmpdir(), "portrait-"));

try {
const page = await browser.newPage({ viewport: { width: options.size, height: options.size } });
page.on("pageerror", (error) => console.error(error.message));
await serve(page, options.hair);
const framing = { turn: options.turn, neck: NECK, headShare: HEAD_SHARE, centerDrop: CENTER_DROP };
const query = new URLSearchParams({
cdn: options.cdn, race: options.race, gender: options.gender,
camera: JSON.stringify(camera), framing: JSON.stringify(framing),
});
await page.goto(`http://capture/page.html?${query}`);
await page.waitForFunction(() => window.ready, null, { timeout: 60000 });

const shots = {};
for (const [name, color] of [["black", 0x000000], ["white", 0xffffff]]) {
await page.evaluate((value) => window.setBackground(value), color);
await page.waitForTimeout(500);
shots[name] = path.join(work, `${name}.png`);
await page.screenshot({ path: shots[name] });
}

execFileSync("magick", [
shots.black,
"(", shots.black, shots.white, "-compose", "difference", "-composite", "-colorspace", "gray", "-negate", ")",
"-alpha", "off", "-compose", "copy_opacity", "-composite", options.out,
]);
console.log(options.out);
} finally {
await browser.close();
rmSync(work, { recursive: true, force: true });
}
42 changes: 42 additions & 0 deletions scripts/portrait-capture/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions scripts/portrait-capture/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "portrait-capture",
"private": true,
"type": "module",
"description": "Renders a 3D portrait stand-in for UI proof with classic-wow-model-viewer in headless Chromium",
"scripts": {
"capture": "node capture.mjs"
},
"dependencies": {
"classic-wow-model-viewer": "0.1.0",
"playwright-core": "1.65.0",
"three": "0.187.0"
}
}
64 changes: 64 additions & 0 deletions scripts/portrait-capture/page.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<!doctype html>
<html>
<body style="margin:0">
<div id="viewer" style="width:100vw;height:100vh"></div>
<script type="importmap">
{ "imports": { "three": "/node_modules/three/build/three.module.js", "three/examples/jsm/": "/node_modules/three/examples/jsm/" } }
</script>
<script type="module">
import * as THREE from "three";
import { ModelViewer, createCdnResolver } from "/node_modules/classic-wow-model-viewer/dist/index.js";

const params = new URLSearchParams(location.search);
const viewer = new ModelViewer({ container: document.getElementById("viewer"), assets: createCdnResolver(params.get("cdn")) });
await viewer.loadCharacter(params.get("race"), params.get("gender"));

viewer.scene.traverse((object) => {
for (const material of [].concat(object.material ?? [])) {
material.alphaTest = 0.5;
material.needsUpdate = true;
}
});

const toScene = ([x, y, z]) => new THREE.Vector3(x, z, -y);
const camera = JSON.parse(params.get("camera"));
const framing = JSON.parse(params.get("framing"));

cancelAnimationFrame(viewer.animFrameId);
viewer.playAnimationByName("Stand");
viewer.animController.update(0);
viewer.scene.updateMatrixWorld(true);

const head = new THREE.Box3();
const vertex = new THREE.Vector3();
viewer.scene.traverse((object) => {
if (!object.isSkinnedMesh) return;
const positions = object.geometry.attributes.position;
for (const index of new Set(object.geometry.index.array)) {
const [x, y, z] = [positions.getX(index), positions.getY(index), positions.getZ(index)];
if (z < framing.neck || Math.abs(x) > 0.3 || Math.abs(y) > 0.25) continue;
head.expandByPoint(object.getVertexPosition(index, vertex).applyMatrix4(object.matrixWorld));
}
});
const size = head.getSize(new THREE.Vector3());
const target = head.getCenter(new THREE.Vector3());
const visible = size.y / framing.headShare;
target.y -= visible * framing.centerDrop;

const direction = toScene(camera.position).sub(toScene(camera.target)).normalize()
.applyAxisAngle(new THREE.Vector3(0, 1, 0), THREE.MathUtils.degToRad(framing.turn));
viewer.camera.fov = THREE.MathUtils.radToDeg(camera.fov);
viewer.camera.near = camera.near;
viewer.camera.far = camera.far;
viewer.camera.position.copy(target).add(direction.multiplyScalar(visible / 2 / Math.tan(camera.fov / 2)));
viewer.camera.lookAt(target);
viewer.camera.updateProjectionMatrix();

window.setBackground = (color) => {
viewer.renderer.setClearColor(color);
viewer.renderer.render(viewer.scene, viewer.camera);
};
window.ready = true;
</script>
</body>
</html>
Loading