2 Commits

Author SHA1 Message Date
52c2e1dacd Add diffrent camera modes 2026-02-04 22:41:53 +01:00
86d6da33d2 Add skybox 2026-02-04 22:34:59 +01:00
6 changed files with 470 additions and 41 deletions

View File

@@ -1,5 +1,6 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
@@ -285,10 +286,51 @@
<script id="sky-fs" type="x-shader/x-fragment">
precision mediump float;
varying vec3 fragPos;
varying vec3 v_rayDir;
uniform vec3 uSunDirection;
void main(void) {
gl_FragColor = vec4(fragPos,1.0);
vec3 rayDir = normalize(v_rayDir);
// Use Z as up (matches world space where ocean is on XY plane)
float upAmount = rayDir.z;
// Sky gradient - from horizon to zenith
float horizonBlend = pow(1.0 - max(upAmount, 0.0), 2.0);
vec3 zenithColor = vec3(0.15, 0.35, 0.75); // Deep blue at top
vec3 horizonColor = vec3(0.55, 0.7, 0.9); // Light blue at horizon
vec3 skyColor = mix(zenithColor, horizonColor, horizonBlend);
// Add warm glow near horizon
float horizonGlow = pow(max(1.0 - abs(upAmount), 0.0), 6.0);
skyColor += vec3(0.4, 0.25, 0.1) * horizonGlow * 0.4;
// Sun direction already in correct coordinate system
vec3 sunDir = normalize(uSunDirection);
float sunAngle = max(dot(rayDir, sunDir), 0.0);
// Sun disk
float sunDisk = smoothstep(0.9993, 0.9998, sunAngle);
vec3 sunColor = vec3(1.0, 0.95, 0.85);
// Sun glow
float sunGlow = pow(sunAngle, 48.0) * 0.6;
float sunHalo = pow(sunAngle, 6.0) * 0.25;
// Combine sun effects
skyColor += sunColor * sunDisk * 3.0;
skyColor += vec3(1.0, 0.85, 0.5) * sunGlow;
skyColor += vec3(1.0, 0.9, 0.7) * sunHalo;
// Below horizon - fade to darker color
if (upAmount < 0.0) {
float depth = -upAmount;
vec3 deepColor = vec3(0.02, 0.08, 0.15);
skyColor = mix(horizonColor * 0.7, deepColor, smoothstep(0.0, 0.5, depth));
}
gl_FragColor = vec4(skyColor, 1.0);
}
</script>
<script id="sky-vs" type="x-shader/x-vertex">
@@ -296,16 +338,18 @@
uniform mat4 projection;
uniform mat4 view;
uniform mat4 testModel;
varying vec3 fragPos;
varying vec3 v_rayDir;
void main(void) {
gl_PointSize = 10.;
gl_Position = projection * mat4(mat3(view)) * vec4(positionAttr, 1.0);
fragPos = (view * vec4(positionAttr,1.0)).xyz; //This is wrong probably
v_rayDir = positionAttr;
// Remove translation from view matrix for skybox
mat4 rotView = mat4(mat3(view));
vec4 pos = projection * rotView * vec4(positionAttr, 1.0);
gl_Position = pos;
}
</script>
</head>
<body>
@@ -314,15 +358,21 @@
<div id="controls">
<h3>🌊 Ocean Controls</h3>
<div class="control-group">
<strong>Camera Rotation:</strong><br>
<span class="key">W</span><span class="key">A</span><span class="key">S</span><span class="key">D</span> or Arrow Keys
<strong>Camera Mode:</strong> <span class="key">C</span> (FPS/Orbital)<br>
<span id="current-camera-mode" style="font-size: 12px; color: #aaa;">Current: FPS</span>
</div>
<div class="control-group">
<strong>Zoom:</strong><br>
<span class="key">Q</span> / <span class="key">E</span> or <span class="key">+</span> / <span class="key">-</span>
<strong>FPS Camera:</strong><br>
<span class="key">W</span><span class="key">A</span><span class="key">S</span><span class="key">D</span> Move<br>
<span class="key">Q</span><span class="key">E</span> or <span class="key">Space</span><span class="key">Ctrl</span> Up/Down<br>
<span class="key">Shift</span> Sprint<br>
Mouse: Look around
</div>
<div class="control-group">
<strong>Mouse:</strong> Click and drag to rotate
<strong>Orbital Camera:</strong><br>
<span class="key">W</span><span class="key">A</span><span class="key">S</span><span class="key">D</span> or Arrows Rotate<br>
<span class="key">Q</span><span class="key">E</span> or <span class="key">+</span><span class="key">-</span> Zoom<br>
Mouse: Click and drag to rotate
</div>
<div class="control-group">
<strong>Reset:</strong> <span class="key">R</span>
@@ -341,6 +391,7 @@
// Toggle controls visibility
const controls = document.getElementById('controls');
const toggleBtn = document.getElementById('toggle-controls');
const cameraModeDisplay = document.getElementById('current-camera-mode');
toggleBtn.addEventListener('click', () => {
controls.classList.toggle('hidden');
@@ -350,6 +401,27 @@
if (evt.key === 'h' || evt.key === 'H') {
controls.classList.toggle('hidden');
}
// Update camera mode display when C is pressed
if (evt.key === 'c' || evt.key === 'C') {
setTimeout(() => {
// Get camera mode from any displayed element
const cameraMode = document.getElementById('camera-mode');
if (cameraMode && cameraModeDisplay) {
const mode = cameraMode.textContent.replace('Camera: ', '');
cameraModeDisplay.textContent = `Current: ${mode}`;
}
}, 100);
}
});
// Listen for custom camera mode toggle events from UI
window.addEventListener('toggleCameraMode', () => {
const cameraMode = document.getElementById('camera-mode');
if (cameraMode && cameraModeDisplay) {
const mode = cameraMode.textContent.replace('Camera: ', '');
cameraModeDisplay.textContent = `Current: ${mode}`;
}
});
</script>
</body>

