cuju-render 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 (382) hide show
  1. cuju/render/__init__.py +759 -0
  2. cuju/render/__main__.py +1065 -0
  3. cuju/render/_export/__init__.py +3 -0
  4. cuju/render/_export/feed.py +542 -0
  5. cuju/render/_export/sizes.py +157 -0
  6. cuju/render/_export/video.py +1618 -0
  7. cuju/render/_export/video_jobs.py +408 -0
  8. cuju/render/_format/__init__.py +3 -0
  9. cuju/render/_format/annotations.py +235 -0
  10. cuju/render/_format/codec.py +307 -0
  11. cuju/render/_format/keep.py +121 -0
  12. cuju/render/_format/recording.py +860 -0
  13. cuju/render/_format/writer.py +54 -0
  14. cuju/render/_guide/__init__.py +3 -0
  15. cuju/render/_guide/doctor.py +523 -0
  16. cuju/render/_guide/help.py +62 -0
  17. cuju/render/_guide/tutorial.py +254 -0
  18. cuju/render/_http/__init__.py +3 -0
  19. cuju/render/_http/commands.py +57 -0
  20. cuju/render/_http/headers.py +103 -0
  21. cuju/render/_http/launch.py +500 -0
  22. cuju/render/_http/launchers.py +408 -0
  23. cuju/render/_http/pwa.py +128 -0
  24. cuju/render/_http/server.py +2105 -0
  25. cuju/render/_http/window.py +360 -0
  26. cuju/render/_moments/__init__.py +3 -0
  27. cuju/render/_moments/captions.py +284 -0
  28. cuju/render/_moments/events.py +1123 -0
  29. cuju/render/_moments/search.py +694 -0
  30. cuju/render/_packages/__init__.py +3 -0
  31. cuju/render/_packages/glsl.py +746 -0
  32. cuju/render/_packages/loudness.py +334 -0
  33. cuju/render/_packages/pack.py +1959 -0
  34. cuju/render/_packages/presentation.py +1376 -0
  35. cuju/render/_packages/vocabulary.py +609 -0
  36. cuju/render/_playing/__init__.py +3 -0
  37. cuju/render/_playing/achievements.py +463 -0
  38. cuju/render/_playing/bench.py +609 -0
  39. cuju/render/_playing/challenges.py +1813 -0
  40. cuju/render/_playing/demo.py +323 -0
  41. cuju/render/_playing/draw.py +211 -0
  42. cuju/render/_playing/errors.py +20 -0
  43. cuju/render/_playing/game.py +645 -0
  44. cuju/render/_playing/limits.py +339 -0
  45. cuju/render/_playing/play.py +926 -0
  46. cuju/render/_playing/policy_worker.py +250 -0
  47. cuju/render/_playing/strict.py +810 -0
  48. cuju/render/_registry/__init__.py +3 -0
  49. cuju/render/_registry/clips.py +394 -0
  50. cuju/render/_registry/joints.py +108 -0
  51. cuju/render/_registry/teams.py +2058 -0
  52. cuju/render/_store/__init__.py +3 -0
  53. cuju/render/_store/home.py +70 -0
  54. cuju/render/_store/library.py +604 -0
  55. cuju/render/_store/samples.py +163 -0
  56. cuju/render/_text/__init__.py +3 -0
  57. cuju/render/_text/languages.py +637 -0
  58. cuju/render/_text/messages.py +1396 -0
  59. cuju/render/_tournaments/__init__.py +3 -0
  60. cuju/render/_tournaments/results.py +547 -0
  61. cuju/render/_tournaments/tournament.py +2742 -0
  62. cuju/render/_tournaments/tournament_cli.py +587 -0
  63. cuju/render/_tournaments/tournament_runner.py +1975 -0
  64. cuju/render/_version.py +6 -0
  65. cuju/render/_watch/__init__.py +3 -0
  66. cuju/render/_watch/grid.py +265 -0
  67. cuju/render/_watch/live.py +664 -0
  68. cuju/render/_watch/notebook.py +79 -0
  69. cuju/render/_watch/show.py +171 -0
  70. cuju/render/samples/sample-11v11.cjr +0 -0
  71. cuju/render/samples/sample-5v5.cjr +0 -0
  72. cuju/render/samples/teams/starter/main.py +33 -0
  73. cuju/render/scenarios/benchmark_full_game_11_vs_11_easy.py +46 -0
  74. cuju/render/scenarios/benchmark_full_game_11_vs_11_hard.py +46 -0
  75. cuju/render/scenarios/benchmark_full_game_11_vs_11_medium.py +46 -0
  76. cuju/render/scenarios/benchmark_full_game_5_vs_5_easy.py +34 -0
  77. cuju/render/scenarios/benchmark_full_game_5_vs_5_hard.py +34 -0
  78. cuju/render/scenarios/benchmark_full_game_5_vs_5_medium.py +34 -0
  79. cuju/render/web/assets/adboard_polygon.webp +0 -0
  80. cuju/render/web/assets/adboard_your_ad_here.webp +0 -0
  81. cuju/render/web/assets/animations/kaykit-rig-medium-combatmelee.glb +0 -0
  82. cuju/render/web/assets/animations/kaykit-rig-medium-general.glb +0 -0
  83. cuju/render/web/assets/animations/kaykit-rig-medium-movementadvanced.glb +0 -0
  84. cuju/render/web/assets/animations/kaykit-rig-medium-movementbasic.glb +0 -0
  85. cuju/render/web/assets/animations/kaykit-rig-medium-simulation.glb +0 -0
  86. cuju/render/web/assets/animations/kaykit-rig-medium-special.glb +0 -0
  87. cuju/render/web/assets/ball.glb +0 -0
  88. cuju/render/web/assets/challenges/3_vs_1_with_keeper.mp4 +0 -0
  89. cuju/render/web/assets/challenges/3_vs_1_with_keeper.webp +0 -0
  90. cuju/render/web/assets/challenges/corner.mp4 +0 -0
  91. cuju/render/web/assets/challenges/corner.webp +0 -0
  92. cuju/render/web/assets/challenges/counterattack_easy.mp4 +0 -0
  93. cuju/render/web/assets/challenges/counterattack_easy.webp +0 -0
  94. cuju/render/web/assets/challenges/counterattack_hard.mp4 +0 -0
  95. cuju/render/web/assets/challenges/counterattack_hard.webp +0 -0
  96. cuju/render/web/assets/challenges/empty_goal.mp4 +0 -0
  97. cuju/render/web/assets/challenges/empty_goal.webp +0 -0
  98. cuju/render/web/assets/challenges/empty_goal_close.mp4 +0 -0
  99. cuju/render/web/assets/challenges/empty_goal_close.webp +0 -0
  100. cuju/render/web/assets/challenges/manifest.json +375 -0
  101. cuju/render/web/assets/challenges/one_on_one.mp4 +0 -0
  102. cuju/render/web/assets/challenges/one_on_one.webp +0 -0
  103. cuju/render/web/assets/challenges/one_on_one_hard.mp4 +0 -0
  104. cuju/render/web/assets/challenges/one_on_one_hard.webp +0 -0
  105. cuju/render/web/assets/challenges/pass_and_shoot_with_keeper.mp4 +0 -0
  106. cuju/render/web/assets/challenges/pass_and_shoot_with_keeper.webp +0 -0
  107. cuju/render/web/assets/challenges/run_pass_and_shoot_with_keeper.mp4 +0 -0
  108. cuju/render/web/assets/challenges/run_pass_and_shoot_with_keeper.webp +0 -0
  109. cuju/render/web/assets/challenges/run_to_score.mp4 +0 -0
  110. cuju/render/web/assets/challenges/run_to_score.webp +0 -0
  111. cuju/render/web/assets/challenges/run_to_score_with_keeper.mp4 +0 -0
  112. cuju/render/web/assets/challenges/run_to_score_with_keeper.webp +0 -0
  113. cuju/render/web/assets/challenges/single_goal_versus_lazy.mp4 +0 -0
  114. cuju/render/web/assets/challenges/single_goal_versus_lazy.webp +0 -0
  115. cuju/render/web/assets/crowd.webp +0 -0
  116. cuju/render/web/assets/crowd_normal.webp +0 -0
  117. cuju/render/web/assets/cuju-logo-384.png +0 -0
  118. cuju/render/web/assets/cuju-logo.png +0 -0
  119. cuju/render/web/assets/cuju-logo.svg +46 -0
  120. cuju/render/web/assets/cuju-mark-light.svg +33 -0
  121. cuju/render/web/assets/cuju-mark.svg +33 -0
  122. cuju/render/web/assets/goal.glb +0 -0
  123. cuju/render/web/assets/grass.webp +0 -0
  124. cuju/render/web/assets/hair_black.png +0 -0
  125. cuju/render/web/assets/hair_blonde.png +0 -0
  126. cuju/render/web/assets/hair_brown.png +0 -0
  127. cuju/render/web/assets/hair_darkblonde.png +0 -0
  128. cuju/render/web/assets/hair_long01.glb +0 -0
  129. cuju/render/web/assets/hair_long02.glb +0 -0
  130. cuju/render/web/assets/hair_medium01.glb +0 -0
  131. cuju/render/web/assets/hair_red.png +0 -0
  132. cuju/render/web/assets/hair_short01.glb +0 -0
  133. cuju/render/web/assets/hair_short02.glb +0 -0
  134. cuju/render/web/assets/icons/cuju-192.png +0 -0
  135. cuju/render/web/assets/icons/cuju-512.png +0 -0
  136. cuju/render/web/assets/icons/cuju-maskable-512.png +0 -0
  137. cuju/render/web/assets/kit_goalkeeper.webp +0 -0
  138. cuju/render/web/assets/kit_mask.png +0 -0
  139. cuju/render/web/assets/kit_normal.webp +0 -0
  140. cuju/render/web/assets/manifest.json +601 -0
  141. cuju/render/web/assets/models/kaykit-barbarian.glb +0 -0
  142. cuju/render/web/assets/models/kaykit-barbarian.json +23 -0
  143. cuju/render/web/assets/models/kaykit-knight.glb +0 -0
  144. cuju/render/web/assets/models/kaykit-knight.json +23 -0
  145. cuju/render/web/assets/models/kaykit-mage.glb +0 -0
  146. cuju/render/web/assets/models/kaykit-mage.json +23 -0
  147. cuju/render/web/assets/models/kaykit-mannequin-medium.glb +0 -0
  148. cuju/render/web/assets/models/kaykit-mannequin-medium.json +23 -0
  149. cuju/render/web/assets/models/kaykit-ranger.glb +0 -0
  150. cuju/render/web/assets/models/kaykit-ranger.json +23 -0
  151. cuju/render/web/assets/models/kaykit-rogue-hooded.glb +0 -0
  152. cuju/render/web/assets/models/kaykit-rogue-hooded.json +23 -0
  153. cuju/render/web/assets/models/kaykit-rogue.glb +0 -0
  154. cuju/render/web/assets/models/kaykit-rogue.json +23 -0
  155. cuju/render/web/assets/models/kaykit-skeleton-mage.glb +0 -0
  156. cuju/render/web/assets/models/kaykit-skeleton-mage.json +23 -0
  157. cuju/render/web/assets/models/kaykit-skeleton-minion.glb +0 -0
  158. cuju/render/web/assets/models/kaykit-skeleton-minion.json +23 -0
  159. cuju/render/web/assets/models/kaykit-skeleton-rogue.glb +0 -0
  160. cuju/render/web/assets/models/kaykit-skeleton-rogue.json +23 -0
  161. cuju/render/web/assets/models/kaykit-skeleton-warrior.glb +0 -0
  162. cuju/render/web/assets/models/kaykit-skeleton-warrior.json +23 -0
  163. cuju/render/web/assets/pitch.webp +0 -0
  164. cuju/render/web/assets/pitch_normal.webp +0 -0
  165. cuju/render/web/assets/player.glb +0 -0
  166. cuju/render/web/assets/shoe.webp +0 -0
  167. cuju/render/web/assets/shoe_sole.png +0 -0
  168. cuju/render/web/assets/skin_01.png +0 -0
  169. cuju/render/web/assets/skin_02.png +0 -0
  170. cuju/render/web/assets/skin_03.png +0 -0
  171. cuju/render/web/assets/skin_04.png +0 -0
  172. cuju/render/web/assets/sounds/applause.ogg +0 -0
  173. cuju/render/web/assets/sounds/beach-wave-1.ogg +0 -0
  174. cuju/render/web/assets/sounds/beach-wave-2.ogg +0 -0
  175. cuju/render/web/assets/sounds/beach-wave-3.ogg +0 -0
  176. cuju/render/web/assets/sounds/beach-wave-4.ogg +0 -0
  177. cuju/render/web/assets/sounds/city-horn.ogg +0 -0
  178. cuju/render/web/assets/sounds/city-loop.ogg +0 -0
  179. cuju/render/web/assets/sounds/city-siren.ogg +0 -0
  180. cuju/render/web/assets/sounds/crowd-cheer.ogg +0 -0
  181. cuju/render/web/assets/sounds/crowd-loop.ogg +0 -0
  182. cuju/render/web/assets/sounds/crowd-ooh.ogg +0 -0
  183. cuju/render/web/assets/sounds/gulls.ogg +0 -0
  184. cuju/render/web/assets/sounds/neon-sting.ogg +0 -0
  185. cuju/render/web/assets/sounds/rain-loop.ogg +0 -0
  186. cuju/render/web/assets/sounds/sounds.json +46 -0
  187. cuju/render/web/assets/sounds/space-beep.ogg +0 -0
  188. cuju/render/web/assets/sounds/space-hum.ogg +0 -0
  189. cuju/render/web/assets/sounds/space-radio.ogg +0 -0
  190. cuju/render/web/assets/sounds/whistle-long.ogg +0 -0
  191. cuju/render/web/assets/sounds/whistle-short.ogg +0 -0
  192. cuju/render/web/assets/sounds/wind-loop.ogg +0 -0
  193. cuju/render/web/easy.css +357 -0
  194. cuju/render/web/export.html +23 -0
  195. cuju/render/web/feed.css +262 -0
  196. cuju/render/web/feed.html +28 -0
  197. cuju/render/web/flat.css +120 -0
  198. cuju/render/web/home.css +837 -0
  199. cuju/render/web/index.html +373 -0
  200. cuju/render/web/js/boot.js +50 -0
  201. cuju/render/web/js/broadcast/audio.js +2141 -0
  202. cuju/render/web/js/broadcast/celebrate.js +1238 -0
  203. cuju/render/web/js/broadcast/decisions.js +609 -0
  204. cuju/render/web/js/broadcast/hud.js +352 -0
  205. cuju/render/web/js/broadcast/show.js +3614 -0
  206. cuju/render/web/js/broadcast/transition.js +2231 -0
  207. cuju/render/web/js/broadcast/voices.js +153 -0
  208. cuju/render/web/js/capture.js +101 -0
  209. cuju/render/web/js/core/accessibility.js +90 -0
  210. cuju/render/web/js/core/api.js +429 -0
  211. cuju/render/web/js/core/comfort.js +135 -0
  212. cuju/render/web/js/core/i18n.js +705 -0
  213. cuju/render/web/js/core/icons.js +167 -0
  214. cuju/render/web/js/core/input-settings.js +156 -0
  215. cuju/render/web/js/core/keys.js +277 -0
  216. cuju/render/web/js/core/language-ui.js +125 -0
  217. cuju/render/web/js/core/menu.js +853 -0
  218. cuju/render/web/js/core/names.js +113 -0
  219. cuju/render/web/js/core/page-structure.js +110 -0
  220. cuju/render/web/js/core/scenarios.js +109 -0
  221. cuju/render/web/js/core/spoilers.js +236 -0
  222. cuju/render/web/js/core/typeahead.js +38 -0
  223. cuju/render/web/js/export/dom-picture.js +330 -0
  224. cuju/render/web/js/export/export-host.js +97 -0
  225. cuju/render/web/js/export/feed-dialog.js +191 -0
  226. cuju/render/web/js/export/feed-params.js +266 -0
  227. cuju/render/web/js/export/feed.js +363 -0
  228. cuju/render/web/js/export/mp4-mux.js +295 -0
  229. cuju/render/web/js/export/photo-core.js +313 -0
  230. cuju/render/web/js/export/photo.js +1314 -0
  231. cuju/render/web/js/export/safe-frame.js +59 -0
  232. cuju/render/web/js/export/size-fields.js +103 -0
  233. cuju/render/web/js/export/sizes.js +178 -0
  234. cuju/render/web/js/export/video-boot.js +55 -0
  235. cuju/render/web/js/export/video-browser.js +325 -0
  236. cuju/render/web/js/export/video-export.js +417 -0
  237. cuju/render/web/js/export/video-plan.js +207 -0
  238. cuju/render/web/js/export/video-range.js +185 -0
  239. cuju/render/web/js/export/webm-mux.js +198 -0
  240. cuju/render/web/js/feed-boot.js +151 -0
  241. cuju/render/web/js/feed-frame.js +101 -0
  242. cuju/render/web/js/help/doctor.js +488 -0
  243. cuju/render/web/js/help/firstrun.js +379 -0
  244. cuju/render/web/js/help/help-center.js +438 -0
  245. cuju/render/web/js/help/install-offer.js +164 -0
  246. cuju/render/web/js/help/install-state.js +104 -0
  247. cuju/render/web/js/help/lessons-core.js +207 -0
  248. cuju/render/web/js/help/lessons.js +463 -0
  249. cuju/render/web/js/help/palette.js +584 -0
  250. cuju/render/web/js/help/pwa.js +257 -0
  251. cuju/render/web/js/help/tour-core.js +241 -0
  252. cuju/render/web/js/help/tour.js +461 -0
  253. cuju/render/web/js/main.js +2513 -0
  254. cuju/render/web/js/pages/draw.js +188 -0
  255. cuju/render/web/js/pages/fieldpage.js +530 -0
  256. cuju/render/web/js/pages/home.js +521 -0
  257. cuju/render/web/js/pages/matches.js +779 -0
  258. cuju/render/web/js/pages/moments-ui.js +359 -0
  259. cuju/render/web/js/pages/queue-filters.js +63 -0
  260. cuju/render/web/js/pages/recording-groups.js +80 -0
  261. cuju/render/web/js/pages/recordings.js +1069 -0
  262. cuju/render/web/js/play/bench.js +347 -0
  263. cuju/render/web/js/play/challenges.js +1302 -0
  264. cuju/render/web/js/play/medals.js +127 -0
  265. cuju/render/web/js/play/play.js +1953 -0
  266. cuju/render/web/js/play/teasers.js +196 -0
  267. cuju/render/web/js/play/touch.js +350 -0
  268. cuju/render/web/js/play/tournament-layout.js +487 -0
  269. cuju/render/web/js/play/tournament-results.js +441 -0
  270. cuju/render/web/js/play/tournament-strict.js +560 -0
  271. cuju/render/web/js/play/tournament.js +2585 -0
  272. cuju/render/web/js/players/animate.js +972 -0
  273. cuju/render/web/js/players/clips.js +224 -0
  274. cuju/render/web/js/players/kaykit.js +162 -0
  275. cuju/render/web/js/players/kits.js +676 -0
  276. cuju/render/web/js/players/number-patch.js +82 -0
  277. cuju/render/web/js/players/players.js +2694 -0
  278. cuju/render/web/js/players/recolor.js +893 -0
  279. cuju/render/web/js/players/retarget.js +325 -0
  280. cuju/render/web/js/players/rig-numbers.js +174 -0
  281. cuju/render/web/js/presentation/animator.js +231 -0
  282. cuju/render/web/js/presentation/assign.js +85 -0
  283. cuju/render/web/js/presentation/behaviors.js +440 -0
  284. cuju/render/web/js/presentation/budget.js +209 -0
  285. cuju/render/web/js/presentation/catalog.js +1674 -0
  286. cuju/render/web/js/presentation/clocks.js +72 -0
  287. cuju/render/web/js/presentation/commands.js +301 -0
  288. cuju/render/web/js/presentation/contract.js +240 -0
  289. cuju/render/web/js/presentation/effects.js +904 -0
  290. cuju/render/web/js/presentation/flash.js +605 -0
  291. cuju/render/web/js/presentation/freeze-worklet.js +22 -0
  292. cuju/render/web/js/presentation/glsl.js +464 -0
  293. cuju/render/web/js/presentation/host.js +323 -0
  294. cuju/render/web/js/presentation/index.js +2066 -0
  295. cuju/render/web/js/presentation/loudness-worklet.js +235 -0
  296. cuju/render/web/js/presentation/loudness.js +740 -0
  297. cuju/render/web/js/presentation/moments.js +536 -0
  298. cuju/render/web/js/presentation/post.js +327 -0
  299. cuju/render/web/js/presentation/preview.js +180 -0
  300. cuju/render/web/js/presentation/protocol.js +174 -0
  301. cuju/render/web/js/presentation/reach.js +158 -0
  302. cuju/render/web/js/presentation/rigging.js +130 -0
  303. cuju/render/web/js/presentation/sandbox.js +157 -0
  304. cuju/render/web/js/presentation/shaders.js +235 -0
  305. cuju/render/web/js/presentation/stage.js +402 -0
  306. cuju/render/web/js/presentation/teamaudio.js +722 -0
  307. cuju/render/web/js/presentation/tracks.js +197 -0
  308. cuju/render/web/js/presentation/values.js +81 -0
  309. cuju/render/web/js/recording/annotation-data.js +203 -0
  310. cuju/render/web/js/recording/captions.js +491 -0
  311. cuju/render/web/js/recording/codec.js +185 -0
  312. cuju/render/web/js/recording/decode-worker.js +70 -0
  313. cuju/render/web/js/recording/decode.js +94 -0
  314. cuju/render/web/js/recording/episodes.js +46 -0
  315. cuju/render/web/js/recording/format.js +461 -0
  316. cuju/render/web/js/recording/live.js +348 -0
  317. cuju/render/web/js/recording/moments-query.js +59 -0
  318. cuju/render/web/js/recording/moments.js +149 -0
  319. cuju/render/web/js/recording/pose.js +86 -0
  320. cuju/render/web/js/recording/timeline.js +275 -0
  321. cuju/render/web/js/teams/art.js +50 -0
  322. cuju/render/web/js/teams/clip-editor.js +293 -0
  323. cuju/render/web/js/teams/editor.js +1979 -0
  324. cuju/render/web/js/teams/library.js +344 -0
  325. cuju/render/web/js/teams/painter.js +633 -0
  326. cuju/render/web/js/teams/surprise-ui.js +195 -0
  327. cuju/render/web/js/teams/surprise.js +497 -0
  328. cuju/render/web/js/teams/team-check.js +127 -0
  329. cuju/render/web/js/watch/annotations.js +270 -0
  330. cuju/render/web/js/watch/flat.js +366 -0
  331. cuju/render/web/js/watch/grid.js +436 -0
  332. cuju/render/web/js/watch/pitch2d.js +289 -0
  333. cuju/render/web/js/watch/player-tools.js +192 -0
  334. cuju/render/web/js/watch/presets.js +201 -0
  335. cuju/render/web/js/world/arenas.js +997 -0
  336. cuju/render/web/js/world/ball.js +204 -0
  337. cuju/render/web/js/world/cameras.js +982 -0
  338. cuju/render/web/js/world/crowd.js +376 -0
  339. cuju/render/web/js/world/field.js +227 -0
  340. cuju/render/web/js/world/framing.js +145 -0
  341. cuju/render/web/js/world/occlusion.js +48 -0
  342. cuju/render/web/js/world/pitch.js +703 -0
  343. cuju/render/web/js/world/scene.js +395 -0
  344. cuju/render/web/js/world/sky.js +325 -0
  345. cuju/render/web/js/world/stadium.js +1262 -0
  346. cuju/render/web/js/world/vendor-sky.js +367 -0
  347. cuju/render/web/js/world/weather.js +264 -0
  348. cuju/render/web/languages/en.json +4750 -0
  349. cuju/render/web/lessons.json +137 -0
  350. cuju/render/web/manifest.webmanifest +23 -0
  351. cuju/render/web/style.css +8399 -0
  352. cuju/render/web/sw.js +235 -0
  353. cuju/render/web/vendor/fabric/LICENSE +16 -0
  354. cuju/render/web/vendor/fabric/fabric.min.mjs +1 -0
  355. cuju/render/web/vendor/lucide/LICENSE +43 -0
  356. cuju/render/web/vendor/lucide/icons.js +141 -0
  357. cuju/render/web/vendor/three/LICENSE +21 -0
  358. cuju/render/web/vendor/three/build/three.core.js +60586 -0
  359. cuju/render/web/vendor/three/build/three.module.js +19719 -0
  360. cuju/render/web/vendor/three/examples/jsm/loaders/GLTFLoader.js +4925 -0
  361. cuju/render/web/vendor/three/examples/jsm/postprocessing/EffectComposer.js +365 -0
  362. cuju/render/web/vendor/three/examples/jsm/postprocessing/MaskPass.js +195 -0
  363. cuju/render/web/vendor/three/examples/jsm/postprocessing/OutputPass.js +148 -0
  364. cuju/render/web/vendor/three/examples/jsm/postprocessing/Pass.js +191 -0
  365. cuju/render/web/vendor/three/examples/jsm/postprocessing/RenderPass.js +193 -0
  366. cuju/render/web/vendor/three/examples/jsm/postprocessing/ShaderPass.js +135 -0
  367. cuju/render/web/vendor/three/examples/jsm/postprocessing/UnrealBloomPass.js +541 -0
  368. cuju/render/web/vendor/three/examples/jsm/shaders/CopyShader.js +52 -0
  369. cuju/render/web/vendor/three/examples/jsm/shaders/LuminosityHighPassShader.js +68 -0
  370. cuju/render/web/vendor/three/examples/jsm/shaders/OutputShader.js +103 -0
  371. cuju/render/web/vendor/three/examples/jsm/utils/BufferGeometryUtils.js +1501 -0
  372. cuju/render/web/vendor/three/examples/jsm/utils/SkeletonUtils.js +496 -0
  373. cuju_render-0.1.0.dist-info/METADATA +116 -0
  374. cuju_render-0.1.0.dist-info/RECORD +382 -0
  375. cuju_render-0.1.0.dist-info/WHEEL +4 -0
  376. cuju_render-0.1.0.dist-info/licenses/LICENSE +202 -0
  377. cuju_render-0.1.0.dist-info/licenses/LICENSES/CC-BY-4.0.txt +396 -0
  378. cuju_render-0.1.0.dist-info/licenses/LICENSES/CC0-1.0.txt +127 -0
  379. cuju_render-0.1.0.dist-info/licenses/LICENSES/ISC.txt +16 -0
  380. cuju_render-0.1.0.dist-info/licenses/LICENSES/MIT.txt +24 -0
  381. cuju_render-0.1.0.dist-info/licenses/LICENSES/Unlicense.txt +13 -0
  382. cuju_render-0.1.0.dist-info/licenses/NOTICE +35 -0
