aboutsummaryrefslogtreecommitdiff
path: root/js/helper-classes/RDGE/src/core/script/jpass.js
blob: 326394dcd5476bf07f5e1b3dea2f9de07f580dbc (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
/* <copyright>
This file contains proprietary software owned by Motorola Mobility, Inc.<br/>
No rights, expressed or implied, whatsoever to this software are provided by Motorola Mobility, Inc. hereunder.<br/>
(c) Copyright 2011 Motorola Mobility, Inc.  All Rights Reserved.
</copyright> */

/*
 *	jpass geometry set - determines the category(s) of geometry that a pass will render
 *	can be OR'ed together
 */
jpassGeoSet =
{
	'BACKGROUND'	:1,
	'OPAQUE'		:2,
	'TRANSPARENT'	:4,
	'ADDITIVE'		:8,
	'TRANSLUCENT'	:16,
	'FOREGROUND'	:32,
	'ALL'			:127,
	'SCREEN_QUAD'	:128,	// a screen aligned quad - for rendering a texture to screen
	'SHADOW'		:256,	// the opaque geometry from shadow light's point of view
	'MAXSETS'		:9
};


/*
 *	The abstract base class that defines a jpass
 *	a jpass represents a single render pass of the scene graph
 */
_jpassBaseClass = function() {
    this.context = g_Engine.getContext();
    this.renderer = g_Engine.getContext().renderer;
    this.sortCats = rdgeConstants.categoryEnumeration;
    this.bucketCount = rdgeConstants.categoryEnumeration.MAX_CAT;

    // render order
    this.renderOrder = [];
    this.renderOrder[this.sortCats.BACKGROUND] = 0;
    this.renderOrder[this.sortCats.OPAQUE] = 1;
    this.renderOrder[this.sortCats.TRANSPARENT] = 2;
    this.renderOrder[this.sortCats.ADDITIVE] = 3
    this.renderOrder[this.sortCats.TRANSLUCENT] = 4;
    this.renderOrder[this.sortCats.FOREGROUND] = 5;

    // the name of this pass
    this.name = "renderPass_" + nodeIdGen.getId();

    /* 
    *	if 0 this pass and children are culled from rendering
    */
    this.visibility = 1;

    /*
    *	called when the pass is hidden - override for customication
    */
    this.onHide = function() {

    }

    /*
    *	Called by the system to hide the pass and its children
    */
    this.hidePass = function() {
        this.onHide();

        for (var i = 0, len = this.children.length; i < len; ++i) {
            this.children[i].hidePass();
        }
    }

    /*
    *	the default output render targets that this pass will create
    */
    this.defaultTargetOut = {};

    /*
    * All the outputs required by the pass
    */
    this.outputs =
	[
    // example
    // {'name':"u_mainRT", 'type':"target", 'width':1024, 'height':1024, 'mips':false}
	];

    /*
    *	notifies the the renderer that the viewport was modified and needs to be reset
    */
    this.dirty = false;

    /*
    *	Index of the currently selected output target
    */
    this.outputIndex = 0;

    /*
    *	outputs from the previous pass are set as inputs for this pass
    */
    this.inputs =
	[
	];

    /*
    *	other textures requested for this pass
    */
    this.textures =
	[

	];

    /*
    *	the flags that control how the pass is rendered
    */
    this.frustum_culling = "enable"; 		// disable/enable frustum culling during the pass
    this.clear = null; 						// flags to clear the output target with before rendering
    this.clearColor = null;

    /*
    *	Contains a list of geometry to be rendered, during a post process render pass this will usually by a screen quad
    */
    this.renderList =
	[
    // example
    // { 'name':'opaqeobjects', 'geo'{ 'OPAQUE':[ new renderObject(meshNode, transformNode, RenderContext)]} }
	];

    /*
    *	The passes that will render after this pass
    */
    this.children = [];

    /*
    *	This shader will override all other shaders
    */
    this.shader = null;

    /*
    *	Technique of from shader to use, if null currently set technique is used
    */
    this.technique = null;

    /*
    *	determines the geometry that will be rendered during the pass
    */
    this.geometrySet = "SCREEN_QUAD";


    /*
    *	A camera set here will override any camera active in the scene
    */
    this.camera = null;

    /*
    *	Initialize the pass
    */
    this.init = function() {

    }

    /*
    *	inserts a node into the child map using the pass name as the key
    */
    this.insertChildPass = function(jpassObj) {
        this.children[jpassObj.name] = jpassObj;
    }

    /*
    *	the scene-graph to process
    */
    this.process = function() {
        // pre-defined local variables to prevent allocation
        var context;
        var shaderProg;
        var listCount;
        var len;
        var passes;
        var pass;
        var node;
        var mesh;
        var meshCount;
        var nodeIdx = 0;
        var meshIdx = 0;
        var paramIdx = 0;
        var passIdx = 0;

        var renderer = g_Engine.getContext().renderer;

        //this.renderer = g_Engine.getContext().renderer;

        // bind output target for rendering
        this.bindOutput();

        // call custom pre-render step
        this.preRender();

        var activeCam = renderer.cameraManager().getActiveCamera();

        if (this.technique) {
            this.shader.setTechnique(this.technique);
        }

        renderer.projectionMatrix = activeCam.proj;

        // parameters that can be set once per pass
        rdgeGlobalParameters.u_inv_viewport_width.set([1.0 / renderer.vpWidth]);
        rdgeGlobalParameters.u_inv_viewport_height.set([1.0 / renderer.vpHeight]);
        rdgeGlobalParameters.u_farZ.set([activeCam.zFar()]);
        rdgeGlobalParameters.u_projMatrix.set(renderer.projectionMatrix);

        for (var bucketIdx = 0, bckCnt = this.renderList.length; bucketIdx < bckCnt; ++bucketIdx) {
            //var curList		= this.renderList[bucketIdx];
            listCount = this.renderList[bucketIdx].length;

            for (nodeIdx = 0; nodeIdx < listCount; ++nodeIdx) {
                node = this.renderList[bucketIdx][nodeIdx].node;

                if (node.world) {
                    context = this.renderList[bucketIdx][nodeIdx].context;
                    shaderProg = this.shader ? this.shader : context.shaderProg;

                    renderer.mvMatrix = mat4.mul4x3(node.world, activeCam.view);
                    renderer.invMvMatrix = mat4.inverse(renderer.mvMatrix);
                    renderer.normalMatrix = mat4.transpose(renderer.invMvMatrix);
                    
                    rdgeGlobalParameters.u_mvMatrix.set(renderer.mvMatrix);
                    rdgeGlobalParameters.u_normalMatrix.set(renderer.normalMatrix);
                    rdgeGlobalParameters.u_worldMatrix.set(node.world);

                    rdgeGlobalParameters.u_viewMatrix.set(activeCam.view);
                    rdgeGlobalParameters.u_invViewMatrix.set(mat4.inverse(activeCam.view));
                    rdgeGlobalParameters.u_invMvMatrix.set(renderer.invMvMatrix);

                    len = context.uniforms.length;
                    for (paramIdx = 0; paramIdx < len; ++paramIdx) {
                        rdgeGlobalParameters[context.uniforms[paramIdx].name].set(context.uniforms[paramIdx].value);
                    }

                    // augment the texture list with any post processing textures
                    this.updateTextureContext(context.textureList);

                    shaderProg.setLightContext(context.lights);
                    shaderProg.setTextureContext(context.textureList);

                    passes = shaderProg.begin();
                    pass = null;
                    for (passIdx = 0; passIdx < passes; ++passIdx) {
                        pass = shaderProg.beginPass(passIdx);

                        meshCount = node.meshes.length;
                        for (meshIdx = 0; meshIdx < meshCount; ++meshIdx) {
                            mesh = g_meshMan.getModelByName(node.meshes[meshIdx].mesh.name);

                            if (mesh)
                                renderer.drawPrimitive(mesh.primitive, pass.program, pass.attributes);

                        }

                        shaderProg.endPass();

                        this.onPassEnd();
                    }

                    shaderProg.end();
                }
            }

        }

        // call custom post render step
        this.postRender();

        // remove the bound render target if applicable
        this.unbindOutput();
    }

    /*
    *	handle any setup 'before' processing the geo/scenegraph
    *	the first step in the pass
    */
    this.preRender = function() {

    }


    /*
    *	handle any setup 'after' processing the geo/scenegraph
    *	the last step in the pass
    */
    this.postRender = function() {

    }


    /*
    *	Custom function to handle any processing in between jshader passes
    */
    this.onPassEnd = function() {
        if (this.outputIndex + 1 < this.outputs.length)
            ++this.outputIndex;
    }

    /*
    *	Set the list of objects to render
    */
    this.setRenderList = function(contextList) {
        this.renderList = contextList;
    }

    /*
    *	Set the render targets to use as input for the next pass
    */
    this.setInputs = function(inputsArr) {
        this.inputs = inputsArr.slice();
    }

    /*
    *	Augment the textureList passed in with the input textures
    *	this will cause the textures to be bound to the jshader
    */
    this.updateTextureContext = function(textureList) {
        var inputs = this.inputs.slice();
        for (var i = 0; i < this.inputs.length; ++i) {
            textureList.push(inputs[i]);
        }

        for (var i = 0; i < this.textures.length; ++i) {
            if (this.textures[i].enabled)
                textureList.push(this.textures[i]);
        }
    }

    /*
    *	If there is an output surface this will bind it
    */
    this.bindOutput = function() {
        this.outputIndex = 0;
        if (this.outputs[this.outputIndex]) {
            this.dirty = true;
            var oldClear = null;
            var fb = this.outputs[this.outputIndex].data[0].frameBuffer;
            this.renderer.ctx.bindFramebuffer(this.renderer.ctx.FRAMEBUFFER, fb);
            this.renderer.ctx.viewport(0, 0, fb.width, fb.height);
            if (this.clearColor) {
                oldClear = this.renderer.clearColor;
                this.renderer.setClearColor(this.clearColor);
            }

            if (this.clear)
                this.renderer.clear(this.clear);
            else
                this.renderer._clear();

            if (this.clearColor) {
                this.renderer.setClearColor(oldClear);
            }
        }
    }

    /*
    *	If an output surface was bound this will unbind it
    */
    this.unbindOutput = function() {
        if (this.dirty) {
            this.dirty = false;
            this.renderer.ctx.bindFramebuffer(this.renderer.ctx.FRAMEBUFFER, null);
            this.renderer.setViewPort(0, 0, this.renderer.vpWidth, this.renderer.vpHeight);
        }

    }
}

/*
 *	The concrete class to be used when creating a scene pass
 */
jpass = function( def )
{
	// inherit from the base class
	this.inheritedFrom = _jpassBaseClass;
	this.inheritedFrom();
	
	// setup the jpass as defined, recursively instantiated the children as they are encountered
	for(var obj in def)
	{
		this[obj] = def[obj];
		
		if(obj == "children")
		{
			var childCount = this[obj].length;
			for(var i = 0; i < childCount; ++i)
			{
				this[obj][i] = new jpass(this[obj][i]);
			}
		}
		// validate array and create the texture/render-target
		else if(obj == "inputs" || obj == "outputs")
		{
			// this makes sure the data type was passed as an array and converts it to an array if needed
			if(!this[obj].slice())
			{
				this[obj] = [this[obj]];
			}
			
			var count = this[obj].length;
			for(var i = 0; i < count; ++i)
			{
				// if the texture/render-target is not created yet do so now
				if(!this[obj][i].data)
				{
					if(this[obj][i].type == "target")
					{
						// setup the render target
						this[obj][i].data = [this.renderer.createRenderTargetTexture(this[obj][i].name, this[obj][i].width, this[obj][i].height, this[obj][i].mips)];
					}
					else
					{
						// make sure data is defined
						this[obj][i].data = [null]				
					}
				}
				
				if(!this[obj][i].handle)
				{
					this[obj][i].handle = this[obj][i].data[0];
				}
			}
		}
		else if("renderList" == obj)
		{
			// put the items listed into their  buckets
			var renderList  = new Array(rdgeConstants.categoryEnumeration.MAX_CAT);
			renderList[rdgeConstants.categoryEnumeration.BACKGROUND]		= [];	//BACKGROUND	
			renderList[rdgeConstants.categoryEnumeration.OPAQUE]			= [];	//OPAQUE		
			renderList[rdgeConstants.categoryEnumeration.TRANSPARENT]		= [];	//TRANSPARENT
			renderList[rdgeConstants.categoryEnumeration.ADDITIVE]			= [];	//ADDITIVE
			renderList[rdgeConstants.categoryEnumeration.TRANSLUCENT]		= [];	//TRANSLUCENT
			renderList[rdgeConstants.categoryEnumeration.FOREGROUND]		= [];	//FOREGROUND
			
			for(var buckets in this[obj])
			{
				// get the enumeration value (ie rdgeConstants.categoryEnumeration.OPAQUE)
				var bucket = rdgeConstants.categoryEnumeration[buckets];
				
				// create the list for this bucket
				
				var len = this[obj][buckets].length;
				for(var i = 0; i < len; ++i)
				{
					// add the corresponding objects to the bucket
					renderList[bucket].push(this[obj][buckets][i]);
				}
				
			}
			
			// overwrite with the new list
			this[obj] = renderList;
		}
		else if("shader" == obj)
		{
			// setup the shader
			if(typeof this[obj] == "string")
			{
				this.shader = new jshader(this[obj]);				
			}
			else
			{
				var finalShader = new jshader();
				finalShader.def = this[obj];
				finalShader.init();
				this[obj] = finalShader;
			}
		}
		else if("geometrySet" == obj)
		{
			if( typeof this[obj] == "string")
			{
				var sets = this[obj].split("|");
				
				var setValue = 0;
				for(var i = 0; i < sets.length; ++i)
				{
					setValue |= jpassGeoSet[sets[i]];	
					if(sets[i] === "SCREEN_QUAD")
					{
						this[obj] = jpassGeoSet[sets[i]];
						this.renderList[0] = [new renderObject( createScreenQuadNode() )];
						break;
					}
				}
				
				this[obj] = setValue;
			}
		}	
		else if("textures" == obj)
		{
			for(var i = 0, len = this[obj].length; i < len; ++i)
			{
				if(typeof this[obj][i].data == "string")
				{
					this[obj][i].name = this[obj][i].data;
					this[obj][i].data = [this[obj][i].data];
					this[obj][i].enabled = true;
				}
				else
				{
					this[obj][i].name = this.renderer.getTextureByName(this[obj][i].data[0].lookUpName);
				}
			}
		}
		
	}
	
	// call initialize code
	this.init();
	
}

/*
 *	a graph describing the hierarchy of scene pass objects to create the final composition
 */ 
jpassGraph = function( def )
{
	// the root pass
	this.root = null;
	
	// going through steps to build the pass graph
	if(def && typeof def == "string")
	{
		// make ajax request
	}
	else if(def)
	{
		this.root = new jpass(def);
	}
	else
	{
		this.root = new jpass({});	
	}
	
	this.find = null;
	this.insert = null;
	
	// an index to the opaque bucket
	this.OPAQUE = rdgeConstants.categoryEnumeration.OPAQUE;
	
	this.setPassRoot = function(jpassObj)
	{
		this.root = jpassObj;
	}
	
	/*
	 *	Helper function to generate the references to passes available as passGraph."passName"
	 */
	this._initHelper = function(node)
	{
		if(!node)
			return;
			
		this[node.name] = node;

		for(var child in node.children)
		{
			this._initHelper(node.children[child]);
		}
	}
	this._initHelper(this.root);
	
	/*
	 *	@param parentName - the name of the parent object to insert under
	 *	@param jpassObj - the jpass object to insert
	 */
	this.insertAsChild = function(parentName, jpassObj)
	{
		this.find = parentName;
		this.insert = jpassObj;
		
		// create ref for this object
		this[jpassObj.name] = jpassObj;
		
		this._insertHelper(this.root);
		
		this.find = null;
		this.insert = null;
	}
	
	/*
	 *	Recursive helper function for traversing the graph and insterting the node
	 */
	this._insertHelper = function(node)
	{
		if(!node)
			return false;
			
		if(node.name == this.find)
		{
			node.insertChildPass(this.insert);
			return true;
		}
		
		for(var child in node.children)
		{
			if(this._insertHelper(node.children[child]))
			{
				break;
			}
		}
		
		return true;
	}
	
	// maps jpassGeoSet values to indices
	this.geoSetMap = [];
	var geoSetIdx = 0;
	for(var geoSet in jpassGeoSet)
	{
		this.geoSetMap[geoSetIdx++] = jpassGeoSet[geoSet];
	}
	
	/*
	 *	Traverse the render graph, breadth first to produce the final render output
	 *	note: breadth first is used to allow generation of an entire level at once, 
	 *	the peers in one level could, in theory, be processed in parallel
	 */
	this.render = function( sceneGraph ) {

		g_renderStats.numPasses.value=0;
		var renderList = sceneGraph.renderList;
		var renderer = g_Engine.getContext().renderer;
		
		// set the first pass with scene geometry
		this.root.setRenderList(renderList);
		
		var curRenderList = null;
		
		var queue = [ {'parent':this.root } ];
		
		var parent = null;
		var setCount = this.geoSetMap.length;
		var maxCats	 = rdgeConstants.categoryEnumeration.MAX_CAT;
		var idx = 0;
		var renderListIdx = 0;
		
		while(queue.length)
		{
			var parent = queue.shift().parent;
			
			// pull out the shadow geometry
			if(sceneGraph.shadowsEnabled && parent.geometrySet === jpassGeoSet.SHADOW)
			{
				parent.setRenderList( [ sceneGraph.shadowRenderList ] );
			}
			// screen quad needs special prep since geometry is never re-assigned, lists needs to be cleaned up
			else if(parent.geometrySet === jpassGeoSet.SCREEN_QUAD)
			{
				parent.renderList[0][0].context.textureList = [];
			}
			// pull out all the sort categories that the pass requested
			else
			{
				curRenderList = [];
				renderListIdx = 0;
				
				// create the pass's render list
				for(idx = 0; idx < setCount; ++idx)
				{
					// assign the render list, checking to make sure the index is less than the total number of material categories
					if(parent.geometrySet & this.geoSetMap[idx])
					{
						if(renderList[idx])
						{
							curRenderList[renderListIdx++] = renderList[idx];
						}
					}
				}
				
				parent.setRenderList(curRenderList);
			}

			// if this pass has a camera push it on the stack
			if(parent.camera)
			{
				renderer.cameraManager().pushCamera(parent.camera);
			}	
			
			// process the geometry - all rendering occurs here
			g_renderStats.numPasses.value++;
			parent.process();
			
			// if this pass had a camera pop it off the stack
			if(parent.camera)
			{
				renderer.cameraManager().popCamera();
			}
			
			// push on the children
			for(idx = parent.children.length - 1; idx >= 0; --idx)
			{
				if(parent.children[idx].visibility === 1)
				{
					parent.children[idx].setInputs( parent.outputs );
					queue.unshift({'parent': parent.children[idx] });
				}
				else if(parent.children[idx].visibility === 0)
				{
					parent.children[idx].hidePass();
					parent.children[idx].visibility = 2;
				}
			}
		}
    }
}