import { makeFace, makeBufferFromFaces } from '../geometry'; import { loadTexture, makeProgram } from '../gl'; import * as linalg from './linalg'; import { loadObjModel } from './obj'; import * as se3 from '../se3'; import { computeOrbit, findSoi, getCartesianState, makeOrbitObject, updateBodyPhysics } from './orbit'; import { getBodyGeometry } from './chunk'; const VSHADER = ` attribute vec3 aPosition; attribute vec3 aNormal; attribute vec2 aTextureCoord; uniform mat4 uProjection; uniform mat4 uModel; uniform mat4 uView; uniform vec3 uLightDirection; uniform float uAmbiantLight; uniform vec3 uGlowColor; varying highp vec2 vTextureCoord; varying lowp vec3 vLighting; varying lowp vec3 vRay; varying lowp vec3 vLightDir; varying lowp vec3 vNormal; highp mat3 transpose(in highp mat3 inmat) { highp vec3 x = inmat[0]; highp vec3 y = inmat[1]; highp vec3 z = inmat[2]; return mat3( vec3(x.x, y.x, z.x), vec3(x.y, y.y, z.y), vec3(x.z, y.z, z.z) ); } void main() { highp mat4 modelview = uView * uModel; gl_Position = uProjection * modelview * vec4(aPosition, 1.0); lowp vec3 normal = mat3(uModel) * aNormal; lowp float diffuseAmount = max(dot(-uLightDirection, normal), 0.0); lowp vec3 ambiant = uAmbiantLight * vec3(1.0, 1.0, 0.9); vLighting = ambiant + vec3(1.0, 1.0, 1.0) * diffuseAmount + uGlowColor; vTextureCoord = aTextureCoord; lowp vec3 camPos = -transpose(mat3(uView))*(uView * vec4(0.0, 0.0, 0.0, 1.0)).xyz; vRay = -normalize((uModel * vec4(aPosition, 1.0)).xyz - camPos); vLightDir = -uLightDirection; vNormal = normal; } `; const FSHADER = ` uniform sampler2D uSampler; varying highp vec2 vTextureCoord; varying lowp vec3 vLighting; varying lowp vec3 vRay; varying lowp vec3 vLightDir; varying lowp vec3 vNormal; void main() { highp vec4 color = texture2D(uSampler, vTextureCoord); if (color.a < 0.1) { discard; } lowp vec3 specularDir = 2.0 * dot(vLightDir, vNormal) * vNormal - vLightDir; lowp float specularAmount = smoothstep(0.92, 1.0, dot(vRay, specularDir)); lowp vec3 specular = 0.8 * specularAmount * vec3(1.0, 1.0, 0.8); gl_FragColor = vec4(vLighting * color.rgb + specular, color.a); } `; const kEpoch = 0; async function initWorldGl(gl: WebGLRenderingContext) { const program = makeProgram(gl, VSHADER, FSHADER); const texture = await loadTexture(gl, 'texture.png'); // load those ahead of time const viewLoc = gl.getUniformLocation(program, 'uView'); const modelLoc = gl.getUniformLocation(program, 'uModel'); const projLoc = gl.getUniformLocation(program, 'uProjection'); const samplerLoc = gl.getUniformLocation(program, 'uSampler'); const lightDirectionLoc = gl.getUniformLocation(program, 'uLightDirection'); const ambiantLoc = gl.getUniformLocation(program, 'uAmbiantLight'); const glowColorLoc = gl.getUniformLocation(program, 'uGlowColor'); const positionLoc = gl.getAttribLocation(program, 'aPosition'); const normalLoc = gl.getAttribLocation(program, 'aNormal'); const textureLoc = gl.getAttribLocation(program, 'aTextureCoord'); const setupScene = (sceneParams) => { const { projectionMatrix, viewMatrix, ambiantLightAmount, } = sceneParams; gl.useProgram(program); gl.uniformMatrix4fv(projLoc, false, new Float32Array(projectionMatrix)); gl.uniformMatrix4fv(viewLoc, false, new Float32Array(viewMatrix)); gl.uniform1f(ambiantLoc, ambiantLightAmount); // doing this here because it's the same for all world stuff gl.uniformMatrix4fv(modelLoc, false, new Float32Array(se3.identity())); gl.uniform1i(samplerLoc, 0); gl.enableVertexAttribArray(positionLoc); gl.enableVertexAttribArray(normalLoc); gl.enableVertexAttribArray(textureLoc); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, texture); }; const drawObject = (objectParams) => { const { position, orientation, glBuffer, numVertices, lightDirection, glowColor, } = objectParams; gl.uniformMatrix4fv(modelLoc, false, new Float32Array(se3.product( se3.translation(...position), orientation))); gl.uniform3fv(lightDirectionLoc, lightDirection); gl.uniform3fv(glowColorLoc, glowColor); gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer); gl.vertexAttribPointer(positionLoc, 3, gl.FLOAT, false, 20, 0); gl.vertexAttribPointer(normalLoc, 3, gl.BYTE, true, 20, 12); gl.vertexAttribPointer(textureLoc, 2, gl.UNSIGNED_SHORT, true, 20, 16); gl.drawArrays(gl.TRIANGLES, 0, numVertices); }; return { setupScene, drawObject, }; } const ORBIT_VSHADER = ` attribute vec3 aPosition; attribute vec2 aValue; uniform mat4 uProjection; uniform mat4 uModel; uniform mat4 uView; varying lowp vec2 vCoords; void main() { highp mat4 modelview = uView * uModel; gl_Position = uProjection * modelview * vec4(aPosition, 1.0); vCoords = aValue; } `; const ORBIT_FSHADER = ` varying lowp vec2 vCoords; void main() { lowp float x = vCoords.x; lowp float y = vCoords.y; lowp float f = sqrt(x * x + y * y); if (f > 1.00) { discard; } else if (f < 0.98) { discard; } gl_FragColor = vec4(1, .5, 0, 0.5); } `; function getOrbitDrawContext(gl) { const program = makeProgram(gl, ORBIT_VSHADER, ORBIT_FSHADER); // load those ahead of time const viewLoc = gl.getUniformLocation(program, 'uView'); const modelLoc = gl.getUniformLocation(program, 'uModel'); const projLoc = gl.getUniformLocation(program, 'uProjection'); const positionLoc = gl.getAttribLocation(program, 'aPosition'); const valueLoc = gl.getAttribLocation(program, 'aValue'); const setupScene = (sceneParams) => { const { projectionMatrix, viewMatrix, } = sceneParams; gl.useProgram(program); gl.uniformMatrix4fv(projLoc, false, new Float32Array(projectionMatrix)); gl.uniformMatrix4fv(viewLoc, false, new Float32Array(viewMatrix)); // doing this here because it's the same for all world stuff gl.uniformMatrix4fv(modelLoc, false, new Float32Array(se3.identity())); gl.enableVertexAttribArray(positionLoc); gl.enableVertexAttribArray(valueLoc); }; const drawObject = (objectParams) => { const { position, orientation, value, glBuffer, } = objectParams; gl.uniformMatrix4fv(modelLoc, false, new Float32Array(se3.product( se3.translation(...position), orientation))); gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer); gl.vertexAttribPointer(positionLoc, 3, gl.FLOAT, false, 20, 0); gl.vertexAttribPointer(valueLoc, 2, gl.FLOAT, false, 20, 12); gl.disable(gl.CULL_FACE); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); gl.enable(gl.CULL_FACE); }; return { setupScene, drawObject, }; } function closeToPlanet(context) { const body = findSoi(context); const relativePos = linalg.diff(context.player.position, body.position); return linalg.norm(relativePos) < 20; } function getSolarSystem(seed: number) { /// XXX: only returns 1 body for now return { name: 'Tat', mass: 1000.0, spin: [0, 0, 0.2], geometry: getBodyGeometry(0), glowColor: [0.5, 0.5, 0.46], children: [ { name: 'Quicksilver', seed: 1336, mass: 0.1, spin: [0.0, 0.0, 0.05], geometry: makeCube([0, 4]), orbit: { excentricity: 0.0, semimajorAxis: 200, inclination: 0.8, ascendingNodeLongitude: 0, periapsisArgument: 0, t0: 0, }, }, { name: 'Satourne', seed: 1338, mass: 0.1, spin: [0.0, 0.5, 0.0], geometry: makeCube([0, 5]), orbit: { excentricity: 0.0, semimajorAxis: 900, inclination: 0.0, ascendingNodeLongitude: 0, periapsisArgument: 0, t0: 0, }, children: [ { name: 'Kyoujin', seed: 13381, mass: 0.01, spin: [0.0, 0.0, 0.05], geometry: makeCube([0, 6]), orbit: { excentricity: 0.0, semimajorAxis: 20, inclination: Math.PI / 2, ascendingNodeLongitude: 0, periapsisArgument: 0, t0: 0, }, }, ], }, { name: 'Tataooine', seed: 1337, mass: 50, spin: [0.0, 0.0, 0.05], geometry: getBodyGeometry(1337), orbit: { excentricity: 0.3, semimajorAxis: 500, inclination: 0.0, ascendingNodeLongitude: 0, periapsisArgument: 0, t0: 0, }, children: [ { name: 'Mun', seed: 13371, mass: 0.01, spin: [0.0, 0.0, 0.05], geometry: makeCube([0, 7]), orbit: { excentricity: 0.0, semimajorAxis: 50, inclination: Math.PI / 2, ascendingNodeLongitude: 0, periapsisArgument: 0, t0: 0, }, }, ], }, ], }; } function initUiListeners(canvas: HTMLCanvasElement, context) { const canvasClickHandler = () => { canvas.requestPointerLock(); canvas.onclick = null; // const clickListener = e => { // switch(e.button) { // case 0: // left click // destroySelectedBlock(context); // break; // case 2: // right click // makeDirBlock(context); // break; // } // }; const clickListener = e => {}; const keyListener = e => { if (e.type === 'keydown') { if (e.repeat) return; context.keys.add(e.code); switch (e.code) { case 'KeyF': context.flying = !context.flying; context.player.velocity = [0, 0, 0]; delete context.orbit; return false; case 'KeyL': if (closeToPlanet(context)) { context.landing = True; } return false; case 'Space': if (!context.flying) { if (context.jumpAmount > 0) { const amount = context.jumpForce; context.player.velocity[1] = amount; context.jumpAmount -= 1; } } return false; } } else { context.keys.delete(e.code); } }; const moveListener = e => { context.camera.orientation[0] -= e.movementY / 500; context.camera.orientation[1] -= e.movementX / 500; context.camera.tf = se3.product( se3.roty(context.camera.orientation[1]), se3.rotx(context.camera.orientation[0]), ); }; const changeListener = () => { if (document.pointerLockElement === canvas) { return; } document.removeEventListener('pointerdown', clickListener); document.removeEventListener('pointerlockchange', changeListener); document.removeEventListener('pointermove', moveListener); document.removeEventListener('keydown', keyListener); document.removeEventListener('keyup', keyListener); canvas.onclick = canvasClickHandler; }; document.addEventListener('pointerdown', clickListener); document.addEventListener('pointerlockchange', changeListener); document.addEventListener('pointermove', moveListener); document.addEventListener('keydown', keyListener); document.addEventListener('keyup', keyListener); }; canvas.onclick = canvasClickHandler; document.addEventListener('keydown', e => { if (e.repeat) return; switch (e.code) { case 'F11': canvas.requestFullscreen(); break; } }); } function handleInput(context) { const move = (forward: number, right: number) => { if (context.keys.has('ShiftLeft')) { forward *= 10; right *= 10; } const tf = se3.product( se3.orientationOnly(context.player.tf), context.camera.tf, ); const dir = [right, 0, -forward, 10]; if (context.flying) { context.player.tf = [ context.player.tf, context.camera.tf, se3.translation(...dir), ].reduce(se3.product); context.camera.tf = se3.identity(); context.camera.orientation = [0, 0, 0]; } else { const vel = context.player.velocity; const dv = linalg.scale(se3.apply(tf, dir), 1/dir[3]); context.player.velocity = linalg.add(vel, dv); delete context.orbit; } }; context.keys.forEach(key => { switch (key) { case 'KeyW': move(0.5, 0.0); return; case 'KeyA': move(0.0, -0.5); return; case 'KeyS': move(-0.5, 0.0); return; case 'KeyD': move(0.0, 0.5); return; case 'KeyR': context.timeOffset += 1; return; } }); } function updatePhysics(time: number, context) { const {player} = context; const dt = time - (context.lastTime || 0); context.lastTime = time; player.position = se3.apply(player.tf, [0, 0, 0, 1]); updateBodyPhysics(time, context.universe); if (!context.flying) { if (context.orbit === undefined) { const newPos = linalg.add(player.position, linalg.scale(player.velocity, dt)); const dx = linalg.diff(newPos, player.position); player.tf = se3.product(se3.translation(...dx), player.tf); const body = findSoi(context.universe, context.player.position); context.orbit = computeOrbit(player, body, time); console.log(`orbiting ${body.name}, excentricity: ${context.orbit.excentricity}`); context.orbitBody = body; } else { const {position: orbitPos, velocity: orbitVel} = getCartesianState( context.orbit, context.orbitBody.mass, time); if (orbitPos === undefined) { const newPos = linalg.add(player.position, linalg.scale(player.velocity, dt)); const dx = linalg.diff(newPos, player.position); player.tf = se3.product(se3.translation(...dx), player.tf); } else { const position = linalg.add(orbitPos, context.orbitBody.position); const velocity = linalg.add(orbitVel, context.orbitBody.velocity); player.velocity = velocity; const dx = linalg.diff(position, player.position); player.tf = se3.product(se3.translation(...dx), player.tf); } } } } function updateGeometry(context, timeout_ms = 10) { } function getObjects(context, body, parentPosition = undefined) { const objects = []; const {gl, glContext, player} = context; const {position, orientation, glowColor} = body; if (body.glBuffer === undefined) { body.glBuffer = makeBufferFromFaces(gl, body.geometry); } objects.push({ geometry: body.glBuffer, orientation, position, glContext, glowColor, }); if (parentPosition !== undefined) { const orbitObject = makeOrbitObject(gl, context.orbitGlContext, body.orbit, parentPosition); objects.push(orbitObject); } else { const shipOrientation = [ se3.rotationOnly(player.tf), se3.rotationOnly(context.camera.tf), se3.rotxyz(-Math.PI / 2, Math.PI / 2, Math.PI / 2), ].reduce(se3.product); const shipPos = player.position; objects.push({ geometry: makeBufferFromFaces(gl, context.spaceship), orientation: shipOrientation, position: shipPos, glContext, }); } if (body.children !== undefined) { for (const child of body.children) { objects.push(...getObjects(context, child, position)); } } return objects; } function sunDirection(position: linalg.vec3) { return linalg.scale(position, 1/linalg.norm(position)); } function draw(context) { const {gl, camera, player, universe, orbit, orbitGlContext, orbitBody} = context; const {skyColor, ambiantLight, projMatrix} = context; const objects = getObjects(context, universe); if (orbit !== undefined && orbit.excentricity < 1) { objects.push(makeOrbitObject(gl, orbitGlContext, orbit, orbitBody.position)); } gl.clearColor(...skyColor, 1.0); gl.clearDepth(1.0); gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.enable(gl.CULL_FACE); gl.cullFace(gl.BACK); gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); const viewMatrix = se3.inverse([ player.tf, // player position & orientation camera.tf, // camera orientation relative to player se3.translation(0, 1, 4), // step back from the player ].reduce(se3.product)); let lastGlContext; for (const {position, orientation, geometry, glContext, glowColor} of objects) { if (glContext !== lastGlContext) { glContext.setupScene({ projectionMatrix: projMatrix, viewMatrix, ambiantLightAmount: ambiantLight, }); } lastGlContext = glContext; const lightDirection = sunDirection(position); glContext.drawObject({ position, orientation, glBuffer: geometry.glBuffer, numVertices: geometry.numVertices, lightDirection, glowColor: glowColor || [0, 0, 0], }); } } function tick(time: number, context) { handleInput(context); const simTime = time * 0.001 + context.timeOffset; updatePhysics(simTime, context); const campos = context.player.position; // world generation / geometry update { // frame time is typically 16.7ms, so this may lag a bit let timeLeft = 10; const start = performance.now(); updateGeometry(context, timeLeft); } draw(context); const dt = (time - context.lastFrameTime) * 0.001; context.lastFrameTime = time; document.querySelector('#fps')!.textContent = `${1.0 / dt} fps`; requestAnimationFrame(time => tick(time, context)); } function makeCube(texture) { return [ makeFace('-x', texture, [-0.5, 0, 0]), makeFace('+x', texture, [+0.5, 0, 0]), makeFace('-y', texture, [0, -0.5, 0]), makeFace('+y', texture, [0, +0.5, 0]), makeFace('-z', texture, [0, 0, -0.5]), makeFace('+z', texture, [0, 0, +0.5]), ]; } async function main() { const canvas = document.querySelector('#game')! as HTMLCanvasElement; // adjust canvas aspect ratio to that of the screen canvas.height = screen.height / screen.width * canvas.width; const gl = canvas.getContext('webgl'); if (gl === null) { console.error('webgl not available') return; } // TODO // [ ] loading bar // [x] spaceship // [ ] landing // [ ] huge planets // [x] lighting // [ ] better lighting // [x] optimize geometry generation const modelPromise = loadObjModel('spaceship.obj'); const context = { gl, projMatrix: se3.perspective(Math.PI / 3, canvas.clientWidth / canvas.clientHeight, 0.1, 10000.0), player: { tf: se3.translation(0.0, 0.0, 80.0), position: [0.0, 0.0, 80.0], velocity: [0, 0, 0], }, camera: { orientation: [0, 0, 0], tf: se3.identity(), }, keys: new Set(), lightDirection: [-0.2, -0.5, 0.4], skyColor: [0.10, 0.15, 0.2], ambiantLight: 0.4, blockSelectDistance: 8, flying: true, isOnGround: false, gravity: -17, jumpForce: 6.5, universe: getSolarSystem(0), timeOffset: 0, }; context.glContext = await initWorldGl(gl); context.orbitGlContext = getOrbitDrawContext(gl); initUiListeners(canvas, context); const starshipGeom = await modelPromise; console.log(`loaded ${starshipGeom.length} triangles`); context.spaceship = starshipGeom; requestAnimationFrame(time => tick(time, context)); } window.onload = main;