aboutsummaryrefslogtreecommitdiff
path: root/js/lib/drawing/world.js
blob: fb70d18c1ff67b14229789b4e094ac3c86888c26 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
/* <copyright>
Copyright (c) 2012, Motorola Mobility, Inc
All Rights Reserved.
BSD License.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

  - Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
  - Neither the name of Motorola Mobility nor the names of its contributors
    may be used to endorse or promote products derived from this software
    without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
</copyright> */


var GeomObj = require("js/lib/geom/geom-obj").GeomObj;
var Line = require("js/lib/geom/line").Line;
var Rectangle = require("js/lib/geom/rectangle").Rectangle;
var Circle = require("js/lib/geom/circle").Circle;
var MaterialsModel = require("js/models/materials-model").MaterialsModel;

var worldCounter = 0;

///////////////////////////////////////////////////////////////////////
// Class GLWorld
//      Manages display in a canvas
///////////////////////////////////////////////////////////////////////
var World = function GLWorld( canvas, use3D, preserveDrawingBuffer ) {
    ///////////////////////////////////////////////////////////////////////
    // Instance variables
    ///////////////////////////////////////////////////////////////////////

	// flag to do the drawing with WebGL
    this._useWebGL = false;
    if(use3D) {
        this._useWebGL = use3D;
    }

    this._canvas = canvas;
	if (this._useWebGL)
	{
        if(preserveDrawingBuffer)
		{
            this._glContext = canvas.getContext("experimental-webgl", {preserveDrawingBuffer: true});
        }
		else
		{
		    this._glContext = canvas.getContext("experimental-webgl");
        }
    }
	else
	{
		this._2DContext = canvas.getContext( "2d" );
    }
    
	this._viewportWidth = canvas.width;
    this._viewportHeight = canvas.height;

	// view parameters
	this._fov = 45.0;
	this._zNear = 0.1;
	this._zFar = 100.0;
	this._viewDist = 5.0;

	// default light parameters
	this._ambientLightColor  = [0.1, 0.1, 0.1,  1.0];
	this._diffuseLightColor  = [0.1, 0.1, 0.1,  1.0];
	this._specularLightColor = [0.6, 0.6, 0.6,  1.0];
	this._pointLightLoc = [0.0, 0.0, 0.05];

	// default material properties.  Material properties should be overridden
	// by the materials used by the objects
	this._materialShininess = 20.0;

    this._geomRoot = undefined;

	this._cameraMat = Matrix.I(4);
	this._cameraMat[14] = 5.0;
	this._cameraMatInv = Matrix.I(4);
	this._cameraMatInv[14] = -5.0;

    this._camera = null;
	// keep a flag indicating whether a render has been completed.
	// this allows us to turn off automatic updating if there are
	// no animated materials
	this._firstRender = true;

	this._worldCount = worldCounter;
	worldCounter++;

	// keep a counter for generating node names
	this._nodeCounter = 0;

    // for sending notifications to listeners
    this._notifier = new Notifier();

    ///////////////////////////////////////////////////////////////////////
    // Property accessors
    ///////////////////////////////////////////////////////////////////////
    this.getGLContext		= function()		{  return this._glContext;			};
    this.setGLContext		= function(gl)		{  this._glContext = gl;			};

    this.get2DContext		= function()		{  return this._2DContext;			};
    this.set2DContext		= function(c)		{  this._2DContext = c;				};

    this.getCanvas			= function()		{  return this._canvas;				};
    this.setCanvas			= function(c)		{  this._canvas = c;				};

    this.getShaderProgram	= function()		{  return this._shaderProgram;		};

	this.getViewportWidth	= function()		{  return this._viewportWidth;		};
	this.getViewportHeight  = function()		{  return this._viewportHeight;		};

	this.getAspect			= function()		{  return this._viewportWidth/this._viewportHeight;  };

	this.getGeomRoot			= function()		{  return this._geomRoot;			};
	this.getZNear				= function()		{  return this._zNear;				};
	this.getZFar				= function()		{  return this._zFar;				};
	this.getFOV					= function()		{  return this._fov;				};

	this.getCamera				= function()		{  return this._camera;				};

	this.getCameraMat			= function()		{  return this._cameraMat.slice(0);	};
	this.setCameraMat			= function(c)		{  this._cameraMat = c.slice(0);  this._cameraMatInv = glmat4.inverse(c, []);  };

	this.getCameraMatInverse  = function()		{  return this._cameraMatInv.slice(0); };

	this.getViewDistance		= function()		{  return this._viewDist;			};

	this.getRootNode			= function()		{  return this._rootNode;			};
	this.setRootNode			= function(r)		{  this._rootNode = r;				};

	this.isWebGL				= function()		{  return this._useWebGL;			};

	this.getRenderer			= function()		{  return this.renderer;			};

    // Flag to play/pause animation at authortime
    this._previewAnimation = true;
  
  ////////////////////////////////////////////////////////////////////////////////////
  // RDGE
  // local variables
    this.myScene = null;
    this.elapsed = 0;
    this.light = null;
    this.light2 = null;
    this.fillShader = null;
    this.strokeShader = null;
    this.renderer = null;

	// keep an array of texture maps that need to be loaded
	this._texMapsToLoad = [];
	this._allMapsLoaded = true;

	// this is the node to which objects get hung
	this._rootNode = null;

	// set up the camera matrix
	var camMat = Matrix.I(4);
	camMat[14] = this.getViewDistance();
	this.setCameraMat( camMat );
    
    // post-load processing of the scene
    this.init = function()
	{
		var ctx1 = RDGE.globals.engine.ctxMan.handleToObject(this._canvas.rdgeCtxHandle),
			ctx2 = RDGE.globals.engine.getContext();
		if (ctx1 != ctx2)  console.log( "***** different contexts *****" );
		this.renderer = ctx1.renderer;
		this.renderer._world = this;
      
		// create a camera, set its perspective, and then point it at the origin
		var cam = new RDGE.camera();
		this._camera = cam;
		cam.setPerspective(this.getFOV(), this.getAspect(), this.getZNear(), this.getZFar());
		cam.setLookAt([0, 0, this.getViewDistance()], [0, 0, 0], RDGE.vec3.up());
        
		// make this camera the active camera
		this.renderer.cameraManager().setActiveCamera(cam);

		// change clear color
		//this.renderer.setClearFlags(RDGE.globals.engine.getContext().DEPTH_BUFFER_BIT);
		this.renderer.setClearColor([0.0, 0.0, 0.0, 0.0]);
		//this.renderer.NinjaWorld = this;
        
		// create an empty scene graph
		this.myScene = new RDGE.SceneGraph();
        
		// create some lights
		// light 1
//		this.light = RDGE.createLightNode("myLight");
//		this.light.setPosition([0,0,1.2]);
//		this.light.setDiffuseColor([0.75,0.9,1.0,1.0]);
        
		// light 2
//		this.light2 = RDGE.createLightNode("myLight2");
//		this.light2.setPosition([-0.5,0,1.2]);
//		this.light2.setDiffuseColor([1.0,0.9,0.75,1.0]);
        
		// create a light transform
		var lightTr = RDGE.createTransformNode("lightTr");
        
		// create and attach a material - materials hold the light data
		lightTr.attachMaterial(RDGE.createMaterialNode("lights"));
        
		// enable light channels 1, 2 - channel 0 is used by the default shader
//		lightTr.materialNode.enableLightChannel(1, this.light);
//		lightTr.materialNode.enableLightChannel(2, this.light2);
     
		// all added objects are parented to the light node
		this._rootNode = lightTr;
        
		// add the light node to the scene
		this.myScene.addNode(lightTr);
        
		// Add the scene to the engine - necessary if you want the engine to draw for you
		//RDGE.globals.engine.AddScene("myScene" + this._canvas.id, this.myScene);
		var name = this._canvas.getAttribute( "data-RDGE-id" ); 
		RDGE.globals.engine.AddScene("myScene" + name, this.myScene);
	};
    
	// main code for handling user interaction and updating the scene   
	this.update = function(dt)
	{
		if (!dt)  dt = 0.2;
        
		dt = 0.01;	// use our own internal throttle
		this.elapsed += dt;
        
		if (this._useWebGL)
		{
			// changed the global position uniform of light 0, another way to change behavior of a light
		    RDGE.rdgeGlobalParameters.u_light0Pos.set([5 * Math.cos(this.elapsed), 5 * Math.sin(this.elapsed), 20]);
        
			// orbit the light nodes around the boxes
//			this.light.setPosition([1.2*Math.cos(this.elapsed*2.0), 1.2*Math.sin(this.elapsed*2.0), 1.2*Math.cos(this.elapsed*2.0)]);
//			this.light2.setPosition([-1.2*Math.cos(this.elapsed*2.0), 1.2*Math.sin(this.elapsed*2.0), -1.2*Math.cos(this.elapsed)]);
		}
        
		this.updateMaterials( this.getGeomRoot(), this.elapsed );

		// now update all the nodes in the scene
		if (this._useWebGL)
			this.myScene.update(dt);
    };

    // defining the draw function to control how the scene is rendered      
	this.draw = function()
	{
		if (this._useWebGL)
		{
			RDGE.globals.engine.setContext( this._canvas.rdgeid );
			var ctx = RDGE.globals.engine.getContext();
			var renderer = ctx.renderer;
			if (renderer.unloadedTextureCount <= 0)
			{
				renderer.disableCulling();
				renderer._clear();
				this.myScene.render();

				if (this._firstRender)
				{
					this._notifier.sendNotification( this._notifier.FIRST_RENDER );
					if (this._canvas.task)
					{
						this._firstRender = false;

						if (!this.hasAnimatedMaterials() || !this._previewAnimation)
						{
							this._canvas.task.stop();
							//this._renderCount = 10;
						}
					}
				}
				else if (this._renderCount >= 0)
				{
					if (this._canvas.task)
					{
						this._renderCount--;
						if (this._renderCount <= 0)
						{
							this._canvas.task.stop();
                        }
					}
				}
			}
		}
		else
		{
			this.render();
		}
    };
	
    this.onRunState = function() {
//		console.log( "GLWorld.onRunState" );
		this.restartRenderLoop();
	};
	
    this.onLoadState = function() {
//		console.log( "GLWorld.onLoadState" );
	};

	this.textureToLoad = function( texture )
	{
		if (!texture.previouslyReferenced)
		{
			var name = texture.lookUpName;
			texture._world = this;
			texture.callback = this.textureMapLoaded;
			this._texMapsToLoad[name] = true;
			this._allMapsLoaded = false;

			// stop the draw loop until all textures have been loaded
			this._canvas.task.stop();
		}
	};

	this.textureMapLoaded = function( texture )
	{
		var world = texture._world;
		if (!world) {
			console.log( "**** loaded texture does not have world defined ****" );
			return;
		}

		var name = texture.lookUpName;
		if (!world._texMapsToLoad[name]) {
			console.log( "loaded an unregistered texture map: " + name );
		}
		else {
			//console.log( "loaded a registered texture map: " + name );
			world._texMapsToLoad[name] = undefined;
		}

		// check if all the texture maps are loaded.  if so, resume the render loop
		world._allMapsLoaded = world.allTextureMapsLoaded();
		if (world._allMapsLoaded) {
			world._canvas.task.start();
        }
	};

	this.allTextureMapsLoaded = function() {
		for (var name in this._texMapsToLoad) {
			var needsLoad = this._texMapsToLoad[name];
			if (needsLoad)  return false;
		}

		return true;
	};

	this.textureLoadedCallback = function( name ) {
//		console.log( "*** material texture loaded: " + name );

		var world = this._world;
		if (!world) {
			console.log( "**** world not defined for loaded texture map: " + name );
        }
		else {
			world.textureMapLoaded( name );
        }
	};
	
	this.hasAnimatedMaterials = function() {
		var root = this.getGeomRoot();
		var rtnVal = false;
		if (root) {
			rtnVal = this.hHasAnimatedMaterials( root );
            this._hasAnimatedMaterials = rtnVal;
        }
		else
		{
			// currently...
			// we set this case to true - cloud materials create a
			// world with no objects but cloud materials animate.
			// TODO - find a better way to do this
			rtnVal = true;
			this._hasAnimatedMaterials = true;
		}

		return rtnVal;
	};

	this.hHasAnimatedMaterials = function( obj ) {
		if (obj) {
			if (obj.getFillMaterial()) {
				if (obj.getFillMaterial().isAnimated())  return true;
			}

			if (obj.getStrokeMaterial()) {
				if (obj.getStrokeMaterial().isAnimated())  return true;
			}


			// do the sibling
			var hasAnim = false;
			if  (obj.getNext())  hasAnim = this.hHasAnimatedMaterials( obj.getNext() );
			if (hasAnim)  return true;
			if  (obj.getChild())  hasAnim = this.hHasAnimatedMaterials( obj.getChild() );
			if (hasAnim)  return true;
		}

		return false;
	};

	this.generateUniqueNodeID = function() {
		var str = "" + this._nodeCounter;
		this._nodeCounter++;
		return str;
	};

    this.addListener = function( obj,  callbackFunc,  calleeData )
    {
        this._notifier.addListener( obj, callbackFunc, calleeData );
    }

    this.removeListener = function( obj )
    {
        this._notifier.removeListener( obj );
    }
    
    // start RDGE passing your runtime object, and false to indicate we don't need a an initialization state
    // in the case of a procedurally built scene an init state is not needed for loading data
	this._canvas.rdgeid = this._canvas.getAttribute( "data-RDGE-id" );
	if (this._useWebGL) {
		rdgeStarted = true;
		RDGE.globals.engine.unregisterCanvas( this._canvas );
		RDGE.globals.engine.registerCanvas(this._canvas, this);
		RDGE.RDGEStart( this._canvas );
		this._canvas.task.stop()
	}
};


