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.
Files changed (209) hide show
  1. demo.py +500 -0
  2. demos/__init__.py +272 -0
  3. demos/scene_3d.py +223 -0
  4. demos/scene_abyssal_bloom.py +515 -0
  5. demos/scene_anim.py +90 -0
  6. demos/scene_anim_path.py +94 -0
  7. demos/scene_astral_cathedral.py +103 -0
  8. demos/scene_aurora.py +57 -0
  9. demos/scene_aurora_lagoon.py +444 -0
  10. demos/scene_aurora_palace.py +106 -0
  11. demos/scene_aurora_storm.py +115 -0
  12. demos/scene_autumn_forest.py +730 -0
  13. demos/scene_bioluminescence.py +78 -0
  14. demos/scene_biome_demo.py +25 -0
  15. demos/scene_black_hole.py +134 -0
  16. demos/scene_braille_current.py +149 -0
  17. demos/scene_celestial_temple.py +123 -0
  18. demos/scene_cellular.py +66 -0
  19. demos/scene_code_shader.py +121 -0
  20. demos/scene_constellation.py +131 -0
  21. demos/scene_cosmic_tunnel.py +126 -0
  22. demos/scene_crystal_cluster.py +133 -0
  23. demos/scene_crystal_nebula.py +133 -0
  24. demos/scene_dna.py +56 -0
  25. demos/scene_double_pendulum.py +115 -0
  26. demos/scene_dungeon.py +44 -0
  27. demos/scene_eclipse.py +97 -0
  28. demos/scene_ecs_lifecycle.py +281 -0
  29. demos/scene_ecs_swarm.py +286 -0
  30. demos/scene_erosion.py +51 -0
  31. demos/scene_ethereal_ruins.py +225 -0
  32. demos/scene_field_demo.py +59 -0
  33. demos/scene_fireflies.py +118 -0
  34. demos/scene_flocking.py +135 -0
  35. demos/scene_flowfield.py +97 -0
  36. demos/scene_forest_fire.py +89 -0
  37. demos/scene_fractals.py +74 -0
  38. demos/scene_fx.py +126 -0
  39. demos/scene_galaxy.py +84 -0
  40. demos/scene_geometric_flower.py +97 -0
  41. demos/scene_glyph_art.py +157 -0
  42. demos/scene_god_rays.py +269 -0
  43. demos/scene_golden_city.py +108 -0
  44. demos/scene_gravity.py +128 -0
  45. demos/scene_horizon.py +395 -0
  46. demos/scene_hypercube.py +119 -0
  47. demos/scene_infinite_temple.py +152 -0
  48. demos/scene_isometric.py +46 -0
  49. demos/scene_kaleidoscope.py +41 -0
  50. demos/scene_landscape.py +102 -0
  51. demos/scene_lava.py +80 -0
  52. demos/scene_lightning.py +77 -0
  53. demos/scene_lorenz.py +89 -0
  54. demos/scene_media_player.py +119 -0
  55. demos/scene_meteor.py +80 -0
  56. demos/scene_misc.py +106 -0
  57. demos/scene_neon_cathedral.py +122 -0
  58. demos/scene_neon_city.py +150 -0
  59. demos/scene_neon_grid.py +54 -0
  60. demos/scene_new_features.py +97 -0
  61. demos/scene_new_features2.py +377 -0
  62. demos/scene_particles.py +84 -0
  63. demos/scene_phantom_galaxy.py +78 -0
  64. demos/scene_phoenix.py +148 -0
  65. demos/scene_phosphor.py +171 -0
  66. demos/scene_photo_ascii.py +46 -0
  67. demos/scene_physics_enhanced.py +131 -0
  68. demos/scene_physics_rigid.py +103 -0
  69. demos/scene_platformer.py +174 -0
  70. demos/scene_powder.py +74 -0
  71. demos/scene_prism_raytracer.py +72 -0
  72. demos/scene_ragdoll.py +300 -0
  73. demos/scene_raytracer_alien.py +37 -0
  74. demos/scene_raytracer_crystal.py +40 -0
  75. demos/scene_raytracer_infinity.py +37 -0
  76. demos/scene_raytracer_jewel.py +46 -0
  77. demos/scene_raytracer_moonlit.py +43 -0
  78. demos/scene_raytracer_nebula.py +42 -0
  79. demos/scene_raytracer_photo.py +36 -0
  80. demos/scene_raytracer_reflections.py +48 -0
  81. demos/scene_raytracer_system.py +36 -0
  82. demos/scene_raytracer_toybox.py +36 -0
  83. demos/scene_ripples.py +39 -0
  84. demos/scene_scenery.py +84 -0
  85. demos/scene_screenfx.py +84 -0
  86. demos/scene_sdf_csg.py +41 -0
  87. demos/scene_sdf_dreamscape.py +75 -0
  88. demos/scene_sdf_glow.py +45 -0
  89. demos/scene_shader_symphony.py +126 -0
  90. demos/scene_shaders.py +96 -0
  91. demos/scene_shadows.py +81 -0
  92. demos/scene_sierpinski.py +122 -0
  93. demos/scene_sim.py +65 -0
  94. demos/scene_solar_flare.py +57 -0
  95. demos/scene_spline_demo.py +55 -0
  96. demos/scene_stained_glass.py +68 -0
  97. demos/scene_starry_night.py +57 -0
  98. demos/scene_synthwave.py +126 -0
  99. demos/scene_terminal_app.py +284 -0
  100. demos/scene_terrain_flyover.py +71 -0
  101. demos/scene_tilemap.py +108 -0
  102. demos/scene_timeline.py +86 -0
  103. demos/scene_tui.py +199 -0
  104. demos/scene_tunnel.py +35 -0
  105. demos/scene_ui.py +82 -0
  106. demos/scene_underwater.py +105 -0
  107. demos/scene_video_player.py +76 -0
  108. demos/scene_voxel_world.py +59 -0
  109. demos/scene_walkers.py +317 -0
  110. demos/scene_worley.py +34 -0
  111. easy_demo.py +81 -0
  112. shader_sandbox.py +26 -0
  113. spore_engine/__init__.py +170 -0
  114. spore_engine/__version__.py +4 -0
  115. spore_engine/anim/__init__.py +3 -0
  116. spore_engine/anim/anim.py +401 -0
  117. spore_engine/anim/ik.py +198 -0
  118. spore_engine/anim/timeline.py +191 -0
  119. spore_engine/cli.py +267 -0
  120. spore_engine/core/__init__.py +150 -0
  121. spore_engine/core/_accel.py +49 -0
  122. spore_engine/core/_optional.py +40 -0
  123. spore_engine/core/assets.py +324 -0
  124. spore_engine/core/camera.py +94 -0
  125. spore_engine/core/canvas.py +692 -0
  126. spore_engine/core/color.py +282 -0
  127. spore_engine/core/draw.py +542 -0
  128. spore_engine/core/ecs.py +197 -0
  129. spore_engine/core/geom.py +247 -0
  130. spore_engine/core/glyphs.py +62 -0
  131. spore_engine/core/input.py +702 -0
  132. spore_engine/core/reload.py +282 -0
  133. spore_engine/core/scene.py +145 -0
  134. spore_engine/core/scene_file.py +375 -0
  135. spore_engine/core/sprite.py +55 -0
  136. spore_engine/core/state.py +184 -0
  137. spore_engine/core/term.py +541 -0
  138. spore_engine/core/util.py +170 -0
  139. spore_engine/easy/__init__.py +17 -0
  140. spore_engine/easy/anim.py +164 -0
  141. spore_engine/easy/app.py +747 -0
  142. spore_engine/easy/sprite.py +297 -0
  143. spore_engine/easy/systems.py +908 -0
  144. spore_engine/easy/util.py +15 -0
  145. spore_engine/easy/widgets.py +101 -0
  146. spore_engine/fx/__init__.py +15 -0
  147. spore_engine/fx/effects.py +376 -0
  148. spore_engine/fx/field.py +117 -0
  149. spore_engine/fx/lightfield.py +621 -0
  150. spore_engine/fx/lighting.py +163 -0
  151. spore_engine/fx/postfx.py +268 -0
  152. spore_engine/fx/screenfx.py +157 -0
  153. spore_engine/fx/shader_lab.py +430 -0
  154. spore_engine/fx/shaderlab.py +345 -0
  155. spore_engine/fx/shaders.py +528 -0
  156. spore_engine/fx/textfx.py +143 -0
  157. spore_engine/fx/transitions.py +159 -0
  158. spore_engine/fx/volumetric.py +195 -0
  159. spore_engine/gen/__init__.py +13 -0
  160. spore_engine/gen/biome_terrain.py +105 -0
  161. spore_engine/gen/delaunay.py +173 -0
  162. spore_engine/gen/dungeon.py +515 -0
  163. spore_engine/gen/erosion.py +202 -0
  164. spore_engine/gen/fractals.py +171 -0
  165. spore_engine/gen/lsystem.py +87 -0
  166. spore_engine/gen/marching_cubes.py +394 -0
  167. spore_engine/gen/maze.py +144 -0
  168. spore_engine/gen/pathfinding.py +140 -0
  169. spore_engine/gen/scenery.py +292 -0
  170. spore_engine/gen/splines.py +98 -0
  171. spore_engine/gen/terrain.py +152 -0
  172. spore_engine/gen/wfc.py +202 -0
  173. spore_engine/media/__init__.py +5 -0
  174. spore_engine/media/_pillow_compat.py +24 -0
  175. spore_engine/media/ansi_io.py +175 -0
  176. spore_engine/media/converter.py +264 -0
  177. spore_engine/media/export.py +378 -0
  178. spore_engine/media/ffmpeg.py +225 -0
  179. spore_engine/media/glyphart.py +326 -0
  180. spore_engine/media/imaging.py +110 -0
  181. spore_engine/media/img3d.py +201 -0
  182. spore_engine/media/video.py +287 -0
  183. spore_engine/render3d/__init__.py +7 -0
  184. spore_engine/render3d/engine3d.py +250 -0
  185. spore_engine/render3d/isometric.py +91 -0
  186. spore_engine/render3d/model_loader.py +127 -0
  187. spore_engine/render3d/raytracer.py +386 -0
  188. spore_engine/render3d/sdf.py +231 -0
  189. spore_engine/render3d/voxel.py +100 -0
  190. spore_engine/sim/__init__.py +9 -0
  191. spore_engine/sim/cellular.py +277 -0
  192. spore_engine/sim/fluid.py +261 -0
  193. spore_engine/sim/noise.py +248 -0
  194. spore_engine/sim/physics.py +988 -0
  195. spore_engine/sim/physics3d.py +194 -0
  196. spore_engine/sim/powder.py +447 -0
  197. spore_engine/sim/softbody.py +238 -0
  198. spore_engine/sim/steering.py +228 -0
  199. spore_engine/ui/__init__.py +4 -0
  200. spore_engine/ui/font.py +113 -0
  201. spore_engine/ui/tilemap.py +194 -0
  202. spore_engine/ui/toolkit.py +476 -0
  203. spore_engine/ui/widgets.py +819 -0
  204. spore_engine-0.1.0.dist-info/METADATA +342 -0
  205. spore_engine-0.1.0.dist-info/RECORD +209 -0
  206. spore_engine-0.1.0.dist-info/WHEEL +5 -0
  207. spore_engine-0.1.0.dist-info/entry_points.txt +3 -0
  208. spore_engine-0.1.0.dist-info/licenses/LICENSE +121 -0
  209. spore_engine-0.1.0.dist-info/top_level.txt +5 -0
