/* * Start File: * /workspace/raytracer-work/src/textureColumn.js */ /** * Texture-column helpers for Wolfenstein-style wall strips. * Each screen column samples exactly one source pixel column. */ function textureColumnIndex (tileX, texWidth) { if (!(texWidth > 0)) { return 0; } var sx = Math.floor(Number(tileX) * texWidth); if (sx < 0) { sx = 0; } if (sx > texWidth - 1) { sx = texWidth - 1; } return sx; } function textureColumnUv (tileX, texWidth) { var sx = textureColumnIndex(tileX, texWidth); var w = texWidth > 0 ? texWidth : 1; return { sx: sx, sw: 1, u0: sx / w, u1: (sx + 1) / w, v0: 0, v1: 1 }; } /** Face U from hit position within a cell (no +1 bias). */ function faceTileX (hitCoord, cellSize, face) { var local = hitCoord % cellSize; if (local < 0) { local += cellSize; } var t = local / cellSize; switch (face) { case "north": return t; case "south": return 1 - t; case "east": return 1 - t; case "west": return t; default: return t; } } if (typeof module !== "undefined" && module.exports) { module.exports = { textureColumnIndex: textureColumnIndex, textureColumnUv: textureColumnUv, faceTileX: faceTileX }; } /* * End File: * /workspace/raytracer-work/src/textureColumn.js */ /* * Start File: * /workspace/raytracer-work/src/ppda/depthDecode.js */ /** * Depth encodings matching Paperdoll Renderer camera::DepthFormat. * Canonical compositor sample is u16 gray + u16 alpha (0..65535). */ var DepthDecode = { EPSILON_U16: 1, parseFormat: function (encoding, bits) { var enc = encoding || "gray"; var b = bits == null ? 16 : Number(bits); if (b !== 8 && b !== 16) { throw new Error("depth_bits moet 8 of 16 zijn, kreeg " + bits); } if (enc !== "gray" && enc !== "rgb_bands" && enc !== "rgb_packed") { throw new Error("depth_encoding onbekend: " + enc); } return { encoding: enc, bits: b }; }, max: function (fmt) { return (1 << fmt.bits) - 1; }, levels: function (fmt) { var m = this.max(fmt); if (fmt.encoding === "gray") { return m; } if (fmt.encoding === "rgb_bands") { return 3 * m; } return Math.pow(2, 3 * fmt.bits) - 1; }, decodeValue: function (fmt, c0, c1, c2) { var m = this.max(fmt); var b = m + 1; var v; if (fmt.encoding === "gray") { v = c0; } else if (fmt.encoding === "rgb_bands") { v = c0 + c1 + c2; } else { v = c0 * b * b + c1 * b + c2; } return v / this.levels(fmt); }, encodeValue: function (fmt, t) { t = Math.max(0, Math.min(1, Number(t) || 0)); var m = this.max(fmt); var v = Math.round(t * this.levels(fmt)); if (fmt.encoding === "gray") { return [v, 0, 0]; } if (fmt.encoding === "rgb_bands") { return [ Math.min(v, m), Math.min(Math.max(v - m, 0), m), Math.min(Math.max(v - 2 * m, 0), m) ]; } var b = m + 1; return [Math.floor(v / (b * b)), Math.floor(v / b) % b, v % b]; }, /** * Decode one pixel channel tuple to canonical u16 (gray, alpha). * channels: [c0,c1,c2,a] in native bit depth units. */ decodePixelChannels: function (fmt, channels) { var c0 = channels[0] || 0; var c1 = channels[1] || 0; var c2 = channels[2] || 0; var a = channels[3] != null ? channels[3] : this.max(fmt); if (fmt.encoding === "rgb_bands") { var m = this.max(fmt); if ((c1 > 0 && c0 !== m) || (c2 > 0 && c1 !== m)) { throw new Error("depth rgb_bands: ongeldige bandvolgorde"); } } var t = this.decodeValue(fmt, c0, c1, c2); var scale = 65535 / this.max(fmt); return { gray: Math.round(t * 65535), alpha: Math.round(a * scale) }; }, /** Meters from camera using near/far and normalized t (0..1 from gray/65535). */ distanceMeters: function (grayU16, near, far) { var t = (grayU16 & 0xffff) / 65535; return near + t * (far - near); } }; if (typeof module !== "undefined" && module.exports) { module.exports = DepthDecode; } /* * End File: * /workspace/raytracer-work/src/ppda/depthDecode.js */ /* * Start File: * /workspace/raytracer-work/src/ppda/viewFrame.js */ /** * Choose paperdoll view (yaw/pitch) and animation frame. * Yaw 0 = character front (Paperdoll/glTF convention). */ var PpdaViewFrame = { /** * Relative viewing yaw in degrees [0,360): direction from NPC to player, * minus the NPC's facing yaw (degrees, 0 = faces +X/east in world… mapped * so that when the player looks at the NPC's front, relative yaw ≈ 0). * * World: +X east, +Y south (legacy raycaster). NPC facingYawDeg: 0 looks * toward +X. Paperdoll yaw 0 is front. We map world facing so that the * camera looking opposite to facing sees front. */ relativeYawDeg: function (playerX, playerY, npcX, npcY, npcFacingDeg) { var dx = playerX - npcX; var dy = playerY - npcY; // Angle of vector NPC→player in world degrees (0=+X, 90=+Y). var toPlayer = Math.atan2(dy, dx) * 180 / Math.PI; if (toPlayer < 0) { toPlayer += 360; } // When player stands in front of NPC, toPlayer ≈ npcFacing. // Paperdoll wants yaw 0 for front → relative = toPlayer - facing. var rel = toPlayer - (npcFacingDeg || 0); rel = ((rel % 360) + 360) % 360; return rel; }, nearestInList: function (value, list, circular360) { if (!list || !list.length) { return 0; } var best = list[0]; var bestD = Infinity; for (var i = 0; i < list.length; i++) { var v = list[i]; var d = Math.abs(value - v); if (circular360) { d = Math.min(d, 360 - d); } if (d < bestD) { bestD = d; best = v; } } return best; }, pickYaw: function (relativeYawDeg, yaws) { return this.nearestInList(((relativeYawDeg % 360) + 360) % 360, yaws || [0], true); }, pickPitch: function (playerPitchRad, pitches) { // player pitch: 0 = horizon; positive looks down in this game. // Paperdoll: positive pitch = from above. Invert sign for mapping. var deg = -(playerPitchRad || 0) * 180 / Math.PI; return this.nearestInList(deg, pitches || [0]); }, frameIndex: function (timeSec, fps, frameCount) { var n = Math.max(1, frameCount | 0); var f = Math.max(1, fps | 0); var idx = Math.floor((timeSec || 0) * f); idx %= n; if (idx < 0) { idx += n; } return idx; }, findClip: function (ppda, clipTokenOrName) { var clips = ppda && ppda.clips || []; for (var i = 0; i < clips.length; i++) { if (clips[i].token === clipTokenOrName || clips[i].name === clipTokenOrName) { return clips[i]; } } return clips[0] || null; }, findView: function (frame, pitch, yaw) { var views = frame && frame.views || []; for (var i = 0; i < views.length; i++) { if (views[i].pitch === pitch && views[i].yaw === yaw) { return views[i]; } } return null; }, uvRect: function (view, atlasW, atlasH) { if (!view) { return { u0: 0, v0: 0, u1: 1, v1: 1, x: 0, y: 0, w: 0, h: 0 }; } var w = atlasW || 1; var h = atlasH || 1; return { x: view.x, y: view.y, w: view.w, h: view.h, u0: view.x / w, v0: view.y / h, u1: (view.x + view.w) / w, v1: (view.y + view.h) / h }; } }; if (typeof module !== "undefined" && module.exports) { module.exports = PpdaViewFrame; } /* * End File: * /workspace/raytracer-work/src/ppda/viewFrame.js */ /* * Start File: * /workspace/raytracer-work/src/ppda/compositor.js */ /** * Live body+equipment compositor — port of compositor.rs compose(). * Per pixel: nearest valid depth wins; ties keep lower layer index (body first). * Valid = depth alpha ≠ 0 AND diffuse alpha ≠ 0. */ var PpdaCompositor = { DEPTH_EPSILON_U16: 1, /** * @param {Array<{width,height,diffuse:Uint8ClampedArray|Uint8Array,depthGray:Uint16Array,depthAlpha:Uint16Array,normal?:Uint8Array,specular?:Uint8Array}>} layers */ compose: function (layers) { if (!layers || !layers.length) { throw new Error("geen lagen om te composeren"); } var width = layers[0].width; var height = layers[0].height; var pixels = width * height; if (!pixels) { throw new Error("lege afmetingen"); } for (var li = 0; li < layers.length; li++) { var L = layers[li]; if (L.width !== width || L.height !== height) { throw new Error("laag " + li + " heeft andere afmetingen"); } if (L.diffuse.length !== pixels * 4 || L.depthGray.length !== pixels || L.depthAlpha.length !== pixels) { throw new Error("laag " + li + " inconsistente buffers"); } } var diffuse = new Uint8ClampedArray(pixels * 4); var normal = new Uint8ClampedArray(pixels * 4); var specular = new Uint8ClampedArray(pixels * 4); var depthGray = new Uint16Array(pixels); var depthAlpha = new Uint16Array(pixels); var winner = new Uint8Array(pixels); for (var i = 0; i < pixels; i++) { winner[i] = 255; } var eps = this.DEPTH_EPSILON_U16; for (var i = 0; i < pixels; i++) { var bestDepth = null; var bestLayer = null; for (var layerIdx = 0; layerIdx < layers.length; layerIdx++) { var layer = layers[layerIdx]; if (layer.depthAlpha[i] === 0 || layer.diffuse[i * 4 + 3] === 0) { continue; } var gray = layer.depthGray[i]; if (bestDepth == null) { bestDepth = gray; bestLayer = layerIdx; } else if (gray + eps < bestDepth) { bestDepth = gray; bestLayer = layerIdx; } else if (gray <= bestDepth + eps) { /* tie: keep lower index */ } } if (bestLayer != null) { var src = layers[bestLayer]; var o = i * 4; diffuse[o] = src.diffuse[o]; diffuse[o + 1] = src.diffuse[o + 1]; diffuse[o + 2] = src.diffuse[o + 2]; diffuse[o + 3] = src.diffuse[o + 3]; if (src.normal) { normal[o] = src.normal[o]; normal[o + 1] = src.normal[o + 1]; normal[o + 2] = src.normal[o + 2]; normal[o + 3] = src.normal[o + 3]; } if (src.specular) { specular[o] = src.specular[o]; specular[o + 1] = src.specular[o + 1]; specular[o + 2] = src.specular[o + 2]; specular[o + 3] = src.specular[o + 3]; } depthGray[i] = src.depthGray[i]; depthAlpha[i] = src.depthAlpha[i]; winner[i] = bestLayer; } } return { width: width, height: height, diffuse: diffuse, normal: normal, specular: specular, depthGray: depthGray, depthAlpha: depthAlpha, winner: winner }; }, /** Simple ambient+Lambert approx for preview (Preview2d-achtig, licht). */ relightDiffuse: function (composed, lightAmt) { lightAmt = lightAmt == null ? 1 : lightAmt; var out = new Uint8ClampedArray(composed.diffuse.length); for (var i = 0; i < composed.diffuse.length; i += 4) { var a = composed.diffuse[i + 3]; if (a === 0) { continue; } var ndot = 0.75; if (composed.normal && composed.normal[i + 3]) { var nx = composed.normal[i] / 255 * 2 - 1; var ny = composed.normal[i + 1] / 255 * 2 - 1; var nz = composed.normal[i + 2] / 255 * 2 - 1; ndot = Math.max(0, nx * 0.3 + ny * 0.2 + nz * 0.9); } var shade = Math.min(1, 0.35 + 0.65 * ndot) * lightAmt; out[i] = Math.min(255, Math.round(composed.diffuse[i] * shade)); out[i + 1] = Math.min(255, Math.round(composed.diffuse[i + 1] * shade)); out[i + 2] = Math.min(255, Math.round(composed.diffuse[i + 2] * shade)); out[i + 3] = a; } return out; } }; if (typeof module !== "undefined" && module.exports) { module.exports = PpdaCompositor; } /* * End File: * /workspace/raytracer-work/src/ppda/compositor.js */ /* * Start File: * /workspace/raytracer-work/src/ppda/loadPpda.js */ /** * Strict-enough .ppda loader for formats 1–5 (Paperdoll AtlasSet consumer). */ var PpdaLoader = { SUPPORTED_FORMATS: [1, 2, 3, 4, 5], parse: function (jsonText, options) { options = options || {}; var doc; try { doc = typeof jsonText === "string" ? JSON.parse(jsonText) : jsonText; } catch (e) { throw new Error("ppda: ongeldige JSON (" + e.message + ")"); } if (!doc || typeof doc !== "object") { throw new Error("ppda: root moet een object zijn"); } var ver = doc.format_version; if (this.SUPPORTED_FORMATS.indexOf(ver) < 0) { throw new Error("ppda: format_version " + ver + " niet ondersteund (wel: " + this.SUPPORTED_FORMATS.join(",") + ")"); } if (!doc.sex || !doc.settype) { throw new Error("ppda: sex/settype verplicht"); } if (!doc.fps || doc.fps < 1) { throw new Error("ppda: fps ongeldig"); } if (!doc.cell_width || !doc.cell_height) { throw new Error("ppda: cell_width/height verplicht"); } if (!Array.isArray(doc.pitches) || !Array.isArray(doc.yaws) || !doc.pitches.length || !doc.yaws.length) { throw new Error("ppda: pitches/yaws verplicht"); } if (!doc.maps || typeof doc.maps !== "object") { throw new Error("ppda: maps verplicht"); } ["diffuse", "depth"].forEach(function (k) { if (!doc.maps[k] || !doc.maps[k].file) { throw new Error("ppda: maps." + k + ".file verplicht"); } if (String(doc.maps[k].file).indexOf("..") >= 0 || String(doc.maps[k].file).indexOf("/") >= 0 || String(doc.maps[k].file).indexOf("\\") >= 0) { throw new Error("ppda: maps." + k + ".file mag geen pad bevatten"); } }); if (!Array.isArray(doc.clips) || !doc.clips.length) { throw new Error("ppda: clips verplicht"); } for (var ci = 0; ci < doc.clips.length; ci++) { var clip = doc.clips[ci]; if (!clip.frames || clip.frames.length !== clip.frame_count) { throw new Error("ppda: clip '" + (clip.name || ci) + "' frames≠frame_count"); } for (var fi = 0; fi < clip.frames.length; fi++) { var fr = clip.frames[fi]; if (!fr.views || !fr.views.length) { throw new Error("ppda: frame zonder views"); } for (var vi = 0; vi < fr.views.length; vi++) { var v = fr.views[vi]; if (v.w == null || v.h == null || v.x == null || v.y == null) { throw new Error("ppda: view mist x/y/w/h"); } } } } var encoding = doc.depth_encoding; var bits = doc.depth_bits; if (!encoding) { // v1 / legacy long text in identity.depth → gray16 encoding = "gray"; bits = bits || 16; } else if (/gray/i.test(encoding) && encoding.indexOf("rgb_") < 0) { encoding = "gray"; } else if (encoding.indexOf("rgb_bands") >= 0) { encoding = "rgb_bands"; } else if (encoding.indexOf("rgb_packed") >= 0) { encoding = "rgb_packed"; } var near = doc.depth_near != null ? doc.depth_near : (doc.identity && doc.identity.near); var far = doc.depth_far != null ? doc.depth_far : (doc.identity && doc.identity.far); if (near == null || far == null) { throw new Error("ppda: depth_near/far of identity.near/far verplicht"); } var fmt = DepthDecode.parseFormat(encoding, bits || 16); return { format_version: ver, sex: doc.sex, settype: doc.settype, fps: doc.fps, cell_width: doc.cell_width, cell_height: doc.cell_height, pitches: doc.pitches.slice(), yaws: doc.yaws.slice(), maps: doc.maps, clips: doc.clips, identity: doc.identity || null, project: doc.project || null, depth_near: Number(near), depth_far: Number(far), depth_format: fmt, camera_distance: doc.identity && doc.identity.camera_distance != null ? Number(doc.identity.camera_distance) : 10, height_milli: doc.identity && doc.identity.framing ? doc.identity.framing.height_milli : 2600, raw: doc }; }, compatKey: function (ppda) { var id = ppda.identity || {}; return { sex: ppda.sex, body_model_sha256: id.body_model_sha256 || "", fps: ppda.fps, cell_width: ppda.cell_width, cell_height: ppda.cell_height, pitches: ppda.pitches.join(","), yaws: ppda.yaws.join(","), near: ppda.depth_near, far: ppda.depth_far }; }, assertCompatible: function (a, b) { var ka = this.compatKey(a); var kb = this.compatKey(b); var keys = Object.keys(ka); for (var i = 0; i < keys.length; i++) { var k = keys[i]; if (String(ka[k]) !== String(kb[k])) { throw new Error("ppda incompatible: " + k + " (" + ka[k] + " vs " + kb[k] + ")"); } } } }; if (typeof module !== "undefined" && module.exports) { module.exports = PpdaLoader; } /* * End File: * /workspace/raytracer-work/src/ppda/loadPpda.js */ /* * Start File: * /workspace/raytracer-work/src/ppda/atlasRuntime.js */ /** * Browser/runtime atlas set: loads PNG diffuse/normal/specular + u16 depth, * extracts cells, composes body+gear on CPU (cell is 32×48 — cheap). */ var PpdaAtlasRuntime = { _canvas: null, _ctx: null, _ensureCanvas: function () { if (typeof document === "undefined") { return null; } if (!this._canvas) { this._canvas = document.createElement("canvas"); this._ctx = this._canvas.getContext("2d", { willReadFrequently: true }); } return this._ctx; }, loadImage: function (url) { return new Promise(function (resolve, reject) { var img = new Image(); img.onload = function () { resolve(img); }; img.onerror = function () { reject(new Error("image load failed: " + url)); }; img.src = url; }); }, loadU16Depth: function (url, expectW, expectH) { return fetch(url).then(function (r) { if (!r.ok) { throw new Error("depth fetch " + r.status + " " + url); } return r.arrayBuffer(); }).then(function (buf) { var need = expectW * expectH * 4; if (buf.byteLength < need) { throw new Error("depth u16 te kort: " + buf.byteLength + " < " + need); } return new Uint16Array(buf.slice(0, need)); }); }, /** * @returns {Promise<{ppda, images, depthU16, baseUrl}>} */ loadSet: function (baseUrl, ppdaFile) { var self = this; baseUrl = baseUrl.replace(/\/?$/, "/"); return fetch(baseUrl + ppdaFile).then(function (r) { if (!r.ok) { throw new Error("ppda fetch " + r.status); } return r.text(); }).then(function (text) { var ppda = PpdaLoader.parse(text); var maps = ppda.maps; var jobs = [ self.loadImage(baseUrl + maps.diffuse.file), maps.normal ? self.loadImage(baseUrl + maps.normal.file) : Promise.resolve(null), maps.specular ? self.loadImage(baseUrl + maps.specular.file) : Promise.resolve(null) ]; var depthFile = maps.depth.file; var dw = maps.depth.width || maps.diffuse.width; var dh = maps.depth.height || maps.diffuse.height; if (maps.depth.storage === "u16le_ga" || /\.u16$/i.test(depthFile)) { jobs.push(self.loadU16Depth(baseUrl + depthFile, dw, dh)); } else { throw new Error("browser-loader verwacht depth als .u16 (storage=u16le_ga); got " + depthFile); } return Promise.all(jobs).then(function (parts) { return { ppda: ppda, baseUrl: baseUrl, diffuseImg: parts[0], normalImg: parts[1], specularImg: parts[2], depthU16: parts[3], depthW: dw, depthH: dh }; }); }); }, extractRgbaCell: function (img, view) { var ctx = this._ensureCanvas(); if (!ctx) { throw new Error("geen canvas voor cell extract"); } this._canvas.width = view.w; this._canvas.height = view.h; ctx.clearRect(0, 0, view.w, view.h); ctx.drawImage(img, view.x, view.y, view.w, view.h, 0, 0, view.w, view.h); return ctx.getImageData(0, 0, view.w, view.h).data; }, extractDepthCell: function (depthU16, atlasW, view) { var n = view.w * view.h; var gray = new Uint16Array(n); var alpha = new Uint16Array(n); for (var y = 0; y < view.h; y++) { for (var x = 0; x < view.w; x++) { var si = ((view.y + y) * atlasW + (view.x + x)) * 2; var di = y * view.w + x; gray[di] = depthU16[si]; alpha[di] = depthU16[si + 1]; } } return { depthGray: gray, depthAlpha: alpha }; }, layerFromSet: function (set, clipToken, frameIndex, pitch, yaw) { var clip = PpdaViewFrame.findClip(set.ppda, clipToken); if (!clip) { throw new Error("clip niet gevonden: " + clipToken); } var frame = clip.frames[frameIndex]; if (!frame) { throw new Error("frame " + frameIndex + " ontbreekt"); } var view = PpdaViewFrame.findView(frame, pitch, yaw); if (!view) { throw new Error("view p" + pitch + " y" + yaw + " ontbreekt"); } if (view.empty) { var emptyN = view.w * view.h; return { width: view.w, height: view.h, diffuse: new Uint8ClampedArray(emptyN * 4), normal: new Uint8ClampedArray(emptyN * 4), specular: new Uint8ClampedArray(emptyN * 4), depthGray: new Uint16Array(emptyN), depthAlpha: new Uint16Array(emptyN), view: view }; } var diffuse = this.extractRgbaCell(set.diffuseImg, view); var normal = set.normalImg ? this.extractRgbaCell(set.normalImg, view) : null; var specular = set.specularImg ? this.extractRgbaCell(set.specularImg, view) : null; var depth = this.extractDepthCell(set.depthU16, set.depthW, view); return { width: view.w, height: view.h, diffuse: diffuse, normal: normal, specular: specular, depthGray: depth.depthGray, depthAlpha: depth.depthAlpha, view: view }; }, composeView: function (bodySet, gearSet, clipToken, frameIndex, pitch, yaw) { var body = this.layerFromSet(bodySet, clipToken, frameIndex, pitch, yaw); var layers = [body]; if (gearSet) { PpdaLoader.assertCompatible(bodySet.ppda, gearSet.ppda); layers.push(this.layerFromSet(gearSet, clipToken, frameIndex, pitch, yaw)); } var composed = PpdaCompositor.compose(layers); composed.view = body.view; composed.lit = PpdaCompositor.relightDiffuse(composed, 1); return composed; } }; if (typeof module !== "undefined" && module.exports) { module.exports = PpdaAtlasRuntime; } /* * End File: * /workspace/raytracer-work/src/ppda/atlasRuntime.js */ /* * Start File: * /workspace/raytracer-work/src/levels.js */ var Levels = [ { name: "Level 1", width: 10, height: 10, spawnX: 1, spawnY: 1, tiles: [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 3, 3, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 2, 1, 0, 1, 1, 0, 1, 0, 0, 1, 3, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] } ]; /* * End File: * /workspace/raytracer-work/src/levels.js */ /* * Start File: * /workspace/raytracer-work/src/tiles.js */ /** Tile table; Image fields filled after preload. */ var Tiles = { Nothing: { ID: 0, Color: { R: 255, G: 255, B: 255 }, Solid: false, ImageName: null }, Stone: { ID: 1, Color: { R: 155, G: 155, B: 155 }, Solid: true, ImageName: "stone" }, Finish: { ID: 2, Color: { R: 255, G: 255, B: 0 }, Solid: false, ImageName: null }, Wood: { ID: 3, Color: { R: 168, G: 102, B: 50 }, Solid: true, ImageName: "wood" }, findByID: function (id) { for (var key in Tiles) { if (!Object.prototype.hasOwnProperty.call(Tiles, key)) { continue; } var value = Tiles[key]; if (value && value.ID === id) { return value; } } return null; }, bindImages: function (images) { for (var key in Tiles) { if (!Object.prototype.hasOwnProperty.call(Tiles, key)) { continue; } var tile = Tiles[key]; if (tile && tile.ImageName && images[tile.ImageName]) { tile.Image = images[tile.ImageName]; } } } }; /* * End File: * /workspace/raytracer-work/src/tiles.js */ /* * Start File: * /workspace/raytracer-work/src/world.js */ var World = { size: 32, level: null, loadLevel: function (index) { this.level = Levels[index]; }, spawnPoint: function () { return { x: this.level.spawnX * this.size + this.size / 2, y: this.level.spawnY * this.size + this.size / 2 }; }, rayCast: function (x, y, radian) { var maxDist = this.level.width + this.level.height; var cell = this.size; var tileXpercentage = 0; var tileXp = 0; var tileYp = 0; // --- horizontal grid lines --- var hrayX, hrayY, hoffX, hoffY, distDone, hmapX, hmapY, htileHit; var hDir = "north"; distDone = 0; var aTan = -1 / Math.tan(radian); if (radian > Math.PI) { hrayY = Math.floor(y / cell) * cell - 0.01; hrayX = (y - hrayY) * aTan + x; hoffY = -cell; hoffX = -hoffY * aTan; } else if (radian < Math.PI) { hrayY = Math.floor(y / cell) * cell + cell; hrayX = (y - hrayY) * aTan + x; hoffY = cell; hoffX = -hoffY * aTan; hDir = "south"; } else { hrayX = x; hrayY = y; distDone = maxDist; } while (distDone < maxDist) { tileXp = ((hrayX % cell) + cell) % cell / cell; tileYp = ((hrayY % cell) + cell) % cell / cell; hmapX = Math.floor(hrayX / cell); hmapY = Math.floor(hrayY / cell); var htileHitId = this.level.tiles[hmapX + hmapY * this.level.width]; htileHit = Tiles.findByID(htileHitId); if (htileHit && htileHit.Solid) { distDone = maxDist; } else { hrayX += hoffX; hrayY += hoffY; distDone += 1; } } switch (hDir) { case "north": tileXpercentage = tileXp; break; case "south": tileXpercentage = 1 - tileXp; break; case "east": tileXpercentage = 1 - tileYp; break; case "west": tileXpercentage = tileYp; break; } var hResult = { tile: htileHit, tileX: tileXpercentage, endX: hrayX, endY: hrayY, dir: hDir }; // --- vertical grid lines --- var rayX, rayY, offX, offY, mapX, mapY, tileHit; var vDir = "east"; var nTan = -Math.tan(radian); distDone = 0; if (radian > Math.PI / 2 && radian < Math.PI * 1.5) { rayX = Math.floor(x / cell) * cell - 0.01; rayY = (x - rayX) * nTan + y; offX = -cell; offY = -offX * nTan; } else if (radian < Math.PI / 2 || radian > Math.PI * 1.5) { rayX = Math.floor(x / cell) * cell + cell; rayY = (x - rayX) * nTan + y; offX = cell; offY = -offX * nTan; vDir = "west"; } else { rayX = x; rayY = y; distDone = maxDist; } while (distDone < maxDist) { tileXp = ((rayX % cell) + cell) % cell / cell; tileYp = ((rayY % cell) + cell) % cell / cell; mapX = Math.floor(rayX / cell); mapY = Math.floor(rayY / cell); var tileHitId = this.level.tiles[mapX + mapY * this.level.width]; tileHit = Tiles.findByID(tileHitId); if (tileHit && tileHit.Solid) { distDone = maxDist; } else { rayX += offX; rayY += offY; distDone += 1; } } switch (vDir) { case "north": tileXpercentage = tileXp; break; case "south": tileXpercentage = 1 - tileXp; break; case "east": tileXpercentage = 1 - tileYp; break; case "west": tileXpercentage = tileYp; break; } var vResult = { tile: tileHit, tileX: tileXpercentage, endX: rayX, endY: rayY, dir: vDir }; var dxH = hResult.endX - x; var dyH = hResult.endY - y; var dxV = vResult.endX - x; var dyV = vResult.endY - y; hResult.distance = Math.sqrt(dxH * dxH + dyH * dyH); vResult.distance = Math.sqrt(dxV * dxV + dyV * dyV); if (hResult.distance < vResult.distance) { return hResult; } return vResult; } }; if (typeof module !== "undefined" && module.exports) { module.exports = { World: World }; } /* * End File: * /workspace/raytracer-work/src/world.js */ /* * Start File: * /workspace/raytracer-work/src/player.js */ var Player = { x: 0, y: 0, rotation: 0, pitch: 0, /** Screen columns per frame. 240 is sharp on ~1080p and cheap (~240 drawSprite calls). */ horizontalResolution: 240, gunX: 0.6, gunY: 0.6, currentGun: 0, guns: 3, resetToSpawn: function () { var spawn = World.spawnPoint(); this.x = spawn.x; this.y = spawn.y; this.rotation = 0; this.pitch = 0; }, applyLookDelta: function (movementX, movementY) { this.pitch += movementY * 0.01; this.rotation += movementX * 0.001; if (this.pitch > Math.PI) { this.pitch = Math.PI; } if (this.pitch < -Math.PI) { this.pitch = -Math.PI; } if (this.rotation > Math.PI * 2) { this.rotation -= Math.PI * 2; } if (this.rotation < 0) { this.rotation += Math.PI * 2; } }, /** Legacy angles: 0 = +X (east), increases toward +Y. */ forwardVector: function (radian) { return { x: Math.cos(radian), y: Math.sin(radian) }; }, tryMove: function (rot, speed, deltaTime) { if (World.rayCast(this.x, this.y, rot).distance <= 5) { return; } var forward = this.forwardVector(rot); this.x += forward.x * deltaTime * speed; this.y += forward.y * deltaTime * speed; }, update: function (deltaTime) { if (GameInput.isHeld(37) || GameInput.isHeld(65)) { var rotL = this.rotation - Math.PI / 2; if (rotL < 0) { rotL += Math.PI * 2; } this.tryMove(rotL, 60, deltaTime); } if (GameInput.isHeld(39) || GameInput.isHeld(68)) { var rotR = this.rotation + Math.PI / 2; if (rotR > Math.PI * 2) { rotR -= Math.PI * 2; } this.tryMove(rotR, 60, deltaTime); } if (GameInput.isHeld(38) || GameInput.isHeld(87)) { this.tryMove(this.rotation, 60, deltaTime); } if (GameInput.isHeld(40) || GameInput.isHeld(83)) { var rotB = this.rotation + Math.PI; if (rotB > Math.PI * 2) { rotB -= Math.PI * 2; } if (World.rayCast(this.x, this.y, rotB).distance > 5) { var forward = this.forwardVector(this.rotation); this.x -= forward.x * deltaTime * 40; this.y -= forward.y * deltaTime * 40; } } if (GameInput.isHeld(188)) { this.horizontalResolution -= this.horizontalResolution * 0.1 * deltaTime; if (this.horizontalResolution < 30) { this.horizontalResolution = 30; } } if (GameInput.isHeld(190)) { this.horizontalResolution += this.horizontalResolution * 0.1 * deltaTime; } } }; /* * End File: * /workspace/raytracer-work/src/player.js */ /* * Start File: * /workspace/raytracer-work/src/npc.js */ /** * 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 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); var screenY = h / 2 + (-player.pitch * h * 0.25); var left = screenX - spriteW / 2; var top = screenY - spriteH / 2; 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.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] = Math.min(255, Math.round(composed.lit[pi * 4] * tint)); data[o + 1] = Math.min(255, Math.round(composed.lit[pi * 4 + 1] * tint)); data[o + 2] = Math.min(255, Math.round(composed.lit[pi * 4 + 2] * tint)); 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 } }); } }; /* * End File: * /workspace/raytracer-work/src/npc.js */ /* * Start File: * /workspace/raytracer-work/src/raycastScene.js */ /** * Fullscreen WebGL raycast view on frameworkv3. * Wall strips: one source texel column per screen column, NEAREST, tinted for shading. */ class RaycastScene extends Scene { constructor (width, height) { super(0, 0, width, height, Scene.DisplayModes.absolute); this.backgroundColor = { r: 0, g: 0, b: 0 }; this.tintShader = null; this.solidTexture = null; this.gunImages = null; this._lookBound = false; } onLoad () { const gl = this.glContext.gl; this.glContext.setDefaultTextureFilter(gl.NEAREST, gl.NEAREST); this.tintShader = new Shader(Shader.DEFAULT_VERT, [ "precision mediump float;", "uniform sampler2D u_texture;", "uniform float u_alpha;", "uniform vec3 u_tint;", "varying vec2 v_texCoord;", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " gl_FragColor = vec4(color.rgb * u_tint, color.a * u_alpha);", "}" ].join("\n")); // 1x1 white for solid (untextured) walls. const c = document.createElement("canvas"); c.width = 1; c.height = 1; const ctx = c.getContext("2d"); ctx.fillStyle = "#ffffff"; ctx.fillRect(0, 0, 1, 1); this.solidTexture = this.glContext.getTexture(c); this.bindPointerLock(); } bindPointerLock () { if (this._lookBound) { return; } this._lookBound = true; const canvas = this.cv_canvas; canvas.addEventListener("click", function () { if (canvas.requestPointerLock) { canvas.requestPointerLock(); } }); document.addEventListener("mousemove", function (e) { if (document.pointerLockElement === canvas) { Player.applyLookDelta(e.movementX || 0, e.movementY || 0); } }); } update (deltaTime) { super.update(deltaTime); Player.update(deltaTime); if (typeof NpcSystem !== "undefined") { NpcSystem.update(deltaTime); } if (Player.horizontalResolution > this.real_size.x) { Player.horizontalResolution = this.real_size.x; } } draw () { if (this.destroyed || !this.glContext) { return; } this.g_fixSize(); const glc = this.glContext; glc.endOffscreenPass(); glc.clear(0, 0, 0, 1); const wallDepth = this.drawColumns(); if (typeof NpcSystem !== "undefined" && NpcSystem.ready) { NpcSystem.draw(this, Player, wallDepth); } this.drawGun(); } faceLight (dir) { switch (dir) { case "east": return 0.9; case "west": return 0.8; case "south": return 0.7; default: return 1.0; } } drawColumns () { const glc = this.glContext; const w = this.real_size.x; const h = this.real_size.y; const cols = Math.max(1, Math.floor(Player.horizontalResolution)); const rad = Math.PI / (cols * 2); const widthLine = w / cols; const wallDepth = new Float32Array(Math.max(1, Math.round(w))); for (var zi = 0; zi < wallDepth.length; zi++) { wallDepth[zi] = 1e9; } for (var i = 0; i < cols; i++) { var offsetP = -0.5 + (i / cols); var offset = offsetP * cols; var rotationalOffset = offset * rad; var rot = Player.rotation + rotationalOffset; if (rot < 0) { rot += Math.PI * 2; } if (rot > Math.PI * 2) { rot -= Math.PI * 2; } var rayHit = World.rayCast(Player.x, Player.y, rot); if (!rayHit || !rayHit.tile) { continue; } var light = this.faceLight(rayHit.dir); var deltaAngle = Player.rotation - rot; var dist = rayHit.distance * Math.cos(deltaAngle); if (dist < 0.0001) { dist = 0.0001; } var xLine = i * widthLine; var wallH = (World.size * h) / dist; var yCenter = (h / 2) + (-Player.pitch * (World.size * h - wallH) * 0.005); var tint = [light, light, light]; var htmlImage = null; var texW = 1; // Z-buffer for NPC occlusion (per screen pixel column). var x0 = Math.max(0, Math.floor(xLine)); var x1 = Math.min(wallDepth.length, Math.ceil(xLine + widthLine)); for (var xz = x0; xz < x1; xz++) { if (dist < wallDepth[xz]) { wallDepth[xz] = dist; } } if (rayHit.tile.Image && rayHit.tile.Image.g_image) { htmlImage = rayHit.tile.Image.g_image; texW = htmlImage.width || 1; var uv = textureColumnUv(rayHit.tileX, texW); glc.drawSprite({ texture: glc.getTexture(htmlImage), x: xLine + widthLine / 2, y: yCenter, w: widthLine, h: wallH, rotationDeg: 0, alpha: 1, uvRect: { u0: uv.u0, v0: uv.v0, u1: uv.u1, v1: uv.v1 }, shader: this.tintShader, uniforms: { u_tint: tint } }); } else { var c = rayHit.tile.Color || { R: 255, G: 255, B: 255 }; tint = [(c.R / 255) * light, (c.G / 255) * light, (c.B / 255) * light]; glc.drawSprite({ texture: this.solidTexture, x: xLine + widthLine / 2, y: yCenter, w: widthLine, h: wallH, rotationDeg: 0, alpha: 1, uvRect: { u0: 0, v0: 0, u1: 1, v1: 1 }, shader: this.tintShader, uniforms: { u_tint: tint } }); } } return wallDepth; } drawGun () { const images = this.game && this.game.images; if (!images) { return; } var gunImg = null; switch (Player.currentGun) { case 0: gunImg = images.shotgun; break; case 1: gunImg = images.machinegun; break; case 2: gunImg = images.pulserifle; break; } if (!gunImg || !gunImg.g_image) { return; } var p = this.real_size.y / 1080; var gw = p * gunImg.g_image.width; var gh = p * gunImg.g_image.height; var gx = this.real_size.x * Player.gunX + gw / 2; var gy = this.real_size.y * Player.gunY + gh / 2; gunImg.draw( this, gx, gy, gw, gh, 0, false, false, 1, 0 ); } } /* * End File: * /workspace/raytracer-work/src/raycastScene.js */ /* * Start File: * /workspace/raytracer-work/src/main.js */ console.log("Raytracer (frameworkv3 + paperdolls) starting"); var game = new Game(); window.onload = function () { game.preloadImagesThenStart( [ { name: "stone", url: "images/stone.png" }, { name: "wood", url: "images/wood.png" }, { name: "shotgun", url: "images/shotgun.png" }, { name: "machinegun", url: "images/machinegun.png" }, { name: "pulserifle", url: "images/pulserifle.png" } ], function () { Tiles.bindImages(game.images); World.loadLevel(0); Player.resetToSpawn(); var w = Math.max(320, window.innerWidth - 2); var h = Math.max(240, window.innerHeight - 2); var scene = new RaycastScene(w, h); scene.npcLight = 1; game.loadScene(scene); NpcSystem.initEmpty(); NpcSystem.addNpc({ x: 48 + 64, y: 48, facingDeg: 180, clip: "walk", animating: true, label: "walker" }); NpcSystem.addNpc({ x: 48 + 128, y: 48 + 96, facingDeg: 90, clip: "walk", animating: false, time: 0.25, label: "guard" }); NpcSystem.addNpc({ x: 48 + 32, y: 48 + 160, facingDeg: 0, clip: "attack", animating: true, label: "attacker" }); NpcSystem.addNpc({ x: 200, y: 100, facingDeg: 270, clip: "walk", animating: true, label: "side" }); NpcSystem.load( "paperdolls/male-body/", "male-body-atlas.ppda", "paperdolls/male-sword/", "male-sword-atlas.ppda" ).then(function () { console.log("Paperdolls loaded (body + sword)"); }).catch(function (err) { console.error("Paperdoll load failed", err); }); window.addEventListener("resize", function () { scene.size.x = Math.max(320, window.innerWidth - 2); scene.size.y = Math.max(240, window.innerHeight - 2); }); } ); }; /* * End File: * /workspace/raytracer-work/src/main.js */