BlueGit

timfa raytracer

Files

raytracer / test / camera.test.js

camera.test.js

camera.test.js 2.7 KiB Download Raw
1"use strict";
2const { describe, it } = require("node:test");
3const assert = require("node:assert/strict");
4const Camera = require("../src/camera.js");
5
6describe("Camera projection (no fish-eye)", () =>
7{
8 it("plane is perpendicular to forward and length tan(halfFov)", () =>
9 {
10 const rot = 0.3;
11 const f = Camera.forward(rot);
12 const p = Camera.plane(rot);
13 assert.ok(Math.abs(f.x * p.x + f.y * p.y) < 1e-9);
14 const plen = Math.sqrt(p.x * p.x + p.y * p.y);
15 assert.ok(Math.abs(plen - Camera.tanHalfFov()) < 1e-9);
16 });
17
18 it("straight wall columns share equal perp depth (flat wall ahead)", () =>
19 {
20 // Player at origin facing +X; wall at x=100 from y=-50..50.
21 // Hits along camera-plane rays to the wall plane x=100 have perp depth = 100.
22 const rot = 0;
23 const wallX = 100;
24 for (const camX of [-0.9, -0.5, 0, 0.5, 0.9])
25 {
26 const d = Camera.rayDir(rot, camX);
27 // intersect x = wallX: player.x + d.x * t = wallX → t = wallX/d.x
28 const t = wallX / d.x;
29 const hitX = d.x * t;
30 const hitY = d.y * t;
31 const euclid = Math.sqrt(hitX * hitX + hitY * hitY);
32 const perp = Camera.perpFromEuclid(euclid, rot, camX);
33 assert.ok(Math.abs(perp - wallX) < 1e-6, "camX=" + camX + " perp=" + perp);
34 const depth = Camera.perpDepth(hitX, hitY, 0, 0, rot);
35 assert.ok(Math.abs(depth - wallX) < 1e-6);
36 }
37 });
38
39 it("sprite screenX moves smoothly; depth stays perp (not Euclidean)", () =>
40 {
41 // NPC at (100, 30), player at origin facing +X: euclid > perp
42 const proj = Camera.projectSprite(100, 30, 0, 0, 0, 320);
43 assert.ok(proj);
44 assert.ok(Math.abs(proj.depth - 100) < 1e-9);
45 const euclid = Math.sqrt(100 * 100 + 30 * 30);
46 assert.ok(proj.depth < euclid);
47 // Rotating in place should keep depth = forward·offset
48 const rot = 0.2;
49 const p2 = Camera.projectSprite(100, 30, 0, 0, rot, 320);
50 const expected = 100 * Math.cos(rot) + 30 * Math.sin(rot);
51 assert.ok(Math.abs(p2.depth - expected) < 1e-9);
52 });
53
54 it("NPC in front of wall keeps smaller depth than wall when only rotating", () =>
55 {
56 // Wall at x=120, NPC at (80, 10). Player at origin, rotate ±0.4.
57 const wallX = 120;
58 const npc = { x: 80, y: 10 };
59 for (const rot of [-0.4, -0.2, 0, 0.2, 0.4])
60 {
61 const npcDepth = Camera.perpDepth(npc.x, npc.y, 0, 0, rot);
62 // Wall hit for the column under the NPC
63 const proj = Camera.projectSprite(npc.x, npc.y, 0, 0, rot, 320);
64 assert.ok(proj && proj.depth > 0);
65 const camX = (2 * proj.screenX / 320) - 1;
66 const d = Camera.rayDir(rot, camX);
67 const t = wallX / d.x; // player at 0
68 const hitY = d.y * t;
69 const wallDepth = Camera.perpDepth(wallX, hitY, 0, 0, rot);
70 assert.ok(npcDepth < wallDepth,
71 "rot=" + rot + " npc=" + npcDepth + " wall=" + wallDepth);
72 }
73 });
74});