-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderer.py
More file actions
177 lines (152 loc) · 6.94 KB
/
renderer.py
File metadata and controls
177 lines (152 loc) · 6.94 KB
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
"""
MIT License
Copyright (c) 2020 Chris Bell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import numpy as np
import ctypes
import OpenGL
# Disable error checking for a speed increase
# OpenGL.ERROR_CHECKING = False
# Manually show errors
OpenGL.ERROR_LOGGING = False
# Ensure we use numpy arrays instead of lists to prevent copying data
OpenGL.ERROR_ON_COPY = True
import OpenGL.GL as GL
import OpenGL.GL.shaders
class Renderer:
def __init__(self):
"""Modern OpenGL rendering class"""
# Chip-8 display
self.width = 64
self.height = 32
# Should be a multiple of 60 for proper timer operation
self.max_fps = 60
# Whether each pixel is on or off
self.display_state = [[0 for y in range(self.height)] for x in range(self.width)]
# Objects for vertex/color buffers
self.buffer_object = np.array([])
# Using 4 vertices per 'pixel'
self.display_buffer = np.array([0] * (4 * self.height * self.width), np.int32)
self.vertex_buffer = []
self.vertex_array_object = 0
self.attributes = {}
self.shader = 0
self.vertex_shader = """
#version 330
in vec2 position;
in int pixel_state;
flat out vec4 color; //don't interpolate the color
void main()
{
if (pixel_state == 0) {
color = vec4(0.1, 0.1, 0.1, 0.1);
} else {
color = vec4(1, 1, 1, 1);
}
gl_Position.xy = position.xy;
gl_Position.zw = vec2(0.0, 1.0);
}
"""
self.fragment_shader = """
#version 330
flat in vec4 color;
void main()
{
gl_FragColor = color;
}
"""
def bind_shader(self):
"""Compiles and binds the shader program"""
self.shader = OpenGL.GL.shaders.compileProgram(
OpenGL.GL.shaders.compileShader(self.vertex_shader, GL.GL_VERTEX_SHADER),
OpenGL.GL.shaders.compileShader(self.fragment_shader, GL.GL_FRAGMENT_SHADER)
)
GL.glUseProgram(self.shader)
def destroy(self):
"""Frees all of the allocated OpenGL resources"""
# Unbind and delete VAO first, then VBOs
GL.glBindVertexArray(0)
GL.glDeleteVertexArrays(1, np.array([self.vertex_array_object]))
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
GL.glDeleteBuffers(len(self.attributes), self.buffer_object)
# Remove attributes
for attribute in self.attributes.values():
GL.glDisableVertexAttribArray(attribute)
# Unbind shader
GL.glUseProgram(0)
def create_vertex_objects(self):
"""Generates the VAO and VBOs"""
# Shader attributes
attribute_names = ['position', 'pixel_state']
# The VAO contains both position and color VBOs
self.vertex_array_object = GL.glGenVertexArrays(1)
GL.glBindVertexArray(self.vertex_array_object)
# Generate VBOs for each of the shader attributes
self.buffer_object = GL.glGenBuffers(len(attribute_names))
# Enable the attributes
for attribute in attribute_names:
self.attributes[attribute] = GL.glGetAttribLocation(self.shader, attribute)
GL.glEnableVertexAttribArray(self.attributes[attribute])
# Bind the position buffer and describe/send its data
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.buffer_object[0])
GL.glVertexAttribPointer(self.attributes['position'], 2, GL.GL_FLOAT, False, 0,
ctypes.c_void_p(0))
# Add vertices of 'pixels' to the buffer
# The position of each vertex is in normalized device coordinate space
x_increment = 2.0 / self.width
y_increment = 2.0 / self.height
for y in range(self.height):
for x in range(self.width):
# Add each 'pixel' to the list
top_left = [-1.0 + (x * x_increment), -1.0 + (y * y_increment)]
self.vertex_buffer.extend([top_left[0], top_left[1]])
self.vertex_buffer.extend([top_left[0] + x_increment, top_left[1]])
self.vertex_buffer.extend([top_left[0] + x_increment, top_left[1] + y_increment])
self.vertex_buffer.extend([top_left[0], top_left[1] + y_increment])
self.vertex_buffer = np.array(self.vertex_buffer, np.float32)
# sizeof float (4) * vertex components (2) * vertices in square (4) * number of 'pixels'
GL.glBufferData(GL.GL_ARRAY_BUFFER, 4 * 2 * 4 * self.height * self.width,
self.vertex_buffer, GL.GL_STATIC_DRAW)
# Bind the color buffer and describe/send its data
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.buffer_object[1])
GL.glVertexAttribPointer(self.attributes['pixel_state'], 1, GL.GL_INT, False, 0,
ctypes.c_void_p(0))
# Size of int (4) * number of vertices in a square (4) * number of 'pixels'
GL.glBufferData(GL.GL_ARRAY_BUFFER, 4 * 4 * self.height * self.width,
self.display_buffer, GL.GL_DYNAMIC_DRAW)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
def get_pixel(self, x, y):
return self.display_state[x][y]
def set_pixel(self, x, y, on):
# Get offset into buffer and update only that pixel
start = (y * self.width * 4 * 4) + (x * 4 * 4)
data = np.array([np.int32(on)] * 4, np.int32)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.buffer_object[1])
GL.glBufferSubData(GL.GL_ARRAY_BUFFER, start, 4 * 4, data)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
# Update display state for interpreter
self.display_state[x][y] = on
def clear_screen(self):
for x in range(self.width):
for y in range(self.height):
self.set_pixel(x, y, 0)
def render(self):
"""Draw each 'pixel'"""
# Clear the color buffer first
GL.glClear(GL.GL_COLOR_BUFFER_BIT)
GL.glDrawArrays(GL.GL_QUADS, 0, 4 * self.height * self.width)