///////////////////////////////////////////////////////////////////////
// Property Accessors
///////////////////////////////////////////////////////////////////////
World.prototype.getGeomRoot = function()  {
    return this._geomRoot;
};


///////////////////////////////////////////////////////////////////////
// Methods
///////////////////////////////////////////////////////////////////////
World.prototype.updateObject = function (obj) {
	if (!this._useWebGL)  return;

	var prims = obj.getPrimitiveArray();
	var materialNodes = obj.getMaterialNodeArray();
	if (prims.length != materialNodes.length)
		throw new Error("inconsistent material and primitive counts");
	var nPrims = prims.length;
	var ctrTrNode;
	if (nPrims > 0)
	{
		ctrTrNode = obj.getTransformNode();
		if (ctrTrNode == null) {
			ctrTrNode = RDGE.createTransformNode("objRootNode_" + this._nodeCounter++);
			this._rootNode.insertAsChild( ctrTrNode );
			obj.setTransformNode( ctrTrNode );
		}

		ctrTrNode.meshes.forEach(
			function(thisMesh) {
				RDGE.globals.meshMan.deleteMesh(thisMesh.mesh.name);
			}
		);
		ctrTrNode.meshes = [];

		ctrTrNode.attachMeshNode(this.renderer.id + "_prim_" + this._nodeCounter++, prims[0]);
		ctrTrNode.attachMaterial(materialNodes[0]);
	}
	
	// delete all of the child nodes
	var i;
	var childTrNode;
	var children = ctrTrNode.children;
	for (i=0;  i<children.length;  i++)
	{
		childTrNode = children[i].transformNode;
		childTrNode.meshes.forEach(
			function(thisMesh)
			{
				RDGE.globals.meshMan.deleteMesh(thisMesh.mesh.name);
			}
		);
		childTrNode.meshes = [];
		children[i] = null;
	}
	ctrTrNode.children = [];

	for (var i = 1; i < nPrims; i++)
	{
		// get the next primitive
		childTrNode = RDGE.createTransformNode("objNode_" + this._nodeCounter++);
		ctrTrNode.insertAsChild(childTrNode);

		// attach the instanced box goe
		var prim = prims[i];
		childTrNode.attachMeshNode(this.renderer.id + "_prim_" + this._nodeCounter++, prim);
		childTrNode.attachMaterial(materialNodes[i]);
	}

	// send a notification that the tree has changed
	this._notifier.sendNotification( this._notifier.OBJECT_CHANGE );
};

