-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathApus.Engine.ResManGL.pas
1747 lines (1611 loc) · 51.7 KB
/
Apus.Engine.ResManGL.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
// OpenGL-based texture classes and texture manager
//
// Copyright (C) 2011 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/)
unit Apus.Engine.ResManGL;
interface
uses Apus.Engine.API, Apus.Images, Apus.Common, Types, Apus.Engine.Resources, SyncObjs;
{$IFDEF IOS} {$DEFINE GLES} {$DEFINE GLES11} {$DEFINE OPENGL} {$ENDIF}
{$IFDEF ANDROID} {$DEFINE GLES} {$DEFINE GLES20} {$DEFINE OPENGL} {$ENDIF}
type
// Текстура OpenGL
TGLTexture=class(TTexture)
const
MAX_LEVEL = 5; // maximal number of supported mip level [0..MAX_LEVEL]
var
texname:cardinal;
realWidth,realHeight:integer; // real dimensions of underlying texture object (can be larger than requested)
filter:TTexFilter;
constructor Create;
procedure Clear(color:cardinal=$808080); override;
destructor Destroy; override;
procedure ClearPart(mipLevel:byte;x,y,width,height:integer;color:cardinal); override;
procedure CloneFrom(src:TTexture); override;
procedure SetAsRenderTarget; virtual;
procedure Lock(miplevel:byte=0;mode:TlockMode=lmReadWrite;r:PRect=nil); override; // 0-й уровень - самый верхний
procedure AddDirtyRect(rect:TRect;level:integer); override;
procedure Unlock; override;
function GetRawImage:TRawImage; override; // Создать RAW image и назначить его на верхний уровень текстуры (только когда текстура залочна!!!)
function Describe:string;
procedure SetFilter(filter:TTexFilter); override;
procedure Dump(filename:string8=''); override;
function GetLayer(layer:integer):TTexture; override;
procedure LockLayer(index:integer;miplevel:byte=0;mode:TLockMode=lmReadWrite;r:PRect=nil); override;
// Direct upload - destroys internal storage
procedure Upload(pixelData:pointer;pitch:integer;pixelFormat:TImagePixelFormat); override;
procedure Upload(mipLevel:byte;pixelData:pointer;pitch:integer;pixelFormat:TImagePixelFormat); override;
procedure UploadPart(mipLevel:byte;x,y,width,height:integer;pixelData:pointer;pitch:integer;pixelFormat:TImagePixelFormat); override;
protected
type
TUploadRequest=record
data:pointer;
pitch:integer;
mipLevel:integer;
pf:TImagePixelFormat;
x,y,width,height:integer;
end;
var
cs:TCriticalSection;
online:boolean; // true when image data is uploaded and ready to use (uv's are valid), false when local image data was modified and should be uploaded
realData:array[0..MAX_LEVEL] of ByteArray; // internal storage of texture data
fbo:cardinal; // framebuffer object (for a render target texture)
rbo:cardinal; // renderbuffer object - for a render target texture with a depth buffer attached (but not for depth buffer textures)
// Define area of the internal storage which is recently updated and need to be uploaded
dirty:array[0..MAX_LEVEL,0..15] of TRect;
dCount:array[0..MAX_LEVEL] of integer; // per each mip level
// Which levels of internal storage are obsolete
realDataObsolete:array[0..MAX_LEVEL] of boolean;
// upload request
uploadRequest:TUploadRequest;
procedure SetLabel; // submit name as label for OpenGL
procedure UpdateFilter;
procedure InitStorage; virtual; // allocate GL texture object (if needed)
procedure UploadInternalData; virtual; // upload modified internal storage data (using dirty rects)
procedure FreeData; virtual;
procedure Bind; virtual;
function IsBound(stage:integer):boolean; virtual;
function GetTextureTarget:integer; virtual;
procedure InvalidateInternalLevel(mipLevel:integer); virtual;
// Download texture data into the internal storage
procedure DownloadLevel(mipLevel:integer); virtual;
procedure ProcessUploadRequest; virtual;
end;
TVertexBufferGL=class(TVertexBuffer)
procedure Upload(fromVertex,numVertices:integer;vertexData:pointer); override;
destructor Destroy; override;
procedure Resize(newCount:integer); override;
protected
buffer:cardinal;
usage:cardinal;
end;
TIndexBufferGL=class(TIndexBuffer)
procedure Upload(fromIndex,numIndices:integer;indexData:pointer); override;
destructor Destroy; override;
procedure Resize(newCount:integer); override;
protected
buffer:cardinal;
usage:cardinal;
end;
// Used for both 2D texture arrays and 3D textures
TGLTextureArray=class(TGLTexture)
constructor Create(numLayers:integer);
function GetLayer(layer:integer):TTexture; override;
procedure LockLayer(index:integer;miplevel:byte=0;mode:TLockMode=lmReadWrite;r:PRect=nil); override;
procedure Lock(miplevel:byte=0;mode:TLockMode=lmReadWrite;r:PRect=nil); overload; override; // treat mip level as array index for convenience
procedure AddDirtyRect(index:integer;rect:TRect); overload; virtual;
procedure Unlock; override;
procedure Dump(filename:string8=''); override;
protected
layers:array of TGLTexture; // fake texture objects used to
lockedLayer:integer;
procedure FreeData; override;
procedure UploadInternalData; override;
function GetTextureTarget:integer; override;
end;
TGLResourceManager=class(TInterfacedObject,IResourceManager)
maxTextureSize,maxRTsize,maxRBsize:integer;
constructor Create;
destructor Destroy; override;
function AllocImage(width,height:integer;PixFmt:TImagePixelFormat;
flags:cardinal;name:String8):TTexture; overload;
function AllocImage(width,height,mipLevels:integer;PixFmt:TImagePixelFormat;
flags:cardinal;name:String8):TTexture; overload;
procedure ResizeImage(var img:TTexture;newWidth,newHeight:integer);
function Clone(img:TTexture):TTexture;
function Copy(img:TTexture):TTexture;
procedure AttachDepthBuffer(tex:TTexture;dBuf:TTexture);
procedure FreeImage(var image:TTexture);
// Allocate texture array
function AllocArray(width,height:integer;PixFmt:TImagePixelFormat;
arraySize:integer;flags:cardinal;name:String8):TGLTextureArray;
procedure MakeOnline(img:TTexture;stage:integer=0);
procedure SetTexFilter(img:TTexture;filter:TTexFilter);
function QueryParams(width,height:integer;format:TImagePixelFormat;usage:integer):boolean;
// Вспомогательные функции (для отладки/получения инфы)
function GetStatus(line:byte):string; // Формирует строки статуса
// Создает дамп использования и распределения видеопамяти
procedure Dump(st:string='');
// Data buffers
function AllocVertexBuffer(layout:TVertexLayout;numVertices:integer;usage:TBufferUsage=buStatic):TVertexBuffer;
procedure UseVertexBuffer(vb:TVertexBuffer);
function AllocIndexBuffer(indCount:integer;elementSize:integer=2;usage:TBufferUsage=buStatic):TIndexBuffer;
procedure UseIndexBuffer(ib:TIndexBuffer);
procedure FreeBuffer(buf:TEngineBuffer);
protected
//CurTag:integer;
//data:TObject;
//texFilters:array[0..15] of TTexFilter;
procedure FreeVidMem; // Освободить некоторое кол-во видеопамяти
procedure FreeMetaTexSpace(n:integer); // Освободить некоторое пространство в указанной метатекстуре
procedure AllocRenderTarget(tex:TGLTexture;flags:cardinal);
end;
var
resourceManagerGL:TGLResourceManager;
// Load image from file (TGA or JPG), result is expected in given pixel format or source pixel format
// function LoadFromFile(filename:string;format:TImagePixelFormat=ipfNone):TDxManagedTexture;
implementation
uses Apus.CrossPlatform, Apus.EventMan, SysUtils, Apus.Structs, Apus.GfxFormats,
{$IFDEF MSWINDOWS}dglOpenGl{$ENDIF}
{$IFDEF LINUX}dglOpenGL{$ENDIF}
{$IFDEF IOS}gles11,glext{$ENDIF}
{$IFDEF ANDROID}gles20{$ENDIF}
;
{ Принцип работы: по возможности текстуры создаются как обычные
буферы данных в памяти. По вызову MakeOnline данные перебрасываются
в текстуры GL. Обычно это происходит непосредственно перед отрисовкой
(и в потоке отрисовки), т.о. избегаем проблем многопоточности.
}
const
{$IFDEF GLES11}
MAX_TEX_SIZE = 1024;
{$ELSE}
MAX_TEX_SIZE = 2048;
{$ENDIF}
var
mainThreadId:TThreadID;
cSect:TMyCriticalSection; // TODO: зачем? Нет глобальных данных, нуждающихся в защите
lastErrorTime:int64;
errorTr:integer;
activeTex:integer; // currently active texture unit
boundTex2D:array[0..15] of TTexture; // current texture bound
boundTex3D:array[0..15] of TTexture;
boundTex2D_Arr:array[0..15] of TTexture;
{$REGION UTILS}
function InMainThread:boolean; inline;
begin
result:=GetCurrentThreadID=mainThreadID;
end;
procedure ActiveTextureUnit(u:integer);
begin
ASSERT((u>=0) and (u<16));
glActiveTexture(GL_TEXTURE0+u);
activeTex:=u;
end;
procedure UnbindTex(tex:TTexture);
var
i:integer;
begin
for i:=0 to high(boundTex2D) do
if boundTex2D[i]=tex then boundTex2D[i]:=nil;
for i:=0 to high(boundTex3D) do
if boundTex3D[i]=tex then boundTex3D[i]:=nil;
for i:=0 to high(boundTex2D_Arr) do
if boundTex2D_Arr[i]=tex then boundTex2D_Arr[i]:=nil;
end;
var
saveActiveTex:GLInt=-1;
procedure SaveActiveTexture;
begin
ASSERT(saveActiveTex=-1);
glGetIntegerv(GL_ACTIVE_TEXTURE,@saveActiveTex);
if saveActiveTex<>GL_TEXTURE0+9 then ActiveTextureUnit(9);
end;
procedure RestoreActiveTexture;
begin
ASSERT(saveActiveTex<>-1);
if saveActiveTex<>GL_TEXTURE0+9 then ActiveTextureUnit(saveActiveTex-GL_TEXTURE0);
saveActiveTex:=-1;
end;
procedure CheckForGLError(msg:string); //inline;
var
error:cardinal;
t:int64;
begin
error:=glGetError;
if error<>GL_NO_ERROR then {try
t:=MyTickCount;
if t<lastErrorTime+1000 then inc(errorTr)
else errorTr:=0;
if errorTr<5 then begin
lastErrorTime:=t;
ForceLogMessage('GLI Error ('+msg+') '+inttostr(error)+' '+GetCallStack);
end else}
raise EError.Create('GLI Error ('+msg+') '+inttostr(error)+' '+GetCallStack);
{ except
end;}
end;
procedure GetGLformat(ipf:TImagePixelFormat;out format,dataType,internalFormat:cardinal);
begin
case ipf of
{$IFNDEF GLES}
ipf8Bit:begin
internalFormat:=4;
format:=GL_COLOR_INDEX;
dataType:=GL_UNSIGNED_BYTE;
end;
ipfRGB:begin
internalFormat:=GL_RGB8;
format:=GL_BGR;
dataType:=GL_UNSIGNED_BYTE;
end;
ipfARGB:begin
internalFormat:=GL_RGBA8;
format:=GL_BGRA;
dataType:=GL_UNSIGNED_BYTE;
end;
ipfXRGB:begin
internalFormat:=GL_RGB8;
format:=GL_BGRA;
dataType:=GL_UNSIGNED_BYTE;
end;
ipfMono8:begin
internalFormat:=GL_R8;
format:=GL_RED;
dataType:=GL_UNSIGNED_BYTE;
end;
ipfMono8u:begin
internalFormat:=GL_R8UI;
format:=GL_RED_INTEGER;
dataType:=GL_UNSIGNED_BYTE;
end;
ipfMono16:begin
internalFormat:=GL_R16;
format:=GL_RED;
dataType:=GL_UNSIGNED_SHORT;
end;
ipfMono16s:begin
internalFormat:=GL_R16_SNORM;
format:=GL_RED;
dataType:=GL_SHORT;
end;
ipfMono16i:begin
internalFormat:=GL_R16I;
format:=GL_RED_INTEGER;
dataType:=GL_SHORT;
end;
ipfMono32f:begin
internalFormat:=GL_R32F;
format:=GL_RED;
dataType:=GL_FLOAT;
end;
ipfDuo32f:begin
internalFormat:=GL_RG32F;
format:=GL_RG;
dataType:=GL_FLOAT;
end;
ipfQuad32f:begin
internalFormat:=GL_RGBA32F;
format:=GL_RGBA;
dataType:=GL_FLOAT;
end;
ipfDuo8:begin
internalFormat:=GL_RG8;
format:=GL_RG;
dataType:=GL_UNSIGNED_BYTE;
end;
ipf565:begin
internalFormat:=GL_RGB5;
format:=GL_RGB;
dataType:=GL_UNSIGNED_SHORT_5_6_5;
end;
ipf1555:begin
internalFormat:=GL_RGB5_A1;
format:=GL_RGBA;
dataType:=GL_UNSIGNED_SHORT_5_5_5_1;
end;
ipf4444:begin
internalFormat:=GL_RGBA4;
format:=GL_RGBA;
dataType:=GL_UNSIGNED_SHORT_4_4_4_4_REV;
end;
ipf4444r:begin
internalFormat:=GL_RGBA4;
format:=GL_RGBA;
dataType:=GL_UNSIGNED_SHORT_4_4_4_4;
end;
ipfDXT1:begin
internalFormat:=GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
format:=GL_COMPRESSED_TEXTURE_FORMATS;
end;
ipfDXT3:begin
internalFormat:=GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
format:=GL_COMPRESSED_TEXTURE_FORMATS;
end;
ipfDXT5:begin
internalFormat:=GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
format:=GL_COMPRESSED_TEXTURE_FORMATS;
end;
ipfA4:begin
internalFormat:=GL_ALPHA4;
format:=GL_ALPHA;
dataType:=GL_UNSIGNED_BYTE;
end;
ipfL4A4:begin
internalFormat:=GL_LUMINANCE4_ALPHA4;
format:=GL_LUMINANCE_ALPHA;
dataType:=GL_UNSIGNED_BYTE;
end;
ipfA8:begin
internalFormat:=GL_ALPHA8;
format:=GL_ALPHA;
dataType:=GL_UNSIGNED_BYTE;
end;
ipfDepth32f:begin
internalFormat:=GL_DEPTH_COMPONENT;
format:=GL_DEPTH_COMPONENT;
dataType:=GL_FLOAT;
end;
{$ENDIF}
{$IFDEF GLES}
ipfARGB:begin
if pos('TEXTURE_FORMAT_BGRA8888',GLES_Extensions)>0 then begin
internalFormat:=GL_BGRA;
format:=GL_BGRA;
end else begin
internalFormat:=GL_RGBA;
format:=GL_RGBA;
end;
subFormat:=GL_UNSIGNED_BYTE;
end;
ipfRGB:begin
internalFormat:=GL_RGB;
format:=GL_RGB;
subFormat:=GL_UNSIGNED_BYTE;
end;
ipf565:begin
internalFormat:=GL_RGB;
format:=GL_RGB;
subFormat:=GL_UNSIGNED_SHORT_5_6_5;
end;
ipf1555:begin
internalFormat:=GL_RGBA;
format:=GL_RGBA;
subFormat:=GL_UNSIGNED_SHORT_5_5_5_1;
end;
{$IFDEF IOS}
ipf4444:begin
internalFormat:=GL_RGBA;
format:=GL_RGBA;
subFormat:=GL_UNSIGNED_SHORT_4_4_4_4_REV;
end;
{$ENDIF}
ipf4444r:begin
internalFormat:=GL_RGBA;
format:=GL_RGBA;
subFormat:=GL_UNSIGNED_SHORT_4_4_4_4;
end;
ipfPVRTC:begin
internalFormat:=GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
format:=GL_COMPRESSED_TEXTURE_FORMATS;
end;
ipfA8:begin
internalFormat:=GL_ALPHA;
format:=GL_ALPHA;
subFormat:=GL_UNSIGNED_BYTE;
end;
{$ENDIF}
else
raise EError.Create('Unsupported pixel format: '+PixFmt2Str(ipf));
end;
end;
{$ENDREGION}
{ TGLTextureArray }
{$REGION TextureArray}
procedure TGLTextureArray.AddDirtyRect(index:integer;rect:TRect);
begin
NotImplemented;
end;
constructor TGLTextureArray.Create(numLayers: integer);
var
i:integer;
begin
SetLength(layers,numLayers);
for i:=0 to numLayers-1 do
layers[i]:=TGLTexture.Create;
end;
procedure TGLTextureArray.Dump(filename:string8);
var
layer,itemSize:integer;
texData,data:ByteArray;
image:TRawImage;
begin
if filename='' then filename:='tex_'+name+'_';
if texname=0 then begin
SaveFile(filename+'.tex','Not allocated');
exit;
end;
Bind;
itemSize:=width*height*4;
SetLength(texData,itemSize*length(layers));
glGetTexImage(GetTextureTarget,0,GL_BGRA,GL_UNSIGNED_INT_8_8_8_8_REV,@texData[0]);
image:=TBitmapImage.Create(width,height,ipfARGB);
for layer:=0 to high(layers) do begin
image.data:=@texData[itemSize*layer];
image.data:=@(layers[layer].realData[0,0]);
data:=SavePNG(image);
SaveFile(filename+inttostr(layer)+'.png',data);
end;
image.Free;
end;
procedure TGLTextureArray.FreeData;
begin
inherited;
end;
function TGLTextureArray.GetLayer(layer:integer):TTexture;
begin
ASSERT((layer>=0) and (layer<=high(layers)));
result:=layers[layer];
end;
function TGLTextureArray.GetTextureTarget:integer;
begin
if HasFlag(tfTexture) then
result:=GL_TEXTURE_3D
else
result:=GL_TEXTURE_2D_ARRAY;
end;
procedure TGLTextureArray.LockLayer(index:integer; miplevel:byte; mode:TlockMode; r:PRect);
begin
inc(locked);
layers[index].Lock(mipLevel,mode,r);
data:=layers[index].data;
pitch:=layers[index].pitch;
lockedLayer:=index;
online:=false;
SetFlag(caps,tfDirty);
end;
procedure TGLTextureArray.Lock(miplevel:byte=0;mode:TlockMode=lmReadWrite;r:PRect=nil);
begin
raise EError.Create('Use LockLayer instead');
end;
procedure TGLTextureArray.Unlock;
begin
layers[lockedLayer].Unlock;
dec(locked);
end;
procedure TGLTextureArray.UploadInternalData;
var
needInit:boolean;
format,subformat,internalFormat,error:cardinal;
i,bpp,z,depth,level:integer;
glTarget:integer;
begin
needInit:=false;
if locked>0 then raise EWarning.Create('MO for a locked texture: '+name);
if texname=0 then begin // allocate texture name
glGenTextures(1,@texname);
CheckForGLError('11');
Bind;
SetLabel;
CheckForGLError('12');
needInit:=true;
end;
// Upload texture data
glTarget:=GetTextureTarget;
GetGLFormat(PixelFormat,format,subFormat,internalFormat);
depth:=length(layers);
if format=GL_COMPRESSED_TEXTURE_FORMATS then begin
for z:=0 to depth-1 do
for level:=0 to MAX_LEVEL do
if length(realData[level])>0 then
glCompressedTexImage3D(glTarget,level,internalFormat,realwidth,realheight,depth,0,
length(layers[z].realData[level]),@realData[level,0]);
end else begin
{$IFNDEF GLES}
if needInit then begin // Specify texture size and pixel format
glTexImage3D(glTarget,0,internalFormat,realwidth,realheight,depth,0,
format,subFormat,nil);
CheckForGLError('13');
UpdateFilter;
end;
// Upload texture data
glPixelStorei(GL_UNPACK_ROW_LENGTH,realWidth);
CheckForGLError('14');
bpp:=pixelSize[pixelFormat] div 8;
for z:=0 to depth-1 do
with layers[z] do
for level:=0 to MAX_LEVEL do begin
for i:=0 to dCount[level]-1 do
with dirty[level,i] do
glTexSubImage3D(glTarget,level,Left,Top,z,right-left+1,bottom-top+1,1,
format,subFormat,@realData[level,(left+top*realWidth)*bpp]);
dCount[level]:=0;
end;
CheckForGLError('15');
{$ELSE}
// GLES doesn't support UNPACK_ROW_LENGTH so it's not possible to upload just a portion of
// the source texture data
NotSupported('');
{ for z:=0 to depth-1 do
with layers[z] do begin
if format=GL_RGBA then ConvertColors32(data,realwidth*realheight);
if format=GL_RGB then ConvertColors24(data,realwidth*realheight);
glTexImage3D(GL_TEXTURE_2D_ARRAY,0,internalFormat,realwidth,realheight,1,0,format,subFormat,data);
end;}
CheckForGLError('16');
{$ENDIF}
if HasFlag(tfAutoMipMap) and (GL_VERSION_3_0 or GL_ARB_framebuffer_object) then begin
glGenerateMipmap(glTarget);
end;
if HasFlag(tfClamped) then begin
glTexParameteri(glTarget,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
glTexParameteri(glTarget,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
end else begin
glTexParameteri(glTarget,GL_TEXTURE_WRAP_S,GL_REPEAT);
glTexParameteri(glTarget,GL_TEXTURE_WRAP_T,GL_REPEAT);
end;
CheckForGLError('17');
end;
online:=true;
ClearFlag(caps,tfDirty);
end;
{$ENDREGION}
{ TGLTexture }
{$REGION Texture}
procedure TGLTexture.Bind;
var
target:integer;
begin
target:=GetTextureTarget;
glBindTexture(target,texname);
CheckForGLError('211');
case target of
GL_TEXTURE_2D:boundTex2D[activeTex]:=self;
GL_TEXTURE_3D:boundTex3D[activeTex]:=self;
GL_TEXTURE_2D_ARRAY:boundTex2D_Arr[activeTex]:=self;
end;
end;
procedure TGLTexture.Clear(color:cardinal);
var
level:integer;
begin
if InMainThread and (@glClearTexImage<>nil) then begin
cs.Enter;
try
InitStorage;
// Clear directly
for level:=0 to mipmaps do
glClearTexImage(texName,level,GL_BGRA,GL_UNSIGNED_BYTE,@color);
CheckForGLError('191');
InvalidateInternalLevel(0);
finally
cs.Leave;
end;
end else begin
// Clear in the internal storage
Lock;
FillDword(realData[0][0],length(realData[0]) div 4,color);
Unlock;
end;
end;
procedure TGLTexture.ClearPart(mipLevel:byte;x,y,width,height:integer;color:cardinal);
var
yy:integer;
pb:PByte;
r:TRect;
begin
if (texName<>0) and InMainThread and (@glClearTexSubImage<>nil) then begin
// Upload remaining data if needed
UploadInternalData;
cs.Enter;
try
// Clear directly
glClearTexSubImage(texName,mipLevel,x,y,0,width,height,1,GL_BGRA,GL_UNSIGNED_BYTE,@color);
CheckForGLError('221');
InvalidateInternalLevel(mipLevel);
finally
cs.Leave;
end;
end else begin
// Clear in the internal storage
r:=Rect(x,y,x+width-1,y+width-1);
Lock(mipLevel,lmReadWrite,@r);
pb:=data;
inc(pb,y*pitch+x*4);
for yy:=y to y+height-1 do begin
FillDword(pb^,width,color);
inc(pb,pitch);
end;
Unlock;
end;
end;
procedure TGLTexture.CloneFrom(src:TTexture);
begin
inherited;
end;
constructor TGLTexture.Create;
begin
inherited;
cs:=TCriticalSection.Create;
end;
destructor TGLTexture.Destroy;
var
t:TTexture;
begin
if texName<>0 then begin
t:=self;
resourceManagerGL.FreeImage(t);
end else begin
if uploadrequest.data<>nil then begin
uploadrequest.data:=nil;
sleep(10);
end;
FreeAndNil(cs);
inherited;
end;
end;
function TGLTexture.Describe: string;
begin
if self is TGLTexture then
result:=Format('GLTexture(%8x):%s w=%d h=%d m=%d c=%x l=%d o=%d tn=%d fbo=%d dC=%d',
[cardinal(self),name,width,height,mipmaps,caps,byte(locked),byte(online),texname,fbo,dCount[0]])
else
result:='Not a GL Texture at: '+inttohex(cardinal(self),8);
end;
procedure TGLTexture.DownloadLevel(mipLevel:integer);
var
format,dataType,internal:cardinal;
begin
Bind;
GetGLformat(pixelFormat,format,dataType,internal);
glGetTexImage(GetTextureTarget,mipLevel,format,dataType,realData[mipLevel]);
CheckForGLError('DownL');
realDataObsolete[mipLevel]:=false;
dCount[mipLevel]:=0;
end;
procedure TGLTexture.Dump(filename:string8);
var
data:ByteArray;
image:TRawImage;
begin
if filename='' then filename:='tex'+name+'.png';
if texname=0 then begin
SaveFile(filename,'Not allocated');
exit;
end;
image:=TBitmapImage.Create(width,height,ipfARGB);
Bind;
glGetTexImage(GetTextureTarget,0,GL_BGRA,GL_UNSIGNED_INT_8_8_8_8,image.data);
data:=SavePNG(image);
image.Free;
SaveFile(filename,data);
end;
procedure TGLTexture.FreeData;
begin
end;
function TGLTexture.GetLayer(layer:integer):TTexture;
begin
result:=self;
end;
function TGLTexture.GetRawImage: TRawImage;
begin
result:=TRawImage.Create;
result.width:=width;
result.height:=height;
result.PixelFormat:=PixelFormat;
result.data:=data;
result.pitch:=pitch;
result.paletteFormat:=palNone;
result.palette:=nil;
result.palSize:=0;
end;
function TGLTexture.GetTextureTarget: integer;
begin
result:=GL_TEXTURE_2D;
end;
procedure TGLTexture.Lock(miplevel:byte=0;mode:TlockMode=lmReadWrite;r:PRect=nil);
var
size:integer;
lockRect:TRect;
begin
ASSERT(mipLevel<=MAX_LEVEL);
if HasFlag(tfNoRead) then
raise EWarning.Create('Can''t lock texture '+name+' for reading');
if HasFlag(tfNoWrite) and (mode<>lmReadOnly) then
raise EWarning.Create('Can''t lock texture '+name+' for writing');
cs.Enter;
if r=nil then lockRect:=Rect(0,0,(width-1) shr mipLevel,(height-1) shr mipLevel) // full rect
else lockRect:=r^;
if (mode=lmCustomUpdate) and (r<>nil) then
raise EWarning.Create('GLTex: for custom update must lock full surface');
mipmaps:=max2(mipmaps,mipLevel);
if length(realdata[mipLevel])=0 then begin // alloc internal storage
size:=max2(width shr mipLevel,1)*max2(height shr mipLevel,1); // number of texels
size:=size*pixelSize[pixelFormat] div 8;
SetLength(realdata[mipLevel],size);
if realDataObsolete[mipLevel] and (mode<>lmWriteOnly) then begin
ASSERT(InMainThread,'Trying to read modified texture data outside the main thread');
DownloadLevel(mipLevel);
end;
end;
pitch:=max2(width shr mipLevel,1)*pixelSize[pixelFormat] shr 3;
if r=nil then data:=@realData[mipLevel,0]
else data:=@realData[mipLevel,lockRect.left*PixelSize[pixelFormat] shr 3+lockRect.Top*pitch];
inc(locked);
if mode=lmReadWrite then begin
online:=false;
SetFlag(caps,tfDirty);
AddDirtyRect(lockRect,mipLevel);
end;
end;
procedure TGLTexture.Unlock;
begin
ASSERT(locked>0,'Texture not locked: '+name);
dec(locked);
cs.Leave;
end;
procedure TGLTexture.LockLayer(index:integer;miplevel:byte;mode:TLockMode;r:PRect);
begin
Lock(mipLevel,mode,r);
end;
procedure TGLTexture.ProcessUploadRequest;
begin
cs.Enter;
try
if uploadrequest.data=nil then exit;
Upload(uploadRequest.mipLevel,uploadRequest.data,uploadrequest.pitch,uploadRequest.pf);
ZeroMem(uploadRequest,sizeof(uploadRequest));
finally
cs.Leave;
end;
end;
procedure TGLTexture.AddDirtyRect(rect:TRect;level:integer);
var
n:integer;
begin
online:=false; SetFlag(caps,tfDirty);
n:=dCount[level];
if n<0 then exit;
if n<high(dirty[level]) then begin
dirty[level,n]:=rect;
inc(dCount[level]);
end else begin
// Too many rects - invalidate all
dCount[level]:=-1; // forbid any more rects
dirty[level,0]:=Types.Rect(0,0,width-1,height-1);
end;
end;
procedure TGLTexture.SetAsRenderTarget;
begin
Assert(HasFlag(tfRenderTarget));
{$IFDEF GLES11}
glBindFramebufferOES(GL_FRAMEBUFFER_OES,fbo);
{$ENDIF}
{$IFDEF GLES20}
glBindFramebuffer(GL_FRAMEBUFFER,fbo);
{$ENDIF}
{$IFNDEF GLES}
if GL_ARB_framebuffer_object then
glBindFramebuffer(GL_FRAMEBUFFER,fbo)
else if GL_EXT_framebuffer_object then
glBindFramebufferEXT(GL_FRAMEBUFFER,fbo)
else
raise EError.Create('SART: Render target not supported');
{$ENDIF}
CheckForGLError('SART:'+Describe);
end;
procedure TGLTexture.SetFilter(filter:TTexFilter);
begin
self.filter:=filter;
if texname<>0 then UpdateFilter;
end;
procedure TGLTexture.SetLabel;
var
lab:String8;
begin
if (name<>'') and (@glObjectLabel<>nil) then begin
lab:=name;
glObjectLabel(GL_TEXTURE,texname,length(lab),@lab[1]);
CheckForGLError('L01');
end;
end;
procedure TGLTexture.UpdateFilter;
var
fMin,fMax:integer;
target,aTex:GLInt;
begin
if texname=0 then exit;
case filter of
fltUndefined:exit;
fltNearest:begin
fMin:=GL_NEAREST;
fMax:=GL_NEAREST;
end;
fltBilinear:begin
if mipmaps>0 then begin
fMin:=GL_LINEAR_MIPMAP_NEAREST;
//fMin:=GL_LINEAR;
fMax:=GL_LINEAR;
end else begin
fMin:=GL_LINEAR;
fMax:=GL_LINEAR;
end;
end;
fltTrilinear:begin
if mipmaps>0 then begin
fMin:=GL_LINEAR_MIPMAP_LINEAR;
fMax:=GL_LINEAR;
end else begin
fMin:=GL_LINEAR;
fMax:=GL_LINEAR;
end;
end;
end;
if @glTextureParameteri<>nil then begin
// GL 4.5 mode
glTextureParameteri(texname,GL_TEXTURE_MIN_FILTER,fMin);
glTextureParameteri(texname,GL_TEXTURE_MAG_FILTER,fMax);
end else
if @glTextureParameteriEXT<>nil then begin
// EXT_direct_state_access mode
target:=GetTextureTarget;
glTextureParameteriEXT(texname,target,GL_TEXTURE_MIN_FILTER,fMin);
glTextureParameteriEXT(texname,target,GL_TEXTURE_MAG_FILTER,fMax);
end else begin
// 4.4- compatibility mode
target:=GetTextureTarget;
SaveActiveTexture;
Bind;
glTexParameteri(target,GL_TEXTURE_MIN_FILTER,fMin);
glTexParameteri(target,GL_TEXTURE_MAG_FILTER,fMax);
CheckForGLError('16');
RestoreActiveTexture;
end;
end;
procedure TGLTexture.Upload(pixelData:pointer;pitch:integer;pixelFormat:TImagePixelFormat);
begin
Upload(0,pixelData,pitch,pixelFormat);
end;
procedure TGLTexture.Upload(mipLevel:byte;pixelData:pointer;pitch:integer;pixelFormat:TImagePixelFormat);
var
format,subformat,internalFormat,error:cardinal;
bpp,y,lineSize:integer;
sp,dp:PByte;
begin
if not InMainThread then begin // upload request from non-main thread: sync
ASSERT(self.pixelFormat=pixelFormat);
repeat
cs.Enter;
if uploadRequest.data=nil then break;
cs.Leave;
sleep(0);
until false;
uploadRequest.pitch:=pitch;
uploadRequest.mipLevel:=mipLevel;
uploadRequest.pf:=pixelFormat;
uploadRequest.x:=0;
uploadRequest.y:=0;
uploadRequest.width:=0;
uploadRequest.height:=0;
uploadRequest.data:=pixelData;
cs.Leave;
Signal('GLImages\Upload',TTag(self));
// wait until request is complete
while uploadRequest.data<>nil do Sleep(0);
exit;
end;
// Direct upload
ASSERT(mipLevel<=MAX_LEVEL);
cs.Enter;
try
if mipLevel>mipmaps then mipMaps:=mipLevel;
if texName=0 then InitStorage;
Bind;
GetGLFormat(PixelFormat,format,subFormat,internalFormat);
bpp:=pixelSize[pixelFormat] div 8;
glPixelStorei(GL_UNPACK_ROW_LENGTH,pitch div bpp);
glTexImage2D(GL_TEXTURE_2D,mipLevel,internalFormat,
max2(realwidth shr mipLevel,1),max2(realheight shr mipLevel,1),0,format,subFormat,pixelData);
CheckForGLError('231');
online:=true; ClearFlag(caps,tfDirty);
InvalidateInternalLevel(mipLevel);
finally
cs.Leave;
end;
end;
procedure TGLTexture.UploadPart(mipLevel:byte;x,y,width,height:integer;pixelData:pointer;pitch:integer;pixelFormat:TImagePixelFormat);
var
format,subformat,internalFormat,error:cardinal;
bpp:integer;
begin
ASSERT(InMainThread,'Direct upload is available in the main thread only');
cs.Enter;
try
ASSERT(texName<>0,'Texture '+name+' must be initialized before partial update');
Bind;
GetGLFormat(PixelFormat,format,subFormat,internalFormat);
bpp:=pixelSize[pixelFormat] div 8;