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
9 changed files with 476 additions and 947 deletions

View File

@@ -1,5 +1,6 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
@@ -10,20 +11,20 @@
padding: 0; padding: 0;
box-sizing: border-box; box-sizing: border-box;
} }
body { body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
overflow: hidden; overflow: hidden;
background: #000; background: #000;
} }
#window { #window {
display: block; display: block;
width: 100vw; width: 100vw;
height: 100vh; height: 100vh;
cursor: move; cursor: move;
} }
#controls { #controls {
position: absolute; position: absolute;
top: 20px; top: 20px;
@@ -37,23 +38,23 @@
backdrop-filter: blur(10px); backdrop-filter: blur(10px);
transition: opacity 0.3s; transition: opacity 0.3s;
} }
#controls.hidden { #controls.hidden {
opacity: 0; opacity: 0;
pointer-events: none; pointer-events: none;
} }
#controls h3 { #controls h3 {
margin: 0 0 10px 0; margin: 0 0 10px 0;
font-size: 16px; font-size: 16px;
font-weight: 600; font-weight: 600;
} }
#controls .control-group { #controls .control-group {
margin-bottom: 8px; margin-bottom: 8px;
line-height: 1.6; line-height: 1.6;
} }
#controls .key { #controls .key {
display: inline-block; display: inline-block;
background: rgba(255, 255, 255, 0.2); background: rgba(255, 255, 255, 0.2);
@@ -63,7 +64,7 @@
font-size: 12px; font-size: 12px;
margin: 0 2px; margin: 0 2px;
} }
#toggle-controls { #toggle-controls {
position: absolute; position: absolute;
top: 20px; top: 20px;
@@ -78,11 +79,11 @@
backdrop-filter: blur(10px); backdrop-filter: blur(10px);
transition: background 0.3s; transition: background 0.3s;
} }
#toggle-controls:hover { #toggle-controls:hover {
background: rgba(0, 0, 0, 0.85); background: rgba(0, 0, 0, 0.85);
} }
#fps-counter { #fps-counter {
position: absolute; position: absolute;
bottom: 20px; bottom: 20px;
@@ -95,56 +96,6 @@
font-size: 14px; font-size: 14px;
backdrop-filter: blur(10px); backdrop-filter: blur(10px);
} }
.slider-group {
margin: 8px 0;
}
.slider-group label {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 4px;
font-size: 13px;
}
.slider-group input[type="range"] {
width: 100%;
height: 6px;
border-radius: 3px;
background: rgba(255, 255, 255, 0.2);
outline: none;
-webkit-appearance: none;
appearance: none;
}
.slider-group input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 14px;
height: 14px;
border-radius: 50%;
background: #4a9eff;
cursor: pointer;
}
.slider-group input[type="range"]::-moz-range-thumb {
width: 14px;
height: 14px;
border-radius: 50%;
background: #4a9eff;
cursor: pointer;
border: none;
}
.slider-value {
background: rgba(255, 255, 255, 0.15);
padding: 2px 6px;
border-radius: 3px;
font-size: 11px;
min-width: 35px;
text-align: center;
}
</style> </style>
<script id="noise-fs" type="x-shader/x-fragment"> <script id="noise-fs" type="x-shader/x-fragment">
precision mediump float; precision mediump float;
@@ -240,429 +191,96 @@
precision mediump float; precision mediump float;
varying vec3 v_fragPos; varying vec3 v_fragPos;
varying vec3 v_normal; varying vec2 v_uv;
varying float v_waveHeight;
varying float v_foamFactor;
varying float v_distanceFade;
uniform vec3 eyePos; uniform vec3 eyePos;
uniform float uFoamIntensity; uniform sampler2D displace_map;
uniform float uGlitterIntensity;
vec3 lightPos = vec3(0.,0.,10.); //not used in diffuse. diffuse uses a directional light. It is only used for specular glittering.
vec3 lightColor = vec3(1.0,1.0,1.0);
// Simple hash function for noise //using forward difference
float hash(vec2 p) { //Normal vectors are compute as: https://www.scratchapixel.com/lessons/procedural-generation-virtual-worlds/perlin-noise-part-2/perlin-noise-computing-derivatives
return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
}
// Value noise for foam texture
float noise(vec2 p) {
vec2 i = floor(p);
vec2 f = fract(p);
f = f * f * (3.0 - 2.0 * f); // smoothstep
float a = hash(i);
float b = hash(i + vec2(1.0, 0.0));
float c = hash(i + vec2(0.0, 1.0));
float d = hash(i + vec2(1.0, 1.0));
return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
}
// Fractal noise for more detailed foam
float foamNoise(vec2 p) {
float n = 0.0;
n += 0.5 * noise(p * 8.0);
n += 0.25 * noise(p * 16.0);
n += 0.125 * noise(p * 32.0);
n += 0.0625 * noise(p * 64.0);
return n;
}
void main(void) { void main(void) {
vec3 lightColor = vec3(1.0, 1.0, 0.95); vec4 displace = texture2D(displace_map, v_uv);
vec3 sunDirection = normalize(vec3(0.3, 0.5, 0.8)); //calculate normal
float gridPointDelta = (1. / 256.);
vec3 norm = normalize(v_normal); vec3 currPoint = vec3(0.0,0.0,displace.x);
vec3 right = vec3(gridPointDelta,0.0,texture2D(displace_map,vec2(v_uv.x + gridPointDelta,v_uv.y)).x*(1./1.));
// View direction vec3 left = vec3(-gridPointDelta,0.0,texture2D(displace_map,vec2(v_uv.x - gridPointDelta,v_uv.y)).x*(1./1.));
vec3 viewDir = normalize(eyePos - v_fragPos); vec3 up = vec3(0.,gridPointDelta,texture2D(displace_map,vec2(v_uv.x ,v_uv.y + gridPointDelta)).x*(1./1.));
vec3 down = vec3(0.,-gridPointDelta,texture2D(displace_map,vec2(v_uv.x ,v_uv.y - gridPointDelta)).x*(1./1.));
// Diffuse lighting
float diff = max(dot(norm, sunDirection), 0.0); //vec3 tangent = normalize(right - currPoint);
//vec3 biTangent = normalize(up - currPoint);
vec3 tangent = normalize(vec3(gridPointDelta,0.,right.z-left.z));
vec3 biTangent = normalize(vec3(0.,gridPointDelta,down.z-up.z));
//vec3 normal = biTangent;
vec3 normal = cross(tangent, biTangent);
vec3 norm = normalize(normal);
norm.y *= -1.; //Normal y direction is somehow inverted
//vec3 lightDir = normalize(lightPos - v_fragPos);
vec3 lightDir = normalize(-vec3(0.0,.0,-1.)); //sun shines in drection of -z
float diff = max(dot(norm,lightDir),0.0);
vec3 diffuse = diff * lightColor; vec3 diffuse = diff * lightColor;
vec3 result = (diffuse) * vec3(0.0,0.0,1.0);
// Schlick's approximation to Fresnel factor //Old lightning
float R0 = 0.02; vec3 toCameraVector = normalize(v_fragPos - eyePos);
float fresnel = R0 + (1.0 - R0) * pow(1.0 - max(dot(norm, viewDir), 0.0), 5.0); vec3 reflec = normalize(reflect(toCameraVector, norm));
// Deep and shallow water colors //Schlicks approximation to Fresnelfactor
vec3 deepColor = vec3(0.0, 0.08, 0.15); float n1 = 1., n2 = 1.33333;
vec3 shallowColor = vec3(0.0, 0.35, 0.45); float R0 = pow((n1-n2)/(n1+n2), 2.);
vec3 skyColor = vec3(0.55, 0.7, 0.9); // Match skybox horizon color float fresnel = R0 + (1. - R0)*pow((1.-dot(norm,reflec)),5.) ;
vec3 foamColor = vec3(0.95, 0.98, 1.0);
// Blend between deep and shallow based on wave height
float heightFactor = clamp(v_waveHeight * 2.0 + 0.5, 0.0, 1.0);
vec3 oceanColor = mix(deepColor, shallowColor, heightFactor);
// Sun glitter - uses wave normals for natural sparkle from fine surface detail
vec3 reflectDir = reflect(-sunDirection, norm);
float specAngle = max(dot(viewDir, reflectDir), 0.0);
// Smooth base specular
float specBase = pow(specAngle, 64.0) * 0.4;
// Medium highlights
float specMid = pow(specAngle, 256.0) * 1.2;
// Sharp glitter peaks
float specSharp = pow(specAngle, 1024.0) * 3.0;
vec3 specular = (specBase + specMid + specSharp) * lightColor * uGlitterIntensity;
// Subsurface scattering
float sssDot = max(dot(viewDir, -sunDirection), 0.0);
float sssWaveContribution = clamp(v_waveHeight + 0.3, 0.0, 1.0);
float sssNormalContribution = pow(1.0 - max(dot(norm, sunDirection), 0.0), 2.0);
float sss = pow(sssDot, 3.0) * sssWaveContribution * sssNormalContribution * 1.5;
vec3 sssColor = vec3(0.1, 0.6, 0.5) * sss;
// Rim SSS effect
float rimSSS = pow(1.0 - max(dot(norm, viewDir), 0.0), 3.0) * 0.3;
vec3 rimColor = vec3(0.0, 0.4, 0.4) * rimSSS * heightFactor;
// Foam with texture - foam persists longer //vec3 waterColor = vec3(34./255.,154./255.,211./255.);
vec2 foamUV = v_fragPos.xy * 1.5; vec3 oceanColor = vec3(0,.4,.4); // under-sea colour
float foamPattern = foamNoise(foamUV); vec3 skyColor = vec3(1.,1.,1.);
// Create foam patches with softer edges //Subsurface scattering
float foamThreshold = 1.0 - v_foamFactor * 1.2 * uFoamIntensity; vec3 sssSun = vec3(0.,-5.,-7.0);
float foam = smoothstep(foamThreshold, foamThreshold + 0.35, foamPattern); vec3 tosssSunVec = normalize(sssSun - v_fragPos);
vec3 tosssSun = normalize(vec3(0.0,-100.,1.));
// Add some bubble-like spots with softer transition float ssDistortion = 0.1;
float bubbles = smoothstep(0.65, 0.85, noise(foamUV * 15.0)) * v_foamFactor; float sssIntensity = 1.;
foam = clamp(foam + bubbles * 0.3, 0.0, 1.0); vec3 halfWay = normalize(tosssSun+norm*ssDistortion);
float ssScateringCoef = pow(clamp(dot(toCameraVector,-halfWay),0.0,1.0),5.) * sssIntensity;
// Softer edge fade based on foam factor //Sun glittering
foam *= smoothstep(0.0, 0.25, v_foamFactor); float glitterFactor = max(0.0,dot(tosssSunVec,reflect(-toCameraVector,norm)));
if(!(glitterFactor > 0.98)) {
// Additional soft fade at foam edges and fade out at distance glitterFactor = 0.0;
foam = pow(foam, 0.7) * uFoamIntensity * v_distanceFade; }
// Combine all lighting //gl_FragColor = vec4(oceanColor + lightColor * glitterFactor,1.0);
vec3 reflectedColor = mix(oceanColor, skyColor, fresnel); //gl_FragColor=vec4(clamp(oceanColor + (oceanColor*ssScateringCoef),0.,1.0),1.0); //Display subsurfacecatterting component
vec3 waterColor = reflectedColor * clamp(diffuse, 0.3, 1.0) + specular + sssColor + rimColor; //gl_FragColor = vec4((mix(oceanColor,skyColor,fresnel).xyz), 1.); //Just display reflection component
//gl_FragColor = vec4(diffuse * oceanColor,1.0); //Render only diffuse component
// Blend foam on top with slight transparency variation //gl_FragColor = vec4(normal,1.0); //show Normal map
vec3 finalColor = mix(waterColor, foamColor * clamp(diffuse + 0.4, 0.0, 1.0), foam * 0.85); //gl_FragColor = vec4(displace.x,displace.x,displace.x,1.0); //Show Perlin Noise texture deactivate vertex distrotion before
gl_FragColor = vec4((clamp(diffuse,0.97,1.0) * (mix(oceanColor + (oceanColor*ssScateringCoef),skyColor*0.8,fresnel).xyz))+ lightColor * glitterFactor, 1.0); //All combined
// Atmospheric fog for distant water - blends to horizon
float dist = length(eyePos - v_fragPos);
// Exponential fog with aggressive horizon fade
float fogFactor = exp(-dist * 0.04);
// Fully fade at stretched horizon vertices
float horizonFade = smoothstep(40.0, 80.0, dist);
fogFactor *= (1.0 - horizonFade);
fogFactor = clamp(fogFactor, 0.0, 1.0);
// Horizon color must exactly match skybox horizon
vec3 horizonColor = vec3(0.55, 0.7, 0.9);
finalColor = mix(horizonColor, finalColor, fogFactor);
gl_FragColor = vec4(finalColor, 1.0);
} }
</script> </script>
<script id="default-vs" type="x-shader/x-vertex"> <script id="default-vs" type="x-shader/x-vertex">
precision mediump float; attribute vec3 positionAttr;
attribute vec2 positionAttr; // Grid position in [0,1] range
uniform mat4 view; uniform mat4 view;
uniform mat4 model;
uniform mat4 projection; uniform mat4 projection;
uniform mat4 uProjectorMatrix; // Inverse projector view-proj uniform sampler2D displace_map;
uniform mat4 uRangeMatrix; // Range conversion matrix
uniform float uTime;
uniform float uWaveHeight;
uniform float uWaveSpeed;
uniform vec3 eyePos;
uniform float uHorizonClipY; // Y position of horizon in clip space [-1,1]
varying vec2 v_uv;
varying vec3 v_fragPos; varying vec3 v_fragPos;
varying vec3 v_normal;
varying float v_waveHeight;
varying float v_foamFactor;
varying float v_distanceFade;
// ============ Simplex Noise Functions ============
// Permutation polynomial: (34x^2 + x) mod 289
vec3 permute(vec3 x) { return mod(((x*34.0)+1.0)*x, 289.0); }
// 2D Simplex noise
float snoise(vec2 v) {
const vec4 C = vec4(0.211324865405187, 0.366025403784439,
-0.577350269189626, 0.024390243902439);
vec2 i = floor(v + dot(v, C.yy));
vec2 x0 = v - i + dot(i, C.xx);
vec2 i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0);
vec4 x12 = x0.xyxy + C.xxzz;
x12.xy -= i1;
i = mod(i, 289.0);
vec3 p = permute(permute(i.y + vec3(0.0, i1.y, 1.0)) + i.x + vec3(0.0, i1.x, 1.0));
vec3 m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0);
m = m*m; m = m*m;
vec3 x = 2.0 * fract(p * C.www) - 1.0;
vec3 h = abs(x) - 0.5;
vec3 ox = floor(x + 0.5);
vec3 a0 = x - ox;
m *= 1.79284291400159 - 0.85373472095314 * (a0*a0 + h*h);
vec3 g;
g.x = a0.x * x0.x + h.x * x0.y;
g.yz = a0.yz * x12.xz + h.yz * x12.yw;
return 130.0 * dot(m, g);
}
// Fractal Brownian Motion (FBM) using simplex noise
float fbm(vec2 p, float time, int octaves, float lacunarity, float gain) {
float sum = 0.0;
float amp = 1.0;
float freq = 1.0;
float maxAmp = 0.0;
for (int i = 0; i < 6; i++) {
if (i >= octaves) break;
// Add subtle animation
vec2 animatedP = p * freq + vec2(time * 0.5 * float(i + 1), time * 0.3);
sum += snoise(animatedP) * amp;
maxAmp += amp;
amp *= gain;
freq *= lacunarity;
}
return sum / maxAmp;
}
// Get noise-based displacement and normal contribution
vec3 noiseWave(vec2 pos, float time, float scale, float amplitude, out vec3 normalContrib) {
vec2 p = pos * scale;
// Sample noise at offset positions for gradient/normal calculation
float eps = 0.1;
float h = fbm(p, time, 4, 2.0, 0.5) * amplitude;
float hx = fbm(p + vec2(eps, 0.0), time, 4, 2.0, 0.5) * amplitude;
float hy = fbm(p + vec2(0.0, eps), time, 4, 2.0, 0.5) * amplitude;
// Calculate normal from height differences
vec3 tangent = normalize(vec3(eps, 0.0, hx - h));
vec3 binormal = normalize(vec3(0.0, eps, hy - h));
normalContrib = normalize(cross(binormal, tangent));
return vec3(0.0, h, 0.0); // Only vertical displacement for noise
}
// ============ Gerstner Wave Function ============
// Gerstner wave function - higher steepness = spikier waves
vec3 gerstnerWave(vec2 pos, float time, vec2 direction, float steepness, float wavelength, out vec3 tangent, out vec3 binormal) {
float k = 2.0 * 3.14159 / wavelength;
float c = sqrt(9.8 / k);
vec2 d = normalize(direction);
float f = k * (dot(d, pos) - c * time);
float a = steepness / k;
tangent = vec3(
1.0 - steepness * d.x * d.x * sin(f),
steepness * d.x * cos(f),
-steepness * d.x * d.y * sin(f)
);
binormal = vec3(
-steepness * d.x * d.y * sin(f),
steepness * d.y * cos(f),
1.0 - steepness * d.y * d.y * sin(f)
);
return vec3(
d.x * a * cos(f),
a * sin(f),
d.y * a * cos(f)
);
}
// Project grid point onto ocean plane using projector
vec3 projectToOcean(vec2 gridPos, out float horizonBlend, out vec3 rayDirection) {
// Transform grid position [0,1] through range matrix to projector space [-1,1]
vec4 clipPos = uRangeMatrix * vec4(gridPos, 0.0, 1.0);
// Get two points along the projection ray (near and far planes)
vec4 nearPoint = uProjectorMatrix * vec4(clipPos.xy, -1.0, 1.0);
vec4 farPoint = uProjectorMatrix * vec4(clipPos.xy, 1.0, 1.0);
// Perspective divide to get world positions
nearPoint /= nearPoint.w;
farPoint /= farPoint.w;
vec3 rayOrigin = nearPoint.xyz;
vec3 rayDir = normalize(farPoint.xyz - nearPoint.xyz);
rayDirection = rayDir;
// The skybox horizon is where rayDir.z = 0 (looking horizontally)
float angleToHorizon = -rayDir.z; // 0 at horizon, negative = looking up, positive = looking down
// If ray is pointing up or nearly horizontal, this vertex approaches horizon
if (angleToHorizon <= 0.001) {
horizonBlend = 1.0;
// Project in horizontal direction at ocean level
vec2 hDir = length(rayDir.xy) > 0.001 ? normalize(rayDir.xy) : vec2(1.0, 0.0);
return vec3(rayOrigin.xy + hDir * 5000.0, 0.0);
}
// Ray is pointing down - intersect with ocean plane (Z = 0)
float t = -rayOrigin.z / rayDir.z;
if (t < 0.0) {
horizonBlend = 1.0;
vec2 hDir = length(rayDir.xy) > 0.001 ? normalize(rayDir.xy) : vec2(1.0, 0.0);
return vec3(rayOrigin.xy + hDir * 5000.0, 0.0);
}
// Camera height affects max render distance
// Higher camera = need to limit distance more to avoid precision issues
float cameraHeight = max(eyePos.z, 0.5);
// Base max distance scales with camera height, but with diminishing returns
// At height 2: maxBase = ~200
// At height 10: maxBase = ~450
// At height 100: maxBase = ~1400
// At height 500: maxBase = ~3100
float maxBase = 100.0 * sqrt(cameraHeight);
// Also limit based on angle - shallow angles get much shorter max distance
float angleScale = smoothstep(0.001, 0.3, angleToHorizon); // 0 at horizon, 1 at ~17 degrees down
float maxT = maxBase * (0.1 + 0.9 * angleScale);
maxT = max(maxT, 50.0); // Minimum distance
// Smooth horizon blend based on angle AND distance
horizonBlend = 1.0 - smoothstep(0.001, 0.05, angleToHorizon);
// If t exceeds limit, increase horizon blend
if (t > maxT * 0.8) {
float distBlend = smoothstep(maxT * 0.8, maxT, t);
horizonBlend = max(horizonBlend, distBlend);
}
t = min(t, maxT);
// Compute world position
vec3 worldPos = rayOrigin + rayDir * t;
return worldPos;
}
void main(void) { void main(void) {
// Project grid point onto ocean plane vec4 displace = texture2D(displace_map, vec2(positionAttr.x,positionAttr.y));
float horizonBlend; vec4 worldPos = model * vec4(positionAttr.x,positionAttr.y,positionAttr.z + displace.x, 1.0);
vec3 rayDir;
vec3 worldPos3 = projectToOcean(positionAttr, horizonBlend, rayDir);
vec4 worldPos = vec4(worldPos3, 1.0);
// Grid is on XY plane, Z is up
vec2 pos = worldPos.xy;
float time = uTime * 0.0004 * uWaveSpeed;
// Calculate distance from camera for wave fading
float distToCamera = length(worldPos.xyz - eyePos);
float waveFade = exp(-distToCamera * 0.015); // Gradual fade over distance
waveFade = clamp(waveFade, 0.0, 1.0);
// Fade out waves at horizon to prevent edge breakup
waveFade *= (1.0 - horizonBlend);
v_distanceFade = waveFade;
float heightMod = uWaveHeight * waveFade;
vec3 displacement = vec3(0.0);
vec3 tangent = vec3(1.0, 0.0, 0.0);
vec3 binormal = vec3(0.0, 0.0, 1.0);
vec3 t, b;
// ============ GERSTNER WAVES - Large Scale Motion ============
// Primary ocean swells
displacement += gerstnerWave(pos, time, vec2(1.0, 0.2), 0.45 * heightMod, 8.0, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
displacement += gerstnerWave(pos, time * 1.1, vec2(0.4, 1.0), 0.38 * heightMod, 6.0, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
// Secondary waves
displacement += gerstnerWave(pos, time * 0.9, vec2(-0.6, 0.8), 0.28 * heightMod, 4.0, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
displacement += gerstnerWave(pos, time * 1.15, vec2(0.8, -0.5), 0.22 * heightMod, 3.0, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
// Medium waves
displacement += gerstnerWave(pos, time, vec2(-0.3, -0.9), 0.18 * heightMod, 2.0, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
// ============ PERLIN/SIMPLEX NOISE - Small Scale Detail ============
// Only apply noise detail when close enough to see it
float detailFade = smoothstep(200.0, 50.0, distToCamera);
if (detailFade > 0.01) {
vec3 noiseNormal;
// Medium frequency noise ripples
vec3 noise1 = noiseWave(pos, time * 0.8, 0.3, 0.15 * heightMod * detailFade, noiseNormal);
displacement += noise1;
tangent += (noiseNormal - vec3(0.0, 0.0, 1.0)) * 0.3 * detailFade;
// High frequency noise for fine detail
vec3 noise2 = noiseWave(pos, time * 1.2, 0.8, 0.08 * heightMod * detailFade, noiseNormal);
displacement += noise2;
tangent += (noiseNormal - vec3(0.0, 0.0, 1.0)) * 0.2 * detailFade;
// Very fine ripples
vec3 noise3 = noiseWave(pos, time * 1.5, 2.0, 0.04 * heightMod * detailFade, noiseNormal);
displacement += noise3;
tangent += (noiseNormal - vec3(0.0, 0.0, 1.0)) * 0.1 * detailFade;
}
// Store wave height for fragment shader
v_waveHeight = displacement.y;
// Calculate foam factor - foam appears on the FRONT/leading edge of waves
// When wave is rising (tangent.y > 0), that's where foam should appear
float waveRising = smoothstep(0.0, 0.3, tangent.y + binormal.y);
float foamFromHeight = smoothstep(0.0, 0.25, displacement.y);
float waveSlope = length(vec2(tangent.y, binormal.y));
float foamFromSlope = smoothstep(0.2, 0.6, waveSlope);
// Foam appears where wave is high AND rising (leading edge / crest)
v_foamFactor = clamp((foamFromHeight * waveRising * 1.2 + foamFromSlope * 0.3), 0.0, 1.0);
// Apply displacement - Z is up, XY is horizontal plane
worldPos.x += displacement.x;
worldPos.y += displacement.z;
worldPos.z += displacement.y; // Height displacement
// Calculate normal from tangent and binormal
// Blend normal towards flat (0, 0, 1) based on distance
vec3 normal = normalize(cross(binormal, tangent));
vec3 flatNormal = vec3(0.0, 0.0, 1.0);
normal = mix(flatNormal, normal, waveFade);
v_normal = vec3(normal.x, normal.z, normal.y);
// Project back to clip space
gl_Position = projection * view * worldPos; gl_Position = projection * view * worldPos;
// For vertices near the horizon, smoothly blend Y towards the horizon line
// This ensures ocean meets skybox without gaps or discontinuities
if (horizonBlend > 0.0) {
float targetY = uHorizonClipY * gl_Position.w;
// Use squared blend for smoother transition
float smoothBlend = horizonBlend * horizonBlend;
gl_Position.y = mix(gl_Position.y, targetY, smoothBlend);
// Push depth towards far plane for horizon vertices
gl_Position.z = mix(gl_Position.z, gl_Position.w * 0.9999, smoothBlend);
}
v_fragPos = worldPos.xyz; v_fragPos = worldPos.xyz;
v_uv = positionAttr.xy;
} }
</script> </script>
<script id="sky-fs" type="x-shader/x-fragment"> <script id="sky-fs" type="x-shader/x-fragment">
@@ -731,23 +349,30 @@
gl_Position = pos; gl_Position = pos;
} }
</script> </script>
</head> </head>
<body> <body>
<canvas id="window"></canvas> <canvas id="window"></canvas>
<div id="controls"> <div id="controls">
<h3>🌊 Ocean Controls</h3> <h3>🌊 Ocean Controls</h3>
<div class="control-group"> <div class="control-group">
<strong>Camera Rotation:</strong><br> <strong>Camera Mode:</strong> <span class="key">C</span> (FPS/Orbital)<br>
<span class="key">W</span><span class="key">A</span><span class="key">S</span><span class="key">D</span> or Arrow Keys <span id="current-camera-mode" style="font-size: 12px; color: #aaa;">Current: FPS</span>
</div> </div>
<div class="control-group"> <div class="control-group">
<strong>Zoom:</strong><br> <strong>FPS Camera:</strong><br>
<span class="key">Q</span> / <span class="key">E</span> or <span class="key">+</span> / <span class="key">-</span> <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>
<div class="control-group"> <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>
<div class="control-group"> <div class="control-group">
<strong>Reset:</strong> <span class="key">R</span> <strong>Reset:</strong> <span class="key">R</span>
@@ -755,74 +380,49 @@
<div class="control-group"> <div class="control-group">
<strong>Toggle Help:</strong> <span class="key">H</span> <strong>Toggle Help:</strong> <span class="key">H</span>
</div> </div>
<div class="control-group" style="margin-top: 10px; padding-top: 10px; border-top: 1px solid rgba(255, 255, 255, 0.2);">
<button id="wireframe-toggle" style="background: rgba(255, 255, 255, 0.2); color: white; border: none; padding: 8px 12px; border-radius: 4px; cursor: pointer; width: 100%; font-size: 13px;">Wireframe: OFF</button>
</div>
<div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid rgba(255, 255, 255, 0.2);">
<strong>Wave Settings</strong>
<div class="slider-group">
<label>Wave Height <span class="slider-value" id="wave-height-val">1.0</span></label>
<input type="range" id="wave-height" min="0" max="2" step="0.1" value="1">
</div>
<div class="slider-group">
<label>Wave Speed <span class="slider-value" id="wave-speed-val">1.0</span></label>
<input type="range" id="wave-speed" min="0.1" max="3" step="0.1" value="1">
</div>
</div>
<div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid rgba(255, 255, 255, 0.2);">
<strong>Foam & Glitter</strong>
<div class="slider-group">
<label>Foam Intensity <span class="slider-value" id="foam-intensity-val">1.0</span></label>
<input type="range" id="foam-intensity" min="0" max="2" step="0.1" value="1">
</div>
<div class="slider-group">
<label>Glitter Intensity <span class="slider-value" id="glitter-intensity-val">1.0</span></label>
<input type="range" id="glitter-intensity" min="0" max="3" step="0.1" value="1">
</div>
</div>
</div> </div>
<button id="toggle-controls">Toggle Controls (H)</button> <button id="toggle-controls">Toggle Controls (H)</button>
<div id="fps-counter">FPS: 0</div> <div id="fps-counter">FPS: 0</div>
<script type="module" src="/src/main.ts"></script> <script type="module" src="/src/main.ts"></script>
<script> <script>
// Toggle controls visibility // Toggle controls visibility
const controls = document.getElementById('controls'); const controls = document.getElementById('controls');
const toggleBtn = document.getElementById('toggle-controls'); const toggleBtn = document.getElementById('toggle-controls');
const cameraModeDisplay = document.getElementById('current-camera-mode');
toggleBtn.addEventListener('click', () => { toggleBtn.addEventListener('click', () => {
controls.classList.toggle('hidden'); controls.classList.toggle('hidden');
}); });
window.addEventListener('keydown', (evt) => { window.addEventListener('keydown', (evt) => {
if (evt.key === 'h' || evt.key === 'H') { if (evt.key === 'h' || evt.key === 'H') {
controls.classList.toggle('hidden'); 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);
}
}); });
// Wireframe toggle // Listen for custom camera mode toggle events from UI
const wireframeBtn = document.getElementById('wireframe-toggle'); window.addEventListener('toggleCameraMode', () => {
wireframeBtn.addEventListener('click', () => { const cameraMode = document.getElementById('camera-mode');
window.dispatchEvent(new CustomEvent('toggleWireframe')); if (cameraMode && cameraModeDisplay) {
const mode = cameraMode.textContent.replace('Camera: ', '');
cameraModeDisplay.textContent = `Current: ${mode}`;
}
}); });
// Slider controls
function setupSlider(id, eventName) {
const slider = document.getElementById(id);
const valueDisplay = document.getElementById(id + '-val');
slider.addEventListener('input', (e) => {
const value = parseFloat(e.target.value);
valueDisplay.textContent = value.toFixed(1);
window.dispatchEvent(new CustomEvent(eventName, { detail: value }));
});
}
setupSlider('wave-height', 'waveHeightChange');
setupSlider('wave-speed', 'waveSpeedChange');
setupSlider('foam-intensity', 'foamIntensityChange');
setupSlider('glitter-intensity', 'glitterIntensityChange');
</script> </script>
</body> </body>

View File

@@ -1,87 +1,63 @@
import { vec3, mat4, vec4 } from 'gl-matrix'; import { vec3, mat4, vec4 } from 'gl-matrix';
import { ICamera } from './ICamera';
/** FPS-style flight camera with free movement */ /** Orbital camera that rotates around the world origin. */
export class Camera { export class OrbitalCamera implements ICamera {
pos: vec3; pos: vec3;
target: vec3; target: vec3;
up: vec3; up: vec3;
// FPS camera angles (in radians) xRot: number;
pitch: number; // Up/down rotation yRot: number;
yaw: number; // Left/right rotation offset: number;
// Direction vectors
forward: vec3;
right: vec3;
constructor() { constructor() {
this.pos = vec3.create(); this.pos = vec3.create();
vec3.set(this.pos, 0.0, -3.0, 2.0); // Start above and behind origin vec3.set(this.pos, 0.0, 0.0, 0.0);
this.target = vec3.create(); this.target = vec3.create();
vec3.set(this.target, 0.0, 0.0, 0.0);
this.up = vec3.create(); this.up = vec3.create();
vec3.set(this.up, 0.0, 0.0, 1.0); // Z is up vec3.set(this.up, 0.0, 1.0, 0.0);
this.forward = vec3.create(); this.xRot = 0.0;
this.right = vec3.create(); this.yRot = 0.0;
this.pitch = -0.3; // Looking slightly down this.offset = 0.0;
this.yaw = Math.PI / 2; // Looking toward +Y
this.updateVectors();
} }
/** Rotate camera by mouse delta */ setRotationX(rotX: number): void {
rotate(deltaX: number, deltaY: number, sensitivity: number = 0.003): void { this.xRot = rotX;
this.yaw -= deltaX * sensitivity; this.updatePos();
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 */ setRotationY(rotY: number): void {
moveForward(amount: number): void { this.yRot = rotY;
vec3.scaleAndAdd(this.pos, this.pos, this.forward, amount); this.updatePos();
this.updateVectors();
} }
moveRight(amount: number): void { /** Sets the offset to world origin. */
vec3.scaleAndAdd(this.pos, this.pos, this.right, amount); setOffset(off: number): void {
this.updateVectors(); this.offset = off;
this.updatePos();
} }
moveUp(amount: number): void { /** Recalculates the position according to xy-rotation and offset. */
// Move along world Z axis private updatePos(): void {
this.pos[2] += amount; const transformation: mat4 = mat4.create();
this.updateVectors(); mat4.identity(transformation);
}
/** Move in the actual look direction (including vertical) */ //2. xy-Rotation
moveInLookDirection(amount: number): void { mat4.rotateX(transformation, transformation, this.xRot);
vec3.scaleAndAdd(this.pos, this.pos, this.forward, amount); mat4.rotateY(transformation, transformation, this.yRot);
this.updateVectors();
}
/** Update direction vectors from pitch/yaw */ //1. Translation
private updateVectors(): void { const translation = vec3.create();
// Calculate forward vector from pitch and yaw vec3.set(translation, 0.0, 0.0, this.offset);
// Z is up, so we use different axis mapping mat4.translate(transformation, transformation, translation);
this.forward[0] = Math.cos(this.pitch) * Math.cos(this.yaw);
this.forward[1] = Math.cos(this.pitch) * Math.sin(this.yaw); const temp: vec4 = vec4.create();
this.forward[2] = Math.sin(this.pitch); vec4.set(temp, 0.0, 0.0, 0.0, 1.0);
vec3.normalize(this.forward, this.forward); vec4.transformMat4(temp, temp, transformation);
// Right vector is perpendicular to forward and world up vec3.set(this.pos, temp[0], temp[1], temp[2]);
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 { getViewMatrix(): mat4 {
@@ -92,6 +68,9 @@ export class Camera {
/** Get view direction for LOD calculations */ /** Get view direction for LOD calculations */
getViewDirection(): vec3 { getViewDirection(): vec3 {
return vec3.clone(this.forward); 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);
}
}

View File

@@ -1,35 +1,23 @@
/** Grid for the water surface */ /** Grid for the water surface */
export class Grid { export class Grid {
private indices: number[] = []; private indices: number[] = [];
private lineIndices: number[] = [];
private vertices: number[] = []; private vertices: number[] = [];
private vao: WebGLVertexArrayObject | null = null; private vao: WebGLVertexArrayObject | null = null;
private lineVao: WebGLVertexArrayObject | null = null;
private size: number; private size: number;
private offsetX: number;
private offsetY: number;
private scale: number;
constructor(size: number = 128, offsetX: number = 0, offsetY: number = 0, scale: number = 1) { constructor(size: number = 128) {
this.size = size; this.size = size;
this.offsetX = offsetX;
this.offsetY = offsetY;
this.scale = scale;
} }
generate(): void { generate(): void {
this.indices = []; this.indices = [];
this.lineIndices = [];
this.vertices = []; this.vertices = [];
for (let j = 0; j <= this.size; ++j) { for (let j = 0; j <= this.size; ++j) {
for (let i = 0; i <= this.size; ++i) { for (let i = 0; i <= this.size; ++i) {
// Generate Vertices normalized to 0-1, then scale and offset // Generate Vertices
// Grid is on XY plane (horizontal), Z is up const x = i / this.size;
const u = i / this.size; const y = j / this.size;
const v = j / this.size;
const x = (u - 0.5) * this.scale + this.offsetX;
const y = (v - 0.5) * this.scale + this.offsetY;
const z = 0; const z = 0;
this.vertices.push(x, y, z); this.vertices.push(x, y, z);
@@ -47,16 +35,6 @@ export class Grid {
this.indices.push(row2 + i + 1); this.indices.push(row2 + i + 1);
this.indices.push(row2 + i); this.indices.push(row2 + i);
} }
// Generate line indices for wireframe
if (i < this.size) {
const currentVertex = j * (this.size + 1) + i;
this.lineIndices.push(currentVertex, currentVertex + 1);
}
if (j < this.size) {
const currentVertex = j * (this.size + 1) + i;
this.lineIndices.push(currentVertex, currentVertex + (this.size + 1));
}
} }
} }
} }
@@ -64,7 +42,6 @@ export class Grid {
initVAO(gl: WebGL2RenderingContext): void { initVAO(gl: WebGL2RenderingContext): void {
this.generate(); this.generate();
// Create VAO for filled triangles
this.vao = gl.createVertexArray(); this.vao = gl.createVertexArray();
gl.bindVertexArray(this.vao); gl.bindVertexArray(this.vao);
@@ -79,28 +56,10 @@ export class Grid {
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 3 * Float32Array.BYTES_PER_ELEMENT, 0); gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 3 * Float32Array.BYTES_PER_ELEMENT, 0);
gl.enableVertexAttribArray(0); gl.enableVertexAttribArray(0);
gl.bindVertexArray(null); gl.bindVertexArray(null);
// Create VAO for wireframe lines
this.lineVao = gl.createVertexArray();
gl.bindVertexArray(this.lineVao);
gl.bindBuffer(gl.ARRAY_BUFFER, vboGrid);
const iboLine: WebGLBuffer | null = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, iboLine);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint32Array(this.lineIndices), gl.STATIC_DRAW);
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 3 * Float32Array.BYTES_PER_ELEMENT, 0);
gl.enableVertexAttribArray(0);
gl.bindVertexArray(null);
} }
draw(gl: WebGL2RenderingContext, wireframe: boolean = false): void { draw(gl: WebGL2RenderingContext): void {
if (wireframe && this.lineVao) { if (this.vao) {
gl.bindVertexArray(this.lineVao);
gl.drawElements(gl.LINES, this.lineIndices.length, gl.UNSIGNED_INT, 0);
gl.bindVertexArray(null);
} else if (this.vao) {
gl.bindVertexArray(this.vao); gl.bindVertexArray(this.vao);
gl.drawElements(gl.TRIANGLES, this.indices.length, gl.UNSIGNED_INT, 0); gl.drawElements(gl.TRIANGLES, this.indices.length, gl.UNSIGNED_INT, 0);
gl.bindVertexArray(null); gl.bindVertexArray(null);

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;
}

View File

@@ -1,167 +0,0 @@
import { vec3, vec4, mat4 } from 'gl-matrix';
/**
* Projected Grid Ocean - Based on the projected grid algorithm.
* Uses a separate projector that can be adjusted to avoid backfiring.
* The grid is created in projector space and projected onto the ocean plane.
*/
export class ProjectedOcean {
private vao: WebGLVertexArrayObject | null = null;
private lineVao: WebGLVertexArrayObject | null = null;
private indexBuffer: WebGLBuffer | null = null;
private vertexBuffer: WebGLBuffer | null = null;
private indexCount: number = 0;
private lineIndexCount: number = 0;
// Grid resolution
private readonly GRID_SIZE_X = 400;
private readonly GRID_SIZE_Y = 400;
// Ocean plane parameters (Z = 0 plane, normal pointing up)
private readonly OCEAN_LEVEL = 0.0;
private readonly MAX_WAVE_HEIGHT = 1.5; // Maximum displacement above ocean level
private readonly MIN_WAVE_HEIGHT = -0.5; // Maximum displacement below ocean level
// Projector parameters
private readonly MIN_PROJECTOR_HEIGHT = 5.0; // Minimum height above upper bound
// Matrices for the shader
public projectorMatrix: mat4 = mat4.create();
public rangeMatrix: mat4 = mat4.create();
constructor() {}
/** Generate the grid vertices (in [0,1] range) */
initVAO(gl: WebGL2RenderingContext): void {
const vertices: number[] = [];
const indices: number[] = [];
// Create grid in [0,1] range - will be transformed by projector matrix
for (let y = 0; y <= this.GRID_SIZE_Y; y++) {
for (let x = 0; x <= this.GRID_SIZE_X; x++) {
const u = x / this.GRID_SIZE_X;
const v = y / this.GRID_SIZE_Y;
vertices.push(u, v);
}
}
// Create indices (counter-clockwise winding when viewed from above, Z up)
for (let y = 0; y < this.GRID_SIZE_Y; y++) {
for (let x = 0; x < this.GRID_SIZE_X; x++) {
const topLeft = y * (this.GRID_SIZE_X + 1) + x;
const topRight = topLeft + 1;
const bottomLeft = (y + 1) * (this.GRID_SIZE_X + 1) + x;
const bottomRight = bottomLeft + 1;
// CCW winding for front face visible from +Z (above)
indices.push(topLeft, topRight, bottomLeft);
indices.push(topRight, bottomRight, bottomLeft);
}
}
this.indexCount = indices.length;
// Create line indices for wireframe
const lineIndices: number[] = [];
for (let y = 0; y <= this.GRID_SIZE_Y; y++) {
for (let x = 0; x <= this.GRID_SIZE_X; x++) {
const currentVertex = y * (this.GRID_SIZE_X + 1) + x;
// Horizontal line
if (x < this.GRID_SIZE_X) {
lineIndices.push(currentVertex, currentVertex + 1);
}
// Vertical line
if (y < this.GRID_SIZE_Y) {
lineIndices.push(currentVertex, currentVertex + (this.GRID_SIZE_X + 1));
}
}
}
this.lineIndexCount = lineIndices.length;
// Create vertex buffer (shared between both VAOs)
this.vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// Create VAO for filled triangles
this.vao = gl.createVertexArray();
gl.bindVertexArray(this.vao);
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
this.indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint32Array(indices), gl.STATIC_DRAW);
gl.bindVertexArray(null);
// Create VAO for wireframe lines
this.lineVao = gl.createVertexArray();
gl.bindVertexArray(this.lineVao);
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
const lineIndexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, lineIndexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint32Array(lineIndices), gl.STATIC_DRAW);
gl.bindVertexArray(null);
}
/**
* Update the projector matrices based on camera position.
* We use the camera's own view-projection to ensure screen coverage.
*/
updateProjector(cameraPos: vec3, cameraForward: vec3, viewMatrix: mat4, projMatrix: mat4): void {
// Use camera's view-projection directly
const viewProj = mat4.create();
mat4.multiply(viewProj, projMatrix, viewMatrix);
// Invert to get unprojection matrix
mat4.invert(this.projectorMatrix, viewProj);
// Range matrix maps [0,1] grid to [-1,1] clip space
this.calculateRangeMatrix(cameraPos, viewMatrix, projMatrix, viewProj);
}
/**
* Calculate the range conversion matrix to focus geometry on visible area
* For simplicity and to ensure horizon coverage, we use the full clip space range
*/
private calculateRangeMatrix(
cameraPos: vec3,
viewMatrix: mat4,
projMatrix: mat4,
projectorViewProj: mat4
): void {
// Use full clip space [-1, 1] to ensure complete coverage including horizon
// The grid [0,1] maps to [-1,1] in projector clip space
mat4.identity(this.rangeMatrix);
this.rangeMatrix[0] = 2.0; // Scale X: [0,1] -> [0,2]
this.rangeMatrix[5] = 2.0; // Scale Y: [0,1] -> [0,2]
this.rangeMatrix[10] = 2.0; // Scale Z
this.rangeMatrix[12] = -1.0; // Translate X: [0,2] -> [-1,1]
this.rangeMatrix[13] = -1.0; // Translate Y: [0,2] -> [-1,1]
this.rangeMatrix[14] = -1.0; // Translate Z
}
draw(gl: WebGL2RenderingContext, wireframe: boolean = false): void {
if (wireframe && this.lineVao) {
gl.bindVertexArray(this.lineVao);
gl.drawElements(gl.LINES, this.lineIndexCount, gl.UNSIGNED_INT, 0);
gl.bindVertexArray(null);
} else if (this.vao) {
gl.bindVertexArray(this.vao);
gl.drawElements(gl.TRIANGLES, this.indexCount, gl.UNSIGNED_INT, 0);
gl.bindVertexArray(null);
}
}
getIndexCount(): number {
return this.indexCount;
}
}

View File

@@ -73,13 +73,8 @@ export class Skybox {
draw(gl: WebGL2RenderingContext): void { draw(gl: WebGL2RenderingContext): void {
if (!this.vao) return; if (!this.vao) return;
// Disable face culling for skybox (we're inside the cube)
gl.disable(gl.CULL_FACE);
gl.bindVertexArray(this.vao); gl.bindVertexArray(this.vao);
gl.drawElements(gl.TRIANGLES, this.indexCount, gl.UNSIGNED_SHORT, 0); gl.drawElements(gl.TRIANGLES, this.indexCount, gl.UNSIGNED_SHORT, 0);
gl.bindVertexArray(null); gl.bindVertexArray(null);
gl.enable(gl.CULL_FACE);
} }
} }

View File

@@ -1,7 +1,7 @@
// Configuration Constants // Configuration Constants
export const GRID_SIZE = 128; export const GRID_SIZE = 128;
export const NOISE_TEXTURE_WIDTH = 1024; export const NOISE_TEXTURE_WIDTH = 256;
export const NOISE_TEXTURE_HEIGHT = 1024; export const NOISE_TEXTURE_HEIGHT = 256;
export const CANVAS_WIDTH = 800; export const CANVAS_WIDTH = 800;
export const CANVAS_HEIGHT = 600; export const CANVAS_HEIGHT = 600;
export const FOV = 1.0; export const FOV = 1.0;

View File

@@ -1,6 +1,8 @@
import { vec3, vec4, mat4 } from 'gl-matrix'; import { vec3, mat4 } from 'gl-matrix';
import { Camera } from './Camera'; import { ICamera } from './ICamera';
import { ProjectedOcean } from './OceanLOD'; import { OrbitalCamera } from './Camera';
import { FPSCamera } from './FPSCamera';
import { Grid } from './Grid';
import { Skybox } from './Skybox'; import { Skybox } from './Skybox';
import { createProgram } from './Shader'; import { createProgram } from './Shader';
import * as Config from './constants'; import * as Config from './constants';
@@ -115,8 +117,8 @@ function initFBO() {
// set the filtering so we don't need mips // set the filtering so we don't need mips
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.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_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureFBO, 0); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureFBO, 0);
@@ -137,26 +139,27 @@ var fpsDisplay: HTMLElement | null = null;
/** Input states*/ /** Input states*/
var mouseXVel = 0; var mouseXVel = 0;
var mouseYVel = 0; var mouseYVel = 0;
var keyboardRotationX = 0;
var keyboardRotationY = 0;
var keyboardZoom = 0;
var keysPressed: Set<string> = new Set(); var keysPressed: Set<string> = new Set();
/** Objects and states*/ /** Objects and states*/
var camera: Camera; var camera: ICamera;
var projectedOcean: ProjectedOcean; var orbitalCamera: OrbitalCamera;
var fpsCamera: FPSCamera;
var oceanGrid: Grid;
var skybox: Skybox; var skybox: Skybox;
var wireframeMode = false; var curRotX = Config.CAMERA_DEFAULT_ROT_X;
/** Camera movement speed */ var curRotY = Config.CAMERA_DEFAULT_ROT_Y;
/** Camera modes */
var cameraMode: 'orbital' | 'fps' = 'fps';
var moveSpeed = 0.15; var moveSpeed = 0.15;
var fastMoveSpeed = 0.4; var fastMoveSpeed = 0.4;
/** Ocean shader settings */
var waveHeight = 1.0;
var waveSpeed = 1.0;
var foamIntensity = 1.0;
var glitterIntensity = 1.0;
function drawScene() { function drawScene() {
fps++; fps++;
let now = new Date(); let now = new Date();
let delta = now.getTime() - lastTime; let delta = now.getTime() - lastTime;
timeSpent += delta; timeSpent += delta;
if ((counter += delta) >= Config.FPS_UPDATE_INTERVAL) { if ((counter += delta) >= Config.FPS_UPDATE_INTERVAL) {
counter = 0; counter = 0;
if (fpsDisplay) { if (fpsDisplay) {
@@ -165,35 +168,84 @@ function drawScene() {
fps = 0; fps = 0;
} }
lastTime = now.getTime(); lastTime = now.getTime();
// Two Rendering passes. The first one generates a perlin noise
// Sun direction (matches the one in ocean shader) // texture. Second one uses the textur for vertex displacement
const sunDirection = vec3.fromValues(0.3, 0.5, 0.8); // of a grid representing the water surface.
vec3.normalize(sunDirection, sunDirection);
//--- Render pass -> Skybox first (no depth write) --- //--- First render pass -> Perlin Noise (it updates the perlin noise texture)
{ {
gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.bindFramebuffer(gl.FRAMEBUFFER, perlinNoiseFBO);
gl.viewport(0, 0, perlinNoiseFBOWidth, perlinNoiseFBOHeight);
//Clear buffer content
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);
// There are 7 floating-point values per vertex
let stride = 5 * Float32Array.BYTES_PER_ELEMENT;
// Set up position stream
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, stride, 0);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(1, 2, gl.FLOAT, false, stride, 3 * Float32Array.BYTES_PER_ELEMENT);
gl.enableVertexAttribArray(1);
gl.useProgram(perlinNoiseProgram);
let uTime = gl.getUniformLocation(<WebGLProgram>perlinNoiseProgram, "uTime");
gl.uniform1f(uTime, timeSpent);
gl.drawArrays(gl.TRIANGLES, 0, 6); // Draw fullscreen quad
}
//--- Second render pass -> Geomtry with displacement by perlin noise texture ---
{
gl.bindFramebuffer(gl.FRAMEBUFFER, null); //Bind default framebuffer
gl.viewport(0, 0, viewportWidth, viewportHeight); gl.viewport(0, 0, viewportWidth, viewportHeight);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
var projection = mat4.create(); gl.activeTexture(gl.TEXTURE0); //Binds the texture to 0
mat4.perspective(projection, Config.FOV, viewportWidth / viewportHeight, Config.NEAR_PLANE, Config.FAR_PLANE); gl.bindTexture(gl.TEXTURE_2D, textureFBO);
// Handle FPS camera movement var projection = mat4.create();
handleCameraMovement(); mat4.identity(projection);
mat4.perspective(projection, Config.FOV, viewportWidth / viewportHeight, Config.NEAR_PLANE, Config.FAR_PLANE); //projection mode should actually be camera specific
// Apply mouse rotation
if (mouseXVel !== 0 || mouseYVel !== 0) { // Handle camera movement and rotation based on mode
camera.rotate(mouseXVel, mouseYVel); if (cameraMode === 'fps') {
mouseXVel = 0; // FPS camera - direct movement
mouseYVel = 0; 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(); 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) // Draw skybox first with depth test disabled (always behind everything)
gl.depthMask(false); gl.depthMask(false);
gl.disable(gl.DEPTH_TEST); gl.disable(gl.DEPTH_TEST);
gl.disable(gl.CULL_FACE); // Disable face culling for skybox (we're inside)
gl.useProgram(skyProgram); gl.useProgram(skyProgram);
let sky_view_loc = gl.getUniformLocation(<WebGLProgram>skyProgram, "view"); let sky_view_loc = gl.getUniformLocation(<WebGLProgram>skyProgram, "view");
@@ -206,124 +258,90 @@ function drawScene() {
skybox.draw(gl); skybox.draw(gl);
gl.enable(gl.DEPTH_TEST); gl.enable(gl.DEPTH_TEST);
gl.depthMask(true); gl.depthMask(true);
gl.enable(gl.CULL_FACE); // Re-enable face culling for ocean
gl.cullFace(gl.BACK); // Cull back faces for ocean
// Update projected ocean's projector matrices var model = mat4.create();
projectedOcean.updateProjector(camera.pos, camera.forward, view, projection); mat4.identity(model);
let translationCentering = vec3.create();
vec3.set(translationCentering, -0.5, -0.5, 0.0);
mat4.translate(model, model, translationCentering); //1. First Center the Surface in the origin.
gl.useProgram(defaultProgram); gl.useProgram(defaultProgram);
let view_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "view"); let view_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "view");
gl.uniformMatrix4fv(view_loc, false, view); gl.uniformMatrix4fv(view_loc, false, view);
let model_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "model");
gl.uniformMatrix4fv(model_loc, false, model);
let projection_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "projection"); let projection_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "projection");
gl.uniformMatrix4fv(projection_loc, false, projection); gl.uniformMatrix4fv(projection_loc, false, projection);
let projectorMatrix_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uProjectorMatrix");
gl.uniformMatrix4fv(projectorMatrix_loc, false, projectedOcean.projectorMatrix);
let rangeMatrix_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uRangeMatrix");
gl.uniformMatrix4fv(rangeMatrix_loc, false, projectedOcean.rangeMatrix);
let eye_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "eyePos"); let eye_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "eyePos");
gl.uniform3fv(eye_loc, camera.pos); gl.uniform3fv(eye_loc, camera.pos);
let uTime_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uTime"); //let uTime_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uTime");
gl.uniform1f(uTime_loc, timeSpent); //gl.uniform1f(uTime_loc, timeSpent);
let displacementMap_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "displace_map");
// Ocean shader settings gl.uniform1i(displacementMap_loc, 0); //Get texture from slot 0
let uWaveHeight_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uWaveHeight"); oceanGrid.draw(gl);
gl.uniform1f(uWaveHeight_loc, waveHeight);
let uWaveSpeed_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uWaveSpeed");
gl.uniform1f(uWaveSpeed_loc, waveSpeed);
let uFoamIntensity_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uFoamIntensity");
gl.uniform1f(uFoamIntensity_loc, foamIntensity);
let uGlitterIntensity_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uGlitterIntensity");
gl.uniform1f(uGlitterIntensity_loc, glitterIntensity);
// Calculate horizon Y in clip space
// The skybox horizon is where rayDir.z = 0 (horizontal ray from camera)
// This is a point at infinity in a horizontal direction from the camera
// We need to find where this projects to in clip space
// Get a horizontal direction (camera forward projected onto XY plane)
const horizonDir = vec3.fromValues(camera.forward[0], camera.forward[1], 0);
if (vec3.length(horizonDir) > 0.001) {
vec3.normalize(horizonDir, horizonDir);
} else {
vec3.set(horizonDir, 1, 0, 0);
}
// Transform a direction vector (not a point) to clip space
// For a point at infinity in direction D, its clip space position is:
// lim(t->inf) ViewProj * (eye + t*D) / w
// Which equals ViewProj * D (as a vec4 with w=0), then we look at x/w, y/w
// But since w would be 0 for a direction, we use the view matrix only
// The horizon is where view-space Y = 0 for an infinite point
// In our Z-up system, the horizon is where the ray is horizontal (z=0 in world)
// Transform a horizontal direction through view matrix
const horizonDirView = vec4.fromValues(horizonDir[0], horizonDir[1], 0, 0);
vec4.transformMat4(horizonDirView, horizonDirView, view);
// The Y in clip space where this direction points is based on the view-space direction
// projected through the projection matrix
// For perspective: clipY/clipW = viewY/(-viewZ) * projectionScaleY
// For a horizontal ray at infinity, we can compute where it ends up
// Simpler approach: transform a point very far away in horizon direction
const farDist = 1000000.0;
const horizonPoint = vec4.fromValues(
camera.pos[0] + horizonDir[0] * farDist,
camera.pos[1] + horizonDir[1] * farDist,
camera.pos[2], // Same height as camera - this is the horizon!
1
);
const viewProj = mat4.create();
mat4.multiply(viewProj, projection, view);
vec4.transformMat4(horizonPoint, horizonPoint, viewProj);
const horizonClipY = horizonPoint[3] !== 0 ? horizonPoint[1] / horizonPoint[3] : 0;
let uHorizonClipY_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uHorizonClipY");
gl.uniform1f(uHorizonClipY_loc, horizonClipY);
// Enable backface culling so ocean isn't visible from below
gl.enable(gl.CULL_FACE);
gl.cullFace(gl.BACK);
gl.frontFace(gl.CCW);
projectedOcean.draw(gl, wireframeMode);
gl.disable(gl.CULL_FACE);
} }
requestAnimationFrame(drawScene); requestAnimationFrame(drawScene);
} }
/** Handle FPS camera movement */ /** Handle FPS camera movement */
function handleCameraMovement() { function handleFPSCameraMovement() {
const speed = keysPressed.has('Shift') ? fastMoveSpeed : moveSpeed; const speed = keysPressed.has('Shift') ? fastMoveSpeed : moveSpeed;
// WASD for horizontal movement // WASD for horizontal movement
if (keysPressed.has('w') || keysPressed.has('W')) { if (keysPressed.has('w') || keysPressed.has('W')) {
camera.moveForward(speed); fpsCamera.moveForward(speed);
} }
if (keysPressed.has('s') || keysPressed.has('S')) { if (keysPressed.has('s') || keysPressed.has('S')) {
camera.moveForward(-speed); fpsCamera.moveForward(-speed);
} }
if (keysPressed.has('a') || keysPressed.has('A')) { if (keysPressed.has('a') || keysPressed.has('A')) {
camera.moveRight(-speed); fpsCamera.moveRight(-speed);
} }
if (keysPressed.has('d') || keysPressed.has('D')) { if (keysPressed.has('d') || keysPressed.has('D')) {
camera.moveRight(speed); fpsCamera.moveRight(speed);
} }
// Q/E for vertical movement // Q/E for vertical movement
if (keysPressed.has('q') || keysPressed.has('Q')) { if (keysPressed.has('q') || keysPressed.has('Q')) {
camera.moveUp(-speed); fpsCamera.moveUp(-speed);
} }
if (keysPressed.has('e') || keysPressed.has('E')) { if (keysPressed.has('e') || keysPressed.has('E')) {
camera.moveUp(speed); fpsCamera.moveUp(speed);
} }
// Space to go up, Ctrl to go down // Space to go up, Ctrl to go down
if (keysPressed.has(' ')) { if (keysPressed.has(' ')) {
camera.moveUp(speed); fpsCamera.moveUp(speed);
} }
if (keysPressed.has('Control')) { if (keysPressed.has('Control')) {
camera.moveUp(-speed); fpsCamera.moveUp(-speed);
}
}
/** Handle keyboard input for camera controls */
function handleKeyboardInput() {
keyboardRotationX = 0;
keyboardRotationY = 0;
if (keysPressed.has('w') || keysPressed.has('W') || keysPressed.has('ArrowUp')) {
keyboardRotationX = Config.KEYBOARD_ROTATION_SPEED;
}
if (keysPressed.has('s') || keysPressed.has('S') || keysPressed.has('ArrowDown')) {
keyboardRotationX = -Config.KEYBOARD_ROTATION_SPEED;
}
if (keysPressed.has('a') || keysPressed.has('A') || keysPressed.has('ArrowLeft')) {
keyboardRotationY = Config.KEYBOARD_ROTATION_SPEED;
}
if (keysPressed.has('d') || keysPressed.has('D') || keysPressed.has('ArrowRight')) {
keyboardRotationY = -Config.KEYBOARD_ROTATION_SPEED;
}
if (keysPressed.has('q') || keysPressed.has('Q') || keysPressed.has('+')) {
keyboardZoom -= Config.KEYBOARD_ZOOM_SPEED;
}
if (keysPressed.has('e') || keysPressed.has('E') || keysPressed.has('-')) {
keyboardZoom += Config.KEYBOARD_ZOOM_SPEED;
} }
} }
@@ -371,19 +389,58 @@ function main() {
window.addEventListener('keydown', (evt) => { window.addEventListener('keydown', (evt) => {
keysPressed.add(evt.key); keysPressed.add(evt.key);
// 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 // Reset camera on 'R' key
if (evt.key === 'r' || evt.key === 'R') { if (evt.key === 'r' || evt.key === 'R') {
camera = new Camera(); // Reset to initial position 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 // Prevent default for space to avoid page scroll
if (evt.key === ' ') { if (evt.key === ' ' && cameraMode === 'fps') {
evt.preventDefault(); evt.preventDefault();
} }
// Handle orbital camera keyboard input
if (cameraMode === 'orbital') {
handleKeyboardInput();
}
}); });
window.addEventListener('keyup', (evt) => { window.addEventListener('keyup', (evt) => {
keysPressed.delete(evt.key); keysPressed.delete(evt.key);
if (cameraMode === 'orbital') {
handleKeyboardInput();
}
}); });
// Window resize handler // Window resize handler
@@ -391,46 +448,43 @@ function main() {
updateCanvasSize(canvas); updateCanvasSize(canvas);
}); });
// Wireframe toggle handler // Camera mode toggle from UI controls
window.addEventListener('toggleWireframe', () => { window.addEventListener('toggleCameraMode', () => {
wireframeMode = !wireframeMode; cameraMode = cameraMode === 'fps' ? 'orbital' : 'fps';
const wireframeBtn = document.getElementById('wireframe-toggle'); camera = cameraMode === 'fps' ? fpsCamera : orbitalCamera;
if (wireframeBtn) { console.log(`Camera mode switched to: ${cameraMode.toUpperCase()}`);
wireframeBtn.textContent = `Wireframe: ${wireframeMode ? 'ON' : 'OFF'}`;
// 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);
} }
console.log(`Wireframe mode: ${wireframeMode ? 'ON' : 'OFF'}`);
}); });
// Ocean settings sliders
window.addEventListener('waveHeightChange', ((evt: CustomEvent) => {
waveHeight = evt.detail;
}) as EventListener);
window.addEventListener('waveSpeedChange', ((evt: CustomEvent) => {
waveSpeed = evt.detail;
}) as EventListener);
window.addEventListener('foamIntensityChange', ((evt: CustomEvent) => {
foamIntensity = evt.detail;
}) as EventListener);
window.addEventListener('glitterIntensityChange', ((evt: CustomEvent) => {
glitterIntensity = evt.detail;
}) as EventListener);
initShaders(); initShaders();
initGeometry(); initGeometry();
initFBO(); initFBO();
projectedOcean = new ProjectedOcean(); oceanGrid = new Grid(Config.GRID_SIZE);
projectedOcean.initVAO(gl); oceanGrid.initVAO(gl);
console.log(`Projected ocean initialized with ${projectedOcean.getIndexCount()} indices`);
skybox = new Skybox(); skybox = new Skybox();
skybox.initVAO(gl); skybox.initVAO(gl);
console.log('Skybox initialized');
camera = new Camera(); // 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. //Check if any errors apeared during init.
if (gl.getError() != gl.NO_ERROR) { if (gl.getError() != gl.NO_ERROR) {
console.log("OpenGL Error!: "); console.log("OpenGL Error!: ");