Compare commits
4 Commits
Background
...
52c2e1dacd
| Author | SHA1 | Date | |
|---|---|---|---|
| 52c2e1dacd | |||
| 86d6da33d2 | |||
| dedcec547d | |||
| 0a7dc2f25f |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1,2 +1,6 @@
|
|||||||
build/
|
build/
|
||||||
|
dist/
|
||||||
node_modules/
|
node_modules/
|
||||||
|
.vscode/
|
||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
stages:
|
stages:
|
||||||
- build #first build
|
- build
|
||||||
- deploy #then deploy
|
- deploy
|
||||||
|
|
||||||
build:
|
build:
|
||||||
stage: build
|
stage: build
|
||||||
@@ -9,19 +9,17 @@ build:
|
|||||||
- npm run build
|
- npm run build
|
||||||
artifacts:
|
artifacts:
|
||||||
paths:
|
paths:
|
||||||
- build
|
- dist
|
||||||
only:
|
only:
|
||||||
- master
|
- main
|
||||||
|
|
||||||
deploy_to_projects:
|
deploy_to_projects:
|
||||||
stage: deploy
|
stage: deploy
|
||||||
script:
|
script:
|
||||||
- mkdir -p /var/www/projects.rismer.de/$CI_PROJECT_NAME
|
- mkdir -p /var/www/projects.rismer.de/$CI_PROJECT_NAME
|
||||||
- cp index.html /var/www/projects.rismer.de/$CI_PROJECT_NAME
|
- cp -r dist/* /var/www/projects.rismer.de/$CI_PROJECT_NAME/
|
||||||
- mkdir -p /var/www/projects.rismer.de/$CI_PROJECT_NAME/build
|
|
||||||
- cp build/app.js /var/www/projects.rismer.de/$CI_PROJECT_NAME/build
|
|
||||||
environment:
|
environment:
|
||||||
name: deploy
|
name: deploy
|
||||||
url: https://projects.rismer.de/$CI_PROJECT_NAME
|
url: https://projects.rismer.de/$CI_PROJECT_NAME
|
||||||
only:
|
only:
|
||||||
- master
|
- main
|
||||||
|
|||||||
230
index.html
230
index.html
@@ -1,7 +1,102 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html>
|
<html>
|
||||||
<header>
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>Web Ocean</title>
|
<title>Web Ocean</title>
|
||||||
|
<style>
|
||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||||
|
overflow: hidden;
|
||||||
|
background: #000;
|
||||||
|
}
|
||||||
|
|
||||||
|
#window {
|
||||||
|
display: block;
|
||||||
|
width: 100vw;
|
||||||
|
height: 100vh;
|
||||||
|
cursor: move;
|
||||||
|
}
|
||||||
|
|
||||||
|
#controls {
|
||||||
|
position: absolute;
|
||||||
|
top: 20px;
|
||||||
|
left: 20px;
|
||||||
|
background: rgba(0, 0, 0, 0.7);
|
||||||
|
color: white;
|
||||||
|
padding: 15px 20px;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 14px;
|
||||||
|
max-width: 300px;
|
||||||
|
backdrop-filter: blur(10px);
|
||||||
|
transition: opacity 0.3s;
|
||||||
|
}
|
||||||
|
|
||||||
|
#controls.hidden {
|
||||||
|
opacity: 0;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
#controls h3 {
|
||||||
|
margin: 0 0 10px 0;
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
#controls .control-group {
|
||||||
|
margin-bottom: 8px;
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
#controls .key {
|
||||||
|
display: inline-block;
|
||||||
|
background: rgba(255, 255, 255, 0.2);
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-radius: 3px;
|
||||||
|
font-family: 'Courier New', monospace;
|
||||||
|
font-size: 12px;
|
||||||
|
margin: 0 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#toggle-controls {
|
||||||
|
position: absolute;
|
||||||
|
top: 20px;
|
||||||
|
right: 20px;
|
||||||
|
background: rgba(0, 0, 0, 0.7);
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
padding: 10px 15px;
|
||||||
|
border-radius: 5px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 14px;
|
||||||
|
backdrop-filter: blur(10px);
|
||||||
|
transition: background 0.3s;
|
||||||
|
}
|
||||||
|
|
||||||
|
#toggle-controls:hover {
|
||||||
|
background: rgba(0, 0, 0, 0.85);
|
||||||
|
}
|
||||||
|
|
||||||
|
#fps-counter {
|
||||||
|
position: absolute;
|
||||||
|
bottom: 20px;
|
||||||
|
left: 20px;
|
||||||
|
background: rgba(0, 0, 0, 0.7);
|
||||||
|
color: #0f0;
|
||||||
|
padding: 8px 12px;
|
||||||
|
border-radius: 5px;
|
||||||
|
font-family: 'Courier New', monospace;
|
||||||
|
font-size: 14px;
|
||||||
|
backdrop-filter: blur(10px);
|
||||||
|
}
|
||||||
|
</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;
|
||||||
|
|
||||||
@@ -191,10 +286,51 @@
|
|||||||
<script id="sky-fs" type="x-shader/x-fragment">
|
<script id="sky-fs" type="x-shader/x-fragment">
|
||||||
precision mediump float;
|
precision mediump float;
|
||||||
|
|
||||||
varying vec3 fragPos;
|
varying vec3 v_rayDir;
|
||||||
|
|
||||||
|
uniform vec3 uSunDirection;
|
||||||
|
|
||||||
void main(void) {
|
void main(void) {
|
||||||
gl_FragColor = vec4(fragPos,1.0);
|
vec3 rayDir = normalize(v_rayDir);
|
||||||
|
|
||||||
|
// Use Z as up (matches world space where ocean is on XY plane)
|
||||||
|
float upAmount = rayDir.z;
|
||||||
|
|
||||||
|
// Sky gradient - from horizon to zenith
|
||||||
|
float horizonBlend = pow(1.0 - max(upAmount, 0.0), 2.0);
|
||||||
|
vec3 zenithColor = vec3(0.15, 0.35, 0.75); // Deep blue at top
|
||||||
|
vec3 horizonColor = vec3(0.55, 0.7, 0.9); // Light blue at horizon
|
||||||
|
vec3 skyColor = mix(zenithColor, horizonColor, horizonBlend);
|
||||||
|
|
||||||
|
// Add warm glow near horizon
|
||||||
|
float horizonGlow = pow(max(1.0 - abs(upAmount), 0.0), 6.0);
|
||||||
|
skyColor += vec3(0.4, 0.25, 0.1) * horizonGlow * 0.4;
|
||||||
|
|
||||||
|
// Sun direction already in correct coordinate system
|
||||||
|
vec3 sunDir = normalize(uSunDirection);
|
||||||
|
float sunAngle = max(dot(rayDir, sunDir), 0.0);
|
||||||
|
|
||||||
|
// Sun disk
|
||||||
|
float sunDisk = smoothstep(0.9993, 0.9998, sunAngle);
|
||||||
|
vec3 sunColor = vec3(1.0, 0.95, 0.85);
|
||||||
|
|
||||||
|
// Sun glow
|
||||||
|
float sunGlow = pow(sunAngle, 48.0) * 0.6;
|
||||||
|
float sunHalo = pow(sunAngle, 6.0) * 0.25;
|
||||||
|
|
||||||
|
// Combine sun effects
|
||||||
|
skyColor += sunColor * sunDisk * 3.0;
|
||||||
|
skyColor += vec3(1.0, 0.85, 0.5) * sunGlow;
|
||||||
|
skyColor += vec3(1.0, 0.9, 0.7) * sunHalo;
|
||||||
|
|
||||||
|
// Below horizon - fade to darker color
|
||||||
|
if (upAmount < 0.0) {
|
||||||
|
float depth = -upAmount;
|
||||||
|
vec3 deepColor = vec3(0.02, 0.08, 0.15);
|
||||||
|
skyColor = mix(horizonColor * 0.7, deepColor, smoothstep(0.0, 0.5, depth));
|
||||||
|
}
|
||||||
|
|
||||||
|
gl_FragColor = vec4(skyColor, 1.0);
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
<script id="sky-vs" type="x-shader/x-vertex">
|
<script id="sky-vs" type="x-shader/x-vertex">
|
||||||
@@ -202,22 +338,92 @@
|
|||||||
|
|
||||||
uniform mat4 projection;
|
uniform mat4 projection;
|
||||||
uniform mat4 view;
|
uniform mat4 view;
|
||||||
uniform mat4 testModel;
|
|
||||||
|
|
||||||
varying vec3 fragPos;
|
varying vec3 v_rayDir;
|
||||||
|
|
||||||
void main(void) {
|
void main(void) {
|
||||||
gl_PointSize = 10.;
|
v_rayDir = positionAttr;
|
||||||
gl_Position = projection * mat4(mat3(view)) * vec4(positionAttr, 1.0);
|
// Remove translation from view matrix for skybox
|
||||||
fragPos = (view * vec4(positionAttr,1.0)).xyz; //This is wrong probably
|
mat4 rotView = mat4(mat3(view));
|
||||||
|
vec4 pos = projection * rotView * vec4(positionAttr, 1.0);
|
||||||
|
gl_Position = pos;
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
</header>
|
|
||||||
|
</head>
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
<canvas id="window" width="800" height="600"
|
<canvas id="window"></canvas>
|
||||||
style="margin:0 auto; border: solid #000000 1px; display:block; cursor:move;"></canvas>
|
|
||||||
<script src="build/app.js"></script>
|
<div id="controls">
|
||||||
|
<h3>🌊 Ocean Controls</h3>
|
||||||
|
<div class="control-group">
|
||||||
|
<strong>Camera Mode:</strong> <span class="key">C</span> (FPS/Orbital)<br>
|
||||||
|
<span id="current-camera-mode" style="font-size: 12px; color: #aaa;">Current: FPS</span>
|
||||||
|
</div>
|
||||||
|
<div class="control-group">
|
||||||
|
<strong>FPS Camera:</strong><br>
|
||||||
|
<span class="key">W</span><span class="key">A</span><span class="key">S</span><span class="key">D</span> Move<br>
|
||||||
|
<span class="key">Q</span><span class="key">E</span> or <span class="key">Space</span><span class="key">Ctrl</span> Up/Down<br>
|
||||||
|
<span class="key">Shift</span> Sprint<br>
|
||||||
|
Mouse: Look around
|
||||||
|
</div>
|
||||||
|
<div class="control-group">
|
||||||
|
<strong>Orbital Camera:</strong><br>
|
||||||
|
<span class="key">W</span><span class="key">A</span><span class="key">S</span><span class="key">D</span> or Arrows Rotate<br>
|
||||||
|
<span class="key">Q</span><span class="key">E</span> or <span class="key">+</span><span class="key">-</span> Zoom<br>
|
||||||
|
Mouse: Click and drag to rotate
|
||||||
|
</div>
|
||||||
|
<div class="control-group">
|
||||||
|
<strong>Reset:</strong> <span class="key">R</span>
|
||||||
|
</div>
|
||||||
|
<div class="control-group">
|
||||||
|
<strong>Toggle Help:</strong> <span class="key">H</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button id="toggle-controls">Toggle Controls (H)</button>
|
||||||
|
|
||||||
|
<div id="fps-counter">FPS: 0</div>
|
||||||
|
|
||||||
|
<script type="module" src="/src/main.ts"></script>
|
||||||
|
<script>
|
||||||
|
// Toggle controls visibility
|
||||||
|
const controls = document.getElementById('controls');
|
||||||
|
const toggleBtn = document.getElementById('toggle-controls');
|
||||||
|
const cameraModeDisplay = document.getElementById('current-camera-mode');
|
||||||
|
|
||||||
|
toggleBtn.addEventListener('click', () => {
|
||||||
|
controls.classList.toggle('hidden');
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener('keydown', (evt) => {
|
||||||
|
if (evt.key === 'h' || evt.key === 'H') {
|
||||||
|
controls.classList.toggle('hidden');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update camera mode display when C is pressed
|
||||||
|
if (evt.key === 'c' || evt.key === 'C') {
|
||||||
|
setTimeout(() => {
|
||||||
|
// Get camera mode from any displayed element
|
||||||
|
const cameraMode = document.getElementById('camera-mode');
|
||||||
|
if (cameraMode && cameraModeDisplay) {
|
||||||
|
const mode = cameraMode.textContent.replace('Camera: ', '');
|
||||||
|
cameraModeDisplay.textContent = `Current: ${mode}`;
|
||||||
|
}
|
||||||
|
}, 100);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Listen for custom camera mode toggle events from UI
|
||||||
|
window.addEventListener('toggleCameraMode', () => {
|
||||||
|
const cameraMode = document.getElementById('camera-mode');
|
||||||
|
if (cameraMode && cameraModeDisplay) {
|
||||||
|
const mode = cameraMode.textContent.replace('Camera: ', '');
|
||||||
|
cameraModeDisplay.textContent = `Current: ${mode}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
</body>
|
</body>
|
||||||
|
|
||||||
</html>
|
</html>
|
||||||
2323
package-lock.json
generated
2323
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
20
package.json
20
package.json
@@ -2,13 +2,12 @@
|
|||||||
"name": "web-ocean",
|
"name": "web-ocean",
|
||||||
"version": "0.0.1",
|
"version": "0.0.1",
|
||||||
"description": "Simulating a ocean with typescript and webgl.",
|
"description": "Simulating a ocean with typescript and webgl.",
|
||||||
"main": "index.html",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"livedev": "concurrently --kill-others \"npm-watch\"",
|
"dev": "vite",
|
||||||
"build:release": "tsc && browserify ./build/main.js | uglifyjs > ./build/app.js",
|
"build": "tsc && vite build",
|
||||||
"build:debug": "tsc && browserify --debug ./build/main.js -o ./build/app.js",
|
"preview": "vite preview",
|
||||||
"build:tsc": "tsc",
|
"build:legacy": "tsc && browserify ./build/main.js | uglifyjs > ./build/app.js"
|
||||||
"test": "echo \"Error: no test specified\" && exit 1"
|
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"webgl",
|
"webgl",
|
||||||
@@ -21,13 +20,10 @@
|
|||||||
"author": "Julian Niessner",
|
"author": "Julian Niessner",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/gl-matrix": "^2.4.5",
|
"typescript": "^5.9.3",
|
||||||
"browserify": "^16.5.0",
|
"vite": "^6.0.7"
|
||||||
"concurrently": "^5.1.0",
|
|
||||||
"typescript": "^3.7.5",
|
|
||||||
"uglifyjs": "^2.4.11"
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"gl-matrix": "^3.1.0"
|
"gl-matrix": "^3.4.4"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
142
readme.md
142
readme.md
@@ -1,7 +1,141 @@
|
|||||||
Projekt bauen:
|
# 🌊 WebOcean
|
||||||
|
|
||||||
```npm run build```
|
An interactive 3D ocean simulation using WebGL2, TypeScript, and Perlin noise for realistic water wave generation.
|
||||||
|
|
||||||
und ausführen
|

|
||||||
|

|
||||||
|

|
||||||
|
|
||||||
```index.html```
|
## ✨ Features
|
||||||
|
|
||||||
|
- **Real-time Ocean Simulation** - Dynamic water surface with Perlin noise-based displacement
|
||||||
|
- **Advanced Rendering Techniques**:
|
||||||
|
- Fresnel reflection for realistic water appearance
|
||||||
|
- Subsurface scattering for light penetration
|
||||||
|
- Specular highlights for sun glitter effect
|
||||||
|
- Dynamic normal mapping from displacement
|
||||||
|
- **Interactive Camera Controls** - Mouse and keyboard navigation
|
||||||
|
- **Responsive Design** - Automatically adapts to window size
|
||||||
|
- **Performance Monitoring** - Real-time FPS counter
|
||||||
|
|
||||||
|
## 🎮 Controls
|
||||||
|
|
||||||
|
| Action | Keys |
|
||||||
|
|--------|------|
|
||||||
|
| **Rotate Camera** | `W` `A` `S` `D` or Arrow Keys |
|
||||||
|
| **Zoom In/Out** | `Q` / `E` or `+` / `-` |
|
||||||
|
| **Mouse Drag** | Click and drag to rotate |
|
||||||
|
| **Reset Camera** | `R` |
|
||||||
|
| **Toggle Help** | `H` |
|
||||||
|
|
||||||
|
## 🚀 Getting Started
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
|
||||||
|
- Node.js (v16 or higher)
|
||||||
|
- npm or yarn
|
||||||
|
|
||||||
|
### Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Clone the repository
|
||||||
|
git clone <repository-url>
|
||||||
|
cd WebOcean
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
### Development
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Start development server with hot reload
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Open your browser at `http://localhost:3000`
|
||||||
|
|
||||||
|
### Build for Production
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Build optimized production bundle
|
||||||
|
npm run build
|
||||||
|
|
||||||
|
# Preview production build
|
||||||
|
npm run preview
|
||||||
|
```
|
||||||
|
|
||||||
|
The built files will be in the `dist/` directory.
|
||||||
|
|
||||||
|
## 🛠️ Technical Details
|
||||||
|
|
||||||
|
### Architecture
|
||||||
|
|
||||||
|
- **WebGL 2.0** - Hardware-accelerated 3D graphics
|
||||||
|
- **TypeScript** - Type-safe development
|
||||||
|
- **Vite** - Fast build tool and dev server
|
||||||
|
- **gl-matrix** - High-performance matrix and vector operations
|
||||||
|
|
||||||
|
### Rendering Pipeline
|
||||||
|
|
||||||
|
1. **First Pass**: Generate Perlin noise texture for displacement
|
||||||
|
2. **Second Pass**: Render ocean grid with:
|
||||||
|
- Vertex displacement using noise texture
|
||||||
|
- Dynamic normal calculation
|
||||||
|
- Advanced lighting (Fresnel + subsurface scattering)
|
||||||
|
- Specular highlights
|
||||||
|
|
||||||
|
### Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
WebOcean/
|
||||||
|
├── src/
|
||||||
|
│ └── main.ts # Main application code
|
||||||
|
├── index.html # HTML entry point
|
||||||
|
├── vite.config.ts # Vite configuration
|
||||||
|
├── tsconfig.json # TypeScript configuration
|
||||||
|
└── package.json # Project dependencies
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📝 Configuration
|
||||||
|
|
||||||
|
Water and rendering parameters can be modified in `src/main.ts`:
|
||||||
|
|
||||||
|
- `GRID_SIZE` - Resolution of water mesh (default: 128)
|
||||||
|
- `NOISE_TEXTURE_WIDTH/HEIGHT` - Perlin noise resolution (default: 256x256)
|
||||||
|
- `FOV` - Field of view
|
||||||
|
- `OCEAN_COLOR` - Base water color
|
||||||
|
- `MOUSE_SENSITIVITY` - Camera rotation sensitivity
|
||||||
|
|
||||||
|
## 🔧 Development Notes
|
||||||
|
|
||||||
|
### Browser Compatibility
|
||||||
|
|
||||||
|
Requires a browser with WebGL 2.0 support:
|
||||||
|
- Chrome 56+
|
||||||
|
- Firefox 51+
|
||||||
|
- Edge 79+
|
||||||
|
- Safari 15+
|
||||||
|
|
||||||
|
### Performance
|
||||||
|
|
||||||
|
- Target: 60 FPS on modern hardware
|
||||||
|
- Grid complexity affects performance linearly
|
||||||
|
- Noise texture resolution affects memory usage
|
||||||
|
|
||||||
|
## 📄 License
|
||||||
|
|
||||||
|
ISC License - see LICENSE file for details
|
||||||
|
|
||||||
|
## 👤 Author
|
||||||
|
|
||||||
|
Julian Niessner
|
||||||
|
|
||||||
|
## 🙏 Acknowledgments
|
||||||
|
|
||||||
|
- Perlin noise implementation based on [WebGL Perlin Noise tutorial](https://medium.com/neosavvy-labs/webgl-with-perlin-noise-part-1-a87b56bbc9fb)
|
||||||
|
- Fresnel and lighting techniques from various WebGL resources
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Enjoy exploring the digital ocean! 🌊**
|
||||||
|
|||||||
76
src/Camera.ts
Normal file
76
src/Camera.ts
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
import { vec3, mat4, vec4 } from 'gl-matrix';
|
||||||
|
import { ICamera } from './ICamera';
|
||||||
|
|
||||||
|
/** Orbital camera that rotates around the world origin. */
|
||||||
|
export class OrbitalCamera implements ICamera {
|
||||||
|
pos: vec3;
|
||||||
|
target: vec3;
|
||||||
|
up: vec3;
|
||||||
|
|
||||||
|
xRot: number;
|
||||||
|
yRot: number;
|
||||||
|
offset: number;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.pos = vec3.create();
|
||||||
|
vec3.set(this.pos, 0.0, 0.0, 0.0);
|
||||||
|
this.target = vec3.create();
|
||||||
|
vec3.set(this.target, 0.0, 0.0, 0.0);
|
||||||
|
this.up = vec3.create();
|
||||||
|
vec3.set(this.up, 0.0, 1.0, 0.0);
|
||||||
|
this.xRot = 0.0;
|
||||||
|
this.yRot = 0.0;
|
||||||
|
this.offset = 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
setRotationX(rotX: number): void {
|
||||||
|
this.xRot = rotX;
|
||||||
|
this.updatePos();
|
||||||
|
}
|
||||||
|
|
||||||
|
setRotationY(rotY: number): void {
|
||||||
|
this.yRot = rotY;
|
||||||
|
this.updatePos();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sets the offset to world origin. */
|
||||||
|
setOffset(off: number): void {
|
||||||
|
this.offset = off;
|
||||||
|
this.updatePos();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Recalculates the position according to xy-rotation and offset. */
|
||||||
|
private updatePos(): void {
|
||||||
|
const transformation: mat4 = mat4.create();
|
||||||
|
mat4.identity(transformation);
|
||||||
|
|
||||||
|
//2. xy-Rotation
|
||||||
|
mat4.rotateX(transformation, transformation, this.xRot);
|
||||||
|
mat4.rotateY(transformation, transformation, this.yRot);
|
||||||
|
|
||||||
|
//1. Translation
|
||||||
|
const translation = vec3.create();
|
||||||
|
vec3.set(translation, 0.0, 0.0, this.offset);
|
||||||
|
mat4.translate(transformation, transformation, translation);
|
||||||
|
|
||||||
|
const temp: vec4 = vec4.create();
|
||||||
|
vec4.set(temp, 0.0, 0.0, 0.0, 1.0);
|
||||||
|
vec4.transformMat4(temp, temp, transformation);
|
||||||
|
|
||||||
|
vec3.set(this.pos, temp[0], temp[1], temp[2]);
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
const dir = vec3.create();
|
||||||
|
vec3.subtract(dir, this.target, this.pos);
|
||||||
|
vec3.normalize(dir, dir);
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
|
}
|
||||||
98
src/FPSCamera.ts
Normal file
98
src/FPSCamera.ts
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
72
src/Grid.ts
Normal file
72
src/Grid.ts
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
/** Grid for the water surface */
|
||||||
|
export class Grid {
|
||||||
|
private indices: number[] = [];
|
||||||
|
private vertices: number[] = [];
|
||||||
|
private vao: WebGLVertexArrayObject | null = null;
|
||||||
|
private size: number;
|
||||||
|
|
||||||
|
constructor(size: number = 128) {
|
||||||
|
this.size = size;
|
||||||
|
}
|
||||||
|
|
||||||
|
generate(): void {
|
||||||
|
this.indices = [];
|
||||||
|
this.vertices = [];
|
||||||
|
|
||||||
|
for (let j = 0; j <= this.size; ++j) {
|
||||||
|
for (let i = 0; i <= this.size; ++i) {
|
||||||
|
// Generate Vertices
|
||||||
|
const x = i / this.size;
|
||||||
|
const y = j / this.size;
|
||||||
|
const z = 0;
|
||||||
|
this.vertices.push(x, y, z);
|
||||||
|
|
||||||
|
if (i < this.size && j < this.size) { // Skip edges
|
||||||
|
const row1 = j * (this.size + 1);
|
||||||
|
const row2 = (j + 1) * (this.size + 1);
|
||||||
|
|
||||||
|
// triangle 1
|
||||||
|
this.indices.push(row1 + i);
|
||||||
|
this.indices.push(row1 + i + 1);
|
||||||
|
this.indices.push(row2 + i + 1);
|
||||||
|
|
||||||
|
// triangle 2
|
||||||
|
this.indices.push(row1 + i);
|
||||||
|
this.indices.push(row2 + i + 1);
|
||||||
|
this.indices.push(row2 + i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
initVAO(gl: WebGL2RenderingContext): void {
|
||||||
|
this.generate();
|
||||||
|
|
||||||
|
this.vao = gl.createVertexArray();
|
||||||
|
gl.bindVertexArray(this.vao);
|
||||||
|
|
||||||
|
const vboGrid: WebGLBuffer | null = gl.createBuffer();
|
||||||
|
gl.bindBuffer(gl.ARRAY_BUFFER, vboGrid);
|
||||||
|
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(this.vertices), gl.STATIC_DRAW);
|
||||||
|
|
||||||
|
const iboGrid: WebGLBuffer | null = gl.createBuffer();
|
||||||
|
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, iboGrid);
|
||||||
|
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint32Array(this.indices), 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): void {
|
||||||
|
if (this.vao) {
|
||||||
|
gl.bindVertexArray(this.vao);
|
||||||
|
gl.drawElements(gl.TRIANGLES, this.indices.length, gl.UNSIGNED_INT, 0);
|
||||||
|
gl.bindVertexArray(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getIndexCount(): number {
|
||||||
|
return this.indices.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
11
src/ICamera.ts
Normal file
11
src/ICamera.ts
Normal 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;
|
||||||
|
}
|
||||||
65
src/Shader.ts
Normal file
65
src/Shader.ts
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
/** Get shader source by HTML-Element<id> */
|
||||||
|
export function getShader(gl: WebGL2RenderingContext, id: string): WebGLShader | null {
|
||||||
|
const script: any = document.getElementById(id);
|
||||||
|
if (!script) {
|
||||||
|
console.error(`Couldn't get shader source from HTML for id: ${id}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
let shader: WebGLShader | null;
|
||||||
|
if (script.type == "x-shader/x-fragment") {
|
||||||
|
shader = gl.createShader(gl.FRAGMENT_SHADER);
|
||||||
|
} else if (script.type == "x-shader/x-vertex") {
|
||||||
|
shader = gl.createShader(gl.VERTEX_SHADER);
|
||||||
|
} else {
|
||||||
|
console.error(`Script type is wrong for id: ${id}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shader == null) {
|
||||||
|
console.error("Cannot create Shaders!");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
gl.shaderSource(shader, script.text);
|
||||||
|
gl.compileShader(shader);
|
||||||
|
|
||||||
|
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
|
||||||
|
console.error(`Shader compilation failed for ${id}:`, gl.getShaderInfoLog(shader));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return shader;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createProgram(
|
||||||
|
gl: WebGL2RenderingContext,
|
||||||
|
vertexShaderId: string,
|
||||||
|
fragmentShaderId: string,
|
||||||
|
programName: string
|
||||||
|
): WebGLProgram | null {
|
||||||
|
const vertexShader = getShader(gl, vertexShaderId);
|
||||||
|
const fragmentShader = getShader(gl, fragmentShaderId);
|
||||||
|
|
||||||
|
if (vertexShader == null || fragmentShader == null) {
|
||||||
|
console.error(`Didn't find ${programName} shader sources!`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const program = gl.createProgram();
|
||||||
|
if (program == null) {
|
||||||
|
console.error(`${programName} program not created!`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
gl.attachShader(program, vertexShader);
|
||||||
|
gl.attachShader(program, fragmentShader);
|
||||||
|
gl.linkProgram(program);
|
||||||
|
|
||||||
|
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
|
||||||
|
console.error(`Could not initialize ${programName} shaders:`, gl.getProgramInfoLog(program));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return program;
|
||||||
|
}
|
||||||
80
src/Skybox.ts
Normal file
80
src/Skybox.ts
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
/** Skybox cube for rendering the sky */
|
||||||
|
export class Skybox {
|
||||||
|
private vao: WebGLVertexArrayObject | null = null;
|
||||||
|
private vbo: WebGLBuffer | null = null;
|
||||||
|
private indexCount: number = 0;
|
||||||
|
|
||||||
|
constructor() {}
|
||||||
|
|
||||||
|
initVAO(gl: WebGL2RenderingContext): void {
|
||||||
|
// Cube vertices - positions only
|
||||||
|
const vertices = new Float32Array([
|
||||||
|
// Front face
|
||||||
|
-1, -1, 1,
|
||||||
|
1, -1, 1,
|
||||||
|
1, 1, 1,
|
||||||
|
-1, 1, 1,
|
||||||
|
// Back face
|
||||||
|
-1, -1, -1,
|
||||||
|
-1, 1, -1,
|
||||||
|
1, 1, -1,
|
||||||
|
1, -1, -1,
|
||||||
|
// Top face
|
||||||
|
-1, 1, -1,
|
||||||
|
-1, 1, 1,
|
||||||
|
1, 1, 1,
|
||||||
|
1, 1, -1,
|
||||||
|
// Bottom face
|
||||||
|
-1, -1, -1,
|
||||||
|
1, -1, -1,
|
||||||
|
1, -1, 1,
|
||||||
|
-1, -1, 1,
|
||||||
|
// Right face
|
||||||
|
1, -1, -1,
|
||||||
|
1, 1, -1,
|
||||||
|
1, 1, 1,
|
||||||
|
1, -1, 1,
|
||||||
|
// Left face
|
||||||
|
-1, -1, -1,
|
||||||
|
-1, -1, 1,
|
||||||
|
-1, 1, 1,
|
||||||
|
-1, 1, -1,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const indices = new Uint16Array([
|
||||||
|
0, 2, 1, 0, 3, 2, // front
|
||||||
|
4, 6, 5, 4, 7, 6, // back
|
||||||
|
8, 10, 9, 8, 11, 10, // top
|
||||||
|
12, 14, 13, 12, 15, 14, // bottom
|
||||||
|
16, 18, 17, 16, 19, 18, // right
|
||||||
|
20, 22, 21, 20, 23, 22, // left
|
||||||
|
]);
|
||||||
|
|
||||||
|
this.indexCount = indices.length;
|
||||||
|
|
||||||
|
this.vao = gl.createVertexArray();
|
||||||
|
gl.bindVertexArray(this.vao);
|
||||||
|
|
||||||
|
this.vbo = gl.createBuffer();
|
||||||
|
gl.bindBuffer(gl.ARRAY_BUFFER, this.vbo);
|
||||||
|
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
|
||||||
|
|
||||||
|
const ibo = gl.createBuffer();
|
||||||
|
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo);
|
||||||
|
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
|
||||||
|
|
||||||
|
// Position attribute
|
||||||
|
gl.enableVertexAttribArray(0);
|
||||||
|
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0);
|
||||||
|
|
||||||
|
gl.bindVertexArray(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
draw(gl: WebGL2RenderingContext): void {
|
||||||
|
if (!this.vao) return;
|
||||||
|
|
||||||
|
gl.bindVertexArray(this.vao);
|
||||||
|
gl.drawElements(gl.TRIANGLES, this.indexCount, gl.UNSIGNED_SHORT, 0);
|
||||||
|
gl.bindVertexArray(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
24
src/constants.ts
Normal file
24
src/constants.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
// Configuration Constants
|
||||||
|
export const GRID_SIZE = 128;
|
||||||
|
export const NOISE_TEXTURE_WIDTH = 256;
|
||||||
|
export const NOISE_TEXTURE_HEIGHT = 256;
|
||||||
|
export const CANVAS_WIDTH = 800;
|
||||||
|
export const CANVAS_HEIGHT = 600;
|
||||||
|
export const FOV = 1.0;
|
||||||
|
export const NEAR_PLANE = 0.1;
|
||||||
|
export const FAR_PLANE = 1000.0;
|
||||||
|
export const CAMERA_DEFAULT_OFFSET = 1.2;
|
||||||
|
export const CAMERA_DEFAULT_ROT_X = 1.1;
|
||||||
|
export const CAMERA_DEFAULT_ROT_Y = 0;
|
||||||
|
export const MOUSE_SENSITIVITY = 0.001;
|
||||||
|
export const KEYBOARD_ROTATION_SPEED = 0.02;
|
||||||
|
export const KEYBOARD_ZOOM_SPEED = 0.05;
|
||||||
|
export const FPS_UPDATE_INTERVAL = 1000;
|
||||||
|
|
||||||
|
// Ocean shader constants
|
||||||
|
export const OCEAN_COLOR_R = 0.0;
|
||||||
|
export const OCEAN_COLOR_G = 0.4;
|
||||||
|
export const OCEAN_COLOR_B = 0.4;
|
||||||
|
export const SKY_COLOR_R = 1.0;
|
||||||
|
export const SKY_COLOR_G = 1.0;
|
||||||
|
export const SKY_COLOR_B = 1.0;
|
||||||
516
src/main.ts
516
src/main.ts
@@ -1,86 +1,45 @@
|
|||||||
import { vec3, mat4, vec4 } from 'gl-matrix'
|
import { vec3, mat4 } from 'gl-matrix';
|
||||||
|
import { ICamera } from './ICamera';
|
||||||
|
import { OrbitalCamera } from './Camera';
|
||||||
|
import { FPSCamera } from './FPSCamera';
|
||||||
|
import { Grid } from './Grid';
|
||||||
|
import { Skybox } from './Skybox';
|
||||||
|
import { createProgram } from './Shader';
|
||||||
|
import * as Config from './constants';
|
||||||
|
|
||||||
var gl: WebGL2RenderingContext;
|
var gl: WebGL2RenderingContext;
|
||||||
var viewportWidth = 0;
|
var viewportWidth = 0;
|
||||||
var viewportHeight = 0;
|
var viewportHeight = 0;
|
||||||
|
|
||||||
/** A camera that always looks at the world origin. Can have an offset and be rotated. */
|
/** A camera that always looks at the world origin. Can have an offset and be rotated. */
|
||||||
class Camera {
|
// Moved to Camera.ts
|
||||||
pos: vec3;
|
|
||||||
target: vec3;
|
|
||||||
up: vec3;
|
|
||||||
|
|
||||||
xRot: number;
|
|
||||||
yRot: number;
|
|
||||||
offset: number;
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
this.pos = vec3.create();
|
|
||||||
vec3.set(this.pos, 0.0, 0.0, 0.0);
|
|
||||||
this.target = vec3.create();
|
|
||||||
vec3.set(this.target, 0.0, 0.0, 0.0);
|
|
||||||
this.up = vec3.create();
|
|
||||||
vec3.set(this.up, 0.0, 1.0, 0.0);
|
|
||||||
this.xRot = 0.0;
|
|
||||||
this.yRot = 0.0;
|
|
||||||
this.offset = 0.0;
|
|
||||||
}
|
|
||||||
|
|
||||||
setRotationX(rotX: number): void {
|
|
||||||
this.xRot = rotX;
|
|
||||||
this.updatePos();
|
|
||||||
}
|
|
||||||
|
|
||||||
setRotationY(rotY: number): void {
|
|
||||||
this.yRot = rotY;
|
|
||||||
this.updatePos();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Sets the offset to world origin. */
|
|
||||||
setOffset(off: number): void {
|
|
||||||
this.offset = off;
|
|
||||||
this.updatePos();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Reculcates the position according to xy-rotation and offset. */
|
|
||||||
private updatePos(): void {
|
|
||||||
var transformation: mat4 = mat4.create();
|
|
||||||
mat4.identity(transformation);
|
|
||||||
|
|
||||||
//2. xy-Rotation
|
|
||||||
mat4.rotateX(transformation, transformation, this.xRot);
|
|
||||||
mat4.rotateY(transformation, transformation, this.yRot);
|
|
||||||
|
|
||||||
//1. Translation
|
|
||||||
var translation = vec3.create();
|
|
||||||
vec3.set(translation, 0.0, 0.0, this.offset);
|
|
||||||
mat4.translate(transformation, transformation, translation);
|
|
||||||
|
|
||||||
var temp: vec4 = vec4.create();
|
|
||||||
vec4.set(temp, 0.0, 0.0, 0.0, 1.0);
|
|
||||||
vec4.transformMat4(temp, temp, transformation);
|
|
||||||
|
|
||||||
vec3.set(this.pos, temp[0], temp[1], temp[2]);
|
|
||||||
}
|
|
||||||
|
|
||||||
getViewMatrix(): mat4 {
|
|
||||||
var ret: mat4;
|
|
||||||
ret = mat4.create();
|
|
||||||
mat4.lookAt(ret, this.pos, this.target, this.up);
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Init OpenGL and gets the viewport/canvas sizes */
|
/** Init OpenGL and gets the viewport/canvas sizes */
|
||||||
function initGL(canvas: HTMLCanvasElement) {
|
function initGL(canvas: HTMLCanvasElement) {
|
||||||
|
// Helper function for canvas resize
|
||||||
|
const updateCanvasSize = (canvas: HTMLCanvasElement) => {
|
||||||
|
const displayWidth = window.innerWidth;
|
||||||
|
const displayHeight = window.innerHeight;
|
||||||
|
|
||||||
|
if (canvas.width !== displayWidth || canvas.height !== displayHeight) {
|
||||||
|
canvas.width = displayWidth;
|
||||||
|
canvas.height = displayHeight;
|
||||||
|
viewportWidth = displayWidth;
|
||||||
|
viewportHeight = displayHeight;
|
||||||
|
|
||||||
|
if (gl) {
|
||||||
|
gl.viewport(0, 0, viewportWidth, viewportHeight);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
var gltemp;
|
var gltemp;
|
||||||
try {
|
try {
|
||||||
gltemp = canvas.getContext("webgl2");
|
gltemp = canvas.getContext("webgl2");
|
||||||
if (!gltemp)
|
if (!gltemp)
|
||||||
gltemp = canvas.getContext("experimental-webgl2");
|
gltemp = canvas.getContext("experimental-webgl2");
|
||||||
if (gltemp != null) {
|
if (gltemp != null) {
|
||||||
viewportWidth = canvas.width;
|
updateCanvasSize(canvas);
|
||||||
viewportHeight = canvas.height;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -88,70 +47,27 @@ function initGL(canvas: HTMLCanvasElement) {
|
|||||||
// Not the best error detection logic.
|
// Not the best error detection logic.
|
||||||
// Redirect to http://get.webgl.org in failure case.
|
// Redirect to http://get.webgl.org in failure case.
|
||||||
if (gltemp == null) {
|
if (gltemp == null) {
|
||||||
alert("Unable to initialize WebGL2. Your browser or machine may not support it.");
|
console.error("Unable to initialize WebGL2. Your browser or machine may not support it.");
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
gl = <WebGL2RenderingContext>gltemp;
|
gl = <WebGL2RenderingContext>gltemp;
|
||||||
//WebGL2 supports floating point textures by default but it does not support filtering them or rendering to them by default. Note: 16bit filtering is included 32bit not
|
//WebGL2 supports floating point textures by default but it does not support filtering them or rendering to them by default. Note: 16bit filtering is included 32bit not
|
||||||
if (!gl.getExtension('EXT_color_buffer_float')) {
|
if (!gl.getExtension('EXT_color_buffer_float')) {
|
||||||
alert("32Bit/16Bit single Color render Buffers not available.");
|
console.error("32Bit/16Bit single Color render Buffers not available.");
|
||||||
} //allow 16bit texture as framebuffer target
|
} //allow 16bit texture as framebuffer target
|
||||||
|
|
||||||
gl.enable(gl.DEPTH_TEST);
|
gl.enable(gl.DEPTH_TEST);
|
||||||
|
|
||||||
|
return updateCanvasSize;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Update canvas size to fill window */
|
||||||
|
// Moved inline below
|
||||||
|
|
||||||
/** Grid for the watersurface */
|
/** Grid for the watersurface */
|
||||||
var gridIndices: number[] = [];
|
// Moved to Grid.ts
|
||||||
var gridVertices: number[] = [];
|
|
||||||
function generateGrid(N: number) {
|
|
||||||
for (let j = 0; j <= N; ++j) {
|
|
||||||
for (let i = 0; i <= N; ++i) {
|
|
||||||
//Generate Vertices
|
|
||||||
let x = i / N;
|
|
||||||
let y = j / N;
|
|
||||||
let z = 0;
|
|
||||||
gridVertices.push(x);
|
|
||||||
gridVertices.push(y);
|
|
||||||
gridVertices.push(z);
|
|
||||||
|
|
||||||
if (i < N && j < N) //Skip edges
|
/** Init Geometry for a Triangle */
|
||||||
{
|
|
||||||
let row1 = j * (N + 1);
|
|
||||||
let row2 = (j + 1) * (N + 1);
|
|
||||||
|
|
||||||
// triangle 1
|
|
||||||
gridIndices.push(row1 + i);
|
|
||||||
gridIndices.push(row1 + i + 1);
|
|
||||||
gridIndices.push(row2 + i + 1);
|
|
||||||
|
|
||||||
// triangle 2
|
|
||||||
gridIndices.push(row1 + i);
|
|
||||||
gridIndices.push(row2 + i + 1);
|
|
||||||
gridIndices.push(row2 + i);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var gridVAO: WebGLVertexArrayObject | null = null;
|
|
||||||
function initGridVAO() {
|
|
||||||
generateGrid(128);
|
|
||||||
|
|
||||||
gridVAO = gl.createVertexArray();
|
|
||||||
gl.bindVertexArray(gridVAO);
|
|
||||||
|
|
||||||
let vboGrid: WebGLBuffer | null = gl.createBuffer();
|
|
||||||
gl.bindBuffer(gl.ARRAY_BUFFER, vboGrid);
|
|
||||||
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(gridVertices), gl.STATIC_DRAW);
|
|
||||||
|
|
||||||
let iboGrid: WebGLBuffer | null = gl.createBuffer();
|
|
||||||
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, iboGrid);
|
|
||||||
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint32Array(gridIndices), gl.STATIC_DRAW);
|
|
||||||
|
|
||||||
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 3 * Float32Array.BYTES_PER_ELEMENT, 0);
|
|
||||||
gl.enableVertexAttribArray(0);
|
|
||||||
gl.bindVertexArray(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Init Geomtry for an Triangle */
|
|
||||||
var VBO: WebGLBuffer | null = null;
|
var VBO: WebGLBuffer | null = null;
|
||||||
function initGeometry() {
|
function initGeometry() {
|
||||||
VBO = gl.createBuffer();
|
VBO = gl.createBuffer();
|
||||||
@@ -170,117 +86,25 @@ function initGeometry() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Get shader source by HTML-Element<id> */
|
/** Get shader source by HTML-Element<id> */
|
||||||
function getShader(id: string) {
|
// Moved to Shader.ts
|
||||||
var script: any = document.getElementById(id);
|
|
||||||
if (!script) {
|
|
||||||
console.log("Coudln't get shader source from HTML!");
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
var shader: WebGLShader | null;
|
|
||||||
if (script.type == "x-shader/x-fragment") {
|
|
||||||
shader = gl.createShader(gl.FRAGMENT_SHADER);
|
|
||||||
} else if (script.type == "x-shader/x-vertex") {
|
|
||||||
shader = gl.createShader(gl.VERTEX_SHADER);
|
|
||||||
} else {
|
|
||||||
console.log("Script type is wrong!");
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (shader == null) {
|
|
||||||
console.log("Cannot create Shaders!")
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
gl.shaderSource(shader, script.text);
|
|
||||||
gl.compileShader(shader);
|
|
||||||
|
|
||||||
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
|
|
||||||
alert(gl.getShaderInfoLog(shader));
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return shader;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Init all Shaders that are needed */
|
/** Init all Shaders that are needed */
|
||||||
var perlinNoiseProgram: WebGLProgram | null;
|
var perlinNoiseProgram: WebGLProgram | null;
|
||||||
var defaultProgram: WebGLProgram | null;
|
var defaultProgram: WebGLProgram | null;
|
||||||
var textureProgram: WebGLProgram | null;
|
var textureProgram: WebGLProgram | null;
|
||||||
|
var skyProgram: WebGLProgram | null;
|
||||||
function initShaders() {
|
function initShaders() {
|
||||||
{ //Get perlinNoiseProgram
|
perlinNoiseProgram = createProgram(gl, "ndc-vs", "noise-fs", "Perlin Noise");
|
||||||
let vertexShader = getShader("ndc-vs");
|
defaultProgram = createProgram(gl, "default-vs", "default-fs", "Default");
|
||||||
let fragmentShader = getShader("noise-fs");
|
textureProgram = createProgram(gl, "texture-vs", "texture-fs", "Texture");
|
||||||
|
skyProgram = createProgram(gl, "sky-vs", "sky-fs", "Sky");
|
||||||
if (vertexShader == null || fragmentShader == null) {
|
|
||||||
console.log("Didn't find shader sources!")
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
perlinNoiseProgram = gl.createProgram();
|
|
||||||
if (perlinNoiseProgram == null) {
|
|
||||||
console.log("Program not created!")
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
gl.attachShader(perlinNoiseProgram, vertexShader);
|
|
||||||
gl.attachShader(perlinNoiseProgram, fragmentShader);
|
|
||||||
gl.linkProgram(perlinNoiseProgram);
|
|
||||||
|
|
||||||
if (!gl.getProgramParameter(perlinNoiseProgram, gl.LINK_STATUS)) {
|
|
||||||
alert("Could not initialise shaders");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
{ //Get defaultShaders
|
|
||||||
let vertexShader = getShader("default-vs");
|
|
||||||
let fragmentShader = getShader("default-fs");
|
|
||||||
|
|
||||||
if (vertexShader == null || fragmentShader == null) {
|
|
||||||
console.log("Didn't find shader sources!")
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
defaultProgram = gl.createProgram();
|
|
||||||
if (defaultProgram == null) {
|
|
||||||
console.log("Program not created!")
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
gl.attachShader(defaultProgram, vertexShader);
|
|
||||||
gl.attachShader(defaultProgram, fragmentShader);
|
|
||||||
gl.linkProgram(defaultProgram);
|
|
||||||
|
|
||||||
if (!gl.getProgramParameter(defaultProgram, gl.LINK_STATUS)) {
|
|
||||||
alert("Could not initialise shaders");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
{ //Get textureShader
|
|
||||||
let vertexShader = getShader("texture-vs");
|
|
||||||
let fragmentShader = getShader("texture-fs");
|
|
||||||
|
|
||||||
if (vertexShader == null || fragmentShader == null) {
|
|
||||||
console.log("Didn't find shader sources!")
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
textureProgram = gl.createProgram();
|
|
||||||
if (textureProgram == null) {
|
|
||||||
console.log("Program not created!")
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
gl.attachShader(textureProgram, vertexShader);
|
|
||||||
gl.attachShader(textureProgram, fragmentShader);
|
|
||||||
gl.linkProgram(textureProgram);
|
|
||||||
|
|
||||||
if (!gl.getProgramParameter(textureProgram, gl.LINK_STATUS)) {
|
|
||||||
alert("Could not initialise shaders");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Init an FBO used for the first render pass / perlin noise */
|
/** Init an FBO used for the first render pass / perlin noise */
|
||||||
var perlinNoiseFBO: WebGLFramebuffer | null = null;
|
var perlinNoiseFBO: WebGLFramebuffer | null = null;
|
||||||
var textureFBO: WebGLTexture | null = null;
|
var textureFBO: WebGLTexture | null = null;
|
||||||
var perlinNoiseFBOWidth = 256;
|
var perlinNoiseFBOWidth = Config.NOISE_TEXTURE_WIDTH;
|
||||||
var ferlinNoiseFBOHeight = 256;
|
var perlinNoiseFBOHeight = Config.NOISE_TEXTURE_HEIGHT;
|
||||||
function initFBO() {
|
function initFBO() {
|
||||||
perlinNoiseFBO = gl.createFramebuffer();
|
perlinNoiseFBO = gl.createFramebuffer();
|
||||||
gl.bindFramebuffer(gl.FRAMEBUFFER, perlinNoiseFBO);
|
gl.bindFramebuffer(gl.FRAMEBUFFER, perlinNoiseFBO);
|
||||||
@@ -288,7 +112,7 @@ function initFBO() {
|
|||||||
// Add attachments
|
// Add attachments
|
||||||
textureFBO = gl.createTexture();
|
textureFBO = gl.createTexture();
|
||||||
gl.bindTexture(gl.TEXTURE_2D, textureFBO); //last 3 parameter not intertesting becuase we are not supplying data
|
gl.bindTexture(gl.TEXTURE_2D, textureFBO); //last 3 parameter not intertesting becuase we are not supplying data
|
||||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.R16F, perlinNoiseFBOWidth, ferlinNoiseFBOHeight, 0, gl.RED, gl.HALF_FLOAT, null);
|
gl.texImage2D(gl.TEXTURE_2D, 0, gl.R16F, perlinNoiseFBOWidth, perlinNoiseFBOHeight, 0, gl.RED, gl.HALF_FLOAT, null);
|
||||||
|
|
||||||
// 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);
|
||||||
@@ -311,21 +135,36 @@ var timeSpent = 0.0;
|
|||||||
var lastTime = new Date().getTime();
|
var lastTime = new Date().getTime();
|
||||||
var counter = 0.0;
|
var counter = 0.0;
|
||||||
var fps = 0;
|
var fps = 0;
|
||||||
|
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();
|
||||||
/** Objects and states*/
|
/** Objects and states*/
|
||||||
var camera: Camera;
|
var camera: ICamera;
|
||||||
var curRotX = 1.1;
|
var orbitalCamera: OrbitalCamera;
|
||||||
var curRotY = 0;
|
var fpsCamera: FPSCamera;
|
||||||
|
var oceanGrid: Grid;
|
||||||
|
var skybox: Skybox;
|
||||||
|
var curRotX = Config.CAMERA_DEFAULT_ROT_X;
|
||||||
|
var curRotY = Config.CAMERA_DEFAULT_ROT_Y;
|
||||||
|
/** Camera modes */
|
||||||
|
var cameraMode: 'orbital' | 'fps' = 'fps';
|
||||||
|
var moveSpeed = 0.15;
|
||||||
|
var fastMoveSpeed = 0.4;
|
||||||
function drawScene() {
|
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) >= 1000.) {
|
if ((counter += delta) >= Config.FPS_UPDATE_INTERVAL) {
|
||||||
counter = 0;
|
counter = 0;
|
||||||
console.log("FPS: " + fps);
|
if (fpsDisplay) {
|
||||||
|
fpsDisplay.textContent = `FPS: ${fps}`;
|
||||||
|
}
|
||||||
fps = 0;
|
fps = 0;
|
||||||
}
|
}
|
||||||
lastTime = now.getTime();
|
lastTime = now.getTime();
|
||||||
@@ -336,12 +175,15 @@ function drawScene() {
|
|||||||
//--- First render pass -> Perlin Noise (it updates the perlin noise texture)
|
//--- First render pass -> Perlin Noise (it updates the perlin noise texture)
|
||||||
{
|
{
|
||||||
gl.bindFramebuffer(gl.FRAMEBUFFER, perlinNoiseFBO);
|
gl.bindFramebuffer(gl.FRAMEBUFFER, perlinNoiseFBO);
|
||||||
gl.viewport(0, 0, perlinNoiseFBOWidth, ferlinNoiseFBOHeight);
|
gl.viewport(0, 0, perlinNoiseFBOWidth, perlinNoiseFBOHeight);
|
||||||
|
|
||||||
//Clear buffer content
|
//Clear buffer content
|
||||||
gl.clearColor(1.0, 1.0, 1.0, 1);
|
gl.clearColor(1.0, 1.0, 1.0, 1);
|
||||||
gl.clear(gl.COLOR_BUFFER_BIT); //No depth buffer
|
gl.clear(gl.COLOR_BUFFER_BIT); //No depth buffer
|
||||||
|
|
||||||
|
// Disable face culling for fullscreen quad
|
||||||
|
gl.disable(gl.CULL_FACE);
|
||||||
|
|
||||||
//draw a fullscreen quad
|
//draw a fullscreen quad
|
||||||
gl.bindBuffer(gl.ARRAY_BUFFER, VBO);
|
gl.bindBuffer(gl.ARRAY_BUFFER, VBO);
|
||||||
|
|
||||||
@@ -372,13 +214,53 @@ function drawScene() {
|
|||||||
|
|
||||||
var projection = mat4.create();
|
var projection = mat4.create();
|
||||||
mat4.identity(projection);
|
mat4.identity(projection);
|
||||||
mat4.perspective(projection, 1.0, viewportWidth / viewportHeight, 0.1, 1000.); //projection mode should actually be camera specific
|
mat4.perspective(projection, Config.FOV, viewportWidth / viewportHeight, Config.NEAR_PLANE, Config.FAR_PLANE); //projection mode should actually be camera specific
|
||||||
|
|
||||||
|
// Handle camera movement and rotation based on mode
|
||||||
|
if (cameraMode === 'fps') {
|
||||||
|
// FPS camera - direct movement
|
||||||
|
camera = fpsCamera;
|
||||||
|
handleFPSCameraMovement();
|
||||||
|
|
||||||
|
// Apply mouse rotation for FPS mode
|
||||||
|
if (mouseXVel !== 0 || mouseYVel !== 0) {
|
||||||
|
fpsCamera.rotate(mouseXVel, mouseYVel);
|
||||||
|
mouseXVel = 0;
|
||||||
|
mouseYVel = 0;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Orbital camera - original behavior
|
||||||
|
camera = orbitalCamera;
|
||||||
|
orbitalCamera.setOffset(Config.CAMERA_DEFAULT_OFFSET + keyboardZoom);
|
||||||
|
orbitalCamera.setRotationX((curRotX += mouseYVel * Config.MOUSE_SENSITIVITY + keyboardRotationX));
|
||||||
|
orbitalCamera.setRotationY((curRotY += mouseXVel * Config.MOUSE_SENSITIVITY + keyboardRotationY));
|
||||||
|
}
|
||||||
|
|
||||||
camera.setOffset(1.2);
|
|
||||||
camera.setRotationX((curRotX += mouseYVel * 0.001));
|
|
||||||
camera.setRotationY((curRotY += mouseXVel * 0.001));
|
|
||||||
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)
|
||||||
|
gl.depthMask(false);
|
||||||
|
gl.disable(gl.DEPTH_TEST);
|
||||||
|
gl.disable(gl.CULL_FACE); // Disable face culling for skybox (we're inside)
|
||||||
|
gl.useProgram(skyProgram);
|
||||||
|
|
||||||
|
let sky_view_loc = gl.getUniformLocation(<WebGLProgram>skyProgram, "view");
|
||||||
|
gl.uniformMatrix4fv(sky_view_loc, false, view);
|
||||||
|
let sky_projection_loc = gl.getUniformLocation(<WebGLProgram>skyProgram, "projection");
|
||||||
|
gl.uniformMatrix4fv(sky_projection_loc, false, projection);
|
||||||
|
let sky_sun_loc = gl.getUniformLocation(<WebGLProgram>skyProgram, "uSunDirection");
|
||||||
|
gl.uniform3fv(sky_sun_loc, sunDirection);
|
||||||
|
|
||||||
|
skybox.draw(gl);
|
||||||
|
gl.enable(gl.DEPTH_TEST);
|
||||||
|
gl.depthMask(true);
|
||||||
|
gl.enable(gl.CULL_FACE); // Re-enable face culling for ocean
|
||||||
|
gl.cullFace(gl.BACK); // Cull back faces for ocean
|
||||||
|
|
||||||
var model = mat4.create();
|
var model = mat4.create();
|
||||||
mat4.identity(model);
|
mat4.identity(model);
|
||||||
let translationCentering = vec3.create();
|
let translationCentering = vec3.create();
|
||||||
@@ -398,16 +280,80 @@ function drawScene() {
|
|||||||
//gl.uniform1f(uTime_loc, timeSpent);
|
//gl.uniform1f(uTime_loc, timeSpent);
|
||||||
let displacementMap_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "displace_map");
|
let displacementMap_loc = gl.getUniformLocation(<WebGLProgram>defaultProgram, "displace_map");
|
||||||
gl.uniform1i(displacementMap_loc, 0); //Get texture from slot 0
|
gl.uniform1i(displacementMap_loc, 0); //Get texture from slot 0
|
||||||
gl.bindVertexArray(gridVAO);
|
oceanGrid.draw(gl);
|
||||||
gl.drawElements(gl.TRIANGLES, gridIndices.length, gl.UNSIGNED_INT, 0);
|
|
||||||
gl.bindVertexArray(null);
|
|
||||||
}
|
}
|
||||||
requestAnimationFrame(drawScene);
|
requestAnimationFrame(drawScene);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Handle FPS camera movement */
|
||||||
|
function handleFPSCameraMovement() {
|
||||||
|
const speed = keysPressed.has('Shift') ? fastMoveSpeed : moveSpeed;
|
||||||
|
|
||||||
|
// WASD for horizontal movement
|
||||||
|
if (keysPressed.has('w') || keysPressed.has('W')) {
|
||||||
|
fpsCamera.moveForward(speed);
|
||||||
|
}
|
||||||
|
if (keysPressed.has('s') || keysPressed.has('S')) {
|
||||||
|
fpsCamera.moveForward(-speed);
|
||||||
|
}
|
||||||
|
if (keysPressed.has('a') || keysPressed.has('A')) {
|
||||||
|
fpsCamera.moveRight(-speed);
|
||||||
|
}
|
||||||
|
if (keysPressed.has('d') || keysPressed.has('D')) {
|
||||||
|
fpsCamera.moveRight(speed);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Q/E for vertical movement
|
||||||
|
if (keysPressed.has('q') || keysPressed.has('Q')) {
|
||||||
|
fpsCamera.moveUp(-speed);
|
||||||
|
}
|
||||||
|
if (keysPressed.has('e') || keysPressed.has('E')) {
|
||||||
|
fpsCamera.moveUp(speed);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Space to go up, Ctrl to go down
|
||||||
|
if (keysPressed.has(' ')) {
|
||||||
|
fpsCamera.moveUp(speed);
|
||||||
|
}
|
||||||
|
if (keysPressed.has('Control')) {
|
||||||
|
fpsCamera.moveUp(-speed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Handle keyboard input for camera controls */
|
||||||
|
function handleKeyboardInput() {
|
||||||
|
keyboardRotationX = 0;
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function main() {
|
function main() {
|
||||||
const canvas: HTMLCanvasElement = <HTMLCanvasElement>document.getElementById("window");
|
const canvas: HTMLCanvasElement = <HTMLCanvasElement>document.getElementById("window");
|
||||||
initGL(canvas);
|
fpsDisplay = document.getElementById("fps-counter");
|
||||||
|
|
||||||
|
const updateCanvasSize = initGL(canvas);
|
||||||
|
if (!updateCanvasSize) {
|
||||||
|
console.error("Failed to initialize WebGL");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
var drag = false;
|
var drag = false;
|
||||||
var previousPosX: number | null;
|
var previousPosX: number | null;
|
||||||
@@ -439,12 +385,106 @@ function main() {
|
|||||||
canvas.addEventListener('mouseup', deactivateMouseMovement, false);
|
canvas.addEventListener('mouseup', deactivateMouseMovement, false);
|
||||||
canvas.addEventListener('mouseleave', deactivateMouseMovement, false);
|
canvas.addEventListener('mouseleave', deactivateMouseMovement, false);
|
||||||
|
|
||||||
|
// Keyboard controls
|
||||||
|
window.addEventListener('keydown', (evt) => {
|
||||||
|
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
|
||||||
|
if (evt.key === 'r' || evt.key === 'R') {
|
||||||
|
if (cameraMode === 'fps') {
|
||||||
|
fpsCamera = new FPSCamera(); // Reset to initial FPS position
|
||||||
|
camera = fpsCamera;
|
||||||
|
console.log('Camera reset to FPS default position');
|
||||||
|
} else {
|
||||||
|
curRotX = Config.CAMERA_DEFAULT_ROT_X;
|
||||||
|
curRotY = Config.CAMERA_DEFAULT_ROT_Y;
|
||||||
|
keyboardZoom = 0;
|
||||||
|
console.log('Camera reset to orbital default position');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prevent default for space to avoid page scroll
|
||||||
|
if (evt.key === ' ' && cameraMode === 'fps') {
|
||||||
|
evt.preventDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle orbital camera keyboard input
|
||||||
|
if (cameraMode === 'orbital') {
|
||||||
|
handleKeyboardInput();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener('keyup', (evt) => {
|
||||||
|
keysPressed.delete(evt.key);
|
||||||
|
|
||||||
|
if (cameraMode === 'orbital') {
|
||||||
|
handleKeyboardInput();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Window resize handler
|
||||||
|
window.addEventListener('resize', () => {
|
||||||
|
updateCanvasSize(canvas);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Camera mode toggle from UI controls
|
||||||
|
window.addEventListener('toggleCameraMode', () => {
|
||||||
|
cameraMode = cameraMode === 'fps' ? 'orbital' : 'fps';
|
||||||
|
camera = cameraMode === 'fps' ? fpsCamera : orbitalCamera;
|
||||||
|
console.log(`Camera mode switched to: ${cameraMode.toUpperCase()}`);
|
||||||
|
|
||||||
|
// Update display
|
||||||
|
const modeText = document.createElement('div');
|
||||||
|
modeText.id = 'camera-mode';
|
||||||
|
modeText.style.cssText = 'position: absolute; top: 40px; left: 10px; color: white; font-family: monospace;';
|
||||||
|
modeText.textContent = `Camera: ${cameraMode.toUpperCase()}`;
|
||||||
|
|
||||||
|
const existingMode = document.getElementById('camera-mode');
|
||||||
|
if (existingMode) {
|
||||||
|
existingMode.textContent = `Camera: ${cameraMode.toUpperCase()}`;
|
||||||
|
} else {
|
||||||
|
document.body.appendChild(modeText);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
initShaders();
|
initShaders();
|
||||||
initGeometry();
|
initGeometry();
|
||||||
initFBO();
|
initFBO();
|
||||||
initGridVAO();
|
|
||||||
|
|
||||||
camera = new Camera();
|
oceanGrid = new Grid(Config.GRID_SIZE);
|
||||||
|
oceanGrid.initVAO(gl);
|
||||||
|
|
||||||
|
skybox = new Skybox();
|
||||||
|
skybox.initVAO(gl);
|
||||||
|
|
||||||
|
// Initialize both cameras
|
||||||
|
orbitalCamera = new OrbitalCamera();
|
||||||
|
fpsCamera = new FPSCamera();
|
||||||
|
camera = fpsCamera; // Start with FPS camera
|
||||||
|
|
||||||
|
console.log('Cameras initialized - Press C to toggle between FPS and Orbital modes');
|
||||||
|
|
||||||
//Check if any errors apeared during init.
|
//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!: ");
|
||||||
|
|||||||
@@ -1,63 +1,18 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
/* Basic Options */
|
"target": "ES2020",
|
||||||
// "incremental": true, /* Enable incremental compilation */
|
"module": "ESNext",
|
||||||
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
|
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||||
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
|
"sourceMap": true,
|
||||||
// "lib": [], /* Specify library files to be included in the compilation. */
|
"outDir": "./build/",
|
||||||
// "allowJs": true, /* Allow javascript files to be compiled. */
|
"strict": true,
|
||||||
// "checkJs": true, /* Report errors in .js files. */
|
"moduleResolution": "bundler",
|
||||||
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
|
"resolveJsonModule": true,
|
||||||
// "declaration": true, /* Generates corresponding '.d.ts' file. */
|
"esModuleInterop": true,
|
||||||
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
|
"allowSyntheticDefaultImports": true,
|
||||||
"sourceMap": true, /* Generates corresponding '.map' file. */
|
"forceConsistentCasingInFileNames": true,
|
||||||
// "outFile": "./", /* Concatenate and emit output to single file. */
|
"skipLibCheck": true
|
||||||
"outDir": "./build/", /* Redirect output structure to the directory. */
|
|
||||||
// "rootDir": "./src/", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
|
|
||||||
// "composite": true, /* Enable project compilation */
|
|
||||||
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
|
|
||||||
// "removeComments": true, /* Do not emit comments to output. */
|
|
||||||
// "noEmit": true, /* Do not emit outputs. */
|
|
||||||
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
|
|
||||||
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
|
|
||||||
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
|
|
||||||
/* Strict Type-Checking Options */
|
|
||||||
"strict": true, /* Enable all strict type-checking options. */
|
|
||||||
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
|
|
||||||
// "strictNullChecks": true, /* Enable strict null checks. */
|
|
||||||
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
|
|
||||||
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
|
|
||||||
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
|
|
||||||
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
|
|
||||||
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
|
|
||||||
/* Additional Checks */
|
|
||||||
// "noUnusedLocals": true, /* Report errors on unused locals. */
|
|
||||||
// "noUnusedParameters": true, /* Report errors on unused parameters. */
|
|
||||||
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
|
|
||||||
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
|
|
||||||
/* Module Resolution Options */
|
|
||||||
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
|
|
||||||
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
|
|
||||||
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
|
|
||||||
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
|
|
||||||
// "typeRoots": [], /* List of folders to include type definitions from. */
|
|
||||||
// "types": [], /* Type declaration files to be included in compilation. */
|
|
||||||
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
|
|
||||||
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
|
|
||||||
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
|
|
||||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
|
||||||
/* Source Map Options */
|
|
||||||
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
|
|
||||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
|
||||||
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
|
|
||||||
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
|
|
||||||
/* Experimental Options */
|
|
||||||
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
|
|
||||||
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
|
|
||||||
/* Advanced Options */
|
|
||||||
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
|
|
||||||
},
|
},
|
||||||
"files": [
|
"include": ["src/**/*"],
|
||||||
"src/main.ts"
|
"exclude": ["node_modules", "dist", "build"]
|
||||||
]
|
|
||||||
}
|
}
|
||||||
15
vite.config.ts
Normal file
15
vite.config.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import { defineConfig } from 'vite';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
base: './',
|
||||||
|
build: {
|
||||||
|
outDir: 'dist',
|
||||||
|
sourcemap: true,
|
||||||
|
minify: 'esbuild',
|
||||||
|
target: 'es2020',
|
||||||
|
},
|
||||||
|
server: {
|
||||||
|
port: 3000,
|
||||||
|
open: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user