World.prototype.addObject = function( obj )
{
    if (!obj)  return;

    try {
        // undefine all the links of the object
        obj.setChild( undefined );
        obj.setNext( undefined );
        obj.setPrev( undefined );
        obj.setParent( undefined );

        obj.setWorld( this );

        if (this._geomRoot == null)
		{
            this._geomRoot = obj;
        }
		else
		{
            var go = this._geomRoot;
            while (go.getNext())  go = go.getNext();
            go.setNext( obj );
            obj.setPrev( go );
        }

		// build the WebGL buffers
		if (this._useWebGL) {
			obj.buildBuffers();
			this.restartRenderLoop();
		}

        // send a notification that the tree has changed
        this._notifier.sendNotification( this._notifier.OBJECT_CHANGE );
    }

    catch(e) {
        alert( "Exception in GLWorld.addObject " + e );
    }
};

World.prototype.restartRenderLoop = function()
{
	//console.log( "restartRenderLoop" );

	this._firstRender = true;
	this._renderCount  = -1;
	if (this._canvas.task)
	{
		if (this._allMapsLoaded)
		{
			//console.log( "starting task" );
			this._canvas.task.start();
		}
		else
		{
			//console.log( "stopping task" );
			this._canvas.task.stop();
		}
	}
};

World.prototype.stop = function()
{
	if (this._canvas && this._canvas.task)
		this._canvas.task.stop();
}

