gamengine3d 0.5.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.
Files changed (141) hide show
  1. gamengine3d/__init__.py +18 -0
  2. gamengine3d/assets/__init__.py +0 -0
  3. gamengine3d/assets/circular_crosshair.png +0 -0
  4. gamengine3d/assets/plus_sign_crosshair.png +0 -0
  5. gamengine3d/cli.py +83 -0
  6. gamengine3d/context.py +319 -0
  7. gamengine3d/engine.py +715 -0
  8. gamengine3d/examples/__init__.py +0 -0
  9. gamengine3d/examples/basics.py +66 -0
  10. gamengine3d/examples/parkour.py +285 -0
  11. gamengine3d/examples/player_movement.py +161 -0
  12. gamengine3d/examples/reactor.py +526 -0
  13. gamengine3d/examples/scripts/__init__.py +0 -0
  14. gamengine3d/examples/scripts/bouncer.py +18 -0
  15. gamengine3d/examples/scripts/breaker_coil.py +17 -0
  16. gamengine3d/examples/scripts/breaker_decoder.py +39 -0
  17. gamengine3d/examples/scripts/breaker_gate.py +23 -0
  18. gamengine3d/examples/scripts/breaker_shield.py +28 -0
  19. gamengine3d/examples/scripts/coin.py +12 -0
  20. gamengine3d/examples/scripts/collector.py +13 -0
  21. gamengine3d/examples/scripts/confetti.py +27 -0
  22. gamengine3d/examples/scripts/director.py +213 -0
  23. gamengine3d/examples/scripts/drone.py +21 -0
  24. gamengine3d/examples/scripts/ghost_pulse.py +24 -0
  25. gamengine3d/examples/scripts/horror_atmosphere.py +96 -0
  26. gamengine3d/examples/scripts/interact.py +45 -0
  27. gamengine3d/examples/scripts/orbiter.py +25 -0
  28. gamengine3d/examples/scripts/player_controller.py +165 -0
  29. gamengine3d/examples/scripts/pulse.py +22 -0
  30. gamengine3d/examples/scripts/reactor_core.py +29 -0
  31. gamengine3d/examples/scripts/spin.py +13 -0
  32. gamengine3d/examples/scripts/sway.py +19 -0
  33. gamengine3d/examples/scripts/void_guard.py +26 -0
  34. gamengine3d/examples/transparency.py +92 -0
  35. gamengine3d/game_objects.py +975 -0
  36. gamengine3d/helper.py +720 -0
  37. gamengine3d/obj_reader.py +29 -0
  38. gamengine3d/objects/0.obj +964 -0
  39. gamengine3d/objects/1.obj +48 -0
  40. gamengine3d/objects/2.obj +983 -0
  41. gamengine3d/objects/3.obj +1623 -0
  42. gamengine3d/objects/4.obj +163 -0
  43. gamengine3d/objects/5.obj +861 -0
  44. gamengine3d/objects/6.obj +1314 -0
  45. gamengine3d/objects/7.obj +70 -0
  46. gamengine3d/objects/8.obj +1932 -0
  47. gamengine3d/objects/9.obj +1458 -0
  48. gamengine3d/objects/A_capital.obj +124 -0
  49. gamengine3d/objects/B_capital.obj +1118 -0
  50. gamengine3d/objects/C_capital.obj +1082 -0
  51. gamengine3d/objects/D_capital.obj +548 -0
  52. gamengine3d/objects/E_capital.obj +128 -0
  53. gamengine3d/objects/F_capital.obj +108 -0
  54. gamengine3d/objects/G_capital.obj +1125 -0
  55. gamengine3d/objects/H_capital.obj +128 -0
  56. gamengine3d/objects/I_capital.obj +48 -0
  57. gamengine3d/objects/J_capital.obj +454 -0
  58. gamengine3d/objects/K_capital.obj +125 -0
  59. gamengine3d/objects/L_capital.obj +68 -0
  60. gamengine3d/objects/M_capital.obj +163 -0
  61. gamengine3d/objects/N_capital.obj +112 -0
  62. gamengine3d/objects/O_capital.obj +968 -0
  63. gamengine3d/objects/P_capital.obj +620 -0
  64. gamengine3d/objects/Q_capital.obj +1362 -0
  65. gamengine3d/objects/R_capital.obj +1036 -0
  66. gamengine3d/objects/S_capital.obj +1346 -0
  67. gamengine3d/objects/T_capital.obj +88 -0
  68. gamengine3d/objects/U_capital.obj +860 -0
  69. gamengine3d/objects/V_capital.obj +81 -0
  70. gamengine3d/objects/W_capital.obj +147 -0
  71. gamengine3d/objects/X_capital.obj +136 -0
  72. gamengine3d/objects/Y_capital.obj +103 -0
  73. gamengine3d/objects/Z_capital.obj +90 -0
  74. gamengine3d/objects/__init__.py +0 -0
  75. gamengine3d/objects/a.obj +1920 -0
  76. gamengine3d/objects/ampersand.obj +2186 -0
  77. gamengine3d/objects/asterisk.obj +2512 -0
  78. gamengine3d/objects/at.obj +2682 -0
  79. gamengine3d/objects/b.obj +1104 -0
  80. gamengine3d/objects/backslash.obj +48 -0
  81. gamengine3d/objects/brace_close.obj +1179 -0
  82. gamengine3d/objects/brace_open.obj +1179 -0
  83. gamengine3d/objects/bracket_close.obj +88 -0
  84. gamengine3d/objects/bracket_open.obj +88 -0
  85. gamengine3d/objects/c.obj +1082 -0
  86. gamengine3d/objects/caret.obj +81 -0
  87. gamengine3d/objects/colon.obj +912 -0
  88. gamengine3d/objects/comma.obj +675 -0
  89. gamengine3d/objects/d.obj +861 -0
  90. gamengine3d/objects/dash.obj +48 -0
  91. gamengine3d/objects/dollar.obj +1671 -0
  92. gamengine3d/objects/dot.obj +532 -0
  93. gamengine3d/objects/doublequote.obj +114 -0
  94. gamengine3d/objects/e.obj +1094 -0
  95. gamengine3d/objects/equals.obj +76 -0
  96. gamengine3d/objects/exclamation.obj +1336 -0
  97. gamengine3d/objects/f.obj +660 -0
  98. gamengine3d/objects/g.obj +2694 -0
  99. gamengine3d/objects/greater.obj +81 -0
  100. gamengine3d/objects/h.obj +628 -0
  101. gamengine3d/objects/hash.obj +332 -0
  102. gamengine3d/objects/i.obj +558 -0
  103. gamengine3d/objects/j.obj +824 -0
  104. gamengine3d/objects/k.obj +104 -0
  105. gamengine3d/objects/l.obj +48 -0
  106. gamengine3d/objects/less.obj +81 -0
  107. gamengine3d/objects/m.obj +1177 -0
  108. gamengine3d/objects/n.obj +628 -0
  109. gamengine3d/objects/o.obj +968 -0
  110. gamengine3d/objects/p.obj +861 -0
  111. gamengine3d/objects/paren_close.obj +554 -0
  112. gamengine3d/objects/paren_open.obj +554 -0
  113. gamengine3d/objects/percent.obj +1767 -0
  114. gamengine3d/objects/plus.obj +128 -0
  115. gamengine3d/objects/q.obj +861 -0
  116. gamengine3d/objects/question.obj +1306 -0
  117. gamengine3d/objects/r.obj +608 -0
  118. gamengine3d/objects/s.obj +1478 -0
  119. gamengine3d/objects/semicolon.obj +1185 -0
  120. gamengine3d/objects/singlequote.obj +70 -0
  121. gamengine3d/objects/slash.obj +48 -0
  122. gamengine3d/objects/t.obj +639 -0
  123. gamengine3d/objects/u.obj +618 -0
  124. gamengine3d/objects/underscore.obj +48 -0
  125. gamengine3d/objects/v.obj +81 -0
  126. gamengine3d/objects/w.obj +147 -0
  127. gamengine3d/objects/x.obj +136 -0
  128. gamengine3d/objects/y.obj +92 -0
  129. gamengine3d/objects/z.obj +90 -0
  130. gamengine3d/renderer.py +1390 -0
  131. gamengine3d/shaders/__init__.py +0 -0
  132. gamengine3d/shaders/default.frag +143 -0
  133. gamengine3d/shaders/default.vert +43 -0
  134. gamengine3d/shaders/depth.frag +2 -0
  135. gamengine3d/shaders/depth.vert +9 -0
  136. gamengine3d-0.5.0.dist-info/METADATA +177 -0
  137. gamengine3d-0.5.0.dist-info/RECORD +141 -0
  138. gamengine3d-0.5.0.dist-info/WHEEL +5 -0
  139. gamengine3d-0.5.0.dist-info/entry_points.txt +2 -0
  140. gamengine3d-0.5.0.dist-info/licenses/LICENSE.txt +21 -0
  141. gamengine3d-0.5.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,975 @@
