/** * Paperdoll NPC billboards. * Compose body+gear on CPU when view/frame changes (cell ~32×48). * Relight once in cell space per (npc, view, light fingerprint), then project * with per-pixel depth into an offscreen RGBA buffer + z-buffer (perp depth, * same space as walls). One WebGL textured quad — no per-screen-pixel shade. */ var NpcSystem = { npcs: [], bodySet: null, gearSet: null, ready: false, cache: {}, litCache: {}, worldScale: 32, _overlay: null, _overlayCtx: null, _overlayImg: null, _zbuf: null, _zbufW: 0, _zbufH: 0, initEmpty: function () { this.npcs = []; this.cache = {}; this.litCache = {}; this.ready = false; }, addNpc: function (opts) { this.npcs.push({ x: opts.x, y: opts.y, z: opts.z != null ? opts.z : 0, facingDeg: opts.facingDeg || 0, clip: opts.clip || "walk", animating: opts.animating !== false, time: opts.time || 0, label: opts.label || "npc" }); }, load: function (bodyBase, bodyPpda, gearBase, gearPpda) { var self = this; return PpdaAtlasRuntime.loadSet(bodyBase, bodyPpda).then(function (body) { self.bodySet = body; if (!gearBase) { self.ready = true; return body; } return PpdaAtlasRuntime.loadSet(gearBase, gearPpda).then(function (gear) { PpdaLoader.assertCompatible(body.ppda, gear.ppda); self.gearSet = gear; self.ready = true; return body; }); }); }, update: function (dt) { for (var i = 0; i < this.npcs.length; i++) { if (this.npcs[i].animating) { this.npcs[i].time += dt; } } }, composedFor: function (npc, pitch, yaw) { if (!this.bodySet) { return null; } var clip = PpdaViewFrame.findClip(this.bodySet.ppda, npc.clip); var frameCount = clip ? clip.frame_count : 1; var frame = PpdaViewFrame.frameIndex(npc.time, this.bodySet.ppda.fps, frameCount); var key = npc.clip + "|" + frame + "|" + pitch + "|" + yaw; if (this.cache[key]) { return this.cache[key]; } var composed = PpdaAtlasRuntime.composeView( this.bodySet, this.gearSet, npc.clip, frame, pitch, yaw ); this.cache[key] = composed; var keys = Object.keys(this.cache); if (keys.length > 96) { delete this.cache[keys[0]]; } return composed; }, _lightFingerprint: function (lights, ambient) { var s = String(ambient == null ? 0.38 : ambient); if (!lights || !lights.length) { return s; } var n = Math.min(lights.length, 8); for (var i = 0; i < n; i++) { var L = lights[i]; s += "|" + (L.x | 0) + "," + (L.y | 0) + "," + ((L.z != null ? L.z : 16) | 0) + "," + ((L.intensity == null ? 1 : L.intensity) * 10 | 0) + "," + ((L.range || 64) | 0); } return s; }, /** * Shade the composed cell once (32×48) into a lit RGBA buffer. * Screen projection only samples this — no per-pixel Lighting on the sprite. */ litCellFor: function (composed, npc, yaw, lights, ambient, heightM, metersToWorld, camDist, near, far) { var fp = this._lightFingerprint(lights, ambient); var key = (composed._cacheKey || "") + "|" + (npc.facingDeg || 0) + "|" + yaw + "|" + (npc.x | 0) + "," + (npc.y | 0) + "|" + fp; if (this.litCache[key]) { return this.litCache[key]; } var w = composed.width; var h = composed.height; var out = new Uint8ClampedArray(w * h * 4); var face = (npc.facingDeg || 0) * Math.PI / 180; var yawR = (yaw || 0) * Math.PI / 180; var camCX = Math.sin(yawR), camCZ = Math.cos(yawR); var frontX = Math.cos(face), frontY = Math.sin(face); var rightX = -Math.sin(face), rightY = Math.cos(face); var camX = rightX * camCX + frontX * camCZ; var camY = rightY * camCX + frontY * camCZ; var viewRightX = -camY; var viewRightY = camX; for (var ty = 0; ty < h; ty++) { for (var tx = 0; tx < w; tx++) { var pi = ty * w + tx; var o = pi * 4; var a = composed.diffuse[o + 3]; if (!a || composed.depthAlpha[pi] === 0) { out[o + 3] = 0; continue; } var u = (tx + 0.5) / w; var ar = composed.diffuse[o]; var ag = composed.diffuse[o + 1]; var ab = composed.diffuse[o + 2]; var heightFrac = 1 - (ty + 0.5) / h; var pxZ = heightFrac * heightM * metersToWorld * 0.5; var depthM = near + (composed.depthGray[pi] / 65535) * (far - near); var depthOff = (depthM - camDist) * metersToWorld; var lat = (u - 0.5) * (heightM * metersToWorld * 0.45); var pxWorld = { x: npc.x + viewRightX * lat + camX * depthOff, y: npc.y + viewRightY * lat + camY * depthOff, z: pxZ + (npc.z || 0) }; var nr = composed.normal ? composed.normal[o] : 128; var ng = composed.normal ? composed.normal[o + 1] : 128; var nb = composed.normal ? composed.normal[o + 2] : 255; var geoTiltX = (u - 0.5) * 2; var shaded; if (typeof Lighting !== "undefined") { shaded = Lighting.shadePaperdollPixel( ar, ag, ab, nr, ng, nb, pxWorld, lights || [], ambient, yaw, npc.facingDeg || 0, geoTiltX ); } else { shaded = { r: ar, g: ag, b: ab }; } out[o] = shaded.r; out[o + 1] = shaded.g; out[o + 2] = shaded.b; out[o + 3] = a; } } this.litCache[key] = out; var keys = Object.keys(this.litCache); if (keys.length > 64) { delete this.litCache[keys[0]]; } return out; }, _ensureOverlay: function (w, h) { if (!this._overlay || this._overlay.width !== w || this._overlay.height !== h) { this._overlay = document.createElement("canvas"); this._overlay.width = w; this._overlay.height = h; this._overlayCtx = this._overlay.getContext("2d"); this._overlayImg = null; this._overlayTex = null; this._zbuf = new Float32Array(w * h); this._zbufW = w; this._zbufH = h; } }, /** * @param {Float32Array} wallDepthPerCol length = screen width (perp depths) */ draw: function (scene, player, wallDepthPerCol) { if (!this.ready || !this.bodySet) { return; } var w = Math.round(scene.real_size.x); var h = Math.round(scene.real_size.y); this._ensureOverlay(w, h); var ctx = this._overlayCtx; ctx.clearRect(0, 0, w, h); var img = ctx.createImageData(w, h); var data = img.data; var zbuf = this._zbuf; var i; for (i = 0; i < w * h; i++) { var col = i % w; zbuf[i] = wallDepthPerCol[col]; } var ppda = this.bodySet.ppda; var heightM = (ppda.height_milli || 2600) / 1000; var camDist = ppda.camera_distance || 10; var near = ppda.depth_near; var far = ppda.depth_far; var metersToWorld = this.worldScale; var lights = World.level && World.level.lights; var ambient = World.level && World.level.ambient != null ? World.level.ambient : 0.38; var playerEyeZ = World.size * 0.5; var list = this.npcs.slice().sort(function (a, b) { var da = Camera.perpDepth(a.x, a.y, player.x, player.y, player.rotation); var db = Camera.perpDepth(b.x, b.y, player.x, player.y, player.rotation); return db - da; }); for (var ni = 0; ni < list.length; ni++) { var npc = list[ni]; var proj = Camera.projectSprite(npc.x, npc.y, player.x, player.y, player.rotation, w); if (!proj) { continue; } var dist = proj.depth; if (dist < 0.5 || dist > 800) { continue; } // Off-screen cull (allow some margin) if (proj.screenX < -w * 0.5 || proj.screenX > w * 1.5) { continue; } var horiz = Math.sqrt( (npc.x - player.x) * (npc.x - player.x) + (npc.y - player.y) * (npc.y - player.y) ); var npcCenterZ = (npc.z || 0) + heightM * metersToWorld * 0.25; var relYaw = PpdaViewFrame.relativeYawDeg(player.x, player.y, npc.x, npc.y, npc.facingDeg); var yaw = PpdaViewFrame.pickYaw(relYaw, ppda.yaws); // Pitch from height difference only — looking up/down must not tilt sprites. var pitch = PpdaViewFrame.pickPitchFromHeight( playerEyeZ, npcCenterZ, horiz, ppda.pitches ); var clipInfo = PpdaViewFrame.findClip(ppda, npc.clip); var frame = PpdaViewFrame.frameIndex( npc.time, ppda.fps, clipInfo ? clipInfo.frame_count : 1 ); var composed = this.composedFor(npc, pitch, yaw); if (!composed) { continue; } composed._cacheKey = npc.clip + "|" + frame + "|" + pitch + "|" + yaw; var lit = this.litCellFor( composed, npc, yaw, lights || [], ambient, heightM, metersToWorld, camDist, near, far ); var spriteH = (World.size * heightM) * (h / dist) * 0.5; var aspect = composed.width / Math.max(1, composed.height); var spriteW = spriteH * aspect; var screenX = proj.screenX; // Horizon uses look pitch for floor alignment; atlas pitch does not. var mid = h / 2 + (-player.pitch * h * 0.25); var floorY = mid + (World.size * 0.5 * h) / dist; var left = screenX - spriteW / 2; var feetRow = composed.height - 1; var feetH = composed.height; var feetW = composed.width; var feetAlpha = composed.diffuse; try { var bodyLayer = PpdaAtlasRuntime.layerFromSet( this.bodySet, npc.clip, frame, pitch, yaw ); feetAlpha = bodyLayer.diffuse; feetW = bodyLayer.width; feetH = bodyLayer.height; feetRow = feetH - 1; } catch (e) { /* fallback: composed */ } for (var fy = feetH - 1; fy >= 0; fy--) { var rowHit = false; for (var fx = 0; fx < feetW; fx++) { if (feetAlpha[(fy * feetW + fx) * 4 + 3] > 10) { rowHit = true; break; } } if (rowHit) { feetRow = fy; break; } } var top = floorY - ((feetRow + 0.5) / feetH) * spriteH; var cols = Math.max(1, Math.ceil(spriteW)); for (var c = 0; c < cols; c++) { var sx = Math.floor(left + c); if (sx < 0 || sx >= w) { continue; } var u = (c + 0.5) / cols; var texX = Math.min(composed.width - 1, Math.max(0, Math.floor(u * composed.width))); var y0 = Math.floor(top); var y1 = Math.ceil(top + spriteH); for (var sy = y0; sy < y1; sy++) { if (sy < 0 || sy >= h) { continue; } var v = (sy - top + 0.5) / spriteH; if (v < 0 || v >= 1) { continue; } var texY = Math.min(composed.height - 1, Math.max(0, Math.floor(v * composed.height))); var pi = texY * composed.width + texX; var a = lit[pi * 4 + 3]; if (!a || composed.depthAlpha[pi] === 0) { continue; } var depthM = near + (composed.depthGray[pi] / 65535) * (far - near); var pixelDist = dist + (depthM - camDist) * metersToWorld; if (pixelDist < 0.05) { pixelDist = 0.05; } var zi = sy * w + sx; if (pixelDist >= zbuf[zi]) { continue; } zbuf[zi] = pixelDist; var o = zi * 4; data[o] = lit[pi * 4]; data[o + 1] = lit[pi * 4 + 1]; data[o + 2] = lit[pi * 4 + 2]; data[o + 3] = a; } } } ctx.putImageData(img, 0, 0); var glc = scene.glContext; if (this._overlayTex) { var gl = glc.gl; gl.bindTexture(gl.TEXTURE_2D, this._overlayTex); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._overlay); } else { var prevMin = glc.textureMinFilter; var prevMag = glc.textureMagFilter; glc.setDefaultTextureFilter(glc.gl.NEAREST, glc.gl.NEAREST); this._overlayTex = glc.getTexture(this._overlay); glc.textureMinFilter = prevMin; glc.textureMagFilter = prevMag; } glc.drawSprite({ texture: this._overlayTex, x: w / 2, y: h / 2, w: w, h: h, rotationDeg: 0, alpha: 1, uvRect: { u0: 0, v0: 0, u1: 1, v1: 1 } }); } };