gamengine3d 1.6.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gamengine3d/__init__.py +15 -0
- gamengine3d/cli.py +34 -0
- gamengine3d/context.py +212 -0
- gamengine3d/engine.py +263 -0
- gamengine3d/examples/__init__.py +0 -0
- gamengine3d/examples/basics.py +11 -0
- gamengine3d/examples/player_movement.py +83 -0
- gamengine3d/examples/scripts/cylinder.py +21 -0
- gamengine3d/examples/scripts/player_movement.py +94 -0
- gamengine3d/examples/scripts/settings.py +6 -0
- gamengine3d/examples/the_everything_demo.py +42 -0
- gamengine3d/game_objects.py +185 -0
- gamengine3d/helper.py +726 -0
- gamengine3d/shaders/__init__.py +0 -0
- gamengine3d/shaders/default.frag +64 -0
- gamengine3d/shaders/default.vert +24 -0
- gamengine3d/shaders/depth.frag +2 -0
- gamengine3d/shaders/depth.vert +9 -0
- gamengine3d-1.6.0.dist-info/METADATA +80 -0
- gamengine3d-1.6.0.dist-info/RECORD +24 -0
- gamengine3d-1.6.0.dist-info/WHEEL +5 -0
- gamengine3d-1.6.0.dist-info/entry_points.txt +2 -0
- gamengine3d-1.6.0.dist-info/licenses/LICENSE.txt +21 -0
- gamengine3d-1.6.0.dist-info/top_level.txt +1 -0
gamengine3d/helper.py
ADDED
|
@@ -0,0 +1,726 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
import importlib.util
|
|
3
|
+
import math
|
|
4
|
+
import moderngl
|
|
5
|
+
import pygame
|
|
6
|
+
from pygame.locals import DOUBLEBUF, OPENGL
|
|
7
|
+
import importlib.resources as pkg_resources
|
|
8
|
+
import numpy as np
|
|
9
|
+
from pyrr import Matrix44
|
|
10
|
+
import os
|
|
11
|
+
|
|
12
|
+
class classproperty(property):
|
|
13
|
+
def __get__(self, cls, owner):
|
|
14
|
+
return self.fget(owner)
|
|
15
|
+
|
|
16
|
+
class vector3d:
|
|
17
|
+
def __init__(self, x, y=None, z=None):
|
|
18
|
+
self.x = x
|
|
19
|
+
self.y = y
|
|
20
|
+
self.z = z
|
|
21
|
+
|
|
22
|
+
if y is None and z is None:
|
|
23
|
+
self.y = self.x
|
|
24
|
+
self.z = self.x
|
|
25
|
+
elif z is None:
|
|
26
|
+
self.z = 0.0
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def magnitude(self):
|
|
30
|
+
return math.sqrt(self.x**2 + self.y**2 + self.z**2)
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def sqr_magnitude(self):
|
|
34
|
+
return self.x**2 + self.y**2 + self.z**2
|
|
35
|
+
|
|
36
|
+
def normalize(self):
|
|
37
|
+
magnitude = self.magnitude
|
|
38
|
+
if magnitude != 0:
|
|
39
|
+
self.x /= magnitude
|
|
40
|
+
self.y /= magnitude
|
|
41
|
+
self.z /= magnitude
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def normalized(self):
|
|
45
|
+
magnitude = self.magnitude
|
|
46
|
+
if magnitude == 0:
|
|
47
|
+
return vector3d(0, 0, 0)
|
|
48
|
+
return vector3d(self.x / magnitude, self.y / magnitude, self.z / magnitude)
|
|
49
|
+
|
|
50
|
+
def dot(self, other):
|
|
51
|
+
return self.x * other.x + self.y * other.y + self.z * other.z
|
|
52
|
+
|
|
53
|
+
def cross(self, other):
|
|
54
|
+
return vector3d(
|
|
55
|
+
self.y * other.z - self.z * other.y,
|
|
56
|
+
self.z * other.x - self.x * other.z,
|
|
57
|
+
self.x * other.y - self.y * other.x,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
def __add__(self, other):
|
|
61
|
+
if isinstance(other, vector3d):
|
|
62
|
+
return vector3d(self.x + other.x, self.y + other.y, self.z + other.z)
|
|
63
|
+
else:
|
|
64
|
+
return vector3d(self.x + other, self.y + other, self.z + other)
|
|
65
|
+
|
|
66
|
+
def __sub__(self, other):
|
|
67
|
+
if isinstance(other, vector3d):
|
|
68
|
+
return vector3d(self.x - other.x, self.y - other.y, self.z - other.z)
|
|
69
|
+
else:
|
|
70
|
+
return vector3d(self.x - other, self.y - other, self.z - other)
|
|
71
|
+
|
|
72
|
+
def __mul__(self, other):
|
|
73
|
+
if isinstance(other, vector3d):
|
|
74
|
+
return vector3d(self.x * other.x, self.y * other.y, self.z * other.z)
|
|
75
|
+
else:
|
|
76
|
+
return vector3d(self.x * other, self.y * other, self.z * other)
|
|
77
|
+
|
|
78
|
+
def __truediv__(self, other):
|
|
79
|
+
if isinstance(other, vector3d):
|
|
80
|
+
return vector3d(self.x / other.x, self.y / other.y, self.z / other.z)
|
|
81
|
+
else:
|
|
82
|
+
return vector3d(self.x / other, self.y / other, self.z / other)
|
|
83
|
+
|
|
84
|
+
def totuple(self):
|
|
85
|
+
return (self.x, self.y, self.z)
|
|
86
|
+
|
|
87
|
+
def __radd__(self, other):
|
|
88
|
+
return vector3d(self.x + other, self.y + other, self.z + other)
|
|
89
|
+
|
|
90
|
+
def __rsub__(self, other):
|
|
91
|
+
return vector3d(self.x - other, self.y - other, self.z - other)
|
|
92
|
+
|
|
93
|
+
def __rtruediv__(self, other):
|
|
94
|
+
return vector3d(self.x / other, self.y / other, self.z / other)
|
|
95
|
+
|
|
96
|
+
def __rmul__(self, other):
|
|
97
|
+
return vector3d(self.x * other, self.y * other, self.z * other)
|
|
98
|
+
|
|
99
|
+
@classmethod
|
|
100
|
+
def fromtuple(cls, tuple):
|
|
101
|
+
return cls(*tuple)
|
|
102
|
+
|
|
103
|
+
def __repr__(self):
|
|
104
|
+
return f"vector3d({self.x}, {self.y}, {self.z})"
|
|
105
|
+
|
|
106
|
+
def copy(self):
|
|
107
|
+
return vector3d(self.x, self.y, self.z)
|
|
108
|
+
|
|
109
|
+
def __neg__(self):
|
|
110
|
+
return vector3d(-self.x, -self.y, -self.z)
|
|
111
|
+
|
|
112
|
+
@classproperty
|
|
113
|
+
def up(cls):
|
|
114
|
+
return cls(0, 1, 0)
|
|
115
|
+
|
|
116
|
+
@classproperty
|
|
117
|
+
def down(cls):
|
|
118
|
+
return cls(0, -1, 0)
|
|
119
|
+
|
|
120
|
+
@classproperty
|
|
121
|
+
def right(cls):
|
|
122
|
+
return cls(1, 0, 0)
|
|
123
|
+
|
|
124
|
+
@classproperty
|
|
125
|
+
def left(cls):
|
|
126
|
+
return cls(-1, 0, 0)
|
|
127
|
+
|
|
128
|
+
@classproperty
|
|
129
|
+
def forward(cls):
|
|
130
|
+
return cls(0, 0, 1)
|
|
131
|
+
|
|
132
|
+
@classproperty
|
|
133
|
+
def back(cls):
|
|
134
|
+
return cls(0, 0, -1)
|
|
135
|
+
|
|
136
|
+
@classproperty
|
|
137
|
+
def one(cls):
|
|
138
|
+
return cls(1, 1, 1)
|
|
139
|
+
|
|
140
|
+
@classproperty
|
|
141
|
+
def zero(cls):
|
|
142
|
+
return cls(0, 0, 0)
|
|
143
|
+
|
|
144
|
+
class Color:
|
|
145
|
+
def __init__(self, r, g, b):
|
|
146
|
+
self.r = r
|
|
147
|
+
self.g = g
|
|
148
|
+
self.b = b
|
|
149
|
+
|
|
150
|
+
@staticmethod
|
|
151
|
+
def RGB(r, g, b): return Color(r, g, b)
|
|
152
|
+
|
|
153
|
+
@staticmethod
|
|
154
|
+
def hex(hex_string):
|
|
155
|
+
if not hex_string.startswith("#"): raise Exception("String must start with #")
|
|
156
|
+
if not len(hex_string) == 7: raise Exception("String must contain 7 characters")
|
|
157
|
+
r = int(hex_string[1:3], 16)
|
|
158
|
+
g = int(hex_string[3:5], 16)
|
|
159
|
+
b = int(hex_string[5:7], 16)
|
|
160
|
+
return Color(r, g, b)
|
|
161
|
+
|
|
162
|
+
def __eq__(self, other):
|
|
163
|
+
if self.r == other.r and self.g == other.g and self.b == other.b:
|
|
164
|
+
return True
|
|
165
|
+
return False
|
|
166
|
+
|
|
167
|
+
def to_hex(self):
|
|
168
|
+
if not all(0 <= x <= 255 for x in (self.r, self.g, self.b)):
|
|
169
|
+
raise ValueError("RGB values must be in the range 0-255")
|
|
170
|
+
return "#{:02X}{:02X}{:02X}".format(self.r, self.g, self.b)
|
|
171
|
+
|
|
172
|
+
def to_rgb(self):
|
|
173
|
+
return self.r, self.g, self.b
|
|
174
|
+
|
|
175
|
+
@classproperty
|
|
176
|
+
def black(cls):
|
|
177
|
+
return cls(0, 0, 0)
|
|
178
|
+
|
|
179
|
+
@classproperty
|
|
180
|
+
def white(cls):
|
|
181
|
+
return cls(255, 255, 255)
|
|
182
|
+
|
|
183
|
+
@classproperty
|
|
184
|
+
def red(cls): return cls(255, 0, 0)
|
|
185
|
+
|
|
186
|
+
@classproperty
|
|
187
|
+
def green(cls): return cls(0, 255, 0)
|
|
188
|
+
|
|
189
|
+
@classproperty
|
|
190
|
+
def blue(cls): return cls(0, 0, 255)
|
|
191
|
+
|
|
192
|
+
@classproperty
|
|
193
|
+
def yellow(cls): return cls(255, 255, 0)
|
|
194
|
+
|
|
195
|
+
@classproperty
|
|
196
|
+
def cyan(cls): return cls(0, 255, 255)
|
|
197
|
+
|
|
198
|
+
@classproperty
|
|
199
|
+
def magenta(cls): return cls(255, 0, 255)
|
|
200
|
+
|
|
201
|
+
@classproperty
|
|
202
|
+
def grey(cls): return cls(33, 33, 33)
|
|
203
|
+
|
|
204
|
+
@classproperty
|
|
205
|
+
def light_grey(cls): return cls(80, 80, 80)
|
|
206
|
+
|
|
207
|
+
@classproperty
|
|
208
|
+
def light_red(cls): return cls(253, 89, 111)
|
|
209
|
+
|
|
210
|
+
@classproperty
|
|
211
|
+
def light_green(cls): return cls(0, 190, 160)
|
|
212
|
+
|
|
213
|
+
@classproperty
|
|
214
|
+
def light_yellow(cls): return cls(254, 208, 95)
|
|
215
|
+
|
|
216
|
+
@classproperty
|
|
217
|
+
def orange(cls): return cls(254, 166, 93)
|
|
218
|
+
|
|
219
|
+
@classproperty
|
|
220
|
+
def light_blue(cls): return cls(109, 154, 218)
|
|
221
|
+
|
|
222
|
+
class Light:
|
|
223
|
+
def __init__(self, position: vector3d, color: Color, intensity: float = 1.0, show=False, name="Light"):
|
|
224
|
+
self.position = position
|
|
225
|
+
self.color = color
|
|
226
|
+
self.intensity = intensity
|
|
227
|
+
self.show = show
|
|
228
|
+
self.name = name
|
|
229
|
+
|
|
230
|
+
class Renderer:
|
|
231
|
+
def __init__(self, width=800, height=600, flags=DOUBLEBUF | OPENGL):
|
|
232
|
+
pygame.init()
|
|
233
|
+
self.screen = pygame.display.set_mode((width, height), flags)
|
|
234
|
+
self.ctx = moderngl.create_context()
|
|
235
|
+
self.ctx.viewport = (0, 0, width, height)
|
|
236
|
+
self.samples = 4
|
|
237
|
+
self.color_tex = self.ctx.texture((width, height), 3, samples=self.samples)
|
|
238
|
+
self.depth_rbo = self.ctx.depth_renderbuffer((width, height), samples=self.samples)
|
|
239
|
+
self.fbo = self.ctx.framebuffer(color_attachments=[self.color_tex], depth_attachment=self.depth_rbo)
|
|
240
|
+
self.lights = []
|
|
241
|
+
self.width = width
|
|
242
|
+
self.height = height
|
|
243
|
+
self.ambient = 0.2
|
|
244
|
+
self.ctx.enable(moderngl.DEPTH_TEST)
|
|
245
|
+
|
|
246
|
+
# === Main shader ===
|
|
247
|
+
self.prog = self._load_shader("default.vert", "default.frag")
|
|
248
|
+
self.prog["model"].write(np.eye(4, dtype="f4").tobytes())
|
|
249
|
+
self.proj = Matrix44.perspective_projection(60.0, width / height, 0.1, 100.0)
|
|
250
|
+
self.view = Matrix44.look_at(
|
|
251
|
+
eye=(3.0, 2.0, 3.0),
|
|
252
|
+
target=(0.0, 0.0, 0.0),
|
|
253
|
+
up=(0.0, 1.0, 0.0)
|
|
254
|
+
)
|
|
255
|
+
self.mvp = self.proj * self.view
|
|
256
|
+
self.prog["mvp"].write(self.mvp.astype("f4").tobytes())
|
|
257
|
+
self.prog["ambient"].value = self.ambient
|
|
258
|
+
|
|
259
|
+
self.shadow_size = 4096
|
|
260
|
+
self.shadow_depth_tex = self.ctx.depth_texture((self.shadow_size, self.shadow_size))
|
|
261
|
+
try:
|
|
262
|
+
self.shadow_depth_tex.repeat_x = False
|
|
263
|
+
self.shadow_depth_tex.repeat_y = False
|
|
264
|
+
except Exception:
|
|
265
|
+
pass
|
|
266
|
+
self.shadow_fbo = self.ctx.framebuffer(depth_attachment=self.shadow_depth_tex)
|
|
267
|
+
self.depth_prog = self._load_shader("depth.vert", "depth.frag")
|
|
268
|
+
self.light_space_matrix = np.eye(4, dtype="f4")
|
|
269
|
+
|
|
270
|
+
# ------------------------------------------
|
|
271
|
+
# Window / Resize Handling
|
|
272
|
+
# ------------------------------------------
|
|
273
|
+
def resize(self, width, height):
|
|
274
|
+
self.width = width
|
|
275
|
+
self.height = height
|
|
276
|
+
pygame.display.set_mode(
|
|
277
|
+
(width, height),
|
|
278
|
+
pygame.OPENGL | pygame.DOUBLEBUF | pygame.RESIZABLE
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
self.ctx = moderngl.create_context()
|
|
282
|
+
self.ctx.viewport = (0, 0, width, height)
|
|
283
|
+
|
|
284
|
+
# Recreate framebuffer and textures for new context
|
|
285
|
+
self.color_tex = self.ctx.texture((width, height), 3, samples=self.samples)
|
|
286
|
+
self.depth_rbo = self.ctx.depth_renderbuffer((width, height), samples=self.samples)
|
|
287
|
+
self.fbo = self.ctx.framebuffer(color_attachments=[self.color_tex], depth_attachment=self.depth_rbo)
|
|
288
|
+
|
|
289
|
+
# Recreate shaders in new context
|
|
290
|
+
self.prog = self._load_shader("default.vert", "default.frag")
|
|
291
|
+
self.prog["model"].write(np.eye(4, dtype="f4").tobytes())
|
|
292
|
+
aspect = width / height
|
|
293
|
+
self.proj = Matrix44.perspective_projection(60.0, aspect, 0.1, 100.0)
|
|
294
|
+
self.mvp = self.proj * self.view
|
|
295
|
+
self.prog["mvp"].write(self.mvp.astype("f4").tobytes())
|
|
296
|
+
self.prog["ambient"].value = self.ambient
|
|
297
|
+
|
|
298
|
+
# Recreate shadow map resources for this context
|
|
299
|
+
self.shadow_depth_tex = self.ctx.depth_texture((self.shadow_size, self.shadow_size))
|
|
300
|
+
try:
|
|
301
|
+
self.shadow_depth_tex.repeat_x = False
|
|
302
|
+
self.shadow_depth_tex.repeat_y = False
|
|
303
|
+
except Exception:
|
|
304
|
+
pass
|
|
305
|
+
self.shadow_fbo = self.ctx.framebuffer(depth_attachment=self.shadow_depth_tex)
|
|
306
|
+
self.depth_prog = self._load_shader("depth.vert", "depth.frag")
|
|
307
|
+
|
|
308
|
+
self._send_lights()
|
|
309
|
+
|
|
310
|
+
# ------------------------------------------
|
|
311
|
+
# Light & Matrix
|
|
312
|
+
# ------------------------------------------
|
|
313
|
+
def add_light(self, light: Light):
|
|
314
|
+
self.lights.append(light)
|
|
315
|
+
|
|
316
|
+
def _compute_normal(self, p1, p2, p3):
|
|
317
|
+
u = p2 - p1
|
|
318
|
+
v = p3 - p1
|
|
319
|
+
return u.cross(v).normalized
|
|
320
|
+
|
|
321
|
+
def compute_light_matrix(self, light: Light):
|
|
322
|
+
"""Compute light-space projection * view for shadow mapping."""
|
|
323
|
+
light_proj = Matrix44.orthogonal_projection(-20, 20, -20, 20, 1, 30)
|
|
324
|
+
light_view = Matrix44.look_at(
|
|
325
|
+
eye=light.position.totuple(),
|
|
326
|
+
target=(0, 0, 0),
|
|
327
|
+
up=(0, 1, 0)
|
|
328
|
+
)
|
|
329
|
+
return light_proj * light_view
|
|
330
|
+
|
|
331
|
+
# ------------------------------------------
|
|
332
|
+
# Shadow Pass
|
|
333
|
+
# ------------------------------------------
|
|
334
|
+
def render_shadow_pass(self, objects):
|
|
335
|
+
"""Render depth map from light's POV."""
|
|
336
|
+
if not self.lights:
|
|
337
|
+
return
|
|
338
|
+
light = self.lights[0]
|
|
339
|
+
self.light_space_matrix = self.compute_light_matrix(light)
|
|
340
|
+
|
|
341
|
+
self.shadow_fbo.clear(depth=1.0)
|
|
342
|
+
self.shadow_fbo.use()
|
|
343
|
+
self.ctx.enable(moderngl.DEPTH_TEST)
|
|
344
|
+
|
|
345
|
+
for obj in objects:
|
|
346
|
+
if not hasattr(obj, "get_corners"):
|
|
347
|
+
continue
|
|
348
|
+
corners = obj.get_corners()
|
|
349
|
+
vertices = []
|
|
350
|
+
for face in obj.faces:
|
|
351
|
+
p1, p2, p3, p4 = [corners[i] for i in face]
|
|
352
|
+
vertices.extend([
|
|
353
|
+
*p1.totuple(), *p2.totuple(), *p3.totuple(),
|
|
354
|
+
*p1.totuple(), *p3.totuple(), *p4.totuple()
|
|
355
|
+
])
|
|
356
|
+
vertices = np.array(vertices, dtype="f4")
|
|
357
|
+
vbo = self.ctx.buffer(vertices.tobytes())
|
|
358
|
+
vao = self.ctx.vertex_array(self.depth_prog, [(vbo, "3f", "in_vert")])
|
|
359
|
+
self.depth_prog["model"].write(np.eye(4, dtype="f4").tobytes())
|
|
360
|
+
self.depth_prog["light_space_matrix"].write(self.light_space_matrix.astype("f4").tobytes())
|
|
361
|
+
vao.render()
|
|
362
|
+
vao.release()
|
|
363
|
+
vbo.release()
|
|
364
|
+
|
|
365
|
+
self.ctx.screen.use()
|
|
366
|
+
|
|
367
|
+
def render_plane(self, p1, p2, p3, color):
|
|
368
|
+
normal = self._compute_normal(p1, p2, p3)
|
|
369
|
+
vertices = np.array([
|
|
370
|
+
*p1.totuple(), *color.to_rgb(), *normal.totuple(),
|
|
371
|
+
*p2.totuple(), *color.to_rgb(), *normal.totuple(),
|
|
372
|
+
*p3.totuple(), *color.to_rgb(), *normal.totuple()
|
|
373
|
+
], dtype="f4")
|
|
374
|
+
vbo = self.ctx.buffer(vertices.tobytes())
|
|
375
|
+
vao = self.ctx.vertex_array(
|
|
376
|
+
self.prog, [(vbo, "3f 3f 3f", "in_vert", "in_color", "in_normal")]
|
|
377
|
+
)
|
|
378
|
+
self._send_lights()
|
|
379
|
+
self.prog["light_space_matrix"].write(self.light_space_matrix.astype("f4").tobytes())
|
|
380
|
+
self.shadow_depth_tex.use(location=0)
|
|
381
|
+
self.prog["shadow_map"].value = 0
|
|
382
|
+
vao.render()
|
|
383
|
+
vao.release()
|
|
384
|
+
vbo.release()
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def render_cylinder(self, center, height, radius, color, segments=32, rotation=vector3d(0, 0, 0)):
|
|
388
|
+
vertices = []
|
|
389
|
+
|
|
390
|
+
# Helper functions for matrix multiplication
|
|
391
|
+
def apply_matrix(v: vector3d, m: Matrix44) -> vector3d:
|
|
392
|
+
vec4 = np.array([v.x, v.y, v.z, 1.0], dtype="f4")
|
|
393
|
+
transformed = m @ vec4
|
|
394
|
+
return vector3d(*transformed[:3])
|
|
395
|
+
|
|
396
|
+
def apply_matrix_normal(n: vector3d, m: Matrix44) -> vector3d:
|
|
397
|
+
vec4 = np.array([n.x, n.y, n.z, 0.0], dtype="f4") # w=0 for direction
|
|
398
|
+
transformed = m @ vec4
|
|
399
|
+
return vector3d(*transformed[:3]).normalized
|
|
400
|
+
|
|
401
|
+
# Precompute rotation matrix if rotation is provided
|
|
402
|
+
rot_x = Matrix44.from_x_rotation(math.radians(rotation.x))
|
|
403
|
+
rot_y = Matrix44.from_y_rotation(math.radians(rotation.y))
|
|
404
|
+
rot_z = Matrix44.from_z_rotation(math.radians(rotation.z))
|
|
405
|
+
rot_matrix = rot_z * rot_y * rot_x
|
|
406
|
+
|
|
407
|
+
for i in range(segments):
|
|
408
|
+
theta1 = 2 * math.pi * i / segments
|
|
409
|
+
theta2 = 2 * math.pi * (i + 1) / segments
|
|
410
|
+
|
|
411
|
+
# Top circle vertices
|
|
412
|
+
top1 = vector3d(radius * math.cos(theta1), height / 2, radius * math.sin(theta1))
|
|
413
|
+
top2 = vector3d(radius * math.cos(theta2), height / 2, radius * math.sin(theta2))
|
|
414
|
+
|
|
415
|
+
# Bottom circle vertices
|
|
416
|
+
bottom1 = vector3d(radius * math.cos(theta1), -height / 2, radius * math.sin(theta1))
|
|
417
|
+
bottom2 = vector3d(radius * math.cos(theta2), -height / 2, radius * math.sin(theta2))
|
|
418
|
+
|
|
419
|
+
# Apply rotation
|
|
420
|
+
top1 = apply_matrix(top1, rot_matrix)
|
|
421
|
+
top2 = apply_matrix(top2, rot_matrix)
|
|
422
|
+
bottom1 = apply_matrix(bottom1, rot_matrix)
|
|
423
|
+
bottom2 = apply_matrix(bottom2, rot_matrix)
|
|
424
|
+
|
|
425
|
+
# Translate to center
|
|
426
|
+
top1 += center
|
|
427
|
+
top2 += center
|
|
428
|
+
bottom1 += center
|
|
429
|
+
bottom2 += center
|
|
430
|
+
|
|
431
|
+
# Compute normals for sides
|
|
432
|
+
normal1 = vector3d(math.cos(theta1), 0, math.sin(theta1))
|
|
433
|
+
normal2 = vector3d(math.cos(theta2), 0, math.sin(theta2))
|
|
434
|
+
normal1 = apply_matrix_normal(normal1, rot_matrix)
|
|
435
|
+
normal2 = apply_matrix_normal(normal2, rot_matrix)
|
|
436
|
+
|
|
437
|
+
# Side quad (two triangles)
|
|
438
|
+
for tri in [(top1, bottom1, bottom2), (top1, bottom2, top2)]:
|
|
439
|
+
n1 = (tri[0] - center).normalized
|
|
440
|
+
n2 = (tri[1] - center).normalized
|
|
441
|
+
n3 = (tri[2] - center).normalized
|
|
442
|
+
vertices.extend([
|
|
443
|
+
*tri[0].totuple(), *color.to_rgb(), *n1.totuple(),
|
|
444
|
+
*tri[1].totuple(), *color.to_rgb(), *n2.totuple(),
|
|
445
|
+
*tri[2].totuple(), *color.to_rgb(), *n3.totuple(),
|
|
446
|
+
])
|
|
447
|
+
|
|
448
|
+
# Top cap
|
|
449
|
+
top_center = vector3d(0, height / 2, 0)
|
|
450
|
+
top_center = apply_matrix(top_center, rot_matrix) + center
|
|
451
|
+
normal_top = apply_matrix_normal(vector3d(0, 1, 0), rot_matrix)
|
|
452
|
+
vertices.extend([
|
|
453
|
+
*top_center.totuple(), *color.to_rgb(), *normal_top.totuple(),
|
|
454
|
+
*top2.totuple(), *color.to_rgb(), *normal_top.totuple(),
|
|
455
|
+
*top1.totuple(), *color.to_rgb(), *normal_top.totuple(),
|
|
456
|
+
])
|
|
457
|
+
|
|
458
|
+
# Bottom cap
|
|
459
|
+
bottom_center = vector3d(0, -height / 2, 0)
|
|
460
|
+
bottom_center = apply_matrix(bottom_center, rot_matrix) + center
|
|
461
|
+
normal_bottom = apply_matrix_normal(vector3d(0, -1, 0), rot_matrix)
|
|
462
|
+
vertices.extend([
|
|
463
|
+
*bottom_center.totuple(), *color.to_rgb(), *normal_bottom.totuple(),
|
|
464
|
+
*bottom1.totuple(), *color.to_rgb(), *normal_bottom.totuple(),
|
|
465
|
+
*bottom2.totuple(), *color.to_rgb(), *normal_bottom.totuple(),
|
|
466
|
+
])
|
|
467
|
+
|
|
468
|
+
vertices = np.array(vertices, dtype="f4")
|
|
469
|
+
vbo = self.ctx.buffer(vertices.tobytes())
|
|
470
|
+
vao = self.ctx.vertex_array(
|
|
471
|
+
self.prog, [(vbo, "3f 3f 3f", "in_vert", "in_color", "in_normal")]
|
|
472
|
+
)
|
|
473
|
+
self._send_lights()
|
|
474
|
+
self.prog["light_space_matrix"].write(self.light_space_matrix.astype("f4").tobytes())
|
|
475
|
+
self.shadow_depth_tex.use(location=0)
|
|
476
|
+
self.prog["shadow_map"].value = 0
|
|
477
|
+
vao.render()
|
|
478
|
+
vao.release()
|
|
479
|
+
vbo.release()
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def render_quad(self, p1, p2, p3, p4, color):
|
|
483
|
+
normal = self._compute_normal(p1, p2, p3)
|
|
484
|
+
vertices = np.array([
|
|
485
|
+
*p1.totuple(), *color.to_rgb(), *normal.totuple(),
|
|
486
|
+
*p2.totuple(), *color.to_rgb(), *normal.totuple(),
|
|
487
|
+
*p3.totuple(), *color.to_rgb(), *normal.totuple(),
|
|
488
|
+
*p1.totuple(), *color.to_rgb(), *normal.totuple(),
|
|
489
|
+
*p3.totuple(), *color.to_rgb(), *normal.totuple(),
|
|
490
|
+
*p4.totuple(), *color.to_rgb(), *normal.totuple()
|
|
491
|
+
], dtype="f4")
|
|
492
|
+
vbo = self.ctx.buffer(vertices.tobytes())
|
|
493
|
+
vao = self.ctx.vertex_array(
|
|
494
|
+
self.prog, [(vbo, "3f 3f 3f", "in_vert", "in_color", "in_normal")]
|
|
495
|
+
)
|
|
496
|
+
self._send_lights()
|
|
497
|
+
self.prog["light_space_matrix"].write(self.light_space_matrix.astype("f4").tobytes())
|
|
498
|
+
self.shadow_depth_tex.use(location=0)
|
|
499
|
+
self.prog["shadow_map"].value = 0
|
|
500
|
+
vao.render()
|
|
501
|
+
vao.release()
|
|
502
|
+
vbo.release()
|
|
503
|
+
|
|
504
|
+
def render_sphere(self, center, radius, color, segments=32, rings=16):
|
|
505
|
+
vertices = []
|
|
506
|
+
for i in range(rings):
|
|
507
|
+
theta1 = math.pi * i / rings
|
|
508
|
+
theta2 = math.pi * (i + 1) / rings
|
|
509
|
+
for j in range(segments):
|
|
510
|
+
phi1 = 2 * math.pi * j / segments
|
|
511
|
+
phi2 = 2 * math.pi * (j + 1) / segments
|
|
512
|
+
p1 = vector3d(radius * math.sin(theta1) * math.cos(phi1),
|
|
513
|
+
radius * math.cos(theta1),
|
|
514
|
+
radius * math.sin(theta1) * math.sin(phi1)) + center
|
|
515
|
+
p2 = vector3d(radius * math.sin(theta2) * math.cos(phi1),
|
|
516
|
+
radius * math.cos(theta2),
|
|
517
|
+
radius * math.sin(theta2) * math.sin(phi1)) + center
|
|
518
|
+
p3 = vector3d(radius * math.sin(theta2) * math.cos(phi2),
|
|
519
|
+
radius * math.cos(theta2),
|
|
520
|
+
radius * math.sin(theta2) * math.sin(phi2)) + center
|
|
521
|
+
p4 = vector3d(radius * math.sin(theta1) * math.cos(phi2),
|
|
522
|
+
radius * math.cos(theta1),
|
|
523
|
+
radius * math.sin(theta1) * math.sin(phi2)) + center
|
|
524
|
+
for tri in [(p1, p2, p3), (p1, p3, p4)]:
|
|
525
|
+
n1 = (tri[0] - center).normalized
|
|
526
|
+
n2 = (tri[1] - center).normalized
|
|
527
|
+
n3 = (tri[2] - center).normalized
|
|
528
|
+
vertices.extend([
|
|
529
|
+
*tri[0].totuple(), *color.to_rgb(), *n1.totuple(),
|
|
530
|
+
*tri[1].totuple(), *color.to_rgb(), *n2.totuple(),
|
|
531
|
+
*tri[2].totuple(), *color.to_rgb(), *n3.totuple(),
|
|
532
|
+
])
|
|
533
|
+
vertices = np.array(vertices, dtype="f4")
|
|
534
|
+
vbo = self.ctx.buffer(vertices.tobytes())
|
|
535
|
+
vao = self.ctx.vertex_array(
|
|
536
|
+
self.prog, [(vbo, "3f 3f 3f", "in_vert", "in_color", "in_normal")]
|
|
537
|
+
)
|
|
538
|
+
self._send_lights()
|
|
539
|
+
self.prog["light_space_matrix"].write(self.light_space_matrix.astype("f4").tobytes())
|
|
540
|
+
self.shadow_depth_tex.use(location=0)
|
|
541
|
+
self.prog["shadow_map"].value = 0
|
|
542
|
+
vao.render()
|
|
543
|
+
vao.release()
|
|
544
|
+
vbo.release()
|
|
545
|
+
|
|
546
|
+
# ------------------------------------------
|
|
547
|
+
# Utility
|
|
548
|
+
# ------------------------------------------
|
|
549
|
+
def _send_lights(self):
|
|
550
|
+
max_lights = 8
|
|
551
|
+
num_lights = min(len(self.lights), max_lights)
|
|
552
|
+
self.prog["num_lights"].value = num_lights
|
|
553
|
+
self.prog["ambient"].value = self.ambient
|
|
554
|
+
for i in range(num_lights):
|
|
555
|
+
light = self.lights[i]
|
|
556
|
+
self.prog[f"lights[{i}].position"].value = light.position.totuple()
|
|
557
|
+
self.prog[f"lights[{i}].color"].value = tuple(c / 255 for c in light.color.to_rgb())
|
|
558
|
+
self.prog[f"lights[{i}].intensity"].value = light.intensity
|
|
559
|
+
|
|
560
|
+
def clear(self, color=Color(26, 26, 31)):
|
|
561
|
+
color_f = np.array(color.to_rgb(), dtype="f4") / 255.0
|
|
562
|
+
self.fbo.clear(*color_f, depth=1.0)
|
|
563
|
+
self.fbo.use()
|
|
564
|
+
|
|
565
|
+
def swap(self):
|
|
566
|
+
self.ctx.copy_framebuffer(dst=self.ctx.screen, src=self.fbo)
|
|
567
|
+
pygame.display.flip()
|
|
568
|
+
|
|
569
|
+
def quit(self):
|
|
570
|
+
pygame.quit()
|
|
571
|
+
|
|
572
|
+
def _load_shader(self, vert_name, frag_name):
|
|
573
|
+
vert_src = pkg_resources.read_text(f"{__package__}.shaders", vert_name)
|
|
574
|
+
frag_src = pkg_resources.read_text(f"{__package__}.shaders", frag_name)
|
|
575
|
+
return self.ctx.program(vertex_shader=vert_src, fragment_shader=frag_src)
|
|
576
|
+
|
|
577
|
+
class Camera:
|
|
578
|
+
def __init__(self, position=None, target=None, up=None, fov=60.0, aspect_ratio=4/3, near=0.1, far=100.0, orbiting=True):
|
|
579
|
+
self.orbiting = orbiting # New: toggle automatic look-at behavior
|
|
580
|
+
self.target = target or vector3d(0, 0, 0)
|
|
581
|
+
self.up = up or vector3d.up
|
|
582
|
+
self.fov = fov
|
|
583
|
+
self.aspect_ratio = aspect_ratio
|
|
584
|
+
self.near = near
|
|
585
|
+
self.far = far
|
|
586
|
+
|
|
587
|
+
# Compute spherical coordinates from initial position
|
|
588
|
+
pos = position or vector3d(3, 2, 3)
|
|
589
|
+
if self.orbiting:
|
|
590
|
+
self._update_spherical(pos)
|
|
591
|
+
self.position = pos
|
|
592
|
+
|
|
593
|
+
self._update_position()
|
|
594
|
+
|
|
595
|
+
def move_to(self, new_position: vector3d):
|
|
596
|
+
"""
|
|
597
|
+
Move the camera to a new position.
|
|
598
|
+
If orbiting is enabled, updates spherical coordinates.
|
|
599
|
+
If orbiting is disabled, just sets position directly.
|
|
600
|
+
"""
|
|
601
|
+
self.position = new_position
|
|
602
|
+
if self.orbiting:
|
|
603
|
+
self._update_spherical(new_position)
|
|
604
|
+
self._update_position()
|
|
605
|
+
|
|
606
|
+
def set_orbiting(self, orbiting: bool):
|
|
607
|
+
"""Enable or disable automatic look-at behavior."""
|
|
608
|
+
self.orbiting = orbiting
|
|
609
|
+
|
|
610
|
+
def _update_spherical(self, pos):
|
|
611
|
+
"""Convert position to spherical coordinates relative to target."""
|
|
612
|
+
dir_vec = pos - self.target
|
|
613
|
+
self.radius = dir_vec.magnitude
|
|
614
|
+
self.azimuth = math.atan2(dir_vec.z, dir_vec.x) # yaw
|
|
615
|
+
self.elevation = math.asin(dir_vec.y / self.radius) # pitch
|
|
616
|
+
|
|
617
|
+
def _update_position(self):
|
|
618
|
+
if self.orbiting:
|
|
619
|
+
x = self.radius * math.cos(self.elevation) * math.cos(self.azimuth)
|
|
620
|
+
y = self.radius * math.sin(self.elevation)
|
|
621
|
+
z = self.radius * math.cos(self.elevation) * math.sin(self.azimuth)
|
|
622
|
+
self.position = self.target + vector3d(x, y, z)
|
|
623
|
+
|
|
624
|
+
look_at = self.target if self.orbiting else self.position + getattr(self, "look_dir", vector3d(0, 0, -1))
|
|
625
|
+
|
|
626
|
+
self.view_matrix = Matrix44.look_at(
|
|
627
|
+
self.position.totuple(),
|
|
628
|
+
look_at.totuple(),
|
|
629
|
+
self.up.totuple()
|
|
630
|
+
)
|
|
631
|
+
self.projection_matrix = Matrix44.perspective_projection(
|
|
632
|
+
self.fov, self.aspect_ratio, self.near, self.far
|
|
633
|
+
)
|
|
634
|
+
|
|
635
|
+
def rotate_around_target(self, delta_azimuth_degrees, delta_elevation_degrees):
|
|
636
|
+
if not self.orbiting:
|
|
637
|
+
return # rotation disabled in free mode
|
|
638
|
+
|
|
639
|
+
self.azimuth += math.radians(delta_azimuth_degrees)
|
|
640
|
+
self.elevation += math.radians(delta_elevation_degrees)
|
|
641
|
+
|
|
642
|
+
# Handle elevation wrapping to allow full rotation without flipping
|
|
643
|
+
while self.elevation > math.pi / 2:
|
|
644
|
+
self.elevation = math.pi - self.elevation
|
|
645
|
+
self.azimuth += math.pi
|
|
646
|
+
self.up = -self.up # flip up vector
|
|
647
|
+
|
|
648
|
+
while self.elevation < -math.pi / 2:
|
|
649
|
+
self.elevation = -math.pi - self.elevation
|
|
650
|
+
self.azimuth += math.pi
|
|
651
|
+
self.up = -self.up # flip up vector
|
|
652
|
+
|
|
653
|
+
self._update_position()
|
|
654
|
+
|
|
655
|
+
def zoom(self, amount):
|
|
656
|
+
self.radius = max(self.radius - amount, 0.01)
|
|
657
|
+
self._update_position()
|
|
658
|
+
|
|
659
|
+
def update_renderer(self, renderer: Renderer):
|
|
660
|
+
renderer.view = self.view_matrix
|
|
661
|
+
renderer.proj = self.projection_matrix
|
|
662
|
+
renderer.mvp = renderer.proj * renderer.view
|
|
663
|
+
renderer.prog["mvp"].write(renderer.mvp.astype("f4").tobytes())
|
|
664
|
+
|
|
665
|
+
class Script:
|
|
666
|
+
def __init__(self, obj, script_path, context):
|
|
667
|
+
self.obj = obj
|
|
668
|
+
self.context = context
|
|
669
|
+
self.script_path = script_path
|
|
670
|
+
self.module = None
|
|
671
|
+
self.cls = None
|
|
672
|
+
self.instance = None
|
|
673
|
+
self.load(script_path)
|
|
674
|
+
|
|
675
|
+
def load(self, path):
|
|
676
|
+
if not os.path.exists(path):
|
|
677
|
+
print(f"[Script] File not found: {path}")
|
|
678
|
+
return
|
|
679
|
+
module_name = os.path.splitext(os.path.basename(path))[0]
|
|
680
|
+
spec = importlib.util.spec_from_file_location(module_name, path)
|
|
681
|
+
module = importlib.util.module_from_spec(spec)
|
|
682
|
+
sys.modules[module_name] = module
|
|
683
|
+
try:
|
|
684
|
+
spec.loader.exec_module(module)
|
|
685
|
+
except Exception as e:
|
|
686
|
+
print(f"[Script] Error loading module {path}: {e}")
|
|
687
|
+
return
|
|
688
|
+
self.module = module
|
|
689
|
+
|
|
690
|
+
# Class is PascalCase version of file name
|
|
691
|
+
class_name = ''.join(word.capitalize() for word in module_name.split('_'))
|
|
692
|
+
if hasattr(module, class_name):
|
|
693
|
+
self.cls = getattr(module, class_name)
|
|
694
|
+
else:
|
|
695
|
+
print(f"[Script] No class '{class_name}' found in {path}")
|
|
696
|
+
|
|
697
|
+
def init_instance(self):
|
|
698
|
+
if self.cls is None or self.instance is not None:
|
|
699
|
+
return
|
|
700
|
+
try:
|
|
701
|
+
self.instance = self.cls(self.obj, self.context)
|
|
702
|
+
except Exception as e:
|
|
703
|
+
print(f"[Script] Failed to instantiate script for {self.obj.name if hasattr(self.obj, "name") else "Engine"}: {e}")
|
|
704
|
+
self.instance = None
|
|
705
|
+
|
|
706
|
+
if self.instance and hasattr(self.instance, "start"):
|
|
707
|
+
try:
|
|
708
|
+
self.instance.start()
|
|
709
|
+
except Exception:
|
|
710
|
+
pass
|
|
711
|
+
|
|
712
|
+
def update(self, dt):
|
|
713
|
+
if self.instance is None:
|
|
714
|
+
return
|
|
715
|
+
self.instance.update(dt)
|
|
716
|
+
|
|
717
|
+
def run(self, func_name):
|
|
718
|
+
if self.instance is None:
|
|
719
|
+
return
|
|
720
|
+
|
|
721
|
+
if hasattr(self.instance, func_name):
|
|
722
|
+
func = getattr(self.instance, func_name)
|
|
723
|
+
func()
|
|
724
|
+
|
|
725
|
+
class EngineError(Exception):
|
|
726
|
+
pass
|