World.prototype.start = function()
{
	if (this._canvas && this._canvas.task)
		this._canvas.task.start();
}

//append to the list of objects if obj doesn't already exist
//if obj exists, then don't add to list of objects
World.prototype.addIfNewObject = function (obj) {
    if (!obj) return;

    try {
        obj.setWorld(this);

        if (this._geomRoot == null)
		{
            this._geomRoot = obj;
        }
		else if (this._geomRoot !== obj)
		{
            var go = this._geomRoot;
            while (go.getNext() && go.getNext() !== obj)
			{
                go = go.getNext();
            }

            if (go.getNext() === null)
			{
                // undefine all the links of the object
                obj.setChild(undefined);
                obj.setNext(undefined);
                obj.setPrev(undefined);
                obj.setParent(undefined);

                go.setNext(obj);
                obj.setPrev(go);
            }
        }

		// build the WebGL buffers
		if (this._useWebGL) {
			obj.buildBuffers();
			this.restartRenderLoop();
		}

        // send a notification that the tree has changed
        this._notifier.sendNotification( this._notifier.OBJECT_CHANGE );

    } catch (e) {
        alert("Exception in GLWorld.addIfNewObject " + e);
    }
};

World.prototype.clearTree = function()
{
    this._notifier.sendNotification( this._notifier.OBJECT_DELETE );

	if (this._useWebGL)
    {
		var root = this._rootNode;
		root.children = new Array();
		RDGE.globals.engine.unregisterCanvas( this._canvas.rdgeid );

		this.update( 0 );
		this.draw();
	}
};

