-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathd3webgl.ts
1479 lines (1254 loc) · 53 KB
/
d3webgl.ts
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// <reference path="defs/three.d.ts" />
module d3webgl {
// SETUP
// object used for writing text elements
var txtCanvas = document.createElement("canvas")
// Webgl context that contains all the necessary THREE.js objects
// e.g. camera, scene, etc.
export class WebGLContext{
scene:THREE.Scene;
camera:THREE.OrthographicCamera;
renderer:THREE.WebGLRenderer;
canvas;
geometry:THREE.BufferGeometry;
interactor:WebGLInteractor;
// set of all data bindings (data object -> visual object)
dataBindings:DataBinding[] = []
// params - placeholder for initialization parameters.
constructor(config?:Object){
txtCanvas = document.createElement("canvas");
txtCanvas.setAttribute('id', 'textCanvas');
}
// render routine. Needs to be called externally
render(){
// check which dataBindings must be updated
for(var i=0 ; i < this.dataBindings.length ; i++){
if(this.dataBindings[i].updateAttributes || this.dataBindings[i].updateStyle){
this.dataBindings[i].set();
}
}
this.renderer.render(this.scene, this.camera)
}
// D3 syntax to create data binding
selectAll(){
return d3webgl.selectAll()
}
///////////////////////
// RENDER PARAMETERS //
///////////////////////
// enables or diables zoom
enableZoom(b?:boolean){
if(b){
window.addEventListener("mousewheel", mouseWheel, false);
function mouseWheel(event){
event.preventDefault();
webgl.camera.zoom += event.wheelDelta/1000;
webgl.camera.zoom = Math.max (0.1, webgl.camera.zoom)
webgl.camera.updateProjectionMatrix();
webgl.render();
}
}else{
window.addEventListener("mousewheel", mouseWheel, false);
}
}
// enables or diables general panning via drag and drop
enablePanning(b:boolean){
this.interactor.isPanEnabled = b;
}
// enables or diables horizontal panning via scroll wheel
enableHorizontalPanning(b:boolean){
this.interactor.isHorizontalPanEnabled = b;
}
} // end of WebGLContext
// gobal webgl object
var webgl;
// initialize WebGL context. This function is called externally to init this API
// and prepare the canvas.
export function initWebGL(parentId:string, width:number, height:number, params?:Object):WebGLContext{
// init WebGLContext (see above)
webgl = new WebGLContext(params);
// init orthographic camera (could be adjusted through config-object (see above))
webgl.camera = new THREE.OrthographicCamera(
width/-2,
width/2,
height/2,
height/-2,
0, 1000)
// init scene and set camera
webgl.scene = new THREE.Scene();
webgl.scene.add(webgl.camera);
webgl.camera.position.z = 100;
// renderer
webgl.renderer = new THREE.WebGLRenderer({
antialias: true,
preserveDrawingBuffer: true
});
webgl.renderer.setSize(width, height)
webgl.renderer.setClearColor( 0xffffff, 1);
// position canvas element
webgl.canvas = webgl.renderer.domElement;
document.getElementById(parentId).appendChild(webgl.canvas);
// init interaction object
webgl.interactor = new WebGLInteractor(webgl.scene, webgl.canvas, webgl.camera);
// init simple white light
var light = new THREE.PointLight( 0x000000, 1, 100 );
light.position.set( 0, 0, 1000 );
webgl.scene.add( light );
return webgl;
}
// if a WebGLContext object already exists, set it explicitly here.
export function setWebGL(scene:THREE.Scene, camera:THREE.Camera, renderer:THREE.Renderer, canvas){
webgl = new WebGLContext();
webgl.camera = camera;
webgl.scene = scene;
webgl.renderer = renderer;
}
///////////////////////////
/// SELECTIONS ///
///////////////////////////
// creates new data binding
export function selectAll():DataBinding{
var q = new d3webgl.DataBinding();
webgl.dataBindings.push(q)
return q;
}
// Data Binding class that maps data objects
// in an array to visual objects on the
// screen.
// There are two ways to manage visual objects:
// 1. Directly by instantiating one THREE.js object
// per data element. This was simplest to implement
// in the first place but is not very performant.
// 2. In-directly by creating one THREE.js buffer geometry
// and do the rendering through shaders. This is currently
// only implemented for the shape 'circle'.
export class DataBinding{
// data elements in this binding
dataElements:Object[] = [];
// Visual objects, one for every data objects
// when shaders are used, only one mesh is necessary
// to represent this data binding (see below)
visualElements:Object[] = [];
// single mesh representing this data bining,
// if shape implements shader
mesh:THREE.Mesh;
// scene, this mesh or visual objects are attached to.
scene:THREE.Scene;
// event handler call-back functions
mouseOverHandler:Function;
mouseMoveHandler:Function;
mouseOutHandler:Function;
mouseDownHandler:Function;
mouseUpHandler:Function;
clickHandler:Function;
// Attribute arrays storing one value per data objects
// These attributes are neccessary only when working
// with shaders. Otherwise, the attributes are stored
// with each THREE object (one per data object).
x:number[] = [];
y:number[] = [];
z:number[] = [];
r:number[] = [];
// Arrays with style values (also for shaders)
fill:number[] = [];
stroke:number[] = [];
strokewidth:number[] = [];
opacity:number[] = []
// stores the type of shape for this data binding,
// e.g. 'circle', 'line', etc.
shape:string;
// flag is set when visual attributes have changed.
updateAttributes:boolean = false
// flag is set when visual style has changed.
updateStyle:boolean = false
// flag to indicate that this databining uses a shader.
// Progressively, all visual objects should use shaders.
IS_SHADER:boolean = false
// CONSTRUCTOR
constructor(){
this.scene = webgl.scene;
}
// assigns data objects
data(arr:Object[]):DataBinding{
this.dataElements = arr.slice(0);
return this;
}
// assings a type of visual object to this data binding
// and initializes one default instance of these objects
// for each data object.
append(shape:string):DataBinding{
var elements = []
switch(shape){
case 'circle': createCirclesWithBuffers(this, this.scene); break
case 'path': elements = createPaths(this.dataElements, this.scene); break
case 'line': elements = createLines(this.dataElements, this.scene); break
case 'rect': elements = createRectangles(this.dataElements, this.scene); break
case 'text': elements = createWebGLText(this.dataElements, this.scene); break
case 'polygon': elements = createPolygons(this.dataElements, this.scene); break
default: console.error('Shape', shape, 'does not exist.')
}
// init position arrays if not shader
if(!this.IS_SHADER){
for(var i=0 ; i <elements.length ; i++){
this.x.push(0);
this.y.push(0);
this.z.push(0);
}
}
this.shape = shape;
this.visualElements = elements;
return this;
}
push(e:any):DataBinding{
this.dataElements.push(e);
return this;
}
// returns the i-th data object
getData(i:any):any{
return this.dataElements[this.visualElements.indexOf(i)];
}
// returns the i-th visual object (if no-shader)
getVisual(i:any):any{
return this.visualElements[this.dataElements.indexOf(i)];
}
// returns number of data elements in this binding.
get length(){
return this.dataElements.length;
}
// returns only those data elements that return
// true in the passed function f. f gets passed
// two parameters: d, and i. d is the data object
// and i the index of d in this array of data objects.
filter(f:Function):DataBinding{
var arr=[];
var visArr = []
for(var i=0 ; i<this.dataElements.length ; i++){
if(f(this.dataElements[i], i)){
arr.push(this.dataElements[i])
visArr.push(this.visualElements[i])
}
}
var q = new DataBinding()
.data(arr);
q.visualElements = visArr;
return q;
}
// Assigns a geometric attribute
// v can be of two types:
// a) a scalar value, which is assigned to all
// visual elemnts in this binding.
// b) a function, which is executed for each
// data object/visual object individually.
// If v is a function f, f gets passed two parameters:
// the data object d and the data object's index i.
attr(name:string, v:any):DataBinding{
var l = this.visualElements.length;
if(this.IS_SHADER){
for(var i=0 ; i < this.dataElements.length ; i++){
this[name][i] = v instanceof Function?v(this.dataElements[i], i):v
}
}else{
for(var i=0 ; i <l ; i++){
this.setAttr(this.visualElements[i], name, v instanceof Function?v(this.dataElements[i], i):v, i);
if(this.visualElements[i].hasOwnProperty('wireframe')){
this.setAttr(this.visualElements[i].wireframe, name, v instanceof Function?v(this.dataElements[i], i):v, i);
}
}
}
this.updateAttributes = true;
return this;
}
// Assigns a geometric attribute
// v can be of two types:
// a) a scalar value, which is assigned to all
// visual elemnts in this binding.
// b) a function, which is executed for each
// data object/visual object individually.
// If v is a function f, f gets passed two parameters:
// the data object d and the data object's index i.
style(name:string, v:any):DataBinding{
var l = this.visualElements.length;
if(this.IS_SHADER){
name = name.replace('-','');
for(var i=0 ; i < this.dataElements.length ; i++){
this[name][i] = v instanceof Function?v(this.dataElements[i], i):v
}
}else{
for(var i=0 ; i<l ; i++){
setStyle(this.visualElements[i], name, v instanceof Function?v(this.dataElements[i], i):v, this);
}
}
this.updateStyle = true;
return this;
}
// Interally called after all visual attributes have been specified.
// Method passes updated values to the shader.
set():DataBinding{
if(!this.IS_SHADER)
return this;
var l = this.visualElements.length;
var vertexPositionBuffer = []
var vertexColorBuffer = []
var c
if(this.shape == 'circle'){
for(var i=0 ; i < this.dataElements.length ; i++){
c = new THREE.Color(this.fill[i])
addBufferedCirlce(vertexPositionBuffer, this.x[i],this.y[i], this.z[i], this.r[i] , vertexColorBuffer, [c.r, c.g, c.b, this.opacity[i]])
}
}
var geometry = this.mesh.geometry;
geometry.addAttribute('position', new THREE.BufferAttribute(makeBuffer3f(vertexPositionBuffer), 3));
geometry.addAttribute('customColor', new THREE.BufferAttribute(makeBuffer4f(vertexColorBuffer), 4));
geometry.needsUpdate = true;
geometry.verticesNeedUpdate = true;
this.mesh.material.needsUpdate = true;
this.updateAttributes = false;
this.updateStyle = false;
return this;
}
// Sets the text string for a text element.
text(v:any):DataBinding{
var l = this.visualElements.length;
for(var i=0 ; i<l ; i++){
this.visualElements[i]['text'] = v instanceof Function ? v(this.dataElements[i], i) : v
if(this.visualElements[i]['text'] == undefined)
continue;
setText(this.visualElements[i], this.visualElements[i]['text']);
}
return this;
}
// Internal function to set an attribute for one
// visual object (if no-shader).
setAttr(element:THREE.Mesh, attr:string, v:any, index:number){
switch(attr){
case 'x': element.position.x = v; this.x[index] = v; break;
case 'y': element.position.y = v; this.y[index] = v; break;
case 'z': element.position.z = v; this.z[index] = v; break;
case 'x1': setX1(element, v); break; // lines only
case 'y1': setY1(element, v); break; // lines only
case 'x2': setX2(element, v); break; // lines only
case 'y2': setY2(element, v); break; // lines only
case 'r': element.scale.set(v,v,v); break; // circles only
case 'width': element.scale.setX(v); break;
case 'height': element.scale.setY(v); break;
case 'depth': element.scale.setZ(v); break;
case 'd': createPath(element, v); break;
case 'points': createPolygon(element, v); break;
case 'rotation': element.rotation.z = v * Math.PI / 180; break;
case 'scaleX': element.scale.x = v; break;
case 'scaleY': element.scale.y = v; break;
default: console.error('Attribute', attr, 'does not exist.')
}
element.geometry.verticesNeedUpdate = true;
element.geometry.elementsNeedUpdate = true;
element.geometry.lineDistancesNeedUpdate = true;
}
removeAll(){
for(var i=0 ; i <this.visualElements.length ; i++){
if(this.visualElements[i].wireframe)
this.scene.remove(this.visualElements[i].wireframe)
this.scene.remove(this.visualElements[i]);
}
}
// Assign event handlers
on(event:string, f:Function):DataBinding{
switch(event){
case 'mouseover': this.mouseOverHandler = f; break;
case 'mousemove': this.mouseMoveHandler = f; break;
case 'mouseout': this.mouseOutHandler = f; break;
case 'mousedown': this.mouseDownHandler = f; break;
case 'mouseup': this.mouseUpHandler = f; break;
case 'click': this.clickHandler = f; break;
}
webgl.interactor.register(this, event);
return this;
}
}
////////////////////////
/// INTERNAL METHODS ///
////////////////////////
// The following methods are internal convenience method, called from within
// the DataBinding object, but not visible to the developer.
// Some of the following methods may vanish as the library moves
// entirly to using shaders.
// SET ATTRIBUTE AND STYLE
function setStyle(element:any, attr:string, v:any, dataBinding:DataBinding){
switch(attr){
case 'fill':
if(dataBinding.shape == 'text')
setText(element, element['text'], {color:v})
else
element.material.color = new THREE.Color(v);
break;
case 'stroke':
if(element.hasOwnProperty('wireframe')){
element.wireframe.material.color = new THREE.Color(v);
} else{
element.material.color = new THREE.Color(v);
}
break;
case 'opacity':
element.material.opacity = v;
if(element.hasOwnProperty('wireframe')) element.wireframe.material.opacity = v;
break;
case 'stroke-width':
if(element.hasOwnProperty('wireframe'))
element.wireframe.material.linewidth = v;
else
element.material.linewidth = v;
break;
case 'font-size':
element.scale.x = v/30;
element.scale.y = v/30;
element.geometry.verticesNeedUpdate = true;
break;
default: console.error('Style', attr, 'does not exist.')
}
element.material.needsUpdate=true;
if(element.hasOwnProperty('wireframe'))
element.wireframe.material.needsUpdate=true;
}
function setText(mesh:any, text:string, parConfig?:Object){
var config = parConfig;
if(config == undefined){
config = {};
}
if(config.color == undefined)
config.color = '#000000'
mesh['text'] = text;
var backgroundMargin = 10;
var txtCanvas = document.createElement("canvas");
var context = txtCanvas.getContext("2d");
var SIZE = 30;
context.font = SIZE + "pt Helvetica";
var WIDTH = context.measureText(text).width;
txtCanvas.width = WIDTH;
txtCanvas.height = SIZE;
context.textAlign = "left";
context.textBaseline = "middle";
context.fillStyle = config.color;
context.font = SIZE + "pt Helvetica";
// context.clearColor(1.0, 1.0, 0.0, 1.0)
// context.clear(gl.COLOR_BUFFER_BIT)
context.fillText(text, 0, txtCanvas.height / 2);
var tex = new THREE.Texture(txtCanvas);
tex.minFilter = THREE.LinearFilter
tex.flipY = true;
tex.needsUpdate = true;
mesh.material.map = tex;
mesh.material.transparent = true;
mesh.material.needsUpdate = true;
// adjust mesh geometry
mesh.geometry = new THREE.PlaneGeometry(WIDTH, SIZE);
mesh.geometry.needsUpdate = true;
mesh.geometry.verticesNeedUpdate = true;
mesh.needsUpdate = true;
}
function setX1(mesh:THREE.Line, v){
mesh.geometry.vertices[0].x = v
}
function setY1(mesh:THREE.Line, v){
mesh.geometry.vertices[0].y = v
}
function setX2(mesh:THREE.Line, v){
mesh.geometry.vertices[1].x = v
}
function setY2(mesh:THREE.Line, v){
mesh.geometry.vertices[1].y = v
}
/// CREATE SHAPES
// not used nor tested: stub
function createG(dataElements:any[], scene:THREE.Scene){
var visualElements = []
// create group element for every data element
for(var i=0 ; i<dataElements.length ; i++){
visualElements.push(new GroupElement());
}
return visualElements;
}
// group element representing the 'g' element in D3.
class GroupElement{
position = {x: 0, y:0, z: 0};
children:Object = [];
}
///////////////
/// SHADERS ///
///////////////
/// CIRCLES
var vertexShaderProgram = "\
attribute vec4 customColor;\
varying vec4 vColor;\
void main() {\
vColor = customColor;\
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1 );\
}";
var fragmentShaderProgram = "\
varying vec4 vColor;\
void main() {\
gl_FragColor = vec4(vColor[0], vColor[1], vColor[2], vColor[3]);\
}";
// Creates circles through one geomery per data binding
// and shaders.
function createCirclesWithBuffers(dataBinding:DataBinding, scene:THREE.Scene){
var dataElements = dataBinding.dataElements;
dataBinding.IS_SHADER = true;
var attributes = {
customColor: { type: 'c', value: [] }
}
var shaderMaterial: THREE.ShaderMaterial = new THREE.ShaderMaterial({
attributes: attributes,
vertexShader: vertexShaderProgram,
fragmentShader: fragmentShaderProgram,
linewidth: 2
});
shaderMaterial.blending = THREE.NormalBlending;
shaderMaterial.depthTest = true;
shaderMaterial.transparent = true;
shaderMaterial.side = THREE.DoubleSide;
var visualElements = []
var c;
var vertexPositionBuffer = []
var vertexColorBuffer = []
var geometry = new THREE.BufferGeometry();
// geometry.vertices.push(new THREE.Vector3(10, -10,0))
addBufferedRect([], 0, 0, 0, 10, 10, [], [0,0,1,.5])
for(var i=0 ; i < dataElements.length ; i++){
// addBufferedCirlce(vertexPositionBuffer, Math.random()*10,Math.random()*10,0,2, vertexColorBuffer, [0,0,1,.5] )
dataBinding.x.push(0)
dataBinding.y.push(0)
dataBinding.z.push(0)
dataBinding.r.push(0)
dataBinding.fill.push('0x000000')
dataBinding.stroke.push('0x000000')
dataBinding.strokewidth.push(1)
dataBinding.opacity.push(1)
}
// geometry = new THREE.BufferGeometry();
// CREATE + ADD MESH
geometry.addAttribute('position', new THREE.BufferAttribute(makeBuffer3f([]), 3));
geometry.addAttribute('customColor', new THREE.BufferAttribute(makeBuffer4f([]), 4));
dataBinding.mesh = new THREE.Mesh(geometry, shaderMaterial);
dataBinding.mesh.position.set(0,0,1)
scene.add(dataBinding.mesh);
return dataBinding;
}
// create rectangles (no shaders)
function createRectangles(dataElements:any[], scene:THREE.Scene){
var material;
var geometry;
var visualElements = []
var c;
for(var i=0 ; i < dataElements.length ; i++){
var rectShape = new THREE.Shape();
rectShape.moveTo( 0, 0 );
rectShape.lineTo( 0, -1 );
rectShape.lineTo( 1, -1 );
rectShape.lineTo( 1, 0 );
rectShape.lineTo( 0, 0 );
geometry = new THREE.ShapeGeometry( rectShape );
c = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( {color:0x000000, transparent:true} ) ) ;
c.position.set(0,0,1)
visualElements.push(c);
scene.add( c );
geometry = new THREE.Geometry()
geometry.vertices.push(
new THREE.Vector3(0,0,0),
new THREE.Vector3(0,-1,0),
new THREE.Vector3(1,-1,0),
new THREE.Vector3(1,0,0),
new THREE.Vector3(0,0,0)
);
var wireframe = new THREE.Line( geometry, new THREE.LineBasicMaterial( {color:0x000000, transparent:true, linewidth:1}) ) ;
c['wireframe'] = wireframe;
wireframe.position.set(0,0,1.1)
scene.add(wireframe);
}
return visualElements;
}
// create paths (no shaders)
function createPaths(dataElements:any[], scene:THREE.Scene){
var material;
var geometry;
var visualElements = []
var c,p;
for(var i=0 ; i < dataElements.length ; i++){
geometry = new THREE.Geometry();
c = new THREE.Line( geometry, new THREE.LineBasicMaterial( {color:0x000000, transparent:true} ) ) ;
c.position.set(0,0,0)
visualElements.push(c);
scene.add( c );
}
return visualElements;
}
// create polygons (no shaders)
function createPolygons(dataElements:any[], scene:THREE.Scene){
var material;
var geometry;
var visualElements = []
var c,p;
for(var i=0 ; i < dataElements.length ; i++){
geometry = new THREE.Geometry();
// geometry.vertices.push(
// new THREE.Vector3(5, 0, 0 ),
// new THREE.Vector3( 15, 3, 0 ),
// new THREE.Vector3( 15, -3, 0 )
// );
// geometry.faces.push(new THREE.Face3(0, 1, 2));
c = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( {color:0x000000, transparent:true, side:THREE.DoubleSide })) ;
c.doubleSided = true;
c.position.set(0,0,0)
visualElements.push(c);
scene.add( c );
}
return visualElements;
}
// create lines (no shaders)
function createLines(dataElements:any[], scene:THREE.Scene){
var material;
var geometry;
var visualElements = []
var c,p;
for(var i=0 ; i < dataElements.length ; i++){
geometry = new THREE.Geometry();
geometry.vertices.push(
new THREE.Vector3( -10, 0, 0 ),
new THREE.Vector3( 0, 10, 0 ));
c = new THREE.Line( geometry, new THREE.LineBasicMaterial( {color:0x000000, transparent:true} ) ) ;
c.position.set(0,0,0)
visualElements.push(c);
scene.add( c );
}
return visualElements;
}
// create text (no shaders)
function createWebGLText(dataElements:any[], scene:THREE.Scene){
var visualElements = []
var mesh;
for(var i=0 ; i < dataElements.length ; i++){
mesh = new THREE.Mesh(new THREE.PlaneGeometry(1000, 100), new THREE.MeshBasicMaterial());
mesh.doubleSided = true;
visualElements.push(mesh);
scene.add(mesh);
}
return visualElements;
}
// internal function for creating single path (no shaders)
function createPath(mesh:THREE.Line, points:Object[]){
mesh.geometry.vertices = []
for(var i=0 ; i < points.length ; i++){
mesh.geometry.vertices.push(new THREE.Vector3(points[i].x ,points[i].y, 0));
}
mesh.geometry.verticesNeedUpdate = true;
}
// internal function for creating single polygon (no shaders)
function createPolygon(mesh:THREE.Mesh, points:Object[]){
var vectors = []
var shape = new THREE.Shape(points);
mesh.geometry = new THREE.ShapeGeometry(shape);
mesh.geometry.verticesNeedUpdate = true;
}
///////////////////
/// INTERACTION ///
///////////////////
// Convenience object handling all kinds of interaction
export class WebGLInteractor{
scene;
canvas;
camera
raycaster;
mouse = [];
mouseStart = []
mouseDown:boolean = false;
cameraStart = []
panOffset = []
lastIntersectedSelections = []
lastIntersectedElements = []
isPanEnabled = true;
isHorizontalPanEnabled = true;
isLassoEnabled = true;
lassoPoints = []
lassoStartHandler:Function;
lassoMoveHandler:Function;
lassoEndHandler:Function;
mouseOverSelections:DataBinding[] = []
mouseMoveSelections:DataBinding[] = []
mouseOutSelections:DataBinding[] = []
mouseDownSelections:DataBinding[] = []
mouseUpSelections:DataBinding[] = []
clickSelections:DataBinding[] = []
constructor(scene:THREE.Scene, canvas:HTMLCanvasElement, camera:THREE.Camera){
this.scene = scene;
this.canvas = canvas
this.camera = camera;
this.mouse = [0,0];
canvas.addEventListener('mousemove', (e) => {
this.mouseMoveHandler(e);
})
canvas.addEventListener('mousedown', (e) => {
this.mouseDownHandler(e);
})
canvas.addEventListener('mouseup', (e) => {
this.mouseUpHandler(e);
})
canvas.addEventListener('click', (e) => {
this.clickHandler(e);
})
// not really working in iFrames.. needs fix
// window.addEventListener('keyDown', (e)=>{
// this.keyDownHandler(e);
// })
// window.addEventListener('keyUp', (e)=>{
// this.keyUpHandler(e);
// })
}
register(selection:DataBinding, method:string){
switch(method){
case 'mouseover': this.mouseOverSelections.push(selection); break;
case 'mousemove': this.mouseMoveSelections.push(selection); break;
case 'mouseout': this.mouseOutSelections.push(selection); break;
case 'mousedown': this.mouseDownSelections.push(selection); break;
case 'mouseup': this.mouseUpSelections.push(selection); break;
case 'click': this.clickSelections.push(selection); break;
}
}
addEventListener(eventName:String, f:Function){
if(eventName == 'lassoStart')
this.lassoStartHandler = f;
if(eventName == 'lassoEnd')
this.lassoEndHandler = f;
if(eventName == 'lassoMove')
this.lassoMoveHandler = f;
}
// Event handlers
mouseMoveHandler(e){
this.mouse = mouseToWorldCoordinates(e.clientX, e.clientY)
if(this.isLassoEnabled && e.which == 2){
this.lassoPoints.push(this.mouse)
if(this.lassoMoveHandler)
this.lassoMoveHandler(this.lassoPoints);
}else{
var intersectedVisualElements:any[] = []
// remove previous highlighting
for(var i = 0 ; i < this.lastIntersectedSelections.length ; i++){
for(var j = 0 ; j < this.lastIntersectedElements[i].length ; j++){
this.lastIntersectedSelections[i].call('mouseout', this.lastIntersectedElements[i][j])
}
}
this.lastIntersectedSelections = []
this.lastIntersectedElements = []
var nothingIntersected = true;
// call mouseover on all elements with a mouse over handler
for(var i = 0 ; i < this.mouseOverSelections.length ; i++){
// If selecton is SHADER, check manually
intersectedVisualElements = this.intersect( this.mouseOverSelections[i], this.mouse[0], this.mouse[1]);
if(intersectedVisualElements.length > 0){
this.lastIntersectedElements.push(intersectedVisualElements);
this.lastIntersectedSelections.push(this.mouseOverSelections[i])
}
for(var j = 0 ; j < intersectedVisualElements.length ; j++){
this.mouseOverSelections[i].call('mouseover',intersectedVisualElements[j], e)
}
if(intersectedVisualElements.length > 0)
nothingIntersected = false;
}
// call mousemove on all elements with a mouse move handler
for(var i = 0 ; i < this.mouseMoveSelections.length ; i++){
intersectedVisualElements = this.intersect( this.mouseMoveSelections[i], this.mouse[0], this.mouse[1]);
// console.log('intersectedVisualElements', intersectedVisualElements, this.mouseMoveSelections[i])
for(var j = 0 ; j < intersectedVisualElements.length ; j++){
this.mouseMoveSelections[i].call('mousemove',intersectedVisualElements[j], e)
}
if(intersectedVisualElements.length > 0)
nothingIntersected = false;
}
// if nothing intersected pan:
if(nothingIntersected && this.mouseDown){
if(this.isPanEnabled){
this.panOffset = [e.clientX - this.mouseStart[0], e.clientY - this.mouseStart[1]]
if(this.isHorizontalPanEnabled)
webgl.camera.position.x = this.cameraStart[0] - this.panOffset[0]/webgl.camera.zoom;
webgl.camera.position.y = this.cameraStart[1] + this.panOffset[1]/webgl.camera.zoom;
webgl.render();
}
}
}
}
clickHandler(e){
this.mouse = mouseToWorldCoordinates(e.clientX, e.clientY)
var intersectedVisualElements:any[] = []
// call mouseclick on all elements with a mouse over handler
for(var i = 0 ; i < this.clickSelections.length ; i++){
intersectedVisualElements = this.intersect( this.clickSelections[i], this.mouse[0], this.mouse[1]);
for(var j = 0 ; j < intersectedVisualElements.length ; j++){
this.clickSelections[i].call('click',intersectedVisualElements[j], e)
}
}
this.mouseDown = false;
}
mouseDownHandler(e){
this.mouse = mouseToWorldCoordinates(e.clientX, e.clientY)
this.mouseStart= [e.clientX, e.clientY]
this.cameraStart = [webgl.camera.position.x, webgl.camera.position.y];
this.mouseDown = true;
var intersectedVisualElements:any[] = []
for(var i = 0 ; i < this.mouseDownSelections.length ; i++){
intersectedVisualElements = this.intersect( this.mouseDownSelections[i], this.mouse[0], this.mouse[1]);
for(var j = 0 ; j < intersectedVisualElements.length ; j++){
this.mouseDownSelections[i].call('mousedown',intersectedVisualElements[j], e)
}
}
this.lassoPoints = []
this.lassoPoints.push(this.mouse)
if(this.lassoStartHandler && e.which == 2){
this.lassoStartHandler(this.lassoPoints);
}
}
mouseUpHandler(e){
this.mouse = mouseToWorldCoordinates(e.clientX, e.clientY)
var intersectedVisualElements:any[] = []
for(var i = 0 ; i < this.mouseUpSelections.length ; i++){
intersectedVisualElements = this.intersect( this.mouseUpSelections[i], this.mouse[0], this.mouse[1]);
for(var j = 0 ; j < intersectedVisualElements.length ; j++){
this.mouseUpSelections[i].call('mouseup',intersectedVisualElements[j], e)
}
}
this.mouseDown = false;
if(this.lassoEndHandler && e.which == 2){
this.lassoEndHandler(this.lassoPoints);
}
}
// Tests for mouse intersection of any of the visual objects in
// the passed data binding.
// Returns list of data elements.
intersect(selection:DataBinding, mousex, mousey):any[]{
switch(selection.shape){
case 'circle': return this.intersectCircles(selection);
case 'rect': return this.intersectRects(selection);
case 'path': return this.intersectPaths(selection);
case 'text': return this.intersectRects(selection);
}
return []
}
intersectCircles(selection:DataBinding):any[]{
var intersectedElements = []
var d;
for(var i = 0 ; i < selection.dataElements.length ; i++){
d = Math.sqrt(Math.pow(this.mouse[0] - selection.x[i], 2) + Math.pow(this.mouse[1] - selection.y[i], 2))
if(d <= selection.r[i])
intersectedElements.push(selection.dataElements[i]);
}
return intersectedElements;
}
intersectRects(selection:DataBinding):any[]{
var intersectedElements = []
var d;
var e;
for(var i = 0 ; i < selection.visualElements.length ; i++){
e = selection.visualElements[i];