View File

@@ -1,7 +1,8 @@
import { vec3, mat4, vec4 } from 'gl-matrix';
import { ICamera } from './ICamera';
/** A camera that always looks at the world origin. Can have an offset and be rotated. */
export class Camera {
/** Orbital camera that rotates around the world origin. */
export class OrbitalCamera implements ICamera {
pos: vec3;
target: vec3;
up: vec3;
@@ -64,4 +65,12 @@ export class Camera {
mat4.lookAt(ret, this.pos, this.target, this.up);
return ret;
}
/** Get view direction for LOD calculations */
getViewDirection(): vec3 {
const dir = vec3.create();
vec3.subtract(dir, this.target, this.pos);
vec3.normalize(dir, dir);
return dir;
}
}

98
src/FPSCamera.ts Normal file
View File

@@ -0,0 +1,98 @@
import { vec3, mat4 } from 'gl-matrix';
import { ICamera } from './ICamera';
/** FPS-style flight camera with free movement */
export class FPSCamera implements ICamera {
pos: vec3;
target: vec3;
up: vec3;
// FPS camera angles (in radians)
pitch: number; // Up/down rotation
yaw: number; // Left/right rotation
// Direction vectors
forward: vec3;
right: vec3;
constructor() {
this.pos = vec3.create();
vec3.set(this.pos, 0.0, -3.0, 2.0); // Start above and behind origin
this.target = vec3.create();
this.up = vec3.create();
vec3.set(this.up, 0.0, 0.0, 1.0); // Z is up
this.forward = vec3.create();
this.right = vec3.create();
this.pitch = -0.3; // Looking slightly down
this.yaw = Math.PI / 2; // Looking toward +Y
this.updateVectors();
}
/** Rotate camera by mouse delta */
rotate(deltaX: number, deltaY: number, sensitivity: number = 0.003): void {
this.yaw -= deltaX * sensitivity;
this.pitch -= deltaY * sensitivity;
// Clamp pitch to avoid flipping
const maxPitch = Math.PI / 2 - 0.01;
this.pitch = Math.max(-maxPitch, Math.min(maxPitch, this.pitch));
this.updateVectors();
}
/** Move camera in the direction it's looking */
moveForward(amount: number): void {
vec3.scaleAndAdd(this.pos, this.pos, this.forward, amount);
this.updateVectors();
}
moveRight(amount: number): void {
vec3.scaleAndAdd(this.pos, this.pos, this.right, amount);
this.updateVectors();
}
moveUp(amount: number): void {
// Move along world Z axis
this.pos[2] += amount;
this.updateVectors();
}
/** Move in the actual look direction (including vertical) */
moveInLookDirection(amount: number): void {
vec3.scaleAndAdd(this.pos, this.pos, this.forward, amount);
this.updateVectors();
}
/** Update direction vectors from pitch/yaw */
private updateVectors(): void {
// Calculate forward vector from pitch and yaw
// Z is up, so we use different axis mapping
this.forward[0] = Math.cos(this.pitch) * Math.cos(this.yaw);
this.forward[1] = Math.cos(this.pitch) * Math.sin(this.yaw);
this.forward[2] = Math.sin(this.pitch);
vec3.normalize(this.forward, this.forward);
// Right vector is perpendicular to forward and world up
const worldUp = vec3.fromValues(0, 0, 1);
vec3.cross(this.right, this.forward, worldUp);
vec3.normalize(this.right, this.right);
// Camera up is perpendicular to forward and right
vec3.cross(this.up, this.right, this.forward);
vec3.normalize(this.up, this.up);
// Update target
vec3.add(this.target, this.pos, this.forward);
}
getViewMatrix(): mat4 {
const ret: mat4 = mat4.create();
mat4.lookAt(ret, this.pos, this.target, this.up);
return ret;
}
/** Get view direction for LOD calculations */
getViewDirection(): vec3 {
return vec3.clone(this.forward);
}
}

11
src/ICamera.ts Normal file
View File

@@ -0,0 +1,11 @@
import { vec3, mat4 } from 'gl-matrix';
/** Camera interface that both camera types implement */
export interface ICamera {
pos: vec3;
target: vec3;
up: vec3;
getViewMatrix(): mat4;
getViewDirection(): vec3;
}

80
src/Skybox.ts Normal file
View File

@@ -0,0 +1,80 @@
/** Skybox cube for rendering the sky */
export class Skybox {
private vao: WebGLVertexArrayObject | null = null;
private vbo: WebGLBuffer | null = null;
private indexCount: number = 0;
constructor() {}
initVAO(gl: WebGL2RenderingContext): void {
// Cube vertices - positions only
const vertices = new Float32Array([
// Front face
-1, -1, 1,
1, -1, 1,
1, 1, 1,
-1, 1, 1,
// Back face
-1, -1, -1,
-1, 1, -1,
1, 1, -1,
1, -1, -1,
// Top face
-1, 1, -1,
-1, 1, 1,
1, 1, 1,
1, 1, -1,
// Bottom face
-1, -1, -1,
1, -1, -1,
1, -1, 1,
-1, -1, 1,
// Right face
1, -1, -1,
1, 1, -1,
1, 1, 1,
1, -1, 1,
// Left face
-1, -1, -1,
-1, -1, 1,
-1, 1, 1,
-1, 1, -1,
]);
const indices = new Uint16Array([
0, 2, 1, 0, 3, 2, // front
4, 6, 5, 4, 7, 6, // back
8, 10, 9, 8, 11, 10, // top
12, 14, 13, 12, 15, 14, // bottom
16, 18, 17, 16, 19, 18, // right
20, 22, 21, 20, 23, 22, // left
]);
this.indexCount = indices.length;
this.vao = gl.createVertexArray();
gl.bindVertexArray(this.vao);
this.vbo = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.vbo);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
const ibo = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
// Position attribute
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0);
gl.bindVertexArray(null);
}
draw(gl: WebGL2RenderingContext): void {
if (!this.vao) return;
gl.bindVertexArray(this.vao);
gl.drawElements(gl.TRIANGLES, this.indexCount, gl.UNSIGNED_SHORT, 0);
gl.bindVertexArray(null);
}
}

