forked from s-macke/VoxelSpace
-
Notifications
You must be signed in to change notification settings - Fork 2
/
VoxelSpace.html
executable file
·600 lines (509 loc) · 15.3 KB
/
VoxelSpace.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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
<!DOCTYPE html>
<html>
<head>
<title>Vancouver Lidar Voxel Space</title>
<meta charset="UTF-8">
<meta name="description" content="Vancouver Lidar 3d Voxel Space">
<meta name="author" content="John Hawthorn and Sebastian Macke">
<meta name="keywords" content="Vancouver, Voxel, VoxelSpace, Voxel Space, Comanche, landscape, rendering">
<style>
html, body {margin: 0; height: 100%; overflow: hidden}
canvas { width: 100%; height: 100%; }
a { color: white; }
#info {
position: absolute;
top: 0px;
width: 100%;
padding: 5px;
z-index:100;
color: white;
font-family: "Arial", Times, serif;
font-size: 120%;
}
#fps {
float: right;
position: absolute;
top: 0px;
right: 10px;
z-index:100;
padding: 5px;
color: white;
font-family: "Arial", Times, serif;
font-size: 120%;
}
</style>
</head>
<body scroll="no">
<div id="fps">
</div>
<div id="info">
Fly controls
<b>WASD</b> or <b>Cursor Keys</b> or <b>left click</b> move, <b>R|F</b> up | down, <b>Q|E</b> pitch,
<br>
<label for="distancerange">Distance</label>
<input id="distancerange" type="range" min="100" max="2000" step="1" onchange="camera.distance = this.value">
<a href="https://github.com/jhawthorn/VoxelSpace">Project Information</a>
</div>
<canvas id="myCanvas" width="800" height="400">
Your browser does not support the canvas element.
</canvas>
<script>
"use strict";
// ---------------------------------------------
// Viewer information
var camera =
{
x: 17713., // x position on the map
y: 11046., // y position on the map
height: 64*256., // height of the camera
angle: 0., // direction of the camera
horizon: 100., // horizon position (look up and down)
distance: 800 // distance of map
};
// ---------------------------------------------
// Landscape data
var map =
{
width: 2048,
height: 2048,
shift: 11, // power of two: 2^10 = 1024
};
var tiles = [];
// ---------------------------------------------
// Screen data
var screendata =
{
canvas: null,
context: null,
imagedata: null,
bufarray: null, // color data
buf8: null, // the same array but with bytes
buf32: null, // the same array but with 32-Bit words
backgroundcolor: 0xFF333333
};
// ---------------------------------------------
// Keyboard and mouse interaction
var input =
{
forwardbackward: 0,
leftright: 0,
updown: 0,
lookup: false,
lookdown: false,
mouseposition: null,
keypressed: false
}
var updaterunning = false;
var time = new Date().getTime();
// for fps display
var timelastframe = new Date().getTime();
var frames = 0;
function getTile(x, y) {
if(x < 0 || y < 0)
return null;
x = x / map.width | 0;
y = y / map.height | 0;
if(tiles[y] === undefined)
return null;
return tiles[y][x];
}
function ClearFar() {
var lowx = (camera.x - camera.distance * 2) / map.width | 0;
var lowy = (camera.y - camera.distance * 2) / map.height | 0;
var highx = (camera.x + camera.distance * 2) / map.width | 0;
var highy = (camera.y + camera.distance * 2) / map.height | 0;
for(var y = 0; y < lowy; y++)
delete tiles[y];
for(var y = highy+1; y < tiles.length; y++)
delete tiles[y];
for(var y = lowy; y <= highy; y++) {
if(tiles[y] === undefined)
continue;
for(var x = 0; x < lowx; x++)
delete tiles[y][x];
for(var x = highx+1; x < tiles[y].length; x++)
delete tiles[y][x];
}
}
var loading = [];
function FetchNear() {
var lowx = (camera.x - camera.distance) / map.width | 0;
var lowy = (camera.y - camera.distance) / map.height | 0;
var highx = (camera.x + camera.distance) / map.width | 0;
var highy = (camera.y + camera.distance) / map.height | 0;
for(var y = lowy; y <= highy; y++) {
for(var x = lowx; x <= highx; x++) {
if(tiles[y] && tiles[y][x]) {
continue;
}
var str = "" + y + "," + x;
if(loading.indexOf(str) < 0) {
loading.push(str);
console.log("loading tile " + str);
var e = 4830 + x*10;
var n = 54620 - y*10;
LoadMap(x, y, "" + e + "E_" + n + "N", function() {
var idx = loading.indexOf(str);
loading.splice(idx, 1);
});
}
}
}
}
// Update the camera for next frame. Dependent on keypresses
function UpdateCamera()
{
var current = new Date().getTime();
input.keypressed = false;
if (input.leftright != 0)
{
camera.angle += input.leftright*0.1*(current-time)*0.03;
input.keypressed = true;
}
if (input.forwardbackward != 0)
{
camera.x -= input.forwardbackward * Math.sin(camera.angle) * (current-time)*0.03;
camera.y -= input.forwardbackward * Math.cos(camera.angle) * (current-time)*0.03;
input.keypressed = true;
}
if (input.updown != 0)
{
camera.height += input.updown * (current-time)*0.03;
input.keypressed = true;
}
if (input.lookup)
{
camera.horizon += 2 * (current-time)*0.1;
input.keypressed = true;
}
if (input.lookdown)
{
camera.horizon -= 2 * (current-time)*0.1;
input.keypressed = true;
}
// Collision detection. Don't fly below the surface.
var mapoffset = ((Math.floor(camera.y) & (map.width-1)) << map.shift) + (Math.floor(camera.x) & (map.height-1))|0;
var cameraHeight = 200;
var tile = getTile(camera.x, camera.y);
if (tile && (tile.altitude[mapoffset]+cameraHeight) > camera.height) camera.height = tile.altitude[mapoffset] + cameraHeight;
time = current;
}
// ---------------------------------------------
// Keyboard and mouse event handlers
// ---------------------------------------------
// Keyboard and mouse event handlers
function GetMousePosition(e)
{
// fix for Chrome
if (e.type.startsWith('touch'))
{
return [e.targetTouches[0].pageX, e.targetTouches[0].pageY];
} else
{
return [e.pageX, e.pageY];
}
}
function DetectMouseDown(e)
{
input.forwardbackward = 6.;
input.mouseposition = GetMousePosition(e);
time = new Date().getTime();
if (!updaterunning) Draw();
return;
}
function DetectMouseUp()
{
input.mouseposition = null;
input.forwardbackward = 0;
input.leftright = 0;
input.updown = 0;
return;
}
function DetectMouseMove(e)
{
e.preventDefault();
if (input.mouseposition == null) return;
if (input.forwardbackward == 0) return;
var currentMousePosition = GetMousePosition(e);
input.leftright = (input.mouseposition[0] - currentMousePosition[0]) / window.innerWidth * 2;
camera.horizon = 100 + (input.mouseposition[1] - currentMousePosition[1]) / window.innerHeight * 500;
input.updown = (input.mouseposition[1] - currentMousePosition[1]) / window.innerHeight * 2000;
}
function DetectKeysDown(e)
{
switch(e.keyCode)
{
case 37: // left cursor
case 65: // a
input.leftright = +1.;
break;
case 39: // right cursor
case 68: // d
input.leftright = -1.;
break;
case 38: // cursor up
case 87: // w
input.forwardbackward = 3.;
break;
case 40: // cursor down
case 83: // s
input.forwardbackward = -3.;
break;
case 82: // r
input.updown = +200.;
break;
case 70: // f
input.updown = -200.;
break;
case 69: // e
input.lookup = true;
break;
case 81: //q
input.lookdown = true;
break;
default:
return;
break;
}
if (!updaterunning) {
time = new Date().getTime();
Draw();
}
return false;
}
function DetectKeysUp(e)
{
switch(e.keyCode)
{
case 37: // left cursor
case 65: // a
input.leftright = 0;
break;
case 39: // right cursor
case 68: // d
input.leftright = 0;
break;
case 38: // cursor up
case 87: // w
input.forwardbackward = 0;
break;
case 40: // cursor down
case 83: // s
input.forwardbackward = 0;
break;
case 82: // r
input.updown = 0;
break;
case 70: // f
input.updown = 0;
break;
case 69: // e
input.lookup = false;
break;
case 81: //q
input.lookdown = false;
break;
default:
return;
break;
}
return false;
}
// ---------------------------------------------
// Fast way to draw vertical lines
function DrawVerticalLine(x, ytop, ybottom, col)
{
x = x|0;
ytop = ytop|0;
ybottom = ybottom|0;
col = col|0;
var buf32 = screendata.buf32;
var screenwidth = screendata.canvas.width|0;
if (ytop < 0) ytop = 0;
if (ytop > ybottom) return;
// get offset on screen for the vertical line
var offset = ((ytop * screenwidth) + x)|0;
for (var k = ytop|0; k < ybottom|0; k=k+1|0)
{
buf32[offset|0] = col|0;
offset = offset + screenwidth|0;
}
}
// ---------------------------------------------
// Basic screen handling
function DrawBackground()
{
var buf32 = screendata.buf32;
var color = screendata.backgroundcolor|0;
for (var i = 0; i < buf32.length; i++) buf32[i] = color|0;
}
// Show the back buffer on screen
function Flip()
{
screendata.imagedata.data.set(screendata.buf8);
screendata.context.putImageData(screendata.imagedata, 0, 0);
}
// ---------------------------------------------
// The main render routine
function Render()
{
var mapwidthperiod = map.width - 1;
var mapheightperiod = map.height - 1;
var screenwidth = screendata.canvas.width|0;
var sinang = Math.sin(camera.angle);
var cosang = Math.cos(camera.angle);
var hiddeny = new Int32Array(screenwidth);
for(var i=0; i<screendata.canvas.width|0; i=i+1|0)
hiddeny[i] = screendata.canvas.height;
var dz = 1.;
// Draw from front to back
for(var z=1; z<camera.distance; z+=dz)
{
// 90 degree field of view
var plx = -cosang * z - sinang * z;
var ply = sinang * z - cosang * z;
var prx = cosang * z - sinang * z;
var pry = -sinang * z - cosang * z;
var dx = (prx - plx) / screenwidth;
var dy = (pry - ply) / screenwidth;
plx += camera.x;
ply += camera.y;
var invz = 1. / z * 4.;
for(var i=0; i<screenwidth|0; i=i+1|0)
{
var tile = getTile(plx, ply);
if(tile) {
var mapoffset = ((Math.floor(ply) & mapwidthperiod) << map.shift) + (Math.floor(plx) & mapheightperiod)|0;
var heightonscreen = (camera.height - tile.altitude[mapoffset]) * invz + camera.horizon|0;
if (heightonscreen < hiddeny[i]) {
DrawVerticalLine(i, heightonscreen|0, hiddeny[i], tile.color[mapoffset]);
hiddeny[i] = heightonscreen;
}
}
plx += dx;
ply += dy;
}
//dz += 0.01;
}
}
// ---------------------------------------------
// Draw the next frame
function Draw()
{
updaterunning = true;
UpdateCamera();
FetchNear();
DrawBackground();
Render();
window.requestAnimationFrame(function(){
Flip();
frames++;
if (!input.keypressed)
{
updaterunning = false;
} else
{
window.setTimeout(Draw, 0);
}
});
}
// ---------------------------------------------
// Init routines
// Util class for downloading the png
function DownloadImagesAsync(urls, OnSuccess) {
var pending = urls.length;
var result = [];
OnSuccess = OnSuccess.bind(null, result);
if (pending === 0) {
setTimeout(OnSuccess, 0);
return;
}
var onLoad = function(image, i) {
var tempcanvas = document.createElement("canvas");
var tempcontext = tempcanvas.getContext("2d");
tempcanvas.width = map.width;
tempcanvas.height = map.height;
tempcontext.drawImage(image, 0, 0, map.width, map.height);
result[i] = tempcontext.getImageData(0, 0, map.width, map.height).data;
pending--;
if (pending === 0) {
setTimeout(OnSuccess, 0);
}
}
urls.forEach(function(url, i) {
var image = new Image();
//image.addEventListener("load", function() {
image.onload = function() {
setTimeout(function() { onLoad(image, i) }, 0);
};
image.src = url;
image.crossOrigin = "Anonymous";
});
}
var tile_basepath = "https://vancouver-heightmaps.s3.amazonaws.com/heightmaps-2018/"
function LoadMap(x, y, file, callback)
{
DownloadImagesAsync([tile_basepath + file + ".png"], function(images) {
console.log("loaded " + x + ", " + y)
if(!tiles[y])
tiles[y] = [];
tiles[y][x] = imageToTile(images[0]);
if(callback) {
callback();
}
Draw();
});
}
function imageToTile(datah) {
var tile = {
altitude: new Uint16Array(2048*2048), // 1024 * 1024 byte array with height information
color: new Uint32Array(2048*2048) // 1024 * 1024 int array with RGB colors
};
for(var i=0; i<map.width*map.height; i++) {
tile.altitude[i] = datah[(i<<2)+1]*256 + datah[(i<<2)+2];
var c = datah[(i<<2)];
tile.color[i] = 0xFF000000 | c << 16 | c << 8 | c;
}
return tile;
}
function OnResizeWindow()
{
screendata.canvas = document.getElementById('myCanvas');
var aspect = window.innerWidth / window.innerHeight;
screendata.canvas.width = window.innerWidth<800?window.innerWidth:800;
screendata.canvas.height = screendata.canvas.width / aspect;
if (screendata.canvas.getContext)
{
screendata.context = screendata.canvas.getContext('2d');
screendata.imagedata = screendata.context.createImageData(screendata.canvas.width, screendata.canvas.height);
}
screendata.bufarray = new ArrayBuffer(screendata.imagedata.width * screendata.imagedata.height * 4);
screendata.buf8 = new Uint8Array(screendata.bufarray);
screendata.buf32 = new Uint32Array(screendata.bufarray);
Draw();
}
function Init()
{
OnResizeWindow();
// set event handlers for keyboard, mouse, touchscreen and window resize
document.onkeydown = DetectKeysDown;
document.onkeyup = DetectKeysUp;
document.onmousedown = DetectMouseDown;
document.onmouseup = DetectMouseUp;
document.onmousemove = DetectMouseMove;
document.ontouchstart = DetectMouseDown;
document.ontouchend = DetectMouseUp;
document.ontouchmove = DetectMouseMove;
window.onresize = OnResizeWindow;
window.setInterval(function(){
var current = new Date().getTime();
document.getElementById('fps').innerText = (frames / (current-timelastframe) * 1000).toFixed(1) + " fps";
//document.getElementById('fps').innerText = (frames / (current-timelastframe) * 1000).toFixed(1) + " fps " + camera.x + ", " + camera.y;
frames = 0;
timelastframe = current;
ClearFar();
}, 2000);
}
Init();
</script>
</body>