forked from pythonarcade/arcade
-
Notifications
You must be signed in to change notification settings - Fork 2
/
shader.py
1608 lines (1326 loc) · 59.2 KB
/
shader.py
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
"""Utilities for dealing with Shaders in OpenGL 3.3+.
"""
from ctypes import (
c_char, c_int, c_buffer,
c_char_p, c_void_p,
cast, POINTER, pointer, byref, sizeof,
create_string_buffer, string_at,
)
from collections import namedtuple
from pathlib import Path
import weakref
from typing import List, Tuple, Iterable, Dict, Optional, Union
from pyglet import gl
# Thank you Benjamin Moran for writing part of this code!
# https://bitbucket.org/HigashiNoKaze/pyglet/src/shaders/pyglet/graphics/shader.py
class ShaderException(Exception):
""" Exception class for shader-specific problems. """
pass
class Uniform:
"""A Program uniform"""
_uniform_getters = {
gl.GLint: gl.glGetUniformiv,
gl.GLfloat: gl.glGetUniformfv,
}
_uniform_setters = {
# uniform type: (gl_type, setter, length, count)
gl.GL_INT: (gl.GLint, gl.glUniform1iv, 1, 1),
gl.GL_INT_VEC2: (gl.GLint, gl.glUniform2iv, 2, 1),
gl.GL_INT_VEC3: (gl.GLint, gl.glUniform3iv, 3, 1),
gl.GL_INT_VEC4: (gl.GLint, gl.glUniform4iv, 4, 1),
gl.GL_FLOAT: (gl.GLfloat, gl.glUniform1fv, 1, 1),
gl.GL_FLOAT_VEC2: (gl.GLfloat, gl.glUniform2fv, 2, 1),
gl.GL_FLOAT_VEC3: (gl.GLfloat, gl.glUniform3fv, 3, 1),
gl.GL_FLOAT_VEC4: (gl.GLfloat, gl.glUniform4fv, 4, 1),
gl.GL_SAMPLER_2D: (gl.GLint, gl.glUniform1iv, 1, 1),
gl.GL_FLOAT_MAT2: (gl.GLfloat, gl.glUniformMatrix2fv, 4, 1),
gl.GL_FLOAT_MAT3: (gl.GLfloat, gl.glUniformMatrix3fv, 9, 1),
gl.GL_FLOAT_MAT4: (gl.GLfloat, gl.glUniformMatrix4fv, 16, 1),
# TODO: test/implement these:
# gl.GL_FLOAT_MAT2x3: glUniformMatrix2x3fv,
# gl.GL_FLOAT_MAT2x4: glUniformMatrix2x4fv,
#
# gl.GL_FLOAT_MAT3x2: glUniformMatrix3x2fv,
# gl.GL_FLOAT_MAT3x4: glUniformMatrix3x4fv,
#
# gl.GL_FLOAT_MAT4x2: glUniformMatrix4x2fv,
# gl.GL_FLOAT_MAT4x3: glUniformMatrix4x3fv,
}
__slots__ = '_program_id', '_location', '_name', '_data_type', '_array_length', 'getter', 'setter'
def __init__(self, program_id, location, name, data_type, array_length):
"""Create a Uniform
:param int location: The location of the uniform in the program
:param str name: Name of the uniform in the program
:param gl.GLenum data_type: The data type of the uniform (GL_FLOAT
"""
self._program_id = program_id
self._location = location
self._name = name
self._data_type = data_type
self._array_length = array_length
self._setup_getters_and_setters()
@property
def location(self) -> int:
"""The location of the uniform in the program"""
return self._location
@property
def name(self) -> str:
"""Name of the uniform"""
return self._name
@property
def array_length(self) -> int:
"""Length of the uniform array. If not an array 1 will be returned"""
return self._array_length
def _setup_getters_and_setters(self):
"""Maps the right getter and setter functions for this uniform"""
try:
gl_type, gl_setter, length, count = self._uniform_setters[self._data_type]
except KeyError:
raise ShaderException(f"Unsupported Uniform type: {self._data_type}")
gl_getter = self._uniform_getters[gl_type]
is_matrix = self._data_type in (gl.GL_FLOAT_MAT2, gl.GL_FLOAT_MAT3, gl.GL_FLOAT_MAT4)
# Create persistent mini c_array for getters and setters:
length = length * self._array_length # Increase buffer size to include arrays
c_array = (gl_type * length)()
ptr = cast(c_array, POINTER(gl_type))
# Create custom dedicated getters and setters for each uniform:
self.getter = Uniform._create_getter_func(self._program_id, self._location, gl_getter, c_array, length)
self.setter = Uniform._create_setter_func(self._location, gl_setter, c_array, length, count, ptr, is_matrix)
@staticmethod
def _create_getter_func(program_id, location, gl_getter, c_array, length):
""" Create a function for getting/setting OpenGL data. """
if length == 1:
def getter_func():
""" Get single-element OpenGL uniform data. """
gl_getter(program_id, location, c_array)
return c_array[0]
else:
def getter_func():
""" Get list of OpenGL uniform data. """
gl_getter(program_id, location, c_array)
return tuple(c_array)
return getter_func
@staticmethod
def _create_setter_func(location, gl_setter, c_array, length, count, ptr, is_matrix):
""" Create setters for OpenGL data. """
if is_matrix:
def setter_func(value): # type: ignore #conditional function variants must have identical signature
""" Set OpenGL matrix uniform data. """
c_array[:] = value
gl_setter(location, count, gl.GL_FALSE, ptr)
elif length == 1 and count == 1:
def setter_func(value): # type: ignore #conditional function variants must have identical signature
""" Set OpenGL uniform data value. """
c_array[0] = value
gl_setter(location, count, ptr)
elif length > 1 and count == 1:
def setter_func(values): # type: ignore #conditional function variants must have identical signature
""" Set list of OpenGL uniform data. """
c_array[:] = values
gl_setter(location, count, ptr)
else:
raise NotImplementedError("Uniform type not yet supported.")
return setter_func
def __repr__(self):
return f"<Uniform '{self._name}' loc={self._location} array_length={self._array_length}"
class Program:
"""Compiled and linked shader program.
Currently supports vertex, fragment and geometry shaders.
Transform feedback also supported when output attributes
names are passed in the varyings parameter.
Access Uniforms via the [] operator.
Example:
program['MyUniform'] = value
"""
__slots__ = '_ctx', '_glo', '_uniforms', '_out_attributes', '_geometry_info', '__weakref__'
def __init__(self,
ctx,
*,
vertex_shader: str,
fragment_shader: str = None,
geometry_shader: str = None,
out_attributes: List[str] = None):
"""Create a Program.
:param Context ctx: The context this program belongs to
:param str vertex_shader: vertex shader source
:param str fragment_shader: fragment shader source
:param str geometry_shader: geometry shader source
:param List[str] out_attributes: List of out attributes used in transform feedback.
"""
self._ctx = ctx
self._glo = glo = gl.glCreateProgram()
self._out_attributes = out_attributes or []
self._geometry_info = (0, 0, 0)
shaders = [(vertex_shader, gl.GL_VERTEX_SHADER)]
if fragment_shader:
shaders.append((fragment_shader, gl.GL_FRAGMENT_SHADER))
if geometry_shader:
shaders.append((geometry_shader, gl.GL_GEOMETRY_SHADER))
shaders_id = []
for shader_code, shader_type in shaders:
shader = Program.compile_shader(shader_code, shader_type)
gl.glAttachShader(self._glo, shader)
shaders_id.append(shader)
# For now we assume varyings can be set up if no fragment shader
if not fragment_shader:
self._setup_out_attributes()
Program.link(self._glo)
if geometry_shader:
geometry_in = gl.GLint()
geometry_out = gl.GLint()
geometry_vertices = gl.GLint()
gl.glGetProgramiv(self._glo, gl.GL_GEOMETRY_INPUT_TYPE, geometry_in);
gl.glGetProgramiv(self._glo, gl.GL_GEOMETRY_OUTPUT_TYPE, geometry_out);
gl.glGetProgramiv(self._glo, gl.GL_GEOMETRY_VERTICES_OUT, geometry_vertices);
self._geometry_info = (geometry_in.value, geometry_out.value, geometry_vertices.value)
# Flag shaders for deletion. Will only be deleted once detached from program.
for shader in shaders_id:
gl.glDeleteShader(shader)
# Handle uniforms
self._uniforms: Dict[str, Uniform] = {}
self._introspect_uniforms()
weakref.finalize(self, Program._delete, shaders_id, glo)
@property
def ctx(self) -> 'Context':
"""The context this program belongs to"""
return self._ctx
@property
def glo(self) -> int:
"""The OpenGL resource id for this program"""
return self._glo
@property
def out_attributes(self) -> List[str]:
"""Out attributes names used in transform feedback"""
return self._out_attributes
@property
def geometry_input(self) -> int:
"""The geometry shader's input primitive type.
This an be compared with ``GL_TRIANGLES``, ``GL_POINTS`` etc.
"""
return self._geometry_info[0]
@property
def geometry_output(self) -> int:
"""The geometry shader's output primitive type.
This an be compared with ``GL_TRIANGLES``, ``GL_POINTS`` etc.
"""
return self._geometry_info[1]
@property
def geometry_vertices(self) -> int:
"""The maximum number of vertices that can be emitted"""
return self._geometry_info[2]
@staticmethod
def _delete(shaders_id, prog_id):
# Check to see if the context was already cleaned up from program
# shut down. If so, we don't need to delete the shaders.
if gl.current_context is None:
return
for shader_id in shaders_id:
gl.glDetachShader(prog_id, shader_id)
gl.glDeleteProgram(prog_id)
def __getitem__(self, item):
try:
uniform = self._uniforms[item]
except KeyError:
raise ShaderException(f"Uniform with the name `{item}` was not found.")
return uniform.getter()
def __setitem__(self, key, value):
# Ensure we are setting the uniform on this program
if self._ctx.active_program != self:
self.use()
try:
uniform = self._uniforms[key]
except KeyError:
raise ShaderException(f"Uniform with the name `{key}` was not found.")
uniform.setter(value)
def use(self):
"""Activates the shader"""
# IMPORTANT: This is the only place glUseProgram should be called
# so we can track active program.
if self._ctx.active_program != self:
gl.glUseProgram(self._glo)
self._ctx.active_program = self
def _setup_out_attributes(self):
"""Set up transform feedback varyings"""
if not self._out_attributes:
return
# Covert names to char**
c_array = (c_char_p * len(self._out_attributes))()
for i, name in enumerate(self._out_attributes):
c_array[i] = name.encode()
ptr = cast(c_array, POINTER(POINTER(c_char)))
# NOTE: We only support interleaved attributes for now
gl.glTransformFeedbackVaryings(
self._glo, # program
len(self._out_attributes), # number of varying variables used for transform feedback
ptr, # zero-terminated strings specifying the names of the varying variables
gl.GL_INTERLEAVED_ATTRIBS,
)
def _introspect_uniforms(self):
"""Figure out what uniforms are available and build an internal map"""
# Number of active uniforms in the program
active_uniforms = gl.GLint(0)
gl.glGetProgramiv(self._glo, gl.GL_ACTIVE_UNIFORMS, byref(active_uniforms))
# Loop all the active uniforms
for index in range(active_uniforms.value):
# Query uniform information like name, type, size etc.
u_name, u_type, u_size = self._query_uniform(index)
u_location = gl.glGetUniformLocation(self._glo, u_name.encode())
# Skip uniforms that may be in Uniform Blocks
# TODO: We should handle all uniforms
if u_location == -1:
print(f"Uniform {u_location} {u_name} {u_size} {u_type} skipped")
continue
u_name = u_name.replace('[0]', '') # Remove array suffix
self._uniforms[u_name] = Uniform(self._glo, u_location, u_name, u_type, u_size)
def _query_uniform(self, location: int) -> Tuple[str, int, int]:
"""Retrieve Uniform information at given location.
Returns the name, the type as a GLenum (GL_FLOAT, ...) and the size. Size is
greater than 1 only for Uniform arrays, like an array of floats or an array
of Matrices.
"""
usize = gl.GLint()
utype = gl.GLenum()
buf_size = 192 # max uniform character length
uname = create_string_buffer(buf_size)
gl.glGetActiveUniform(
self._glo, # program to query
location, # location to query
buf_size, # size of the character/name buffer
None, # the number of characters actually written by OpenGL in the string
usize, # size of the uniform variable
utype, # data type of the uniform variable
uname # string buffer for storing the name
)
return uname.value.decode(), utype.value, usize.value
@staticmethod
def compile_shader(source: str, shader_type: gl.GLenum) -> gl.GLuint:
"""Compile the shader code of the given type.
`shader_type` could be GL_VERTEX_SHADER, GL_FRAGMENT_SHADER, ...
Returns the shader id as a GLuint
"""
shader = gl.glCreateShader(shader_type)
source_bytes = source.encode('utf-8')
# Turn the source code string into an array of c_char_p arrays.
strings = byref(
cast(
c_char_p(source_bytes),
POINTER(c_char)
)
)
# Make an array with the strings lengths
lengths = pointer(c_int(len(source_bytes)))
gl.glShaderSource(shader, 1, strings, lengths)
gl.glCompileShader(shader)
result = c_int()
gl.glGetShaderiv(shader, gl.GL_COMPILE_STATUS, byref(result))
if result.value == gl.GL_FALSE:
msg = create_string_buffer(512)
length = c_int()
gl.glGetShaderInfoLog(shader, 512, byref(length), msg)
raise ShaderException(
f"Shader compile failure ({result.value}): {msg.value.decode('utf-8')}")
return shader
@staticmethod
def link(glo):
gl.glLinkProgram(glo)
status = c_int()
gl.glGetProgramiv(glo, gl.GL_LINK_STATUS, status)
if not status.value:
length = c_int()
gl.glGetProgramiv(glo, gl.GL_INFO_LOG_LENGTH, length)
log = c_buffer(length.value)
gl.glGetProgramInfoLog(glo, len(log), None, log)
raise ShaderException('Program link error: {}'.format(log.value.decode()))
def __repr__(self):
return "<Program id={}>".format(self._glo)
class Buffer:
"""OpenGL Buffer object. Buffers store byte data and upload it
to graphics memory. They are used for storage og vertex data,
element data (vertex indexing), uniform buffer data etc.
Common bind targets are: ``GL_ARRAY_BUFFER``, ``GL_ELEMENT_ARRAY_BUFFER``,
``GL_UNIFORM_BUFFER``, ``GL_SHADER_STORAGE_BUFFER``
It doesn't matter what bind target the buffer has on creation. What
matters is how we bind it in rendering calls.
"""
__slots__ = '_ctx', '_glo', '_size', '_usage', '__weakref__'
usages = {
'static': gl.GL_STATIC_DRAW,
'dynamic': gl.GL_DYNAMIC_DRAW,
'stream': gl.GL_STREAM_DRAW
}
def __init__(self, ctx, data: bytes = None, reserve: int = 0, usage: str = 'static'):
self._ctx = ctx
self._glo = glo = gl.GLuint()
self._size = -1
self._usage = Buffer.usages[usage]
gl.glGenBuffers(1, byref(self._glo))
# print(f"glGenBuffers() -> {self._glo.value}")
if self._glo.value == 0:
raise ShaderException("Cannot create Buffer object.")
# print(f"glBindBuffer({self._glo.value})")
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._glo)
# print(f"glBufferData(gl.GL_ARRAY_BUFFER, {self._size}, data, {self._usage})")
if data and len(data) > 0:
self._size = len(data)
gl.glBufferData(gl.GL_ARRAY_BUFFER, self._size, data, self._usage)
elif reserve > 0:
self._size = reserve
gl.glBufferData(gl.GL_ARRAY_BUFFER, self._size, None, self._usage)
else:
raise ValueError("Buffer takes byte data or number of reserved bytes")
weakref.finalize(self, Buffer.release, glo)
@property
def size(self) -> int:
"""The byte size of the buffer"""
return self._size
@property
def ctx(self) -> 'Context':
"""The context this resource belongs to"""
return self._ctx
@property
def glo(self) -> gl.GLuint:
"""The OpenGL resource id"""
return self._glo
@staticmethod
def release(glo: gl.GLuint):
""" Release/delete open gl buffer. """
# print(f"*** Buffer {glo} have no more references. Deleting.")
# If we have no context, then we are shutting down, so skip this
if gl.current_context is None:
return
if glo.value != 0:
gl.glDeleteBuffers(1, byref(glo))
glo.value = 0
def read(self, size=-1, offset=0) -> bytes:
"""Read data from the buffer.
:param int size: The bytes to read. -1 means the entire buffer
:param int offset: Byte read offset
"""
if size == -1:
size = self._size
# Catch this before confusing INVALID_OPERATION is raised
if size < 1:
raise ValueError("Attempting to read 0 or less bytes from buffer")
# Manually detect this so it doesn't raise a confusing INVALID_VALUE error
if size + offset > self._size:
raise ValueError(
(
"Attempting to read outside the buffer. "
f"Buffer size: {self._size} "
f"Reading from {offset} to {size + offset}"
)
)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._glo)
ptr = gl.glMapBufferRange(gl.GL_ARRAY_BUFFER, offset, size, gl.GL_MAP_READ_BIT)
data = string_at(ptr, size=size)
gl.glUnmapBuffer(gl.GL_ARRAY_BUFFER)
return data
def write(self, data: bytes, offset: int = 0):
"""Write byte data to the buffer.
:param bytes data: The byte data to write
:param int offset: The byte offset
"""
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._glo)
gl.glBufferSubData(gl.GL_ARRAY_BUFFER, gl.GLintptr(offset), len(data), data)
def copy_from_buffer(self, source: 'Buffer', size=-1, offset=0, source_offset=0):
"""Copy data into this buffer from another buffer
:param Buffer source: The buffer to copy from
:param int size: The amount of bytes to copy
:param int offset: The byte offset to write the data in this buffer
:param int source_offset: The byte offset to read from the source buffer
"""
# Read the entire source buffer into this buffer
if size == -1:
size = source.size
# TODO: Check buffer bounds
if size + source_offset > source.size:
raise ValueError("Attempting to read outside the source buffer")
if size + offset > self._size:
raise ValueError("Attempting to write outside the buffer")
gl.glBindBuffer(gl.GL_COPY_READ_BUFFER, source.glo)
gl.glBindBuffer(gl.GL_COPY_WRITE_BUFFER, self._glo)
gl.glCopyBufferSubData(
gl.GL_COPY_READ_BUFFER,
gl.GL_COPY_WRITE_BUFFER,
gl.GLintptr(source_offset), # readOffset
gl.GLintptr(offset), # writeOffset
size # size (number of bytes to copy)
)
def orphan(self, size=-1):
"""
Re-allocate the entire buffer memory.
If the current buffer is busy in redering operations
it will be deallocated by OpenGL when completed.
:param int size: New size of buffer. -1 will retain the current size.
"""
if size > -1:
self._size = size
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._glo)
gl.glBufferData(gl.GL_ARRAY_BUFFER, self._size, None, self._usage)
class BufferDescription:
"""Vertex Buffer Object description, allowing easy use with VAOs.
This class provides a Buffer object with a description of its content, allowing
a VertexArray object to correctly enable its shader attributes with the
vertex Buffer object.
The formats is a string providing the number and type of each attribute. Currently
we only support f (float), i (integer) and B (unsigned byte).
`normalized` enumerates the attributes which must have their values normalized.
This is useful for instance for colors attributes given as unsigned byte and
normalized to floats with values between 0.0 and 1.0.
`instanced` allows this buffer to be used as instanced buffer. Each value will
be used once for the whole geometry. The geometry will be repeated a number of
times equal to the number of items in the Buffer.
"""
GL_TYPES_ENUM = {
'B': gl.GL_UNSIGNED_BYTE,
'f': gl.GL_FLOAT,
'i': gl.GL_INT,
}
GL_TYPES = {
'B': gl.GLubyte,
'f': gl.GLfloat,
'i': gl.GLint,
}
def __init__(self,
buff: Buffer,
formats: str,
attributes: Iterable[str],
normalized: Iterable[str] = None,
instanced: bool = False):
self.buffer = buff
self.attributes = list(attributes)
self.normalized = set() if normalized is None else set(normalized)
self.instanced = instanced
if self.normalized > set(self.attributes):
raise ShaderException("Normalized attribute not found in attributes.")
formats_list = formats.split(" ")
if len(formats_list) != len(self.attributes):
raise ShaderException(
f"Different lengths of formats ({len(formats_list)}) and "
f"attributes ({len(self.attributes)})"
)
self.formats: List[Tuple[int, int, int]] = []
for i, fmt in enumerate(formats_list):
sizechar, type_ = fmt
if sizechar not in '1234' or type_ not in 'fiB':
raise ShaderException("Wrong format {fmt}.")
size = int(sizechar)
gl_type_enum = BufferDescription.GL_TYPES_ENUM[type_]
gl_type = BufferDescription.GL_TYPES[type_]
attribsize = size * sizeof(gl_type)
self.formats.append((size, attribsize, gl_type_enum))
class VertexArray:
"""Vertex Array Object (VAO) is holding all the different OpenGL objects
together.
A VAO is the glue between a Shader program and buffers data.
Buffer information is provided through a list of tuples `content`
content = [
(buffer, 'format str', 'attrib1', 'attrib2', ...),
]
The first item is a Buffer object. Then comes a format string providing information
about the count and type of data in the buffer. Type can be `f` for floats or `i`
for integers. Count can be 1, 2, 3 or 4.
Finally comes the strings representing the attributes found in the shader.
Example:
Providing a buffer with data of interleaved positions (x, y) and colors
(r, g, b, a):
content = [(buffer, '2f 4f', 'in_pos', 'in_color')]
vao = VertexArray(...)
"""
__slots__ = '_ctx', '_program', '_glo', '_ibo', '_num_vertices', '__weakref__'
def __init__(self,
ctx,
prog: Program,
content: Iterable[BufferDescription],
index_buffer: Buffer = None):
self._ctx = ctx
self._program = prog
self._glo = glo = gl.GLuint()
self._num_vertices = -1
self._ibo = index_buffer
gl.glGenVertexArrays(1, byref(self._glo))
gl.glBindVertexArray(self._glo)
for buffer_desc in content:
self._enable_attrib(buffer_desc)
if self._ibo is not None:
gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self._ibo.glo)
weakref.finalize(self, VertexArray.release, glo)
@property
def ctx(self) -> 'Context':
"""The Context this object belongs to"""
return self._ctx
@property
def glo(self) -> gl.GLuint:
"""The OpenGL resource id"""
return self._glo
@property
def program(self) -> Program:
"""The assigned program"""
return self._program
@property
def ibo(self) -> Optional[Buffer]:
"""Element/index buffer"""
return self._ibo
@property
def num_vertices(self) -> int:
"""The number of vertices"""
return self._num_vertices
@staticmethod
def release(glo: gl.GLuint):
"""Delete the object"""
# If we have no context, then we are shutting down, so skip this
if gl.current_context is None:
return
if glo.value != 0:
gl.glDeleteVertexArrays(1, byref(glo))
glo.value = 0
def _enable_attrib(self, buf_desc: BufferDescription):
buff = buf_desc.buffer
stride = sum(attribsize for _, attribsize, _ in buf_desc.formats)
if buf_desc.instanced:
if self._num_vertices == -1:
raise ShaderException(
"The first vertex attribute cannot be a per instance attribute."
)
else:
self._num_vertices = max(self._num_vertices, buff.size // stride)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buff.glo)
offset = 0
for (size, attribsize, gl_type_enum), attrib in zip(buf_desc.formats, buf_desc.attributes):
loc = gl.glGetAttribLocation(self._program.glo, attrib.encode())
if loc == -1:
raise ShaderException(f"Attribute {attrib} not found in shader program")
normalized = gl.GL_TRUE if attrib in buf_desc.normalized else gl.GL_FALSE
gl.glVertexAttribPointer(
loc, size, gl_type_enum,
normalized, stride, c_void_p(offset)
)
if buf_desc.instanced:
gl.glVertexAttribDivisor(loc, 1)
offset += attribsize
gl.glEnableVertexAttribArray(loc)
def render(self, mode: gl.GLuint, instances: int = 1):
"""Render the VertexArray to the currently active framebuffer.
:param GLunit mode: Primitive type to render. TRIANGLES, LINES etc.
:param int instances: OpenGL instance, used in using vertexes over and over
"""
gl.glBindVertexArray(self._glo)
self._program.use()
if self._ibo is not None:
count = self._ibo.size // 4
gl.glDrawElementsInstanced(mode, count, gl.GL_UNSIGNED_INT, None, instances)
else:
gl.glDrawArraysInstanced(mode, 0, self.num_vertices, instances)
class Texture:
"""
Class that represents an OpenGL texture.
"""
__slots__ = (
'_ctx', '_glo', '_width', '_height', '_dtype', '_target', '_components',
'_format', '_internal_format', '_type', '_component_size', '_samples', '_filter', '_wrap_x', '_wrap_y', '__weakref__',
)
_float_base_format = (0, gl.GL_RED, gl.GL_RG, gl.GL_RGB, gl.GL_RGBA)
_int_base_format = (0, gl.GL_RED_INTEGER, gl.GL_RG_INTEGER, gl.GL_RGB_INTEGER, gl.GL_RGBA_INTEGER)
# format: (base_format, internal_format, type, size)
_formats = {
# float formats
'f1': (_float_base_format, (0, gl.GL_R8, gl.GL_RG8, gl.GL_RGB8, gl.GL_RGBA8), gl.GL_UNSIGNED_BYTE, 1),
'f2': (_float_base_format, (0, gl.GL_R16F, gl.GL_RG16F, gl.GL_RGB16F, gl.GL_RGBA16F), gl.GL_HALF_FLOAT, 2),
'f4': (_float_base_format, (0, gl.GL_R32F, gl.GL_RG32F, gl.GL_RGB32F, gl.GL_RGBA32F), gl.GL_FLOAT, 4),
# int formats
'i1': (_int_base_format, (0, gl.GL_R8UI, gl.GL_RG8UI, gl.GL_RGB8UI, gl.GL_RGBA8UI), gl.GL_UNSIGNED_BYTE, 1),
'i2': (_int_base_format, (0, gl.GL_R16UI, gl.GL_RG16UI, gl.GL_RGB16UI, gl.GL_RGBA16UI), gl.GL_UNSIGNED_SHORT, 2),
'i4': (_int_base_format, (0, gl.GL_R32UI, gl.GL_RG32UI, gl.GL_RGB32UI, gl.GL_RGBA32UI), gl.GL_UNSIGNED_INT, 4),
# uint formats
'u1': (_int_base_format, (0, gl.GL_R8UI, gl.GL_RG8UI, gl.GL_RGB8UI, gl.GL_RGBA8UI), gl.GL_BYTE, 1),
'u2': (_int_base_format, (0, gl.GL_R16UI, gl.GL_RG16UI, gl.GL_RGB16UI, gl.GL_RGBA16UI), gl.GL_SHORT, 2),
'u4': (_int_base_format, (0, gl.GL_R32UI, gl.GL_RG32UI, gl.GL_RGB32UI, gl.GL_RGBA32UI), gl.GL_INT, 4),
}
def __init__(self,
ctx: 'Context',
size: Tuple[int, int],
*,
components: int = 4,
dtype: str = 'f1',
data: bytes = None,
filter: Tuple[gl.GLuint, gl.GLuint] = None,
wrap_x: gl.GLuint = None,
wrap_y: gl.GLuint = None):
"""Represents an OpenGL texture.
A texture can be created with or without initial data.
NOTE: Currently does not support multisample textures even
thought ``samples`` is exposed.
:param Context ctx: The context the object belongs to
:param Tuple[int, int] size: The size of the texture
:param int components: The number of components (1: R, 2: RG, 3: RGB, 4: RGBA)
:param str dtype: The data type of each component: f1, f2, f4 / i1, i2, i4 / u1, u2, u4
:param bytes data: The byte data to initialize the texture with
:param Tuple[gl.GLuint, gl.GLuint] filter: The minification/magnification filter of the texture
:param gl.GLuint wrap_s
:param data: The texture data (optional)
"""
self._ctx = ctx
self._width, self._height = size
self._dtype = dtype
self._components = components
self._target = gl.GL_TEXTURE_2D
self._samples = 0
# These are the default states in OpenGL
self._filter = gl.GL_LINEAR, gl.GL_LINEAR
self._wrap_x = gl.GL_REPEAT
self._wrap_y = gl.GL_REPEAT
if components not in [1, 2, 3, 4]:
raise ValueError("Components must be 1, 2, 3 or 4")
try:
format_info = self._formats[self._dtype]
except KeyError:
raise ValueError(f"dype '{dtype}' not support. Supported types are : {tuple(self._formats.keys())}")
gl.glActiveTexture(gl.GL_TEXTURE0) # Create textures in the default channel (0)
self._glo = glo = gl.GLuint()
gl.glGenTextures(1, byref(self._glo))
if self._glo.value == 0:
raise ShaderException("Cannot create Texture. OpenGL failed to generate a texture id")
gl.glBindTexture(self._target, self._glo)
gl.glPixelStorei(gl.GL_PACK_ALIGNMENT, 1)
gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1)
try:
_format, _internal_format, self._type, self._component_size = format_info
self._format = _format[components]
self._internal_format = _internal_format[components]
gl.glTexImage2D(
self._target, # target
0, # level
self._internal_format, # internal_format
self._width, # width
self._height, # height
0, # border
self._format, # format
self._type, # type
data # data
)
except gl.GLException as ex:
raise gl.GLException((
f"Unable to create texture: {ex} : dtype={dtype} size={size} components={components} "
"GL_MAX_TEXTURE_SIZE = {gl.GL_MAX_TEXTURE_SIZE}"
))
self.filter = filter or self._filter
self.wrap_x = wrap_x or self._wrap_x
self.wrap_y = wrap_y or self._wrap_y
weakref.finalize(self, Texture.release, glo)
@property
def ctx(self) -> 'Context':
"""The context this texture belongs to"""
return self._ctx
@property
def glo(self) -> gl.GLuint:
"""The OpenGL texture id"""
return self._glo
@property
def width(self) -> int:
"""The width of the texture in pixels"""
return self._width
@property
def height(self) -> int:
"""The height of the texture in pixels"""
return self._height
@property
def dtype(self) -> str:
"""The data type of each component"""
return self._dtype
@property
def size(self) -> Tuple[int, int]:
"""The size of the texture as a tuple"""
return self._width, self._height
@property
def components(self) -> int:
"""Number of components in the texture"""
return self._components
@property
def filter(self) -> Tuple[int, int]:
"""The (min, mag) filter for this texture.
Default value is ``GL_LINEAR, GL_LINEAR``.
Can be set to ``GL_NEAREST, GL_NEAREST`` for pixelated graphics.
When mipmapping is used the min filter needs to be `GL_*_MIPMAP_*`.
Also see:
* https://www.khronos.org/opengl/wiki/Texture#Mip_maps
* https://www.khronos.org/opengl/wiki/Sampler_Object#Filtering
"""
return self._filter
@filter.setter
def filter(self, value):
if not isinstance(value, tuple) or not len(value) == 2:
raise ValueError("Texture filter must be a 2 component tuple (min, mag)")
self._filter = value
self.use()
gl.glTexParameteri(self._target, gl.GL_TEXTURE_MIN_FILTER, self._filter[0])
gl.glTexParameteri(self._target, gl.GL_TEXTURE_MAG_FILTER, self._filter[1])
@property
def wrap_x(self):
"""
The horizontal wrapping of the texture. This decides how textures
are read when texture coordinates are outside the [0.0, 1.0] area.
Valid options are: ``GL_REPEAT``, ``GL_MIRRORED_REPEAT``, ``GL_CLAMP_TO_EDGE``, ``GL_CLAMP_TO_BORDER``
"""
return self._wrap_x
@wrap_x.setter
def wrap_x(self, value):
self._wrap_x = value
self.use()
gl.glTexParameteri(self._target, gl.GL_TEXTURE_WRAP_S, value)
@property
def wrap_y(self):
"""
The horizontal wrapping of the texture. This decides how textures
are read when texture coordinates are outside the [0.0, 1.0] area.
Valid options are: ``GL_REPEAT``, ``GL_MIRRORED_REPEAT``, ``GL_CLAMP_TO_EDGE``, ``GL_CLAMP_TO_BORDER``
"""
return self._wrap_y
@wrap_y.setter
def wrap_y(self, value):
self._wrap_y = value
self.use()
gl.glTexParameteri(self._target, gl.GL_TEXTURE_WRAP_T, value)
def read(self, level: int = 0, alignment: int = 1) -> bytearray:
"""
Read the contents of the texture.
"""
gl.glActiveTexture(gl.GL_TEXTURE0)
gl.glBindTexture(self._target, self._glo)
gl.glPixelStorei(gl.GL_PACK_ALIGNMENT, 1)
gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1)
buffer = (gl.GLubyte * (self.width * self.height * self._component_size))()
gl.glGetTexImage(gl.GL_TEXTURE_2D, 0, self._format, self._type, buffer)
return bytearray(buffer)
def write(self, data: Union[bytes, Buffer], level: int = 0, viewport=None):
"""Write byte data to the texture
:param Union[bytes, Buffer] data: bytes or a Buffer with data to write
:param int level: The texture level to write
:param tuple viewport: The are of the texture to write. 2 or 4 component tuple
"""
# TODO: Support writing to layers using viewport + alignment
if self._samples > 0:
raise ValueError("Writing to multisample textures not supported")
x, y, w, h = 0, 0, self._width, self._height
if viewport:
if len(viewport) == 2:
w, h = viewport
elif len(viewport) == 4:
x, y, w, h = viewport
else:
raise ValueError("Viewport must be of length 2 or 4")
if isinstance(data, bytes):
gl.glActiveTexture(gl.GL_TEXTURE0)
gl.glBindTexture(self._target, self._glo)
gl.glPixelStorei(gl.GL_PACK_ALIGNMENT, 1)
gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1)
gl.glTexSubImage2D(
self._target, # target
level, # level
x, # x offset
y, # y offset
w, # width