-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
527 lines (426 loc) · 18.3 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
<!DOCTYPE html>
<html>
<head>
<title>Terrain Generator</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chroma-js/2.4.2/chroma.min.js"></script>
<script src="gif.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>-->
<script src="//cdnjs.cloudflare.com/ajax/libs/seedrandom/3.0.5/seedrandom.min.js">
</script>
<style>
body {
margin: 0;
overflow: hidden;
}
#controls {
background-color: whitesmoke;
position: fixed;
width: 240px;
padding: 16px;
top: 24px;
right: 24px;
}
</style>
</head>
<body>
<div id="container">
<canvas id="canvas"></canvas>
</div>
<div id="controls">
Point Count
<input id="pointcount" type="range" min="500" max="250000" value="25000">
<h5>Ridges</h5>
Max Ridge Length
<input id="ridgelen" type="range" min="1" max="500" value="50">
Max Distance
<input id="maxdistance" type="range" min="1" max="100" value="10">
Peaks
<input id="peaks" type="range" min="1" max="1000" value="50">
Max Height
<input id="maxheight" type="range" min="1" max="50" value="10">
<br>
<div>
<label>
<input id="smooth" name="smooth" type="checkbox">
<span>Smooth</span>
</label>
<br />
<label>
<input id="rainfall" name="rainfall" type="checkbox">
<span>Rainfall (experimental)</span>
</label>
<label>
<input id="rotate" name="rotate" type="checkbox" checked>
<span>Rotate</span>
</label>
</div>
<br />
<a id="regenerate" class="waves-effect waves-light btn-small">Regenerate</a>
<a id="generategif" class="waves-effect waves-light btn-small">Download GIF</a>
</div>
</body>
<script type="module">
import Delaunator from 'https://cdn.skypack.dev/[email protected]';
import {OrbitControls} from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/controls/OrbitControls.js';
import {Node} from './node.js';
import {calculateRainfall} from './rainfall.js';
let container, canvas;
let camera, scene, renderer;
let landscapeMesh;
let gifRendering = false;
// Landscape parameters
let seed = "josh";
let landscapePointCount;
let landscapeMaxDistance;
let landscapeRidgeLength;
let landscapeRidgeAngleMax = true;
let landscapePeaksCount;
let landscapeMaxHeight;
let landscapeRotate;
let landscapeSmooth;
let landscapeRainfall;
// Add listeners for controls changing
const inputs = document.querySelectorAll('input');
inputs.forEach((input) => {
input.addEventListener('change', updateLandscapeParameters);
});
const regenerateButton = document.querySelector('#regenerate');
if (regenerateButton != undefined) {
regenerateButton.addEventListener('click', () => {
seed = Date.now().toString();
updateLandscapeParameters(null);
});
}
// Add listener for generating gif
const generateGifButton = document.querySelector('#generategif');
generateGifButton.addEventListener('click', function () {
gifRendering = true;
generateGifButton.disabled = true;
const oldGenerateGifButtonText = generateGifButton.textContent;
generateGifButton.textContent = 'Rendering...'
let gif = new GIF({
workers: 32,
debug: true,
quality: 30,
transparent: 0x111111,
});
const gifCanvas = document.createElement('canvas');
gifCanvas.width = 512; //canvas.width;
gifCanvas.height = 512 * canvas.height / canvas.width;
const context = gifCanvas.getContext('2d');
// Generate
for (let i = 0.0; i <= 1.0; i += 0.01) {
render(i);
context.drawImage(canvas, 0, 0, gifCanvas.width, gifCanvas.height);
gif.addFrame(gifCanvas, {copy: true, delay: 100});
}
// Once we've written out all the frames, we can resume normal rendering
gifRendering = false;
// When finished, automatically download the gif
gif.on('finished', function(blob) {
const link = document.createElement( 'a' );
link.href = URL.createObjectURL( blob );
link.download = 'animation.gif';
link.dispatchEvent( new MouseEvent( 'click' ) );
// Reset the rendering flag as well as the button to export
generateGifButton.disabled = false;
generateGifButton.textContent = oldGenerateGifButtonText;
});
// Begin rendering through the workers
gif.render()
});
function updateLandscapeParameters(e) {
landscapePointCount = document.querySelector("#pointcount").value;
landscapeRidgeLength = document.querySelector("#ridgelen").value;
landscapeMaxDistance = document.querySelector("#maxdistance").value;
landscapePeaksCount = document.querySelector("#peaks").value;
landscapeMaxHeight = document.querySelector("#maxheight").value / 10; // Sliders don't seem to work with floats?
landscapeRotate = document.querySelector("#rotate").checked;
landscapeSmooth = document.querySelector("#smooth").checked;
landscapeRainfall = document.querySelector("#rainfall").checked;
// Consistent seeding :D
Math.seedrandom(seed);
// Clean up and remove the old landscape mesh
if (landscapeMesh != undefined) {
const o = scene.getObjectByProperty('uuid', landscapeMesh.uuid);
if (o != undefined) {
o.geometry.dispose();
o.material.dispose();
scene.remove(o);
}
}
landscapeMesh = generateLandscape();
scene.add(landscapeMesh);
}
init();
updateLandscapeParameters(null);
requestAnimationFrame(animate);
function init() {
container = document.getElementById( 'container' );
camera = new THREE.PerspectiveCamera( 27, window.innerWidth / window.innerHeight, 1, 3500 );
scene = new THREE.Scene();
scene.background = new THREE.Color( 0x111111 );
//scene.fog = new THREE.Fog( 0x050505, 2000, 3500 );
// Lighting
//scene.add( new THREE.AmbientLight( 0x444444 ) );
let position = [0, 50, -100];
const light1 = new THREE.DirectionalLight( 0xFDFBD3, 0.7 );
//light1.castShadow = true;
light1.position.set(...position);
scene.add( light1 );
/*
const sphereGeometry = new THREE.SphereGeometry( 1, 32, 16 );
const sphereMaterial = new THREE.MeshBasicMaterial({color: 0xFFFFFF});
const sphereMesh = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphereMesh.position.set(...position);
scene.add(sphereMesh);
const light2 = new THREE.DirectionalLight( 0xffffff, 1.5 );
light2.position.set( 0, - 1, 0 );
scene.add( light2 );
*/
/*
const gridHelper = new THREE.GridHelper( 100, 100, 0x990000, 0x444444 );
scene.add( gridHelper );
*/
canvas = document.getElementById('canvas');
renderer = new THREE.WebGLRenderer({canvas: canvas});
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.outputEncoding = THREE.sRGBEncoding;
const controls = new OrbitControls( camera, renderer.domElement );
camera.position.set( 10, 6, 10 );
controls.update();
window.addEventListener( 'resize', onWindowResize );
}
function generateLandscape() {
// Delaunay triangulation
var coords = [];
var nodes = []
// Create points on a 20x20 grid
for (let i = 0; i < landscapePointCount; i++) {
var x = Math.random() * 10 - 5;
var y = Math.random() * 10 - 5;
coords.push(x, y);
nodes.push(new Node(i, x, y));
}
const delaunay = new Delaunator(coords);
// Connect nodes to each other
for (let i = 0; i < delaunay.triangles.length; i += 3) {
for (let j = 0; j < 3; j += 1) {
let p = delaunay.triangles[i + j];
for (let k = 0; k < 3; k += 1) {
let neighbor = delaunay.triangles[i + k];
if (neighbor == p) {
continue;
}
nodes[p].addNeighbors(nodes[neighbor]);
}
}
}
// Centers each node. Can lead to weirdness around edges.
if (landscapeSmooth) {
nodes.forEach((node) => {
node.center();
});
}
// Height functions
// Ideally these are plug-and-playable.
function calculateHeight(troughInversion, originHeight, formerHeight, maxDistance, distance) {
let newHeight = (troughInversion - troughInversion * distance / maxDistance) * originHeight; //* (0.9 + Math.random() * 0.1);
let blendDistance = maxDistance;
if (distance > maxDistance - blendDistance && formerHeight !== undefined) {
// Blend current height in
let newBlend = maxDistance - distance;
let formerBlend = blendDistance - newBlend;
newHeight = (newBlend * newHeight + formerBlend * formerHeight) / blendDistance;
}
return newHeight;
}
for ( let i = 0; i < landscapePeaksCount; i++ ) {
let origin = nodes[Math.floor(Math.random() * nodes.length)];
let limit = 2.5;
if (origin.x < -limit || origin.x > limit || origin.y < -limit || origin.y > limit) {
i--;
continue;
}
let minDistance = landscapePointCount / 10000;
let maxDistance = Math.floor(Math.random() * landscapeMaxDistance + minDistance);
let ridgeLength = Math.floor(Math.random() * landscapeRidgeLength) + 2;
let originHeight = 0.5 + (Math.random() * landscapeMaxHeight - 0.5);
/* Instead of starting at a random height > 0.5,
* 10% - start at 0.1 (plains)
* 20% - start at the origin height
*/
let chance = Math.random();
if (chance > 0.8) {
originHeight = 0.1;
} else if (chance > 0.6) {
originHeight = origin.height;
}
// -1 if we want to invert the ridge (for example, sea troughs)
let troughInversion = 1;
if (Math.random() > 0.9) {
troughInversion = -1;
}
let seen = new Set();
seen.add(origin);
let q = [origin];
let distances = {};
distances[origin.id] = 0;
// Build the ridgeline from unique nodes
let node = [...origin.neighbors][Math.floor(Math.random() * origin.neighbors.size)];
for (let j = 0; j < ridgeLength; j++ ) {
q.push(node);
distances[node.id] = 0;
seen.add(node.id);
let options = [];
for (let neighbor of node.neighbors) {
if (seen.has(neighbor.id)) {
continue;
}
options.push(neighbor);
}
if (options.length == 0) {
break;
}
//landscapeRidgeAngleMax = false;
if (landscapeRidgeAngleMax && q.length > 2) {
// Determine the option with the maximum angle relative to the incoming node
let priorNode = q[q.length - 2];
let aLen = Math.sqrt((node.x - priorNode.x) ** 2 + (node.y - priorNode.y) ** 2);
let angle, bestAngle = 0, bestNode;
let bLen, cLen;
for (let optionNode of options) {
bLen = Math.sqrt((node.x - optionNode.x) ** 2 + (node.y - optionNode.y) ** 2);
cLen = Math.sqrt((priorNode.x - optionNode.x) ** 2 + (priorNode.y - optionNode.y) ** 2);
// Cosine rule
angle = Math.acos((aLen ** 2 + bLen ** 2 - cLen ** 2) / (2 * aLen * bLen));
if (angle > bestAngle) {
bestAngle = angle;
bestNode = optionNode;
}
// Quick exit if we've found a "big enough" angle
// this leads to clockwise spirals, I believe due to neighbor order
/*
if (angle > (Math.PI / 1.75)) {
break;
}
*/
}
node = bestNode;
} else {
// Pick a random node we haven't seen to add to the ridgeline
node = options[Math.floor(Math.random() * options.length)];
}
// Could also look at the angle between the node we come from, this node, and the neighbors,
//to find the arm with the greatest angle
}
while (q.length > 0) {
let node = q.shift();
let distance = distances[node.id];
let newHeight = calculateHeight(troughInversion, originHeight, node['height'], maxDistance, distance);
node.height = newHeight;
if (newHeight > node.height || node.height == 0) {
node.height = newHeight; // * (1.0 - Math.random() * 0.05);
}
// If in blend range, blend edges
if (distance == maxDistance) {
node.edge = true;
continue;
}
node.edge = false;
for (let neighbor of node.neighbors) {
if (neighbor.id in distances) {
continue;
}
distances[neighbor.id] = distance + 1;
q.push(neighbor);
}
}
}
// Create a new material to represent our rainfall
if (landscapeRainfall) {
const rainfallMaterial = new THREE.LineBasicMaterial( { color: 0x0099ff } );
// Other landscape processing
let rainfallRecieved = calculateRainfall(nodes);
let maxRainfallRecieved = 0.0;
for (const [k, v] of Object.entries(rainfallRecieved)) {
let node = nodes[k];
maxRainfallRecieved = Math.max(maxRainfallRecieved, v);
const rainfallPoints = [];
rainfallPoints.push(new THREE.Vector3(node.x, 1, node.y));
rainfallPoints.push(new THREE.Vector3(node.x, 1 + (v / 25), node.y));
const rainfallGeometry = new THREE.BufferGeometry().setFromPoints( rainfallPoints );
const line = new THREE.Line( rainfallGeometry, rainfallMaterial );
//scene.add(line);
}
// Adjust height based on the rainfall recieved
console.log(maxRainfallRecieved);
for (let node of nodes) {
node.height = Math.max(0.0, node.height - (rainfallRecieved[node.id] / maxRainfallRecieved) * 1.0);
}
}
const geometry = new THREE.BufferGeometry();
const positions = [];
const indices = [];
const normals = [];
const colors = [];
// Create a vertex from index node so we can index them
for (let i = 0; i < nodes.length; i++) {
let node = nodes[i];
positions.push(node.x, node.height, node.y);
colors.push(...node.color(landscapeMaxHeight));
}
for ( let i = 0; i < delaunay.triangles.length; i += 3 ) {
let currentNodes = [];
let nodeIdx;
// Positions
for (let j = 0; j < 3; j++) {
nodeIdx = (delaunay.triangles[i + j] * 2) / 2;
indices.push(nodeIdx);
currentNodes.push(nodes[nodeIdx]);
}
}
function disposeArray() {
this.array = null;
}
geometry.setIndex(indices);
geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ).onUpload( disposeArray ) );
//geometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ).onUpload( disposeArray ) );
geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( colors, 4 ).onUpload( disposeArray ) );
geometry.computeBoundingSphere();
const material = new THREE.MeshToonMaterial( {
color: 0xaaaaaa,
side: THREE.DoubleSide,
vertexColors: true,
transparent: true,
wireframe: false,
});
//material.shading = THREE.SmoothShading;
geometry.computeVertexNormals(true);
return new THREE.Mesh( geometry, material );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate(time) {
// Only render if we're not rendering out a GIF already
if (!gifRendering) {
// 20000 is the number of milliseconds required to do a full rotation
render( (time / 20000) % 1 );
}
requestAnimationFrame( animate );
}
// Progress goes from 0 to 1
function render(progress) {
if (landscapeRotate) {
landscapeMesh.rotation.y = progress * Math.PI * 2;
}
renderer.render( scene, camera );
}
</script>
</html>