// 手写 WebGL 渲染器:地图(按材质合批)、玩家模型、第一人称枪模型、 // 曳光弹、粒子、假投影、黄昏天空。不引第三方库,贴图全部现场生成。 const TILE = 2.0; // 一个贴图平铺多少米 /* ------------------------------ 矩阵工具(列主序) ------------------------------ */ export function mat4() { const m = new Float32Array(16); m[0] = m[5] = m[10] = m[15] = 1; return m; } export function mul(a, b) { const o = new Float32Array(16); for (let c = 0; c < 4; c++) { for (let r = 0; r < 4; r++) { o[c * 4 + r] = a[r] * b[c * 4] + a[4 + r] * b[c * 4 + 1] + a[8 + r] * b[c * 4 + 2] + a[12 + r] * b[c * 4 + 3]; } } return o; } export function translate(x, y, z) { const m = mat4(); m[12] = x; m[13] = y; m[14] = z; return m; } export function scale(x, y, z) { const m = mat4(); m[0] = x; m[5] = y; m[10] = z; return m; } export function rotX(a) { const m = mat4(); const c = Math.cos(a); const s = Math.sin(a); m[5] = c; m[6] = s; m[9] = -s; m[10] = c; return m; } export function rotY(a) { const m = mat4(); const c = Math.cos(a); const s = Math.sin(a); m[0] = c; m[2] = -s; m[8] = s; m[10] = c; return m; } export function perspective(fovy, aspect, near, far) { const m = new Float32Array(16); const f = 1 / Math.tan(fovy / 2); const nf = 1 / (near - far); m[0] = f / aspect; m[5] = f; m[10] = (far + near) * nf; m[11] = -1; m[14] = 2 * far * near * nf; return m; } export function rotZ(a) { const m = mat4(); const c = Math.cos(a); const s = Math.sin(a); m[0] = c; m[1] = s; m[4] = -s; m[5] = c; return m; } function mat3Identity() { return new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]); } /** 只带偏航的旋转法线矩阵(模型都是绕 Y 转的方块) */ function yawNormalMat(yaw) { const c = Math.cos(-yaw); const s = Math.sin(-yaw); return new Float32Array([c, 0, -s, 0, 1, 0, s, 0, c]); } function hexToRgb(hex) { const n = parseInt(hex.slice(1), 16); return [(n >> 16) & 255, (n >> 8) & 255, n & 255]; } /* --------------------------------- 贴图生成 --------------------------------- */ function canvasTex(size) { const c = document.createElement("canvas"); c.width = c.height = size; return c; } function noiseFill(g, size, base, spread) { const img = g.getImageData(0, 0, size, size); const d = img.data; for (let i = 0; i < d.length; i += 4) { const n = (Math.random() - 0.5) * spread; d[i] = Math.max(0, Math.min(255, base[0] + n)); d[i + 1] = Math.max(0, Math.min(255, base[1] + n)); d[i + 2] = Math.max(0, Math.min(255, base[2] + n)); d[i + 3] = 255; } g.putImageData(img, 0, 0); } function paintConcrete(g, s) { noiseFill(g, s, [140, 133, 118], 24); g.globalAlpha = 0.42; g.strokeStyle = "#5d5648"; g.lineWidth = 2; for (let y = 0; y <= s; y += 64) { g.beginPath(); g.moveTo(0, y); g.lineTo(s, y); g.stroke(); } for (let y = 0; y < s; y += 64) { const off = (y / 64) % 2 ? 64 : 32; for (let x = 0; x <= s; x += 128) { g.beginPath(); g.moveTo(x + off, y); g.lineTo(x + off, y + 64); g.stroke(); } } g.globalAlpha = 0.1; for (let i = 0; i < 14; i++) { const x = Math.random() * s; const y = Math.random() * s; const r = 10 + Math.random() * 34; const grd = g.createRadialGradient(x, y, 0, x, y, r); grd.addColorStop(0, "#3b3427"); grd.addColorStop(1, "rgba(59,52,39,0)"); g.fillStyle = grd; g.fillRect(0, 0, s, s); } g.globalAlpha = 1; } function paintWood(g, s) { noiseFill(g, s, [126, 92, 58], 16); const plank = 42; for (let y = 0; y < s; y += plank) { g.globalAlpha = 0.34; g.fillStyle = "#4d351f"; g.fillRect(0, y, s, 2); g.globalAlpha = 0.12; g.fillStyle = "#e0b483"; g.fillRect(0, y + 3, s, 2); g.globalAlpha = 0.14; g.strokeStyle = "#3a2513"; g.lineWidth = 1; for (let k = 0; k < 7; k++) { const yy = y + 5 + Math.random() * (plank - 10); g.beginPath(); g.moveTo(0, yy); for (let x = 0; x <= s; x += 24) { g.lineTo(x, yy + Math.sin(x * 0.07 + k) * 1.6); } g.stroke(); } } g.globalAlpha = 0.5; g.fillStyle = "#2e2a24"; for (let y = 12; y < s; y += plank) { for (let x = 14; x < s; x += 96) { g.beginPath(); g.arc(x, y, 2, 0, Math.PI * 2); g.fill(); } } g.globalAlpha = 1; } function paintMetal(g, s) { noiseFill(g, s, [76, 86, 98], 12); g.globalAlpha = 0.26; g.strokeStyle = "#2a323b"; g.lineWidth = 3; for (let x = 0; x <= s; x += 85) { g.beginPath(); g.moveTo(x, 0); g.lineTo(x, s); g.stroke(); } g.globalAlpha = 0.5; for (let y = 16; y < s; y += 42) { for (let x = 16; x < s; x += 42) { g.fillStyle = "#9fb0c0"; g.beginPath(); g.arc(x, y, 2.2, 0, Math.PI * 2); g.fill(); } } g.globalAlpha = 0.14; for (let i = 0; i < 16; i++) { g.fillStyle = "#7a4a26"; g.fillRect(Math.random() * s, Math.random() * s, 2 + Math.random() * 4, 20 + Math.random() * 60); } g.globalAlpha = 1; } function paintFloor(g, s) { noiseFill(g, s, [106, 102, 92], 18); g.globalAlpha = 0.42; g.strokeStyle = "#57534a"; g.lineWidth = 3; for (let i = 0; i <= s; i += 64) { g.beginPath(); g.moveTo(i, 0); g.lineTo(i, s); g.stroke(); g.beginPath(); g.moveTo(0, i); g.lineTo(s, i); g.stroke(); } g.globalAlpha = 0.1; for (let i = 0; i < 26; i++) { g.fillStyle = "#c8c2b0"; g.fillRect(Math.random() * s, Math.random() * s, 3 + Math.random() * 9, 1 + Math.random() * 3); } g.globalAlpha = 1; } function radialShadow(g, s) { const grd = g.createRadialGradient(s / 2, s / 2, 0, s / 2, s / 2, s / 2); grd.addColorStop(0, "rgba(0,0,0,0.9)"); grd.addColorStop(0.5, "rgba(0,0,0,0.55)"); grd.addColorStop(1, "rgba(0,0,0,0)"); g.fillStyle = grd; g.fillRect(0, 0, s, s); } /* --------------------------------- 着色器 --------------------------------- */ const WORLD_VS = ` attribute vec3 aPos; attribute vec3 aNormal; attribute vec2 aUV; uniform mat4 uProj, uView, uModel; uniform mat3 uNormalMat; varying vec3 vNormal; varying vec2 vUV; varying vec3 vWorld; void main() { vec4 wp = uModel * vec4(aPos, 1.0); vWorld = wp.xyz; vNormal = uNormalMat * aNormal; vUV = aUV; gl_Position = uProj * uView * wp; }`; const WORLD_FS = ` precision mediump float; uniform sampler2D uTex; uniform vec3 uTint; uniform vec3 uLightDir; uniform vec3 uLightColor; uniform vec3 uFillDir; uniform vec3 uFillColor; uniform vec3 uAmbient; uniform vec3 uFogColor; uniform vec3 uCamPos; uniform float uFogNear, uFogFar; uniform float uEmissive; varying vec3 vNormal; varying vec2 vUV; varying vec3 vWorld; void main() { vec3 base = texture2D(uTex, vUV).rgb * uTint; vec3 n = normalize(vNormal); float diff = max(dot(n, uLightDir), 0.0); float fill = max(dot(n, uFillDir), 0.0); float hemi = 0.55 + 0.45 * n.y; vec3 light = uAmbient * hemi + uLightColor * diff + uFillColor * fill; vec3 col = base * (light + uEmissive); float f = smoothstep(uFogNear, uFogFar, length(vWorld - uCamPos)); gl_FragColor = vec4(mix(col, uFogColor, f), 1.0); }`; const SKY_VS = ` attribute vec3 aPos; uniform mat4 uProj, uView; uniform vec3 uCam; varying vec3 vDir; void main() { vDir = aPos; gl_Position = uProj * uView * vec4(aPos * 400.0 + uCam, 1.0); }`; const SKY_FS = ` precision mediump float; uniform vec3 uHorizon, uZenith, uSunColor, uSunDir; varying vec3 vDir; void main() { vec3 d = normalize(vDir); float h = clamp(d.y * 0.5 + 0.5, 0.0, 1.0); vec3 col = mix(uHorizon, uZenith, smoothstep(0.42, 0.95, h)); float sun = pow(max(dot(d, uSunDir), 0.0), 24.0); col += uSunColor * sun * 0.5; gl_FragColor = vec4(col, 1.0); }`; const FLAT_VS = ` attribute vec3 aPos; attribute vec2 aUV; uniform mat4 uProj, uView, uModel; varying vec2 vUV; void main() { vUV = aUV; gl_Position = uProj * uView * uModel * vec4(aPos, 1.0); }`; const FLAT_FS = ` precision mediump float; uniform sampler2D uTex; uniform vec3 uTint; uniform float uAlpha; varying vec2 vUV; void main() { float a = texture2D(uTex, vUV).a * uAlpha; if (a < 0.004) discard; gl_FragColor = vec4(uTint, a); }`; const PARTICLE_VS = ` attribute vec3 aPos; attribute float aSize; attribute vec4 aColor; uniform mat4 uProj, uView; uniform float uScale; varying vec4 vColor; void main() { vec4 vp = uView * vec4(aPos, 1.0); gl_Position = uProj * vp; gl_PointSize = clamp(aSize * uScale / max(-vp.z, 0.15), 1.0, 80.0); vColor = aColor; }`; const PARTICLE_FS = ` precision mediump float; varying vec4 vColor; void main() { vec2 c = gl_PointCoord - 0.5; float d = length(c); if (d > 0.5) discard; gl_FragColor = vec4(vColor.rgb, vColor.a * smoothstep(0.5, 0.06, d)); }`; const LINE_VS = ` attribute vec3 aPos; uniform mat4 uProj, uView; void main() { gl_Position = uProj * uView * vec4(aPos, 1.0); }`; const LINE_FS = ` precision mediump float; uniform vec3 uColor; uniform float uAlpha; void main() { gl_FragColor = vec4(uColor, uAlpha); }`; /* --------------------------------- 几何 --------------------------------- */ const FACES = [ [0, 1], [0, -1], [1, 1], [1, -1], [2, 1], [2, -1], ]; function buildCube() { const pos = []; const nor = []; const uv = []; const idx = []; let n = 0; for (const [axis, sign] of FACES) { const u = (axis + 1) % 3; const v = (axis + 2) % 3; const corners = [ [0, 0], [1, 0], [1, 1], [0, 1], ]; for (const [cu, cv] of corners) { const p = [0, 0, 0]; p[axis] = sign > 0 ? 0.5 : -0.5; p[u] = cu - 0.5; p[v] = cv - 0.5; pos.push(p[0], p[1], p[2]); const nn = [0, 0, 0]; nn[axis] = sign; nor.push(nn[0], nn[1], nn[2]); uv.push(cu, cv); } if (sign > 0) idx.push(n, n + 1, n + 2, n, n + 2, n + 3); else idx.push(n, n + 2, n + 1, n, n + 3, n + 2); n += 4; } return { positions: new Float32Array(pos), normals: new Float32Array(nor), uvs: new Float32Array(uv), indices: new Uint16Array(idx), count: idx.length, }; } /* --------------------------------- 渲染器 --------------------------------- */ export class Renderer { constructor(canvas) { this.canvas = canvas; const opts = { antialias: true, alpha: false, depth: true, powerPreference: "high-performance" }; this.gl = canvas.getContext("webgl2", opts) || canvas.getContext("webgl", opts); if (!this.gl) throw new Error("这台设备不支持 WebGL"); const gl = this.gl; this.level = null; this.matBuffers = []; this.shadowQuads = []; this.cube = buildCube(); const coarse = window.matchMedia && window.matchMedia("(pointer: coarse)").matches; this.dpr = Math.min(window.devicePixelRatio || 1, coarse ? 1.3 : 2); this.progWorld = this.program(WORLD_VS, WORLD_FS); this.progSky = this.program(SKY_VS, SKY_FS); this.progFlat = this.program(FLAT_VS, FLAT_FS); this.progParticle = this.program(PARTICLE_VS, PARTICLE_FS); this.progLine = this.program(LINE_VS, LINE_FS); this.world = this.locations(this.progWorld, [ "aPos", "aNormal", "aUV", "uProj", "uView", "uModel", "uNormalMat", "uTex", "uTint", "uLightDir", "uLightColor", "uFillDir", "uFillColor", "uAmbient", "uFogColor", "uCamPos", "uFogNear", "uFogFar", "uEmissive", ]); this.sky = this.locations(this.progSky, ["aPos", "uProj", "uView", "uCam", "uHorizon", "uZenith", "uSunColor", "uSunDir"]); this.flat = this.locations(this.progFlat, ["aPos", "aUV", "uProj", "uView", "uModel", "uTex", "uTint", "uAlpha"]); this.particle = this.locations(this.progParticle, ["aPos", "aSize", "aColor", "uProj", "uView", "uScale"]); this.line = this.locations(this.progLine, ["aPos", "uProj", "uView", "uColor", "uAlpha"]); this.textures = [ this.canvasTexture(paintConcrete), this.canvasTexture(paintWood), this.canvasTexture(paintMetal), this.canvasTexture(paintFloor), ]; this.white = this.solidTexture([255, 255, 255, 255]); this.shadowTex = this.canvasTexture(radialShadow, 128); // 立方体(模型 / 阴影共用):顶点交错成 pos+normal+uv,跟地图格式一致 const cn = this.cube.positions.length / 3; const cdata = new Float32Array(cn * 8); for (let i = 0; i < cn; i++) { cdata[i * 8] = this.cube.positions[i * 3]; cdata[i * 8 + 1] = this.cube.positions[i * 3 + 1]; cdata[i * 8 + 2] = this.cube.positions[i * 3 + 2]; cdata[i * 8 + 3] = this.cube.normals[i * 3]; cdata[i * 8 + 4] = this.cube.normals[i * 3 + 1]; cdata[i * 8 + 5] = this.cube.normals[i * 3 + 2]; cdata[i * 8 + 6] = this.cube.uvs[i * 2]; cdata[i * 8 + 7] = this.cube.uvs[i * 2 + 1]; } this.cubeVbo = this.buffer(cdata); this.cubeIbo = this.elementBuffer(this.cube.indices); this.cubeMesh = { vbo: this.cubeVbo, ibo: this.cubeIbo, count: this.cube.count }; this.skyVbo = this.buffer(this.cube.positions); this.skyCount = this.cube.count; this.particleBuf = gl.createBuffer(); this.lineBuf = gl.createBuffer(); this.particleData = new Float32Array(4096 * 8); this.lineData = new Float32Array(4096 * 3); this.lightDir = normalize3([-0.42, 0.72, 0.55]); this.lightColor = [1.0, 0.88, 0.68]; this.fillDir = normalize3([0.55, 0.22, -0.62]); this.fillColor = [0.22, 0.27, 0.35]; this.ambient = [0.3, 0.37, 0.47]; this.fogColor = [0.115, 0.16, 0.215]; this.sunDir = normalize3([-0.5, 0.34, 0.62]); this.skyHorizon = [0.24, 0.29, 0.35]; this.skyZenith = [0.05, 0.08, 0.13]; this.sunColor = [1.0, 0.55, 0.25]; gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.enable(gl.CULL_FACE); gl.cullFace(gl.BACK); gl.clearColor(this.fogColor[0], this.fogColor[1], this.fogColor[2], 1); this.resize(); } /* ------------------------------ GL 小工具 ------------------------------ */ program(vs, fs) { const gl = this.gl; const compile = (type, src) => { const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s); if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) { throw new Error("shader: " + gl.getShaderInfoLog(s)); } return s; }; const p = gl.createProgram(); gl.attachShader(p, compile(gl.VERTEX_SHADER, vs)); gl.attachShader(p, compile(gl.FRAGMENT_SHADER, fs)); gl.linkProgram(p); if (!gl.getProgramParameter(p, gl.LINK_STATUS)) { throw new Error("link: " + gl.getProgramInfoLog(p)); } return p; } locations(prog, names) { const out = {}; for (const n of names) { out[n] = n.startsWith("u") ? this.gl.getUniformLocation(prog, n) : this.gl.getAttribLocation(prog, n); } return out; } buffer(data) { const gl = this.gl; const b = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, b); gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW); return b; } elementBuffer(data) { const gl = this.gl; const b = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, b); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, data, gl.STATIC_DRAW); return b; } /** 只启用本次绘制用到的顶点属性,避免不同 program 的属性串味 */ useAttribs(indices) { const gl = this.gl; for (let i = 0; i < 8; i++) { if (indices.includes(i)) gl.enableVertexAttribArray(i); else gl.disableVertexAttribArray(i); } } canvasTexture(paint, size = 256) { const gl = this.gl; const c = canvasTex(size); const g = c.getContext("2d"); paint(g, size); const tex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tex); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, c); gl.generateMipmap(gl.TEXTURE_2D); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); return tex; } solidTexture(rgba) { const gl = this.gl; const tex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tex); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(rgba)); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); return tex; } /* -------------------------------- 地图 -------------------------------- */ setLevel(level) { const gl = this.gl; this.level = level; const meshes = [0, 1, 2, 3].map(() => ({ v: [], i: [], n: 0 })); const tiles = [1.5, 1.7, 2.6, 2.1]; for (const b of level.boxes) { const m = meshes[b.mat] || meshes[0]; for (const [axis, sign] of FACES) { const u = (axis + 1) % 3; const v = (axis + 2) % 3; const corners = [ [0, 0], [1, 0], [1, 1], [0, 1], ]; const base = m.n; const nn = [0, 0, 0]; nn[axis] = sign; for (const [cu, cv] of corners) { const p = [0, 0, 0]; p[axis] = sign > 0 ? b.max[axis] : b.min[axis]; p[u] = cu ? b.max[u] : b.min[u]; p[v] = cv ? b.max[v] : b.min[v]; const tile = tiles[b.mat] || TILE; m.v.push(p[0], p[1], p[2], nn[0], nn[1], nn[2], p[u] / tile, p[v] / tile); m.n++; } if (sign > 0) m.i.push(base, base + 1, base + 2, base, base + 2, base + 3); else m.i.push(base, base + 2, base + 1, base, base + 3, base + 2); } } this.matBuffers = meshes.map((m) => { if (!m.n) return null; return { vbo: this.buffer(new Float32Array(m.v)), ibo: this.elementBuffer(new Uint16Array(m.i)), count: m.i.length, }; }); this.shadowQuads = []; for (const b of level.boxes) { if (b.min[1] <= 0.05 && b.max[1] > 0.4 && b.mat !== 3) { this.shadowQuads.push({ min: [b.min[0], b.min[2]], max: [b.max[0], b.max[2]] }); } } } resize() { const w = Math.max(1, Math.round(this.canvas.clientWidth * this.dpr)); const h = Math.max(1, Math.round(this.canvas.clientHeight * this.dpr)); if (this.canvas.width !== w || this.canvas.height !== h) { this.canvas.width = w; this.canvas.height = h; } this.gl.viewport(0, 0, w, h); } /* -------------------------------- 渲染 -------------------------------- */ render(s) { const gl = this.gl; this.aspect = this.canvas.width / Math.max(1, this.canvas.height); this.fov = s.fov || 78; this.proj = perspective((this.fov * Math.PI) / 180, this.aspect, 0.045, 320); this.view = mul(mul(rotX(-s.pitch), rotY(s.yaw)), translate(-s.pos[0], -s.pos[1], -s.pos[2])); this.eye = s.pos; gl.clearColor(this.fogColor[0], this.fogColor[1], this.fogColor[2], 1); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); this.drawSky(s); this.drawWorld(); this.drawShadows(s); this.drawPlayers(s); this.drawParticles(s); this.drawTracers(s); } drawMesh(buf, tex, tint, model, normalMat, emissive = 0) { const gl = this.gl; const w = this.world; gl.bindBuffer(gl.ARRAY_BUFFER, buf.vbo); gl.vertexAttribPointer(w.aPos, 3, gl.FLOAT, false, 32, 0); gl.vertexAttribPointer(w.aNormal, 3, gl.FLOAT, false, 32, 12); gl.vertexAttribPointer(w.aUV, 2, gl.FLOAT, false, 32, 24); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buf.ibo); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, tex); gl.uniform1i(w.uTex, 0); gl.uniform3fv(w.uTint, tint); gl.uniformMatrix4fv(w.uModel, false, model); gl.uniformMatrix3fv(w.uNormalMat, false, normalMat); gl.uniform1f(w.uEmissive, emissive); gl.drawElements(gl.TRIANGLES, buf.count, gl.UNSIGNED_SHORT, 0); } drawSky(s) { const gl = this.gl; const p = this.sky; gl.useProgram(this.progSky); this.useAttribs([p.aPos]); gl.disable(gl.DEPTH_TEST); gl.depthMask(false); gl.disable(gl.CULL_FACE); gl.bindBuffer(gl.ARRAY_BUFFER, this.skyVbo); gl.vertexAttribPointer(p.aPos, 3, gl.FLOAT, false, 0, 0); gl.uniformMatrix4fv(p.uProj, false, this.proj); gl.uniformMatrix4fv(p.uView, false, this.view); gl.uniform3fv(p.uCam, s.pos); gl.uniform3fv(p.uHorizon, this.skyHorizon); gl.uniform3fv(p.uZenith, this.skyZenith); gl.uniform3fv(p.uSunColor, this.sunColor); gl.uniform3fv(p.uSunDir, this.sunDir); gl.drawArrays(gl.TRIANGLES, 0, this.skyCount); gl.enable(gl.DEPTH_TEST); gl.depthMask(true); gl.enable(gl.CULL_FACE); } beginWorld() { const gl = this.gl; const w = this.world; gl.useProgram(this.progWorld); this.useAttribs([w.aPos, w.aNormal, w.aUV]); gl.uniformMatrix4fv(w.uProj, false, this.proj); gl.uniformMatrix4fv(w.uView, false, this.view); gl.uniform3fv(w.uLightDir, this.lightDir); gl.uniform3fv(w.uLightColor, this.lightColor); gl.uniform3fv(w.uFillDir, this.fillDir); gl.uniform3fv(w.uFillColor, this.fillColor); gl.uniform3fv(w.uAmbient, this.ambient); gl.uniform3fv(w.uFogColor, this.fogColor); gl.uniform3fv(w.uCamPos, this.eye); gl.uniform1f(w.uFogNear, 26); gl.uniform1f(w.uFogFar, 95); gl.uniform1f(w.uEmissive, 0); } drawWorld() { const gl = this.gl; this.beginWorld(); const I = mat4(); const tints = [ [1, 1, 1], [1, 0.96, 0.9], [0.94, 0.98, 1], [1, 0.99, 0.96], ]; for (let i = 0; i < this.matBuffers.length; i++) { const buf = this.matBuffers[i]; if (!buf) continue; this.drawMesh(buf, this.textures[i], tints[i], I, mat3Identity(), 0); } void gl; } drawShadows(s) { const gl = this.gl; const f = this.flat; gl.useProgram(this.progFlat); this.useAttribs([f.aPos]); // UV 用一个常量,贴图是径向渐变 gl.disableVertexAttribArray(f.aUV); gl.vertexAttrib2f(f.aUV, 0.5, 0.5); gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); gl.depthMask(false); gl.disable(gl.CULL_FACE); gl.bindBuffer(gl.ARRAY_BUFFER, this.cubeVbo); gl.vertexAttribPointer(f.aPos, 3, gl.FLOAT, false, 32, 0); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.cubeIbo); gl.uniformMatrix4fv(f.uProj, false, this.proj); gl.uniformMatrix4fv(f.uView, false, this.view); gl.uniform1i(f.uTex, 0); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, this.shadowTex); gl.uniform3f(f.uTint, 0, 0, 0); const quad = (cx, cz, sx, sz, alpha) => { gl.uniform1f(f.uAlpha, alpha); const m = mul(translate(cx, 0.022, cz), mul(rotX(-Math.PI / 2), scale(sx, sz, 0.002))); gl.uniformMatrix4fv(f.uModel, false, m); gl.drawElements(gl.TRIANGLES, this.cube.count, gl.UNSIGNED_SHORT, 0); }; for (const q of this.shadowQuads) { quad((q.min[0] + q.max[0]) / 2, (q.min[1] + q.max[1]) / 2, q.max[0] - q.min[0] + 0.6, q.max[1] - q.min[1] + 0.6, 0.3); } for (const p of s.players) { if (!p.alive) continue; quad(p.pos[0], p.pos[2], 1.15, 1.15, 0.42); } gl.depthMask(true); gl.disable(gl.BLEND); gl.enable(gl.CULL_FACE); } drawPlayers(s) { this.beginWorld(); const box = this.cubeMesh; for (const p of s.players) { if (!p.alive) continue; if (p.slot === s.selfSlot && !s.spectating) continue; const base = mul(translate(p.pos[0], p.pos[1], p.pos[2]), rotY(-p.yaw)); const nm = yawNormalMat(p.yaw); const leg = [0.2, 0.22, 0.26]; const team = p.bot ? [0.8, 0.4, 0.2] : [0.86, 0.33, 0.16]; const head = [0.76, 0.64, 0.53]; const part = (local, size, color, emissive) => { const m = mul(base, mul(translate(local[0], local[1], local[2]), scale(size[0], size[1], size[2]))); this.drawMesh(box, this.white, color, m, nm, emissive); }; part([-0.16, 0.42, 0], [0.22, 0.84, 0.3], leg, 0.04); part([0.16, 0.42, 0], [0.22, 0.84, 0.3], leg, 0.04); part([0, 1.14, 0], [0.6, 0.62, 0.36], team, 0.12); part([0, 1.63, -0.02], [0.32, 0.3, 0.32], head, 0.08); part([0.14, 1.16, -0.4], [0.1, 0.13, 0.62], [0.13, 0.14, 0.16], 0.04); // 头顶一个小小的队伍色标记,远距离更好认 part([0, 1.84, 0], [0.13, 0.045, 0.13], team, 0.9); } } drawParticles(s) { const gl = this.gl; const list = s.particles; if (!list || !list.length) return; const p = this.particle; let n = 0; const arr = this.particleData; for (const q of list) { if (n >= 4096) break; const o = n * 8; arr[o] = q.pos[0]; arr[o + 1] = q.pos[1]; arr[o + 2] = q.pos[2]; arr[o + 3] = q.size; arr[o + 4] = q.color[0]; arr[o + 5] = q.color[1]; arr[o + 6] = q.color[2]; arr[o + 7] = q.alpha; n++; } gl.useProgram(this.progParticle); this.useAttribs([p.aPos, p.aSize, p.aColor]); gl.bindBuffer(gl.ARRAY_BUFFER, this.particleBuf); gl.bufferData(gl.ARRAY_BUFFER, arr.subarray(0, n * 8), gl.DYNAMIC_DRAW); gl.vertexAttribPointer(p.aPos, 3, gl.FLOAT, false, 32, 0); gl.vertexAttribPointer(p.aSize, 1, gl.FLOAT, false, 32, 12); gl.vertexAttribPointer(p.aColor, 4, gl.FLOAT, false, 32, 16); gl.uniformMatrix4fv(p.uProj, false, this.proj); gl.uniformMatrix4fv(p.uView, false, this.view); gl.uniform1f(p.uScale, this.canvas.height / (2 * Math.tan((this.fov * Math.PI) / 360))); gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE); gl.depthMask(false); gl.drawArrays(gl.POINTS, 0, n); gl.depthMask(true); gl.disable(gl.BLEND); } drawTracers(s) { const gl = this.gl; const list = s.tracers; if (!list || !list.length) return; const p = this.line; let n = 0; for (const t of list) { if (n + 2 > 4096) break; this.lineData[n * 3] = t.from[0]; this.lineData[n * 3 + 1] = t.from[1]; this.lineData[n * 3 + 2] = t.from[2]; n++; this.lineData[n * 3] = t.to[0]; this.lineData[n * 3 + 1] = t.to[1]; this.lineData[n * 3 + 2] = t.to[2]; n++; } gl.useProgram(this.progLine); this.useAttribs([p.aPos]); gl.bindBuffer(gl.ARRAY_BUFFER, this.lineBuf); gl.bufferData(gl.ARRAY_BUFFER, this.lineData.subarray(0, n * 3), gl.DYNAMIC_DRAW); gl.vertexAttribPointer(p.aPos, 3, gl.FLOAT, false, 0, 0); gl.uniformMatrix4fv(p.uProj, false, this.proj); gl.uniformMatrix4fv(p.uView, false, this.view); gl.uniform3f(p.uColor, 1.0, 0.8, 0.4); gl.uniform1f(p.uAlpha, 0.75); gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE); gl.depthMask(false); gl.drawArrays(gl.LINES, 0, n); gl.depthMask(true); gl.disable(gl.BLEND); } } function normalize3(v) { const l = Math.hypot(v[0], v[1], v[2]) || 1; return [v[0] / l, v[1] / l, v[2] / l]; }