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,1390 @@
1
+ import math
2
+ import moderngl
3
+ import pygame
4
+ from pygame.locals import DOUBLEBUF, OPENGL
5
+ import importlib.resources as pkg_resources
6
+ import numpy as np
7
+ import os
8
+ import subprocess
9
+ from pyrr import Matrix44
10
+ from .helper import vector3d, ShadowVolume, vector2d
11
+
12
+ _GPU_CHECKED = False
13
+ _HAS_NVIDIA = False
14
+
15
+
16
+ def detect_nvidia():
17
+ global _GPU_CHECKED, _HAS_NVIDIA
18
+ if not _GPU_CHECKED:
19
+ _GPU_CHECKED = True
20
+ try:
21
+ r = subprocess.run(["nvidia-smi", "-L"], capture_output=True, timeout=5)
22
+ _HAS_NVIDIA = r.returncode == 0
23
+ except Exception:
24
+ _HAS_NVIDIA = False
25
+ return _HAS_NVIDIA
26
+
27
+
28
+ def set_gpu_preference(gpu="auto"):
29
+ """Select the GL device before the context is created.
30
+
31
+ On X11/GLX the GPU is chosen by the driver library the window uses, which
32
+ can be steered with PRIME offload env vars. Set them before any GL context
33
+ is created (Renderer.__init__ does that). Values: "auto", "nvidia", "intel",
34
+ or the GAMENGINE3D_GPU env var.
35
+ """
36
+ gpu = gpu or os.environ.get("GAMENGINE3D_GPU", "auto")
37
+ gpu = gpu.lower()
38
+ if gpu == "intel":
39
+ os.environ.pop("__GLX_VENDOR_LIBRARY_NAME", None)
40
+ os.environ["__NV_PRIME_RENDER_OFFLOAD"] = "0"
41
+ elif gpu == "nvidia" or (gpu == "auto" and detect_nvidia()):
42
+ os.environ.setdefault("__NV_PRIME_RENDER_OFFLOAD", "1")
43
+ os.environ.setdefault("__GLX_VENDOR_LIBRARY_NAME", "nvidia")
44
+ return gpu
45
+
46
+ class Renderer:
47
+ def __init__(self, width=800, height=600, flags=DOUBLEBUF | OPENGL, gpu="auto", shadow_size=2048):
48
+ self._gpu = set_gpu_preference(gpu)
49
+ pygame.init()
50
+ self.screen = pygame.display.set_mode((width, height), flags)
51
+ self.ctx = moderngl.create_context()
52
+ self._gpu_name = self.ctx.info.get("GL_RENDERER", "unknown")
53
+ print(f"[gamengine3d] OpenGL renderer: {self._gpu_name}")
54
+ if self._gpu == "nvidia" and "nvidia" not in self._gpu_name.lower():
55
+ print("[gamengine3d] WARNING: requested NVIDIA GPU but the active "
56
+ "renderer is not NVIDIA; check nvidia-smi/driver install.")
57
+ self.ctx.viewport = (0, 0, width, height)
58
+ # MSAA is off by default: on software GL the interpolated
59
+ # light-space coordinates used for shadow-map compares become corrupt
60
+ # when rendering to a multisampled main framebuffer.
61
+ self.samples = 0
62
+ self.color_tex = self.ctx.texture((width, height), 3, samples=self.samples)
63
+ self.depth_rbo = self.ctx.depth_renderbuffer((width, height), samples=self.samples)
64
+ self.fbo = self.ctx.framebuffer(color_attachments=[self.color_tex], depth_attachment=self.depth_rbo)
65
+ self.lights = []
66
+ self.frame_emissives = []
67
+ self.width = width
68
+ self.height = height
69
+ self.ambient = 0.2
70
+ self.ctx.enable(moderngl.DEPTH_TEST)
71
+ self.MAX_VERTICES = 500_000
72
+
73
+ self.prog = self._load_shader("default.vert", "default.frag")
74
+ self.prog["model"].write(np.eye(4, dtype="f4").tobytes())
75
+ self.proj = Matrix44.perspective_projection(60.0, width / height, 0.1, 100.0)
76
+ self.view = Matrix44.look_at(
77
+ eye=(3.0, 2.0, 3.0),
78
+ target=(0.0, 0.0, 0.0),
79
+ up=(0.0, 1.0, 0.0)
80
+ )
81
+ self.mvp = self.proj * self.view
82
+ self.prog["mvp"].write(self.mvp.astype("f4").tobytes())
83
+ self.prog["ambient"].value = self.ambient
84
+ try:
85
+ self.prog["object_alpha"].value = 1.0
86
+ except Exception:
87
+ pass
88
+
89
+
90
+ # --- Shadow configuration: support multiple per-light shadow maps ---
91
+ # Runtime toggle: set renderer.shadows = False to disable shadow rendering/binding
92
+ self.shadows = True
93
+ # Shadow map resolution (reduce if VRAM is tight)
94
+ self.shadow_size = shadow_size
95
+ # Maximum shadow maps to allocate (must match shader MAX_LIGHTS)
96
+ self.max_shadow_maps = 8
97
+ # Pre-create depth textures and FBOs, one per potential casting light
98
+ self.shadow_depth_textures = [
99
+ self.ctx.depth_texture((self.shadow_size, self.shadow_size))
100
+ for _ in range(self.max_shadow_maps)
101
+ ]
102
+ for tex in self.shadow_depth_textures:
103
+ try:
104
+ tex.repeat_x = False
105
+ tex.repeat_y = False
106
+ except Exception:
107
+ pass
108
+ self.shadow_fbos = [self.ctx.framebuffer(depth_attachment=tex) for tex in self.shadow_depth_textures]
109
+ # Per-light light-space matrices (uploaded to shader each frame)
110
+ self.light_space_matrices = [np.eye(4, dtype="f4") for _ in range(self.max_shadow_maps)]
111
+
112
+ # depth shader (unchanged)
113
+ self.depth_prog = self._load_shader("depth.vert", "depth.frag")
114
+
115
+ self._shadow_maps_rendered = 0
116
+
117
+ # Bind light-space matrices and shadow-map samplers on the main program.
118
+ # Light i reads shadow_maps[slot] on unit (slot + 1); unit 0 stays
119
+ # reserved for overlays. The light->slot mapping is uploaded per frame.
120
+ ident8 = np.tile(np.eye(4, dtype="f4"), (self.max_shadow_maps, 1, 1))
121
+ self.prog["light_space_matrix"].write(ident8.tobytes())
122
+ self.prog["shadow_maps"].value = tuple(range(1, self.max_shadow_maps + 1))
123
+ self.prog["light_to_shadow_map"].value = (-1,) * self.max_shadow_maps
124
+ self.prog["shadow_texel"].value = 1.0 / self.shadow_size
125
+
126
+ self.frame_vertices = []
127
+ self.frame_vertex_arrays = []
128
+ self._frustum_planes = None
129
+ self._last_lights = None
130
+ self.vbo = self.ctx.buffer(reserve=self.MAX_VERTICES * 4 * 12)
131
+
132
+ self.vao = self.ctx.vertex_array(
133
+ self.prog,
134
+ [(self.vbo, "3f 3f 3f 3f", "in_vert", "in_color", "in_normal", "in_emission")]
135
+ )
136
+
137
+ self.shadow_volume = ShadowVolume(minx=-50, maxx=50, miny=-50, maxy=50, minz=1, maxz=100)
138
+
139
+ # Persistent buffers for the depth pass: one shared VBO re-written per
140
+ # light each frame (avoids allocating GPU buffers per light per frame).
141
+ self.depth_vbo = self.ctx.buffer(reserve=self.MAX_VERTICES * 4 * 3)
142
+ self.depth_vao = self.ctx.vertex_array(
143
+ self.depth_prog,
144
+ [(self.depth_vbo, "3f", "in_vert")]
145
+ )
146
+ # Per-light shadow map slot (-1 = no map for this light this frame).
147
+ self._light_to_map = [-1] * self.max_shadow_maps
148
+ # Per-light reuse state: last signature and the slot it rendered into.
149
+ self._last_light_sigs = {}
150
+ self._light_slots_prev = {}
151
+
152
+ self._images = {}
153
+ self._overlay_queue = []
154
+ self._overlay_prog = None
155
+ self.frame_transparents = []
156
+
157
+ def resize(self, width, height):
158
+ self.width = width
159
+ self.height = height
160
+ pygame.display.set_mode((width, height), pygame.OPENGL | pygame.DOUBLEBUF | pygame.RESIZABLE)
161
+
162
+ # just update viewport, don’t create a new context
163
+ self.ctx.viewport = (0, 0, width, height)
164
+
165
+ # update projection matrix
166
+ aspect = width / height
167
+ self.proj = Matrix44.perspective_projection(60.0, aspect, 0.1, 100.0)
168
+ self.mvp = self.proj * self.view
169
+ self.prog["mvp"].write(self.mvp.astype("f4").tobytes())
170
+
171
+ # resize textures and framebuffers
172
+ self.color_tex.release()
173
+ self.color_tex = self.ctx.texture((width, height), 3, samples=self.samples)
174
+
175
+ self.depth_rbo.release()
176
+ self.depth_rbo = self.ctx.depth_renderbuffer((width, height), samples=self.samples)
177
+
178
+ self.fbo.release()
179
+ self.fbo = self.ctx.framebuffer(color_attachments=[self.color_tex], depth_attachment=self.depth_rbo)
180
+
181
+ self._send_lights()
182
+
183
+ def add_light(self, light):
184
+ self.lights.append(light)
185
+
186
+ def _compute_normal(self, p1, p2, p3):
187
+ u = p2 - p1
188
+ v = p3 - p1
189
+ return u.cross(v).normalized
190
+
191
+ # ------------------------------------------------------------------
192
+ # Frustum culling
193
+ # ------------------------------------------------------------------
194
+ def _update_frustum(self):
195
+ """Extract the 6 view-frustum planes (normalized, inward = >= 0)
196
+ from the current projection * view matrix."""
197
+ m = self.mvp
198
+ rows = [
199
+ [m[0][i], m[1][i], m[2][i], m[3][i]]
200
+ for i in range(4)
201
+ ]
202
+ r3 = rows[3]
203
+ planes = []
204
+ for r in (rows[0], rows[1], rows[2]):
205
+ planes.append((r3[0] + r[0], r3[1] + r[1], r3[2] + r[2], r3[3] + r[3]))
206
+ planes.append((r3[0] - r[0], r3[1] - r[1], r3[2] - r[2], r3[3] - r[3]))
207
+ planes.append((r3[0] + rows[2][0], r3[1] + rows[2][1], r3[2] + rows[2][2], r3[3] + rows[2][3]))
208
+ planes.append((r3[0] - rows[2][0], r3[1] - rows[2][1], r3[2] - rows[2][2], r3[3] - rows[2][3]))
209
+
210
+ out = []
211
+ for a, b, c, d in planes:
212
+ n = math.sqrt(a * a + b * b + c * c)
213
+ if n < 1e-9:
214
+ out.append((0.0, 0.0, 0.0, 0.0))
215
+ else:
216
+ out.append((a / n, b / n, c / n, d / n))
217
+ self._frustum_planes = out
218
+
219
+ def in_view(self, aabb_min, aabb_max) -> bool:
220
+ """True if the given AABB is at least partially inside the camera
221
+ frustum (conservative; no false negatives)."""
222
+ planes = self._frustum_planes
223
+ if planes is None:
224
+ return True
225
+ for a, b, c, d in planes:
226
+ if a == 0.0 and b == 0.0 and c == 0.0:
227
+ continue
228
+ px = aabb_max.x if a >= 0 else aabb_min.x
229
+ py = aabb_max.y if b >= 0 else aabb_min.y
230
+ pz = aabb_max.z if c >= 0 else aabb_min.z
231
+ if a * px + b * py + c * pz + d < 0:
232
+ return False
233
+ return True
234
+
235
+ def _sphere_in_frustum(self, cx, cy, cz, radius) -> bool:
236
+ planes = self._frustum_planes
237
+ if planes is None:
238
+ return True
239
+ for a, b, c, d in planes:
240
+ if a == 0.0 and b == 0.0 and c == 0.0:
241
+ continue
242
+ if a * cx + b * cy + c * cz + d < -radius:
243
+ return False
244
+ return True
245
+
246
+ def queue(self, verts_np, alpha: float = 1.0):
247
+ """Queue a cached numpy vertex array (N x 12 floats, flattened) for
248
+ the main render pass.
249
+
250
+ alpha in [0,1]: 1.0 = opaque (batched with all other opaque geometry);
251
+ < 1.0 = transparent (drawn in a separate pass, sorted back-to-front
252
+ and alpha-blended)."""
253
+ if not len(verts_np):
254
+ return
255
+ if alpha >= 1.0:
256
+ self.frame_vertex_arrays.append(verts_np)
257
+ else:
258
+ self.frame_transparents.append((alpha, verts_np))
259
+
260
+ def compute_light_matrix(self, light):
261
+ """Legacy: fixed shadow-volume light-space matrix."""
262
+ return self._build_light_matrix(
263
+ light,
264
+ (self.shadow_volume.minx, self.shadow_volume.maxx,
265
+ self.shadow_volume.miny, self.shadow_volume.maxy,
266
+ self.shadow_volume.minz, self.shadow_volume.maxz)
267
+ )
268
+
269
+ def _caster_bottom_y(self, obj):
270
+ t = type(obj).__name__
271
+ if t == "Cuboid":
272
+ return obj.pos.y - obj.size.y / 2
273
+ if t == "Sphere":
274
+ return obj.pos.y - obj.radius
275
+ if t == "Cylinder":
276
+ return obj.pos.y - obj.length / 2
277
+ if t == "ObjModel":
278
+ amin = getattr(obj, "_aabb_min", None)
279
+ if amin is not None:
280
+ return amin.y
281
+ try:
282
+ lo, _ = obj.get_size()
283
+ except Exception:
284
+ return None
285
+ return lo.y if lo is not None else None
286
+ return None
287
+
288
+ def _build_light_view(self, light):
289
+ """World -> light-space view matrix (light looks at the origin)."""
290
+ eye = light.position.totuple()
291
+ target = (0.0, 0.0, 0.0)
292
+ up = (0.0, 1.0, 0.0)
293
+
294
+ fwd = np.array(target) - np.array(eye)
295
+ fwd = fwd / np.linalg.norm(fwd)
296
+ s = np.cross(fwd, up)
297
+ if np.linalg.norm(s) < 1e-6:
298
+ # Degenerate: light directly above/below target (fwd parallel to up).
299
+ up = np.array([1.0, 0.0, 0.0])
300
+ s = np.cross(fwd, up)
301
+ s = s / np.linalg.norm(s)
302
+ u = np.cross(s, fwd)
303
+
304
+ view = np.eye(4)
305
+ view[0, 0:3] = s
306
+ view[1, 0:3] = u
307
+ view[2, 0:3] = -fwd
308
+ view[0, 3] = -s.dot(eye)
309
+ view[1, 3] = -u.dot(eye)
310
+ view[2, 3] = fwd.dot(eye)
311
+ return view
312
+
313
+ def _build_light_matrix(self, light, bounds):
314
+ """Ortho * LookAt for the given (minx, maxx, miny, maxy, minz, maxz)
315
+ bounds in light space."""
316
+ minx, maxx, miny, maxy, minz, maxz = bounds
317
+ view = self._build_light_view(light)
318
+
319
+ proj = np.eye(4)
320
+ proj[0, 0] = 2.0 / (maxx - minx)
321
+ proj[1, 1] = 2.0 / (maxy - miny)
322
+ proj[2, 2] = -2.0 / (maxz - minz)
323
+ proj[0, 3] = -(maxx + minx) / (maxx - minx)
324
+ proj[1, 3] = -(maxy + miny) / (maxy - miny)
325
+ proj[2, 3] = -(maxz + minz) / (maxz - minz)
326
+
327
+ return proj @ view
328
+
329
+ def _fit_light_bounds(self, light, in_range):
330
+ """Fit tight ortho bounds to the shadow casters in light space.
331
+ in_range: list of (center, radius, obj) bounding spheres.
332
+ Returns (mat, view, bounds) or None when nothing can cast.
333
+
334
+ OpenGL view convention: geometry in FRONT of the light has negative
335
+ view-space z, so the ortho near/far distances come from the closest /
336
+ farthest points that way.
337
+ """
338
+ view = self._build_light_view(light)
339
+
340
+ minx = miny = float("inf")
341
+ maxx = maxy = -float("inf")
342
+ near_dist = 0.0 # closest approach toward the light
343
+ far_dist = 0.0 # farthest point along the light direction
344
+
345
+ for center, radius, obj in in_range:
346
+ vc = view @ np.array([center.x, center.y, center.z, 1.0])
347
+ x, y, z = vc[0], vc[1], vc[2]
348
+ if z - radius > -0.5:
349
+ continue # fully behind the light (or at it)
350
+ minx = min(minx, x - radius)
351
+ maxx = max(maxx, x + radius)
352
+ miny = min(miny, y - radius)
353
+ maxy = max(maxy, y + radius)
354
+ near_dist = max(near_dist, -(z + radius))
355
+ far_dist = max(far_dist, -(z - radius))
356
+
357
+ if far_dist <= 0.0:
358
+ return None
359
+
360
+ near = max(near_dist, 0.5) # keep a small bubble around the light
361
+ far = far_dist + 1.0
362
+ if far <= near + 1e-4:
363
+ far = near + 1.0
364
+
365
+ margin = 1.0
366
+ minx -= margin
367
+ maxx += margin
368
+ miny -= margin
369
+ maxy += margin
370
+
371
+ mat = self._build_light_matrix(light, (minx, maxx, miny, maxy, near, far))
372
+ return mat, view, (minx, maxx, miny, maxy, near, far)
373
+
374
+ def _sphere_in_light_bounds(self, view, bounds, center, radius):
375
+ """True if the bounding sphere intersects the light's ortho volume."""
376
+ vc = view @ np.array([center.x, center.y, center.z, 1.0])
377
+ x, y, z = vc[0], vc[1], vc[2]
378
+ minx, maxx, miny, maxy, near, far = bounds
379
+ if x + radius < minx or x - radius > maxx:
380
+ return False
381
+ if y + radius < miny or y - radius > maxy:
382
+ return False
383
+ if z + radius < -far or z - radius > -near:
384
+ return False
385
+ return True
386
+
387
+
388
+ def render_shadow_pass(self, objects):
389
+ """Render a depth map for each relevant casting light (up to
390
+ max_shadow_maps).
391
+
392
+ Depth maps only depend on light positions and the geometry near the
393
+ light (not the camera), so each light caches a signature of
394
+ (position, in-range casters) and keeps its previous depth texture
395
+ when nothing relevant changed. Lights outside the camera frustum or
396
+ with ~zero intensity are skipped outright.
397
+ """
398
+ if not getattr(self, 'shadows', True):
399
+ return
400
+
401
+ casters = [
402
+ l for l in self.lights
403
+ if not getattr(l, 'is_area', False)
404
+ and hasattr(l, 'position')
405
+ and getattr(l, 'shadow_caster', True)
406
+ ]
407
+ if not casters:
408
+ return
409
+
410
+ casters = casters[:self.max_shadow_maps]
411
+
412
+ # Reset per-light -> map-slot mapping for this frame.
413
+ self._light_to_map = [-1] * self.max_shadow_maps
414
+ self._shadow_maps_rendered = 0
415
+
416
+ # Lightweight per-object metadata (no vertex building yet).
417
+ meta = []
418
+ for obj in objects:
419
+ if hasattr(obj, "image"):
420
+ continue
421
+ if not getattr(obj, "visible", True):
422
+ continue
423
+ if not getattr(obj, "shadow_caster", True):
424
+ continue
425
+ center, radius = self._shadow_center_radius(obj)
426
+ if center is None:
427
+ continue
428
+ meta.append((center, radius, obj))
429
+
430
+ if not meta:
431
+ return
432
+
433
+ # Two-phase plan: cache hits reserve their old slot before any
434
+ # re-rendering picks slots, so a cached map can never be overwritten
435
+ # by a light that re-renders into the same slot.
436
+ plan = []
437
+ taken = set()
438
+ for light in casters:
439
+ if float(light.intensity) <= 0.001:
440
+ continue
441
+ if not self._sphere_in_frustum(
442
+ light.position.x, light.position.y, light.position.z,
443
+ getattr(light, "range", 30.0)):
444
+ continue
445
+
446
+ rng = getattr(light, "range", 30.0)
447
+ in_range = []
448
+ lx, ly, lz = light.position.x, light.position.y, light.position.z
449
+ for center, radius, obj in meta:
450
+ if self._caster_bottom_y(obj) is not None and \
451
+ self._caster_bottom_y(obj) > light.position.y + 0.01:
452
+ continue
453
+ dx = center.x - lx
454
+ dy = center.y - ly
455
+ dz = center.z - lz
456
+ if dx * dx + dy * dy + dz * dz <= (rng + radius) ** 2:
457
+ in_range.append((center, radius, obj))
458
+ if not in_range:
459
+ continue
460
+
461
+ # Static reuse per light: skip re-render unless the light moved
462
+ # or an in-range caster changed. _geom_key excludes position
463
+ # (position is applied as a cheap numpy offset), so the cached
464
+ # geometry key is included too.
465
+ sig = (lx, ly, lz,
466
+ tuple((obj._geom_key,
467
+ getattr(obj, "_cached_pos", None),
468
+ obj.visible) for _, _, obj in in_range))
469
+ fidx = self._flat_light_index(light)
470
+ if fidx < 0 or fidx >= self.max_shadow_maps:
471
+ # No shadow slot exists for this light: _send_lights clips the
472
+ # shader's light array to max_shadow_maps entries, so a light
473
+ # beyond that limit can never consume a shadow map.
474
+ continue
475
+ if sig == self._last_light_sigs.get(light.name):
476
+ old_slot = self._light_slots_prev.get(light.name, -1)
477
+ if old_slot >= 0:
478
+ plan.append((light, "cached", old_slot))
479
+ taken.add(old_slot)
480
+ continue
481
+ plan.append((light, "render", sig, in_range))
482
+
483
+ slot = 0
484
+ for entry in plan:
485
+ light = entry[0]
486
+ if entry[1] == "cached":
487
+ old_slot = entry[2]
488
+ self._light_to_map[self._flat_light_index(light)] = old_slot
489
+ self._shadow_maps_rendered = max(self._shadow_maps_rendered, old_slot + 1)
490
+ continue
491
+
492
+ sig, in_range = entry[2], entry[3]
493
+ fit = self._fit_light_bounds(light, in_range)
494
+ if fit is None:
495
+ continue
496
+ mat, view, bounds = fit
497
+ mat_f4 = mat.T.astype("<f4")
498
+ while slot in taken:
499
+ slot += 1
500
+ if slot >= self.max_shadow_maps:
501
+ break
502
+ self.light_space_matrices[slot] = mat_f4
503
+
504
+ # Cull geometry to this light's volume (sphere test in light
505
+ # space), then gather cached positions only for survivors.
506
+ pos_parts = []
507
+ for center, radius, obj in in_range:
508
+ if not self._sphere_in_light_bounds(view, bounds, center, radius):
509
+ continue
510
+ try:
511
+ _, positions, _, _ = obj._get_geometry()
512
+ except Exception:
513
+ continue
514
+ if positions.size:
515
+ pos_parts.append(positions)
516
+ if not pos_parts:
517
+ continue
518
+
519
+ all_pos = np.concatenate(pos_parts)
520
+ fbo = self.shadow_fbos[slot]
521
+ fbo.clear(depth=1.0)
522
+ fbo.use()
523
+ self.ctx.viewport = (0, 0, self.shadow_size, self.shadow_size)
524
+ self.ctx.enable(moderngl.DEPTH_TEST)
525
+
526
+ try:
527
+ self.depth_prog["model"].write(np.eye(4, dtype="f4").tobytes())
528
+ except Exception:
529
+ pass
530
+ try:
531
+ self.depth_prog["light_space_matrix"].write(mat_f4.tobytes())
532
+ except Exception:
533
+ pass
534
+
535
+ data = all_pos.tobytes()
536
+ num_verts = len(all_pos) // 3
537
+ if len(data) <= self.depth_vbo.size:
538
+ self.depth_vbo.write(data)
539
+ self.depth_vao.render(vertices=num_verts)
540
+ else:
541
+ tmp_vbo = self.ctx.buffer(data)
542
+ tmp_vao = self.ctx.vertex_array(
543
+ self.depth_prog, [(tmp_vbo, "3f", "in_vert")])
544
+ tmp_vao.render(vertices=num_verts)
545
+ tmp_vao.release()
546
+ tmp_vbo.release()
547
+
548
+ self._light_to_map[self._flat_light_index(light)] = slot
549
+ self._last_light_sigs[light.name] = sig
550
+ self._light_slots_prev[light.name] = slot
551
+
552
+ slot += 1
553
+ self._shadow_maps_rendered = max(self._shadow_maps_rendered, slot)
554
+ if slot >= self.max_shadow_maps:
555
+ break
556
+
557
+ # restore default framebuffer and window viewport
558
+ self.ctx.screen.use()
559
+ self.ctx.viewport = (0, 0, self.width, self.height)
560
+
561
+ def _shadow_center_radius(self, obj):
562
+ """Cheap world-space (center, radius) bounding sphere — no vertex
563
+ building required."""
564
+ t = type(obj).__name__
565
+ if t == "Cuboid":
566
+ s = obj.size
567
+ return obj.pos, s.magnitude * 0.5
568
+ if t == "Sphere":
569
+ return obj.pos, obj.radius
570
+ if t == "Cylinder":
571
+ r = obj.radius
572
+ half = obj.length / 2
573
+ return obj.pos, math.sqrt(r * r + half * half)
574
+ if t == "ObjModel":
575
+ cached = getattr(obj, "_aabb_min", None)
576
+ if cached is not None:
577
+ half = (obj._aabb_max - obj._aabb_min) * 0.5
578
+ return obj.pos, half.magnitude
579
+ try:
580
+ lo, hi = obj.get_size()
581
+ except Exception:
582
+ return None, 0.0
583
+ if lo is None:
584
+ return None, 0.0
585
+ half = (hi - lo) * 0.5
586
+ return obj.pos, half.magnitude
587
+ return None, 0.0
588
+
589
+ def _flat_light_index(self, light):
590
+ """Index of `light` in the flattened lights[] array uploaded by
591
+ _send_lights (area lights occupy one slot per sample point)."""
592
+ idx = 0
593
+ for l in self.lights:
594
+ if l is light:
595
+ return idx
596
+ if getattr(l, 'is_area', False):
597
+ try:
598
+ pts = l.sample_points() if hasattr(l, 'sample_points') else []
599
+ except Exception:
600
+ pts = []
601
+ idx += max(0, len(pts))
602
+ else:
603
+ idx += 1
604
+ return -1
605
+
606
+ def _append_vertices(self, vertices, alpha: float = 1.0):
607
+ if alpha >= 1.0:
608
+ self.frame_vertices.extend(vertices)
609
+ else:
610
+ self.frame_transparents.append((alpha, np.array(vertices, dtype="f4")))
611
+
612
+ def flush(self):
613
+ opaque_drawn = False
614
+ if self.frame_vertex_arrays or self.frame_vertices:
615
+ opaque_drawn = True
616
+ if self.frame_vertices:
617
+ parts = list(self.frame_vertex_arrays)
618
+ parts.append(np.array(self.frame_vertices, dtype="f4"))
619
+ vertices = np.concatenate(parts)
620
+ elif len(self.frame_vertex_arrays) == 1:
621
+ vertices = self.frame_vertex_arrays[0]
622
+ else:
623
+ vertices = np.concatenate(self.frame_vertex_arrays)
624
+
625
+ if vertices.ndim == 2:
626
+ vertices = vertices.reshape(-1)
627
+ vertices = np.ascontiguousarray(vertices, dtype="f4")
628
+
629
+ self.vbo.write(vertices.tobytes())
630
+ # Ensure FBO is bound before rendering
631
+ self.fbo.use()
632
+ # Send lights and bind shadow maps + matrices
633
+ self._send_lights()
634
+ self._bind_shadow_maps()
635
+ try:
636
+ self.prog["object_alpha"].value = 1.0
637
+ except Exception:
638
+ pass
639
+ # Draw
640
+ num_verts = len(vertices) // 12
641
+ self.vao.render(vertices=num_verts)
642
+ self.frame_vertex_arrays.clear()
643
+ self.frame_vertices.clear()
644
+
645
+ if self.frame_transparents:
646
+ self._flush_transparents()
647
+
648
+ def _flush_transparents(self):
649
+ """Draw transparent geometry back-to-front, alpha-blended over the
650
+ opaque pass already in the FBO (depth test stays on).
651
+
652
+ Depth sort uses the same matrix the GPU clips with. The mvp uniform is
653
+ uploaded in numpy row-major bytes and GLSL reads a mat4 column-major,
654
+ so the effective render transform is mvp.T — sorting with the raw
655
+ `mvp` yields a z-order that disagrees with the depth buffer at certain
656
+ camera angles, which makes the far transparent object vanish (it gets
657
+ depth-culled behind a nearer one)."""
658
+ mvp = np.asarray(self.mvp).T.astype("f4")
659
+ items = []
660
+ for alpha, verts_np in self.frame_transparents:
661
+ # view-space depth from the object's centroid (more negative = farther)
662
+ pos = verts_np[:, :3] if verts_np.ndim == 2 else verts_np.reshape(-1, 12)[:, :3]
663
+ cx = (pos[:, 0].min() + pos[:, 0].max()) * 0.5
664
+ cy = (pos[:, 1].min() + pos[:, 1].max()) * 0.5
665
+ cz = (pos[:, 2].min() + pos[:, 2].max()) * 0.5
666
+ clip = mvp @ np.array([cx, cy, cz, 1.0])
667
+ depth = clip[2] / clip[3]
668
+ items.append((depth, alpha, verts_np))
669
+ items.sort(key=lambda it: it[0]) # ascending depth: farthest first
670
+
671
+ self.fbo.use()
672
+ # Transparents must never write depth: with writes on, the first
673
+ # transparent drawn stamps its depth and every farther transparent
674
+ # (or farther face of the same object) fails the depth test and
675
+ # disappears. Depth *testing* against the opaque pass stays enabled.
676
+ prev_depth_mask = self.fbo.depth_mask
677
+ self.fbo.depth_mask = False
678
+ self._send_lights()
679
+ self._bind_shadow_maps()
680
+ try:
681
+ self.ctx.enable(moderngl.BLEND)
682
+ self.ctx.blend_func = (moderngl.SRC_ALPHA, moderngl.ONE_MINUS_SRC_ALPHA)
683
+ except Exception:
684
+ pass
685
+
686
+ for _, alpha, verts_np in items:
687
+ if verts_np.ndim == 2:
688
+ verts_np = verts_np.reshape(-1)
689
+ verts_np = np.ascontiguousarray(verts_np, dtype="f4")
690
+ try:
691
+ self.prog["object_alpha"].value = float(alpha)
692
+ except Exception:
693
+ pass
694
+ self.vbo.write(verts_np.tobytes())
695
+ self.vao.render(vertices=len(verts_np) // 12)
696
+
697
+ try:
698
+ self.prog["object_alpha"].value = 1.0
699
+ self.ctx.disable(moderngl.BLEND)
700
+ except Exception:
701
+ pass
702
+ self.fbo.depth_mask = bool(prev_depth_mask)
703
+ self.frame_transparents.clear()
704
+
705
+ def _bind_shadow_maps(self):
706
+ """Upload the per-light shadow data to the main program.
707
+
708
+ light_to_shadow_map[light i] = slot of its depth texture, or -1 when
709
+ the light has no map this frame (it is then treated as fully lit).
710
+ """
711
+ buf = np.array(self.light_space_matrices[:self.max_shadow_maps], dtype="f4").tobytes()
712
+ try:
713
+ self.prog["light_space_matrix"].write(buf)
714
+ except Exception:
715
+ pass
716
+
717
+ try:
718
+ self.prog["light_to_shadow_map"].value = tuple(self._light_to_map)
719
+ except Exception:
720
+ pass
721
+
722
+ n = min(getattr(self, "_shadow_maps_rendered", 0), self.max_shadow_maps)
723
+ for i in range(n):
724
+ try:
725
+ self.shadow_depth_textures[i].use(location=i + 1)
726
+ except Exception:
727
+ pass
728
+
729
+ def render_plane(self, p1, p2, p3, color, emit: bool = False, alpha: float = 1.0):
730
+
731
+ normal = self._compute_normal(p1, p2, p3)
732
+
733
+ # per-vertex emission marker (non-zero -> emissive)
734
+ em_triplet = (1.0, 1.0, 1.0) if emit else (0.0, 0.0, 0.0)
735
+
736
+ def v_entry(p):
737
+ return [*p.totuple(), *color.to_rgb(), *normal.totuple(), *em_triplet]
738
+
739
+ vertices = []
740
+ vertices.extend(v_entry(p1))
741
+ vertices.extend(v_entry(p2))
742
+ vertices.extend(v_entry(p3))
743
+
744
+ self._append_vertices(vertices, alpha=alpha)
745
+
746
+ def render_sphere(self, center, radius, color, segments=32, rings=16,
747
+ emit: bool = False, alpha: float = 1.0):
748
+ """
749
+ Render a sphere with optional emission.
750
+ - center: vector3d
751
+ - radius: float
752
+ - color: Color
753
+ - segments, rings: tessellation
754
+ - emit / emission_*: same meaning as for render_plane
755
+ """
756
+ vertices = []
757
+ em_triplet = (1.0, 1.0, 1.0) if emit else (0.0, 0.0, 0.0)
758
+
759
+ for i in range(rings):
760
+ theta1 = math.pi * i / rings
761
+ theta2 = math.pi * (i + 1) / rings
762
+ for j in range(segments):
763
+ phi1 = 2 * math.pi * j / segments
764
+ phi2 = 2 * math.pi * (j + 1) / segments
765
+
766
+ p1 = vector3d(radius * math.sin(theta1) * math.cos(phi1),
767
+ radius * math.cos(theta1),
768
+ radius * math.sin(theta1) * math.sin(phi1)) + center
769
+ p2 = vector3d(radius * math.sin(theta2) * math.cos(phi1),
770
+ radius * math.cos(theta2),
771
+ radius * math.sin(theta2) * math.sin(phi1)) + center
772
+ p3 = vector3d(radius * math.sin(theta2) * math.cos(phi2),
773
+ radius * math.cos(theta2),
774
+ radius * math.sin(theta2) * math.sin(phi2)) + center
775
+ p4 = vector3d(radius * math.sin(theta1) * math.cos(phi2),
776
+ radius * math.cos(theta1),
777
+ radius * math.sin(theta1) * math.sin(phi2)) + center
778
+
779
+ for tri in [(p1, p2, p3), (p1, p3, p4)]:
780
+ n1 = (tri[0] - center).normalized
781
+ n2 = (tri[1] - center).normalized
782
+ n3 = (tri[2] - center).normalized
783
+ vertices.extend([
784
+ *tri[0].totuple(), *color.to_rgb(), *n1.totuple(), *em_triplet,
785
+ *tri[1].totuple(), *color.to_rgb(), *n2.totuple(), *em_triplet,
786
+ *tri[2].totuple(), *color.to_rgb(), *n3.totuple(), *em_triplet,
787
+ ])
788
+
789
+ self._append_vertices(vertices, alpha=alpha)
790
+
791
+ def render_cylinder(self, center, height, radius, color, segments=32, rotation=vector3d(0, 0, 0),
792
+ emit: bool = False, alpha: float = 1.0):
793
+ vertices = []
794
+
795
+ def apply_matrix(v: vector3d, m: Matrix44) -> vector3d:
796
+ vec4 = np.array([v.x, v.y, v.z, 1.0], dtype="f4")
797
+ transformed = m @ vec4
798
+ return vector3d(*transformed[:3])
799
+
800
+ def apply_matrix_normal(n: vector3d, m: Matrix44) -> vector3d:
801
+ vec4 = np.array([n.x, n.y, n.z, 0.0], dtype="f4") # w=0 for direction
802
+ transformed = m @ vec4
803
+ return vector3d(*transformed[:3]).normalized
804
+
805
+ rot_x = Matrix44.from_x_rotation(math.radians(rotation.x))
806
+ rot_y = Matrix44.from_y_rotation(math.radians(rotation.y))
807
+ rot_z = Matrix44.from_z_rotation(math.radians(rotation.z))
808
+ rot_matrix = rot_z * rot_y * rot_x
809
+
810
+ em_triplet = (1.0, 1.0, 1.0) if emit else (0.0, 0.0, 0.0)
811
+
812
+ for i in range(segments):
813
+ theta1 = 2 * math.pi * i / segments
814
+ theta2 = 2 * math.pi * (i + 1) / segments
815
+
816
+ # Top/bottom circle vertices
817
+ top1 = vector3d(radius * math.cos(theta1), height / 2, radius * math.sin(theta1))
818
+ top2 = vector3d(radius * math.cos(theta2), height / 2, radius * math.sin(theta2))
819
+ bottom1 = vector3d(radius * math.cos(theta1), -height / 2, radius * math.sin(theta1))
820
+ bottom2 = vector3d(radius * math.cos(theta2), -height / 2, radius * math.sin(theta2))
821
+
822
+ top1 = apply_matrix(top1, rot_matrix) + center
823
+ top2 = apply_matrix(top2, rot_matrix) + center
824
+ bottom1 = apply_matrix(bottom1, rot_matrix) + center
825
+ bottom2 = apply_matrix(bottom2, rot_matrix) + center
826
+
827
+ normal1 = apply_matrix_normal(vector3d(math.cos(theta1), 0, math.sin(theta1)), rot_matrix)
828
+ normal2 = apply_matrix_normal(vector3d(math.cos(theta2), 0, math.sin(theta2)), rot_matrix)
829
+
830
+ # Side quad (two triangles)
831
+ for tri in [(top1, bottom1, bottom2), (top1, bottom2, top2)]:
832
+ n1 = (tri[0] - center).normalized
833
+ n2 = (tri[1] - center).normalized
834
+ n3 = (tri[2] - center).normalized
835
+ vertices.extend([
836
+ *tri[0].totuple(), *color.to_rgb(), *n1.totuple(), *em_triplet,
837
+ *tri[1].totuple(), *color.to_rgb(), *n2.totuple(), *em_triplet,
838
+ *tri[2].totuple(), *color.to_rgb(), *n3.totuple(), *em_triplet,
839
+ ])
840
+
841
+ # Top cap (triangle fan triangles)
842
+ top_center = apply_matrix(vector3d(0, height / 2, 0), rot_matrix) + center
843
+ normal_top = apply_matrix_normal(vector3d(0, 1, 0), rot_matrix)
844
+ vertices.extend([
845
+ *top_center.totuple(), *color.to_rgb(), *normal_top.totuple(), *em_triplet,
846
+ *top2.totuple(), *color.to_rgb(), *normal_top.totuple(), *em_triplet,
847
+ *top1.totuple(), *color.to_rgb(), *normal_top.totuple(), *em_triplet,
848
+ ])
849
+
850
+ bottom_center = apply_matrix(vector3d(0, -height / 2, 0), rot_matrix) + center
851
+ normal_bottom = apply_matrix_normal(vector3d(0, -1, 0), rot_matrix)
852
+ vertices.extend([
853
+ *bottom_center.totuple(), *color.to_rgb(), *normal_bottom.totuple(), *em_triplet,
854
+ *bottom1.totuple(), *color.to_rgb(), *normal_bottom.totuple(), *em_triplet,
855
+ *bottom2.totuple(), *color.to_rgb(), *normal_bottom.totuple(), *em_triplet,
856
+ ])
857
+
858
+ self._append_vertices(vertices, alpha=alpha)
859
+
860
+ def render_quad(self, p1, p2, p3, p4, color, emit: bool = False, alpha: float = 1.0):
861
+ normal = self._compute_normal(p1, p2, p3)
862
+
863
+ if emit:
864
+ em_triplet = (1.0, 1.0, 1.0)
865
+ else:
866
+ em_triplet = (0.0, 0.0, 0.0)
867
+
868
+ def v_entry(p):
869
+ return [*p.totuple(), *color.to_rgb(), *normal.totuple(), *em_triplet]
870
+
871
+ vertices = []
872
+ vertices.extend(v_entry(p1))
873
+ vertices.extend(v_entry(p2))
874
+ vertices.extend(v_entry(p3))
875
+ vertices.extend(v_entry(p1))
876
+ vertices.extend(v_entry(p3))
877
+ vertices.extend(v_entry(p4))
878
+
879
+ self._append_vertices(vertices, alpha=alpha)
880
+
881
+ def _send_lights(self):
882
+ max_lights = 8
883
+
884
+ # Helper: sample a quad (p1,p2,p3,p4) into n_samples in a grid
885
+ def sample_quad(corners, n_samples):
886
+ p1, p2, p3, p4 = corners
887
+ n = int(math.sqrt(n_samples))
888
+ if n * n < n_samples:
889
+ n += 1
890
+ pts = []
891
+ count = 0
892
+ for i in range(n):
893
+ for j in range(n):
894
+ if count >= n_samples:
895
+ break
896
+ u = (i + 0.5) / n
897
+ v = (j + 0.5) / n
898
+ # bilinear interpolation on quad (p1->p2 and p4->p3 interpolation)
899
+ a = p1 * (1.0 - u) + p2 * u
900
+ b = p4 * (1.0 - u) + p3 * u
901
+ pos = a * (1.0 - v) + b * v
902
+ pts.append(pos)
903
+ count += 1
904
+ if count >= n_samples:
905
+ break
906
+ return pts
907
+
908
+ # Helper: sample a triangle using barycentric / grid sampling
909
+ def sample_tri(corners, n_samples):
910
+ p1, p2, p3 = corners
911
+ # We'll use a simple stratified scheme: find grid m x m such that m*m >= n_samples
912
+ m = int(math.sqrt(n_samples))
913
+ if m * m < n_samples:
914
+ m += 1
915
+ pts = []
916
+ count = 0
917
+ for i in range(m):
918
+ for j in range(m):
919
+ if count >= n_samples:
920
+ break
921
+ u = (i + 0.5) / m
922
+ v = (j + 0.5) / m
923
+ # enforce u+v <= 1 by folding when >1 to stay inside triangle
924
+ if u + v > 1.0:
925
+ u = 1.0 - u
926
+ v = 1.0 - v
927
+ # barycentric interpolation
928
+ pos = p1 * (1 - u - v) + p2 * u + p3 * v
929
+ pts.append(pos)
930
+ count += 1
931
+ if count >= n_samples:
932
+ break
933
+ return pts
934
+
935
+ flattened = []
936
+
937
+ # --- persistent lights (existing self.lights) ---
938
+ for light in self.lights:
939
+ if hasattr(light, 'is_area') and getattr(light, 'is_area'):
940
+ if hasattr(light, 'sample_points'):
941
+ try:
942
+ pts = light.sample_points()
943
+ except Exception:
944
+ pts = []
945
+ else:
946
+ pts = []
947
+ if not pts:
948
+ continue
949
+ per_sample_int = float(light.intensity) / max(1, len(pts))
950
+ color_tuple = tuple(c / 255 for c in light.color.to_rgb())
951
+ for p in pts:
952
+ flattened.append({
953
+ 'position': p.totuple(),
954
+ 'color': color_tuple,
955
+ 'intensity': per_sample_int
956
+ })
957
+ else:
958
+ flattened.append({
959
+ 'position': light.position.totuple(),
960
+ 'color': tuple(c / 255 for c in light.color.to_rgb()),
961
+ 'intensity': float(light.intensity)
962
+ })
963
+
964
+ # --- per-frame emissive surfaces collected during draw calls ---
965
+ for em in self.frame_emissives:
966
+ shape = em.get('shape')
967
+ samples = int(em.get('samples', 4))
968
+ em_color = tuple(c / 255 for c in em.get('color', (255, 255, 255)))
969
+ em_intensity = float(em.get('intensity', 1.0))
970
+ if shape == 'quad':
971
+ corners = em['params']['corners']
972
+ pts = sample_quad(corners, samples)
973
+ elif shape == 'tri':
974
+ corners = em['params']['corners']
975
+ pts = sample_tri(corners, samples)
976
+ else:
977
+ pts = []
978
+ if not pts:
979
+ continue
980
+ per_sample_int = em_intensity / max(1, len(pts))
981
+ for p in pts:
982
+ flattened.append({
983
+ 'position': p.totuple(),
984
+ 'color': em_color,
985
+ 'intensity': per_sample_int
986
+ })
987
+
988
+ # Clamp to shader max lights
989
+ num_lights = min(len(flattened), max_lights)
990
+
991
+ # Ambient can change independently; always upload it (cheap).
992
+ try:
993
+ self.prog["ambient"].value = self.ambient
994
+ except Exception:
995
+ pass
996
+
997
+ # Skip per-light uniform uploads entirely when unchanged.
998
+ key = []
999
+ for i in range(num_lights):
1000
+ l = flattened[i]
1001
+ key.append((l['position'], l['color'], l['intensity']))
1002
+ key = tuple(key)
1003
+ if key == getattr(self, "_last_lights", None):
1004
+ return
1005
+ self._last_lights = key
1006
+
1007
+ self.prog["num_lights"].value = num_lights
1008
+ for i in range(num_lights):
1009
+ l = flattened[i]
1010
+ self.prog[f"lights[{i}].position"].value = l['position']
1011
+ self.prog[f"lights[{i}].color"].value = l['color']
1012
+ self.prog[f"lights[{i}].intensity"].value = l['intensity']
1013
+
1014
+ def clear(self, color):
1015
+ color_f = np.array(color.to_rgb(), dtype="f4") / 255.0
1016
+ self.fbo.clear(*color_f, depth=1.0)
1017
+ self.fbo.use()
1018
+ self.frame_vertex_arrays.clear()
1019
+ self.frame_vertices.clear()
1020
+ self.frame_transparents.clear()
1021
+ self.frame_emissives.clear()
1022
+
1023
+
1024
+ def swap(self):
1025
+ self.flush()
1026
+ # copy resolved multisampled FBO to default framebuffer
1027
+ self.ctx.copy_framebuffer(dst=self.ctx.screen, src=self.fbo)
1028
+
1029
+ # draw any per-frame overlays queued via render_image()
1030
+ if self._overlay_queue:
1031
+ # lazy-create overlay shader program if needed
1032
+ if self._overlay_prog is None:
1033
+ vs = """
1034
+ #version 330
1035
+ in vec2 in_pos; in vec2 in_uv; out vec2 v_uv;
1036
+ void main() { gl_Position = vec4(in_pos, 0.0, 1.0); v_uv = in_uv; }
1037
+ """
1038
+ fs = """
1039
+ #version 330
1040
+ uniform sampler2D tex; uniform float u_alpha;
1041
+ in vec2 v_uv; out vec4 f_color;
1042
+ void main() { f_color = texture(tex, v_uv); f_color.a *= u_alpha; }
1043
+ """
1044
+ self._overlay_prog = self.ctx.program(vertex_shader=vs, fragment_shader=fs)
1045
+ try:
1046
+ self._overlay_prog["tex"].value = 0
1047
+ except Exception:
1048
+ pass
1049
+ try:
1050
+ self._overlay_prog["u_alpha"].value = 1.0
1051
+ except Exception:
1052
+ pass
1053
+
1054
+ # draw overlays to default framebuffer
1055
+ self.ctx.screen.use()
1056
+ try:
1057
+ self.ctx.disable(moderngl.DEPTH_TEST)
1058
+ except Exception:
1059
+ pass
1060
+ self.ctx.enable(moderngl.BLEND)
1061
+ try:
1062
+ self.ctx.blend_func = (moderngl.SRC_ALPHA, moderngl.ONE_MINUS_SRC_ALPHA)
1063
+ except Exception:
1064
+ pass
1065
+
1066
+ for entry in self._overlay_queue:
1067
+ # entry format: (tex, img_w, img_h, x, y, w, h, rotation_deg, flip_x, flip_y, alpha)
1068
+ try:
1069
+ tex, img_w, img_h, x, y, w, h, rotation_deg, flip_x, flip_y, alpha = entry
1070
+ except Exception:
1071
+ continue
1072
+ try:
1073
+ self._render_overlay_tex(tex, x, y, w, h, rotation_deg, flip_x, flip_y, alpha)
1074
+ except Exception:
1075
+ pass
1076
+
1077
+ try:
1078
+ self.ctx.disable(moderngl.BLEND)
1079
+ self.ctx.enable(moderngl.DEPTH_TEST)
1080
+ except Exception:
1081
+ pass
1082
+
1083
+ self._overlay_queue.clear()
1084
+
1085
+ pygame.display.flip()
1086
+
1087
+ def load_image(self, path, key=None):
1088
+ """Load an RGBA image from disk and register it under `key`. Returns the key used."""
1089
+ if key is None:
1090
+ key = path
1091
+ surf = pygame.image.load(path).convert_alpha()
1092
+ img_w, img_h = surf.get_size()
1093
+ data = pygame.image.tostring(surf, "RGBA", True)
1094
+ tex = self.ctx.texture((img_w, img_h), 4, data)
1095
+ tex.filter = (moderngl.LINEAR, moderngl.LINEAR)
1096
+ self._images[key] = {"tex": tex, "size": (img_w, img_h)}
1097
+ return key
1098
+
1099
+ def render_image(self, key, position=None, scale=None, rotation: float = 0.0, flip_x: bool = False, flip_y: bool = False, alpha: float = 1.0):
1100
+ if key not in self._images:
1101
+ raise KeyError(f"Image key not found: {key}")
1102
+ if position is None:
1103
+ position = vector2d.zero
1104
+ if scale is None:
1105
+ scale = vector2d.one
1106
+ if not isinstance(position, vector2d) or not isinstance(scale, vector2d):
1107
+ raise TypeError("position and scale must be vector2d instances")
1108
+
1109
+ entry = self._images[key]
1110
+ tex = entry["tex"]
1111
+ img_w, img_h = entry["size"]
1112
+
1113
+ # compute pixel size after scaling
1114
+ w = int(round(img_w * scale.x))
1115
+ h = int(round(img_h * scale.y))
1116
+
1117
+ # convert screen-centered position to top-left pixel coords
1118
+ # screen center in pixels
1119
+ cx = self.width / 2.0
1120
+ cy = self.height / 2.0
1121
+ # position.x positive to right; position.y positive up
1122
+ center_x_px = cx + position.x
1123
+ center_y_px = cy - position.y
1124
+ # top-left so that image center matches requested center
1125
+ x = int(round(center_x_px - w / 2.0))
1126
+ y = int(round(center_y_px - h / 2.0))
1127
+
1128
+ # enqueue (tex,img_w,img_h,x,y,w,h,rotation,flip_x,flip_y,alpha)
1129
+ self._overlay_queue.append((tex, img_w, img_h, x, y, w, h, float(rotation), bool(flip_x), bool(flip_y), float(alpha)))
1130
+
1131
+ def _render_overlay_tex(self, tex, x, y, w, h, rotation_deg=0.0, flip_x=False, flip_y=False, alpha=1.0):
1132
+ """Render a texture at pixel top-left (x,y) with size (w,h), supports rotation and flipping."""
1133
+ # compute pixel-space corners (top-left origin)
1134
+ corners = [(x, y), (x + w, y), (x + w, y + h), (x, y + h)]
1135
+ if rotation_deg != 0.0:
1136
+ theta = math.radians(rotation_deg)
1137
+ c = math.cos(theta); s = math.sin(theta)
1138
+ cx = x + w / 2.0; cy = y + h / 2.0
1139
+ rot = []
1140
+ for px, py in corners:
1141
+ dx = px - cx; dy = py - cy
1142
+ rx = c * dx - s * dy
1143
+ ry = s * dx + c * dy
1144
+ rot.append((cx + rx, cy + ry))
1145
+ corners = rot
1146
+
1147
+ # UVs correspond to corners order
1148
+ uvs = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
1149
+ if flip_x:
1150
+ uvs = [(1.0 - u, v) for (u, v) in uvs]
1151
+ if flip_y:
1152
+ uvs = [(u, 1.0 - v) for (u, v) in uvs]
1153
+
1154
+ verts = []
1155
+ for (px, py), (u, v) in zip(corners, uvs):
1156
+ ndc_x = (px / self.width) * 2.0 - 1.0
1157
+ ndc_y = 1.0 - (py / self.height) * 2.0
1158
+ verts.extend([ndc_x, ndc_y, u, v])
1159
+
1160
+ verts = np.array(verts, dtype="f4")
1161
+ idx = np.array([0, 1, 2, 0, 2, 3], dtype="i4")
1162
+ vbo = self.ctx.buffer(verts.tobytes())
1163
+ ibo = self.ctx.buffer(idx.tobytes())
1164
+ vao = self.ctx.vertex_array(self._overlay_prog, [(vbo, "2f 2f", "in_pos", "in_uv")], ibo)
1165
+ tex.use(location=0)
1166
+ try:
1167
+ self._overlay_prog["tex"].value = 0
1168
+ except Exception:
1169
+ pass
1170
+ try:
1171
+ self._overlay_prog["u_alpha"].value = float(alpha)
1172
+ except Exception:
1173
+ pass
1174
+ vao.render()
1175
+ try:
1176
+ vao.release()
1177
+ except Exception:
1178
+ pass
1179
+ try:
1180
+ vbo.release(); ibo.release()
1181
+ except Exception:
1182
+ pass
1183
+
1184
+ def quit(self):
1185
+ pygame.quit()
1186
+
1187
+ def _load_shader(self, vert_name, frag_name):
1188
+ vert_src = pkg_resources.read_text(f"{__package__}.shaders", vert_name)
1189
+ frag_src = pkg_resources.read_text(f"{__package__}.shaders", frag_name)
1190
+ return self.ctx.program(vertex_shader=vert_src, fragment_shader=frag_src)
1191
+
1192
+ class Camera:
1193
+ def __init__(self, position=None, target=None, up=None, fov=60.0, aspect_ratio=4/3, near=0.1, far=100.0, orbiting=True):
1194
+ self.orbiting = orbiting # New: toggle automatic look-at behavior
1195
+ self.target = target or vector3d(0, 0, 0)
1196
+ self.up = up or vector3d.up
1197
+ self.fov = fov
1198
+ self.aspect_ratio = aspect_ratio
1199
+ self.near = near
1200
+ self.far = far
1201
+
1202
+ # Compute spherical coordinates from initial position
1203
+ pos = position or vector3d(3, 2, 3)
1204
+ if self.orbiting:
1205
+ self._update_spherical(pos)
1206
+ else:
1207
+ self.radius = (pos - self.target).magnitude or 5.0
1208
+ self.position = pos
1209
+ self.mouse_look = False
1210
+
1211
+ self._update_position()
1212
+
1213
+ def move_to(self, new_position: vector3d):
1214
+ """
1215
+ Move the camera to a new position.
1216
+ If orbiting is enabled, updates spherical coordinates.
1217
+ If orbiting is disabled, just sets position directly.
1218
+ """
1219
+ self.position = new_position
1220
+ if self.orbiting:
1221
+ self._update_spherical(new_position)
1222
+ self._update_position()
1223
+
1224
+ def set_orbiting(self, orbiting: bool):
1225
+ """Enable or disable automatic look-at behavior."""
1226
+ self.orbiting = orbiting
1227
+
1228
+ def set_mouse_look(self, enabled: bool = True):
1229
+ """Enable or disable FPS-style mouse look (free camera, rotation only).
1230
+
1231
+ While enabled the camera stops orbiting: its position is driven
1232
+ directly and the view direction is changed via rotate_look().
1233
+ Enabling preserves the current viewing direction.
1234
+ """
1235
+ self.mouse_look = bool(enabled)
1236
+ if enabled:
1237
+ if self.orbiting:
1238
+ self.look_dir = (self.target - self.position).normalized
1239
+ self.set_orbiting(False)
1240
+ else:
1241
+ self.look_dir = getattr(self, "look_dir", vector3d(0, 0, -1)).normalized
1242
+ if not hasattr(self, "radius"):
1243
+ self.radius = (self.position - self.target).magnitude if self.target is not None else 5.0
1244
+ self._update_position()
1245
+
1246
+ def rotate_look(self, delta_yaw, delta_pitch):
1247
+ """Apply yaw/pitch deltas (in degrees) to the view direction.
1248
+
1249
+ Only works in mouse-look mode (non-orbiting). Positive delta_yaw
1250
+ turns the view to the right; positive delta_pitch pitches up.
1251
+ Pitch is clamped to +/- 89 degrees to avoid flipping.
1252
+ """
1253
+ if not getattr(self, "mouse_look", False) or self.orbiting:
1254
+ return
1255
+ forward = getattr(self, "look_dir", vector3d(0, 0, -1)).normalized
1256
+ yaw = math.degrees(math.atan2(forward.z, forward.x))
1257
+ pitch = math.degrees(math.asin(max(-1.0, min(1.0, forward.y))))
1258
+
1259
+ yaw += delta_yaw
1260
+ pitch = max(-89.0, min(89.0, pitch + delta_pitch))
1261
+
1262
+ pyr = math.radians(pitch)
1263
+ yyr = math.radians(yaw)
1264
+ cp = math.cos(pyr)
1265
+ self.look_dir = vector3d(cp * math.cos(yyr), math.sin(pyr), cp * math.sin(yyr))
1266
+ self._update_position()
1267
+
1268
+ def _update_spherical(self, pos):
1269
+ """Convert position to spherical coordinates relative to target."""
1270
+ dir_vec = pos - self.target
1271
+ self.radius = dir_vec.magnitude
1272
+ self.azimuth = math.atan2(dir_vec.z, dir_vec.x) # yaw
1273
+ self.elevation = math.asin(dir_vec.y / self.radius) # pitch
1274
+
1275
+ def _update_position(self):
1276
+ if self.orbiting:
1277
+ x = self.radius * math.cos(self.elevation) * math.cos(self.azimuth)
1278
+ y = self.radius * math.sin(self.elevation)
1279
+ z = self.radius * math.cos(self.elevation) * math.sin(self.azimuth)
1280
+ self.position = self.target + vector3d(x, y, z)
1281
+
1282
+ look_at = self.target if self.orbiting else self.position + getattr(self, "look_dir", vector3d(0, 0, -1))
1283
+
1284
+ self.view_matrix = Matrix44.look_at(
1285
+ self.position.totuple(),
1286
+ look_at.totuple(),
1287
+ self.up.totuple()
1288
+ )
1289
+
1290
+ self.near = max(self.radius * 0.001, 1e-4)
1291
+ self.far = self.radius * 10_000
1292
+ self.projection_matrix = Matrix44.perspective_projection(
1293
+ self.fov, self.aspect_ratio, self.near, self.far
1294
+ )
1295
+
1296
+
1297
+ def rotate_around_target(self, delta_azimuth_degrees, delta_elevation_degrees):
1298
+ if not self.orbiting:
1299
+ return # rotation disabled in free mode
1300
+
1301
+ self.azimuth += math.radians(delta_azimuth_degrees)
1302
+ self.elevation += math.radians(delta_elevation_degrees)
1303
+
1304
+ # Handle elevation wrapping to allow full rotation without flipping
1305
+ while self.elevation > math.pi / 2:
1306
+ self.elevation = math.pi - self.elevation
1307
+ self.azimuth += math.pi
1308
+ self.up = -self.up # flip up vector
1309
+
1310
+ while self.elevation < -math.pi / 2:
1311
+ self.elevation = -math.pi - self.elevation
1312
+ self.azimuth += math.pi
1313
+ self.up = -self.up # flip up vector
1314
+
1315
+ self._update_position()
1316
+
1317
+
1318
+ def zoom(self, amount):
1319
+ """
1320
+ Dolly zoom:
1321
+ Positive amount moves forward
1322
+ Negative amount moves backward
1323
+ """
1324
+
1325
+ # Forward direction
1326
+ if self.orbiting:
1327
+ forward = (self.target - self.position).normalized
1328
+ else:
1329
+ forward = getattr(self, "look_dir", vector3d(0, 0, -1)).normalized
1330
+
1331
+ # Move camera
1332
+ delta = forward * amount
1333
+ self.position += delta
1334
+
1335
+ if self.orbiting:
1336
+ self._update_spherical(self.position)
1337
+
1338
+ self._update_position()
1339
+
1340
+ def update_renderer(self, renderer: Renderer):
1341
+ renderer.view = self.view_matrix
1342
+ renderer.proj = self.projection_matrix
1343
+ renderer.mvp = renderer.proj * renderer.view
1344
+ renderer.prog["mvp"].write(renderer.mvp.astype("f4").tobytes())
1345
+ renderer._update_frustum()
1346
+
1347
+ def look_at(self, point: vector3d):
1348
+ """
1349
+ Make the camera look at a specific point in space.
1350
+ - In orbiting mode, sets the target and updates spherical coordinates.
1351
+ - In free mode, sets the look direction vector.
1352
+ """
1353
+ if self.orbiting:
1354
+ self.target = point
1355
+ self._update_spherical(self.position)
1356
+ else:
1357
+ self.look_dir = (point - self.position).normalized # direction vector in free mode
1358
+
1359
+ self._update_position()
1360
+
1361
+ def screen_point_to_ray(self, x, y, screen_width, screen_height):
1362
+ # maps screen pixel to a direction vector in world space (and returns near-point too)
1363
+ ndc_x = (2.0 * x) / screen_width - 1.0
1364
+ ndc_y = 1.0 - (2.0 * y) / screen_height
1365
+
1366
+ near_clip = np.array([ndc_x, ndc_y, -1.0, 1.0], dtype="f8")
1367
+ far_clip = np.array([ndc_x, ndc_y, 1.0, 1.0], dtype="f8")
1368
+
1369
+ m = (self.projection_matrix * self.view_matrix)
1370
+ inv = m.inverse # pyrr Matrix44.inverse is a property
1371
+
1372
+ near_world = np.asarray(inv @ near_clip, dtype="f8").ravel()
1373
+ far_world = np.asarray(inv @ far_clip, dtype="f8").ravel()
1374
+
1375
+ if abs(near_world[3]) > 1e-9:
1376
+ near_world = near_world / near_world[3]
1377
+ if abs(far_world[3]) > 1e-9:
1378
+ far_world = far_world / far_world[3]
1379
+
1380
+ from .helper import vector3d
1381
+ origin = vector3d(float(near_world[0]), float(near_world[1]), float(near_world[2]))
1382
+ far_pt = vector3d(float(far_world[0]), float(far_world[1]), float(far_world[2]))
1383
+
1384
+ dir_vec = (far_pt - origin)
1385
+ if dir_vec.magnitude == 0:
1386
+ direction = (self.target - self.position).normalized
1387
+ else:
1388
+ direction = dir_vec.normalized
1389
+
1390
+ return origin, direction