2 Commits

3 changed files with 406 additions and 273 deletions

View File

@@ -374,15 +374,17 @@
<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 model;
uniform mat4 projection;
uniform mat4 uProjectorMatrix; // Inverse projector view-proj
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 vec3 v_fragPos;
varying vec3 v_normal;
@@ -390,6 +392,73 @@
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;
@@ -417,8 +486,83 @@
);
}
// 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) {
vec4 worldPos = model * vec4(positionAttr.xyz, 1.0);
// Project grid point onto ocean plane
float horizonBlend;
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;
@@ -427,6 +571,8 @@
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;
@@ -436,49 +582,47 @@
vec3 binormal = vec3(0.0, 0.0, 1.0);
vec3 t, b;
// === Large primary waves ===
displacement += gerstnerWave(pos, time, vec2(1.0, 0.2), 0.42 * heightMod, 6.0, 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.35 * heightMod, 5.0, t, b);
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);
// === Medium waves ===
displacement += gerstnerWave(pos, time * 0.9, vec2(-0.6, 0.8), 0.25 * heightMod, 3.0, t, b);
// 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.2, vec2(0.8, -0.5), 0.2 * heightMod, 2.2, t, b);
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);
displacement += gerstnerWave(pos, time, vec2(-0.3, -0.9), 0.18 * heightMod, 1.8, t, b);
// 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);
// === Small detail waves ===
displacement += gerstnerWave(pos, time * 1.2, vec2(0.9, -0.4), 0.12 * heightMod, 1.2, 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);
displacement += gerstnerWave(pos, time * 0.9, vec2(-0.5, -0.7), 0.10 * heightMod, 1.0, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
if (detailFade > 0.01) {
vec3 noiseNormal;
displacement += gerstnerWave(pos, time * 1.3, vec2(0.3, 0.95), 0.08 * heightMod, 0.8, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
// 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;
// === Tiny ripples ===
displacement += gerstnerWave(pos, time * 2.0, vec2(0.9, 0.1), 0.05 * heightMod, 0.35, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
// 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;
displacement += gerstnerWave(pos, time * 2.2, vec2(-0.2, 0.95), 0.04 * heightMod, 0.25, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
// === Micro ripples for fine surface detail ===
displacement += gerstnerWave(pos, time * 2.5, vec2(0.7, -0.7), 0.03 * heightMod, 0.18, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
displacement += gerstnerWave(pos, time * 3.0, vec2(-0.8, 0.6), 0.025 * heightMod, 0.12, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
displacement += gerstnerWave(pos, time * 3.5, vec2(0.5, -0.9), 0.02 * heightMod, 0.08, t, b);
tangent += t - vec3(1.0, 0.0, 0.0); binormal += b - vec3(0.0, 0.0, 1.0);
// 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;
@@ -504,42 +648,22 @@
normal = mix(flatNormal, normal, waveFade);
v_normal = vec3(normal.x, normal.z, normal.y);
// Horizon projection: calculate where the world horizon would be in clip space
// The horizon is where z=0 plane meets the sky (at eye height)
// Project a point at the horizon in the same XY direction as this vertex
float horizonStretch = smoothstep(40.0, 100.0, distToCamera);
if (horizonStretch > 0.0) {
// Get direction from camera to vertex (XY only, on ocean plane)
vec2 toVertex = normalize(worldPos.xy - eyePos.xy);
// Create a horizon point far away in that direction at z=0
vec3 horizonPoint = vec3(
eyePos.xy + toVertex * 10000.0,
0.0
);
// Project horizon point to get true horizon clip position
vec4 horizonClip = projection * view * vec4(horizonPoint, 1.0);
// Get actual clip position
vec4 clipPos = projection * view * worldPos;
// Blend vertex toward the horizon point's clip position (normalized)
// Overshoot slightly past horizon to ensure no gap
float horizonY = horizonClip.y / horizonClip.w * clipPos.w;
float overshoot = 1.0 + horizonStretch * 0.1; // Push slightly past horizon
clipPos.y = mix(clipPos.y, horizonY * overshoot, horizonStretch);
gl_Position = clipPos;
} else {
// Project back to clip space
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;
}
</script>
}
</script>
<script id="sky-fs" type="x-shader/x-fragment">
precision mediump float;

View File

@@ -1,200 +1,167 @@
import { Grid } from './Grid';
import { vec3 } from 'gl-matrix';
import { vec3, vec4, mat4 } from 'gl-matrix';
/** Manages multiple ocean grid patches with LOD based on camera distance and view cone */
export class OceanLOD {
private grids: Array<{
grid: Grid;
centerX: number;
centerY: number;
size: number;
lodLevel: number;
visible: boolean;
}> = [];
/**
* 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;
private readonly LOD_LEVELS = [
{ distance: 3.0, gridSize: 256 }, // Very close - ultra detail
{ distance: 8.0, gridSize: 128 }, // Close - high detail
{ distance: 20.0, gridSize: 64 }, // Medium distance
{ distance: 40.0, gridSize: 16 }, // Far - low detail
{ distance: 80.0, gridSize: 8 }, // Very far - minimal
{ distance: Infinity, gridSize: 4 },// Horizon - lowest (will be stretched anyway)
];
// Grid resolution
private readonly GRID_SIZE_X = 400;
private readonly GRID_SIZE_Y = 400;
private readonly PATCH_SIZE = 10.0; // Larger patches = fewer needed
private readonly PATCHES_PER_SIDE = 21; // 21x21 = 441 patches (covers ~200 units)
private readonly VIEW_CONE_COS = Math.cos(Math.PI * 0.45); // ~81 degree half-angle (wider than typical FOV)
// 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
// Track the grid origin to re-center when camera moves
private gridOriginX: number = 0;
private gridOriginY: number = 0;
// Projector parameters
private readonly MIN_PROJECTOR_HEIGHT = 5.0; // Minimum height above upper bound
constructor() {
this.createGridPatches();
}
// Matrices for the shader
public projectorMatrix: mat4 = mat4.create();
public rangeMatrix: mat4 = mat4.create();
private createGridPatches(): void {
const halfPatches = Math.floor(this.PATCHES_PER_SIDE / 2);
for (let y = -halfPatches; y <= halfPatches; y++) {
for (let x = -halfPatches; x <= halfPatches; x++) {
const centerX = x * this.PATCH_SIZE + this.gridOriginX;
const centerY = y * this.PATCH_SIZE + this.gridOriginY;
// Start with lowest detail - will be updated based on camera
const grid = new Grid(
this.LOD_LEVELS[5].gridSize,
centerX,
centerY,
this.PATCH_SIZE
);
this.grids.push({
grid,
centerX,
centerY,
size: this.PATCH_SIZE,
lodLevel: 5,
visible: true
});
}
}
}
/** Re-center the grid around a new origin */
private recenterGrid(gl: WebGL2RenderingContext, newOriginX: number, newOriginY: number): void {
this.gridOriginX = newOriginX;
this.gridOriginY = newOriginY;
const halfPatches = Math.floor(this.PATCHES_PER_SIDE / 2);
let i = 0;
for (let y = -halfPatches; y <= halfPatches; y++) {
for (let x = -halfPatches; x <= halfPatches; x++) {
const patch = this.grids[i];
const newCenterX = x * this.PATCH_SIZE + this.gridOriginX;
const newCenterY = y * this.PATCH_SIZE + this.gridOriginY;
// Only update if patch position changed
if (patch.centerX !== newCenterX || patch.centerY !== newCenterY) {
patch.centerX = newCenterX;
patch.centerY = newCenterY;
// Force LOD recalculation
patch.lodLevel = -1;
}
i++;
}
}
}
/** Update LOD based on camera position and view direction */
updateLOD(gl: WebGL2RenderingContext, cameraPos: vec3, cameraTarget: vec3): void {
// Calculate view direction (normalized)
const viewDir = vec3.create();
vec3.subtract(viewDir, cameraTarget, cameraPos);
vec3.normalize(viewDir, viewDir);
// Check if we need to recenter the grid (camera moved more than one patch size from origin)
const cameraGridX = Math.floor(cameraPos[0] / this.PATCH_SIZE) * this.PATCH_SIZE;
const cameraGridY = Math.floor(cameraPos[1] / this.PATCH_SIZE) * this.PATCH_SIZE;
if (cameraGridX !== this.gridOriginX || cameraGridY !== this.gridOriginY) {
this.recenterGrid(gl, cameraGridX, cameraGridY);
}
for (const patch of this.grids) {
// Calculate vector from camera to patch center (on XY plane, Z=0 for ocean surface)
const toPatch = vec3.fromValues(
patch.centerX - cameraPos[0],
patch.centerY - cameraPos[1],
0 - cameraPos[2] // Ocean is at Z=0
);
const distance = vec3.length(toPatch);
// Normalize direction to patch
const toPatchDir = vec3.create();
vec3.normalize(toPatchDir, toPatch);
// Calculate dot product with view direction (how aligned is patch with where we're looking)
const dotProduct = vec3.dot(viewDir, toPatchDir);
// Determine if patch is in front of camera and within view cone
const isInFront = dotProduct > -0.3; // Slightly behind is ok for edge cases
const isInViewCone = dotProduct > this.VIEW_CONE_COS;
// Frustum culling - don't draw patches behind camera
patch.visible = isInFront;
// Calculate LOD level
let newLodLevel = 5; // Default to lowest detail
if (!isInFront) {
// Behind camera - skip (will not be drawn)
newLodLevel = 5;
} else if (isInViewCone) {
// In view cone - use distance-based LOD
for (let i = 0; i < this.LOD_LEVELS.length; i++) {
if (distance < this.LOD_LEVELS[i].distance) {
newLodLevel = i;
break;
}
}
} else {
// In front but outside view cone - reduce detail by 1-2 levels
for (let i = 0; i < this.LOD_LEVELS.length; i++) {
if (distance < this.LOD_LEVELS[i].distance) {
newLodLevel = Math.min(i + 2, 5); // Reduce detail
break;
}
}
}
// Only recreate grid if LOD level changed
if (newLodLevel !== patch.lodLevel) {
patch.lodLevel = newLodLevel;
patch.grid = new Grid(
this.LOD_LEVELS[newLodLevel].gridSize,
patch.centerX,
patch.centerY,
patch.size
);
patch.grid.initVAO(gl);
}
}
}
constructor() {}
/** Generate the grid vertices (in [0,1] range) */
initVAO(gl: WebGL2RenderingContext): void {
for (const { grid } of this.grids) {
grid.initVAO(gl);
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 {
for (const patch of this.grids) {
if (patch.visible) {
patch.grid.draw(gl, wireframe);
}
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);
}
}
getGridCount(): number {
return this.grids.length;
}
getTotalVertexCount(): number {
let total = 0;
for (const { grid } of this.grids) {
total += grid.getIndexCount() / 3;
}
return total;
}
/** Get statistics about current LOD distribution */
getLODStats(): { [key: number]: number } {
const stats: { [key: number]: number } = { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 };
for (const patch of this.grids) {
stats[patch.lodLevel]++;
}
return stats;
getIndexCount(): number {
return this.indexCount;
}
}

View File

@@ -1,6 +1,6 @@
import { vec3, mat4 } from 'gl-matrix';
import { vec3, vec4, mat4 } from 'gl-matrix';
import { Camera } from './Camera';
import { OceanLOD } from './OceanLOD';
import { ProjectedOcean } from './OceanLOD';
import { Skybox } from './Skybox';
import { createProgram } from './Shader';
import * as Config from './constants';
@@ -134,14 +134,13 @@ var lastTime = new Date().getTime();
var counter = 0.0;
var fps = 0;
var fpsDisplay: HTMLElement | null = null;
var lodStatsTimer = 0;
/** Input states*/
var mouseXVel = 0;
var mouseYVel = 0;
var keysPressed: Set<string> = new Set();
/** Objects and states*/
var camera: Camera;
var oceanLOD: OceanLOD;
var projectedOcean: ProjectedOcean;
var skybox: Skybox;
var wireframeMode = false;
/** Camera movement speed */
@@ -157,7 +156,6 @@ function drawScene() {
let now = new Date();
let delta = now.getTime() - lastTime;
timeSpent += delta;
lodStatsTimer += delta;
if ((counter += delta) >= Config.FPS_UPDATE_INTERVAL) {
counter = 0;
@@ -166,13 +164,6 @@ function drawScene() {
}
fps = 0;
}
// Log LOD stats every 5 seconds
if (lodStatsTimer >= 5000) {
lodStatsTimer = 0;
const stats = oceanLOD.getLODStats();
console.log(`LOD Stats - High:${stats[0]} Med:${stats[1]} Low:${stats[2]} VeryLow:${stats[3]}`);
}
lastTime = now.getTime();
// Sun direction (matches the one in ocean shader)
@@ -216,20 +207,18 @@ function drawScene() {
gl.enable(gl.DEPTH_TEST);
gl.depthMask(true);
// Update LOD based on camera position and view direction
oceanLOD.updateLOD(gl, camera.pos, camera.target);
var model = mat4.create();
mat4.identity(model);
// No centering needed - grids are already positioned correctly in world space
// Update projected ocean's projector matrices
projectedOcean.updateProjector(camera.pos, camera.forward, view, projection);
gl.useProgram(defaultProgram);
let view_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "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");
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");
gl.uniform3fv(eye_loc, camera.pos);
let uTime_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uTime");
@@ -245,7 +234,60 @@ function drawScene() {
let uGlitterIntensity_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "uGlitterIntensity");
gl.uniform1f(uGlitterIntensity_loc, glitterIntensity);
oceanLOD.draw(gl, wireframeMode);
// 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);
}
@@ -380,9 +422,9 @@ function main() {
initGeometry();
initFBO();
oceanLOD = new OceanLOD();
oceanLOD.initVAO(gl);
console.log(`Ocean LOD initialized with ${oceanLOD.getGridCount()} patches`);
projectedOcean = new ProjectedOcean();
projectedOcean.initVAO(gl);
console.log(`Projected ocean initialized with ${projectedOcean.getIndexCount()} indices`);
skybox = new Skybox();
skybox.initVAO(gl);