forked from adobe/GLS3D
-
Notifications
You must be signed in to change notification settings - Fork 0
/
libGL.as
3185 lines (2759 loc) · 129 KB
/
libGL.as
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
/*
Copyright (c) 2012, Adobe Systems Incorporated
All rights reserved.
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 Adobe Systems Incorporated 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.
*/
package GLS3D
{
import flash.display.*;
import flash.display3D.*;
import flash.display3D.textures.*;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.TextEvent;
import flash.geom.*;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.trace.Trace;
import flash.utils.*;
import com.adobe.utils.*;
import com.adobe.utils.macro.*;
import com.adobe.flascc.CModule;
// Linker trickery
[Csym("D", "___libgl_abc__", ".data")]
public class GLAPI
{
include 'libGLconsts.as';
private static var _instance:GLAPI
public var disableCulling:Boolean = false
public var disableBlending:Boolean = false
public var log:Object = null; // new TraceLog();
public var context:Context3D
public var genOnBind:Boolean = false
private const consts:Vector.<Number> = new <Number>[0.0, 0.5, 1.0, 2.0]
private const zeroes:Vector.<Number> = new <Number>[0.0, 0.0, 0.0, 0.0]
// bit 0 = whether textures are enabled
private const ENABLE_TEXTURE_OFFSET:uint = 0
// bits 1-6 = whether clip planes 0-5 are enabled
private const ENABLE_CLIPPLANE_OFFSET:uint = 1
// bit 7 = whether color material is enabled
private const ENABLE_COLOR_MATERIAL_OFFSET:uint = 7
// bit 8 = whether lighting is enabled
private const ENABLE_LIGHTING_OFFSET:uint = 8
// bit 9-16 = whether lights 0-7 are enabled
private const ENABLE_LIGHT_OFFSET:uint = 9
// bit 17 = whether specular is separate
private const ENABLE_SEPSPEC_OFFSET:uint = 17
// bit 18 = whether polygon offset is enabled
private const ENABLE_POLYGON_OFFSET:uint = 18
private var _stage:Stage
private var overrideR:uint
private var overrideG:uint
private var overrideB:uint
private var overrideA:uint = 0xFF
private var scissorRect:Rectangle
private var contextEnableScissor:Boolean = false
private var bgColorOverride:Boolean = false
private var fixed_function_programs:Dictionary = new Dictionary()
private var contextDepthFunction:String = Context3DCompareMode.LESS
private var reusableCommandList:CommandList = new CommandList()
private var reusableVertexBuffers:Dictionary = new Dictionary()
private var immediateVertexBuffers:VertexBufferPool = new VertexBufferPool()
private var sharedIndexBuffers:Dictionary = new Dictionary()
private var contextColor:Vector.<Number> = new <Number>[1, 1, 1, 1]
private var frontFaceClockWise:Boolean = false // we default to CCW
private var glCullMode:uint = GL_BACK
private var lightingStates:Vector.<LightingState> = new Vector.<LightingState>()
private var texID:uint = 1 // so we have 0 as non-valid id
private var shininessVec:Vector.<Number> = new <Number>[0.0, 0.0, 0.0, 0.0]
private var globalAmbient:Vector.<Number> = new <Number>[0.2, 0.2, 0.2, 1]
private var polygonOffsetValue:Number = -0.0005
private var lights:Vector.<Light> = new Vector.<Light>(8)
private var lightsEnabled:Vector.<Boolean> = new Vector.<Boolean>(8)
private var enableTexGenS:Boolean = false
private var enableTexGenT:Boolean = false
private var texGenParamS:uint = GL_SPHERE_MAP
private var texGenParamT:uint = GL_SPHERE_MAP
private var contextWidth:int = 0
private var contextHeight:int = 0
private var contextAA:int = 0
private var contextClearR:Number
private var contextClearG:Number
private var contextClearB:Number
private var contextClearA:Number
private var contextClearDepth:Number = 1.0
private var contextClearStencil:uint = 0
private var contextClearMask:uint
private var contextEnableStencil:Boolean = false
private var contextEnableAlphaTest:Boolean = false
private var contextStencilActionStencilFail:String = Context3DStencilAction.KEEP
private var contextStencilActionDepthFail:String = Context3DStencilAction.KEEP
private var contextStencilActionPass:String = Context3DStencilAction.KEEP
private var contextStencilCompareMode:String = Context3DCompareMode.ALWAYS
private var contextEnableDepth:Boolean = true
private var contextDepthMask:Boolean = true
private var contextSrcBlendFunc:String = Context3DBlendFactor.ZERO
private var contextDstBlendFunc:String = Context3DBlendFactor.ONE
private var contextEnableCulling:Boolean
private var contextEnableBlending:Boolean
private var contextDepthFunc:String = Context3DCompareMode.ALWAYS
private var contextEnableTextures:Boolean = false
private var contextEnableLighting:Boolean = false
private var contextColorMaterial:Boolean = false
private var contextSeparateSpecular:Boolean = false
private var contextEnablePolygonOffset:Boolean = false
private var needClear:Boolean = true
private var vertexAttributesDirty:Boolean = true
private var activeCommandList:CommandList = null
private var commandLists:Vector.<CommandList> = null
private var textures:Dictionary = new Dictionary()
private var vertexBufferAttributes:Vector.<VertexBufferAttribute> = new Vector.<VertexBufferAttribute>(8)
private var textureUnits:Array = new Array(32)
private var activeProgram:ProgramInstance
private var activeTextureUnit:uint = 0
private var activeTexture:TextureInstance
private var textureSamplers:Vector.<TextureInstance> = new Vector.<TextureInstance>(8)
private var textureSamplerIDs:Vector.<uint> = new Vector.<uint>(8)
private var vertexBufferObjects:Vector.<VertexBuffer3D> = new Vector.<VertexBuffer3D>()
private var framestamp:uint = 1
private var offsetFactor:Number = 0.0
private var offsetUnits:Number = 0.0
private var glStateFlags:uint = 0
private var clipPlanes:Vector.<Number> = new Vector.<Number>(6 * 4) // space for 6 clip planes
private var clipPlaneEnabled:Vector.<Boolean> = new Vector.<Boolean>(8) // defaults to false
private var modelViewStack:Vector.<Matrix3D> = new <Matrix3D>[ new Matrix3D() ]
private var projectionStack:Vector.<Matrix3D> = new <Matrix3D>[ new Matrix3D() ]
private var textureStack:Vector.<Matrix3D> = new <Matrix3D>[ new Matrix3D() ]
private var currentMatrixStack:Vector.<Matrix3D> = modelViewStack
private var contextMaterial:Material = new Material(true)
private var cubeVertexData:Vector.<Number>;
private var cubeVertexBuffer:VertexBuffer3D = null;
public static function init(context:Context3D, log:Object, stage:Stage):void
{
_instance = new GLAPI(context, log, stage)
if (log) log.send("GLAPI initialized.")
}
public static function get instance():GLAPI
{
if (!_instance)
{
trace("Instance is null, did you forget calling GLAPI.init() in AlcConsole.as?")
}
return _instance
}
public function send(value:String):void
{
if (log)
log.send(value)
}
private function matrix3DToString(m:Matrix3D):String
{
var data:Vector.<Number> = m.rawData
return ("[ " + data[0].toFixed(3) + ", " + data[4].toFixed(3) + ", " + data[8].toFixed(3) + ", " + data[12].toFixed(3) + " ]\n" +
"[ " + data[1].toFixed(3) + ", " + data[5].toFixed(3) + ", " + data[9].toFixed(3) + ", " + data[13].toFixed(3) + " ]\n" +
"[ " + data[2].toFixed(3) + ", " + data[6].toFixed(3) + ", " + data[10].toFixed(3) + ", " + data[14].toFixed(3) + " ]\n" +
"[ " + data[3].toFixed(3) + ", " + data[7].toFixed(3) + ", " + data[11].toFixed(3) + ", " + data[15].toFixed(3) + " ]")
}
// ======================================================================
// Polygon Offset
// ----------------------------------------------------------------------
public function glPolygonMode(face:uint, mode:uint):void
{
switch(mode)
{
case GL_POINT:
if (log) log.send("glPolygonMode GL_POINT not yet implemented, mode is always GL_FILL.")
break
case GL_LINE:
if (log) log.send("glPolygonMode GL_LINE not yet implemented, mode is always GL_FILL.")
break
default:
// GL_FILL!
}
}
public function glPolygonOffset(factor:Number, units:Number):void
{
offsetFactor = factor
offsetUnits = units
//if (log) log.send("glPolygonOffset() called with (" + factor + ", " + units + ")")
if (log) log.send("glPolygonOffset() not yet implemented.")
}
public function glShadeModel(mode:uint):void
{
switch(mode)
{
case GL_FLAT:
if (log) log.send("glShadeModel GL_FLAT not yet implemented, mode is always GL_SMOOTH.")
break
default:
// GL_SMOOTH!
}
}
// ======================================================================
// Alpha Testing
// ----------------------------------------------------------------------
public function glAlphaFunc(func:uint, ref:Number):void
{
//TODO: fixme
}
private function setVector(vec:Vector.<Number>, x:Number, y:Number, z:Number, w:Number):void
{
vec[0] = x
vec[1] = y
vec[2] = z
vec[3] = w
}
private function copyVector(dest:Vector.<Number>, src:Vector.<Number>):void
{
dest[0] = src[0]
dest[1] = src[1]
dest[2] = src[2]
dest[3] = src[3]
}
public function glMaterial(face:uint, pname:uint, r:Number, g:Number, b:Number, a:Number):void
{
// if pname == GL_SPECULAR, then "r" is shininess.
// FIXME (klin): Ignore face for now. Always GL_FRONT_AND_BACK
var material:Material
if (activeCommandList)
{
var activeState:ContextState = activeCommandList.ensureActiveState()
material = activeCommandList.activeState.material
}
else
{
material = contextMaterial
}
switch (pname)
{
case GL_AMBIENT:
if (!material.ambient)
material.ambient = new <Number>[r, g, b, a]
else
setVector(material.ambient, r, g, b, a)
break
case GL_DIFFUSE:
if (!material.diffuse)
material.diffuse = new <Number>[r, g, b, a]
else
setVector(material.diffuse, r, g, b, a)
break
case GL_AMBIENT_AND_DIFFUSE:
if (!material.ambient)
material.ambient = new <Number>[r, g, b, a]
else
setVector(material.ambient, r, g, b, a)
if (!material.diffuse)
material.diffuse = new <Number>[r, g, b, a]
else
setVector(material.diffuse, r, g, b, a)
break
case GL_SPECULAR:
if (!material.specular)
material.specular = new <Number>[r, g, b, a]
else
setVector(material.specular, r, g, b, a)
break
case GL_SHININESS:
material.shininess = r
break
case GL_EMISSION:
if (!material.emission)
material.emission = new <Number>[r, g, b, a]
else
setVector(material.emission, r, g, b, a)
break
default:
if (log) log.send("[NOTE] Unsupported glMaterial call with 0x" + pname.toString(16))
}
}
public function glLightModeli(pname:uint, param:int):void
{
switch (pname)
{
case GL_LIGHT_MODEL_COLOR_CONTROL:
contextSeparateSpecular = (param == GL_SEPARATE_SPECULAR_COLOR)
if (contextSeparateSpecular)
setGLState(ENABLE_SEPSPEC_OFFSET)
else
clearGLState(ENABLE_SEPSPEC_OFFSET)
break
// unsupported for now
case GL_LIGHT_MODEL_TWO_SIDE:
case GL_LIGHT_MODEL_AMBIENT:
case GL_LIGHT_MODEL_LOCAL_VIEWER:
default:
break
}
if (log) log.send("glLightModeli() not yet implemented")
}
public function glLight(light:uint, pname:uint, r:Number, g:Number, b:Number, a:Number):void
{
var lightIndex:int = light - GL_LIGHT0
if (lightIndex < 0 || lightIndex > 7)
{
if (log) log.send("glLight(): light index " + lightIndex + " out of bounds")
return
}
var l:Light = lights[lightIndex]
if (!l)
l = lights[lightIndex] = new Light(true, lightIndex == 0)
switch (pname)
{
case GL_AMBIENT:
l.ambient[0] = r
l.ambient[1] = g
l.ambient[2] = b
l.ambient[3] = a
break
case GL_DIFFUSE:
l.diffuse[0] = r
l.diffuse[1] = g
l.diffuse[2] = b
l.diffuse[3] = a
break
case GL_SPECULAR:
l.specular[0] = r
l.specular[1] = g
l.specular[2] = b
l.specular[3] = a
break
case GL_POSITION:
// transform position to eye-space before storing.
var m:Matrix3D = modelViewStack[modelViewStack.length - 1].clone();
var result:Vector3D;
if (a == 0.0)
{ // Directional light
m.position = new Vector3D(0, 0, 0, 1);
result = m.transformVector(new Vector3D(r, g, b, a));
l.position[0] = result.x;
l.position[1] = result.y;
l.position[2] = result.z;
l.position[3] = 0;
l.type = Light.LIGHT_TYPE_DIRECTIONAL;
}
else
{ // Point light
result = m.transformVector(new Vector3D(r, g, b, a));
l.position[0] = result.x;
l.position[1] = result.y;
l.position[2] = result.z;
l.position[3] = result.w;
l.type = Light.LIGHT_TYPE_POINT;
}
break
default:
break
}
}
public function glGetIntegerv(pname:uint, buf:ByteArray, offset:uint):void
{
if (log) log.send("glGetIntegerv")
switch (pname)
{
case GL_MAX_TEXTURE_SIZE:
buf.position = offset
buf.writeInt(4096)
break
case GL_VIEWPORT:
buf.position = offset+0; buf.writeInt(0); // x
buf.position = offset+4; buf.writeInt(0); // y
buf.position = offset+8; buf.writeInt(contextWidth); // width
buf.position = offset+12; buf.writeInt(contextHeight); // height
break
default:
if (log) log.send("[NOTE] Unsupported glGetIntegerv call with 0x" + pname.toString(16))
}
}
public function glGetFloatv(pname:uint, buf:ByteArray, offset:uint):void
{
if (log) log.send("glGetFloatv")
switch (pname)
{
case GL_MODELVIEW_MATRIX:
var v:Vector.<Number> = new Vector.<Number>(16)
modelViewStack[modelViewStack.length - 1].copyRawDataTo(v)
buf.position = offset
for (var i:int; i < 16; i++)
buf.writeFloat(v[i])
break
default:
if (log) log.send("[NOTE] Unsupported glGetFloatv call with 0x" + pname.toString(16))
}
}
public function glClipPlane(plane:uint, a:Number, b:Number, c:Number, d:Number):void
{
if (log) log.send("[NOTE] glClipPlane called for plane 0x" + plane.toString(16) + ", with args " + a + ", " + b + ", " + c + ", " + d)
var index:int = plane - GL_CLIP_PLANE0
// Convert coordinates to eye space (modelView) before storing
var m:Matrix3D = modelViewStack[modelViewStack.length - 1].clone()
m.invert()
m.transpose()
var result:Vector3D = m.transformVector(new Vector3D(a, b, c, d))
clipPlanes[ index * 4 + 0 ] = result.x
clipPlanes[ index * 4 + 1 ] = result.y
clipPlanes[ index * 4 + 2 ] = result.z
clipPlanes[ index * 4 + 3 ] = a * m.rawData[3] + b * m.rawData[7] + c * m.rawData[11] + d * m.rawData[15] //result.w
}
private function executeCommandList(cl:CommandList):void
{
// FIXME (egeorgire): do this on-deamnd?
// Pre-calculate matrix
var m:Matrix3D = modelViewStack[modelViewStack.length - 1].clone()
var p:Matrix3D = projectionStack[projectionStack.length - 1].clone()
var t:Matrix3D = textureStack[textureStack.length - 1].clone()
//m.append(p)
p.prepend(m)
var invM:Matrix3D = m.clone()
invM.invert()
var modelToClipSpace:Matrix3D = p
if (isGLState(ENABLE_POLYGON_OFFSET))
{
// Adjust the projection matrix to give us z offset
if (log)
log.send("Applying polygon offset")
modelToClipSpace = p.clone()
modelToClipSpace.appendTranslation(0, 0, polygonOffsetValue)
}
// Current active textures ??
var ti:TextureInstance
var i:int
for (i = 0; i < 1; i++ )
{
ti = textureSamplers[i]
if (ti && contextEnableTextures) {
context.setTextureAt(i, ti.boundType == GL_TEXTURE_2D ? ti.texture : ti.cubeTexture)
if(log) log.send("setTexture " + i + " -> " + ti.texID)
}
else {
context.setTextureAt(i, null)
if(log) log.send("setTexture " + i + " -> 0")
}
}
var textureStatInvalid:Boolean = false;
const count:int = cl.commands.length
var command:Object
for (var k:int = 0; k < count; k++)
{
command = cl.commands[k]
var stateChange:ContextState = command as ContextState
if (stateChange)
{
// We execute state changes before stream changes, so
// we must have a state change
// Execute state changes
if (contextEnableTextures && stateChange.textureSamplers)
{
for (i = 0; i < 1; i++ )
{
var texID:int = stateChange.textureSamplers[i]
if (texID != -1)
{
if (log) log.send("Mapping texture " + texID + " to sampler " + i)
ti = (texID != 0) ? textures[texID] : null
textureSamplers[i] = ti
activeTexture = ti // Executing the glBind, so that after running through the list we have the side-effect correctly
textureStatInvalid = true
if (ti)
context.setTextureAt(i, ti.boundType == GL_TEXTURE_2D ? ti.texture : ti.cubeTexture)
else
context.setTextureAt(i, null)
if(log) log.send("setTexture " + i + " -> " + (ti ? ti.texID : 0))
}
}
}
var stateMaterial:Material = stateChange.material
if (stateMaterial)
{
if (stateMaterial.ambient)
copyVector(contextMaterial.ambient, stateMaterial.ambient)
if (stateMaterial.diffuse)
copyVector(contextMaterial.diffuse, stateMaterial.diffuse)
if (stateMaterial.specular)
copyVector(contextMaterial.specular, stateMaterial.specular)
if (!isNaN(stateMaterial.shininess))
contextMaterial.shininess = stateMaterial.shininess
if (stateMaterial.emission)
copyVector(contextMaterial.emission, stateMaterial.emission)
}
}
var stream:VertexStream = command as VertexStream
if (stream)
{
// Make sure we have the right program, and see if we need to updated it if some state change requires it
ensureProgramUpToDate(stream)
// If the program has no textures, then disable them all:
if (!stream.program.hasTexture)
{
for (i = 0; i < 8; i++ )
{
context.setTextureAt(i, null)
if(log) log.send("setTexture " + i + " -> 0")
}
}
context.setProgram(stream.program.program)
// FIXME (egeorgie): do we need to do this after setting every program, or just once after we calculate the matrix?
if (stream.polygonOffset)
{
// Adjust the projection matrix to give us z offset
if (log)
log.send("Applying polygon offset, recorded in the list")
modelToClipSpace = p.clone()
modelToClipSpace.appendTranslation(0, 0, polygonOffsetValue)
}
context.setProgramConstantsFromMatrix(Context3DProgramType.VERTEX, 0, modelToClipSpace, true)
if (stream.polygonOffset)
{
// Restore
modelToClipSpace = p
}
context.setProgramConstantsFromMatrix(Context3DProgramType.VERTEX, 4, m, true)
context.setProgramConstantsFromMatrix(Context3DProgramType.VERTEX, 8, invM, true)
context.setProgramConstantsFromMatrix(Context3DProgramType.VERTEX, 12, t, true)
context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, 16, consts)
context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, 17, contextColor)
// Upload the clip planes
context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, 18, clipPlanes, 6)
// Zero-out the ones that are not enabled
for (i = 0; i < 6; i++)
{
if (!clipPlaneEnabled[i])
context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, 18 + i, zeroes, 1)
}
// Calculate origin of eye-space
context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, 24, new <Number>[0, 0, 0, 1], 1)
// Upload material components
context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, 25, contextMaterial.ambient, 1)
context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, 26, contextMaterial.diffuse, 1)
context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, 27, contextMaterial.specular, 1)
shininessVec[0] = contextMaterial.shininess
context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, 28, shininessVec, 1)
context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, 29, contextMaterial.emission, 1)
// Upload lights
// FIXME (klin): will be per light...for now, fake a light and assume local viewer.
// default global light:
context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, 30, globalAmbient, 1)
// light constants
for (i = 0; i < 8; i++)
{
var index:int = 31 + i*4
if (lightsEnabled[i])
{
var l:Light = lights[i]
context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, index, l.position, 1)
context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, index+1, l.ambient, 1)
context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, index+2, l.diffuse, 1)
context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, index+3, l.specular, 1)
}
else
{
context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, index, zeroes, 1)
context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, index+1, zeroes, 1)
context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, index+2, zeroes, 1)
context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, index+3, zeroes, 1)
}
}
// Map the Vertex buffer
// position
context.setVertexBufferAt(0, stream.vertexBuffer, 0 /*bufferOffset*/, Context3DVertexBufferFormat.FLOAT_3)
// color
if (0 != (stream.program.vertexStreamUsageFlags & VertexBufferBuilder.HAS_COLOR))
context.setVertexBufferAt(1, stream.vertexBuffer, 3 /*bufferOffset*/, Context3DVertexBufferFormat.FLOAT_4)
else
context.setVertexBufferAt(1, null)
// normal
if (0 != (stream.program.vertexStreamUsageFlags & VertexBufferBuilder.HAS_NORMAL))
context.setVertexBufferAt(2, stream.vertexBuffer, 7 /*bufferOffset*/, Context3DVertexBufferFormat.FLOAT_3)
else
context.setVertexBufferAt(2, null)
// texture coords
if (0 != (stream.program.vertexStreamUsageFlags & VertexBufferBuilder.HAS_TEXTURE2D))
context.setVertexBufferAt(3, stream.vertexBuffer, 10 /*bufferOffset*/, Context3DVertexBufferFormat.FLOAT_2)
else
context.setVertexBufferAt(3, null)
context.drawTriangles(stream.indexBuffer)
// If we're executing on compilation, this may be an immediate command stream, so update the pool
if (cl.executeOnCompile)
immediateVertexBuffers.markInUse(stream.vertexBuffer)
}
}
}
public function glGenLists(count:uint):uint
{
if (log) log.send("glGenLists " + count)
if (!commandLists)
commandLists = new Vector.<CommandList>()
var oldLength:int = commandLists.length
commandLists.length = oldLength + count
return oldLength
}
public function glMatrixMode(mode:uint):void
{
if (log) log.send("glMatrixMode \nSwitch stack to " + MATRIX_MODE[mode - GL_MODELVIEW])
switch (mode)
{
case GL_MODELVIEW:
currentMatrixStack = modelViewStack
break
case GL_PROJECTION:
currentMatrixStack = projectionStack
break
case GL_TEXTURE:
currentMatrixStack = textureStack
break
default:
if (log) log.send("Unknown Matrix Mode " + mode)
}
}
public function glPushMatrix():void
{
if (log) log.send("glPushMatrix")
currentMatrixStack.push(currentMatrixStack[currentMatrixStack.length - 1].clone())
}
public function glPopMatrix():void
{
if (log) log.send("glPopMatrix")
currentMatrixStack.pop()
if(currentMatrixStack.length == 0) {
trace("marix stack underflow!")
currentMatrixStack.push(new Matrix3D())
}
}
public function glLoadIdentity():void
{
if (log) log.send("glLoadIdentity")
currentMatrixStack[currentMatrixStack.length - 1].identity()
}
public function glOrtho(left:Number, right:Number, bottom:Number, top:Number, zNear:Number, zFar:Number):void
{
if (log) log.send("glOrtho: left = " + left + ", right = " + right + ", bottom = " + bottom + ", top = " + top + ", zNear = " + zNear + ", zFar = " + zFar)
var tx:Number = - (right + left) / (right - left)
var ty:Number = - (top + bottom) / (top - bottom)
var tz:Number = - (zFar + zNear) / (zFar - zNear)
// in column-major order...
var m:Matrix3D = new Matrix3D( new <Number>[
2 / (right - left), 0, 0, 0,
0, 2 / (top - bottom), 0, 0,
0, 0, - 2 / ( zFar - zNear), 0,
tx, ty, tz, 1]
)
// Multiply current matrix by the ortho matrix
currentMatrixStack[currentMatrixStack.length - 1].prepend(m)
}
public function glTranslate(x:Number, y:Number, z:Number):void
{
if (log) log.send("glTranslate")
currentMatrixStack[currentMatrixStack.length - 1].prependTranslation(x, y, z)
}
public function glRotate(degrees:Number, x:Number, y:Number, z:Number):void
{
if (log) log.send("glRotate")
currentMatrixStack[currentMatrixStack.length - 1].prependRotation(degrees, new Vector3D(x, y, z))
}
public function glScale(x:Number, y:Number, z:Number):void
{
if (log) log.send("glScale")
if (x != 0 && y != 0 && z != 0)
currentMatrixStack[currentMatrixStack.length - 1].prependScale(x, y, z)
}
public function glMultMatrix(ram:ByteArray, floatArray:Boolean):void
{
if (log) log.send("glMultMatrix floatArray: " + floatArray.toString())
var v:Vector.<Number> = new Vector.<Number>(16)
for (var i:int; i < 16; i++)
v[i] = floatArray ? ram.readFloat() : ram.readDouble()
var m:Matrix3D = new Matrix3D(v)
currentMatrixStack[currentMatrixStack.length - 1].prepend(m)
}
public function multMatrix(m:Matrix3D):void
{
currentMatrixStack[currentMatrixStack.length - 1].prepend(m)
}
public function glLoadMatrix(ram:ByteArray, floatArray:Boolean):void
{
if (log) log.send("glLoadMatrix floatArray: " + floatArray.toString())
var v:Vector.<Number> = new Vector.<Number>(16)
for (var i:int; i < 16; i++)
v[i] = floatArray ? ram.readFloat() : ram.readDouble()
var m:Matrix3D = new Matrix3D(v)
currentMatrixStack[currentMatrixStack.length - 1] = m
}
public function glDepthMask(enable:Boolean):void
{
if (log) log.send("glDepthMask(" + enable + "), currently contextEnableDepth = " + contextEnableDepth)
contextDepthMask = enable
if (contextEnableDepth)
{
context.setDepthTest(contextDepthMask, contextDepthFunction)
}
}
public function glDepthFunc(mode:uint):void
{
if (log) log.send("glDepthFunc( " + COMPARE_MODE[mode - GL_NEVER] + " ), currently contextEnableDepth = " + contextEnableDepth)
contextDepthFunction = convertCompareMode(mode)
if (contextEnableDepth)
context.setDepthTest(contextDepthMask, contextDepthFunction)
}
private function convertCompareMode(mode:uint):String
{
switch (mode)
{
case GL_NEVER: return Context3DCompareMode.NEVER
case GL_LESS: return Context3DCompareMode.LESS
case GL_EQUAL: return Context3DCompareMode.EQUAL
case GL_LEQUAL: return Context3DCompareMode.LESS_EQUAL
case GL_GREATER: return Context3DCompareMode.GREATER
case GL_NOTEQUAL: return Context3DCompareMode.NOT_EQUAL
case GL_GEQUAL: return Context3DCompareMode.GREATER_EQUAL
case GL_ALWAYS: return Context3DCompareMode.ALWAYS
}
return null
}
private function texGenParamToString(param:uint):String
{
if (param < GL_NORMAL_MAP)
return GL_PARAM[param - GL_EYE_LINEAR]
else
return GL_PARAM[param - GL_NORMAL_MAP]
}
public function glTexGeni(coord:uint, pname:uint, param:uint):void
{
if (log) log.send("glTexGeni( " + GL_COORD_NAME[coord - GL_S] + ", " + GL_PARAM_NAME[pname - GL_TEXTURE_GEN_MODE] + ", " + texGenParamToString(param) + ")")
if (GL_T < coord)
{
if (log) log.send("Unsupported " + GL_COORD_NAME[coord - GL_S])
return
}
if (pname != GL_TEXTURE_GEN_MODE)
{
if (log) log.send("Unsupported " + GL_PARAM_NAME[pname - GL_TEXTURE_GEN_MODE])
return
}
switch (coord)
{
case GL_S:
texGenParamS = param
break
case GL_T:
texGenParamT = param
break
}
}
private function setupIndexBuffer(stream:VertexStream, mode:uint, count:int):void
{
var key:uint = ((mode << 20) | count)
var indexBuffer:IndexBuffer3D = sharedIndexBuffers[key]
if (!indexBuffer)
{
var indexData:Vector.<uint> = new Vector.<uint>()
generateDLIndexData(mode, count, indexData)
indexBuffer = context.createIndexBuffer(indexData.length)
indexBuffer.uploadFromVector(indexData, 0, indexData.length)
// Cache
sharedIndexBuffers[key] = indexBuffer
}
stream.indexBuffer = indexBuffer
}
private function generateDLIndexData(mode:uint, count:int, indexData:Vector.<uint>):void
{
var i:int
var p0:int
var p1:int
var p2:int
var p3:int
switch (mode)
{
case GL_QUADS:
// Assert count == n * 4, n >= 1
// for each group of 4 vertices 0, 1, 2, 3 draw two triangles 0, 1, 2 and 0, 2, 3
for (i = 0; i < count; i += 4)
{
indexData.push(i)
indexData.push(i + 1)
indexData.push(i + 2)
indexData.push(i)
indexData.push(i + 2)
indexData.push(i + 3)
}
break
case GL_QUAD_STRIP:
// Assert count == n * 2, n >= 2
// Draws a connected group of quadrilaterals. One quadrilateral is defined for each pair of vertices presented after the first pair.
// Vertices 2n - 2, 2n - 1, 2n + 1, 2n define a quadrilateral.
for (i = 0; i < count - 2; i += 2)
{
// The four corners of the quadrilateral are
p0 = i
p1 = i + 1
p2 = i + 2
p3 = i + 3
// Draw as two triangles 0, 1, 2 and 2, 1, 3
indexData.push(p0)
indexData.push(p1)
indexData.push(p2)
indexData.push(p2)
indexData.push(p1)
indexData.push(p3)
}
break
case GL_TRIANGLES:
for (i = 0; i <count; i++)
{
indexData.push(i)
}
break
case GL_TRIANGLE_STRIP:
for (i = 0; i < count - 2; i++)
{
p0 = i
p1 = i + 1
p2 = i + 2
indexData.push(p0)
if(i % 2 == 0) {
indexData.push(p1)
indexData.push(p2)
} else {
indexData.push(p2)
indexData.push(p1)
}
}
break
case GL_POLYGON:
case GL_TRIANGLE_FAN:
for (i = 0; i < count-2; i++)
{
p0 = i + 1
p1 = i + 2
indexData.push(0)
indexData.push(p0)
indexData.push(p1)
}
break
default:
if (log) log.send("Not yet implemented mode for glBegin " + BEGIN_MODE[mode])
for (i = 0; i <count; i++)
{
indexData.push(i)
}
}
}
public function glGenBuffers(count:uint, dataPtr:uint):void
{
if(count != 1)
throw "unimplemented"
vertexBufferObjects.push(null); // will be created for real by glBufferData
CModule.write32(dataPtr, vertexBufferObjects.length - 1);
}
public function glBufferData(target:uint, size:uint, dataPtr:uint, usage:uint):void
{