View File

@@ -1,6 +1,9 @@
import { vec3, mat4 } from 'gl-matrix';
import { Camera } from './Camera';
import { ICamera } from './ICamera';
import { OrbitalCamera } from './Camera';
import { FPSCamera } from './FPSCamera';
import { Grid } from './Grid';
import { Skybox } from './Skybox';
import { createProgram } from './Shader';
import * as Config from './constants';
@@ -89,10 +92,12 @@ function initGeometry() {
var perlinNoiseProgram: WebGLProgram | null;
var defaultProgram: WebGLProgram | null;
var textureProgram: WebGLProgram | null;
var skyProgram: WebGLProgram | null;
function initShaders() {
perlinNoiseProgram = createProgram(gl, "ndc-vs", "noise-fs", "Perlin Noise");
defaultProgram = createProgram(gl, "default-vs", "default-fs", "Default");
textureProgram = createProgram(gl, "texture-vs", "texture-fs", "Texture");
skyProgram = createProgram(gl, "sky-vs", "sky-fs", "Sky");
}
/** Init an FBO used for the first render pass / perlin noise */
@@ -139,10 +144,17 @@ var keyboardRotationY = 0;
var keyboardZoom = 0;
var keysPressed: Set<string> = new Set();
/** Objects and states*/
var camera: Camera;
var camera: ICamera;
var orbitalCamera: OrbitalCamera;
var fpsCamera: FPSCamera;
var oceanGrid: Grid;
var skybox: Skybox;
var curRotX = Config.CAMERA_DEFAULT_ROT_X;
var curRotY = Config.CAMERA_DEFAULT_ROT_Y;
/** Camera modes */
var cameraMode: 'orbital' | 'fps' = 'fps';
var moveSpeed = 0.15;
var fastMoveSpeed = 0.4;
function drawScene() {
fps++;
let now = new Date();
@@ -169,6 +181,9 @@ function drawScene() {
gl.clearColor(1.0, 1.0, 1.0, 1);
gl.clear(gl.COLOR_BUFFER_BIT); //No depth buffer
// Disable face culling for fullscreen quad
gl.disable(gl.CULL_FACE);
//draw a fullscreen quad
gl.bindBuffer(gl.ARRAY_BUFFER, VBO);
@@ -201,11 +216,51 @@ function drawScene() {
mat4.identity(projection);
mat4.perspective(projection, Config.FOV, viewportWidth / viewportHeight, Config.NEAR_PLANE, Config.FAR_PLANE); //projection mode should actually be camera specific
camera.setOffset(Config.CAMERA_DEFAULT_OFFSET + keyboardZoom);
camera.setRotationX((curRotX += mouseYVel * Config.MOUSE_SENSITIVITY + keyboardRotationX));
camera.setRotationY((curRotY += mouseXVel * Config.MOUSE_SENSITIVITY + keyboardRotationY));
// Handle camera movement and rotation based on mode
if (cameraMode === 'fps') {
// FPS camera - direct movement
camera = fpsCamera;
handleFPSCameraMovement();
// Apply mouse rotation for FPS mode
if (mouseXVel !== 0 || mouseYVel !== 0) {
fpsCamera.rotate(mouseXVel, mouseYVel);
mouseXVel = 0;
mouseYVel = 0;
}
} else {
// Orbital camera - original behavior
camera = orbitalCamera;
orbitalCamera.setOffset(Config.CAMERA_DEFAULT_OFFSET + keyboardZoom);
orbitalCamera.setRotationX((curRotX += mouseYVel * Config.MOUSE_SENSITIVITY + keyboardRotationX));
orbitalCamera.setRotationY((curRotY += mouseXVel * Config.MOUSE_SENSITIVITY + keyboardRotationY));
}
var view = camera.getViewMatrix();
// Sun direction (matches the one in ocean shader)
const sunDirection = vec3.fromValues(0.3, 0.5, 0.8);
vec3.normalize(sunDirection, sunDirection);
// Draw skybox first with depth test disabled (always behind everything)
gl.depthMask(false);
gl.disable(gl.DEPTH_TEST);
gl.disable(gl.CULL_FACE); // Disable face culling for skybox (we're inside)
gl.useProgram(skyProgram);
let sky_view_loc = gl.getUniformLocation(<WebGLProgram>skyProgram, "view");
gl.uniformMatrix4fv(sky_view_loc, false, view);
let sky_projection_loc = gl.getUniformLocation(<WebGLProgram>skyProgram, "projection");
gl.uniformMatrix4fv(sky_projection_loc, false, projection);
let sky_sun_loc = gl.getUniformLocation(<WebGLProgram>skyProgram, "uSunDirection");
gl.uniform3fv(sky_sun_loc, sunDirection);
skybox.draw(gl);
gl.enable(gl.DEPTH_TEST);
gl.depthMask(true);
gl.enable(gl.CULL_FACE); // Re-enable face culling for ocean
gl.cullFace(gl.BACK); // Cull back faces for ocean
var model = mat4.create();
mat4.identity(model);
let translationCentering = vec3.create();
@@ -230,6 +285,41 @@ function drawScene() {
requestAnimationFrame(drawScene);
}
/** Handle FPS camera movement */
function handleFPSCameraMovement() {
const speed = keysPressed.has('Shift') ? fastMoveSpeed : moveSpeed;
// WASD for horizontal movement
if (keysPressed.has('w') || keysPressed.has('W')) {
fpsCamera.moveForward(speed);
}
if (keysPressed.has('s') || keysPressed.has('S')) {
fpsCamera.moveForward(-speed);
}
if (keysPressed.has('a') || keysPressed.has('A')) {
fpsCamera.moveRight(-speed);
}
if (keysPressed.has('d') || keysPressed.has('D')) {
fpsCamera.moveRight(speed);
}
// Q/E for vertical movement
if (keysPressed.has('q') || keysPressed.has('Q')) {
fpsCamera.moveUp(-speed);
}
if (keysPressed.has('e') || keysPressed.has('E')) {
fpsCamera.moveUp(speed);
}
// Space to go up, Ctrl to go down
if (keysPressed.has(' ')) {
fpsCamera.moveUp(speed);
}
if (keysPressed.has('Control')) {
fpsCamera.moveUp(-speed);
}
}
/** Handle keyboard input for camera controls */
function handleKeyboardInput() {
keyboardRotationX = 0;
@@ -298,19 +388,59 @@ function main() {
// Keyboard controls
window.addEventListener('keydown', (evt) => {
keysPressed.add(evt.key);
handleKeyboardInput();
// Toggle camera mode with 'C' key
if (evt.key === 'c' || evt.key === 'C') {
cameraMode = cameraMode === 'fps' ? 'orbital' : 'fps';
console.log(`Camera mode: ${cameraMode.toUpperCase()}`);
// Update FPS display to show camera mode
if (fpsDisplay) {
const modeText = document.createElement('div');
modeText.id = 'camera-mode';
modeText.style.cssText = 'position: absolute; top: 40px; left: 10px; color: white; font-family: monospace;';
modeText.textContent = `Camera: ${cameraMode.toUpperCase()}`;
const existingMode = document.getElementById('camera-mode');
if (existingMode) {
existingMode.textContent = `Camera: ${cameraMode.toUpperCase()}`;
} else {
document.body.appendChild(modeText);
}
}
}
// Reset camera on 'R' key
if (evt.key === 'r' || evt.key === 'R') {
curRotX = Config.CAMERA_DEFAULT_ROT_X;
curRotY = Config.CAMERA_DEFAULT_ROT_Y;
keyboardZoom = 0;
if (cameraMode === 'fps') {
fpsCamera = new FPSCamera(); // Reset to initial FPS position
camera = fpsCamera;
console.log('Camera reset to FPS default position');
} else {
curRotX = Config.CAMERA_DEFAULT_ROT_X;
curRotY = Config.CAMERA_DEFAULT_ROT_Y;
keyboardZoom = 0;
console.log('Camera reset to orbital default position');
}
}
// Prevent default for space to avoid page scroll
if (evt.key === ' ' && cameraMode === 'fps') {
evt.preventDefault();
}
// Handle orbital camera keyboard input
if (cameraMode === 'orbital') {
handleKeyboardInput();
}
});
window.addEventListener('keyup', (evt) => {
keysPressed.delete(evt.key);
handleKeyboardInput();
if (cameraMode === 'orbital') {
handleKeyboardInput();
}
});
// Window resize handler
@@ -318,6 +448,26 @@ function main() {
updateCanvasSize(canvas);
});
// Camera mode toggle from UI controls
window.addEventListener('toggleCameraMode', () => {
cameraMode = cameraMode === 'fps' ? 'orbital' : 'fps';
camera = cameraMode === 'fps' ? fpsCamera : orbitalCamera;
console.log(`Camera mode switched to: ${cameraMode.toUpperCase()}`);
// Update display
const modeText = document.createElement('div');
modeText.id = 'camera-mode';
modeText.style.cssText = 'position: absolute; top: 40px; left: 10px; color: white; font-family: monospace;';
modeText.textContent = `Camera: ${cameraMode.toUpperCase()}`;
const existingMode = document.getElementById('camera-mode');
if (existingMode) {
existingMode.textContent = `Camera: ${cameraMode.toUpperCase()}`;
} else {
document.body.appendChild(modeText);
}
});
initShaders();
initGeometry();
initFBO();
@@ -325,7 +475,16 @@ function main() {
oceanGrid = new Grid(Config.GRID_SIZE);
oceanGrid.initVAO(gl);
camera = new Camera();
skybox = new Skybox();
skybox.initVAO(gl);
// Initialize both cameras
orbitalCamera = new OrbitalCamera();
fpsCamera = new FPSCamera();
camera = fpsCamera; // Start with FPS camera
console.log('Cameras initialized - Press C to toggle between FPS and Orbital modes');
//Check if any errors apeared during init.
if (gl.getError() != gl.NO_ERROR) {
console.log("OpenGL Error!: ");