BlueGit

timfa raytracer

Files

raytracer / src / npc.js

npc.js

npc.js 11.1 KiB Download Raw
1/**
2 * Paperdoll NPC billboards.
3 * Compose body+gear on CPU when view/frame changes (cell ~32×48).
4 * Relight once in cell space per (npc, view, light fingerprint), then project
5 * with per-pixel depth into an offscreen RGBA buffer + z-buffer (perp depth,
6 * same space as walls). One WebGL textured quad — no per-screen-pixel shade.
7 */
8var NpcSystem =
9{
10 npcs: [],
11 bodySet: null,
12 gearSet: null,
13 ready: false,
14 cache: {},
15 litCache: {},
16 worldScale: 32,
17 _overlay: null,
18 _overlayCtx: null,
19 _overlayImg: null,
20 _zbuf: null,
21 _zbufW: 0,
22 _zbufH: 0,
23
24 initEmpty: function ()
25 {
26 this.npcs = [];
27 this.cache = {};
28 this.litCache = {};
29 this.ready = false;
30 },
31
32 addNpc: function (opts)
33 {
34 this.npcs.push({
35 x: opts.x,
36 y: opts.y,
37 z: opts.z != null ? opts.z : 0,
38 facingDeg: opts.facingDeg || 0,
39 clip: opts.clip || "walk",
40 animating: opts.animating !== false,
41 time: opts.time || 0,
42 label: opts.label || "npc"
43 });
44 },
45
46 load: function (bodyBase, bodyPpda, gearBase, gearPpda)
47 {
48 var self = this;
49 return PpdaAtlasRuntime.loadSet(bodyBase, bodyPpda).then(function (body)
50 {
51 self.bodySet = body;
52 if (!gearBase)
53 {
54 self.ready = true;
55 return body;
56 }
57 return PpdaAtlasRuntime.loadSet(gearBase, gearPpda).then(function (gear)
58 {
59 PpdaLoader.assertCompatible(body.ppda, gear.ppda);
60 self.gearSet = gear;
61 self.ready = true;
62 return body;
63 });
64 });
65 },
66
67 update: function (dt)
68 {
69 for (var i = 0; i < this.npcs.length; i++)
70 {
71 if (this.npcs[i].animating)
72 { this.npcs[i].time += dt; }
73 }
74 },
75
76 composedFor: function (npc, pitch, yaw)
77 {
78 if (!this.bodySet)
79 { return null; }
80 var clip = PpdaViewFrame.findClip(this.bodySet.ppda, npc.clip);
81 var frameCount = clip ? clip.frame_count : 1;
82 var frame = PpdaViewFrame.frameIndex(npc.time, this.bodySet.ppda.fps, frameCount);
83 var key = npc.clip + "|" + frame + "|" + pitch + "|" + yaw;
84 if (this.cache[key])
85 { return this.cache[key]; }
86 var composed = PpdaAtlasRuntime.composeView(
87 this.bodySet,
88 this.gearSet,
89 npc.clip,
90 frame,
91 pitch,
92 yaw
93 );
94 this.cache[key] = composed;
95 var keys = Object.keys(this.cache);
96 if (keys.length > 96)
97 { delete this.cache[keys[0]]; }
98 return composed;
99 },
100
101 _lightFingerprint: function (lights, ambient)
102 {
103 var s = String(ambient == null ? 0.38 : ambient);
104 if (!lights || !lights.length)
105 { return s; }
106 var n = Math.min(lights.length, 8);
107 for (var i = 0; i < n; i++)
108 {
109 var L = lights[i];
110 s += "|" + (L.x | 0) + "," + (L.y | 0) + "," + ((L.z != null ? L.z : 16) | 0)
111 + "," + ((L.intensity == null ? 1 : L.intensity) * 10 | 0)
112 + "," + ((L.range || 64) | 0);
113 }
114 return s;
115 },
116
117 /**
118 * Shade the composed cell once (32×48) into a lit RGBA buffer.
119 * Screen projection only samples this — no per-pixel Lighting on the sprite.
120 */
121 litCellFor: function (composed, npc, yaw, lights, ambient, heightM, metersToWorld, camDist, near, far)
122 {
123 var fp = this._lightFingerprint(lights, ambient);
124 var key = (composed._cacheKey || "") + "|" + (npc.facingDeg || 0) + "|" + yaw
125 + "|" + (npc.x | 0) + "," + (npc.y | 0) + "|" + fp;
126 if (this.litCache[key])
127 { return this.litCache[key]; }
128
129 var w = composed.width;
130 var h = composed.height;
131 var out = new Uint8ClampedArray(w * h * 4);
132 var face = (npc.facingDeg || 0) * Math.PI / 180;
133 var yawR = (yaw || 0) * Math.PI / 180;
134 var camCX = Math.sin(yawR), camCZ = Math.cos(yawR);
135 var frontX = Math.cos(face), frontY = Math.sin(face);
136 var rightX = -Math.sin(face), rightY = Math.cos(face);
137 var camX = rightX * camCX + frontX * camCZ;
138 var camY = rightY * camCX + frontY * camCZ;
139 var viewRightX = -camY;
140 var viewRightY = camX;
141
142 for (var ty = 0; ty < h; ty++)
143 {
144 for (var tx = 0; tx < w; tx++)
145 {
146 var pi = ty * w + tx;
147 var o = pi * 4;
148 var a = composed.diffuse[o + 3];
149 if (!a || composed.depthAlpha[pi] === 0)
150 {
151 out[o + 3] = 0;
152 continue;
153 }
154 var u = (tx + 0.5) / w;
155 var ar = composed.diffuse[o];
156 var ag = composed.diffuse[o + 1];
157 var ab = composed.diffuse[o + 2];
158 var heightFrac = 1 - (ty + 0.5) / h;
159 var pxZ = heightFrac * heightM * metersToWorld * 0.5;
160 var depthM = near + (composed.depthGray[pi] / 65535) * (far - near);
161 var depthOff = (depthM - camDist) * metersToWorld;
162 var lat = (u - 0.5) * (heightM * metersToWorld * 0.45);
163 var pxWorld = {
164 x: npc.x + viewRightX * lat + camX * depthOff,
165 y: npc.y + viewRightY * lat + camY * depthOff,
166 z: pxZ + (npc.z || 0)
167 };
168 var nr = composed.normal ? composed.normal[o] : 128;
169 var ng = composed.normal ? composed.normal[o + 1] : 128;
170 var nb = composed.normal ? composed.normal[o + 2] : 255;
171 var geoTiltX = (u - 0.5) * 2;
172 var shaded;
173 if (typeof Lighting !== "undefined")
174 {
175 shaded = Lighting.shadePaperdollPixel(
176 ar, ag, ab, nr, ng, nb, pxWorld,
177 lights || [], ambient, yaw, npc.facingDeg || 0, geoTiltX
178 );
179 }
180 else
181 {
182 shaded = { r: ar, g: ag, b: ab };
183 }
184 out[o] = shaded.r;
185 out[o + 1] = shaded.g;
186 out[o + 2] = shaded.b;
187 out[o + 3] = a;
188 }
189 }
190 this.litCache[key] = out;
191 var keys = Object.keys(this.litCache);
192 if (keys.length > 64)
193 { delete this.litCache[keys[0]]; }
194 return out;
195 },
196
197 _ensureOverlay: function (w, h)
198 {
199 if (!this._overlay || this._overlay.width !== w || this._overlay.height !== h)
200 {
201 this._overlay = document.createElement("canvas");
202 this._overlay.width = w;
203 this._overlay.height = h;
204 this._overlayCtx = this._overlay.getContext("2d");
205 this._overlayImg = null;
206 this._overlayTex = null;
207 this._zbuf = new Float32Array(w * h);
208 this._zbufW = w;
209 this._zbufH = h;
210 }
211 },
212
213 /**
214 * @param {Float32Array} wallDepthPerCol length = screen width (perp depths)
215 */
216 draw: function (scene, player, wallDepthPerCol)
217 {
218 if (!this.ready || !this.bodySet)
219 { return; }
220
221 var w = Math.round(scene.real_size.x);
222 var h = Math.round(scene.real_size.y);
223 this._ensureOverlay(w, h);
224 var ctx = this._overlayCtx;
225 ctx.clearRect(0, 0, w, h);
226 var img = ctx.createImageData(w, h);
227 var data = img.data;
228 var zbuf = this._zbuf;
229 var i;
230 for (i = 0; i < w * h; i++)
231 {
232 var col = i % w;
233 zbuf[i] = wallDepthPerCol[col];
234 }
235
236 var ppda = this.bodySet.ppda;
237 var heightM = (ppda.height_milli || 2600) / 1000;
238 var camDist = ppda.camera_distance || 10;
239 var near = ppda.depth_near;
240 var far = ppda.depth_far;
241 var metersToWorld = this.worldScale;
242 var lights = World.level && World.level.lights;
243 var ambient = World.level && World.level.ambient != null
244 ? World.level.ambient : 0.38;
245 var playerEyeZ = World.size * 0.5;
246
247 var list = this.npcs.slice().sort(function (a, b)
248 {
249 var da = Camera.perpDepth(a.x, a.y, player.x, player.y, player.rotation);
250 var db = Camera.perpDepth(b.x, b.y, player.x, player.y, player.rotation);
251 return db - da;
252 });
253
254 for (var ni = 0; ni < list.length; ni++)
255 {
256 var npc = list[ni];
257 var proj = Camera.projectSprite(npc.x, npc.y, player.x, player.y, player.rotation, w);
258 if (!proj)
259 { continue; }
260 var dist = proj.depth;
261 if (dist < 0.5 || dist > 800)
262 { continue; }
263 // Off-screen cull (allow some margin)
264 if (proj.screenX < -w * 0.5 || proj.screenX > w * 1.5)
265 { continue; }
266
267 var horiz = Math.sqrt(
268 (npc.x - player.x) * (npc.x - player.x) +
269 (npc.y - player.y) * (npc.y - player.y)
270 );
271 var npcCenterZ = (npc.z || 0) + heightM * metersToWorld * 0.25;
272 var relYaw = PpdaViewFrame.relativeYawDeg(player.x, player.y, npc.x, npc.y, npc.facingDeg);
273 var yaw = PpdaViewFrame.pickYaw(relYaw, ppda.yaws);
274 // Pitch from height difference only — looking up/down must not tilt sprites.
275 var pitch = PpdaViewFrame.pickPitchFromHeight(
276 playerEyeZ, npcCenterZ, horiz, ppda.pitches
277 );
278
279 var clipInfo = PpdaViewFrame.findClip(ppda, npc.clip);
280 var frame = PpdaViewFrame.frameIndex(
281 npc.time, ppda.fps, clipInfo ? clipInfo.frame_count : 1
282 );
283 var composed = this.composedFor(npc, pitch, yaw);
284 if (!composed)
285 { continue; }
286 composed._cacheKey = npc.clip + "|" + frame + "|" + pitch + "|" + yaw;
287
288 var lit = this.litCellFor(
289 composed, npc, yaw, lights || [], ambient,
290 heightM, metersToWorld, camDist, near, far
291 );
292
293 var spriteH = (World.size * heightM) * (h / dist) * 0.5;
294 var aspect = composed.width / Math.max(1, composed.height);
295 var spriteW = spriteH * aspect;
296 var screenX = proj.screenX;
297 // Horizon uses look pitch for floor alignment; atlas pitch does not.
298 var mid = h / 2 + (-player.pitch * h * 0.25);
299 var floorY = mid + (World.size * 0.5 * h) / dist;
300 var left = screenX - spriteW / 2;
301
302 var feetRow = composed.height - 1;
303 var feetH = composed.height;
304 var feetW = composed.width;
305 var feetAlpha = composed.diffuse;
306 try
307 {
308 var bodyLayer = PpdaAtlasRuntime.layerFromSet(
309 this.bodySet, npc.clip, frame, pitch, yaw
310 );
311 feetAlpha = bodyLayer.diffuse;
312 feetW = bodyLayer.width;
313 feetH = bodyLayer.height;
314 feetRow = feetH - 1;
315 }
316 catch (e) { /* fallback: composed */ }
317 for (var fy = feetH - 1; fy >= 0; fy--)
318 {
319 var rowHit = false;
320 for (var fx = 0; fx < feetW; fx++)
321 {
322 if (feetAlpha[(fy * feetW + fx) * 4 + 3] > 10)
323 { rowHit = true; break; }
324 }
325 if (rowHit)
326 { feetRow = fy; break; }
327 }
328 var top = floorY - ((feetRow + 0.5) / feetH) * spriteH;
329 var cols = Math.max(1, Math.ceil(spriteW));
330
331 for (var c = 0; c < cols; c++)
332 {
333 var sx = Math.floor(left + c);
334 if (sx < 0 || sx >= w)
335 { continue; }
336 var u = (c + 0.5) / cols;
337 var texX = Math.min(composed.width - 1, Math.max(0, Math.floor(u * composed.width)));
338 var y0 = Math.floor(top);
339 var y1 = Math.ceil(top + spriteH);
340
341 for (var sy = y0; sy < y1; sy++)
342 {
343 if (sy < 0 || sy >= h)
344 { continue; }
345 var v = (sy - top + 0.5) / spriteH;
346 if (v < 0 || v >= 1)
347 { continue; }
348 var texY = Math.min(composed.height - 1, Math.max(0, Math.floor(v * composed.height)));
349 var pi = texY * composed.width + texX;
350 var a = lit[pi * 4 + 3];
351 if (!a || composed.depthAlpha[pi] === 0)
352 { continue; }
353
354 var depthM = near + (composed.depthGray[pi] / 65535) * (far - near);
355 var pixelDist = dist + (depthM - camDist) * metersToWorld;
356 if (pixelDist < 0.05)
357 { pixelDist = 0.05; }
358
359 var zi = sy * w + sx;
360 if (pixelDist >= zbuf[zi])
361 { continue; }
362 zbuf[zi] = pixelDist;
363
364 var o = zi * 4;
365 data[o] = lit[pi * 4];
366 data[o + 1] = lit[pi * 4 + 1];
367 data[o + 2] = lit[pi * 4 + 2];
368 data[o + 3] = a;
369 }
370 }
371 }
372
373 ctx.putImageData(img, 0, 0);
374 var glc = scene.glContext;
375 if (this._overlayTex)
376 {
377 var gl = glc.gl;
378 gl.bindTexture(gl.TEXTURE_2D, this._overlayTex);
379 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._overlay);
380 }
381 else
382 {
383 var prevMin = glc.textureMinFilter;
384 var prevMag = glc.textureMagFilter;
385 glc.setDefaultTextureFilter(glc.gl.NEAREST, glc.gl.NEAREST);
386 this._overlayTex = glc.getTexture(this._overlay);
387 glc.textureMinFilter = prevMin;
388 glc.textureMagFilter = prevMag;
389 }
390
391 glc.drawSprite({
392 texture: this._overlayTex,
393 x: w / 2,
394 y: h / 2,
395 w: w,
396 h: h,
397 rotationDeg: 0,
398 alpha: 1,
399 uvRect: { u0: 0, v0: 0, u1: 1, v1: 1 }
400 });
401 }
402};