Skip to content

Commit c6bd04d

Browse files
committed
renderuje sie
1 parent 0237329 commit c6bd04d

File tree

4 files changed

+138
-14
lines changed

4 files changed

+138
-14
lines changed

my_engine/material.py

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,21 +5,45 @@
55
from OpenGL.GL.shaders import compileProgram, compileShader
66
from OpenGL.GL import GL_VERTEX_SHADER, GL_FRAGMENT_SHADER, GL_ACTIVE_ATTRIBUTES, \
77
glGetProgramiv, glGetActiveAttrib, GLuint, GLenum, GLint, GLsizei, GLchar, glGetActiveUniform, GL_ACTIVE_UNIFORMS, \
8-
glGetUniformLocation, glGetAttribLocation, GL_GEOMETRY_SHADER, glUseProgram
8+
glGetUniformLocation, glGetAttribLocation, GL_GEOMETRY_SHADER, glUseProgram, GL_FLOAT, GL_FLOAT_VEC2, GL_FLOAT_VEC3, \
9+
GL_FLOAT_VEC4, GL_INT, GL_INT_VEC2, GL_INT_VEC3, GL_INT_VEC4, glUniformMatrix4fv, GL_FLOAT_MAT4
10+
11+
12+
TYPE_TO_LENGTH = {
13+
GL_FLOAT: 1,
14+
GL_FLOAT_VEC2: 2,
15+
GL_FLOAT_VEC3: 3,
16+
GL_FLOAT_VEC4: 4,
17+
GL_INT: 1,
18+
GL_INT_VEC2: 2,
19+
GL_INT_VEC3: 3,
20+
GL_INT_VEC4: 4
21+
}
22+
23+
UNIFORM_TYPE_TO_FUNC = {
24+
GL_FLOAT_MAT4: glUniformMatrix4fv,
25+
26+
}
927

1028

1129
class Material(Component):
1230
def __init__(self, vertex_shader: Union[str, None] = None, fragment_shader: Union[str, None] = None,
13-
geometry_shader: Union[str, None] = None, obj=None):
31+
geometry_shader: Union[str, None] = None, view_matrix_name: str = 'view_matrix',
32+
projection_matrix_name: str = 'projection_matrix', model_matrix_name: str = 'model_matrix', obj=None):
1433
super().__init__('Material', obj)
1534
self.__vertex_shader = vertex_shader
1635
self.__fragment_shader = fragment_shader
1736
self.__geometry_shader = geometry_shader
1837
self.__attributes: Dict[str, int] = {}
1938
self.__uniforms: Dict[str, int] = {}
39+
self.view_matrix_name = view_matrix_name
40+
self.projection_matrix_name = projection_matrix_name
41+
self.model_matrix_name = model_matrix_name
2042

2143
self.__attributes_values: Union[Dict[str, np.ndarray]] = {}
2244
self.__uniforms_values: Union[Dict[str, np.ndarray]] = {}
45+
self.__attributes_types = {}
46+
self.__uniforms_types = {}
2347

