/** * Paperdoll NPC billboards. * Compose body+gear on CPU when view/frame changes (cell ~32×48). * Project with per-pixel depth into an offscreen RGBA buffer + z-buffer, * then one WebGL textured quad — avoids thousands of drawSprite calls. */ var NpcSystem = { npcs: [], bodySet: null, gearSet: null, ready: false, cache: {}, worldScale: 32, _overlay: null, _overlayCtx: null, _overlayImg: null, _zbuf: null, _zbufW: 0, _zbufH: 0, initEmpty: function () { this.npcs = []; this.cache = {}; this.ready = false; }, addNpc: function (opts) { this.npcs.push({ x: opts.x, y: opts.y, 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; }, _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 */ 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 tint = scene.npcLight != null ? scene.npcLight : 1; var list = this.npcs.slice().sort(function (a, b) { var da = (a.x - player.x) * (a.x - player.x) + (a.y - player.y) * (a.y - player.y); var db = (b.x - player.x) * (b.x - player.x) + (b.y - player.y) * (b.y - player.y); return db - da; }); for (var ni = 0; ni < list.length; ni++) { var npc = list[ni]; var dx = npc.x - player.x; var dy = npc.y - player.y; var dist = Math.sqrt(dx * dx + dy * dy); if (dist < 0.5 || dist > 800) { continue; } var angleTo = Math.atan2(dy, dx); var delta = angleTo - player.rotation; while (delta > Math.PI) { delta -= Math.PI * 2; } while (delta < -Math.PI) { delta += Math.PI * 2; } if (Math.abs(delta) > Math.PI * 0.55) { continue; } var relYaw = PpdaViewFrame.relativeYawDeg(player.x, player.y, npc.x, npc.y, npc.facingDeg); var yaw = PpdaViewFrame.pickYaw(relYaw, ppda.yaws); var pitch = Math.abs(player.pitch) < 0.25 ? PpdaViewFrame.nearestInList(0, ppda.pitches) : PpdaViewFrame.pickPitch(player.pitch, 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; } var spriteH = (World.size * heightM) * (h / dist) * 0.5; var aspect = composed.width / Math.max(1, composed.height); var spriteW = spriteH * aspect; var screenX = (w / 2) + (delta / (Math.PI / 3)) * (w / 2); // Horizon + pitch (same mid as FloorCast). Visual feet (= last opaque // atlas row) sit on the floor plane at this distance. var mid = h / 2 + (-player.pitch * h * 0.25); var floorY = mid + (World.size * 0.5 * h) / dist; var left = screenX - spriteW / 2; // Feet from BODY atlas only (gear can hang below and would lift the sprite). 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 = composed.diffuse[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; var ar = composed.diffuse[pi * 4]; var ag = composed.diffuse[pi * 4 + 1]; var ab = composed.diffuse[pi * 4 + 2]; var lights = World.level && World.level.lights; var ambient = World.level && World.level.ambient != null ? World.level.ambient : 0.38; // Pixel world: NPC feet + height from atlas v + depth along view cam. var heightFrac = 1 - (texY + 0.5) / composed.height; var pxZ = heightFrac * heightM * metersToWorld * 0.5; var depthOff = (depthM - camDist) * metersToWorld; 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 lat = (u - 0.5) * (heightM * metersToWorld * 0.35); var pxWorld = { x: npc.x + (-camY) * lat + camX * depthOff, y: npc.y + (camX) * lat + camY * depthOff, z: pxZ }; var nr = composed.normal ? composed.normal[pi * 4] : 128; var ng = composed.normal ? composed.normal[pi * 4 + 1] : 128; var nb = composed.normal ? composed.normal[pi * 4 + 2] : 255; var shaded; if (typeof Lighting !== "undefined") { shaded = Lighting.shadePaperdollPixel( ar, ag, ab, nr, ng, nb, pxWorld, lights || [], ambient, yaw, npc.facingDeg || 0 ); } else { shaded = { r: Math.min(255, Math.round(composed.lit[pi * 4] * tint)), g: Math.min(255, Math.round(composed.lit[pi * 4 + 1] * tint)), b: Math.min(255, Math.round(composed.lit[pi * 4 + 2] * tint)) }; } data[o] = shaded.r; data[o + 1] = shaded.g; data[o + 2] = shaded.b; data[o + 3] = a; } } } ctx.putImageData(img, 0, 0); var glc = scene.glContext; // Re-upload every frame (content changes). 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 } }); } };