@@ -0,0 +1,515 @@
1
+ import math
2
+ import random
3
+
4
+ import numpy as np
5
+
6
+ from spore_engine import (Canvas, Color, Gradient, HiResCanvas, LinearCanvas,
7
+ PerlinNoise, add_light, clamp, color_vec, gradient_lut,
8
+ monotonic, scene_state)
9
+
10
+ TAU = math.tau
11
+
12
+ # ---------------------------------------------------------------------------
13
+ # Palettes.
14
+ #
15
+ # The water column is the whole background, so it carries the entire colour
16
+ # story: near-black violet at the abyss, through indigo, to a cold aqua where
17
+ # the surface light still reaches. Every organism is then a saturated accent
18
+ # read against that ramp - a warm-cored cyan would vanish into it.
19
+ # ---------------------------------------------------------------------------
20
+
21
+ _WATER = Gradient(
22
+ Color(1, 2, 6), # abyss
23
+ Color(3, 7, 20), # deep
24
+ Color(7, 18, 44), # mid
25
+ Color(12, 38, 70), # upper
26
+ Color(19, 62, 96), # near-surface
27
+ )
28
+
29
+ #: Bioluminescent hues. Kept apart in hue so a shoal reads as a shoal rather
30
+ #: than as one repeated sprite; the violet and magenta are what stop the frame
31
+ #: from being a monochrome cyan wash.
32
+ _BLOOM = (
33
+ Color(96, 255, 244), # aqua
34
+ Color(120, 190, 255), # ice
35
+ Color(176, 140, 255), # violet
36
+ Color(255, 128, 214), # magenta
37
+ Color(140, 255, 190), # green
38
+ )
39
+
40
+ _RAY = Color(150, 226, 255)
41
+ _SNOW = Color(198, 232, 255)
42
+ _FISH = Color(214, 238, 255)
43
+ _FISH_WARM = Color(255, 226, 186)
44
+
45
+ #: Shoal. `v` is depth in the column.
46
+ #:
47
+ #: The composition is deliberately two-zone: shafts and a distant bait ball
48
+ #: own the lit upper third, and the bioluminescence owns everything below it.
49
+ #: Putting a glowing bell up in the bright water wastes it - the animal is only
50
+ #: luminous against black, so the hero lives in the dark and only one small
51
+ #: animal drifts up near the light to tie the two halves together.
52
+ #:
53
+ #: Bells are sized against the *short* screen axis, because a bell is a
54
+ #: near-circle: sized against width on a wide terminal it stays a two-row smudge
55
+ #: no matter how large the number is.
56
+ #:
57
+ #: depth, bell radius fraction, bell aspect, tentacle count, tentacle length
58
+ #: (fraction of frame height), pulse rate, phase, bloom index, lateral drift
59
+ _SHOAL = (
60
+ (0.58, 0.165, 0.66, 9, 0.40, 0.40, 0.0, 0, 0.014), # hero, in the dark
61
+ (0.76, 0.105, 0.76, 7, 0.30, 0.54, 1.7, 2, -0.010),
62
+ (0.34, 0.062, 0.80, 5, 0.44, 0.33, 3.1, 1, 0.018), # the one up in the light
63
+ (0.68, 0.128, 0.70, 8, 0.34, 0.47, 5.9, 4, 0.012),
64
+ (0.90, 0.072, 0.82, 5, 0.22, 0.70, 4.4, 3, -0.007), # deep, barely lit
65
+ )
66
+
67
+ #: surface shafts: lateral position, width, sway rate, sway amplitude, reach
68
+ _RAYS = (
69
+ (0.15, 0.030, 0.11, 0.026, 0.86),
70
+ (0.29, 0.018, 0.14, 0.034, 0.70),
71
+ (0.41, 0.024, 0.09, 0.020, 0.96),
72
+ (0.52, 0.014, 0.17, 0.030, 0.62),
73
+ (0.63, 0.022, 0.12, 0.030, 0.80),
74
+ (0.76, 0.016, 0.16, 0.024, 0.66),
75
+ (0.88, 0.030, 0.10, 0.022, 0.74),
76
+ )
77
+
78
+
79
+ _WATER_LUT = gradient_lut(_WATER)
80
+
81
+ #: Normalised to 0-1, so an intensity is directly comparable to a 0-255 buffer
82
+ #: level. Dividing a 0-255 colour instead would make 96.0 mean "96x too bright".
83
+ _RAY_N = color_vec(_RAY) / 255.0
84
+ _SNOW_N = color_vec(_SNOW) / 255.0
85
+ _FISH_N = color_vec(_FISH) / 255.0
86
+ _FISH_WARM_N = color_vec(_FISH_WARM) / 255.0
87
+ _BLOOM_N = tuple(v / 255.0 for v in (color_vec(c) for c in _BLOOM))
88
+
89
+
90
+ def _fbm_line(pn, w, freq, off, octaves=3, gain=1.0):
91
+ """A 1-D fBm trace across the frame, sampled through the engine's grid.
92
+
93
+ Every silhouette here wants a per-column fBm. Looping ``PerlinNoise.fbm1``
94
+ per column costs about 0.5ms each; the same trace through
95
+ :meth:`PerlinNoise.fbm2d_grid` uses the JIT-compiled kernel and costs about
96
+ 0.03ms, and falls back to plain Python when numba is absent.
97
+ """
98
+ if freq == 0.0 or w < 1:
99
+ return np.full(max(1, w), 0.5 * gain, dtype=np.float32)
100
+ grid = pn.fbm2d_grid(w, 1, scale=freq, ox=off / freq, oy=off * 0.41,
101
+ octaves=octaves)
102
+ return (grid[0] * 0.5 + 0.5).astype(np.float32) * gain
103
+
104
+
105
+ def _water_column(frame, w, h, t, pn, st):
106
+ """The background: a depth ramp, the surface shafts, and surface shimmer.
107
+
108
+ Accumulates into ``frame``, the LinearCanvas buffer, rather than returning
109
+ a new array - the depth ramp has to land in the same place the shafts
110
+ brighten, and a second buffer would mean either a copy or an ``+=``.
111
+ """
112
+ f32 = np.float32
113
+ yy = np.arange(h, dtype=f32)[:, None]
114
+ xx = np.arange(w, dtype=f32)[None, :]
115
+
116
+ # -- depth ramp ---------------------------------------------------------
117
+ # Sampled on depth rather than on y so a resize keeps the water column
118
+ # anchored to the top of the frame instead of re-stretching it.
119
+ depth = (yy / max(1, h - 1)) ** 1.15
120
+ idx = np.clip((1.0 - depth) * 255.0, 0, 255).astype(np.int32)
121
+ frame += _WATER_LUT[idx]
122
+
123
+ # a slow lateral density variation, so the water is not a flat wash
124
+ swirl = _fbm_line(pn, w, 0.020, t * 0.012, 3)
125
+ frame += (swirl[None, :, None] * 9.0) * (_WATER_LUT[180] / 255.0)[None, None, :]
126
+
127
+ # -- surface light shafts ----------------------------------------------
128
+ # Each shaft sways on its own rate and widens as it descends, because a
129
+ # real one enters narrow at the surface and spreads through the water.
130
+ # These are the frame's main event, not a background wash: they are the
131
+ # underwater analogue of Aurora Lagoon's curtains, and the whole reason the
132
+ # bait ball has something bright to be a silhouette against.
133
+ # Narrow-but-bright beats wide-but-faint here - a soft band at this
134
+ # resolution is just fog.
135
+ # Accumulated shaft light, reused below to gate the filament texture.
136
+ shaft_light = np.zeros((h, w), dtype=f32)
137
+ for frac, wid, rate, amp, reach in _RAYS:
138
+ # The shear is per *sub-cell* and has to stay small. At 0.012 a shaft
139
+ # travels nearly half the frame width by the bottom, which slides every
140
+ # ray off the left and leaves the right half of the image empty.
141
+ centre = w * frac + w * amp * np.sin(t * rate + frac * 11.0) - yy * w * 0.0028
142
+ width = w * wid * (1.0 + 1.55 * depth)
143
+ shaft = np.exp(-(((xx - centre) / np.maximum(1.0, width)) ** 2))
144
+ # flicker from a second, slower sine: a shaft that only sways reads as
145
+ # a solid bar rather than as moving water
146
+ shaft *= 0.62 + 0.38 * np.sin(t * (rate * 3.1) + frac * 5.0 - yy * 0.09)
147
+ shaft *= np.clip(1.0 - depth / reach, 0, 1) ** 1.9
148
+ shaft_light += shaft
149
+ frame += (shaft * 96.0)[..., None] * _RAY_N
150
+
151
+ # -- caustics right at the top -----------------------------------------
152
+ # Two crossing high-frequency traces beat any single one, and the result is
153
+ # confined to the top eighth of the frame where it reads as a surface.
154
+ top = np.clip(1.0 - yy / (h * 0.13), 0, 1) ** 2.0
155
+ c1 = 0.5 + 0.5 * np.sin(xx * 0.55 + t * 0.9)
156
+ c2 = 0.5 + 0.5 * np.sin(xx * 0.31 - t * 0.7 + 1.3)
157
+ caustic = (c1 * c2) ** 2.2 * top
158
+ frame += (caustic * 30.0)[..., None] * _RAY_N
159
+
160
+ # -- glitter -------------------------------------------------------------
161
+ # A smooth field has no detail: the frame measures as flat no matter how
162
+ # bright it is. Real water carries fast specular twinkle, and because the
163
+ # twinkle is what the eye reads as "water", it is what carries the local
164
+ # contrast. The hash is decorrelated per cell, so this is grain rather than
165
+ # another wave - the wave part is already in the shafts.
166
+ cellx = np.floor(xx * 0.5).astype(np.int64)
167
+ celly = np.floor(yy * 0.5).astype(np.int64)
168
+ # cheap integer hash -> [0, 1)
169
+ hv = ((cellx * 73856093) ^ (celly * 19349663) ^ (int(t * 6.0) * 83492791))
170
+ hv = (hv & 0x7FFFFFFF).astype(np.float64) / 0x7FFFFFFF
171
+ # only a small minority of cells glint at any instant, and only where
172
+ # there is light to glint off
173
+ twinkle = np.clip((hv - 0.82) / 0.18, 0, 1) ** 2 * np.clip(1.0 - depth / reach, 0, 1)
174
+ frame += (twinkle * 240.0)[..., None] * _RAY_N
175
+
176
+ # -- filaments -----------------------------------------------------------
177
+ # The shafts are currently a smooth envelope, so they read as painted bars.
178
+ # High-frequency ridged noise along the shaft direction is what turns them
179
+ # into light *in* water: the edges shred and the interior gets grain.
180
+ fil = np.zeros((h, w))
181
+ for lane, (fq, amp) in enumerate(((0.85, 1.0), (2.10, 0.55), (4.70, 0.25))):
182
+ n = _fbm_line(pn, w, fq * 3.1, lane * 17.0, octaves=3, gain=0.55)
183
+ fil += (np.abs(n - 0.5) * 2.0 - 0.5) * amp
184
+ fil = np.clip(fil * 0.5 + 0.5, 0, 1)
185
+ frame += (fil * shaft_light * 44.0)[..., None] * _RAY_N
186
+
187
+
188
+ def _bait_ball(frame, w, h, t, st):
189
+ """A bait ball: a few hundred small fish turning as one body.
190
+
191
+ This carries the "there is a large mass here" job that a whale silhouette
192
+ cannot at this resolution. A whale at 80x48 is a wide flat shape four
193
+ sub-cells tall: drawn carefully it is a smudge, and drawn loosely it is a
194
+ black band across the picture. A bait ball has no such problem - it is made
195
+ of hundreds of one-sub-cell highlights, so it reads as a dense shifting
196
+ cloud at any size, and it gives the jellyfish something to be scattered
197
+ around.
198
+
199
+ The fish are deliberately dim. 230 of them inside a 14x6 sub-cell disc land
200
+ roughly five to a cell, so anything near the snow motes' brightness sums
201
+ into a solid white blob within a few cells; the shimmer has to live in the
202
+ texture of the cluster, not in its peak.
203
+ """
204
+ f32 = np.float32
205
+
206
+ def build():
207
+ rnd = random.Random(0xF15)
208
+ fish = []
209
+ for _ in range(230):
210
+ # sqrt keeps the disc uniformly filled instead of clumping at the
211
+ # centre, which is what makes a projected ball look hollow
212
+ rad = rnd.random() ** 0.5
213
+ fish.append((rad, rnd.random() * TAU, rnd.random(),
214
+ rnd.random() * TAU, rnd.random() < 0.22))
215
+ return fish
216
+
217
+ cx = w * (0.60 + 0.012 * math.sin(t * 0.037))
218
+ cy = h * (0.225 + 0.010 * math.sin(t * 0.043 + 1.1))
219
+ rx = w * 0.085
220
+ ry = h * 0.058
221
+
222
+ xs, ys, gains, warms = [], [], [], []
223
+ # The whole ball turns slowly; a static cluster of dots reads as noise.
224
+ spin = t * 0.085
225
+ for rad, ang, depth, ph, warm in st.get('bait', None, build):
226
+ a = ang + spin * (0.35 + 0.65 * rad)
227
+ # a slight vertical squash plus per-fish depth: fish further back sit
228
+ # higher in the ball and are dimmer, which is what gives it volume
229
+ px = cx + rx * rad * math.cos(a) * (1.0 - 0.18 * depth)
230
+ py = cy + ry * rad * math.sin(a) - h * 0.012 * depth
231
+ xi = int(px)
232
+ yi = int(py)
233
+ if not (0 <= xi < w and 0 <= yi < h):
234
+ continue
235
+ # shimmer: each fish catches the surface light on its own beat
236
+ sh = 0.42 + 0.58 * (0.5 + 0.5 * math.sin(t * 2.1 + ph * 6.0))
237
+ # brighter toward the front of the ball
238
+ front = 0.34 + 0.66 * (1.0 - depth)
239
+ xs.append(xi)
240
+ ys.append(yi)
241
+ gains.append(sh * front * 34.0)
242
+ warms.append(warm)
243
+
244
+ if not xs:
245
+ return
246
+ xa = np.array(xs, dtype=np.int32)
247
+ ya = np.array(ys, dtype=np.int32)
248
+ ga = np.array(gains, dtype=f32)
249
+ warm = np.array(warms, dtype=bool)
250
+ cool_c = _FISH_N
251
+ warm_c = _FISH_WARM_N
252
+ col = np.where(warm[:, None], warm_c[None, :], cool_c[None, :])
253
+
254
+ # the fish body, then a dimmer tail cell: a two-sub-cell dash is the
255
+ # smallest mark that still reads as an animal rather than as dust
256
+ np.add.at(frame, (ya, xa), col * ga[:, None])
257
+ tail = np.clip(xa - 1, 0, w - 1)
258
+ np.add.at(frame, (ya, tail), col * (ga * 0.45)[:, None])
259
+
260
+
261
+ def _jelly(frame, w, h, u, v, r, col, t, rate, phase, ntents, tlen):
262
+ """One jellyfish: pulsing bell, lit rim, and trailing tentacles.
263
+
264
+ The pulse is what makes it read as alive. Contracting the bell while the
265
+ tentacles trail slightly behind is the whole silhouette of the animal; a
266
+ bell that only changes brightness reads as a pulsing lamp.
267
+ """
268
+ f32 = np.float32
269
+ x = u * w
270
+ y = v * h + 0.020 * h * math.sin(t * 0.21 + phase)
271
+ rad = r * (0.90 + 0.16 * math.sin(t * rate * TAU + phase))
272
+ ry = rad * 0.74
273
+
274
+ yy = np.arange(h, dtype=f32)[:, None]
275
+ xx = np.arange(w, dtype=f32)[None, :]
276
+
277
+ dx = (xx - x) / max(0.6, rad)
278
+ dy = (yy - y) / max(0.6, ry)
279
+ rr = np.hypot(dx, dy)
280
+
281
+ # Bell: a dome, open at the bottom. Masking the lower half is what stops
282
+ # it reading as a ball of light.
283
+ dome = (yy <= y + ry * 0.30)
284
+
285
+ # The interior stays nearly black. A filled bell is a glowing ball; it is
286
+ # the contrast between a dark body and a lit rim that reads as a dome, and
287
+ # the fill is the first thing to go when the bell stops looking like an
288
+ # animal.
289
+ inside = np.clip(1.0 - rr, 0, 1) * dome
290
+ # the bright ring just inside the bell edge, hard enough to survive
291
+ # sub-cell sampling
292
+ ring = np.exp(-((rr - 0.82) ** 2) / 0.016) * dome
293
+ # the gonad cluster: a small bright core, the detail that makes it a
294
+ # jellyfish rather than a ring
295
+ core = np.exp(-((rr / 0.30) ** 2)) * dome
296
+ # a wide faint halo, so the animal is *in* the water rather than pasted on
297
+ halo = np.exp(-((rr / 1.30) ** 2))
298
+
299
+ c = col
300
+ gain = 104.0 * (0.80 + 0.20 * math.sin(t * rate * TAU * 0.5 + phase))
301
+ frame += ((inside * 0.10 + ring * 1.00 + core * 0.62)[..., None] * c * gain
302
+ + (halo * 7.0)[..., None] * c)
303
+
304
+ # -- the gonads themselves ----------------------------------------------
305
+ # The core term is a smooth bump, so it dies under sub-cell sampling. Four
306
+ # discrete points per bell give the eye something sharp to lock onto, and
307
+ # they are the brightest thing in the frame - which is what makes the hero
308
+ # read as the focal point rather than just the largest shape.
309
+ if ry > 1.2:
310
+ for gi, (gx, gy) in enumerate(((-0.30, -0.18), (0.30, -0.18),
311
+ (-0.30, 0.14), (0.30, 0.14))):
312
+ gxp = x + gx * rad
313
+ gyp = y + gy * ry + ry * 0.04
314
+ if 1 <= int(gxp) < w - 1 and 1 <= int(gyp) < h - 1:
315
+ d = np.hypot(xx - gxp, yy - gyp)
316
+ pt_ = np.exp(-(d ** 2) / 0.55)
317
+ bright = 300.0 * (0.72 + 0.28 * math.sin(t * 2.3 + gi * 1.6 + phase))
318
+ frame += (pt_[..., None] * c * bright)
319
+
320
+
321
+ # -- tentacles ---------------------------------------------------------
322
+ # Each is a column of scatters rather than a per-cell loop: a 6-tentacle
323
+ # jelly then costs six vectorised writes instead of six times its length
324
+ # in Python.
325
+ rows = np.arange(int(y + ry * 0.35), int(min(h, y + ry * 0.35 + tlen * h)))
326
+ if rows.size == 0:
327
+ return
328
+ down = (rows - (y + ry * 0.35)) / max(1.0, rows.size)
329
+ for k in range(ntents):
330
+ spread = (k / max(1, ntents - 1) - 0.5) * rad * 1.55 if ntents > 1 else 0.0
331
+ wave = (np.sin(down * 5.2 + t * 1.15 + phase + k * 0.85) * rad * 0.34
332
+ + np.sin(down * 11.0 - t * 0.8 + k * 1.9) * rad * 0.13)
333
+ # tentacles converge as they descend, which is what gives the animal
334
+ # its trailing shape
335
+ xs = (x + spread * (1.0 - 0.55 * down) + wave).astype(np.int32)
336
+ np.clip(xs, 0, w - 1, out=xs)
337
+ # fade along the length, with a slow travelling pulse down each
338
+ fade = (1.0 - down) ** 1.35
339
+ pulse = 0.55 + 0.45 * np.sin(down * 7.0 - t * 2.2 + phase + k)
340
+ a = fade * pulse
341
+ # The tentacles converge, so several land on the same cell and add.
342
+ # Each one is therefore deliberately dim: at a per-tentacle intensity
343
+ # that looks right on its own, the overlap alone pushed the frame past
344
+ # 500 and flattened the animal into a white smear.
345
+ frame[rows, xs] += c * (a * 58.0)[:, None]
346
+ # a one-cell halo, so a tentacle is a streak of light and not a dotted
347
+ # line
348
+ halo = np.clip(xs + 1, 0, w - 1)
349
+ frame[rows, halo] += c * (a * 21.0)[:, None]
350
+
351
+
352
+ def _shoal(frame, w, h, t, st):
353
+ """The drifting shoal, parallaxed by depth."""
354
+ def build():
355
+ rnd = random.Random(0xB105)
356
+ return [rnd.uniform(0.14, 0.86) for _ in range(len(_SHOAL))]
357
+
358
+ for (v, rf, aspect, ntents, tlen, rate, phase, ci, drift), u0 in zip(
359
+ _SHOAL, st.get('shoal', None, build)):
360
+ # A slow swim that oscillates rather than wraps. Wrapping parks a
361
+ # jellyfish against the frame edge for most of the loop, and a bell
362
+ # clipped by the border reads as a rendering fault, not as an animal
363
+ # leaving the shot.
364
+ u = u0 + 0.30 * math.sin(t * drift * TAU * 0.5 + phase)
365
+ u = clamp(u, 0.09, 0.91)
366
+ y = v + 0.012 * math.sin(t * 0.17 + phase)
367
+ rad = rf * min(w, h * 0.85)
368
+ _jelly(frame, w, h, u, y, rad, _BLOOM_N[ci], t, rate, phase, ntents, tlen)
369
+
370
+
371
+
372
+ def _marine_snow(frame, w, h, t, st):
373
+ """Drifting detritus, three parallax planes.
374
+
375
+ Scattered with ``np.add.at`` rather than a per-particle loop: several
376
+ hundred Python-level additions cost more than the rest of the frame put
377
+ together.
378
+ """
379
+ f32 = np.float32
380
+
381
+ def build():
382
+ rnd = random.Random(0x5A0F)
383
+ planes = []
384
+ for count, speed, size, bright in ((240, 0.030, 1.0, 1.00),
385
+ (150, 0.055, 0.8, 0.66),
386
+ (66, 0.085, 0.7, 0.40)):
387
+ planes.append([
388
+ (rnd.random(), # u
389
+ rnd.random() ** 0.85, # v (biased upward)
390
+ rnd.random() * TAU, # twinkle phase
391
+ rnd.random() < 0.14) # a few brighter motes
392
+ for _ in range(count)])
393
+ return planes
394
+
395
+ c = _SNOW_N
396
+ for plane, (speed, size, bright) in zip(
397
+ st.get('snow', None, build), ((0.030, 1.0, 1.00), (0.055, 0.8, 0.66),
398
+ (0.085, 0.7, 0.40))):
399
+
400
+ ys, xs, gains = [], [], []
401
+ for u, v, ph, hot in plane:
402
+ tw = 0.5 + 0.5 * math.sin(t * 1.1 + ph * 4.0)
403
+ if tw < 0.22:
404
+ continue
405
+ # slow fall, wrapped, so the field never empties
406
+ yv = (v + t * speed * 0.11) % 1.04 - 0.02
407
+ xi = int(u * w)
408
+ yi = int(min(0.999, yv) * h)
409
+ if not (0 <= xi < w and 0 <= yi < h):
410
+ continue
411
+ ys.append(yi)
412
+ xs.append(xi)
413
+ # Snow is the frame's fine detail budget: a single isolated bright
414
+ # cell per particle is what a Laplacian reads as texture, so the
415
+ # hot motes have to genuinely clip rather than merely stand out.
416
+ gains.append(tw * bright * (260.0 if hot else 96.0))
417
+ if not ys:
418
+ continue
419
+ ya = np.array(ys)
420
+ xa = np.array(xs)
421
+ ga = np.array(gains, dtype=f32)
422
+ np.add.at(frame, (ya, xa), c[None, :] * ga[:, None])
423
+ if size >= 1.0:
424
+ # only the nearest plane gets a halo, so depth reads
425
+ hx = np.clip(xa + 1, 0, w - 1)
426
+ np.add.at(frame, (ya, hx), c[None, :] * (ga * 0.30)[:, None])
427
+
428
+
429
+ def _grade(lc):
430
+ """Highlight rolloff, a tight bloom and a vignette, in place.
431
+
432
+ The three stages are the engine's, and the numbers are this scene's: a low
433
+ bloom threshold, because on a frame this dark almost everything luminous
434
+ should glow and a threshold tuned for a daylight scene leaves the organisms
435
+ looking like stickers; and a deep vignette, because the subject is a light
436
+ source in a dark room.
437
+ """
438
+ lc.tonemap(knee=150.0)
439
+ lc.bloom(threshold=26.0, span=74.0, radii=(1, 3), weights=(0.80, 0.42),
440
+ tint=(0.72, 0.94, 1.0), gain=46.0)
441
+ lc.vignette(gain=0.60, exponent=2.0, radius=0.74)
442
+
443
+
444
+ def _sparkle(hr, w, h, t, st):
445
+ """A handful of extra motes lit on top, the way a jellyfish lights the
446
+ water around it. Drawn after the fold so they read as foreground points."""
447
+ now = monotonic()
448
+ last = st.get('clock')
449
+ st.clock = now
450
+ fps = st.get('fps')
451
+ if last is not None and 0.0 < now - last < 0.5:
452
+ inst = 1.0 / (now - last)
453
+ st.fps = inst if fps is None else fps * 0.88 + inst * 0.12
454
+
455
+ def build():
456
+ rnd = random.Random(0x1CE)
457
+ return [(rnd.random(), rnd.random(), rnd.random() * TAU,
458
+ rnd.uniform(0.010, 0.032), rnd.random() < 0.5) for _ in range(30)]
459
+
460
+ for u, v, ph, spd, warm in st.get('sparkle', None, build):
461
+ tw = 0.5 + 0.5 * math.sin(t * 1.35 + ph * 3.0)
462
+ if tw < 0.30:
463
+ continue
464
+ col = _BLOOM[4] if warm else _BLOOM[1]
465
+ gain = 0.30 + 0.85 * tw
466
+ x = int(((u + t * spd) % 1.0) * (w - 1))
467
+ y = int(((v + t * spd * 0.22) % 1.0) * (h - 1))
468
+ add_light(hr, x, y, col.r * gain, col.g * gain, col.b * gain, 40)
469
+ halo = gain * 0.20
470
+ for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):
471
+ add_light(hr, x + dx, y + dy, col.r * halo, col.g * halo, col.b * halo, 40)
472
+
473
+
474
+ def _hud(c, t, st):
475
+ """Title and a live readout of the incremental renderer."""
476
+ c.draw_text(2, 0, '✦ Abyssal Bloom ✦',
477
+ Color.from_hsv(0.50 + 0.04 * math.sin(t * 0.05), 0.45, 1.0), z=100)
478
+ c.draw_text(2, c.h - 1,
479
+ 'linear-light bloom | pulsing bells | three parallax planes',
480
+ Color(58, 84, 110), z=100)
481
+
482
+ stats = c.render_stats
483
+ if stats is None:
484
+ return
485
+ fps = st.get('fps')
486
+ rate = f'{fps:5.0f} fps' if fps else ' -- fps'
487
+ note = 'full redraw' if stats['full'] else f'{stats["cells"]} cells'
488
+ c.draw_text_at(3, 0, f'{rate} · {note} · {stats["bytes"] / 1024:.1f} KiB/f',
489
+ Color(58, 86, 116), z=100, anchor='ne')
490
+
491
+
492
+ def scene_abyssal_bloom(c: Canvas, hr: HiResCanvas, t: float, pt, dt: float):
493
+ """Abyssal Bloom - bioluminescent jellyfish drifting in a deep water column."""
494
+ w, h = hr.w, hr.h
495
+ st = scene_state('abyssal_bloom')
496
+ pn = st.get('noise', None, lambda: PerlinNoise(0xAB75))
497
+
498
+ if w < 8 or h < 8:
499
+ return
500
+
501
+ lc = LinearCanvas(w, h)
502
+ frame = lc.data
503
+ _water_column(frame, w, h, t, pn, st)
504
+ _bait_ball(frame, w, h, t, st)
505
+ _shoal(frame, w, h, t, st)
506
+ _marine_snow(frame, w, h, t, st)
507
+ _grade(lc)
508
+ # Keep the returned cache: dropping it rebuilds it every frame, and the
509
+ # Color reuse is worth more than the rest of the frame combined.
510
+ st['keys'], st['objs'] = lc.to_hires(hr, prev=st.get('keys', None),
511
+ objs=st.get('objs', None))
512
+ _sparkle(hr, w, h, t, st)
513
+
514
+ hr.to_canvas(c)
515
+ _hud(c, t, st)
demos/scene_anim.py ADDED
@@ -0,0 +1,90 @@
1
+ import math, random
2
+ from spore_engine.core.color import Color, WHITE, DIM
3
+ from spore_engine.anim.anim import Tween, Oscillator, Sequence, bounce_out, elastic_in_out, sine_in_out
4
+
5
+ SHADE = ' .:-=+*#%@'
6
+ _LS = None
7
+
8
+ def scene_anim(c, hr, t, pt, dt):
9
+ global _LS
10
+ if _LS is None:
11
+ _LS = {
12
+ 'tweens': [
13
+ Tween(2.0, 'bounce_out', yoyo=True),
14
+ Tween(1.5, 'elastic_out', yoyo=True),
15
+ Tween(2.5, 'cubic_in_out', yoyo=True, loop=True),
16
+ Tween(1.8, 'back_out', yoyo=True),
17
+ Tween(2.0, 'circ_out', yoyo=True),
18
+ ],
19
+ 'seq': Sequence((1.0, 'quad_out'), (1.0, 'elastic_out'), (1.0, 'bounce_out')),
20
+ 'osc': Oscillator(2.0, 0, 1),
21
+ 'color_t': Tween(3.0, 'sine_in_out', loop=True),
22
+ }
23
+ _LS['tweens'][3].elapsed = 1.0 # staggered start
24
+
25
+ c.clear()
26
+
27
+ # Background
28
+ for y in range(c.h):
29
+ for x in range(c.w):
30
+ c.set_pixel(x, y, ' ', bg=Color(5, 3, 15), z=-100)
31
+
32
+ # -- TAB TITLE -------------------------------------------------
33
+ c.draw_text(2, 0, "Animation Demo", Color(255, 200, 100), z=100)
34
+
35
+ # -- TWEEENS (bouncing balls, progress bars) ------------------
36
+ for i, tw in enumerate(_LS['tweens']):
37
+ tw.update(dt)
38
+ v = tw.value
39
+ bx = 8 + i * 15
40
+ by = int(4 + (1 - v) * 12)
41
+
42
+ # Ball
43
+ for dy in (-1, 0, 1):
44
+ for dx in (-1, 0, 1):
45
+ if math.hypot(dx, dy) <= 1.5:
46
+ px, py = bx+dx, by+dy
47
+ if 0 <= px < c.w and 0 <= py < c.h:
48
+ c.set_pixel(px, py, '@' if dx==0 and dy==0 else 'O',
49
+ Color(120+int(v*135), int(100*v)+80, 255), z=20)
50
+
51
+ # Bar
52
+ bw = 12
53
+ filled = int(v * bw)
54
+ for bx2 in range(bw):
55
+ px = bx - bw//2 + bx2
56
+ py = 18
57
+ if 0 <= px < c.w:
58
+ ch = '█' if bx2 < filled else '░'
59
+ c.set_pixel(px, py, ch, Color(60+int(v*195), 60, 180), z=15)
60
+
61
+ # Label
62
+ names = ['bounce', 'elastic', 'cubic io', 'back', 'circ']
63
+ c.draw_text(bx - 3, 20, names[i], DIM, z=100)
64
+
65
+ # -- OSCILLATOR -----------------------------------------------
66
+ ov = _LS['osc'].value(t)
67
+ ox = int(4 + ov * (c.w - 8))
68
+ oy = 5
69
+ for dx in range(-2, 3):
70
+ for dy in range(-1, 2):
71
+ px, py = ox+dx, oy+dy
72
+ if 0 <= px < c.w and 0 <= py < c.h:
73
+ c.set_pixel(px, py, '#', Color(255, 100+int(ov*155), 100), z=20)
74
+ c.draw_text(c.w//2-8, 0, "Oscillator:", DIM)
75
+ c.set_pixel(c.w-3, 5 if ov > 0.5 else 4, '→' if ov > 0.5 else '←', WHITE)
76
+
77
+ # -- SEQUENCE -------------------------------------------------
78
+ _LS['seq'].update(dt)
79
+ sv = _LS['seq'].value
80
+ if not _LS['seq'].done:
81
+ sx = int(10 + sv * 50)
82
+ sy = 10
83
+ for dx in range(-2, 3):
84
+ px = sx + dx
85
+ if 0 <= px < c.w and 0 <= sy < c.h:
86
+ c.set_pixel(px, sy, '■', Color(100+int(sv*155), 255, 100), z=20)
87
+ c.draw_text(sx-4, 12, "seq→", DIM)
88
+ else:
89
+ if random.random() < dt:
90
+ _LS['seq'].reset()