-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathApus.Engine.PainterGL.pas
1164 lines (1061 loc) · 36.6 KB
/
Apus.Engine.PainterGL.pas
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
// Class for painting routines using OpenGL: fixed-function pipeline (1.4+, GLES 1.1)
// For programmable-function pipeline (GLES 2.0+) use PainterGL2!
//
// Copyright (C) 2011-2014 Ivan Polyacov, Apus Software ([email protected])
// This file is licensed under the terms of BSD-3 license (see license.txt)
// This file is a part of the Apus Game Engine (http://apus-software.com/engine/)
{$IFDEF IOS}{$DEFINE GLES} {$DEFINE GLES11} {$ENDIF}
{$IFDEF ANDROID}{$DEFINE GLES} {$DEFINE GLES20} {$ENDIF}
unit Apus.Engine.PainterGL;
interface
uses Types, Apus.Engine.API;
type
TMatrixType=(mtModelView,mtProjection);
TGLPainter=class(TBasicPainter)
constructor Create;
destructor Destroy; override;
// Setup render destination
procedure SetDefaultRenderArea(oX,oY,VPwidth,VPheight,renderWidth,renderHeight:integer); override;
procedure SetDefaultRenderTarget(rt:TTexture); override;
procedure Restore; override;
procedure RestoreClipping; override; // Установить параметры отсечения по текущему viewport'у
// Установка RenderTarget'а (потомки класса могут иметь дополнительные методы,характерные для конкретного 3D API, например D3D)
procedure ResetTarget; override; // Установить target в backbuffer
procedure SetTargetToTexture(tex:TTexture); override; // Установить target в указанную текстуру
procedure Clear(color:cardinal;zbuf:single=0;stencil:integer=-1); override;
{$IFNDEF GLES20}
procedure DrawMultiTex(x1,y1,x2,y2:integer; layers:PMultiTexLayer; color:cardinal); override;
// Режим работы
procedure SetTexMode(stage:byte;colorMode,alphaMode:TTexBlendingMode;filter:TTexFilter=fltUndefined;intFactor:single=0.0); override; // Режим текстурирования
procedure ResetTexMode; override; // возврат к стандартному режиму текстурирования (втч после использования своего шейдера)
{$ENDIF}
procedure SetMode(blend:TBlendingMode); override;
procedure SetMask(rgb:boolean;alpha:boolean); override;
procedure ResetMask; override; // вернуть маску на ту, которая была до предыдущего SetMask
procedure UseDepthBuffer(test:TDepthBufferTest;writeEnable:boolean=true); override;
// Set camera (view) matrix
procedure Set3DView(view:T3DMatrix); override;
// Set model matrix
procedure Set3DTransform(mat:T3DMatrix); override;
// Setup projection
procedure SetPerspective(xMin,xMax,yMin,yMax,zScreen,zMin,zMax:double); override;
procedure SetOrthographic(scale,zMin,zMax:double); override;
procedure SetDefaultView; override;
procedure UseTexture(tex:TTexture;stage:integer=0); override;
// Extended shader functionality
// attribNames='aName1,aName2,...aNameN' - attribute names bound to indices 0..n-1
function BuildShaderProgram(vSrc,fSrc:AnsiString;attribNames:AnsiString=''):integer;
// Set predefined shader for color transformation (nil - go back to default shader)
procedure SetColorTransform(const mat:T3DMatrix);
procedure ResetColorTransform;
protected
curstate:byte; // Текущий режим (0 - не установлен, 1 - StateTextured и т.д.)
// for texture stage 0:
curColorMode,curAlphaMode:array[0..3] of TTexBlendingMode;
curRGBScale:array[0..3] of integer;
curblend:TBlendingMode;
curFilters:array[0..3] of TTexFilter;
curTextures:array[0..3] of TTexture;
curmask:integer;
oldmask:array[0..15] of integer;
oldmaskpos:byte;
actualClip:TRect; // реальные границы отсечения на данный момент (в рабочем пространстве)
partBuf,txtBuf:array of TVertex;
partInd,bandInd:array of word;
// Text effect
txttex:TTexture;
chardrawer:integer;
outputPos:TPoint; // output area in the default render target (bottom-left corner, relative to bottom-left RT corner)
VPwidth,VPheight:integer; // viewport size for backbuffer
targetScaleX,targetScaleY:single; // VPwidth/renderWidth
defaultRenderTarget:TTexture; // Texture to render into
defaultFramebuffer:cardinal; // Default render target for OpenGL ES (GL resource)
colorMatrixShader:cardinal;
colorMatrixRed,colorMatrixGreen,colorMatrixBlue:cardinal;
procedure Initialize; virtual; // инициализация (после потери девайса)
// Установка вьюпорта (в координатах окна) и области отсечения
procedure SetupViewport; virtual;
{$IFNDEF GLES20}
function SetStates(state:byte;primRect:TRect;tex:TTexture=nil):boolean; override; // возвращает false если примитив полностью отсекается
procedure renderDevice.Draw(primType,primCount:integer;vertices:pointer;stride:integer); override;
procedure DrawPrimitivesMulti(primType,primCount:integer;vertices:pointer;stride:integer;stages:integer); override;
procedure DrawPrimitivesFromBuf(primType,primCount,vrtStart:integer;
vertexBuf:TPainterBuffer;stride:integer); override;
procedure DrawIndexedPrimitives(primType:integer;vertexBuf,indBuf:TPainterBuffer;
stride:integer;vrtStart,vrtCount:integer; indStart,primCount:integer); override;
procedure DrawIndexedPrimitivesDirectly(primType:integer;vertexBuf:PVertex;indBuf:PWord;
stride:integer;vrtStart,vrtCount:integer; indStart,primCount:integer); override;
{$ENDIF}
function LockBuffer(buf:TPainterBuffer;offset,size:cardinal):pointer; override;
procedure UnlockBuffer(buf:TPainterBuffer); override;
procedure ResetTextures; virtual;
procedure SetGLMatrix(mType:TMatrixType;mat:PDouble); virtual;
procedure SwitchToDefaultFramebuffer; virtual;
end;
var
glDebug:boolean = {$IFDEF MSWINDOWS} false {$ELSE} true {$ENDIF};
implementation
uses Apus.CrossPlatform, Apus.Common, Apus.Geom2D, Apus.Geom3D, SysUtils,
{$IFDEF GLES11}gles11,glext,{$ENDIF}
{$IFDEF GLES20}gles20,{$ENDIF}
{$IFNDEF GLES}dglOpenGl,{$ENDIF}
Apus.Images, Apus.Engine.GLImages;
type
TScrPoint8=record
x,y,z,rhw:single;
diffuse,specular:cardinal;
uv:array[0..7,0..1] of single;
end;
procedure CheckForGLError(lab:integer=0); inline;
var
error:cardinal;
begin
if glDebug then begin
error:=glGetError;
if error<>GL_NO_ERROR then begin
ForceLogMessage('PGL Error ('+inttostr(lab)+'): '+inttostr(error)+' '+GetCallStack);
end;
end;
end;
constructor TGLPainter.Create;
var
i:integer;
begin
try
// Adjust font cache
if game.screenWidth*game.screenHeight>2500000 then textCacheHeight:=max2(textCacheHeight,1024);
if game.screenWidth*game.screenHeight>3500000 then textCacheWidth:=max2(textCacheWidth,1024);
texman:=TGLTextureMan.Create;
inherited Create;
defaultRenderTarget:=nil;
Initialize;
textcolorx2:=false;
stackcnt:=0;
curmask:=$F;
canPaint:=0;
efftex:=nil;
txtTex:=nil;
efftex:=texman.AllocImage(256,32,ipfARGB,aiTexture,'effectTex') as TGLtexture;
txttex:=texman.AllocImage(1024,32,ipfARGB,aiTexture,'txtTex') as TGLtexture;
textCache:=texman.AllocImage(textCacheWidth,textCacheHeight,ipfA8,aiTexture,'textCache');
colorFormat:=1; // colors should be flipped
supportARGB:=true; // always supported
for i:=0 to 3 do begin
curColorMode[i]:=tblNone;
curAlphaMode[i]:=tblNone;
curRGBScale[i]:=0;
end;
viewMatrix:=IdentMatrix4;
objMatrix:=IdentMatrix4;
try
colorMatrixShader:=0;
colorMatrixShader:=BuildShaderProgram(vColorMatrix,fColorMatrix);
if colorMatrixShader>0 then begin
colorMatrixRed:=glGetUniformLocation(colorMatrixShader,'newRed');
colorMatrixGreen:=glGetUniformLocation(colorMatrixShader,'newGreen');
colorMatrixBlue:=glGetUniformLocation(colorMatrixShader,'newBlue');
end;
except
end;
except
on e:Exception do begin
ForceLogMessage('Error in GLPainter constructor: '+e.message);
raise EFatalError.Create('GLPainter: '+e.Message);
end;
end;
end;
destructor TGLPainter.Destroy;
begin
// Здесь надо бы освободить шрифты и всё такое прочее
LogMessage('Painter deleted');
inherited;
end;
function TGLPainter.BuildShaderProgram(vSrc,fSrc:AnsiString;attribNames:AnsiString=''):integer;
var
vsh,fsh:GLuint;
str:PAnsiChar;
i,len,res:integer;
prog:integer;
sa:AStringArr;
function GetShaderError(shader:GLuint):string;
var
maxlen:integer;
errorLog:PAnsiChar;
begin
glGetShaderiv(shader,GL_INFO_LOG_LENGTH,@maxlen);
errorLog:=AnsiStrAlloc(maxlen);
{$IFDEF GLES}
glGetShaderInfoLog(shader,maxLen,@maxLen,errorLog);
{$ELSE}
glGetShaderInfoLog(shader,maxLen,@maxLen,errorLog);
{$ENDIF}
glDeleteShader(shader);
result:=errorLog;
end;
begin
if not GL_VERSION_2_0 then begin
result:=0; exit;
end;
vsh:=glCreateShader(GL_VERTEX_SHADER);
str:=PAnsiChar(vSrc);
len:=length(vSrc);
glShaderSource(vsh,1,@str,@len);
glCompileShader(vsh);
glGetShaderiv(vsh,GL_COMPILE_STATUS,@res);
if res=0 then raise EError.Create('VShader compilation failed: '+GetShaderError(vsh));
// Fragment shader
fsh:=glCreateShader(GL_FRAGMENT_SHADER);
str:=PAnsiChar(fSrc);
len:=length(fSrc);
glShaderSource(fsh,1,@str,@len);
glCompileShader(fsh);
glGetShaderiv(fsh,GL_COMPILE_STATUS,@res);
if res=0 then raise EError.Create('FShader compilation failed: '+GetShaderError(fsh));
// Build program object
prog:=glCreateProgram;
glAttachShader(prog,vsh);
glAttachShader(prog,fsh);
if attribNames>'' then begin
sa:=splitA(',',attribNames);
for i:=0 to high(sa) do
glBindAttribLocation(prog,i,PAnsiChar(sa[i])); // Link attribute index i to attribute named sa[i]
end;
glLinkProgram(prog);
glGetProgramiv(prog,GL_LINK_STATUS,@res);
if res=0 then raise EError.Create('Shader program not linked!');
result:=prog;
end;
{$IFNDEF GLES20}
procedure TGLPainter.DrawIndexedPrimitives(primType: integer; vertexBuf,
indBuf: TPainterBuffer; stride:integer; vrtStart, vrtCount, indStart, primCount: integer);
var
vrt:PVertex;
ind:Pointer;
begin
case vertexBuf of
vertBuf:vrt:=@partBuf[0];
textVertBuf:vrt:=@txtBuf[0];
else raise EWarning.Create('DIP: Wrong vertbuf');
end;
case indBuf of
partIndBuf:ind:=@partind[indStart];
bandIndBuf:ind:=@bandInd[indStart];
else raise EWarning.Create('DIP: Wrong indbuf');
end;
glVertexPointer(3,GL_FLOAT,stride,@vrt.x);
glColorPointer(4,GL_UNSIGNED_BYTE,stride,@vrt.color);
glTexCoordPointer(2,GL_FLOAT,stride,@vrt.u);
case primtype of
LINE_LIST:glDrawElements(GL_LINES,primCount*2,GL_UNSIGNED_SHORT,ind);
LINE_STRIP:glDrawElements(GL_LINE_STRIP,primCount+1,GL_UNSIGNED_SHORT,ind);
TRG_LIST:glDrawElements(GL_TRIANGLES,primCount*3,GL_UNSIGNED_SHORT,ind);
TRG_FAN:glDrawElements(GL_TRIANGLE_FAN,primCount+2,GL_UNSIGNED_SHORT,ind);
TRG_STRIP:glDrawElements(GL_TRIANGLE_STRIP,primCount+2,GL_UNSIGNED_SHORT,ind);
end;
end;
procedure TGLPainter.DrawIndexedPrimitivesDirectly(primType: integer;
vertexBuf: PVertex; indBuf: PWord; stride, vrtStart, vrtCount, indStart,
primCount: integer);
begin
glVertexPointer(3,GL_FLOAT,stride,@vertexBuf.x);
glColorPointer(4,GL_UNSIGNED_BYTE,stride,@vertexBuf.color);
glTexCoordPointer(2,GL_FLOAT,stride,@vertexBuf.u);
case primtype of
LINE_LIST:glDrawElements(GL_LINES,primCount*2,GL_UNSIGNED_SHORT,indBuf);
LINE_STRIP:glDrawElements(GL_LINE_STRIP,primCount+1,GL_UNSIGNED_SHORT,indBuf);
TRG_LIST:glDrawElements(GL_TRIANGLES,primCount*3,GL_UNSIGNED_SHORT,indBuf);
TRG_FAN:glDrawElements(GL_TRIANGLE_FAN,primCount+2,GL_UNSIGNED_SHORT,indBuf);
TRG_STRIP:glDrawElements(GL_TRIANGLE_STRIP,primCount+2,GL_UNSIGNED_SHORT,indBuf);
end;
end;
procedure TGLPainter.renderDevice.Draw(primType, primCount: integer;
vertices: pointer; stride: integer);
var
vrt:PVertex;
begin
vrt:=vertices;
glVertexPointer(3,GL_FLOAT,stride,@vrt.x);
glColorPointer(4,GL_UNSIGNED_BYTE,stride,@vrt.color);
glTexCoordPointer(2,GL_FLOAT,stride,@vrt.u);
case primtype of
LINE_LIST:glDrawArrays(GL_LINES,0,primCount*2);
LINE_STRIP:glDrawArrays(GL_LINE_STRIP,0,primCount+1);
TRG_LIST:glDrawArrays(GL_TRIANGLES,0,primCount*3);
TRG_FAN:glDrawArrays(GL_TRIANGLE_FAN,0,primCount+2);
TRG_STRIP:glDrawArrays(GL_TRIANGLE_STRIP,0,primCount+2);
end;
end;
procedure TGLPainter.DrawPrimitivesMulti(primType,primCount:integer;vertices:pointer;stride:integer;stages:integer);
var
vrt:PScrPoint3;
i:integer;
begin
vrt:=vertices;
glVertexPointer(3,GL_FLOAT,stride,@vrt.x);
glColorPointer(4,GL_UNSIGNED_BYTE,stride,@vrt.color);
glTexCoordPointer(2,GL_FLOAT,stride,@vrt.u);
// Texture 2
if stages>1 then begin
glClientActiveTexture(GL_TEXTURE1);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2,GL_FLOAT,stride,@vrt.u2);
end;
if stages>2 then begin
glClientActiveTexture(GL_TEXTURE2);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2,GL_FLOAT,stride,@vrt.u3);
end;
case primtype of
LINE_LIST:glDrawArrays(GL_LINES,0,primCount*2);
LINE_STRIP:glDrawArrays(GL_LINE_STRIP,0,primCount+1);
TRG_LIST:glDrawArrays(GL_TRIANGLES,0,primCount*3);
TRG_FAN:glDrawArrays(GL_TRIANGLE_FAN,0,primCount+2);
TRG_STRIP:glDrawArrays(GL_TRIANGLE_STRIP,0,primCount+2);
end;
for i:=1 to stages-1 do begin
glClientActiveTexture(GL_TEXTURE0+i);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
end;
glClientActiveTexture(GL_TEXTURE0);
end;
procedure TGLPainter.DrawPrimitivesFromBuf(primType, primCount,
vrtStart: integer; vertexBuf: TPainterBuffer; stride:integer);
var
vrt:PVertex;
begin
case vertexBuf of
vertBuf:vrt:=@partBuf[0];
textVertBuf:vrt:=@txtBuf[0];
end;
glVertexPointer(3,GL_FLOAT,stride,@vrt.x);
glColorPointer(4,GL_UNSIGNED_BYTE,stride,@vrt.color);
glTexCoordPointer(2,GL_FLOAT,stride,@vrt.u);
case primtype of
LINE_LIST:glDrawArrays(GL_LINES,vrtStart,primCount*2);
LINE_STRIP:glDrawArrays(GL_LINE_STRIP,vrtStart,primCount+1);
TRG_LIST:glDrawArrays(GL_TRIANGLES,vrtStart,primCount*3);
TRG_FAN:glDrawArrays(GL_TRIANGLE_FAN,vrtStart,primCount+2);
TRG_STRIP:glDrawArrays(GL_TRIANGLE_STRIP,vrtStart,primCount+2);
end;
end;
procedure TGLPainter.DrawMultiTex(x1, y1, x2, y2: integer; layers:PMultiTexLayer; color: cardinal);
var
vrt:array[0..3] of TScrPoint8;
lr:array[0..7] of TMultiTexLayer;
i,lMax:integer;
// cnt:integer;
// ïåðåâåñòè ìàòðèöó èç ïîëíîãî ìàñøòàáà ê ìàñøòàáó èçîáðàæåíèÿ â ìåòàòåêñòóðå
procedure AdjustMatrix(const texture:TTexture;var matrix:TMatrix32s);
var
sx,sy,dx,dy:single;
i:integer;
begin
with texture do begin
sx:=u2-u1; sy:=v2-v1;
dx:=u1; dy:=v1;
end;
for i:=0 to 2 do begin
matrix[i,0]:=matrix[i,0]*sx;
matrix[i,1]:=matrix[i,1]*sy;
end;
matrix[2,0]:=matrix[2,0]+dx;
matrix[2,1]:=matrix[2,1]+dy;
end;
begin
if not SetStates(1,types.Rect(x1,y1,x2+1,y2+1)) then exit;
// Copy layers data to modify later
for i:=0 to High(lr) do begin
lMax:=i;
lr[i]:=layers^;
layers:=layers.next;
if layers=nil then break;
end;
// fillchar(vrt,sizeof(vrt),0);
with vrt[0] do begin
x:=x1-0.5; y:=y1-0.5; z:=0; rhw:=1; diffuse:=color;
for i:=0 to lMax do begin
uv[i,0]:=0; uv[i,1]:=0;
end;
end;
with vrt[1] do begin
x:=x2+0.5; y:=y1-0.5; z:=0; rhw:=1; diffuse:=color;
for i:=0 to lMax do begin
uv[i,0]:=1; uv[i,1]:=0;
end;
end;
with vrt[2] do begin
x:=x2+0.5; y:=y2+0.5; z:=0; rhw:=1; diffuse:=color;
for i:=0 to lMax do begin
uv[i,0]:=1; uv[i,1]:=1;
end;
end;
with vrt[3] do begin
x:=x1-0.5; y:=y2+0.5; z:=0; rhw:=1; diffuse:=color;
for i:=0 to lMax do begin
uv[i,0]:=0; uv[i,1]:=1;
end;
end;
for i:=0 to lMax do
with lr[i] do begin
if texture=nil then break;
UseTexture(texture,i);
if texture.caps and tfTexture=0 then AdjustMatrix(texture,matrix);
MultPnts(matrix,PPoint2s(@vrt[0].uv[i,0]),4,sizeof(TScrPoint8));
MultPnts(matrix,PPoint2s(@vrt[0].uv[i,1]),4,sizeof(TScrPoint8));
if i>0 then begin
glClientActiveTexture(GL_TEXTURE0+i);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
end;
glTexCoordPointer(2,GL_FLOAT,sizeof(TScrPoint8),@vrt[0].uv[i]);
end;
glClientActiveTexture(GL_TEXTURE0);
glVertexPointer(3,GL_FLOAT,sizeof(TScrPoint3),@vrt);
glColorPointer(4,GL_UNSIGNED_BYTE,sizeof(TScrPoint3),@vrt[0].color);
// glTexCoordPointer(2,GL_FLOAT,sizeof(TScrPoint3),@vrt[0].u);
glDrawArrays(GL_TRIANGLE_FAN,0,4);
for i:=1 to lMax do begin
glClientActiveTexture(GL_TEXTURE0+i);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
end;
// Вообще-то это должен делать вызывающий код
glActiveTexture(GL_TEXTURE1);
glDisable(GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE0);
glClientActiveTexture(GL_TEXTURE0);
end;
procedure TGLPainter.SetTexMode;
var
scale:integer;
color:array[0..3] of single;
begin
if (stage=0) and (filter<>fltUndefined) then curFilters[0]:=filter;
if (stage>0) or (colorMode<>tblNone) or (alphaMode<>tblNone) then begin
glActiveTexture(GL_TEXTURE0+stage);
if stage>0 then
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
if colorMode<>curColorMode[stage] then
if colorMode<>tblDisable then begin
glEnable(GL_TEXTURE_2D);
end else
glDisable(GL_TEXTURE_2D);
if filter<>fltUndefined then curFilters[stage]:=filter;
if colorMode<>curColorMode[stage] then begin
case colorMode of
tblKeep:begin
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_REPLACE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_PREVIOUS);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR);
scale:=1;
end;
tblReplace:begin
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_REPLACE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_TEXTURE);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR);
scale:=1;
end;
tblModulate:begin
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE); // функция - умножение (Arg0 * Arg1)
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_PREVIOUS); // Указывает что Arg0 берётся из предыдущей стадии
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR); // Указывает какие именно данные берутся в качестве Arg0
glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_TEXTURE);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR);
scale:=1;
end;
tblModulate2X:begin
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_PREVIOUS);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_TEXTURE);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR);
scale:=2;
end;
tblAdd:begin
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_ADD);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_PREVIOUS);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_TEXTURE);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR);
scale:=1;
end;
tblInterpolate:begin
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_PREVIOUS);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_TEXTURE);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR);
scale:=1;
end;
else scale:=1;
end;
curColorMode[stage]:=colorMode;
if scale<>curRGBScale[stage] then begin
glTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE, scale);
curRGBScale[stage]:=scale;
end;
end;
if alphaMode<>curAlphaMode[stage] then
case alphaMode of
tblKeep:begin
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_PREVIOUS);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA);
end;
tblReplace:begin
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_TEXTURE);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA);
end;
tblModulate:begin
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_MODULATE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_PREVIOUS);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_ALPHA, GL_TEXTURE);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA, GL_SRC_ALPHA);
end;
tblModulate2X:begin
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_MODULATE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_PREVIOUS);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_ALPHA, GL_TEXTURE);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA, GL_SRC_ALPHA);
end;
tblAdd:begin
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_ADD);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_PREVIOUS);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_ALPHA, GL_TEXTURE);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA, GL_SRC_ALPHA);
end;
tblInterpolate:begin
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_INTERPOLATE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_PREVIOUS);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_ALPHA, GL_TEXTURE);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA, GL_SRC_ALPHA);
end;
end;
// Interpolation mode set and factor changed?
if (alphaMode=tblInterpolate) or (colorMode=tblInterpolate) then
if (intFactor<>texIntFactor[stage]) then begin
color[0]:=intFactor; color[1]:=intFactor; color[2]:=intFactor; color[3]:=intFactor;
glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, @color);
texIntFactor[stage]:=intFactor;
end;
glActiveTexture(GL_TEXTURE0);
end;
curAlphaMode[stage]:=alphaMode;
end;
function TGLPainter.SetStates(state:byte;primRect:TRect;tex:TTexture=nil):boolean;
var
f1,f2:byte;
r:TRect;
op:TPoint;
begin
f1:=IntersectRects(primRect,clipRect,r);
if f1=0 then begin
result:=false;
exit;
end else result:=true;
if tex<>nil then begin
if (state=STATE_TEXTURED2X) and
(tex.PixelFormat in [ipfA8,ipfA4]) then state:=STATE_COLORED2X; // override color blending mode for alpha only textures
end;
if curstate<>state then begin
ASSERT(state in [0..4]);
case state of
STATE_TEXTURED2X,STATE_MULTITEX:begin
//SetTexMode(0,tblModulate2X,tblModulate,fltBilinear);
case curstate of
STATE_COLORED:glEnable(GL_TEXTURE_2D); // Colored -> Textured
STATE_MULTITEX:UseTexture(nil,1); // Multitex->SingleTex: Disable multi-texturing
end;
SetTexMode(0,tblModulate2X,tblModulate,fltBilinear);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
end;
STATE_COLORED:begin
SetTexMode(0,tblKeep,tblKeep,fltUndefined);
// glTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE, 1);
glDisable(GL_TEXTURE_2D);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
// SetTexMode(0,tblKeep,tblKeep,fltUndefined);
curTextures[0]:=nil;
end;
STATE_COLORED2X:begin
if curState=STATE_COLORED then
glEnable(GL_TEXTURE_2D);
SetTexMode(0,tblKeep,tblModulate,fltBilinear);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
end;
end;
curstate:=state;
end;
if not EqualRect(clipRect,actualClip) then begin
f2:=IntersectRects(primRect,actualClip,r);
if (f1<>f2) or (f1>1) then begin
if curtarget=defaultRenderTarget then begin
if curtarget=nil then op:=outputPos else op:=Point(0,0);
glScissor(oP.x+round(clipRect.Left*targetScaleX),
oP.Y+round((screenRect.Bottom-clipRect.Bottom)*targetScaleY),
round((clipRect.Right-clipRect.left)*targetScaleX),
round((clipRect.Bottom-clipRect.Top)*targetScaleY));
end else
glScissor(clipRect.Left,
clipRect.Top,
clipRect.Right-clipRect.left,
clipRect.Bottom-clipRect.Top);
actualClip:=ClipRect;
end;
end;
end;
{$ENDIF}
procedure TGLPainter.SetMode;
begin
if blend=curblend then exit;
case blend of
blNone:begin
glDisable(GL_BLEND);
end;
blAlpha:begin
glEnable(GL_BLEND);
if GL_VERSION_2_0 then
glBlendFuncSeparate(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA)
else
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
end;
blAdd:begin
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE);
end;
blSub:begin
raise EError.Create('blSub not supported');
end;
blModulate:begin
glEnable(GL_BLEND);
glBlendFuncSeparate(GL_ZERO,GL_SRC_COLOR,GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
end;
blModulate2X:begin
glEnable(GL_BLEND);
glBlendFuncSeparate(GL_DST_COLOR,GL_SRC_COLOR,GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
end;
blMove:begin
glEnable(GL_BLEND);
glBlendFunc(GL_ONE,GL_ZERO);
end
else
raise EWarning.Create('Blending mode not supported');
end;
curblend:=blend;
CheckForGLError(31);
end;
procedure TGLPainter.SetupViewport;
var
w,h:integer;
begin
SetDefaultView;
if curtarget<>nil then
glViewport(0,0,curTarget.width,curTarget.height)
else
glViewport(outputPos.X,outputPos.Y,VPwidth,VPheight);
CheckForGLError(1);
end;
procedure TGLPainter.Set3DView(view:T3DMatrix);
var
x,y,z:double;
begin
Invert4Full(view,viewMatrix);
Set3DTransform(objMatrix);
end;
procedure TGlPainter.SetGLMatrix(mType:TMatrixType;mat:PDouble);
begin
{$IFNDEF GLES20}
case mType of
mtModelView:glMatrixMode(GL_MODELVIEW);
mtProjection:glMatrixMode(GL_PROJECTION);
end;
if mat<>nil then glLoadMatrixd(PGLDouble(mat))
else glLoadIdentity;
CheckForGLError;
{$ENDIF}
end;
procedure TGLPainter.Set3DTransform(mat:T3DMatrix);
var
m:array[0..15] of double;
ms:T3DMatrix;
begin
objMatrix:=mat;
MultMat4(mat,viewMatrix,ms);
SetGLMatrix(mtModelView,@ms);
end;
procedure TGLPainter.SetDefaultRenderArea(oX, oY, VPwidth, VPheight,
renderWidth, renderHeight: integer);
begin
defaultRenderTarget:=nil;
outputPos:=Point(oX,oY);
outputPos:=Point(oX,oY);
self.renderWidth:=renderWidth;
self.renderHeight:=renderHeight;
self.VPwidth:=VPwidth;
self.VPheight:=VPheight;
ResetTarget;
end;
procedure TGLPainter.SetDefaultRenderTarget(rt: TTexture);
begin
defaultRenderTarget:=rt;
end;
procedure TGLPainter.SetDefaultView;
var
w,h:integer;
begin
w:=screenRect.Right-screenRect.Left;
h:=screenRect.Bottom-screenRect.top;
if (w=0) and (h=0) then exit;
projMatrix[0,0]:=2/w; projMatrix[1,0]:=0; projMatrix[2,0]:=0; projMatrix[3,0]:=-1+1/w;
if (curtarget<>defaultRenderTarget) then begin
projMatrix[0,1]:=0; projMatrix[1,1]:=2/h; projMatrix[2,1]:=0; projMatrix[3,1]:=-(1-1/h);
end else begin
projMatrix[0,1]:=0; projMatrix[1,1]:=-2/h; projMatrix[2,1]:=0; projMatrix[3,1]:=1-1/h;
end;
projMatrix[0,2]:=0; projMatrix[1,2]:=0; projMatrix[2,2]:=-1; projMatrix[3,2]:=0;
projMatrix[0,3]:=0; projMatrix[1,3]:=0; projMatrix[2,3]:=0; projMatrix[3,3]:=1;
{ m[0]:=2/w; m[4]:=0; m[8]:=0; m[12]:=-1+1/w;
// в текстурах ось Y направлена сверху-вниз, а в defaultRT (даже если это тоже текстура) - снизу вверх
if (curtarget<>defaultRenderTarget) then begin
m[1]:=0; m[5]:=2/h; m[9]:=0; m[13]:=-(1-1/h);
end else begin
m[1]:=0; m[5]:=-2/h; m[9]:=0; m[13]:=1-1/h;
end;
m[2]:=0; m[6]:=0; m[10]:=-1; m[14]:=0;
m[3]:=0; m[7]:=0; m[11]:=0; m[15]:=1;}
viewMatrix:=IdentMatrix4;
objMatrix:=IdentMatrix4;
SetGLMatrix(mtProjection,@projMatrix);
SetGLMatrix(mtModelView,nil);
end;
procedure TGlPainter.SetOrthographic(scale,zMin,zMax:double);
var
w,h:integer;
begin
w:=(screenRect.Right-screenRect.Left);
h:=(screenRect.Bottom-screenRect.top);
projMatrix[0,0]:=scale*2/w; projMatrix[1,0]:=0; projMatrix[2,0]:=0; projMatrix[3,0]:=0;
if (curtarget<>defaultRenderTarget) then begin
projMatrix[0,1]:=0; projMatrix[1,1]:=scale*2/h; projMatrix[2,1]:=0; projMatrix[3,1]:=0;
end else begin
projMatrix[0,1]:=0; projMatrix[1,1]:=-scale*2/h; projMatrix[2,1]:=0; projMatrix[3,1]:=0;
end;
projMatrix[0,2]:=0; projMatrix[1,2]:=0; projMatrix[2,2]:=2/(zMax-zMin); projMatrix[3,2]:=-(zMax+zMin)/(zMax-zMin);
projMatrix[0,3]:=0; projMatrix[1,3]:=0; projMatrix[2,3]:=0; projMatrix[3,3]:=1;
SetGLMatrix(mtProjection,@projMatrix);
end;
procedure TGlPainter.SetPerspective(xMin,xMax,yMin,yMax,zScreen,zMin,zMax:double);
var
i:integer;
begin
inherited;
if curtarget=defaultRenderTarget then // нужно переворачивать ось Y если только не рисуем в текстуру
for i:=0 to 3 do
projMatrix[i,1]:=-projMatrix[i,1];
SetGLMatrix(mtProjection,@projMatrix);
end;
procedure TGlPainter.ResetColorTransform;
begin
glUseProgram(0);
end;
procedure TGLPainter.SetColorTransform(const mat:T3DMatrix);
begin
if colorMatrixShader=0 then exit;
glUseProgram(colorMatrixShader);
glUniform3f(colorMatrixRed, mat[0,0],mat[0,1],mat[0,2]);
glUniform3f(colorMatrixGreen,mat[1,0],mat[1,1],mat[1,2]);
glUniform3f(colorMatrixBlue, mat[2,0],mat[2,1],mat[2,2]);
end;
procedure TGLPainter.SetMask(rgb:boolean;alpha:boolean);
var
mask:integer;
begin
ASSERT(oldmaskpos<15);
mask:=0;
oldmask[oldmaskpos]:=curmask;
oldmaskpos:=(oldmaskpos+1) and 15;
// DebugMessage('SetMask -> '+inttostr(oldmaskpos));
if rgb then mask:=mask+7;
if alpha then mask:=mask+8;
if curmask<>mask then begin
{$IFDEF GLES}
glColorMask((mask and 4),
(mask and 2),
(mask and 1),
(mask and 8));
{$ELSE}
glColorMask((mask and 4)>0,
(mask and 2)>0,
(mask and 1)>0,
(mask and 8)>0);
{$ENDIF}
curmask:=mask;
end;
end;
procedure TGLPainter.ResetMask;
var
mask:integer;
begin
// DebugMessage('ResetMask -> '+inttostr(oldmaskpos));
ASSERT(oldmaskpos>0);
oldmaskpos:=(oldmaskpos-1) and 15;
mask:=oldmask[oldmaskpos];
if curmask<>mask then begin
{$IFDEF GLES}
glColorMask((mask and 4),
(mask and 2),
(mask and 1),
(mask and 8));
{$ELSE}
glColorMask((mask and 4)>0,
(mask and 2)>0,
(mask and 1)>0,
(mask and 8)>0);
{$ENDIF}
curmask:=mask;
end;
end;
procedure TGLPainter.Restore;
var
bl:TBlendingMode;
begin
bl:=curblend;
inc(curblend);
SetMode(bl);
CheckForGLError(10);
SetTexMode(0,tblNone,tblNone,fltUndefined);
CheckForGLError(11);
curmask:=-1;
curTextures[0]:=nil;
curTextures[1]:=nil;
curTextures[2]:=nil;
curTextures[3]:=nil;
curstate:=0;
RestoreClipping;
viewMatrix:=IdentMatrix4;
objMatrix:=IdentMatrix4;
end;
{$IFNDEF GLES20}
procedure TGLPainter.ResetTexMode;
begin
if GL_VERSION_2_0 then glUseProgram(0);
SetTexMode(0,tblModulate2X,tblModulate);
SetTexMode(1,tblDisable,tblDisable);
end;
{$ENDIF}
procedure TGLPainter.ResetTextures;
begin
with texman as TGLTextureMan do begin
MakeOnline(nil,0);
MakeOnline(nil,1);
MakeOnline(nil,2);
end;
end;
procedure TGLPainter.SwitchToDefaultFramebuffer;
begin
{$IFDEF GLES11}
glBindFramebufferOES(GL_FRAMEBUFFER_OES,defaultFramebuffer);
{$ENDIF}
{$IFDEF GLES20}
glBindFramebuffer(GL_FRAMEBUFFER,0);
{$ENDIF}
{$IFNDEF GLES}
if GL_ARB_framebuffer_object then
glBindFramebuffer(GL_DRAW_FRAMEBUFFER,0);
{$ENDIF}
CheckForGLError(3);
end;
procedure TGLPainter.ResetTarget;
var
stage:integer;
begin
try
stage:=0;
if defaultRenderTarget<>nil then begin
if curtarget<>defaultRenderTarget then
SetTargetToTexture(defaultRenderTarget);
CheckForGLError(4);
exit;
end;
stage:=1;
FlushTextCache;
//glFlush;
CheckForGLError(5);
stage:=2;
SwitchToDefaultFramebuffer;
curtarget:=nil;
stage:=3;
CheckForGLError(12);
RestoreClipping;
screenRect:=ActualClip;
clipRect:=ActualClip;
stage:=4;
SetupViewport;
stage:=5;
ResetTextures;
CheckForGLError(6);
except
on e:exception do ForceLogMessage('Error in ResetTarget '+inttostr(stage)+': '+ExceptionMsg(e));
end;
end;
procedure TGLPainter.SetTargetToTexture(tex: TTexture);