2448
if self.__vertex_shader and self.__fragment_shader:
2549
program = compileProgram(
@@ -34,6 +58,7 @@ def __init__(self, vertex_shader: Union[str, None] = None, fragment_shader: Unio
3458
name, size, type_ = glGetActiveAttrib(program, u)
3559
location = glGetAttribLocation(program, name)
3660
name = name.decode("utf-8")
61+
self.__attributes_types[name] = type_
3762
self.__attributes[name] = location
3863
self.__attributes_values[name] = np.array([])
3964

@@ -42,13 +67,22 @@ def __init__(self, vertex_shader: Union[str, None] = None, fragment_shader: Unio
4267
name, size, type_ = glGetActiveUniform(program, u)
4368
location = glGetUniformLocation(program, name)
4469
name = name.decode("utf-8")
70+
self.__uniforms_types[name] = type_
4571
self.__uniforms[name] = location
4672
self.__uniforms_values[name] = np.array([])
4773

4874
@property
4975
def attributes(self):
5076
return self.__attributes
5177

78+
@property
79+
def attributes_types(self):
80+
return self.__attributes_types
81+
82+
@property
83+
def uniforms_types(self):
84+
return self.__uniforms_types
85+
5286
@property
5387
def uniforms(self):
5488
return self.__uniforms

my_engine/renderer.py

Lines changed: 66 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,21 @@
11
from my_engine.component import Component
2-
from my_engine.material import Material
2+
from my_engine.material import Material, TYPE_TO_LENGTH
33
from my_engine.mesh import Mesh
44
from my_engine.camera import Camera
55
from typing import Tuple, Union
66
from collections import defaultdict
7-
from OpenGL.GL import glGenBuffers, glClearColor, glEnable, glBlendFunc, GL_DEPTH_TEST, GL_BLEND, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA
7+
from OpenGL.GL import glGenBuffers, glBindBuffer, glBufferData, glClearColor, glEnable, glBlendFunc, GL_DEPTH_TEST, \
8+
GL_BLEND, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ARRAY_BUFFER, GL_ELEMENT_ARRAY_BUFFER, GL_STATIC_DRAW, \
9+
glEnableVertexAttribArray, glVertexAttribPointer, GL_FALSE, GL_FLOAT, GL_SAMPLER_2D, glUniformMatrix4fv, glDrawElements, \
10+
GL_TRIANGLES, GL_UNSIGNED_INT, glDrawRangeElements
11+
import numpy as np
12+
import ctypes
813

914

1015
class Renderer(Component):
1116
def __init__(self, obj, active_camera: Camera=None, enable: Tuple = (GL_DEPTH_TEST,),
12-
blend_settings: Union[Tuple[2], None] = (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA),
13-
clear_color: Tuple[4] = (0.1, 0.1, 0.1, 1)):
17+
blend_settings: Union[Tuple, None] = (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA),
18+
clear_color: Tuple = (0.1, 0.1, 0.1, 1)):
1419
super().__init__('Renderer', obj)
1520
self.__active_camera = active_camera
1621
self.__enable = enable
@@ -23,6 +28,9 @@ def __init__(self, obj, active_camera: Camera=None, enable: Tuple = (GL_DEPTH_TE
2328
# glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
2429
# glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, GL_STATIC_DRAW)
2530
self.__all_objects = {}
31+
self.__data_for_render = {}
32+
self.__vertices = np.array([])
33+
self.__indices = np.array([])
2634

2735
@property
2836
def active_camera(self):
@@ -33,17 +41,15 @@ def active_camera(self, val):
3341
self.__active_camera = val
3442

3543
def get_all_objects(self):
36-
descendants = {child: child.matrix for child in self.__obj.children}
37-
unchecked_children = [child1 for child in self.__obj.children for child1 in child.children]
44+
descendants = {child: child.matrix for child in self.obj.children}
45+
unchecked_children = [child1 for child in self.obj.children for child1 in child.children]
3846
while unchecked_children:
3947
child = unchecked_children.pop()
40-
descendants[child] = descendants[child.parent] * child.matrix
48+
descendants[child] = descendants[child.parent] @ child.matrix
4149
unchecked_children.extend(child.children)
4250
return descendants
4351

4452
def start(self):
45-
self.__VBO = glGenBuffers(1)
46-
self.__EBO = glGenBuffers(1)
4753
glClearColor(*self.__clear_color)
4854
for setting in self.__enable:
4955
glEnable(setting)
@@ -53,9 +59,58 @@ def start(self):
5359

5460
self.__all_objects = [(key, val) for key, val in self.get_all_objects().items() if 'Material' in key.components and 'Mesh' in key.components]
5561

56-
shaders = defaultdict(list)
62+
vertices = []
63+
indices = []
5764

65+
shaders = defaultdict(list)
66+
verts_len = 0
5867
for obj in self.__all_objects:
5968
material = obj[0].components['Material']
6069
mesh = obj[0].components['Mesh']
61-
shaders[material].append((mesh.get_data_positioned_to_material(material), mesh.indices, obj[1]))
70+
vertices.extend(list(mesh.get_data_positioned_to_material(material)))
71+
object_data = {'pointer': len(indices), 'length': mesh.indices.size, 'matrix': obj[1], 'object': obj[0]}
72+
indices.extend(list(mesh.indices.flatten() + verts_len))
73+
verts_len += len(mesh.vertices)
74+
if 'Texture' in obj[0].components:
75+
object_data['texture'] = obj[0].components['Texture']
76+
shaders[material].append(object_data)
77+
78+
self.__data_for_render = shaders
79+
80+
self.__vertices = np.array(vertices, dtype=np.float32)
81+
self.__indices = np.array(indices, dtype=np.uint32)
82+
83+
self.__VBO = glGenBuffers(1)
84+
self.__EBO = glGenBuffers(1)
85+
86+
glBindBuffer(GL_ARRAY_BUFFER, self.__VBO)
87+
glBufferData(GL_ARRAY_BUFFER, self.__vertices.nbytes, self.__vertices, GL_STATIC_DRAW)
88+
89+
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.__EBO)
90+
glBufferData(GL_ELEMENT_ARRAY_BUFFER, self.__indices.nbytes, self.__indices, GL_STATIC_DRAW)
91+
92+
def update(self):
93+
for material, data in self.__data_for_render.items():
94+
num_of_items = sum(TYPE_TO_LENGTH[type_] for attrib, type_ in material.attributes_types.items())
95+
pointer = 0
96+
for attrib, index in sorted(material.attributes.items(), key=lambda x: x[1]):
97+
length = TYPE_TO_LENGTH[material.attributes_types[attrib]]
98+
glEnableVertexAttribArray(index)
99+
glVertexAttribPointer(index, length, GL_FLOAT, GL_FALSE, self.__vertices.itemsize * num_of_items, ctypes.c_void_p(pointer * 4))
100+
pointer += length
101+
material.use_program()
102+
glUniformMatrix4fv(material.uniforms[material.view_matrix_name], 1, GL_FALSE, self.__active_camera.obj.inverse_matrix)
103+
glUniformMatrix4fv(material.uniforms[material.projection_matrix_name], 1, GL_FALSE, self.__active_camera.projection)
104+
for dat in data:
105+
for uniform, index in material.uniforms.items():
106+
if material.uniforms_types[uniform] == GL_SAMPLER_2D:
107+
pass
108+
elif material.model_matrix_name == uniform:
109+
glUniformMatrix4fv(index, 1, GL_FALSE, dat['matrix'])
110+
elif material.view_matrix_name == uniform:
111+
pass
112+
elif material.projection_matrix_name == uniform:
113+
pass
114+
# glDrawElements(GL_TRIANGLES, dat['length'], GL_UNSIGNED_INT, ctypes.c_void_p(dat['pointer'] * 0))
115+
glDrawElements(GL_TRIANGLES, len(self.__indices), GL_UNSIGNED_INT, None)
116+
# glDrawRangeElements(GL_TRIANGLES, len(self.__indices), GL_UNSIGNED_INT, None)

my_engine/texture.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from my_engine.component import Component
2+
import numpy as np
3+
import pygame
4+
from OpenGL.GL import glTexImage2D, glGenTextures, glBindTexture, glTexParameteri, GL_TEXTURE_2D, GL_RGBA, GL_UNSIGNED_BYTE, GL_TEXTURE_WRAP_S, GL_REPEAT, GL_TEXTURE_WRAP_T, GL_TEXTURE_MIN_FILTER, GL_TEXTURE_MAG_FILTER, GL_LINEAR
5+
6+
7+
class Texture(Component):
8+
def __init__(self, obj=None, image=None, settings=((GL_TEXTURE_WRAP_S, GL_REPEAT),
9+
(GL_TEXTURE_WRAP_T, GL_REPEAT),
10+
(GL_TEXTURE_MIN_FILTER, GL_LINEAR),
11+
(GL_TEXTURE_MAG_FILTER, GL_LINEAR))):
12+
super().__init__('Texture', obj)
13+
self.__settings = settings
14+
self.__image = image
15+
self.__image_width, self.__image_height = image.get_rect().size
16+
self.__img_data = pygame.image.tostring(image, "RGBA")
17+
18+
def load_from_file(self, path):
19+
image = pygame.image.load(path)
20+
image = pygame.transform.flip(image, False, True)
21+
self.__image_width, self.__image_height = image.get_rect().size
22+
self.__img_data = pygame.image.tostring(image, "RGBA")
23+
24+
def load_settings(self):
25+
for setting in self.__settings:
26+
glTexParameteri(GL_TEXTURE_2D, *setting)
27+
28+
@staticmethod
29+
def get_buffer():
30+
texture = glGenTextures(1)
31+
glBindTexture(GL_TEXTURE_2D, texture)
32+
return texture
33+
34+
def send_texture(self):
35+
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self.__image_width, self.__image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, self.__img_data)

opengl8_uv_textures_pygame.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@
153153
# glUniformMatrix4fv(rotation_loc, 1, GL_FALSE, rot_x @ rot_y)
154154
glUniformMatrix4fv(rotation_loc, 1, GL_FALSE, rot_x * rot_y)
155155

156-
glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None)
156+
glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, ctypes.c_void_p(0))
157157

158158
pygame.display.flip()
159159

0 commit comments

Comments
 (0)