1
+ import numpy as np
2
+ from itertools import product
3
+ from pyrr import Matrix44
4
+ import math
5
+ from .obj_reader import OBJReader
6
+ from .helper import Color, vector3d, Script, Message, EngineError, vector2d, ray_intersects_triangle
7
+ from .renderer import Renderer
8
+ from pathlib import Path
9
+
10
+
11
+ def _aabb_from_corners(corners):
12
+ xs = [c.x for c in corners]
13
+ ys = [c.y for c in corners]
14
+ zs = [c.z for c in corners]
15
+ return vector3d(min(xs), min(ys), min(zs)), vector3d(max(xs), max(ys), max(zs))
16
+
17
+
18
+ _EM_TRI = (1.0, 1.0, 1.0)
19
+ _NO_EM = (0.0, 0.0, 0.0)
20
+
21
+
22
+ def _emit_triplet(emit):
23
+ return _EM_TRI if emit else _NO_EM
24
+
25
+
26
+ def _clamp_alpha(transparency):
27
+ return max(0.0, min(1.0, float(transparency)))
28
+
29
+ class GameObject:
30
+ def __init__(self, name):
31
+ self.name = name
32
+ self.scripts = []
33
+ self.script_paths = []
34
+ self.messages = []
35
+ self.received_message = False
36
+
37
+ def update(self, dt):
38
+ for script in self.scripts:
39
+ script.update(dt)
40
+
41
+ self.received_message = False
42
+
43
+ def draw(self, renderer: Renderer):
44
+ pass
45
+
46
+ def attach(self, file_path, context):
47
+ if isinstance(file_path, str):
48
+ self.script_paths.append(file_path)
49
+ else:
50
+ self.script_paths.append(str(file_path))
51
+ script = Script(self, file_path, context)
52
+ script.init_instance()
53
+ self.scripts.append(script)
54
+
55
+ def attach_scripts(self, scripts, context):
56
+ for path in scripts:
57
+ self.attach(path, context)
58
+
59
+ def init_scripts(self):
60
+ for script in self.scripts:
61
+ script.init_instance()
62
+
63
+ def message(self, message, sender):
64
+ self.messages.append(Message(message=message, sender=sender))
65
+ self.received_message = True
66
+
67
+ class Cuboid(GameObject):
68
+ def __init__(self, pos: vector3d = None,
69
+ size: vector3d = None,
70
+ color: Color = Color.green,
71
+ name: str = "Cuboid",
72
+ rotation: vector3d = None,
73
+ visible: bool = True, emit: bool = False,
74
+ transparency: float = 1.0):
75
+ super().__init__(name)
76
+ self.name = name
77
+ if pos is None:
78
+ pos = vector3d.zero
79
+ if size is None:
80
+ size = vector3d(5)
81
+ if rotation is None:
82
+ rotation = vector3d.zero
83
+ self.pos = pos
84
+ self.size = size
85
+ self.color = color
86
+ self.rotation = rotation
87
+ self.visible = visible
88
+ self.rigid_body = None
89
+ self.emit = emit
90
+ self.transparency = _clamp_alpha(transparency)
91
+
92
+ self.faces = [
93
+ [0, 1, 3, 2],
94
+ [4, 6, 7, 5],
95
+ [0, 4, 5, 1],
96
+ [2, 3, 7, 6],
97
+ [0, 2, 6, 4],
98
+ [1, 5, 7, 3],
99
+ ]
100
+
101
+ self._geom_key = None
102
+ self._cached_verts = None
103
+ self._cached_positions = None
104
+ self._aabb_min = None
105
+ self._aabb_max = None
106
+
107
+ def get_rotation_matrix(self):
108
+ return Matrix44.from_eulers((
109
+ math.radians(self.rotation.x),
110
+ math.radians(self.rotation.y),
111
+ math.radians(self.rotation.z)
112
+ )).transpose()[:3, :3] # extract 3x3 rotation
113
+
114
+ def get_corners(self):
115
+ corners = []
116
+ half_size = self.size / 2
117
+ rot = self.get_rotation_matrix()
118
+
119
+ for dx, dy, dz in product([-1, 1], repeat=3):
120
+ local = np.array([dx * half_size.x, dy * half_size.y, dz * half_size.z])
121
+ rotated = rot @ local
122
+ world = self.pos + vector3d(*rotated)
123
+ corners.append(world)
124
+
125
+ return corners
126
+
127
+ def _get_geometry(self):
128
+ """Return (verts_np, positions_np, aabb_min, aabb_max).
129
+
130
+ The tessellated base is built once; position/radius changes only
131
+ re-apply a numpy offset (fast), so moving objects never rebuild their
132
+ mesh in Python.
133
+ """
134
+ key = (self.rotation.totuple(),
135
+ (self.size.x, self.size.y, self.size.z),
136
+ self.color.to_rgb(), self.emit)
137
+ if getattr(self, "_geom_key", None) != key or self._base_verts is None:
138
+ half_size = self.size / 2
139
+ rot = self.get_rotation_matrix()
140
+ local_corners = []
141
+ for dx, dy, dz in product([-1, 1], repeat=3):
142
+ local = np.array([dx * half_size.x, dy * half_size.y, dz * half_size.z])
143
+ rotated = rot @ local
144
+ local_corners.append(vector3d(*rotated))
145
+
146
+ color = self.color.to_rgb()
147
+ em = _emit_triplet(self.emit)
148
+ vertices = []
149
+
150
+ def push(p1, p2, p3):
151
+ normal = (p2 - p1).cross(p3 - p1).normalized
152
+ for p in (p1, p2, p3):
153
+ vertices.extend([*p.totuple(), *color, *normal.totuple(), *em])
154
+
155
+ for face_idx in self.faces:
156
+ p1, p2, p3, p4 = [local_corners[i] for i in face_idx]
157
+ push(p1, p2, p3)
158
+ push(p1, p3, p4)
159
+
160
+ self._base_verts = np.array(vertices, dtype="f4").reshape(-1, 12)
161
+ xs = [c.x for c in local_corners]
162
+ ys = [c.y for c in local_corners]
163
+ zs = [c.z for c in local_corners]
164
+ self._local_aabb_min = vector3d(min(xs), min(ys), min(zs))
165
+ self._local_aabb_max = vector3d(max(xs), max(ys), max(zs))
166
+ self._geom_key = key
167
+ self._cached_verts = None
168
+ self._cached_pos = None
169
+
170
+ if self._cached_verts is None or self._cached_pos != self.pos.totuple():
171
+ verts = self._base_verts.copy()
172
+ verts[:, :3] += (self.pos.x, self.pos.y, self.pos.z)
173
+ self._cached_verts = verts
174
+ self._cached_positions = verts[:, :3].ravel()
175
+ self._aabb_min = self._local_aabb_min + self.pos
176
+ self._aabb_max = self._local_aabb_max + self.pos
177
+ self._cached_pos = self.pos.totuple()
178
+
179
+ return self._cached_verts, self._cached_positions, self._aabb_min, self._aabb_max
180
+
181
+ def is_point_in(self, point: vector3d) -> bool:
182
+ p = np.array([point.x, point.y, point.z])
183
+ center = np.array([self.pos.x, self.pos.y, self.pos.z])
184
+ half = np.array([self.size.x / 2, self.size.y / 2, self.size.z / 2])
185
+
186
+ rot = self.get_rotation_matrix()
187
+ inv_rot = rot.T
188
+
189
+ local_point = inv_rot @ (p - center)
190
+
191
+ return np.all(np.abs(local_point) <= half + 1e-6)
192
+
193
+ def draw(self, renderer: Renderer):
194
+ if not self.visible:
195
+ return
196
+ if self.transparency <= 0:
197
+ return
198
+ verts, _, amin, amax = self._get_geometry()
199
+ if len(verts) == 0 or not renderer.in_view(amin, amax):
200
+ return
201
+ renderer.queue(verts, alpha=self.transparency)
202
+
203
+ def serialize(self):
204
+ return {
205
+ "type": "cuboid",
206
+ "pos": self.pos.totuple(),
207
+ "size": self.size.totuple(),
208
+ "color": self.color.to_rgb(),
209
+ "name": self.name,
210
+ "rotation": self.rotation.totuple(),
211
+ "scripts": self.script_paths,
212
+ "visible": self.visible,
213
+ "emit": self.emit,
214
+ "transparency": self.transparency,
215
+ }
216
+
217
+ @staticmethod
218
+ def deserialize(data, context):
219
+ pos = data["pos"]
220
+ size = data["size"]
221
+ color = data["color"]
222
+ name = data["name"]
223
+ rotation = data["rotation"]
224
+ scripts = data["scripts"]
225
+ visible = data["visible"]
226
+ emit = data["emit"]
227
+ transparency = data.get("transparency", 1.0)
228
+
229
+ obj = Cuboid(pos=vector3d.fromtuple(pos), color=Color.RGB(*color), size=vector3d.fromtuple(size), name=name, rotation=vector3d.fromtuple(rotation), visible=visible, emit=emit, transparency=transparency)
230
+ obj.attach_scripts(scripts, context)
231
+
232
+ return obj
233
+
234
+ class Sphere(GameObject):
235
+ def __init__(self, pos: vector3d = None,
236
+ radius: float = 5,
237
+ color: Color = Color.green,
238
+ segments: int = 32,
239
+ rings: int = 16,
240
+ name: str = "Sphere", visible=True,
241
+ emit: bool = False,
242
+ transparency: float = 1.0):
243
+ super().__init__(name)
244
+ self.name = name
245
+ if pos is None:
246
+ pos = vector3d.zero
247
+ self.pos = pos
248
+ self.radius = radius
249
+ self.color = color
250
+ self.segments = segments
251
+ self.rings = rings
252
+ self.visible = visible
253
+ self.emit = emit
254
+ self.transparency = _clamp_alpha(transparency)
255
+
256
+ self._geom_key = None
257
+ self._cached_verts = None
258
+ self._cached_positions = None
259
+ self._aabb_min = None
260
+ self._aabb_max = None
261
+
262
+ def is_point_in(self, point: vector3d) -> bool:
263
+ dx = point.x - self.pos.x
264
+ dy = point.y - self.pos.y
265
+ dz = point.z - self.pos.z
266
+ distance_squared = dx*dx + dy*dy + dz*dz
267
+ return distance_squared <= self.radius * self.radius
268
+
269
+ def _get_geometry(self):
270
+ """Unit-direction base is built once; radius + position are applied
271
+ as cheap numpy ops, so spheres that move/resize never rebuild their
272
+ tessellation in Python."""
273
+ key = (self.segments, self.rings, self.color.to_rgb(), self.emit)
274
+ if getattr(self, "_geom_key", None) != key or self._base_dirs is None:
275
+ dirs = []
276
+ for i in range(self.rings):
277
+ theta1 = math.pi * i / self.rings
278
+ theta2 = math.pi * (i + 1) / self.rings
279
+ for j in range(self.segments):
280
+ phi1 = 2 * math.pi * j / self.segments
281
+ phi2 = 2 * math.pi * (j + 1) / self.segments
282
+
283
+ p1 = (math.sin(theta1) * math.cos(phi1), math.cos(theta1), math.sin(theta1) * math.sin(phi1))
284
+ p2 = (math.sin(theta2) * math.cos(phi1), math.cos(theta2), math.sin(theta2) * math.sin(phi1))
285
+ p3 = (math.sin(theta2) * math.cos(phi2), math.cos(theta2), math.sin(theta2) * math.sin(phi2))
286
+ p4 = (math.sin(theta1) * math.cos(phi2), math.cos(theta1), math.sin(theta1) * math.sin(phi2))
287
+
288
+ for tri in (p1, p2, p3, p1, p3, p4):
289
+ dirs.append(tri)
290
+
291
+ n = len(dirs)
292
+ self._base_dirs = np.array(dirs, dtype="f4").reshape(-1, 3)
293
+ color = np.array(self.color.to_rgb(), dtype="f4")
294
+ self._color_block = np.tile(color, (n, 1))
295
+ em = _emit_triplet(self.emit)
296
+ self._em_block = np.tile(np.array(em, dtype="f4"), (n, 1))
297
+ self._geom_key = key
298
+ self._cached_verts = None
299
+ self._cached_pos = None
300
+
301
+ pos_key = (self.pos.x, self.pos.y, self.pos.z, self.radius)
302
+ if self._cached_verts is None or self._cached_pos != pos_key:
303
+ xyz = self._base_dirs * self.radius + (self.pos.x, self.pos.y, self.pos.z)
304
+ verts = np.hstack((xyz, self._color_block, self._base_dirs, self._em_block))
305
+ self._cached_verts = verts
306
+ self._cached_positions = verts[:, :3].ravel()
307
+ r = self.radius
308
+ self._aabb_min = self.pos - vector3d(r, r, r)
309
+ self._aabb_max = self.pos + vector3d(r, r, r)
310
+ self._cached_pos = pos_key
311
+
312
+ return self._cached_verts, self._cached_positions, self._aabb_min, self._aabb_max
313
+
314
+ def draw(self, renderer: Renderer):
315
+ if not self.visible:
316
+ return
317
+ if self.transparency <= 0:
318
+ return
319
+ verts, _, amin, amax = self._get_geometry()
320
+ if len(verts) == 0 or not renderer.in_view(amin, amax):
321
+ return
322
+ renderer.queue(verts, alpha=self.transparency)
323
+
324
+ def serialize(self):
325
+ return {
326
+ "type": "sphere",
327
+ "pos": self.pos.totuple(),
328
+ "color": self.color.to_rgb(),
329
+ "radius": self.radius,
330
+ "segments": self.segments,
331
+ "rings": self.rings,
332
+ "name": self.name,
333
+ "scripts": self.script_paths,
334
+ "visible": self.visible,
335
+ "emit": self.emit,
336
+ "transparency": self.transparency,
337
+ }
338
+
339
+ @staticmethod
340
+ def deserialize(data, context):
341
+ pos = data["pos"]
342
+ color = data["color"]
343
+ radius = data["radius"]
344
+ segments = data["segments"]
345
+ rings = data["rings"]
346
+ name = data["name"]
347
+ scripts = data["scripts"]
348
+ visible = data["visible"]
349
+ emit = data["emit"]
350
+ transparency = data.get("transparency", 1.0)
351
+
352
+ obj = Sphere(pos=vector3d.fromtuple(pos), color=Color.RGB(*color), radius=radius, segments=segments, rings=rings, name=name, visible=visible, emit=emit, transparency=transparency)
353
+ obj.attach_scripts(scripts, context)
354
+
355
+ return obj
356
+
357
+ class Cylinder(GameObject):
358
+ def __init__(self, pos: vector3d = None,
359
+ length: float = 2,
360
+ radius: float = 0.5,
361
+ color: Color = Color.light_yellow,
362
+ segments: int = 32,
363
+ rotation: vector3d = None,
364
+ name: str = "Cylinder", visible: bool = True,
365
+ emit: bool = False,
366
+ transparency: float = 1.0):
367
+ super().__init__(name)
368
+ self.name = name
369
+ if pos is None:
370
+ pos = vector3d.zero
371
+ if rotation is None:
372
+ rotation = vector3d.zero
373
+ self.pos = pos
374
+ self.length = length
375
+ self.radius = radius
376
+ self.color = color
377
+ self.segments = segments
378
+ self.rotation = rotation # Euler angles in degrees
379
+ self.visible = visible
380
+ self.emit = emit
381
+ self.transparency = _clamp_alpha(transparency)
382
+
383
+ self._geom_key = None
384
+ self._cached_verts = None
385
+ self._cached_positions = None
386
+ self._aabb_min = None
387
+ self._aabb_max = None
388
+
389
+ def get_rotation_matrix(self):
390
+ rx, ry, rz = math.radians(self.rotation.x), math.radians(self.rotation.y), math.radians(self.rotation.z)
391
+ cx, sx = math.cos(rx), math.sin(rx)
392
+ cy, sy = math.cos(ry), math.sin(ry)
393
+ cz, sz = math.cos(rz), math.sin(rz)
394
+ # Rotation matrices
395
+ Rx = np.array([[1,0,0],[0,cx,-sx],[0,sx,cx]])
396
+ Ry = np.array([[cy,0,sy],[0,1,0],[-sy,0,cy]])
397
+ Rz = np.array([[cz,-sz,0],[sz,cz,0],[0,0,1]])
398
+ return Rz @ Ry @ Rx # apply in XYZ order
399
+
400
+ def _apply_matrix(self, v: vector3d, m: Matrix44) -> vector3d:
401
+ vec4 = np.array([v.x, v.y, v.z, 1.0], dtype="f4")
402
+ transformed = m @ vec4
403
+ return vector3d(*transformed[:3])
404
+
405
+ def _apply_matrix_normal(self, n: vector3d, m: Matrix44) -> vector3d:
406
+ vec4 = np.array([n.x, n.y, n.z, 0.0], dtype="f4")
407
+ transformed = m @ vec4
408
+ return vector3d(*transformed[:3]).normalized
409
+
410
+ def _get_geometry(self):
411
+ """Tessellation is cached; position is applied as a cheap numpy
412
+ offset when it changes."""
413
+ key = (self.length, self.radius, self.segments,
414
+ self.rotation.totuple(), self.color.to_rgb(), self.emit)
415
+ if getattr(self, "_geom_key", None) != key or self._base_verts is None:
416
+ color = self.color.to_rgb()
417
+ em = _emit_triplet(self.emit)
418
+ vertices = []
419
+
420
+ rot_x = Matrix44.from_x_rotation(math.radians(self.rotation.x))
421
+ rot_y = Matrix44.from_y_rotation(math.radians(self.rotation.y))
422
+ rot_z = Matrix44.from_z_rotation(math.radians(self.rotation.z))
423
+ rot_matrix = rot_z * rot_y * rot_x
424
+
425
+ height = self.length
426
+ for i in range(self.segments):
427
+ theta1 = 2 * math.pi * i / self.segments
428
+ theta2 = 2 * math.pi * (i + 1) / self.segments
429
+
430
+ top1 = self._apply_matrix(vector3d(self.radius * math.cos(theta1), height / 2, self.radius * math.sin(theta1)), rot_matrix)
431
+ top2 = self._apply_matrix(vector3d(self.radius * math.cos(theta2), height / 2, self.radius * math.sin(theta2)), rot_matrix)
432
+ bottom1 = self._apply_matrix(vector3d(self.radius * math.cos(theta1), -height / 2, self.radius * math.sin(theta1)), rot_matrix)
433
+ bottom2 = self._apply_matrix(vector3d(self.radius * math.cos(theta2), -height / 2, self.radius * math.sin(theta2)), rot_matrix)
434
+
435
+ normal1 = self._apply_matrix_normal(vector3d(math.cos(theta1), 0, math.sin(theta1)), rot_matrix)
436
+ normal2 = self._apply_matrix_normal(vector3d(math.cos(theta2), 0, math.sin(theta2)), rot_matrix)
437
+
438
+ for tri, nts in [((top1, bottom1, bottom2), (normal1, normal1, normal2)),
439
+ ((top1, bottom2, top2), (normal1, normal2, normal2))]:
440
+ for p, n in zip(tri, nts):
441
+ vertices.extend([*p.totuple(), *color, *n.totuple(), *em])
442
+
443
+ top_center = self._apply_matrix(vector3d(0, height / 2, 0), rot_matrix)
444
+ normal_top = self._apply_matrix_normal(vector3d(0, 1, 0), rot_matrix)
445
+ for p in (top_center, top2, top1):
446
+ vertices.extend([*p.totuple(), *color, *normal_top.totuple(), *em])
447
+
448
+ bottom_center = self._apply_matrix(vector3d(0, -height / 2, 0), rot_matrix)
449
+ normal_bottom = self._apply_matrix_normal(vector3d(0, -1, 0), rot_matrix)
450
+ for p in (bottom_center, bottom1, bottom2):
451
+ vertices.extend([*p.totuple(), *color, *normal_bottom.totuple(), *em])
452
+
453
+ self._base_verts = np.array(vertices, dtype="f4").reshape(-1, 12)
454
+ amin = vector3d(self._base_verts[:, 0].min(), self._base_verts[:, 1].min(), self._base_verts[:, 2].min())
455
+ amax = vector3d(self._base_verts[:, 0].max(), self._base_verts[:, 1].max(), self._base_verts[:, 2].max())
456
+ self._local_aabb_min, self._local_aabb_max = amin, amax
457
+ self._geom_key = key
458
+ self._cached_verts = None
459
+ self._cached_pos = None
460
+
461
+ if self._cached_verts is None or self._cached_pos != self.pos.totuple():
462
+ verts = self._base_verts.copy()
463
+ verts[:, :3] += (self.pos.x, self.pos.y, self.pos.z)
464
+ self._cached_verts = verts
465
+ self._cached_positions = verts[:, :3].ravel()
466
+ self._aabb_min = self._local_aabb_min + self.pos
467
+ self._aabb_max = self._local_aabb_max + self.pos
468
+ self._cached_pos = self.pos.totuple()
469
+
470
+ return self._cached_verts, self._cached_positions, self._aabb_min, self._aabb_max
471
+
472
+ def is_point_in(self, point: vector3d, eps=1e-9) -> bool:
473
+ p = np.array([point.x, point.y, point.z])
474
+ center = np.array([self.pos.x, self.pos.y, self.pos.z])
475
+
476
+ # Transform point into cylinder local space
477
+ R = self.get_rotation_matrix()
478
+ invR = R.T # inverse rotation
479
+ local = invR @ (p - center)
480
+
481
+ # Check axial bounds (Y axis)
482
+ half_length = self.length / 2
483
+ if not (-half_length - eps <= local[1] <= half_length + eps):
484
+ return False
485
+
486
+ # Check radial distance in XZ plane
487
+ radial_dist_sq = local[0]**2 + local[2]**2
488
+ return radial_dist_sq <= (self.radius + eps)**2
489
+
490
+ def draw(self, renderer: Renderer):
491
+ if not self.visible:
492
+ return
493
+ if self.transparency <= 0:
494
+ return
495
+ verts, _, amin, amax = self._get_geometry()
496
+ if len(verts) == 0 or not renderer.in_view(amin, amax):
497
+ return
498
+ renderer.queue(verts, alpha=self.transparency)
499
+
500
+ def serialize(self):
501
+ return {
502
+ "type": "cylinder",
503
+ "pos": self.pos.totuple(),
504
+ "length": self.length,
505
+ "radius": self.radius,
506
+ "color": self.color.to_rgb(),
507
+ "segments": self.segments,
508
+ "rotation": self.rotation.totuple(),
509
+ "name": self.name,
510
+ "scripts": self.script_paths,
511
+ "visible": self.visible,
512
+ "emit": self.emit,
513
+ "transparency": self.transparency,
514
+ }
515
+
516
+ @staticmethod
517
+ def deserialize(data, context):
518
+ pos = data["pos"]
519
+ length = data["length"]
520
+ radius = data["radius"]
521
+ color = data["color"]
522
+ segments = data["segments"]
523
+ rotation = data["rotation"]
524
+ name = data["name"]
525
+ scripts = data["scripts"]
526
+ visible = data["visible"]
527
+ emit = data["emit"]
528
+ transparency = data.get("transparency", 1.0)
529
+
530
+ obj = Cylinder(pos=vector3d.fromtuple(pos), length=length, radius=radius, color=Color.RGB(*color), segments=segments, rotation=vector3d.fromtuple(rotation), name=name, visible=visible, emit=emit, transparency=transparency)
531
+ obj.attach_scripts(scripts, context)
532
+
533
+ return obj
534
+
535
+ class ObjModel(GameObject):
536
+ def __init__(self, pos: vector3d = None,
537
+ color: Color = Color.white,
538
+ name: str = "ObjModel",
539
+ scale: vector3d = None,
540
+ rotation: vector3d = None,
541
+ file_path: str = "", visible: bool = True, emit: bool = False,
542
+ transparency: float = 1.0):
543
+ super().__init__(name)
544
+ self.name = name
545
+ if pos is None:
546
+ pos = vector3d.zero
547
+ if scale is None:
548
+ scale = vector3d.one
549
+ if rotation is None:
550
+ rotation = vector3d.zero
551
+ self.pos = pos
552
+ self.color = color
553
+ self.file_path = file_path
554
+ self.visible = visible
555
+ self.scale = scale
556
+ self.rotation = rotation
557
+ self.emit = emit
558
+ self.transparency = _clamp_alpha(transparency)
559
+
560
+ self.vertices = []
561
+ self.faces = []
562
+
563
+ self._geom_key = None
564
+ self._cached_verts = None
565
+ self._cached_positions = None
566
+ self._aabb_min = None
567
+ self._aabb_max = None
568
+
569
+ self.load_from_file()
570
+
571
+ def load_from_file(self):
572
+ reader = OBJReader(self.file_path)
573
+ self.vertices, self.faces = reader.read()
574
+
575
+ def rotate_vertex(self, v: vector3d):
576
+ vcopy = v.copy()
577
+ x, y, z = vcopy.x, vcopy.y, vcopy.z
578
+ rx, ry, rz = math.radians(self.rotation.x), math.radians(self.rotation.y), math.radians(self.rotation.z)
579
+
580
+ # Rotate X
581
+ cosx, sinx = math.cos(rx), math.sin(rx)
582
+ y, z = y * cosx - z * sinx, y * sinx + z * cosx
583
+
584
+ # Rotate Y
585
+ cosy, siny = math.cos(ry), math.sin(ry)
586
+ x, z = x * cosy + z * siny, -x * siny + z * cosy
587
+
588
+ # Rotate Z
589
+ cosz, sinz = math.cos(rz), math.sin(rz)
590
+ x, y = x * cosz - y * sinz, x * sinz + y * cosz
591
+
592
+ return vector3d(x, y, z)
593
+
594
+ def _get_geometry(self):
595
+ """Tessellation is cached; position is applied as a cheap numpy
596
+ offset when it changes."""
597
+ key = (self.scale.totuple(), self.rotation.totuple(),
598
+ self.color.to_rgb(), self.emit)
599
+ if getattr(self, "_geom_key", None) != key or self._base_verts is None:
600
+ color = self.color.to_rgb()
601
+ em = _emit_triplet(self.emit)
602
+ vertices = []
603
+ mins = [float("inf")] * 3
604
+ maxs = [-float("inf")] * 3
605
+
606
+ for face in self.faces:
607
+ p1 = self.rotate_vertex(self.vertices[face[0]]) * self.scale
608
+ p2 = self.rotate_vertex(self.vertices[face[1]]) * self.scale
609
+ p3 = self.rotate_vertex(self.vertices[face[2]]) * self.scale
610
+ normal = (p2 - p1).cross(p3 - p1).normalized
611
+ for p in (p1, p2, p3):
612
+ vertices.extend([*p.totuple(), *color, *normal.totuple(), *em])
613
+ for axis, comp in enumerate(p.totuple()):
614
+ mins[axis] = min(mins[axis], comp)
615
+ maxs[axis] = max(maxs[axis], comp)
616
+
617
+ self._base_verts = np.array(vertices, dtype="f4").reshape(-1, 12) if vertices else np.zeros((0, 12), dtype="f4")
618
+ self._local_aabb_min = vector3d(*mins)
619
+ self._local_aabb_max = vector3d(*maxs)
620
+ self._geom_key = key
621
+ self._cached_verts = None
622
+ self._cached_pos = None
623
+
624
+ if self._cached_verts is None or self._cached_pos != self.pos.totuple():
625
+ verts = self._base_verts.copy()
626
+ verts[:, :3] += (self.pos.x, self.pos.y, self.pos.z)
627
+ self._cached_verts = verts
628
+ self._cached_positions = verts[:, :3].ravel()
629
+ self._aabb_min = self._local_aabb_min + self.pos
630
+ self._aabb_max = self._local_aabb_max + self.pos
631
+ self._cached_pos = self.pos.totuple()
632
+
633
+ return self._cached_verts, self._cached_positions, self._aabb_min, self._aabb_max
634
+
635
+ def draw(self, renderer: Renderer):
636
+ if not self.visible:
637
+ return
638
+ if self.transparency <= 0:
639
+ return
640
+ verts, _, amin, amax = self._get_geometry()
641
+ if len(verts) == 0 or not renderer.in_view(amin, amax):
642
+ return
643
+ renderer.queue(verts, alpha=self.transparency)
644
+
645
+ def is_point_in(self, point: vector3d) -> bool:
646
+ if not self.faces or not self.vertices:
647
+ return False
648
+
649
+ ray_dir = vector3d(1, 0, 0) # +X direction
650
+ intersections = 0
651
+
652
+ for face in self.faces:
653
+ v0 = self.rotate_vertex(self.vertices[face[0]]) * self.scale + self.pos
654
+ v1 = self.rotate_vertex(self.vertices[face[1]]) * self.scale + self.pos
655
+ v2 = self.rotate_vertex(self.vertices[face[2]]) * self.scale + self.pos
656
+
657
+ if ray_intersects_triangle(point, ray_dir, v0, v1, v2):
658
+ intersections += 1
659
+
660
+ return (intersections % 2) == 1
661
+
662
+ def get_size(self):
663
+ """Compute axis-aligned bounding box after rotation and scaling."""
664
+ if not self.vertices:
665
+ return None # No vertices loaded
666
+
667
+ transformed = []
668
+ for v in self.vertices:
669
+ rotated = self.rotate_vertex(v)
670
+ scaled = vector3d(rotated.x * self.scale.x,
671
+ rotated.y * self.scale.y,
672
+ rotated.z * self.scale.z)
673
+ transformed.append(scaled + self.pos)
674
+
675
+ xs = [v.x for v in transformed]
676
+ ys = [v.y for v in transformed]
677
+ zs = [v.z for v in transformed]
678
+
679
+ min_corner = vector3d(min(xs), min(ys), min(zs))
680
+ max_corner = vector3d(max(xs), max(ys), max(zs))
681
+ return min_corner, max_corner
682
+
683
+ def serialize(self):
684
+ return {
685
+ "type": "obj-model",
686
+ "pos": self.pos.totuple(),
687
+ "color": self.color.to_rgb(),
688
+ "name": self.name,
689
+ "scripts": self.script_paths,
690
+ "scale": self.scale.totuple(),
691
+ "rotation": self.rotation.totuple(), # Serialize rotation
692
+ "file_path": self.file_path,
693
+ "visible": self.visible,
694
+ "emit": self.emit,
695
+ "transparency": self.transparency,
696
+ }
697
+
698
+ @staticmethod
699
+ def deserialize(data, context):
700
+ pos = vector3d.fromtuple(data["pos"])
701
+ color = Color.RGB(*data["color"])
702
+ name = data["name"]
703
+ scripts = data["scripts"]
704
+ scale = vector3d.fromtuple(data["scale"])
705
+ rotation = vector3d.fromtuple(data.get("rotation", (0,0,0)))
706
+ visible = data["visible"]
707
+ file_path = data["file_path"]
708
+ emit = data["emit"]
709
+ transparency = data.get("transparency", 1.0)
710
+
711
+ obj = ObjModel(pos=pos, name=name, color=color, scale=scale, rotation=rotation, visible=visible, file_path=file_path, emit=emit, transparency=transparency)
712
+ obj.attach_scripts(scripts, context)
713
+ return obj
714
+
715
+ def __repr__(self):
716
+ return f"ObjModel(file_path={self.file_path}, name={self.name}, faces={len(self.faces)})"
717
+
718
+ class Text(GameObject):
719
+ def __init__(self, pos: vector3d = None,
720
+ text: str = "0",
721
+ color: Color = Color.light_green,
722
+ scale: vector3d = None,
723
+ name: str = "Text",
724
+ visible: bool = True,
725
+ spacing: float = .2,
726
+ rotation: vector3d = None,
727
+ center: bool = False, emit: bool = False,
728
+ transparency: float = 1.0):
729
+ super().__init__(name)
730
+ self.name = name
731
+ if pos is None:
732
+ pos = vector3d.zero
733
+ if scale is None:
734
+ scale = vector3d.one
735
+ if rotation is None:
736
+ rotation = vector3d.zero
737
+ self.pos = pos
738
+ self._text = text # Use internal variable for property setter
739
+ self.color = color
740
+ self.scale = scale
741
+ self.visible = visible
742
+ self.spacing = spacing
743
+ self.rotation = rotation
744
+ self.center = center
745
+ self.script_paths = []
746
+ self.emit = emit
747
+ self.transparency = _clamp_alpha(transparency)
748
+
749
+ self.symbol_map = {
750
+ '!': "exclamation",
751
+ '@': "at",
752
+ '#': "hash",
753
+ '$': "dollar",
754
+ '%': "percent",
755
+ '^': "caret",
756
+ '&': "ampersand",
757
+ '*': "asterisk",
758
+ '(': "paren_open",
759
+ ')': "paren_close",
760
+ "'": "singlequote",
761
+ '"': "doublequote",
762
+ ';': "semicolon",
763
+ ':': "colon",
764
+ '[': "bracket_open",
765
+ ']': "bracket_close",
766
+ '{': "brace_open",
767
+ '}': "brace_close",
768
+ '+': "plus",
769
+ '=': "equals",
770
+ '_': "underscore",
771
+ '-': "dash",
772
+ ',': "comma",
773
+ '<': "less",
774
+ '>': "greater",
775
+ '.': "dot",
776
+ '?': "question",
777
+ '/': "slash",
778
+ '\\': "backslash"
779
+ }
780
+ self.digits = []
781
+ self.create_chars()
782
+
783
+ @property
784
+ def text(self):
785
+ return self._text
786
+
787
+ @text.setter
788
+ def text(self, value):
789
+ self._text = value
790
+ self.create_chars()
791
+
792
+ def create_chars(self):
793
+ digits = []
794
+ sizes = []
795
+ package_folder = Path(__file__).parent
796
+
797
+ # Helper function to get the filename for a character
798
+ def get_obj_file(char):
799
+ if char.isupper() and char.isalpha():
800
+ return f"{char}_capital.obj"
801
+ elif char.islower() or char.isdigit():
802
+ return f"{char}.obj"
803
+ elif char in self.symbol_map:
804
+ return f"{self.symbol_map[char]}.obj"
805
+ else:
806
+ raise EngineError(f"Invalid character '{char}' in text '{self._text}'")
807
+
808
+ # First pass — compute widths
809
+ for char in self._text:
810
+ file_path = package_folder / "objects" / get_obj_file(char)
811
+ tmp = ObjModel(
812
+ pos=self.pos,
813
+ color=self.color,
814
+ scale=self.scale,
815
+ rotation=self.rotation,
816
+ file_path=str(file_path),
817
+ visible=False, # temporary just for size
818
+ transparency=self.transparency,
819
+ )
820
+ min_corner, max_corner = tmp.get_size()
821
+ width = max_corner.x - min_corner.x
822
+ sizes.append(width)
823
+
824
+ total_width = sum(sizes) + self.spacing * (len(sizes) - 1)
825
+ start_x = -total_width / 2.0 if self.center else 0.0
826
+
827
+ # Second pass — actually create digit objects
828
+ x_offset = start_x
829
+ for char, width in zip(self._text, sizes):
830
+ file_path = package_folder / "objects" / get_obj_file(char)
831
+ digit_model = ObjModel(
832
+ pos=self.pos + vector3d(x_offset, 0, 0),
833
+ color=self.color,
834
+ scale=self.scale,
835
+ rotation=self.rotation,
836
+ file_path=str(file_path),
837
+ visible=self.visible,
838
+ emit=self.emit,
839
+ transparency=self.transparency,
840
+ )
841
+ digits.append(digit_model)
842
+ x_offset += width + self.spacing
843
+
844
+ self.digits = digits
845
+
846
+ def draw(self, renderer: Renderer):
847
+ if not self.visible:
848
+ return
849
+
850
+ # Sync transparency to the per-character digit models so changes to
851
+ # Text.transparency take effect without recreating the glyphs.
852
+ for digit in self.digits:
853
+ if digit.transparency != self.transparency:
854
+ digit.transparency = self.transparency
855
+
856
+ for digit in self.digits:
857
+ digit.draw(renderer)
858
+
859
+ def serialize(self):
860
+ return {
861
+ "type": "text",
862
+ "pos": self.pos.totuple(),
863
+ "text": self._text,
864
+ "color": self.color.to_rgb(),
865
+ "scale": self.scale.totuple(),
866
+ "rotation": self.rotation.totuple(),
867
+ "spacing": self.spacing,
868
+ "name": self.name,
869
+ "scripts": self.script_paths,
870
+ "visible": self.visible,
871
+ "center": self.center,
872
+ "emit": self.emit,
873
+ "transparency": self.transparency,
874
+ }
875
+
876
+ @staticmethod
877
+ def deserialize(data, context):
878
+ pos = vector3d.fromtuple(data["pos"])
879
+ text = data["text"]
880
+ color = Color.RGB(*data["color"])
881
+ scale = vector3d.fromtuple(data["scale"])
882
+ rotation = vector3d.fromtuple(data.get("rotation", (0,0,0)))
883
+ spacing = data.get("spacing", 0.05)
884
+ name = data["name"]
885
+ scripts = data["scripts"]
886
+ visible = data["visible"]
887
+ center = data.get("center", False)
888
+ emit = data["emit"]
889
+ transparency = data.get("transparency", 1.0)
890
+
891
+ obj = Text(pos=pos, text=text, color=color, scale=scale,
892
+ rotation=rotation, spacing=spacing, name=name, visible=visible,
893
+ center=center, emit=emit, transparency=transparency)
894
+ obj.attach_scripts(scripts, context)
895
+
896
+ return obj
897
+
898
+ class ImageOverlay(GameObject):
899
+ def __init__(self, key: str, pos: vector2d = None, scale: vector2d = None, rotation: float = 0.0, flip_x: bool = False, flip_y: bool = False, name: str = "Image Overlay", visible: bool = True,
900
+ transparency: float = 1.0):
901
+ super().__init__(name)
902
+
903
+ if pos is None:
904
+ pos = vector2d.zero
905
+ if scale is None:
906
+ scale = vector2d.one
907
+ self.name = name
908
+ self.pos = pos
909
+ self.scale = scale
910
+ self.rotation = rotation
911
+ self.flip_x = flip_x
912
+ self.flip_y = flip_y
913
+ self.image = key
914
+ self.visible = visible
915
+ self.transparency = _clamp_alpha(transparency)
916
+
917
+ def draw(self, renderer: Renderer):
918
+ if not self.visible:
919
+ return
920
+ if self.transparency <= 0:
921
+ return
922
+
923
+ renderer.render_image(
924
+ key=self.image,
925
+ position=self.pos,
926
+ scale=self.scale,
927
+ rotation=self.rotation,
928
+ flip_x=self.flip_x,
929
+ flip_y=self.flip_y,
930
+ alpha=self.transparency,
931
+ )
932
+
933
+ def serialize(self):
934
+ return {
935
+ "type": "image-overlay",
936
+ "pos": self.pos.totuple(),
937
+ "key": self.image,
938
+ "scale": self.scale.totuple(),
939
+ "rotation": self.rotation,
940
+ "flip_x": self.flip_x,
941
+ "flip_y": self.flip_y,
942
+ "name": self.name,
943
+ "visible": self.visible,
944
+ "scripts": self.script_paths,
945
+ "transparency": self.transparency,
946
+ }
947
+
948
+ @staticmethod
949
+ def deserialize(data, context):
950
+ pos = vector2d.fromtuple(data["pos"])
951
+ key = data["key"]
952
+ scale = vector2d.fromtuple(data["scale"])
953
+ rotation = data["rotation"]
954
+ flip_x = data["flip_x"]
955
+ flip_y = data["flip_y"]
956
+ name = data["name"]
957
+ visible = data["visible"]
958
+ scripts = data["scripts"]
959
+ transparency = data.get("transparency", 1.0)
960
+
961
+ obj = ImageOverlay(
962
+ pos=pos,
963
+ key=key,
964
+ scale=scale,
965
+ rotation=rotation,
966
+ flip_x=flip_x,
967
+ flip_y=flip_y,
968
+ name=name,
969
+ visible=visible,
970
+ transparency=transparency,
971
+ )
972
+
973
+ obj.attach_scripts(scripts, context)
974
+
975
+ return obj