World.prototype.updateMaterials = function( obj, time ) {
	if (!obj)  return;

	var matArray = obj.getMaterialArray();
	if (matArray) {
		var n = matArray.length;
		for (var i=0;  i<n;  i++) {
			matArray[i].update( time );
	}
	}

	this.updateMaterials( obj.getNext(),  time );
	this.updateMaterials( obj.getChild(), time );
};

// return the origin of the world in NDC
World.prototype.getNDCOrigin = function() {
  var pt = MathUtils.transformPoint( [0,0,0], this.getCameraMatInverse() );
  var projMat = Matrix.makePerspective( this.getFOV(), this.getAspect(), this.getZNear(), this.getZFar());
  var ndcPt = MathUtils.transformHomogeneousPoint( pt, projMat );

  return  MathUtils.applyHomogeneousCoordinate( ndcPt );
};

World.prototype.worldToScreen = function(v) {
	var pMatrix = Matrix.makePerspective( this._fov, this.getAspect(), this._zNear, this._zFar);
	var mvMatrix = this.getCameraMatInverse();
	//var tmpMat = pMatrix.multiply( mvMatrix );
	var tmpMat = glmat4.multiply(pMatrix, mvMatrix, []);
	//var v2 = tmpMat.multiply( v );
	var v2 = glmat4.multiplyVec3( tmpMat, v, []);
	var v3 = MathUtils.transformHomogeneousPoint( v, tmpMat );
	v3 = MathUtils.applyHomogeneousCoordinate( v3 );
	var x = v2[0],  y = v2[1],  z = v2[2];

	var h = this.getGLContext().viewportHeight/2.0, w = this.getGLContext().viewportWidth/2.0;
    var x2 = w * (1 + x), y2 = h * ( 1 - y );
    return [x2, y2, z, 1];
};

World.prototype.screenToView = function( x, y ) {
	var gl = this._glContext;
	var w = gl.viewportWidth/2.0,
		h = gl.viewportHeight/2.0;

	var xv = x/w - 1,
		yv = 1.0 - y/h;

	return [xv,yv];
};

