-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathcanvas-ply-reader.html
614 lines (540 loc) · 16.2 KB
/
canvas-ply-reader.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
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PLY 3D model viewer based on HTML5 canvas</title>
<script type="text/javascript">
function color(r, g, b, a)
{
this.r = r;
this.g = g;
this.b = b;
this.a = a;
this.lightnessMap = [];
}
color.prototype.lightness = function(lightnessK)
{
var min = Math.min(this.r, this.g, this.b);
var max = Math.max(this.r, this.g, this.b);
var lightnessMapIndex = Math.round(lightnessK * 255);
if(this.lightnessMap[lightnessMapIndex])
return this.lightnessMap[lightnessMapIndex];
// Simple processing gray colors
if(min == max)
{
return this.lightnessMap[lightnessMapIndex] = new color(this.r * lightnessK, this.g * lightnessK, this.b * lightnessK, this.a);
}
// Convert to HSL
var H;
var S;
var L = (min + max) / 2 / 255;
if(max == this.r && this.g >= this.b)
H = 60 * (this.g - this.b) / (max - min) + 0;
else if(max == this.r)
H = 60 * (this.g - this.b) / (max - min) + 360;
else if(max == this.g)
H = 60 * (this.b - this.r) / (max - min) + 120;
else if(max == this.b)
H = 60 * (this.r - this.g) / (max - min) + 240;
H = H % 360;
if(L == 0 || max == min)
S = 0;
else if(L <= 0.5)
S = (max - min) / (2 * L) / 255;
else if(L < 1)
S = (max - min) / (2 - 2*L) / 255;
else if(L == 1)
S = 1;
// Apply lightness
L = L * lightnessK;
// Convert to RGB
if(L <= 0.5)
var Q = L * (1 + S);
else
var Q = L + S - (L * S);
var P = 2 * L - Q;
var Hk = H / 360;
var Tr = Hk + 1/3; if(Tr < 0) Tr = Tr + 1;
var Tg = Hk;
var Tb = Hk - 1/3; if(Tr > 1) Tr = Tr - 1;
if(Tr < 1/6)
var r = P + ((Q - P) * 6 * Tr);
else if(Tr < 1/2)
var r = Q;
else if(Tr < 2/3)
var r = P + ((Q - P) * 6 * (2/3 - Tr));
else
var r = P;
if(Tg < 1/6)
var g = P + ((Q - P) * 6 * Tg);
else if(Tg < 1/2)
var g = Q;
else if(Tg < 2/3)
var g = P + ((Q - P) * 6 * (2/3 - Tg));
else
var g = P;
if(Tb < 1/6)
var b = P + ((Q - P) * 6 * Tb);
else if(Tb < 1/2)
var b = Q;
else if(Tb < 2/3)
var b = P + ((Q - P) * 6 * (2/3 - Tb));
else
var b = P;
return this.lightnessMap[lightnessMapIndex] = new color(Math.round(r*255), Math.round(g*255), Math.round(b*255), this.a);
}
function point3D(x, y, z)
{
this.x = x;
this.y = y;
this.z = z;
}
point3D.prototype.move = function(p3D)
{
this.x += p3D.x;
this.y += p3D.y;
this.z += p3D.z;
}
point3D.prototype.swap = function(p3D)
{
this.x = p3D.x;
this.y = p3D.y;
this.z = p3D.z;
}
point3D.prototype.rotate = function(axis, angleRad)
{
switch (axis)
{
case "x":
{
var tempPoint = new point3D(
this.x,
this.y * Math.cos(angleRad) - this.z * Math.sin(angleRad),
this.y * Math.sin(angleRad) + this.z * Math.cos(angleRad)
);
this.swap(tempPoint);
break;
}
case "y":
{
var tempPoint = new point3D(
this.x * Math.cos(angleRad) + this.z * Math.sin(angleRad),
this.y,
-this.x * Math.sin(angleRad) + this.z * Math.cos(angleRad)
);
this.swap(tempPoint);
break;
}
case "z":
{
var tempPoint = new point3D(
this.x * Math.cos(angleRad) - this.y * Math.sin(angleRad),
this.x * Math.sin(angleRad) + this.y * Math.cos(angleRad),
this.z
);
this.swap(tempPoint);
break;
}
}
}
function poly() // Dynamic amount of parameters
{
var normal = arguments[0];
var points = [];
for(var i = 1; i < arguments.length; i++)
{
points.push(arguments[i]);
}
this.points = points;
// Calculating normal
if(normal === null)
{
var v1 = new point3D(points[2].x - points[1].x, points[2].y - points[1].y, points[2].z - points[1].z);
var v2 = new point3D(points[0].x - points[1].x, points[0].y - points[1].y, points[0].z - points[1].z);
var normal = new point3D(v1.y*v2.z-v2.y*v1.z, v1.z*v2.x-v2.z*v1.x, v1.x*v2.y-v2.x*v1.y);
var normalLen = Math.sqrt(normal.x*normal.x + normal.y*normal.y + normal.z*normal.z);
normal.x /= normalLen;
normal.y /= normalLen;
normal.z /= normalLen;
}
this.normal = normal;
this.hidden = Math.acos(this.normal.z) >= Math.PI / 2;
this.recalculateDistanceToScreen();
}
poly.prototype.move = function(p3D)
{
for(var i = 0; i < this.points.length; i++)
{
var point = this.points[i];
point.move(p3D);
}
this.recalculateDistanceToScreen();
}
poly.prototype.rotate = function(axis, angleRad)
{
for(var i = 0; i < this.points.length; i++)
{
var point = this.points[i];
point.rotate(axis, angle);
}
this.normal.rotate(axis, angleRad);
this.hidden = Math.acos(this.normal.z) >= Math.PI / 2;
this.recalculateDistanceToScreen();
}
poly.prototype.put = function(center, fillColor, edgeColor)
{
// Check visibility
if(this.hidden)
return;
var normalAngleRad = Math.acos(this.normal.z);
var lightIntensity = 1 - 2 * (normalAngleRad / Math.PI); // Convert RAD -> GRAD
var newColor = fillColor.lightness(lightIntensity);
ctx.fillStyle = 'rgba('+newColor.r+','+newColor.g+','+newColor.b+','+newColor.a+')';
ctx.beginPath();
for(var i = 0; i < this.points.length; i++)
{
var point = this.points[i];
if(i)
ctx.lineTo(center.x + parseInt(point.x), center.y - parseInt(point.y));
else
ctx.moveTo(center.x + parseInt(point.x), center.y - parseInt(point.y));
}
ctx.fill();
// Paint edges to fix problem with dark liner between polygons
if(!edgeColor)
edgeColor = fillColor;
ctx.lineWidth = 1;
var newColor = edgeColor.lightness(lightIntensity);
ctx.strokeStyle = 'rgba('+newColor.r+','+newColor.g+','+newColor.b+','+newColor.a+')';
ctx.beginPath();
var point = this.points[this.points.length-1];
ctx.moveTo(center.x + parseInt(point.x), center.y - parseInt(point.y));
for(var i = 0; i < this.points.length; i++)
{
var point = this.points[i];
ctx.lineTo(center.x + parseInt(point.x), center.y - parseInt(point.y));
}
ctx.stroke();
}
poly.prototype.recalculateDistanceToScreen = function()
{
var distance = 0.0;
for(var i = 0; i < this.points.length; i++)
{
distance += this.points[i].z;
}
this.distanceToScreen = distance / this.points.length;
}
function Model(polys, points, fillColor, edgeColor)
{
this.polys = polys;
this.points = points;
this.fillColor = fillColor;
this.edgeColor = edgeColor;
}
Model.prototype.move = function(p3D)
{
for(var i = 0; i < this.points.length - this.polys.length; i++)
{
var point = this.points[i];
point.move(p3D);
}
for(var i = 0; i < this.polys.length; i++)
{
var poly = this.polys[i];
poly.recalculateDistanceToScreen();
}
}
Model.prototype.put = function (center)
{
var zSorting = [];
for(var i = 0; i < this.polys.length; i++)
{
var poly = this.polys[i];
if(poly.hidden)
continue;
zSorting.push(poly.distanceToScreen);
}
zSorting.sort((function(a, b){return a - b;}));
var lastZ;
for(var i = 0; i < zSorting.length; i++)
{
if(lastZ == zSorting[i])
continue;
lastZ = zSorting[i];
for(var j = 0; j < this.polys.length; j++)
{
var poly = this.polys[j];
if(poly.hidden)
continue;
if(poly.distanceToScreen != zSorting[i])
continue;
poly.put(center, this.fillColor, this.edgeColor);
}
}
return zSorting.length;
}
Model.prototype.rotate = function(axis, angleRad)
{
for(var i = 0; i < this.points.length; i++)
{
this.points[i].rotate(axis, angleRad);
}
for(var i = 0; i < this.polys.length; i++)
{
this.polys[i].recalculateDistanceToScreen();
this.polys[i].hidden = Math.acos(this.polys[i].normal.z) >= Math.PI / 2;
}
}
function nextFrame()
{
ctx.fillStyle = 'rgba(0, 0, 0, 1)';
ctx.fillRect(0, 0, canvas.width, canvas.height); // clear canvas
model.rotate('y', 0.6 * Math.PI / 180);
ctx.fillStyle = 'rgba(50, 50, 200, 1)';
ctx.strokeStyle = 'rgba(60, 60, 210, 1)';
var visiblePolygons = model.put(centerScreen);
// FPS calculation
if(!fpslastUpdate)
{
fpslastUpdate = Date.now();
}
else
{
var now = Date.now();
fps.push(1000 / (now - fpslastUpdate));
fpslastUpdate = now;
}
if(fps.length >= fpsFilter)
{
var fpsValue = 0.0;
for(var i = fps.length - fpsFilter; i < fps.length; i++)
fpsValue += fps[i];
ctx.fillStyle = "white";
ctx.fillText("" + Math.floor(fpsValue/fpsFilter) + " fps, "+visiblePolygons+" visible polygons, "+Math.round(visiblePolygons*fpsValue/fpsFilter)+" polygons per sec", 8, 16);
}
if(fps.length >= fpsFilter * 8)
{
fps = fps.slice(fps.length - fpsFilter);
}
}
function processReqChange()
{
try {
if (req.readyState == 4) {
if (req.status == 200) {
initAfterGettingModel(req.responseText)
} else {
alert("Cannot get 3D data:\n" + req.statusText);
}
}
}
catch (e) {
alert(e+' line: ' + e.lineNumber);
}
}
function ply_reader(data)
{
var model;
var scaleFactor = PLYFile == 'monkey.ply' ? 100 : 50 ;
var hasNormal = false;
// Read header
while(data.length)
{
var retval = data.match(/.*/);
var str = retval[0];
data = data.substr(str.length+1);
var retval = str.match(/element (\w+) (\d+)/);
if(retval)
{
if(retval[1] == "vertex")
var npoints = parseInt(retval[2]);
if(retval[1] == "face")
var npolys = parseInt(retval[2]);
}
if(str == "property float nx")
hasNormal = true;
if(str == "end_header")
break;
}
// Read points
var minPoint = new point3D(Infinity, Infinity, Infinity);
var maxPoint = new point3D(-Infinity, -Infinity, -Infinity);
var points = [], uniquePointsKeys = [], uniquePoints = [];
var normals = [];
for (var i = 0; i < npoints; i++)
{
var retval = data.match(/([\d.-]+ ?)+/);
var str = retval[0];
data = data.substr(str.length+1);
var retval = str.match(/([\d.-]+)/g);
var uniqueKey = ""+retval[0]+" "+retval[1]+" "+retval[2];
var index = uniquePointsKeys.indexOf(uniqueKey);
if(index == -1)
{
var point = new point3D(parseFloat(retval[0])*scaleFactor, parseFloat(retval[1])*scaleFactor, parseFloat(retval[2])*scaleFactor);
uniquePointsKeys.push(uniqueKey);
uniquePoints.push(point);
}
else
{
var point = uniquePoints[index];
}
points.push(point);
minPoint.x = Math.min(minPoint.x, point.x);minPoint.y = Math.min(minPoint.y, point.y);minPoint.z = Math.min(minPoint.z, point.z);
maxPoint.x = Math.max(maxPoint.x, point.x);maxPoint.y = Math.max(maxPoint.y, point.y);maxPoint.z = Math.max(maxPoint.z, point.z);
if(hasNormal)
{
var normal = new point3D(parseFloat(retval[3]), parseFloat(retval[4]), parseFloat(retval[5]));
normals.push(normal);
}
}
// Polygons
var polys = [];
for (var i = 0; i < npolys; i++)
{
var retval = data.match(/(\d+ ?)+/);
var str = retval[0];
data = data.substr(str.length+1);
var retval = str.match(/(\d+)/g);
var newPolyString = "new poly(";
newPolyString += hasNormal ? "normals["+retval[1]+"]," : "null,";
for (var j = 0; j < retval.length; j++)
{
retval[j] = parseInt(retval[j]);
if(j >= 2)
newPolyString += ",";
if(j)
newPolyString += "points["+retval[j]+"]";
}
newPolyString += ");";
var polygon = eval(newPolyString);
polys.push(polygon);
var uniqueKey = ""+polygon.normal.x+" "+polygon.normal.y+" "+polygon.normal.z;
var index = uniquePointsKeys.indexOf(uniqueKey);
if(index == -1)
{
uniquePointsKeys.push(uniqueKey);
uniquePoints.push(polygon.normal);
}
else
{
polygon.normal = uniquePoints[index];
}
}
var divinfo = document.getElementById('fileinfo');
divinfo.innerHTML += ", polygons: "+npolys+", points: "+npoints;
// Create model
model = new Model(polys, uniquePoints, new color(220,220,30,1), null);
// Center model
model.move(new point3D(-(maxPoint.x + minPoint.x)/2, -(maxPoint.y + minPoint.y)/2, -(maxPoint.z + minPoint.z)/2));
return model;
}
var PLYFile = 'monkey.ply';
var fpsWanted = 24;
var fps = [], fpslastUpdate;
var fpsFilter = fpsWanted*2;
function init()
{
document.getElementById('startButton').disabled = false;
// Redefine model file
var retval = document.location.search.match(/file=([\w\.]+)/);
if(retval)
PLYFile = retval[1];
var divinfo = document.getElementById('fileinfo');
divinfo.innerHTML = "File: <a href='"+PLYFile+"'>"+PLYFile+"</a>";
canvas = document.getElementById('canvas');
if (canvas.getContext){
ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgba(0, 0, 0, 1)';
ctx.fillRect(0, 0, canvas.width, canvas.height); // clear canvas
centerScreen = new point3D(canvas.width / 2, canvas.height / 2, 0);
try {
req = new XMLHttpRequest();
} catch (e) {
alert("Unsupported browser:\n"+e);
}
if (req) {
// Try to get model
req.open("GET", PLYFile, true);
req.onreadystatechange = processReqChange;
req.send(null);
}
}
}
function initAfterGettingModel(data)
{
model = ply_reader(data);
var divinfo = document.getElementById('fileinfo');
divinfo.innerHTML += ", unique points+normals: "+model.points.length;
if(PLYFile == 'teapot.ply')
model.rotate('x', -90 * Math.PI / 180);
model.put(centerScreen);
}
function startRotating()
{
var radios = document.getElementsByName('fps');
for (var index in radios)
if(radios[index].checked == true)
fpsWanted = radios[index].value;
document.getElementById('startButton').disabled = true;
document.getElementById('stopButton').disabled = false;
if(typeof timer != "undefined")
return;
timer = setInterval(nextFrame, 1000 / fpsWanted);
}
function stopRotating()
{
document.getElementById('startButton').disabled = false;
document.getElementById('stopButton').disabled = true;
if(!timer)
return;
clearInterval(timer);
timer = undefined;
fps = [];
}
function changeFPS(input)
{
if(typeof timer != "undefined")
{
stopRotating();
startRotating();
}
}
</script>
<style type="text/css">
canvas { border: 0px solid black; }
</style>
</head>
<body onload="init();">
<h1>PLY 3D model viewer based on HTML5 canvas on 2D contex</h1>
<p>Features:
<ul>
<li>3D operations: rotating, moving object center</li>
<li>Directional light</li>
<li>Highlighting edges</li>
<li>Painter's algorithm for sorting polygons</li>
<li>Optimizations:
<ul>
<li>Skip outputting of invisible polygons</li>
<li>Skip processing of duplicated points, normals</li>
</ul>
</li>
</ul>
</p>
<canvas id="canvas" width="400" height="225"></canvas>
<br>
<div id="fileinfo"></div>
<br>
Max allowed:
<label><input type="radio" name="fps" onclick="changeFPS(this)" value="12"/>12 fps</label>
<label><input type="radio" name="fps" onclick="changeFPS(this)" value="24" checked="checked"/>24 fps</label>
<label><input type="radio" name="fps" onclick="changeFPS(this)" value="48"/>48 fps</label>
<label><input type="radio" name="fps" onclick="changeFPS(this)" value="60"/>60 fps</label>
<label><input type="radio" name="fps" onclick="changeFPS(this)" value="72"/>72 fps</label>
<label><input type="radio" name="fps" onclick="changeFPS(this)" value="100"/>100 fps</label>
<label><input type="radio" name="fps" onclick="changeFPS(this)" value="120"/>120 fps</label>
<br>
<button id="startButton" onclick="startRotating()">Start Y rotating</button> <button id="stopButton" onclick="stopRotating()" disabled="disabled">Stop Y rotating</button>
</body>
</html>