spore-engine 0.1.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.
- demo.py +500 -0
- demos/__init__.py +272 -0
- demos/scene_3d.py +223 -0
- demos/scene_abyssal_bloom.py +515 -0
- demos/scene_anim.py +90 -0
- demos/scene_anim_path.py +94 -0
- demos/scene_astral_cathedral.py +103 -0
- demos/scene_aurora.py +57 -0
- demos/scene_aurora_lagoon.py +444 -0
- demos/scene_aurora_palace.py +106 -0
- demos/scene_aurora_storm.py +115 -0
- demos/scene_autumn_forest.py +730 -0
- demos/scene_bioluminescence.py +78 -0
- demos/scene_biome_demo.py +25 -0
- demos/scene_black_hole.py +134 -0
- demos/scene_braille_current.py +149 -0
- demos/scene_celestial_temple.py +123 -0
- demos/scene_cellular.py +66 -0
- demos/scene_code_shader.py +121 -0
- demos/scene_constellation.py +131 -0
- demos/scene_cosmic_tunnel.py +126 -0
- demos/scene_crystal_cluster.py +133 -0
- demos/scene_crystal_nebula.py +133 -0
- demos/scene_dna.py +56 -0
- demos/scene_double_pendulum.py +115 -0
- demos/scene_dungeon.py +44 -0
- demos/scene_eclipse.py +97 -0
- demos/scene_ecs_lifecycle.py +281 -0
- demos/scene_ecs_swarm.py +286 -0
- demos/scene_erosion.py +51 -0
- demos/scene_ethereal_ruins.py +225 -0
- demos/scene_field_demo.py +59 -0
- demos/scene_fireflies.py +118 -0
- demos/scene_flocking.py +135 -0
- demos/scene_flowfield.py +97 -0
- demos/scene_forest_fire.py +89 -0
- demos/scene_fractals.py +74 -0
- demos/scene_fx.py +126 -0
- demos/scene_galaxy.py +84 -0
- demos/scene_geometric_flower.py +97 -0
- demos/scene_glyph_art.py +157 -0
- demos/scene_god_rays.py +269 -0
- demos/scene_golden_city.py +108 -0
- demos/scene_gravity.py +128 -0
- demos/scene_horizon.py +395 -0
- demos/scene_hypercube.py +119 -0
- demos/scene_infinite_temple.py +152 -0
- demos/scene_isometric.py +46 -0
- demos/scene_kaleidoscope.py +41 -0
- demos/scene_landscape.py +102 -0
- demos/scene_lava.py +80 -0
- demos/scene_lightning.py +77 -0
- demos/scene_lorenz.py +89 -0
- demos/scene_media_player.py +119 -0
- demos/scene_meteor.py +80 -0
- demos/scene_misc.py +106 -0
- demos/scene_neon_cathedral.py +122 -0
- demos/scene_neon_city.py +150 -0
- demos/scene_neon_grid.py +54 -0
- demos/scene_new_features.py +97 -0
- demos/scene_new_features2.py +377 -0
- demos/scene_particles.py +84 -0
- demos/scene_phantom_galaxy.py +78 -0
- demos/scene_phoenix.py +148 -0
- demos/scene_phosphor.py +171 -0
- demos/scene_photo_ascii.py +46 -0
- demos/scene_physics_enhanced.py +131 -0
- demos/scene_physics_rigid.py +103 -0
- demos/scene_platformer.py +174 -0
- demos/scene_powder.py +74 -0
- demos/scene_prism_raytracer.py +72 -0
- demos/scene_ragdoll.py +300 -0
- demos/scene_raytracer_alien.py +37 -0
- demos/scene_raytracer_crystal.py +40 -0
- demos/scene_raytracer_infinity.py +37 -0
- demos/scene_raytracer_jewel.py +46 -0
- demos/scene_raytracer_moonlit.py +43 -0
- demos/scene_raytracer_nebula.py +42 -0
- demos/scene_raytracer_photo.py +36 -0
- demos/scene_raytracer_reflections.py +48 -0
- demos/scene_raytracer_system.py +36 -0
- demos/scene_raytracer_toybox.py +36 -0
- demos/scene_ripples.py +39 -0
- demos/scene_scenery.py +84 -0
- demos/scene_screenfx.py +84 -0
- demos/scene_sdf_csg.py +41 -0
- demos/scene_sdf_dreamscape.py +75 -0
- demos/scene_sdf_glow.py +45 -0
- demos/scene_shader_symphony.py +126 -0
- demos/scene_shaders.py +96 -0
- demos/scene_shadows.py +81 -0
- demos/scene_sierpinski.py +122 -0
- demos/scene_sim.py +65 -0
- demos/scene_solar_flare.py +57 -0
- demos/scene_spline_demo.py +55 -0
- demos/scene_stained_glass.py +68 -0
- demos/scene_starry_night.py +57 -0
- demos/scene_synthwave.py +126 -0
- demos/scene_terminal_app.py +284 -0
- demos/scene_terrain_flyover.py +71 -0
- demos/scene_tilemap.py +108 -0
- demos/scene_timeline.py +86 -0
- demos/scene_tui.py +199 -0
- demos/scene_tunnel.py +35 -0
- demos/scene_ui.py +82 -0
- demos/scene_underwater.py +105 -0
- demos/scene_video_player.py +76 -0
- demos/scene_voxel_world.py +59 -0
- demos/scene_walkers.py +317 -0
- demos/scene_worley.py +34 -0
- easy_demo.py +81 -0
- shader_sandbox.py +26 -0
- spore_engine/__init__.py +170 -0
- spore_engine/__version__.py +4 -0
- spore_engine/anim/__init__.py +3 -0
- spore_engine/anim/anim.py +401 -0
- spore_engine/anim/ik.py +198 -0
- spore_engine/anim/timeline.py +191 -0
- spore_engine/cli.py +267 -0
- spore_engine/core/__init__.py +150 -0
- spore_engine/core/_accel.py +49 -0
- spore_engine/core/_optional.py +40 -0
- spore_engine/core/assets.py +324 -0
- spore_engine/core/camera.py +94 -0
- spore_engine/core/canvas.py +692 -0
- spore_engine/core/color.py +282 -0
- spore_engine/core/draw.py +542 -0
- spore_engine/core/ecs.py +197 -0
- spore_engine/core/geom.py +247 -0
- spore_engine/core/glyphs.py +62 -0
- spore_engine/core/input.py +702 -0
- spore_engine/core/reload.py +282 -0
- spore_engine/core/scene.py +145 -0
- spore_engine/core/scene_file.py +375 -0
- spore_engine/core/sprite.py +55 -0
- spore_engine/core/state.py +184 -0
- spore_engine/core/term.py +541 -0
- spore_engine/core/util.py +170 -0
- spore_engine/easy/__init__.py +17 -0
- spore_engine/easy/anim.py +164 -0
- spore_engine/easy/app.py +747 -0
- spore_engine/easy/sprite.py +297 -0
- spore_engine/easy/systems.py +908 -0
- spore_engine/easy/util.py +15 -0
- spore_engine/easy/widgets.py +101 -0
- spore_engine/fx/__init__.py +15 -0
- spore_engine/fx/effects.py +376 -0
- spore_engine/fx/field.py +117 -0
- spore_engine/fx/lightfield.py +621 -0
- spore_engine/fx/lighting.py +163 -0
- spore_engine/fx/postfx.py +268 -0
- spore_engine/fx/screenfx.py +157 -0
- spore_engine/fx/shader_lab.py +430 -0
- spore_engine/fx/shaderlab.py +345 -0
- spore_engine/fx/shaders.py +528 -0
- spore_engine/fx/textfx.py +143 -0
- spore_engine/fx/transitions.py +159 -0
- spore_engine/fx/volumetric.py +195 -0
- spore_engine/gen/__init__.py +13 -0
- spore_engine/gen/biome_terrain.py +105 -0
- spore_engine/gen/delaunay.py +173 -0
- spore_engine/gen/dungeon.py +515 -0
- spore_engine/gen/erosion.py +202 -0
- spore_engine/gen/fractals.py +171 -0
- spore_engine/gen/lsystem.py +87 -0
- spore_engine/gen/marching_cubes.py +394 -0
- spore_engine/gen/maze.py +144 -0
- spore_engine/gen/pathfinding.py +140 -0
- spore_engine/gen/scenery.py +292 -0
- spore_engine/gen/splines.py +98 -0
- spore_engine/gen/terrain.py +152 -0
- spore_engine/gen/wfc.py +202 -0
- spore_engine/media/__init__.py +5 -0
- spore_engine/media/_pillow_compat.py +24 -0
- spore_engine/media/ansi_io.py +175 -0
- spore_engine/media/converter.py +264 -0
- spore_engine/media/export.py +378 -0
- spore_engine/media/ffmpeg.py +225 -0
- spore_engine/media/glyphart.py +326 -0
- spore_engine/media/imaging.py +110 -0
- spore_engine/media/img3d.py +201 -0
- spore_engine/media/video.py +287 -0
- spore_engine/render3d/__init__.py +7 -0
- spore_engine/render3d/engine3d.py +250 -0
- spore_engine/render3d/isometric.py +91 -0
- spore_engine/render3d/model_loader.py +127 -0
- spore_engine/render3d/raytracer.py +386 -0
- spore_engine/render3d/sdf.py +231 -0
- spore_engine/render3d/voxel.py +100 -0
- spore_engine/sim/__init__.py +9 -0
- spore_engine/sim/cellular.py +277 -0
- spore_engine/sim/fluid.py +261 -0
- spore_engine/sim/noise.py +248 -0
- spore_engine/sim/physics.py +988 -0
- spore_engine/sim/physics3d.py +194 -0
- spore_engine/sim/powder.py +447 -0
- spore_engine/sim/softbody.py +238 -0
- spore_engine/sim/steering.py +228 -0
- spore_engine/ui/__init__.py +4 -0
- spore_engine/ui/font.py +113 -0
- spore_engine/ui/tilemap.py +194 -0
- spore_engine/ui/toolkit.py +476 -0
- spore_engine/ui/widgets.py +819 -0
- spore_engine-0.1.0.dist-info/METADATA +342 -0
- spore_engine-0.1.0.dist-info/RECORD +209 -0
- spore_engine-0.1.0.dist-info/WHEEL +5 -0
- spore_engine-0.1.0.dist-info/entry_points.txt +3 -0
- spore_engine-0.1.0.dist-info/licenses/LICENSE +121 -0
- spore_engine-0.1.0.dist-info/top_level.txt +5 -0
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
"""Hot reload: notice edited source files and re-import them in place.
|
|
2
|
+
|
|
3
|
+
The engine's iteration loop used to be *edit -> save -> restart the process*.
|
|
4
|
+
Restarting throws away every bit of scene state, so tuning a constant meant
|
|
5
|
+
re-watching a five-second animation from frame zero every time, and a typo in
|
|
6
|
+
the file being edited killed the run instead of showing an error.
|
|
7
|
+
|
|
8
|
+
This module adds the missing half:
|
|
9
|
+
|
|
10
|
+
* :class:`Watcher` polls a set of paths for ``st_mtime`` changes and reports
|
|
11
|
+
which ones changed since the last check. Polling is deliberate rather than
|
|
12
|
+
inotify: it works identically on every platform the engine supports, needs no
|
|
13
|
+
dependency, and a handful of ``stat()`` calls per frame is free next to
|
|
14
|
+
rendering a full screen of cells.
|
|
15
|
+
* :func:`reload_modules` re-imports modules by name, forcing a fresh read of
|
|
16
|
+
the source file so the new code is what actually runs.
|
|
17
|
+
|
|
18
|
+
Both are engine-level so the demo runner, the shader sandbox and user apps all
|
|
19
|
+
share one implementation.
|
|
20
|
+
"""
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import importlib
|
|
24
|
+
import os
|
|
25
|
+
import sys
|
|
26
|
+
import traceback
|
|
27
|
+
import types
|
|
28
|
+
|
|
29
|
+
from .term import monotonic
|
|
30
|
+
|
|
31
|
+
__all__ = ['Watcher', 'ReloadResult', 'reload_modules', 'module_paths',
|
|
32
|
+
'source_of', 'collect_dependencies']
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def source_of(module) -> str | None:
|
|
36
|
+
"""Best-effort source file for a module object or module name.
|
|
37
|
+
|
|
38
|
+
Returns ``None`` for namespace/executable-backed modules (``__main__``
|
|
39
|
+
run from a zipapp, a REPL, ``exec``'d code) where there is no file on disk
|
|
40
|
+
to watch or reload.
|
|
41
|
+
"""
|
|
42
|
+
mod = sys.modules.get(module) if isinstance(module, str) else module
|
|
43
|
+
if mod is None:
|
|
44
|
+
return None
|
|
45
|
+
f = getattr(mod, '__file__', None)
|
|
46
|
+
if not f:
|
|
47
|
+
return None
|
|
48
|
+
if f.endswith(('.pyc', '.pyo')):
|
|
49
|
+
f = f[:-1]
|
|
50
|
+
return f if f.endswith('.py') else None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _iter_modules(names_or_modules):
|
|
54
|
+
"""Yield module objects/names from a varargs or a single iterable.
|
|
55
|
+
|
|
56
|
+
Callers naturally write either ``module_paths(a, b)`` or
|
|
57
|
+
``module_paths(sys.modules)``; both have to work.
|
|
58
|
+
"""
|
|
59
|
+
for entry in names_or_modules:
|
|
60
|
+
if isinstance(entry, str) or hasattr(entry, '__name__'):
|
|
61
|
+
yield entry
|
|
62
|
+
elif isinstance(entry, (list, tuple, set, frozenset, dict)):
|
|
63
|
+
for sub in entry:
|
|
64
|
+
if isinstance(sub, str) or hasattr(sub, '__name__'):
|
|
65
|
+
yield sub
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def module_paths(*names_or_modules) -> list[str]:
|
|
69
|
+
"""Absolute source paths for the given modules, skipping unreloadable ones.
|
|
70
|
+
|
|
71
|
+
Accepts modules, module names, or a single iterable of either.
|
|
72
|
+
"""
|
|
73
|
+
out = []
|
|
74
|
+
for n in _iter_modules(names_or_modules):
|
|
75
|
+
p = source_of(n)
|
|
76
|
+
if p:
|
|
77
|
+
p = os.path.abspath(p)
|
|
78
|
+
if p not in out:
|
|
79
|
+
out.append(p)
|
|
80
|
+
return out
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def collect_dependencies(module_names) -> list[str]:
|
|
84
|
+
"""Paths for a module plus the project-local modules it imports.
|
|
85
|
+
|
|
86
|
+
A scene that pulls in a helper module should reload when *that* file
|
|
87
|
+
changes too, not only when the scene file does. Only modules living under
|
|
88
|
+
the same top-level package directory as the entry module are followed, so a
|
|
89
|
+
reload never reaches into ``site-packages`` or the standard library.
|
|
90
|
+
"""
|
|
91
|
+
entries = list(_iter_modules([module_names]))
|
|
92
|
+
paths: list[str] = []
|
|
93
|
+
roots: set[str] = set()
|
|
94
|
+
mods = []
|
|
95
|
+
for entry in entries:
|
|
96
|
+
p = source_of(entry)
|
|
97
|
+
if p:
|
|
98
|
+
ap = os.path.abspath(p)
|
|
99
|
+
if ap not in paths:
|
|
100
|
+
paths.append(ap)
|
|
101
|
+
roots.add(_project_root(ap))
|
|
102
|
+
mod = sys.modules.get(entry) if isinstance(entry, str) else entry
|
|
103
|
+
if mod is not None and getattr(mod, '__name__', None):
|
|
104
|
+
mods.append(mod)
|
|
105
|
+
seen = {getattr(m, '__name__', None) for m in mods}
|
|
106
|
+
for mod in mods:
|
|
107
|
+
for value in list(vars(mod).values()):
|
|
108
|
+
name = getattr(value, '__name__', None)
|
|
109
|
+
if not name or name in seen or not isinstance(value, types.ModuleType):
|
|
110
|
+
continue
|
|
111
|
+
p = source_of(value)
|
|
112
|
+
if not p:
|
|
113
|
+
continue
|
|
114
|
+
ap = os.path.abspath(p)
|
|
115
|
+
if ap in paths or _project_root(ap) not in roots:
|
|
116
|
+
continue
|
|
117
|
+
paths.append(ap)
|
|
118
|
+
return paths
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _project_root(path: str) -> str:
|
|
122
|
+
"""The top-level package directory containing ``path``.
|
|
123
|
+
|
|
124
|
+
``/x/y/demos/scene_a.py`` with ``__init__.py`` in ``/x/y/demos`` yields
|
|
125
|
+
``/x/y/demos``, so two different scenes are not treated as separate roots
|
|
126
|
+
and ``__main__``-adjacent files are still followed.
|
|
127
|
+
"""
|
|
128
|
+
d = os.path.dirname(path)
|
|
129
|
+
while True:
|
|
130
|
+
if os.path.exists(os.path.join(d, '__init__.py')):
|
|
131
|
+
parent = os.path.dirname(d)
|
|
132
|
+
# A directory with __init__.py whose parent has none is the package
|
|
133
|
+
# root; otherwise keep walking up.
|
|
134
|
+
if not os.path.exists(os.path.join(parent, '__init__.py')):
|
|
135
|
+
return d
|
|
136
|
+
d = parent
|
|
137
|
+
else:
|
|
138
|
+
return d
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class Watcher:
|
|
142
|
+
"""Poll a set of files for modification.
|
|
143
|
+
|
|
144
|
+
w = Watcher(['scene_fire.py'])
|
|
145
|
+
...
|
|
146
|
+
for path in w.changed():
|
|
147
|
+
reload_modules([path])
|
|
148
|
+
|
|
149
|
+
A file whose mtime moves *backwards* (a checkout, an editor rewriting with
|
|
150
|
+
an older stamp) still counts as changed, and a file whose mtime is
|
|
151
|
+
unchanged but whose size changed is caught too, which is what makes this
|
|
152
|
+
survive editors that preserve timestamps.
|
|
153
|
+
"""
|
|
154
|
+
|
|
155
|
+
def __init__(self, paths=None, poll_interval: float = 0.5):
|
|
156
|
+
self._stamps: dict[str, tuple] = {}
|
|
157
|
+
self.poll_interval = max(0.05, float(poll_interval))
|
|
158
|
+
self._last_check = 0.0
|
|
159
|
+
#: Set when a watched file cannot be stat'ed (deleted mid-run).
|
|
160
|
+
self.missing: set[str] = set()
|
|
161
|
+
self.add(paths or [])
|
|
162
|
+
|
|
163
|
+
def add(self, paths) -> 'Watcher':
|
|
164
|
+
for p in paths:
|
|
165
|
+
ap = os.path.abspath(p)
|
|
166
|
+
if ap not in self._stamps:
|
|
167
|
+
self._stamps[ap] = self._stamp(ap)
|
|
168
|
+
return self
|
|
169
|
+
|
|
170
|
+
def remove(self, paths) -> 'Watcher':
|
|
171
|
+
for p in paths:
|
|
172
|
+
self._stamps.pop(os.path.abspath(p), None)
|
|
173
|
+
return self
|
|
174
|
+
|
|
175
|
+
@property
|
|
176
|
+
def paths(self) -> list[str]:
|
|
177
|
+
return sorted(self._stamps)
|
|
178
|
+
|
|
179
|
+
def _stamp(self, path: str):
|
|
180
|
+
try:
|
|
181
|
+
st = os.stat(path)
|
|
182
|
+
except OSError:
|
|
183
|
+
return None
|
|
184
|
+
return (st.st_mtime_ns, st.st_size)
|
|
185
|
+
|
|
186
|
+
def due(self, now: float | None = None) -> bool:
|
|
187
|
+
"""Whether enough time has passed to be worth stat'ing again."""
|
|
188
|
+
t = monotonic() if now is None else now
|
|
189
|
+
if t - self._last_check < self.poll_interval:
|
|
190
|
+
return False
|
|
191
|
+
self._last_check = t
|
|
192
|
+
return True
|
|
193
|
+
|
|
194
|
+
def changed(self, force: bool = False) -> list[str]:
|
|
195
|
+
"""Paths modified since the previous call.
|
|
196
|
+
|
|
197
|
+
Returns ``[]`` until :attr:`poll_interval` has elapsed, so calling this
|
|
198
|
+
every frame is cheap. Pass ``force=True`` to bypass the interval, which
|
|
199
|
+
is what the tests and a manual reload key want.
|
|
200
|
+
"""
|
|
201
|
+
if not force and not self.due():
|
|
202
|
+
return []
|
|
203
|
+
hits = []
|
|
204
|
+
self.missing = set()
|
|
205
|
+
for path in list(self._stamps):
|
|
206
|
+
now = self._stamp(path)
|
|
207
|
+
if now is None:
|
|
208
|
+
self.missing.add(path)
|
|
209
|
+
# A deleted file is a change: drop the stamp so restoring the
|
|
210
|
+
# file later is noticed too.
|
|
211
|
+
if self._stamps[path] is not None:
|
|
212
|
+
hits.append(path)
|
|
213
|
+
self._stamps[path] = None
|
|
214
|
+
continue
|
|
215
|
+
if self._stamps[path] != now:
|
|
216
|
+
hits.append(path)
|
|
217
|
+
# Only commit the new stamps for files that actually moved, so a file
|
|
218
|
+
# edited twice inside one interval still reports on the next check.
|
|
219
|
+
for path in hits:
|
|
220
|
+
self._stamps[path] = self._stamp(path)
|
|
221
|
+
return hits
|
|
222
|
+
|
|
223
|
+
def clear(self) -> None:
|
|
224
|
+
"""Forget every stamp, so the next check reports all files as changed."""
|
|
225
|
+
for path in self._stamps:
|
|
226
|
+
self._stamps[path] = None
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
class ReloadResult:
|
|
230
|
+
"""Outcome of a reload attempt.
|
|
231
|
+
|
|
232
|
+
``ok`` is False when any module raised. ``error`` holds the formatted
|
|
233
|
+
traceback and ``name`` the module that failed, so a caller can show the
|
|
234
|
+
problem on screen and keep running instead of dying.
|
|
235
|
+
"""
|
|
236
|
+
|
|
237
|
+
__slots__ = ('ok', 'reloaded', 'name', 'error')
|
|
238
|
+
|
|
239
|
+
def __init__(self, ok: bool, reloaded=(), name: str | None = None,
|
|
240
|
+
error: str | None = None):
|
|
241
|
+
self.ok = ok
|
|
242
|
+
self.reloaded = tuple(reloaded)
|
|
243
|
+
self.name = name
|
|
244
|
+
self.error = error
|
|
245
|
+
|
|
246
|
+
def __bool__(self) -> bool:
|
|
247
|
+
return self.ok
|
|
248
|
+
|
|
249
|
+
def __repr__(self) -> str:
|
|
250
|
+
if self.ok:
|
|
251
|
+
return f'ReloadResult(ok, reloaded={list(self.reloaded)})'
|
|
252
|
+
return f'ReloadResult(failed at {self.name!r})'
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def reload_modules(modules) -> ReloadResult:
|
|
256
|
+
"""Re-import modules (or module names) from source.
|
|
257
|
+
|
|
258
|
+
Uses ``importlib.reload``, which re-executes the module body in the *same*
|
|
259
|
+
module object, so references other modules already imported keep pointing
|
|
260
|
+
at the live code rather than a stale copy. A module that raises leaves the
|
|
261
|
+
previous version in place and is reported, not propagated.
|
|
262
|
+
"""
|
|
263
|
+
done = []
|
|
264
|
+
for m in modules:
|
|
265
|
+
name = m if isinstance(m, str) else getattr(m, '__name__', None)
|
|
266
|
+
if not name:
|
|
267
|
+
continue
|
|
268
|
+
mod = sys.modules.get(name)
|
|
269
|
+
if mod is None:
|
|
270
|
+
try:
|
|
271
|
+
importlib.import_module(name)
|
|
272
|
+
except Exception:
|
|
273
|
+
return ReloadResult(False, done, name,
|
|
274
|
+
traceback.format_exc())
|
|
275
|
+
done.append(name)
|
|
276
|
+
continue
|
|
277
|
+
try:
|
|
278
|
+
importlib.reload(mod)
|
|
279
|
+
except Exception:
|
|
280
|
+
return ReloadResult(False, done, name, traceback.format_exc())
|
|
281
|
+
done.append(name)
|
|
282
|
+
return ReloadResult(True, done)
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Scene composition: a low-res canvas, an optional HiRes surface, and
|
|
2
|
+
stacked overlay layers, presented together in one incremental frame."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
from .canvas import Canvas, HiResCanvas
|
|
8
|
+
|
|
9
|
+
__all__ = ['Layer', 'Scene']
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Layer:
|
|
13
|
+
"""A low-res overlay canvas fixed to a Scene, drawn at a given depth.
|
|
14
|
+
|
|
15
|
+
Attribute access falls through to the layer's own canvas, so
|
|
16
|
+
``layer.draw_text(...)`` works without going through ``layer.canvas``.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def __init__(self, scene: Scene, name: str, z: float):
|
|
20
|
+
object.__setattr__(self, 'scene', scene)
|
|
21
|
+
object.__setattr__(self, 'name', name)
|
|
22
|
+
object.__setattr__(self, 'z', z)
|
|
23
|
+
object.__setattr__(self, 'canvas', Canvas(scene.w, scene.h))
|
|
24
|
+
object.__setattr__(self, 'visible', True)
|
|
25
|
+
|
|
26
|
+
def __getattr__(self, key):
|
|
27
|
+
# __getattr__ only runs when normal lookup fails, so the attributes
|
|
28
|
+
# set in __init__ are always found directly and the explicit guard is
|
|
29
|
+
# only a backstop. The important case is 'canvas' itself: if it is
|
|
30
|
+
# missing (a __init__ that raised partway, or __new__ without __init__)
|
|
31
|
+
# then getattr(self.canvas, key) would recurse forever.
|
|
32
|
+
if key.startswith('_') or key in ('scene', 'name', 'z', 'canvas',
|
|
33
|
+
'visible'):
|
|
34
|
+
raise AttributeError(key)
|
|
35
|
+
canvas = self.__dict__.get('canvas')
|
|
36
|
+
if canvas is None:
|
|
37
|
+
raise AttributeError(key)
|
|
38
|
+
return getattr(canvas, key)
|
|
39
|
+
|
|
40
|
+
def clear(self):
|
|
41
|
+
"""Blank the layer's canvas."""
|
|
42
|
+
self.canvas.clear()
|
|
43
|
+
|
|
44
|
+
def resize(self, width: int, height: int):
|
|
45
|
+
"""Resize the layer's canvas, preserving content."""
|
|
46
|
+
self.canvas.resize(width, height)
|
|
47
|
+
|
|
48
|
+
def __repr__(self):
|
|
49
|
+
return f'Layer({self.name!r}, z={self.z})'
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Scene:
|
|
53
|
+
"""Compositing container: one Canvas + one HiResCanvas + overlay layers.
|
|
54
|
+
|
|
55
|
+
sc = Scene(100, 40)
|
|
56
|
+
sc.hr.set_pixel(40, 50, '*', fg=gold, z=50) # hires actors
|
|
57
|
+
sc.fill_sky(Gradient(BLUE, DARK)) # bg on main canvas
|
|
58
|
+
sc.layer('hud', z=90).draw_text(1, 1, 'SCORE') # fixed overlay
|
|
59
|
+
sc.present(sys.stdout) # compose + draw
|
|
60
|
+
|
|
61
|
+
Attribute access falls through to the main canvas, so ``sc.draw_circle(...)``
|
|
62
|
+
draws straight onto it. Pass ``hires=False`` to skip the HiRes surface;
|
|
63
|
+
:attr:`surface` is then ``None``.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
def __init__(self, width: int, height: int, hires: bool = True):
|
|
67
|
+
self.w = width
|
|
68
|
+
self.h = height
|
|
69
|
+
self.hires_enabled = hires
|
|
70
|
+
self.canvas = Canvas(width, height)
|
|
71
|
+
self.hr = HiResCanvas(width, height * 2) if hires else None
|
|
72
|
+
self._layers: list = []
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def main(self) -> Canvas:
|
|
76
|
+
"""The low-resolution canvas (the compositing target)."""
|
|
77
|
+
return self.canvas
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def surface(self):
|
|
81
|
+
"""The HiRes surface, or ``None`` when the scene was built with
|
|
82
|
+
``hires=False``."""
|
|
83
|
+
return self.hr
|
|
84
|
+
|
|
85
|
+
def __getattr__(self, key):
|
|
86
|
+
if key.startswith('_'):
|
|
87
|
+
raise AttributeError(key)
|
|
88
|
+
# Guard against infinite recursion: if 'canvas' is not in __dict__ the
|
|
89
|
+
# getattr below would call __getattr__ again with the same key.
|
|
90
|
+
canvas = self.__dict__.get('canvas')
|
|
91
|
+
if canvas is None:
|
|
92
|
+
raise AttributeError(key)
|
|
93
|
+
return getattr(canvas, key)
|
|
94
|
+
|
|
95
|
+
def resize(self, width: int, height: int):
|
|
96
|
+
"""Resize the scene and every layer, preserving content.
|
|
97
|
+
|
|
98
|
+
The HiRes surface keeps its 2x vertical resolution, so it becomes
|
|
99
|
+
``width x height * 2``. Call this from a ``ResizeEvent`` handler: the
|
|
100
|
+
engine detects terminal resizes but never resizes a surface on its own.
|
|
101
|
+
"""
|
|
102
|
+
self.w = width
|
|
103
|
+
self.h = height
|
|
104
|
+
self.canvas.resize(width, height)
|
|
105
|
+
if self.hr is not None:
|
|
106
|
+
self.hr.resize(width, height * 2)
|
|
107
|
+
for lay in self._layers:
|
|
108
|
+
lay.canvas.resize(width, height)
|
|
109
|
+
|
|
110
|
+
def layer(self, name: str = 'layer', z: float = 0) -> Layer:
|
|
111
|
+
"""Create (or fetch) an overlay layer canvas by name."""
|
|
112
|
+
for lay in self._layers:
|
|
113
|
+
if lay.name == name:
|
|
114
|
+
lay.z = z
|
|
115
|
+
return lay
|
|
116
|
+
lay = Layer(self, name, z)
|
|
117
|
+
self._layers.append(lay)
|
|
118
|
+
return lay
|
|
119
|
+
|
|
120
|
+
def get_layer(self, name: str, z: float = 0) -> Layer:
|
|
121
|
+
return self.layer(name, z)
|
|
122
|
+
|
|
123
|
+
def clear(self):
|
|
124
|
+
self.canvas.clear()
|
|
125
|
+
if self.hr is not None:
|
|
126
|
+
self.hr.clear()
|
|
127
|
+
for lay in self._layers:
|
|
128
|
+
lay.canvas.clear()
|
|
129
|
+
|
|
130
|
+
def compose(self, z: float = 0):
|
|
131
|
+
"""Blit hires actors + overlay layers onto the main canvas.
|
|
132
|
+
|
|
133
|
+
Empty hires cells are skipped, so low-res background remains intact;
|
|
134
|
+
pass ``hr`` cells drawn at z >= ``z`` to stack them above it."""
|
|
135
|
+
if self.hr is not None:
|
|
136
|
+
self.hr.to_canvas(self.canvas, z=z)
|
|
137
|
+
for lay in sorted((l for l in self._layers if l.visible), key=lambda l: l.z):
|
|
138
|
+
self.canvas.blit_canvas(lay.canvas)
|
|
139
|
+
|
|
140
|
+
def present(self, stream, z: float = 0, clear_first: bool = True):
|
|
141
|
+
self.compose(z)
|
|
142
|
+
self.canvas.render_to(stream, clear_first)
|
|
143
|
+
|
|
144
|
+
def __repr__(self):
|
|
145
|
+
return f'Scene({self.w}x{self.h}, {len(self._layers)} layers)'
|