World.prototype.screenToWorld = function( xScr,  yScr ) {
	var viewVec = this.screenToView( xScr, yScr );
	var xView = viewVec[0],  yView = viewVec[1];

	var tmp = this.worldToScreen( [0,0,0,1] );
	var zView = tmp[2];

	// get the perspective matrix
	var pMatrix = Matrix.makePerspective( this._fov, this.getAspect(), this._zNear, this._zFar);
	var mvMatrix = Matrix.I(4);   // this would be the inverse of the camera matrix (if we had one).

	//var tmpMat = pMatrix.multiply( mvMatrix );
	var tmpMat = glmat4.multiply( pMatrix, mvMatrix, []);
	//var tmpInv = tmpMat.inverse();
	var tmpInv = glmat4.inverse( tmpMat, []);
	var v3 = [xView,  yView, zView, 1 ];
	//var w = tmpInv.multiply( v3 );
	var w = glmat4.multiplyVec4( tmpInv, v3, []);
	w[0] /= w[3];
	w[1] /= w[3];
	w[2] /= w[3];
	w[3] = 1.0;

	return w;
};

World.prototype.GLToScreen = function( glPt ) {
};

World.prototype.ScreenToGL = function( scrPt ) {
};


World.prototype.resetMatrixStack = function() {
    this._matStack = new Array();
    this._matStack.push( Matrix.I(4) );
};

World.prototype.pushMatrix = function( mat ) {
    if (mat) {
        var mat2 = this.stackTop();
        if (mat2) {
			var mat12 = glmat4.multiply( mat, mat2, []);
			this._matStack.push( mat12 );
		}
    }
};

World.prototype.stackTop = function() {
    var mat;
    if (this._matStack && (this._matStack.length > 0)) {
        mat = this._matStack[ this._matStack.length-1];
    }

    return mat;
};

World.prototype.popMatrix = function() {
    if (this._matStack.length == 0) {
        throw "Invalid popMatrix!";
    }

    return this._matStack.pop();
};

World.prototype.setMVMatrix = function() {
    var mat = this.stackTop();
    if (mat) {
		var gl = this._glContext;

        //var mvMatrix = this._cameraMatInv.multiply(mat);
		var mvMatrix = glmat4.multiply( this._cameraMatInv, mat, []);
        //var mat2 = mat.multiply( this._cameraMatInv );
        gl.uniformMatrix4fv(this._shaderProgram.mvMatrixUniform, false, new Float32Array(mvMatrix));

        var normalMatrix = mat3.create();
        // RDGE.mat4.toInverseMat3(mvMatrix, normalMatrix);
        // RDGE.mat4.toInverseMat3(new Float32Array(mvMatrix.flatten()), normalMatrix);
        RDGE.mat4.toInverseMat3(new Float32Array(mvMatrix), normalMatrix);
        mat3.transpose(normalMatrix);
        gl.uniformMatrix3fv(this._shaderProgram.nMatrixUniform, false, normalMatrix);
    }
};

World.prototype.makePerspectiveMatrix = function() {
  return Matrix.makePerspective( this.getFOV(),  this.getAspect(),  this.getZNear(),  this.getZFar() );
};

World.prototype.render = function()
{
	if (!this._useWebGL)
	{
		// clear the context
		var ctx = this.get2DContext();
		if (!ctx)  return;
		ctx.clearRect(0, 0, this.getViewportWidth(), this.getViewportHeight());
		
		// render the geometry
		var root = this.getGeomRoot();
		this.hRender( root );
	} 
	else
	{
		RDGE.globals.engine.setContext( this._canvas.rdgeid );
		//this.draw();
		this.restartRenderLoop();
	}
};

World.prototype.hRender = function( obj )
{
	if (!obj)  return;
	obj.render();

	this.hRender( obj.getChild() );
	this.hRender( obj.getNext() );
};

World.prototype.setViewportFromCanvas = function(canvas) {
	this._viewportWidth = canvas.width;
	this._viewportHeight = canvas.height;

	if (this._useWebGL) {
		this._glContext.viewportWidth = canvas.width;
		this._glContext.viewportHeight = canvas.height;

		this.getCamera().setPerspective(this.getFOV(), this.getAspect(), this.getZNear(), this.getZFar());
		
		this.renderer.setViewPort(0, 0, canvas.width, canvas.height);
	}
};

World.prototype.getShapeFromPoint = function( offsetX, offsetY ) {
	var x = offsetX/this._canvas.width;
	var y = offsetY/this._canvas.height;

	var go = th