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.
- gamengine3d/__init__.py +18 -0
- gamengine3d/assets/__init__.py +0 -0
- gamengine3d/assets/circular_crosshair.png +0 -0
- gamengine3d/assets/plus_sign_crosshair.png +0 -0
- gamengine3d/cli.py +83 -0
- gamengine3d/context.py +319 -0
- gamengine3d/engine.py +715 -0
- gamengine3d/examples/__init__.py +0 -0
- gamengine3d/examples/basics.py +66 -0
- gamengine3d/examples/parkour.py +285 -0
- gamengine3d/examples/player_movement.py +161 -0
- gamengine3d/examples/reactor.py +526 -0
- gamengine3d/examples/scripts/__init__.py +0 -0
- gamengine3d/examples/scripts/bouncer.py +18 -0
- gamengine3d/examples/scripts/breaker_coil.py +17 -0
- gamengine3d/examples/scripts/breaker_decoder.py +39 -0
- gamengine3d/examples/scripts/breaker_gate.py +23 -0
- gamengine3d/examples/scripts/breaker_shield.py +28 -0
- gamengine3d/examples/scripts/coin.py +12 -0
- gamengine3d/examples/scripts/collector.py +13 -0
- gamengine3d/examples/scripts/confetti.py +27 -0
- gamengine3d/examples/scripts/director.py +213 -0
- gamengine3d/examples/scripts/drone.py +21 -0
- gamengine3d/examples/scripts/ghost_pulse.py +24 -0
- gamengine3d/examples/scripts/horror_atmosphere.py +96 -0
- gamengine3d/examples/scripts/interact.py +45 -0
- gamengine3d/examples/scripts/orbiter.py +25 -0
- gamengine3d/examples/scripts/player_controller.py +165 -0
- gamengine3d/examples/scripts/pulse.py +22 -0
- gamengine3d/examples/scripts/reactor_core.py +29 -0
- gamengine3d/examples/scripts/spin.py +13 -0
- gamengine3d/examples/scripts/sway.py +19 -0
- gamengine3d/examples/scripts/void_guard.py +26 -0
- gamengine3d/examples/transparency.py +92 -0
- gamengine3d/game_objects.py +975 -0
- gamengine3d/helper.py +720 -0
- gamengine3d/obj_reader.py +29 -0
- gamengine3d/objects/0.obj +964 -0
- gamengine3d/objects/1.obj +48 -0
- gamengine3d/objects/2.obj +983 -0
- gamengine3d/objects/3.obj +1623 -0
- gamengine3d/objects/4.obj +163 -0
- gamengine3d/objects/5.obj +861 -0
- gamengine3d/objects/6.obj +1314 -0
- gamengine3d/objects/7.obj +70 -0
- gamengine3d/objects/8.obj +1932 -0
- gamengine3d/objects/9.obj +1458 -0
- gamengine3d/objects/A_capital.obj +124 -0
- gamengine3d/objects/B_capital.obj +1118 -0
- gamengine3d/objects/C_capital.obj +1082 -0
- gamengine3d/objects/D_capital.obj +548 -0
- gamengine3d/objects/E_capital.obj +128 -0
- gamengine3d/objects/F_capital.obj +108 -0
- gamengine3d/objects/G_capital.obj +1125 -0
- gamengine3d/objects/H_capital.obj +128 -0
- gamengine3d/objects/I_capital.obj +48 -0
- gamengine3d/objects/J_capital.obj +454 -0
- gamengine3d/objects/K_capital.obj +125 -0
- gamengine3d/objects/L_capital.obj +68 -0
- gamengine3d/objects/M_capital.obj +163 -0
- gamengine3d/objects/N_capital.obj +112 -0
- gamengine3d/objects/O_capital.obj +968 -0
- gamengine3d/objects/P_capital.obj +620 -0
- gamengine3d/objects/Q_capital.obj +1362 -0
- gamengine3d/objects/R_capital.obj +1036 -0
- gamengine3d/objects/S_capital.obj +1346 -0
- gamengine3d/objects/T_capital.obj +88 -0
- gamengine3d/objects/U_capital.obj +860 -0
- gamengine3d/objects/V_capital.obj +81 -0
- gamengine3d/objects/W_capital.obj +147 -0
- gamengine3d/objects/X_capital.obj +136 -0
- gamengine3d/objects/Y_capital.obj +103 -0
- gamengine3d/objects/Z_capital.obj +90 -0
- gamengine3d/objects/__init__.py +0 -0
- gamengine3d/objects/a.obj +1920 -0
- gamengine3d/objects/ampersand.obj +2186 -0
- gamengine3d/objects/asterisk.obj +2512 -0
- gamengine3d/objects/at.obj +2682 -0
- gamengine3d/objects/b.obj +1104 -0
- gamengine3d/objects/backslash.obj +48 -0
- gamengine3d/objects/brace_close.obj +1179 -0
- gamengine3d/objects/brace_open.obj +1179 -0
- gamengine3d/objects/bracket_close.obj +88 -0
- gamengine3d/objects/bracket_open.obj +88 -0
- gamengine3d/objects/c.obj +1082 -0
- gamengine3d/objects/caret.obj +81 -0
- gamengine3d/objects/colon.obj +912 -0
- gamengine3d/objects/comma.obj +675 -0
- gamengine3d/objects/d.obj +861 -0
- gamengine3d/objects/dash.obj +48 -0
- gamengine3d/objects/dollar.obj +1671 -0
- gamengine3d/objects/dot.obj +532 -0
- gamengine3d/objects/doublequote.obj +114 -0
- gamengine3d/objects/e.obj +1094 -0
- gamengine3d/objects/equals.obj +76 -0
- gamengine3d/objects/exclamation.obj +1336 -0
- gamengine3d/objects/f.obj +660 -0
- gamengine3d/objects/g.obj +2694 -0
- gamengine3d/objects/greater.obj +81 -0
- gamengine3d/objects/h.obj +628 -0
- gamengine3d/objects/hash.obj +332 -0
- gamengine3d/objects/i.obj +558 -0
- gamengine3d/objects/j.obj +824 -0
- gamengine3d/objects/k.obj +104 -0
- gamengine3d/objects/l.obj +48 -0
- gamengine3d/objects/less.obj +81 -0
- gamengine3d/objects/m.obj +1177 -0
- gamengine3d/objects/n.obj +628 -0
- gamengine3d/objects/o.obj +968 -0
- gamengine3d/objects/p.obj +861 -0
- gamengine3d/objects/paren_close.obj +554 -0
- gamengine3d/objects/paren_open.obj +554 -0
- gamengine3d/objects/percent.obj +1767 -0
- gamengine3d/objects/plus.obj +128 -0
- gamengine3d/objects/q.obj +861 -0
- gamengine3d/objects/question.obj +1306 -0
- gamengine3d/objects/r.obj +608 -0
- gamengine3d/objects/s.obj +1478 -0
- gamengine3d/objects/semicolon.obj +1185 -0
- gamengine3d/objects/singlequote.obj +70 -0
- gamengine3d/objects/slash.obj +48 -0
- gamengine3d/objects/t.obj +639 -0
- gamengine3d/objects/u.obj +618 -0
- gamengine3d/objects/underscore.obj +48 -0
- gamengine3d/objects/v.obj +81 -0
- gamengine3d/objects/w.obj +147 -0
- gamengine3d/objects/x.obj +136 -0
- gamengine3d/objects/y.obj +92 -0
- gamengine3d/objects/z.obj +90 -0
- gamengine3d/renderer.py +1390 -0
- gamengine3d/shaders/__init__.py +0 -0
- gamengine3d/shaders/default.frag +143 -0
- gamengine3d/shaders/default.vert +43 -0
- gamengine3d/shaders/depth.frag +2 -0
- gamengine3d/shaders/depth.vert +9 -0
- gamengine3d-0.5.0.dist-info/METADATA +177 -0
- gamengine3d-0.5.0.dist-info/RECORD +141 -0
- gamengine3d-0.5.0.dist-info/WHEEL +5 -0
- gamengine3d-0.5.0.dist-info/entry_points.txt +2 -0
- gamengine3d-0.5.0.dist-info/licenses/LICENSE.txt +21 -0
- gamengine3d-0.5.0.dist-info/top_level.txt +1 -0
gamengine3d/engine.py
ADDED
|
@@ -0,0 +1,715 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
from itertools import product
|
|
4
|
+
|
|
5
|
+
from pyrr import Matrix44
|
|
6
|
+
from .context import Context
|
|
7
|
+
import pygame
|
|
8
|
+
from .game_objects import Cuboid, GameObject, Sphere, Cylinder, ObjModel, Text, ImageOverlay
|
|
9
|
+
from .helper import vector3d, Color, Light, EngineError, Script, ray_intersect_aabb, vector2d
|
|
10
|
+
from .renderer import Renderer, Camera
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
import math
|
|
13
|
+
|
|
14
|
+
class Engine:
|
|
15
|
+
def __init__(self, width=500, height=500, resizable=True, name="GamEngine3d", background_color=Color.light_grey, ambient_light=.2, gpu="auto", shadow_size=2048):
|
|
16
|
+
"""gpu: "auto", "nvidia" or "intel" — selects which OpenGL device is used
|
|
17
|
+
(or set the GAMENGINE3D_GPU env var). "auto" prefers the discrete
|
|
18
|
+
NVIDIA GPU on hybrid laptops, falling back to the default when none.
|
|
19
|
+
shadow_size: resolution of each per-light shadow map (2048 default;
|
|
20
|
+
drop to 1024 for cheaper shadow rendering)."""
|
|
21
|
+
self.width = width
|
|
22
|
+
self.height = height
|
|
23
|
+
self.resizable = resizable
|
|
24
|
+
self.window_name = name
|
|
25
|
+
self.background_color = background_color
|
|
26
|
+
self.scripts = []
|
|
27
|
+
self.script_paths = []
|
|
28
|
+
self.debug_picking = False
|
|
29
|
+
|
|
30
|
+
flags = pygame.DOUBLEBUF | pygame.OPENGL
|
|
31
|
+
if self.resizable:
|
|
32
|
+
flags |= pygame.RESIZABLE
|
|
33
|
+
|
|
34
|
+
pygame.display.set_caption(self.window_name)
|
|
35
|
+
self.renderer = Renderer(width, height, flags=flags, gpu=gpu, shadow_size=shadow_size)
|
|
36
|
+
self.renderer.ambient = ambient_light
|
|
37
|
+
self.clock = pygame.time.Clock()
|
|
38
|
+
|
|
39
|
+
self.camera = Camera(position=vector3d(0, 1.5, 3),
|
|
40
|
+
target=vector3d(0, 0, 0),
|
|
41
|
+
aspect_ratio=self.width / self.height)
|
|
42
|
+
|
|
43
|
+
self.last_mouse_pos = None
|
|
44
|
+
self.mouse_sensitivity = 0.3
|
|
45
|
+
self.pan_sensitivity = 0.005
|
|
46
|
+
self.active_button = None
|
|
47
|
+
self._grab_state = None
|
|
48
|
+
self._mouse_last_pos = None
|
|
49
|
+
self._mouse_saw_motion = False
|
|
50
|
+
self._mouse_diag_frames = 0
|
|
51
|
+
|
|
52
|
+
self.gameobjects = []
|
|
53
|
+
self.package_folder = Path(__file__).parent
|
|
54
|
+
|
|
55
|
+
self.context = Context()
|
|
56
|
+
|
|
57
|
+
self.context.functions.draw_cube = self.draw_cuboid
|
|
58
|
+
self.context.functions.draw_sphere = self.draw_sphere
|
|
59
|
+
self.context.functions.add_light = self.add_light
|
|
60
|
+
self.context.functions.add_object = self.add_object
|
|
61
|
+
self.context.functions.draw_cylinder = self.draw_cylinder
|
|
62
|
+
self.context.functions.get_game_object = self.get_object
|
|
63
|
+
self.context.functions.is_colliding = self.is_colliding
|
|
64
|
+
self.context.functions.remove_light = self.remove_light
|
|
65
|
+
self.context.functions.remove_object = self.remove_object
|
|
66
|
+
self.context.functions.is_colliding_pos = self.is_colliding_pos
|
|
67
|
+
self.context.functions.is_near = self.is_near
|
|
68
|
+
self.context.functions.save_scene = self.save_scene
|
|
69
|
+
self.context.functions.load_scene = self.load_scene
|
|
70
|
+
self.context.functions.load_image = self.renderer.load_image
|
|
71
|
+
self.context.functions.render_image = self.renderer.render_image
|
|
72
|
+
|
|
73
|
+
self.context.game_objects = self.gameobjects
|
|
74
|
+
self.context.engine = self
|
|
75
|
+
self.context.camera = self.camera
|
|
76
|
+
self.context.renderer = self.renderer
|
|
77
|
+
self.context.clock = self.clock
|
|
78
|
+
|
|
79
|
+
self.renderer.load_image(str(self.package_folder / "assets" / "plus_sign_crosshair.png"), key="plus-sign-crosshair")
|
|
80
|
+
self.renderer.load_image(str(self.package_folder / "assets" / "circular_crosshair.png"), key="circular-crosshair")
|
|
81
|
+
|
|
82
|
+
self.crosshair = None
|
|
83
|
+
self.crosshair_scale = vector2d.one
|
|
84
|
+
self.crosshair_position = vector2d.zero
|
|
85
|
+
self.crosshair_rotation = 0
|
|
86
|
+
self.flip_crosshair_x = False
|
|
87
|
+
self.flip_crosshair_y = False
|
|
88
|
+
|
|
89
|
+
self.context.crosshair = self.crosshair
|
|
90
|
+
self.context.crosshair_scale = self.crosshair_scale
|
|
91
|
+
self.context.crosshair_position = self.crosshair_position
|
|
92
|
+
self.context.crosshair_rotation = self.crosshair_rotation
|
|
93
|
+
self.context.flip_crosshair_x = self.flip_crosshair_x
|
|
94
|
+
self.context.flip_crosshair_y = self.flip_crosshair_y
|
|
95
|
+
|
|
96
|
+
self.context.lights = self.renderer.lights
|
|
97
|
+
self.context.ambient_light = ambient_light
|
|
98
|
+
|
|
99
|
+
def run(self, fps=60, dynamic_view=True):
|
|
100
|
+
running = True
|
|
101
|
+
self.context.fps = fps
|
|
102
|
+
keys_held = []
|
|
103
|
+
self.context.keys_held = keys_held
|
|
104
|
+
self.init_scripts()
|
|
105
|
+
|
|
106
|
+
for script in self.scripts:
|
|
107
|
+
script.run("on_start")
|
|
108
|
+
|
|
109
|
+
while running:
|
|
110
|
+
keys_pressed = []
|
|
111
|
+
keys_released = []
|
|
112
|
+
dt = self.clock.get_time() / 1000
|
|
113
|
+
self.mouse_sensitivity = self.context.mouse_sensitivity
|
|
114
|
+
self.pan_sensitivity = self.context.pan_sensitivity
|
|
115
|
+
self.context.fps = self.clock.get_fps()
|
|
116
|
+
|
|
117
|
+
# Mouse look owns mouse motion exclusively. Rotation is accumulated from
|
|
118
|
+
# MOUSEMOTION events (event.rel), applied in a single dedicated step
|
|
119
|
+
# after the event loop, so it is fully decoupled from grab state,
|
|
120
|
+
# window focus, dynamic_view drag handlers, keyboard input, and the
|
|
121
|
+
# ESC release / click re-capture cycle. ESC only shows the cursor
|
|
122
|
+
# (pauses look); any click re-arms look without any script.
|
|
123
|
+
mouse_look = getattr(self.context, "mouse_look", False)
|
|
124
|
+
released = getattr(self.context, "mouse_released", False)
|
|
125
|
+
_look_debug = os.environ.get("GAMENGINE3D_LOOK_DEBUG") == "1"
|
|
126
|
+
if _look_debug:
|
|
127
|
+
_pp = ""
|
|
128
|
+
for _o in self.gameobjects:
|
|
129
|
+
if getattr(_o, "name", None) == "Player":
|
|
130
|
+
_pp = f" player=({_o.pos.x:.2f},{_o.pos.y:.2f},{_o.pos.z:.2f})"
|
|
131
|
+
break
|
|
132
|
+
print(f"[look] frame ml={mouse_look} rel={released} grab={pygame.event.get_grab()} vis={pygame.mouse.get_visible()} keys={list(keys_held)} relraw={pygame.mouse.get_rel()}{_pp}")
|
|
133
|
+
pygame.mouse.set_visible(released or not mouse_look)
|
|
134
|
+
want_grab = bool(mouse_look and not released)
|
|
135
|
+
if pygame.event.get_grab() != want_grab:
|
|
136
|
+
pygame.event.set_grab(want_grab)
|
|
137
|
+
if want_grab:
|
|
138
|
+
pygame.mouse.get_rel() # discard the initial warp delta
|
|
139
|
+
|
|
140
|
+
if mouse_look:
|
|
141
|
+
self.camera.mouse_look = True
|
|
142
|
+
if self.camera.orbiting:
|
|
143
|
+
self.camera.set_orbiting(False)
|
|
144
|
+
|
|
145
|
+
mouse_dx = 0
|
|
146
|
+
mouse_dy = 0
|
|
147
|
+
|
|
148
|
+
for event in pygame.event.get():
|
|
149
|
+
if event.type == pygame.QUIT:
|
|
150
|
+
running = False
|
|
151
|
+
|
|
152
|
+
if self.resizable and event.type == pygame.VIDEORESIZE:
|
|
153
|
+
self.width, self.height = event.w, event.h
|
|
154
|
+
self.renderer.resize(self.width, self.height)
|
|
155
|
+
|
|
156
|
+
self.camera.aspect_ratio = self.width / self.height
|
|
157
|
+
|
|
158
|
+
old_pos = self.camera.position.copy()
|
|
159
|
+
self.camera.move_to(vector3d.one)
|
|
160
|
+
self.camera.move_to(old_pos)
|
|
161
|
+
|
|
162
|
+
if dynamic_view:
|
|
163
|
+
if event.type == pygame.MOUSEBUTTONDOWN:
|
|
164
|
+
if not getattr(self.context, "mouse_look", False) and event.button in (1, 3):
|
|
165
|
+
self.last_mouse_pos = pygame.mouse.get_pos()
|
|
166
|
+
self.active_button = event.button
|
|
167
|
+
|
|
168
|
+
elif event.type == pygame.MOUSEBUTTONUP:
|
|
169
|
+
if not getattr(self.context, "mouse_look", False) and event.button in (1, 3):
|
|
170
|
+
self.last_mouse_pos = None
|
|
171
|
+
self.active_button = None
|
|
172
|
+
|
|
173
|
+
elif event.type == pygame.MOUSEMOTION:
|
|
174
|
+
if not getattr(self.context, "mouse_look", False) and self.last_mouse_pos is not None:
|
|
175
|
+
x, y = pygame.mouse.get_pos()
|
|
176
|
+
dx = x - self.last_mouse_pos[0]
|
|
177
|
+
dy = y - self.last_mouse_pos[1]
|
|
178
|
+
self.last_mouse_pos = (x, y)
|
|
179
|
+
|
|
180
|
+
if self.active_button == 3:
|
|
181
|
+
self.camera.rotate_around_target(-dx * self.mouse_sensitivity, dy * self.mouse_sensitivity)
|
|
182
|
+
|
|
183
|
+
elif self.active_button == 1:
|
|
184
|
+
self._pan_camera(dx, dy)
|
|
185
|
+
|
|
186
|
+
elif event.type == pygame.MOUSEWHEEL:
|
|
187
|
+
self.camera.zoom(event.y * 0.5)
|
|
188
|
+
|
|
189
|
+
# Mouse look accumulates relative motion from every
|
|
190
|
+
# MOUSEMOTION event as long as look is armed and not released.
|
|
191
|
+
# Deliberately NOT chained to the dynamic_view handlers above,
|
|
192
|
+
# so look works during scripts that move the player (walking).
|
|
193
|
+
if (
|
|
194
|
+
mouse_look
|
|
195
|
+
and not released
|
|
196
|
+
and event.type == pygame.MOUSEMOTION
|
|
197
|
+
):
|
|
198
|
+
mouse_dx += event.rel[0]
|
|
199
|
+
mouse_dy += event.rel[1]
|
|
200
|
+
if _look_debug:
|
|
201
|
+
print(f"[look] motion rel={event.rel} accum=({mouse_dx},{mouse_dy})")
|
|
202
|
+
|
|
203
|
+
if event.type == pygame.KEYDOWN:
|
|
204
|
+
key_name = pygame.key.name(event.key)
|
|
205
|
+
if key_name == "escape" and getattr(self.context, "mouse_look", False):
|
|
206
|
+
self.context.mouse_released = True
|
|
207
|
+
keys_pressed.append(key_name)
|
|
208
|
+
keys_held.append(key_name)
|
|
209
|
+
|
|
210
|
+
elif event.type == pygame.KEYUP:
|
|
211
|
+
key_name = pygame.key.name(event.key)
|
|
212
|
+
keys_held.remove(key_name)
|
|
213
|
+
keys_released.append(key_name)
|
|
214
|
+
|
|
215
|
+
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
|
|
216
|
+
# Click to recapture the mouse after ESC released it,
|
|
217
|
+
# or to re-arm the initial look when the camera entered
|
|
218
|
+
# mouse-look mode from an explicit script call.
|
|
219
|
+
if getattr(self.context, "mouse_look", False) and getattr(self.context, "mouse_released", False):
|
|
220
|
+
self.context.mouse_released = False
|
|
221
|
+
elif not getattr(self.context, "mouse_look", False) and getattr(self.camera, "mouse_look", False):
|
|
222
|
+
self.context.mouse_look = True
|
|
223
|
+
self.context.mouse_released = False
|
|
224
|
+
|
|
225
|
+
# Apply accumulated mouse look — a single dedicated step driven
|
|
226
|
+
# only by the look intent, decoupled from grab state,
|
|
227
|
+
# dynamic_view drag handlers, and key input, so it keeps working
|
|
228
|
+
# while player-movement scripts move the camera.
|
|
229
|
+
if (mouse_look and not released) and (mouse_dx or mouse_dy):
|
|
230
|
+
if _look_debug:
|
|
231
|
+
print(f"[look] APPLY rotate(dx={mouse_dx}, dy={mouse_dy})")
|
|
232
|
+
self.camera.rotate_look(
|
|
233
|
+
mouse_dx * self.mouse_sensitivity,
|
|
234
|
+
-mouse_dy * self.mouse_sensitivity,
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
self.context.keys_pressed = keys_pressed
|
|
238
|
+
self.context.keys_released = keys_released
|
|
239
|
+
self.context.update(dt)
|
|
240
|
+
|
|
241
|
+
self.renderer.render_shadow_pass(self.gameobjects)
|
|
242
|
+
self.renderer.clear(self.background_color)
|
|
243
|
+
|
|
244
|
+
self.renderer.ambient = self.context.ambient_light
|
|
245
|
+
|
|
246
|
+
self.renderer.shadows = True
|
|
247
|
+
|
|
248
|
+
for script in self.scripts:
|
|
249
|
+
script.update(dt)
|
|
250
|
+
|
|
251
|
+
for obj in self.gameobjects:
|
|
252
|
+
self.context.push_caller(obj)
|
|
253
|
+
obj.update(dt)
|
|
254
|
+
self.camera.update_renderer(self.renderer)
|
|
255
|
+
|
|
256
|
+
for obj in self.gameobjects:
|
|
257
|
+
self.context.push_caller(obj)
|
|
258
|
+
obj.draw(self.renderer)
|
|
259
|
+
|
|
260
|
+
if self.context.exit:
|
|
261
|
+
running = False
|
|
262
|
+
|
|
263
|
+
if self.crosshair:
|
|
264
|
+
self.renderer.render_image(key=self.crosshair, position=self.crosshair_position, scale=self.crosshair_scale, rotation=self.crosshair_rotation, flip_x=self.flip_crosshair_x, flip_y=self.flip_crosshair_y)
|
|
265
|
+
|
|
266
|
+
self.renderer.flush()
|
|
267
|
+
self.renderer.swap()
|
|
268
|
+
self.clock.tick(fps)
|
|
269
|
+
|
|
270
|
+
for script in self.scripts:
|
|
271
|
+
script.run("on_exit")
|
|
272
|
+
self.renderer.quit()
|
|
273
|
+
|
|
274
|
+
def _pan_camera(self, dx, dy):
|
|
275
|
+
forward = (self.camera.target - self.camera.position).normalized
|
|
276
|
+
right = forward.cross(self.camera.up).normalized
|
|
277
|
+
up = self.camera.up.normalized
|
|
278
|
+
|
|
279
|
+
pan = (right * -dx + up * dy) * self.pan_sensitivity * self.camera.radius
|
|
280
|
+
self.camera.target += pan
|
|
281
|
+
self.camera.position += pan
|
|
282
|
+
self.camera._update_position()
|
|
283
|
+
|
|
284
|
+
def add_light(self, light):
|
|
285
|
+
self.renderer.add_light(light)
|
|
286
|
+
if light.show:
|
|
287
|
+
self.add_object(Sphere(pos=light.position, color=light.color, radius=.1))
|
|
288
|
+
|
|
289
|
+
def add_object(self, obj: GameObject):
|
|
290
|
+
self.gameobjects.append(obj)
|
|
291
|
+
|
|
292
|
+
def remove_object(self, name):
|
|
293
|
+
obj = self.get_object(name)
|
|
294
|
+
self.gameobjects.remove(obj)
|
|
295
|
+
|
|
296
|
+
def remove_light(self, name):
|
|
297
|
+
for light in self.renderer.lights:
|
|
298
|
+
if light.name == name:
|
|
299
|
+
self.renderer.lights.remove(light)
|
|
300
|
+
return
|
|
301
|
+
|
|
302
|
+
raise EngineError(f"No Light Object Named {name}")
|
|
303
|
+
|
|
304
|
+
def get_object(self, name):
|
|
305
|
+
for obj in self.gameobjects:
|
|
306
|
+
if obj.name == name:
|
|
307
|
+
return obj
|
|
308
|
+
|
|
309
|
+
raise EngineError(f"Game Object with name {name} not found")
|
|
310
|
+
|
|
311
|
+
def is_colliding(self, name1, name2):
|
|
312
|
+
obj1 = self.get_object(name1)
|
|
313
|
+
obj2 = self.get_object(name2)
|
|
314
|
+
|
|
315
|
+
if not (isinstance(obj1, (Cuboid, ObjModel)) and isinstance(obj2, (Cuboid, ObjModel))):
|
|
316
|
+
raise NotImplementedError(f"Cylinder And Sphere Collision Not Implemented")
|
|
317
|
+
|
|
318
|
+
corners = obj1.get_corners()
|
|
319
|
+
for corner in corners:
|
|
320
|
+
if obj2.is_point_in(corner):
|
|
321
|
+
return True
|
|
322
|
+
|
|
323
|
+
return False
|
|
324
|
+
|
|
325
|
+
def is_colliding_pos(self, name, pos):
|
|
326
|
+
obj = self.get_object(name)
|
|
327
|
+
if not isinstance(obj, Cuboid):
|
|
328
|
+
raise NotImplementedError(f"Cylinder And Sphere Collision Not Implemented")
|
|
329
|
+
|
|
330
|
+
return obj.is_point_in(pos)
|
|
331
|
+
|
|
332
|
+
def is_near(self, name1, name2, radius):
|
|
333
|
+
obj1 = self.get_object(name1).pos
|
|
334
|
+
obj2 = self.get_object(name2).pos
|
|
335
|
+
|
|
336
|
+
return (obj1.x - obj2.x) ** 2 + (obj1.y - obj2.y) ** 2 + (obj1.z - obj2.z) ** 2 <= radius ** 2
|
|
337
|
+
|
|
338
|
+
def draw_cuboid(self, pos: vector3d=None, size: vector3d=None, rotation: vector3d=None, color: Color = Color.light_blue, emit: bool = False, transparency: float = 1.0):
|
|
339
|
+
if pos is None:
|
|
340
|
+
pos = vector3d.zero
|
|
341
|
+
if size is None:
|
|
342
|
+
size = vector3d(2)
|
|
343
|
+
if rotation is None:
|
|
344
|
+
rotation = vector3d.zero
|
|
345
|
+
faces = [
|
|
346
|
+
[0, 1, 3, 2],
|
|
347
|
+
[4, 6, 7, 5],
|
|
348
|
+
[0, 4, 5, 1],
|
|
349
|
+
[2, 3, 7, 6],
|
|
350
|
+
[0, 2, 6, 4],
|
|
351
|
+
[1, 5, 7, 3],
|
|
352
|
+
]
|
|
353
|
+
|
|
354
|
+
half_size = size / 2
|
|
355
|
+
|
|
356
|
+
rot_matrix = Matrix44.from_eulers((
|
|
357
|
+
math.radians(rotation.x),
|
|
358
|
+
math.radians(rotation.y),
|
|
359
|
+
math.radians(rotation.z)
|
|
360
|
+
))
|
|
361
|
+
|
|
362
|
+
corners = []
|
|
363
|
+
for dx, dy, dz in product([-1, 1], repeat=3):
|
|
364
|
+
local = vector3d(dx * half_size.x, dy * half_size.y, dz * half_size.z)
|
|
365
|
+
|
|
366
|
+
rotated = vector3d(
|
|
367
|
+
*(rot_matrix @ [local.x, local.y, local.z, 1.0])[:3]
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
world = pos + rotated
|
|
371
|
+
corners.append(world)
|
|
372
|
+
|
|
373
|
+
for face_idx in faces:
|
|
374
|
+
self.renderer.render_quad(
|
|
375
|
+
corners[face_idx[0]],
|
|
376
|
+
corners[face_idx[1]],
|
|
377
|
+
corners[face_idx[2]],
|
|
378
|
+
corners[face_idx[3]],
|
|
379
|
+
color=color,
|
|
380
|
+
emit=emit,
|
|
381
|
+
alpha=transparency,
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
def draw_sphere(self, pos: vector3d=None, radius: int=2, color: Color=Color.light_red, segments=32, rings=16, emit: bool = False, transparency: float = 1.0):
|
|
385
|
+
if pos is None:
|
|
386
|
+
pos = vector3d.zero
|
|
387
|
+
self.renderer.render_sphere(center=pos, radius=radius, color=color, segments=segments, rings=rings, emit=emit, alpha=transparency)
|
|
388
|
+
|
|
389
|
+
def draw_cylinder(self, pos: vector3d=None, length: int=2, radius: int=.5, color: Color=Color.light_yellow, segments: int=32, rotation: vector3d=None, emit: bool = False, transparency: float = 1.0):
|
|
390
|
+
if pos is None:
|
|
391
|
+
pos = vector3d.zero
|
|
392
|
+
if rotation is None:
|
|
393
|
+
rotation = vector3d.zero
|
|
394
|
+
self.renderer.render_cylinder(center=pos, height=length, radius=radius, color=color, segments=segments, rotation=rotation, emit=emit, alpha=transparency)
|
|
395
|
+
|
|
396
|
+
def attach(self, path):
|
|
397
|
+
script = Script(self, path, self.context)
|
|
398
|
+
script.init_instance()
|
|
399
|
+
self.script_paths.append(path)
|
|
400
|
+
self.scripts.append(script)
|
|
401
|
+
|
|
402
|
+
def attach_scripts(self, scripts):
|
|
403
|
+
for path in scripts:
|
|
404
|
+
self.attach(path)
|
|
405
|
+
|
|
406
|
+
def init_scripts(self):
|
|
407
|
+
for script in self.scripts:
|
|
408
|
+
script.init_instance()
|
|
409
|
+
|
|
410
|
+
def physics_update(self, dt):
|
|
411
|
+
for obj in self.gameobjects:
|
|
412
|
+
if isinstance(obj, Cuboid):
|
|
413
|
+
cube = obj
|
|
414
|
+
rb = cube.rigid_body
|
|
415
|
+
if rb is not None:
|
|
416
|
+
if rb.gravity:
|
|
417
|
+
rb.velocity += vector3d.down * 9.8 * dt
|
|
418
|
+
|
|
419
|
+
# integrate forces
|
|
420
|
+
rb.velocity += (rb.forces / rb.mass) * dt
|
|
421
|
+
rb.forces = vector3d.zero
|
|
422
|
+
|
|
423
|
+
# integrate movement
|
|
424
|
+
cube.pos += rb.velocity * dt
|
|
425
|
+
|
|
426
|
+
def resolve_collision(self, name1, name2):
|
|
427
|
+
obj1 = self.get_object(name1)
|
|
428
|
+
obj2 = self.get_object(name2)
|
|
429
|
+
|
|
430
|
+
if not (isinstance(obj1, Cuboid) and isinstance(obj2, Cuboid)):
|
|
431
|
+
raise NotImplementedError("Cylinder And Sphere Collision Not Implemented")
|
|
432
|
+
|
|
433
|
+
# If they do not overlap, exit
|
|
434
|
+
if not self.is_colliding(name1, name2):
|
|
435
|
+
return
|
|
436
|
+
|
|
437
|
+
rb = obj1.rigid_body # the moving object
|
|
438
|
+
# obj2 may or may not have rigid body — we treat it as static for now
|
|
439
|
+
|
|
440
|
+
# Determine correction direction by checking corners
|
|
441
|
+
corners = obj1.get_corners()
|
|
442
|
+
|
|
443
|
+
min_penetration = float("inf")
|
|
444
|
+
best_axis = None
|
|
445
|
+
|
|
446
|
+
for corner in corners:
|
|
447
|
+
if obj2.is_point_in(corner):
|
|
448
|
+
# penetration vector = from obj2 center to corner
|
|
449
|
+
penetration_vec = corner - obj2.pos
|
|
450
|
+
# absolute magnitude along each axis
|
|
451
|
+
px = abs(penetration_vec.x)
|
|
452
|
+
py = abs(penetration_vec.y)
|
|
453
|
+
pz = abs(penetration_vec.z)
|
|
454
|
+
|
|
455
|
+
# pick smallest axis penetration
|
|
456
|
+
axis_val = min(px, py, pz)
|
|
457
|
+
if axis_val < min_penetration:
|
|
458
|
+
min_penetration = axis_val
|
|
459
|
+
if axis_val == px:
|
|
460
|
+
best_axis = vector3d.right if penetration_vec.x > 0 else vector3d.left
|
|
461
|
+
elif axis_val == py:
|
|
462
|
+
best_axis = vector3d.up if penetration_vec.y > 0 else vector3d.down
|
|
463
|
+
else:
|
|
464
|
+
best_axis = vector3d.forward if penetration_vec.z > 0 else vector3d.back
|
|
465
|
+
|
|
466
|
+
if best_axis is None:
|
|
467
|
+
return
|
|
468
|
+
|
|
469
|
+
correction = best_axis * min_penetration
|
|
470
|
+
obj1.pos += correction
|
|
471
|
+
|
|
472
|
+
normal = best_axis.normalized()
|
|
473
|
+
vel_along_normal = rb.velocity.dot(normal)
|
|
474
|
+
|
|
475
|
+
if vel_along_normal < 0:
|
|
476
|
+
rb.velocity -= (1 + rb.bounce) * vel_along_normal * normal
|
|
477
|
+
|
|
478
|
+
def pick_at_screen(self, x, y):
|
|
479
|
+
"""
|
|
480
|
+
Return (obj, hit_point, t) for nearest hit, or None.
|
|
481
|
+
Uses camera.position as ray origin and camera.screen_point_to_ray to get direction.
|
|
482
|
+
"""
|
|
483
|
+
# get direction from camera unprojection; use camera.position as origin for robustness
|
|
484
|
+
try:
|
|
485
|
+
# screen_point_to_ray may return (origin, direction) depending on your implementation;
|
|
486
|
+
# we only need direction here and will use camera.position as origin.
|
|
487
|
+
_, direction = self.camera.screen_point_to_ray(x, y, self.width, self.height)
|
|
488
|
+
except Exception:
|
|
489
|
+
direction = (self.camera.target - self.camera.position).normalized
|
|
490
|
+
|
|
491
|
+
origin = self.camera.position.copy()
|
|
492
|
+
|
|
493
|
+
closest_t = float("inf")
|
|
494
|
+
closest_obj = None
|
|
495
|
+
hit_point = None
|
|
496
|
+
|
|
497
|
+
# iterate all gameobjects and test AABB (get_corners or get_size)
|
|
498
|
+
for obj in self.gameobjects:
|
|
499
|
+
# compute object's AABB (axis-aligned bounding box in world space)
|
|
500
|
+
if hasattr(obj, "get_corners"):
|
|
501
|
+
corners = obj.get_corners()
|
|
502
|
+
xs = [float(c.x) for c in corners]
|
|
503
|
+
ys = [float(c.y) for c in corners]
|
|
504
|
+
zs = [float(c.z) for c in corners]
|
|
505
|
+
amin = vector3d(min(xs), min(ys), min(zs))
|
|
506
|
+
amax = vector3d(max(xs), max(ys), max(zs))
|
|
507
|
+
elif hasattr(obj, "get_size"):
|
|
508
|
+
s = obj.get_size()
|
|
509
|
+
if s is None:
|
|
510
|
+
continue
|
|
511
|
+
amin, amax = s
|
|
512
|
+
else:
|
|
513
|
+
continue
|
|
514
|
+
|
|
515
|
+
if getattr(self, "debug_picking", False):
|
|
516
|
+
print(f"[pick] testing {obj.name} AABB min={amin} max={amax}")
|
|
517
|
+
|
|
518
|
+
res = ray_intersect_aabb(origin, direction, amin, amax)
|
|
519
|
+
# require non-negative t and prefer smallest positive t
|
|
520
|
+
if res is not None and res >= 0 and res < closest_t:
|
|
521
|
+
closest_t = res
|
|
522
|
+
closest_obj = obj
|
|
523
|
+
hit_point = origin + direction * res
|
|
524
|
+
if getattr(self, "debug_picking", False):
|
|
525
|
+
print(f"[pick] hit {obj.name} t={res} hit_point={hit_point}")
|
|
526
|
+
|
|
527
|
+
if closest_obj:
|
|
528
|
+
return closest_obj, hit_point, closest_t
|
|
529
|
+
return None
|
|
530
|
+
|
|
531
|
+
def pick_forward_sample(self, max_distance: float = 5.0, step: float = 0.05):
|
|
532
|
+
"""
|
|
533
|
+
Cast a ray from camera.position in camera forward direction, stepping along the ray
|
|
534
|
+
up to max_distance with the given step. For each sample point, test object.is_point_in(point)
|
|
535
|
+
where available. Returns (obj, hit_point, t) for the first object hit, or None.
|
|
536
|
+
This matches 'shoot that ray until threshold like 5 units' behaviour.
|
|
537
|
+
"""
|
|
538
|
+
# forward direction: if camera is orbiting, direction toward target; else use look_dir
|
|
539
|
+
if getattr(self.camera, 'orbiting', True):
|
|
540
|
+
forward = (self.camera.target - self.camera.position).normalized
|
|
541
|
+
else:
|
|
542
|
+
forward = getattr(self.camera, 'look_dir', vector3d(0, 0, -1)).normalized
|
|
543
|
+
|
|
544
|
+
origin = self.camera.position.copy()
|
|
545
|
+
|
|
546
|
+
if getattr(self, "debug_picking", False):
|
|
547
|
+
print(f"[pick_forward_sample] origin={origin} forward={forward} max_distance={max_distance} step={step}")
|
|
548
|
+
|
|
549
|
+
t = 0.0
|
|
550
|
+
while t <= max_distance:
|
|
551
|
+
sample_point = origin + forward * t
|
|
552
|
+
# check each object using their point-in tests where available
|
|
553
|
+
for obj in self.gameobjects:
|
|
554
|
+
# Many types expose is_point_in (Cuboid, Sphere, Cylinder)
|
|
555
|
+
if hasattr(obj, "is_point_in"):
|
|
556
|
+
try:
|
|
557
|
+
if obj.is_point_in(sample_point):
|
|
558
|
+
if getattr(self, "debug_picking", False):
|
|
559
|
+
print(f"[pick_forward_sample] hit {obj.name} at t={t} sample_point={sample_point}")
|
|
560
|
+
return obj, sample_point, t
|
|
561
|
+
except Exception:
|
|
562
|
+
# ignore objects whose is_point_in may raise or not support this point exactly
|
|
563
|
+
pass
|
|
564
|
+
else:
|
|
565
|
+
# fallback: if object has get_corners/get_size, test AABB containment
|
|
566
|
+
if hasattr(obj, "get_corners"):
|
|
567
|
+
corners = obj.get_corners()
|
|
568
|
+
xs = [float(c.x) for c in corners]
|
|
569
|
+
ys = [float(c.y) for c in corners]
|
|
570
|
+
zs = [float(c.z) for c in corners]
|
|
571
|
+
amin = vector3d(min(xs), min(ys), min(zs))
|
|
572
|
+
amax = vector3d(max(xs), max(ys), max(zs))
|
|
573
|
+
elif hasattr(obj, "get_size"):
|
|
574
|
+
s = obj.get_size()
|
|
575
|
+
if s is None:
|
|
576
|
+
continue
|
|
577
|
+
amin, amax = s
|
|
578
|
+
else:
|
|
579
|
+
continue
|
|
580
|
+
|
|
581
|
+
# simple point-in-AABB test
|
|
582
|
+
if (amin.x - 1e-9 <= sample_point.x <= amax.x + 1e-9 and
|
|
583
|
+
amin.y - 1e-9 <= sample_point.y <= amax.y + 1e-9 and
|
|
584
|
+
amin.z - 1e-9 <= sample_point.z <= amax.z + 1e-9):
|
|
585
|
+
if getattr(self, "debug_picking", False):
|
|
586
|
+
print(f"[pick_forward_sample] hit (AABB) {obj.name} at t={t} sample_point={sample_point}")
|
|
587
|
+
return obj, sample_point, t
|
|
588
|
+
|
|
589
|
+
t += step
|
|
590
|
+
|
|
591
|
+
if getattr(self, "debug_picking", False):
|
|
592
|
+
print("[pick_forward_sample] no hit within max_distance")
|
|
593
|
+
return None
|
|
594
|
+
|
|
595
|
+
def pick_forward(self, max_distance: float = 5.0):
|
|
596
|
+
"""
|
|
597
|
+
Fast ray-AABB test from camera.position along camera forward direction.
|
|
598
|
+
Returns (obj, hit_point, t) of nearest hit within max_distance, or None.
|
|
599
|
+
Uses `ray_intersect_aabb` from helper.py.
|
|
600
|
+
"""
|
|
601
|
+
# forward direction: if camera is orbiting, direction toward target; else use look_dir
|
|
602
|
+
if getattr(self.camera, 'orbiting', True):
|
|
603
|
+
forward = (self.camera.target - self.camera.position).normalized
|
|
604
|
+
else:
|
|
605
|
+
forward = getattr(self.camera, 'look_dir', vector3d(0, 0, -1)).normalized
|
|
606
|
+
|
|
607
|
+
origin = self.camera.position.copy()
|
|
608
|
+
|
|
609
|
+
if getattr(self, "debug_picking", False):
|
|
610
|
+
print(f"[pick_forward] origin={origin} forward={forward} max_distance={max_distance}")
|
|
611
|
+
|
|
612
|
+
closest_t = float('inf')
|
|
613
|
+
closest_obj = None
|
|
614
|
+
hit_point = None
|
|
615
|
+
|
|
616
|
+
for obj in self.gameobjects:
|
|
617
|
+
# get world-space AABB
|
|
618
|
+
if hasattr(obj, "get_corners"):
|
|
619
|
+
corners = obj.get_corners()
|
|
620
|
+
xs = [float(c.x) for c in corners]
|
|
621
|
+
ys = [float(c.y) for c in corners]
|
|
622
|
+
zs = [float(c.z) for c in corners]
|
|
623
|
+
amin = vector3d(min(xs), min(ys), min(zs))
|
|
624
|
+
amax = vector3d(max(xs), max(ys), max(zs))
|
|
625
|
+
elif hasattr(obj, "get_size"):
|
|
626
|
+
s = obj.get_size()
|
|
627
|
+
if s is None:
|
|
628
|
+
continue
|
|
629
|
+
amin, amax = s
|
|
630
|
+
else:
|
|
631
|
+
continue
|
|
632
|
+
|
|
633
|
+
if getattr(self, "debug_picking", False):
|
|
634
|
+
print(f"[pick_forward] testing {obj.name} AABB min={amin} max={amax}")
|
|
635
|
+
|
|
636
|
+
res = ray_intersect_aabb(origin, forward, amin, amax)
|
|
637
|
+
if res is not None and res >= 0 and res <= max_distance and res < closest_t:
|
|
638
|
+
closest_t = res
|
|
639
|
+
closest_obj = obj
|
|
640
|
+
hit_point = origin + forward * res
|
|
641
|
+
if getattr(self, "debug_picking", False):
|
|
642
|
+
print(f"[pick_forward] hit {obj.name} t={res} hit_point={hit_point}")
|
|
643
|
+
|
|
644
|
+
if closest_obj:
|
|
645
|
+
return closest_obj, hit_point, closest_t
|
|
646
|
+
return None
|
|
647
|
+
|
|
648
|
+
def save_scene(self, filename):
|
|
649
|
+
all_gameobjects = []
|
|
650
|
+
for obj in self.gameobjects:
|
|
651
|
+
all_gameobjects.append(obj.serialize())
|
|
652
|
+
|
|
653
|
+
all_lights = []
|
|
654
|
+
for light in self.renderer.lights:
|
|
655
|
+
all_lights.append(light.serialize())
|
|
656
|
+
|
|
657
|
+
context_attrs = self.context.serialize()
|
|
658
|
+
|
|
659
|
+
with open(filename, "w") as f:
|
|
660
|
+
json.dump({"game-objects": all_gameobjects, "lights": all_lights, "engine": self.serialize(), "context": context_attrs}, f, indent=4)
|
|
661
|
+
|
|
662
|
+
def load_scene(self, filename):
|
|
663
|
+
with open(filename, "r") as f:
|
|
664
|
+
data = json.load(f)
|
|
665
|
+
|
|
666
|
+
self.context.deserialize(data["context"])
|
|
667
|
+
|
|
668
|
+
lights = data["lights"]
|
|
669
|
+
for light in lights:
|
|
670
|
+
self.renderer.add_light(Light.deserialize(light))
|
|
671
|
+
|
|
672
|
+
gameobjects = data["game-objects"]
|
|
673
|
+
for gameobject in gameobjects:
|
|
674
|
+
if gameobject["type"] == "cuboid":
|
|
675
|
+
obj = Cuboid.deserialize(gameobject, self.context)
|
|
676
|
+
self.add_object(obj)
|
|
677
|
+
|
|
678
|
+
elif gameobject["type"] == "sphere":
|
|
679
|
+
obj = Sphere.deserialize(gameobject, self.context)
|
|
680
|
+
self.add_object(obj)
|
|
681
|
+
|
|
682
|
+
elif gameobject["type"] == "cylinder":
|
|
683
|
+
obj = Cylinder.deserialize(gameobject, self.context)
|
|
684
|
+
self.add_object(obj)
|
|
685
|
+
|
|
686
|
+
elif gameobject["type"] == "obj-model":
|
|
687
|
+
obj = ObjModel.deserialize(gameobject, self.context)
|
|
688
|
+
self.add_object(obj)
|
|
689
|
+
|
|
690
|
+
elif gameobject["type"] == "text":
|
|
691
|
+
obj = Text.deserialize(gameobject, self.context)
|
|
692
|
+
self.add_object(obj)
|
|
693
|
+
|
|
694
|
+
elif gameobject["type"] == "image-overlay":
|
|
695
|
+
obj = ImageOverlay.deserialize(gameobject, self.context)
|
|
696
|
+
self.add_object(obj)
|
|
697
|
+
|
|
698
|
+
engine = data["engine"]
|
|
699
|
+
self.deserialize(engine)
|
|
700
|
+
|
|
701
|
+
def serialize(self):
|
|
702
|
+
return {
|
|
703
|
+
"ambient_light": self.renderer.ambient,
|
|
704
|
+
"background_color": self.background_color.to_rgb(),
|
|
705
|
+
"scripts": self.script_paths,
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
def deserialize(self, data):
|
|
709
|
+
ambient_light = data["ambient_light"]
|
|
710
|
+
background_color = data["background_color"]
|
|
711
|
+
scripts = data["scripts"]
|
|
712
|
+
|
|
713
|
+
self.renderer.ambient = ambient_light
|
|
714
|
+
self.background_color = Color.RGB(*background_color)
|
|
715
|
+
self.attach_scripts(scripts)
|