@@ -0,0 +1,664 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """A live source, which streams one environment of a running batch to the renderer's page.
5
+
6
+ The source listens on a port of the loopback interface and announces itself with a small file in
7
+ the renderer's folder, which the server lists. It reads a state only while a viewer watches, in
8
+ passages of five seconds of play paced to real time, so an unwatched batch pays one attribute check
9
+ per step and a watched one reads about ten states per second of wall time. Reading a state leaves
10
+ every output of the batch as it is, and a failure of the source turns it off, never the step.
11
+
12
+ The source keeps the last ten seconds of the steps it read, so a viewer who joins late starts with
13
+ that history. `CUJU_RENDER_BACKLOG` makes it read every step even unwatched, at the cost of one
14
+ state read per step, so that the first viewer finds a history as well.
15
+
16
+ A viewer may switch the environment that the source shows with `select_environment`, or through
17
+ the server, and the switch waits for the end of the next step. It changes which environment the
18
+ source reads and nothing of the batch, ends every stream of the last environment and starts a new
19
+ stream identifier, which the announcement names.
20
+
21
+ A viewer that asks for `/stream?sequence=1` receives every frame after a serial number of eight
22
+ bytes, and the stream ends with the serial `END`. The serials count the frames of one stream
23
+ identifier, which the header names, so a viewer that reconnects drops the frames it already holds
24
+ and sees the frames it missed as a gap.
25
+
26
+ A viewer that asks for `/grid?first=0&count=16` receives small views of a range of environments
27
+ as JSON, which the source reads at a low and bounded pace while a viewer asks, as `_grid` says.
28
+
29
+ A viewer of numbered frames that also asks for `annotations=1` receives the annotations of
30
+ `annotate`, each batch of them after the serial `NOTES`, the length of a JSON object and the
31
+ object, before the next frame.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import atexit
37
+ import collections
38
+ import contextlib
39
+ import http.server
40
+ import json
41
+ import logging
42
+ import operator
43
+ import os
44
+ import queue
45
+ import struct
46
+ import threading
47
+ import time
48
+ import urllib.parse
49
+ import weakref
50
+ from typing import Any
51
+
52
+ from cuju.errors import ArgumentError
53
+
54
+ from .._format import annotations as _annotations
55
+ from .._format import recording as _recording
56
+ from .._store import home as _home
57
+ from .._text import messages as _messages
58
+ from . import grid as _grid
59
+
60
+ # The variable that turns live sources on for every batch, with the environment to show.
61
+ LIVE_VARIABLE = 'CUJU_RENDER'
62
+ # Frames a viewer may hold before the source skips steps, five seconds of play.
63
+ _BUFFER = 50
64
+ # The variable that makes a source read every step, watched or not, for a history of its seconds.
65
+ BACKLOG_VARIABLE = 'CUJU_RENDER_BACKLOG'
66
+ # The history that a late viewer receives, ten seconds of steps.
67
+ _HISTORY = 100
68
+ # A watched source reads passages of this many consecutive steps, five seconds of play, and starts
69
+ # the next one when the wall clock has caught up, so a fast batch reads ten states a second.
70
+ _PASSAGE = 50
71
+ _STEPS_PER_SECOND = 10
72
+ _LOOPBACK = ('127.0.0.1', 'localhost', '::1')
73
+ # The serial that ends a numbered stream, which no frame carries.
74
+ END = 2**64 - 1
75
+ # The serial that opens a batch of annotations, which no frame carries either.
76
+ NOTES = 2**64 - 2
77
+ _SERIAL = struct.Struct('<Q')
78
+ _LENGTH = struct.Struct('<I')
79
+ _LOGGER = logging.getLogger('cuju')
80
+
81
+
82
+ class _Viewer:
83
+ """One connected viewer, with its queue of frames, numbered when `sequence` is true.
84
+
85
+ A viewer with `annotations` receives the annotations too, which need numbered frames.
86
+ """
87
+
88
+ def __init__(self, sequence: bool = False, annotations: bool = False) -> None:
89
+ self.frames: queue.Queue[bytes | None] = queue.Queue(_BUFFER)
90
+ self.header: bytes | None = None
91
+ self.sequence = sequence
92
+ self.annotations = sequence and annotations
93
+
94
+
95
+ def check_environment(batch: Any, environment: Any) -> None:
96
+ """Raises `ArgumentError` unless `environment` is an index of an environment of `batch`."""
97
+ count = int(batch.environment_count)
98
+ try:
99
+ if isinstance(environment, bool):
100
+ raise TypeError
101
+ environment = operator.index(environment)
102
+ except TypeError:
103
+ raise ArgumentError(
104
+ f'expected the environment as an integer, found {environment!r}'
105
+ ) from None
106
+ if not 0 <= environment < count:
107
+ raise ArgumentError(f'expected an environment from 0 to {count - 1}, found {environment}')
108
+
109
+
110
+ def _text(title: dict[str, Any] | str) -> str:
111
+ """Returns the English text of a title, a label or a person's text."""
112
+ return title['text'] if isinstance(title, dict) else str(title)
113
+
114
+
115
+ class LiveSource:
116
+ """Streams one environment of a batch to the renderer while a viewer watches.
117
+
118
+ Attributes:
119
+ identifier: The name of the source in the renderer's list.
120
+ environment: The index of the environment that the source shows.
121
+ environment_count: The number of environments of the batch, which a viewer may switch
122
+ between.
123
+ title: The title that the viewer shows.
124
+ port: The port of the loopback interface that the source listens on.
125
+ """
126
+
127
+ def __init__(
128
+ self,
129
+ batch: Any,
130
+ environment: int = 0,
131
+ title: str | dict[str, Any] | None = None,
132
+ teams: list[dict[str, Any]] | None = None,
133
+ scenario: str | None = None,
134
+ backlog: bool = False,
135
+ announce: bool = True,
136
+ ) -> None:
137
+ """Starts a source for `environment` of `batch` and announces it to the renderer.
138
+
139
+ Args:
140
+ batch: The batch, which `watch` or `CUJU_RENDER` gives the source as an observer.
141
+ environment: The environment to show.
142
+ title: The title, by default the scenario, the environment and the process. A title
143
+ that cuju makes is a label of `_messages.label`, which the page shows in its own
144
+ language, and `title` reads as its English text.
145
+ teams: The names and colors of the left and right team, as for a recording.
146
+ scenario: The name of the scenario, for the title and the list of sources, by default
147
+ the batch's.
148
+ backlog: Whether to read every step, watched or not, so that any viewer starts with
149
+ ten seconds of history, at the cost of one state read per step.
150
+ announce: Whether the source joins the renderer's list of live sources. A game that a
151
+ person plays streams through the server alone, so it stays off the list.
152
+ """
153
+ check_environment(batch, environment)
154
+ self._batch = weakref.ref(batch)
155
+ self.environment = int(environment)
156
+ self.environment_count = int(batch.environment_count)
157
+ # The environment that a viewer chose, which the source shows after the next step.
158
+ self._pending_environment: int | None = None
159
+ players = int(batch.left_players[self.environment] + batch.right_players[self.environment])
160
+ self._reader = _recording.StateReader(players)
161
+ self._scenario = scenario or scenario_name(batch)
162
+ # A title of the caller stays through a switch, the default one names the environment.
163
+ self._title = title
164
+ self._label: dict[str, Any] | str = title or self._default_title()
165
+ self.title = _text(self._label)
166
+ self._teams = teams
167
+ # The scenario's timing comes with the first state read, since a batch may announce its
168
+ # source before its first reset.
169
+ self._timing: dict[str, Any] | None = None
170
+ self._backlog = backlog
171
+ self._history: collections.deque[bytes] = collections.deque(maxlen=_HISTORY)
172
+ # The serial of each frame of the history, and the serial of the next frame.
173
+ self._serials: collections.deque[int] = collections.deque(maxlen=_HISTORY)
174
+ self._sequence = 0
175
+ self._generation = 0
176
+ # The annotations of the frames of the history, by serial and player, and those that the
177
+ # viewers have not received yet.
178
+ self._notes: dict[tuple[int, int], dict[str, Any]] = {}
179
+ self._fresh: dict[tuple[int, int], dict[str, Any]] = {}
180
+ self._lineup: list[dict[str, Any]] | None = None
181
+ self._viewers: list[_Viewer] = []
182
+ self._lock = threading.Lock()
183
+ self._passage = 0
184
+ self._passage_start = 0.0
185
+ # Small views of many environments, read only while a viewer asks for them.
186
+ self._grid = _grid.Grid(self.environment_count)
187
+ self.identifier = _home.new_identifier('live')
188
+ self._server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), self._handler())
189
+ self._server.daemon_threads = True
190
+ self.port = self._server.server_address[1]
191
+ self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
192
+ self._closed = False
193
+ self._thread.start()
194
+ self._announcement = _home.folder('live') / f'{self.identifier}.json'
195
+ self._announce = announce
196
+ if announce:
197
+ self._write_announcement()
198
+ atexit.register(self.close)
199
+
200
+ def __repr__(self) -> str:
201
+ state = 'closed' if self._closed else f'port {self.port}'
202
+ return (
203
+ f'LiveSource({self.identifier!r}, environment {self.environment} of '
204
+ f'{self.environment_count}, {self.title!r}, {state})'
205
+ )
206
+
207
+ def _default_title(self) -> dict[str, Any]:
208
+ """Returns the title that names the scenario, the environment and the process."""
209
+ return _messages.label(
210
+ 'server.names.live',
211
+ scenario=_messages.scenario(self._scenario),
212
+ environment=self.environment,
213
+ process=os.getpid(),
214
+ )
215
+
216
+ def _write_announcement(self) -> None:
217
+ """Writes the small file through which the server lists the source.
218
+
219
+ The file is written beside its place and moved there, so the server never reads half of it.
220
+ """
221
+ temporary = self._announcement.with_suffix('.part')
222
+ try:
223
+ temporary.write_text(
224
+ json.dumps(
225
+ {
226
+ 'id': self.identifier,
227
+ **_messages.named('title', self._label),
228
+ 'scenario': self._scenario,
229
+ 'environment': self.environment,
230
+ 'environment_count': self.environment_count,
231
+ 'generation': self._generation,
232
+ 'port': self.port,
233
+ 'pid': os.getpid(),
234
+ }
235
+ ),
236
+ encoding='utf-8',
237
+ )
238
+ temporary.replace(self._announcement)
239
+ except OSError:
240
+ with contextlib.suppress(OSError):
241
+ temporary.unlink()
242
+ raise
243
+
244
+ def _handler(self) -> type[http.server.BaseHTTPRequestHandler]:
245
+ """Returns the request handler class, bound to this source."""
246
+ source = self
247
+
248
+ class Handler(http.server.BaseHTTPRequestHandler):
249
+ def log_message(self, *arguments: Any) -> None:
250
+ pass
251
+
252
+ def do_POST(self) -> None:
253
+ # The server relays a switch without an origin, a page of any site sends one.
254
+ host = urllib.parse.urlsplit('//' + (self.headers.get('Host') or '')).hostname
255
+ if (
256
+ host not in _LOOPBACK
257
+ or self.headers.get('Origin') is not None
258
+ or self.headers.get('Content-Type') != 'application/json'
259
+ ):
260
+ self.send_error(403)
261
+ return
262
+ if self.path != '/environment':
263
+ self.send_error(404)
264
+ return
265
+ try:
266
+ length = int(self.headers.get('Content-Length') or 0)
267
+ if not 0 < length <= 1024:
268
+ raise ArgumentError('expected a request body of at most 1024 bytes')
269
+ document = json.loads(self.rfile.read(length))
270
+ if not isinstance(document, dict):
271
+ raise ArgumentError('expected a JSON object')
272
+ source.select_environment(document.get('environment'))
273
+ except ValueError as error:
274
+ self.send_error(400, str(error))
275
+ return
276
+ self.send_response(202)
277
+ self.send_header('Content-Length', '0')
278
+ self.end_headers()
279
+
280
+ def do_GET(self) -> None:
281
+ # The same guard as the server's, against pages of other sites that resolve here.
282
+ host = urllib.parse.urlsplit('//' + (self.headers.get('Host') or '')).hostname
283
+ if host not in _LOOPBACK:
284
+ self.send_error(403)
285
+ return
286
+ route = urllib.parse.urlsplit(self.path)
287
+ if route.path == '/grid':
288
+ _grid.respond(self, source._grid, route.query)
289
+ return
290
+ if route.path != '/stream':
291
+ self.send_error(404)
292
+ return
293
+ query = urllib.parse.parse_qs(route.query)
294
+ viewer = _Viewer(query.get('sequence') == ['1'], query.get('annotations') == ['1'])
295
+ # The history and the registration share the lock, so no step is sent twice.
296
+ with source._lock:
297
+ history = list(source._history)
298
+ if viewer.sequence:
299
+ history = [
300
+ _SERIAL.pack(serial) + frame
301
+ for serial, frame in zip(source._serials, history, strict=True)
302
+ ]
303
+ if viewer.annotations and source._notes:
304
+ history.append(_notes_payload(source._notes.values()))
305
+ if source._lineup is not None:
306
+ viewer.header = source._header(viewer.sequence, viewer.annotations)
307
+ if source._closed:
308
+ return
309
+ source._viewers.append(viewer)
310
+ try:
311
+ self.send_response(200)
312
+ self.send_header('Content-Type', 'application/octet-stream')
313
+ self.send_header('Cache-Control', 'no-store')
314
+ self.end_headers()
315
+ if viewer.header is not None:
316
+ self.wfile.write(viewer.header + b''.join(history))
317
+ self.wfile.flush()
318
+ while True:
319
+ frame = viewer.frames.get()
320
+ if frame is None:
321
+ # A numbered stream ends with its marker, so the viewer can tell the
322
+ # end from a lost connection.
323
+ if viewer.sequence:
324
+ self.wfile.write(_SERIAL.pack(END))
325
+ self.wfile.flush()
326
+ break
327
+ self.wfile.write(frame)
328
+ self.wfile.flush()
329
+ except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError):
330
+ pass
331
+ finally:
332
+ with source._lock:
333
+ if viewer in source._viewers:
334
+ source._viewers.remove(viewer)
335
+
336
+ return Handler
337
+
338
+ def _header(self, sequence: bool = False, annotations: bool = False) -> bytes:
339
+ """Returns the header of a stream, once a state has given the lineup.
340
+
341
+ Args:
342
+ sequence: Whether the stream numbers its frames, which the header then announces with
343
+ the identifier of the stream that the numbers count.
344
+ annotations: Whether the stream carries annotations, which the header announces.
345
+ """
346
+ fields = dict(self._timing or {})
347
+ fields['environment_count'] = self.environment_count
348
+ if sequence:
349
+ fields['stream_sequence'] = 1
350
+ fields['stream_id'] = f'{self.identifier}:{self._generation}'
351
+ if sequence and annotations:
352
+ fields['stream_annotations'] = 1
353
+ return _recording.header(
354
+ self._label,
355
+ self._scenario,
356
+ self._lineup,
357
+ self._teams,
358
+ timing=fields,
359
+ provenance={'source': 'live', 'environment': self.environment},
360
+ )
361
+
362
+ def _paced(self) -> bool:
363
+ """Returns whether this step belongs to a passage that a viewer receives."""
364
+ now = time.monotonic()
365
+ if self._passage >= _PASSAGE:
366
+ if now < self._passage_start + _PASSAGE / _STEPS_PER_SECOND:
367
+ return False
368
+ self._passage = 0
369
+ if self._passage == 0:
370
+ self._passage_start = now
371
+ self._passage += 1
372
+ return True
373
+
374
+ def __call__(self, batch: Any, done: Any, information: dict[str, Any]) -> None:
375
+ """Captures a step as a step observer of the batch, and closes with the batch.
376
+
377
+ A failure closes the source and raises, so the batch removes it with one warning and
378
+ steps on.
379
+ """
380
+ if done is None:
381
+ if information.get('close'):
382
+ self.close()
383
+ return
384
+ try:
385
+ self.after_step(done)
386
+ except Exception:
387
+ self.close()
388
+ raise
389
+
390
+ def after_step(self, done: Any) -> None:
391
+ """Captures the environment's frame for every viewer with room in its queue.
392
+
393
+ Args:
394
+ done: The done flags of the step.
395
+ """
396
+ with self._lock:
397
+ if self._pending_environment is not None:
398
+ self._switch()
399
+ viewers = [viewer for viewer in self._viewers if not viewer.frames.full()]
400
+ if self._grid.watched:
401
+ batch = self._batch()
402
+ if batch is not None:
403
+ self._grid.step(batch)
404
+ if viewers and not self._paced():
405
+ viewers = []
406
+ if not viewers and not self._backlog:
407
+ return
408
+ batch = self._batch()
409
+ if batch is None:
410
+ return
411
+ state = batch.get_state(self.environment, stacked=batch.stacked)
412
+ frame = self._reader.frame(state, _end_flags(batch, done, self.environment))
413
+ with self._lock:
414
+ if self._lineup is None:
415
+ self._lineup = self._reader.lineup(state)
416
+ if self._timing is None:
417
+ self._timing = _recording.scenario_timing(state)
418
+ self._deliver(frame, viewers)
419
+
420
+ def _switch(self) -> None:
421
+ """Shows the pending environment from this step on, with the lock held.
422
+
423
+ The switch changes which environment the source reads and nothing of the batch. The
424
+ streams of the last environment end, and the next stream starts with a new header, its own
425
+ history and its own serials. A failure to rewrite the announcement leaves the source
426
+ running under its old entry, with one warning.
427
+ """
428
+ batch = self._batch()
429
+ if batch is None:
430
+ return
431
+ self.environment, self._pending_environment = self._pending_environment, None
432
+ if self._title is None:
433
+ self._label = self._default_title()
434
+ self.title = _text(self._label)
435
+ players = int(batch.left_players[self.environment] + batch.right_players[self.environment])
436
+ self._reader = _recording.StateReader(players)
437
+ self._lineup = self._timing = None
438
+ self._history.clear()
439
+ self._serials.clear()
440
+ self._notes.clear()
441
+ self._fresh.clear()
442
+ self._sequence = 0
443
+ self._passage = 0
444
+ self._generation += 1
445
+ # The announcement changes before the streams end, so a viewer that asks the server
446
+ # straight after the end finds the new stream.
447
+ if self._announce:
448
+ try:
449
+ self._write_announcement()
450
+ except OSError as error:
451
+ _LOGGER.warning(
452
+ 'cuju render: the live source could not announce environment %d, %s: %s',
453
+ self.environment,
454
+ type(error).__name__,
455
+ error,
456
+ )
457
+ viewers, self._viewers = self._viewers, []
458
+ for viewer in viewers:
459
+ _end(viewer)
460
+
461
+ def select_environment(self, environment: int) -> None:
462
+ """Shows another environment of the batch from the end of its next step on.
463
+
464
+ Every stream of the current environment ends then, and a viewer who connects again
465
+ receives the new environment with a header of its own. A batch that is not stepping keeps
466
+ the choice until its next step, and the last choice before that step wins.
467
+
468
+ Args:
469
+ environment: The index of the environment to show.
470
+
471
+ Raises:
472
+ ArgumentError: When the index is not a whole number of the batch, or the source is
473
+ closed.
474
+ """
475
+ if (
476
+ isinstance(environment, bool)
477
+ or not isinstance(environment, int)
478
+ or not 0 <= environment < self.environment_count
479
+ ):
480
+ raise ArgumentError(
481
+ f'expected an environment from 0 to {self.environment_count - 1}, '
482
+ f'found {environment!r}'
483
+ )
484
+ with self._lock:
485
+ if self._closed:
486
+ raise ArgumentError('expected an open live source, found a closed one')
487
+ self._pending_environment = None if environment == self.environment else environment
488
+
489
+ def annotate(
490
+ self,
491
+ values: dict[str, Any] | None = None,
492
+ text: str | None = None,
493
+ player: Any = None,
494
+ step: int | None = None,
495
+ probabilities: Any = None,
496
+ action: Any = None,
497
+ ) -> bool:
498
+ """Attaches numbers or text to a frame that the source streamed, for its viewers.
499
+
500
+ The arguments are those of `Recorder.annotate`. The annotation reaches the viewers with
501
+ the next frame, and a viewer who joins later receives those of the frames of the history.
502
+ Annotating reads nothing of the batch and changes nothing of it.
503
+
504
+ Returns:
505
+ Whether a frame took the annotation, which an unwatched source, holding no frame of the
506
+ step, declines.
507
+
508
+ Raises:
509
+ ArgumentError: If a part of the annotation is invalid.
510
+ """
511
+ record = _annotations.note([], values, text, None, probabilities, action)
512
+ with self._lock:
513
+ lineup = self._lineup
514
+ frames = list(zip(self._serials, self._history, strict=True))
515
+ if lineup is None or not frames:
516
+ return False
517
+ if player is not None:
518
+ record['p'] = _annotations.player_index(lineup, player)
519
+ if step is None:
520
+ serial = frames[-1][0]
521
+ else:
522
+ found = [
523
+ serial for serial, frame in frames if struct.unpack_from('<i', frame)[0] == step
524
+ ]
525
+ if not found:
526
+ return False
527
+ serial = found[-1]
528
+ with self._lock:
529
+ if not self._serials or serial < self._serials[0]:
530
+ return False
531
+ merged = _annotations.merge(self._notes, serial, record)
532
+ self._fresh[(serial, merged.get('p', -1))] = merged
533
+ return True
534
+
535
+ def push(self, frame: bytes, lineup: list[dict[str, Any]]) -> None:
536
+ """Sends a frame that the caller read to every viewer at once, without pacing.
537
+
538
+ A game that a person plays reads each frame for its recording and streams the same bytes,
539
+ so the source reads no state of its own and the page receives every step as it happens.
540
+
541
+ Args:
542
+ frame: The frame, as `StateReader.frame` returns it.
543
+ lineup: The header entry of each player, as `StateReader.lineup` returns it.
544
+ """
545
+ with self._lock:
546
+ if self._lineup is None:
547
+ self._lineup = lineup
548
+ viewers = list(self._viewers)
549
+ self._deliver(frame, viewers)
550
+
551
+ def _deliver(self, frame: bytes, viewers: list[_Viewer]) -> None:
552
+ """Adds a frame to the history and queues it for `viewers`, a header first for new ones."""
553
+ with self._lock:
554
+ # The history holds consecutive steps only, so a gap starts it again.
555
+ if self._history:
556
+ (last,) = struct.unpack_from('<i', self._history[-1])
557
+ (step,) = struct.unpack_from('<i', frame)
558
+ if step != last + 1:
559
+ self._history.clear()
560
+ self._serials.clear()
561
+ if self._closed:
562
+ return
563
+ serial = self._sequence
564
+ self._sequence += 1
565
+ self._history.append(frame)
566
+ self._serials.append(serial)
567
+ # The annotations of frames that left the history go with them, and those that the
568
+ # viewers have not received go before this frame.
569
+ first = self._serials[0]
570
+ if any(key[0] < first for key in self._notes):
571
+ self._notes = {key: note for key, note in self._notes.items() if key[0] >= first}
572
+ notes = _notes_payload(self._fresh.values()) if self._fresh else b''
573
+ self._fresh.clear()
574
+ for viewer in viewers:
575
+ payload = _SERIAL.pack(serial) + frame if viewer.sequence else frame
576
+ if viewer.annotations:
577
+ payload = notes + payload
578
+ if viewer.header is None:
579
+ viewer.header = self._header(viewer.sequence, viewer.annotations)
580
+ payload = viewer.header + payload
581
+ with contextlib.suppress(queue.Full):
582
+ viewer.frames.put_nowait(payload)
583
+
584
+ def close(self) -> None:
585
+ """Ends every stream, stops listening and withdraws the announcement."""
586
+ if self._closed:
587
+ return
588
+ self._closed = True
589
+ atexit.unregister(self.close)
590
+ batch = self._batch()
591
+ if batch is not None and any(
592
+ observer is self for observer in getattr(batch, 'observers', ())
593
+ ):
594
+ batch.remove_observer(self)
595
+ # The announcement goes first, so a viewer whose stream ends finds the source gone.
596
+ with contextlib.suppress(OSError):
597
+ self._announcement.unlink()
598
+ with self._lock:
599
+ viewers, self._viewers = self._viewers, []
600
+ for viewer in viewers:
601
+ _end(viewer)
602
+ self._server.shutdown()
603
+ self._server.server_close()
604
+
605
+ def __enter__(self) -> LiveSource:
606
+ return self
607
+
608
+ def __exit__(self, *exception: object) -> None:
609
+ """Closes the source, so that `with cuju.render.watch(batch):` withdraws it at the end."""
610
+ self.close()
611
+
612
+
613
+ def _notes_payload(records: Any) -> bytes:
614
+ """Returns a batch of annotations as a numbered stream carries it."""
615
+ data = _annotations.encode(records)
616
+ return _SERIAL.pack(NOTES) + _LENGTH.pack(len(data)) + data
617
+
618
+
619
+ def _end(viewer: _Viewer) -> None:
620
+ """Ends the stream of a viewer, dropping the frames it has not received yet."""
621
+ while True:
622
+ try:
623
+ viewer.frames.get_nowait()
624
+ except queue.Empty:
625
+ break
626
+ viewer.frames.put_nowait(None)
627
+
628
+
629
+ def _end_flags(batch: Any, done: Any, environment: int) -> int:
630
+ """Returns the flags of a frame for the done flags of its step.
631
+
632
+ With automatic resets the step that ends an episode already shows the next kick-off, so its
633
+ frame carries 2, an episode ended just before it, and otherwise the frame that ends one carries
634
+ 1.
635
+ """
636
+ if done is None or not bool(done[environment]):
637
+ return 0
638
+ return 2 if batch.auto_reset else 1
639
+
640
+
641
+ def from_environment(batch: Any) -> LiveSource | None:
642
+ """Returns a source for `batch` when `CUJU_RENDER` asks for one, else `None`.
643
+
644
+ `CUJU_RENDER` holds `on` for environment 0, or the index of the environment to show, and an
645
+ empty value or `off` leaves the batch without a source. A non-empty `CUJU_RENDER_BACKLOG` other
646
+ than `0` or `off` makes the source read every step, so that any viewer starts with a history.
647
+ The caller adds the source to the batch's observers.
648
+
649
+ Args:
650
+ batch: The batch.
651
+ """
652
+ value = os.environ.get(LIVE_VARIABLE, '').strip().lower()
653
+ if value in ('', 'off', 'false', 'no'):
654
+ return None
655
+ environment = int(value) if value.isdigit() else 0
656
+ if not 0 <= environment < batch.environment_count:
657
+ environment = 0
658
+ backlog = os.environ.get(BACKLOG_VARIABLE, '').strip().lower() not in ('', '0', 'off', 'no')
659
+ return LiveSource(batch, environment, scenario=scenario_name(batch), backlog=backlog)
660
+
661
+
662
+ def scenario_name(batch: Any) -> str:
663
+ """Returns the scenarios a batch was created with, as `scenario_name` names them, or `match`."""
664
+ return getattr(batch, 'scenario_name', None) or 'match'