-
Notifications
You must be signed in to change notification settings - Fork 2
/
index_new.html
663 lines (592 loc) · 20.6 KB
/
index_new.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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />
<meta name="mobile-web-app-capable" content="yes">
<title>AR - fur shurr</title>
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="./js/canvas2image.js"></script>
<script src='./js/three.min.js'></script>
<script src="./js/shaders/SSAOShader.js"></script>
<script src="./js/shaders/CopyShader.js"></script>
<script src="./js/postprocessing/EffectComposer.js"></script>
<script src="./js/postprocessing/RenderPass.js"></script>
<script src="./js/postprocessing/ShaderPass.js"></script>
<script src="./js/postprocessing/MaskPass.js"></script>
<script src="./js/postprocessing/SSAOPass.js"></script>
<script src="./js/OBJLoader.js"></script>
<script src="./js/MTLLoader.js"></script>
<script src="./js/ColladaLoader.js"></script>
<script src="./js/ar.js"></script>
<script src="https://unpkg.com/merge-images"></script>
<script src="./js/download.js"></script>
<script>
THREEx.ArToolkitContext.baseURL = './'
</script>
<style media="screen">
html,
body {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
#blinds {
font-family: "Courier New";
text-align: center;
font-size: 6vw;
color: white
}
#blinds:before {
content: "";
display: inline-block;
height: 75%;
vertical-align: middle;
}
canvas {
z-index: -1
}
</style>
</head>
<body>
<!-- snappy stuff -->
<button id="snap-button" style="display: block; margin: 0 auto;z-index:10" onclick="snappysnap()"> snappy sneks </button>
<div id="blinds" style="position:absolute;margin:0;width:100%;height:100%;background:rgba(0,0,0,0.7);line-height:100%">
Find the Marker
<img style="position:absolute;width:120px;height:120px;margin-left:-60px;margin-top:-10px;left:50%;top:50%;" src="./assets/gp.png" alt="">
</div>
<script>
//////////////////////////////////////////////////////////////////////////////////
// Init
//////////////////////////////////////////////////////////////////////////////////
var date;
var orbitRadius = 7;
var treeposses = [];
var treespacing = 0.8;
var trees = {
"beech_tree": {
parent: "island_forest",
scale: [0.02, 0.02, 0.02]
},
"pine_tree": {
parent: "island_forest",
scale: [0.003, 0.0065, 0.003]
}
}
let islands = {
"island_forest": {
position: [-2.2, 2, -3.5],
scale: [0.03, 0.02, 0.02]
},
"island_main": {
position: [1.2, 1.5, 1],
scale: [0.03, 0.03, 0.03]
},
"island_lake": {
position: [-2, 1.8, 2.5],
scale: [0.03, 0.03, 0.03]
}
}
// array of functions for the rendering loop
var onRenderFcts = [];
// init scene and camera
var scene = new THREE.Scene();
// called by snap-button, takes a screenshot of video and canvas
function snappysnap() {
// save frame from video, i.e. camera
let frame = captureVideoFrame("video", "png")
// save canvas object
let canvas = renderer.domElement // just object is needed
// resize canvas to match frame dimensions
canvas = resizeCanvas(canvas, frame.width, frame.height)
frame = frame.dataUri
// merge frame and canvas and download the resulting file
mergeImages([frame, canvas]).then(b64 => {
console.log("downloading screenshot")
download(b64, "AR.png", "image/png")
})
}
//////////////////////////////////////////////////////////////////////////////////
// Initialize a basic camera + lights
//////////////////////////////////////////////////////////////////////////////////
// Create a camera
var camera = new THREE.PerspectiveCamera;
scene.add(camera);
// add lights to scene and dynamic camera based light
var ambientLight = new THREE.AmbientLight(0x212223, 6);
scene.add(ambientLight);
var pointLight = new THREE.DirectionalLight(0xffffff, 4);
pointLight.position.set(-.5, -12, 1.5)
pointLight.castShadow = true;
scene.add(pointLight);
scene.add(pointLight.target);
// init renderer
var renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
preserveDrawingBuffer: true // needed for screenshots
});
renderer.setPixelRatio(4);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.domElement.style.position = 'absolute';
renderer.domElement.style.top = '0px';
renderer.domElement.style.left = '0px';
renderer.shadowMapEnabled = true;
renderer.shadowMapSoft = true;
renderer.shadowCameraNear = 0.1;
renderer.shadowCameraFar = 9999999999999;
renderer.shadowCameraFov = 150;
renderer.shadowMapBias = 0.0039;
renderer.shadowMapDarkness = 0.2;
renderer.shadowMapWidth = 1024;
renderer.shadowMapHeight = 1024;
document.body.appendChild(renderer.domElement);
////////////////////////////////////////////////////////////////////////////////
// handle arToolkitSource
////////////////////////////////////////////////////////////////////////////////
var arToolkitSource = new THREEx.ArToolkitSource({
// to read from the webcam
sourceType: 'webcam',
})
arToolkitSource.init(function onReady() {
onResize()
})
// handle resize
window.addEventListener('resize', function() {
onResize()
})
function onResize() {
arToolkitSource.onResizeElement();
arToolkitSource.copyElementSizeTo(renderer.domElement)
if (arToolkitContext.arController !== null) {
arToolkitSource.copyElementSizeTo(arToolkitContext.arController.canvas)
}
}
////////////////////////////////////////////////////////////////////////////////
// initialize arToolkitContext
////////////////////////////////////////////////////////////////////////////////
// create atToolkitContext
var arToolkitContext = new THREEx.ArToolkitContext({
cameraParametersUrl: './assets/camera_para.dat',
detectionMode: 'mono',
maxDetectionRate: 60,
canvasWidth: 80 * 3,
canvasHeight: 60 * 3,
})
// initialize it
arToolkitContext.init(function onCompleted() {
// copy projection matrix to camera
camera.projectionMatrix.copy(arToolkitContext.getProjectionMatrix());
})
// update artoolkit on every frame
onRenderFcts.push(function() {
if (arToolkitSource.ready === false) return
arToolkitContext.update(arToolkitSource.domElement)
})
////////////////////////////////////////////////////////////////////////////////
// Create a ArMarkerControls
////////////////////////////////////////////////////////////////////////////////
var markerRoot = new THREE.Group
scene.add(markerRoot)
var artoolkitMarker = new THREEx.ArMarkerControls(arToolkitContext, markerRoot, {
type: 'pattern',
patternUrl: './assets/patt.gp',
size: 1,
confidence:.2
})
// build a smoothedControls
var smoothedRoot = new THREE.Group()
scene.add(smoothedRoot)
var smoothedControls = new THREEx.ArSmoothedControls(smoothedRoot, {
lerpPosition: 0.35,
lerpQuaternion: 0.18,
lerpScale: 1,
})
onRenderFcts.push(function(delta) {
smoothedControls.update(markerRoot)
})
//////////////////////////////////////////////////////////////////////////////////
// add an object in the scene
//////////////////////////////////////////////////////////////////////////////////
var arWorldRoot = smoothedRoot;
arWorldRoot.name = "arWorldRoot" // makes finding it easier
var geometry = new THREE.SphereGeometry(0.3, 32, 32);
var material = new THREE.MeshBasicMaterial({
color: 0xffff00
});
var sphere = new THREE.Mesh(geometry, material);
//var reference = new THREE.Mesh(geometry, material);
arWorldRoot.add(sphere);
//arWorldRoot.add(reference);
//reference.position.set(0,0,0);
let mtlLoader = new THREE.MTLLoader();
//let objLoader = new THREE.OBJLoader();
function loadIsland(islandDirectory, islandName) {
/* something like a docstring
islandDirectory str, path to directory that contains .mtl, .obj
islandName str, the name of the island files
positions array of length 3, containing xyz coords for placement
*/
mtlLoader.setTexturePath(islandDirectory)
mtlLoader.setPath(islandDirectory)
// load material
mtlLoader.load(islandName + ".mtl", materials => {
materials.preload()
let objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials)
objLoader.setPath(islandDirectory)
// load object
objLoader.load(islandName + ".obj", object => {
console.log(`currently loading ${islandName}`)
console.log(object)
object.traverse(node => {
if (node instanceof THREE.Mesh) {
node.geometry.computeVertexNormals()
}
})
object.scale.set(...islands[islandName].scale)
object.position.set(...islands[islandName].position) // needs to be an array
console.log(islands[islandName].scale, islands[islandName])
object.name = islandName
arWorldRoot.add(object)
})
})
}
function loadAsset(assetDirectory, assetName, x, y, z, sx, sy, sz) {
/* something like a docstring
islandDirectory str, path to directory that contains .mtl, .obj
islandName str, the name of the island files
positions array of length 3, containing xyz coords for placement
*/
mtlLoader.setTexturePath(assetDirectory)
mtlLoader.setPath(assetDirectory)
// load material
mtlLoader.load(assetName + ".mtl", materials => {
materials.preload()
let objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials)
objLoader.setPath(assetDirectory)
// load object
objLoader.load(assetName + ".obj", object => {
console.log(`currently loading ${assetName}`)
console.log(object)
object.traverse(node => {
if (node instanceof THREE.Mesh) {
node.geometry.computeVertexNormals()
}
})
object.scale.set(sx,sy,sz)
object.position.set(x,y,z)
object.name = assetName
arWorldRoot.add(object)
})
})
}
function loadTreesOnForestIsland(assetDirectory, assetName) {
/* something like a docstring
assetName Name of the Asset to load
mtlLoader THREE.MTLLoader instance
islandDirectory str, path to directory that contains .mtl, .obj
islandName str, the name of the island files
positions array of length 3, containing xyz coords for placement
*/
mtlLoader.setTexturePath(assetDirectory)
mtlLoader.setPath(assetDirectory)
// load material
mtlLoader.load(assetName + ".mtl", materials => {
materials.preload();
let objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials)
objLoader.setPath(assetDirectory)
// load object
objLoader.load(assetName + ".obj", object => {
console.log(`currently loading ${assetName}`)
console.log(object)
object.traverse(node => {
if (node instanceof THREE.Mesh) {
node.geometry.computeVertexNormals()
}
})
object.scale.set(...trees[assetName].scale)
spacefound = false;
var calcdx;
var calcdz;
while (!spacefound) {
potentialx = -1.3 + (Math.random());
potentialz = -1.8 + (Math.random());
if (treeposses.length > 0) {
for (var j = 0; j < treeposses.length; j++) {
var distance = distanceBetweenTwoPoints(potentialx, treeposses[j].x, potentialz, treeposses[j].z);
if (distance > treespacing) {
calcdx = potentialx;
calcdz = potentialz;
spacefound = true;
console.log("positionfound!: " + distance)
} else {
console.log("looking for more space because too small: " + distance)
}
}
} else {
calcdx = potentialx;
calcdz = potentialz;
spacefound = true;
}
}
object.position.set(calcdx, 0.4, calcdz)
treeposses.push(object.position);
console.log(trees[assetName])
object.name = assetName
arWorldRoot.add(object)
})
})
}
// iterate over all islands
Object.keys(islands).forEach(island => {
loadIsland("./assets/islands/", island)
})
// iterate over all trees
Object.keys(trees).forEach(tree => {
for (var i = 0; i < 5; i++) {
//loadTreesOnForestIsland("./assets/trees/", tree)
}
})
//////////////////////////////////////////////////////////////////////////////////
// render the whole thing on the page
//////////////////////////////////////////////////////////////////////////////////
// render the scene
onRenderFcts.push(function() {
renderer.render(scene, camera);
})
// object foo
let islandDirections = {
"island_forest": 1,
"island_main": 1,
"island_lake": 1
}
// run the rendering loop
var lastTimeMsec = null
requestAnimationFrame(function animate(nowMsec) {
// keep looping
requestAnimationFrame(animate);
// lift or lower blinds based on whether marker is visible or not.
if (markerRoot.visible) {
$("#blinds").fadeOut(100)
} else {
$("#blinds").fadeIn();
camera
}
// measure time
lastTimeMsec = lastTimeMsec || nowMsec - 1000 / 60
var deltaMsec = Math.min(200, nowMsec - lastTimeMsec)
lastTimeMsec = nowMsec
// call each update function
onRenderFcts.forEach(function(onRenderFct) {
onRenderFct(deltaMsec / 1000, nowMsec / 1000)
})
// iterate over all available islands
let availableIslands = []
// push all available islands to array
scene.getObjectByName(arWorldRoot.name).children.forEach(obj => {
if (obj.name !== "") {
availableIslands.push(obj.name)
}
})
// actual iteration
availableIslands.forEach(island => {
let islandModel = model(island)
let dir = 1 // short direction variable name for convenience
// switch-case:
switch (island) {
case "island_forest":
if (islandModel.position.y < 2) {
islandDirections[island] = 1
} else if (islandModel.position.y > 2.4) {
islandDirections[island] = -1
}
dir = islandDirections[island]
islandModel.position.set(islandModel.position.x,
islandModel.position.y + 0.001 * dir,
islandModel.position.z)
for (var i = 0; i < arWorldRoot.children.length; i++) {
if (arWorldRoot.children[i].name.includes("tree")) {
arWorldRoot.children[i].position.set(arWorldRoot.children[i].position.x,
islandModel.position.y + 0.001 * dir,
arWorldRoot.children[i].position.z)
}
}
break;
case "island_main":
if (islandModel.position.y < 1.5) {
islandDirections[island] = 1
} else if (islandModel.position.y > 2.9) {
islandDirections[island] = -1
}
dir = islandDirections[island]
islandModel.position.set(islandModel.position.x,
islandModel.position.y + 0.002 * dir,
islandModel.position.z)
break;
case "island_lake":
if (islandModel.position.y < 1.8) {
islandDirections[island] = 1
} else if (islandModel.position.y > 2.4) {
islandDirections[island] = -1
}
dir = islandDirections[island]
islandModel.position.set(islandModel.position.x,
islandModel.position.y + 0.003 * dir,
islandModel.position.z)
break;
default:
//console.log(`entered default case for variable ${island}.`)
}
})
date = Date.now() * 0.0002;
pointLight.position.set(
Math.cos(date) * orbitRadius,
Math.sin(date) * orbitRadius,
Math.sin(date) * orbitRadius
);
sphere.position.set(
Math.cos(date) * orbitRadius,
Math.sin(date) * orbitRadius,
Math.sin(date) * orbitRadius
);
//console.log(pointLight.position);
})
///////////////////////////////////////////////////////////////////////////
// CUSTOM FUNCTIONS //
///////////////////////////////////////////////////////////////////////////
function animate() {
console.log("placeholder function cause gabe forgot")
}
//Island Deleter
//NOTE: does this need 'name' as a parameter?
function deleteIslands() {
for (var i = 0; i < arWorldRoot.children.length; i++) {
if (arWorldRoot.children[i].name) {
var toRemove = model(arWorldRoot.children[i].name);
arWorldRoot.remove(toRemove);
// animate();
}
}
}
function addXTreesToForest(x){
for(var i = 0 ; i < x ; i++){
addTreeToForest();
}
}
function addTreeToForest(){
if(treeposses.length == 0){
loadAsset("./assets/trees/", "pine_tree",-.5, 2, -1.2,0.05,0.05,0.05);
treeposses.push({x:-.5, y:2, z:-1.2});
} else {
var foundspace = false;
while(!foundspace){
var potentialx = (Math.random());
potentialx *= Math.floor(Math.random()*2) == 1 ? 1 : -1;
potentialx += -.5;
var potentialz = (Math.random());
potentialz *= Math.floor(Math.random()*2) == 1 ? 1 : -1;
potentialz += -1.2;
foundspace = true;
for(var z = 0 ; z < treeposses.length; z++){
console.log(treeposses[z])
var distance = distanceBetweenTwoPoints(potentialx,potentialz,treeposses[z].x,treeposses[z].z);
console.log(distance);
if(distance<.15){
foundspace = false;
}
}
if(foundspace){
loadAsset("./assets/trees/", "pine_tree",potentialx, 2, potentialz,0.05,0.05,0.05);
treeposses.push({x:potentialx, y:2, z:potentialz});
}
}
}
}
function setGrassGreenness(greenness) {
model("island_forest").children[0].material.color.r = 1 - greenness;
model("island_forest").children[0].material.color.g = greenness * .7 + 0.3;
}
function setWaterClarity(clarity) {
model("island_lake").children[0].material[3].color.r = 0;
model("island_lake").children[0].material[3].color.g = clarity * 0.2;
model("island_lake").children[0].material[3].color.b = clarity;
model("island_lake").children[0].material[3].opacity = 1 - clarity * .3;
}
function distanceBetweenTwoPoints(x1, z1, x2, z2) {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(z2 - z1, 2));
}
function model(name) {
for (var i = 0; i < arWorldRoot.children.length; i++) {
if (arWorldRoot.children[i].name == name) {
return arWorldRoot.children[i];
}
}
}
function findMat(iname, tname) {
materials = model(iname).children[0].material;
for (var x = 0; x < materials.length; x++) {
if (materials[x].name == tname) {
return materials[x]
}
}
}
// stolen from https://github.com/jeromeetienne/AR.js/issues/358#issuecomment-395911581
function captureVideoFrame(video, format, width, height) {
if (typeof video === 'string') {
video = document.querySelector(video)
}
format = format || 'jpeg'
if (!video || (format !== 'png' && format !== 'jpeg')) {
return false
}
let canvas = document.createElement("CANVAS")
canvas.width = width || video.videoWidth
canvas.height = height || video.videoHeight
canvas.getContext('2d').drawImage(video, 0, 0)
let dataUri = canvas.toDataURL('image/' + format)
let data = dataUri.split(',')[1]
let mimeType = dataUri.split(';')[0].slice(5)
let bytes = window.atob(data)
let buf = new ArrayBuffer(bytes.length)
let arr = new Uint8Array(buf)
for (let i = 0; i < bytes.length; i++) {
arr[i] = bytes.charCodeAt(i)
}
let blob = new Blob([arr], {
type: mimeType
})
return {
blob: blob,
dataUri: dataUri,
format: format,
width: canvas.width,
height: canvas.height
}
}
// stolen from https://github.com/jeromeetienne/AR.js/issues/358#issuecomment-404543089
function resizeCanvas(origCanvas, width, height) {
let resizedCanvas = document.createElement("canvas");
let resizedContext = resizedCanvas.getContext("2d");
resizedCanvas.height = height;
resizedCanvas.width = width;
if (width > height) {
// Landscape
resizedContext.drawImage(origCanvas, 0, 0, width, height);
} else {
// Portrait
var scale = height / width;
var scaledHeight = origCanvas.width * scale;
var scaledWidth = origCanvas.height * scale;
var marginLeft = (origCanvas.width - scaledWidth) / 2;
resizedContext.drawImage(origCanvas, marginLeft, 0, scaledWidth, scaledHeight);
}
return resizedCanvas.toDataURL();
}
</script>
</body>
</html>