@bornengine/engine 0.4.16

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 (213) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +231 -0
  3. package/native/android/Cargo.lock +1848 -0
  4. package/native/android/Cargo.toml +24 -0
  5. package/native/android/src/lib.rs +702 -0
  6. package/native/ios/Cargo.lock +1690 -0
  7. package/native/ios/Cargo.toml +32 -0
  8. package/native/ios/src/lib.rs +1267 -0
  9. package/native/linux/Cargo.lock +3279 -0
  10. package/native/linux/Cargo.toml +29 -0
  11. package/native/linux/src/lib.rs +1331 -0
  12. package/native/macos/Cargo.lock +3310 -0
  13. package/native/macos/Cargo.toml +46 -0
  14. package/native/macos/src/lib.rs +1302 -0
  15. package/native/shared/Cargo.lock +1899 -0
  16. package/native/shared/Cargo.toml +62 -0
  17. package/native/shared/assets/default_font.ttf +0 -0
  18. package/native/shared/build.rs +270 -0
  19. package/native/shared/shaders/common/clouds.wgsl +122 -0
  20. package/native/shared/shaders/common/fog.wgsl +16 -0
  21. package/native/shared/shaders/common/foliage_wind.wgsl +98 -0
  22. package/native/shared/shaders/common/imposter.wgsl +112 -0
  23. package/native/shared/shaders/common/pbr.wgsl +186 -0
  24. package/native/shared/shaders/common/shadows.wgsl +186 -0
  25. package/native/shared/shaders/common/sky.wgsl +8 -0
  26. package/native/shared/shaders/common/tonemap.wgsl +25 -0
  27. package/native/shared/shaders/impulse_field.wgsl +57 -0
  28. package/native/shared/shaders/material_abi.wgsl +383 -0
  29. package/native/shared/shaders/materials/test_minimal.wgsl +42 -0
  30. package/native/shared/src/anim_mixer.rs +61 -0
  31. package/native/shared/src/attach.rs +263 -0
  32. package/native/shared/src/audio/decode.rs +123 -0
  33. package/native/shared/src/audio/mod.rs +863 -0
  34. package/native/shared/src/audio/render.rs +892 -0
  35. package/native/shared/src/audio/spsc.rs +156 -0
  36. package/native/shared/src/audio/stream.rs +226 -0
  37. package/native/shared/src/custom_shaders.rs +104 -0
  38. package/native/shared/src/decals.rs +245 -0
  39. package/native/shared/src/drs.rs +211 -0
  40. package/native/shared/src/engine.rs +261 -0
  41. package/native/shared/src/ffi.rs +116 -0
  42. package/native/shared/src/ffi_core/assets.rs +388 -0
  43. package/native/shared/src/ffi_core/audio_ffi.rs +184 -0
  44. package/native/shared/src/ffi_core/draw.rs +334 -0
  45. package/native/shared/src/ffi_core/game_loop.rs +577 -0
  46. package/native/shared/src/ffi_core/input.rs +234 -0
  47. package/native/shared/src/ffi_core/mod.rs +127 -0
  48. package/native/shared/src/ffi_core/models.rs +1154 -0
  49. package/native/shared/src/ffi_core/ragdoll_ffi.rs +261 -0
  50. package/native/shared/src/ffi_core/scene.rs +626 -0
  51. package/native/shared/src/ffi_core/vfx.rs +212 -0
  52. package/native/shared/src/ffi_core/visual.rs +691 -0
  53. package/native/shared/src/frame_callbacks.rs +122 -0
  54. package/native/shared/src/geometry.rs +236 -0
  55. package/native/shared/src/handles.rs +182 -0
  56. package/native/shared/src/input.rs +448 -0
  57. package/native/shared/src/jolt_sys.rs +822 -0
  58. package/native/shared/src/lib.rs +55 -0
  59. package/native/shared/src/models.rs +1093 -0
  60. package/native/shared/src/models_gltf.rs +1280 -0
  61. package/native/shared/src/particles.rs +391 -0
  62. package/native/shared/src/physics_jolt.rs +1908 -0
  63. package/native/shared/src/picking.rs +298 -0
  64. package/native/shared/src/postfx.rs +345 -0
  65. package/native/shared/src/profiler.rs +492 -0
  66. package/native/shared/src/ragdoll.rs +474 -0
  67. package/native/shared/src/renderer/atmosphere_lut.rs +573 -0
  68. package/native/shared/src/renderer/brdf_lut.rs +154 -0
  69. package/native/shared/src/renderer/draw2d.rs +143 -0
  70. package/native/shared/src/renderer/formats.rs +822 -0
  71. package/native/shared/src/renderer/froxel.rs +421 -0
  72. package/native/shared/src/renderer/gi_bake.rs +653 -0
  73. package/native/shared/src/renderer/graph.rs +462 -0
  74. package/native/shared/src/renderer/hiz.rs +269 -0
  75. package/native/shared/src/renderer/hot_reload.rs +390 -0
  76. package/native/shared/src/renderer/impulse_field.rs +456 -0
  77. package/native/shared/src/renderer/lighting.rs +154 -0
  78. package/native/shared/src/renderer/material_instancing.rs +171 -0
  79. package/native/shared/src/renderer/material_pipeline.rs +700 -0
  80. package/native/shared/src/renderer/material_system.rs +1996 -0
  81. package/native/shared/src/renderer/material_system_tests.rs +601 -0
  82. package/native/shared/src/renderer/material_system_wasm.rs +41 -0
  83. package/native/shared/src/renderer/mod.rs +12556 -0
  84. package/native/shared/src/renderer/model_draw.rs +641 -0
  85. package/native/shared/src/renderer/occlusion.rs +429 -0
  86. package/native/shared/src/renderer/planar_pass.rs +593 -0
  87. package/native/shared/src/renderer/planar_reflection.rs +499 -0
  88. package/native/shared/src/renderer/post_pass.rs +249 -0
  89. package/native/shared/src/renderer/postfx_chain.rs +728 -0
  90. package/native/shared/src/renderer/pt_pass.rs +577 -0
  91. package/native/shared/src/renderer/scene_pass.rs +607 -0
  92. package/native/shared/src/renderer/shader_include.rs +205 -0
  93. package/native/shared/src/renderer/shader_library.rs +135 -0
  94. package/native/shared/src/renderer/shaders/ao.rs +570 -0
  95. package/native/shared/src/renderer/shaders/core.rs +1243 -0
  96. package/native/shared/src/renderer/shaders/env.rs +907 -0
  97. package/native/shared/src/renderer/shaders/gi.rs +810 -0
  98. package/native/shared/src/renderer/shaders/mod.rs +19 -0
  99. package/native/shared/src/renderer/shaders/post.rs +1558 -0
  100. package/native/shared/src/renderer/shaders/pt.rs +1859 -0
  101. package/native/shared/src/renderer/shaders/ssgi.rs +1586 -0
  102. package/native/shared/src/renderer/shadow_pass.rs +731 -0
  103. package/native/shared/src/renderer/ssgi_pass.rs +392 -0
  104. package/native/shared/src/renderer/ssr_pass.rs +188 -0
  105. package/native/shared/src/renderer/texture_store.rs +473 -0
  106. package/native/shared/src/renderer/transient.rs +591 -0
  107. package/native/shared/src/renderer/types.rs +941 -0
  108. package/native/shared/src/renderer/util.rs +152 -0
  109. package/native/shared/src/scene.rs +1362 -0
  110. package/native/shared/src/sdf_cache.rs +274 -0
  111. package/native/shared/src/shadows.rs +1036 -0
  112. package/native/shared/src/staging.rs +102 -0
  113. package/native/shared/src/string_header.rs +266 -0
  114. package/native/shared/src/text_renderer.rs +502 -0
  115. package/native/shared/src/textures.rs +197 -0
  116. package/native/tvos/Cargo.lock +1693 -0
  117. package/native/tvos/Cargo.toml +36 -0
  118. package/native/tvos/metal-patched/Cargo.toml +178 -0
  119. package/native/tvos/metal-patched/LICENSE-APACHE +201 -0
  120. package/native/tvos/metal-patched/LICENSE-MIT +25 -0
  121. package/native/tvos/metal-patched/src/acceleration_structure.rs +667 -0
  122. package/native/tvos/metal-patched/src/acceleration_structure_pass.rs +108 -0
  123. package/native/tvos/metal-patched/src/argument.rs +366 -0
  124. package/native/tvos/metal-patched/src/blitpass.rs +102 -0
  125. package/native/tvos/metal-patched/src/buffer.rs +71 -0
  126. package/native/tvos/metal-patched/src/capturedescriptor.rs +76 -0
  127. package/native/tvos/metal-patched/src/capturemanager.rs +113 -0
  128. package/native/tvos/metal-patched/src/commandbuffer.rs +192 -0
  129. package/native/tvos/metal-patched/src/commandqueue.rs +44 -0
  130. package/native/tvos/metal-patched/src/computepass.rs +107 -0
  131. package/native/tvos/metal-patched/src/constants.rs +152 -0
  132. package/native/tvos/metal-patched/src/counters.rs +119 -0
  133. package/native/tvos/metal-patched/src/depthstencil.rs +190 -0
  134. package/native/tvos/metal-patched/src/device.rs +2134 -0
  135. package/native/tvos/metal-patched/src/drawable.rs +39 -0
  136. package/native/tvos/metal-patched/src/encoder.rs +2041 -0
  137. package/native/tvos/metal-patched/src/heap.rs +281 -0
  138. package/native/tvos/metal-patched/src/indirect_encoder.rs +344 -0
  139. package/native/tvos/metal-patched/src/lib.rs +657 -0
  140. package/native/tvos/metal-patched/src/library.rs +902 -0
  141. package/native/tvos/metal-patched/src/mps.rs +575 -0
  142. package/native/tvos/metal-patched/src/pipeline/compute.rs +475 -0
  143. package/native/tvos/metal-patched/src/pipeline/mod.rs +71 -0
  144. package/native/tvos/metal-patched/src/pipeline/render.rs +762 -0
  145. package/native/tvos/metal-patched/src/renderpass.rs +443 -0
  146. package/native/tvos/metal-patched/src/resource.rs +182 -0
  147. package/native/tvos/metal-patched/src/sampler.rs +165 -0
  148. package/native/tvos/metal-patched/src/sync.rs +178 -0
  149. package/native/tvos/metal-patched/src/texture.rs +352 -0
  150. package/native/tvos/metal-patched/src/types.rs +90 -0
  151. package/native/tvos/metal-patched/src/vertexdescriptor.rs +250 -0
  152. package/native/tvos/src/audio_backend.rs +197 -0
  153. package/native/tvos/src/lib.rs +1891 -0
  154. package/native/visionos/Cargo.lock +1693 -0
  155. package/native/visionos/Cargo.toml +40 -0
  156. package/native/visionos/src/audio_backend.rs +197 -0
  157. package/native/visionos/src/lib.rs +1887 -0
  158. package/native/watchos/Cargo.lock +16 -0
  159. package/native/watchos/Cargo.toml +19 -0
  160. package/native/watchos/shaders/bloom_postfx.metal +99 -0
  161. package/native/watchos/src/BloomWatchApp.swift +1267 -0
  162. package/native/watchos/src/BloomWatchAudio.swift +179 -0
  163. package/native/watchos/src/audio.rs +55 -0
  164. package/native/watchos/src/draw_list.rs +229 -0
  165. package/native/watchos/src/ffi_stubs.rs +915 -0
  166. package/native/watchos/src/ffi_stubs_manual.rs +35 -0
  167. package/native/watchos/src/lib.rs +1124 -0
  168. package/native/watchos/src/models.rs +746 -0
  169. package/native/watchos/src/postfx.rs +95 -0
  170. package/native/watchos/src/scene.rs +534 -0
  171. package/native/watchos/src/textures.rs +184 -0
  172. package/native/web/Cargo.lock +1657 -0
  173. package/native/web/Cargo.toml +43 -0
  174. package/native/web/bloom_glue.js +695 -0
  175. package/native/web/build.sh +131 -0
  176. package/native/web/index.html +35 -0
  177. package/native/web/jolt_bridge.js +1519 -0
  178. package/native/web/src/input_ffi.rs +286 -0
  179. package/native/web/src/lib.rs +1796 -0
  180. package/native/web/src/material_ffi.rs +710 -0
  181. package/native/web/src/parity_ffi.rs +343 -0
  182. package/native/web/src/physics_ffi.rs +643 -0
  183. package/native/web/src/ragdoll_ffi.rs +250 -0
  184. package/native/web/src/render_settings.rs +98 -0
  185. package/native/windows/Cargo.lock +1815 -0
  186. package/native/windows/Cargo.toml +68 -0
  187. package/native/windows/src/lib.rs +1486 -0
  188. package/package.json +4279 -0
  189. package/src/audio/index.ts +315 -0
  190. package/src/core/colors.ts +63 -0
  191. package/src/core/index.ts +1206 -0
  192. package/src/core/keys.ts +63 -0
  193. package/src/core/types.ts +104 -0
  194. package/src/index.ts +171 -0
  195. package/src/math/index.ts +516 -0
  196. package/src/mobile/index.ts +294 -0
  197. package/src/models/index.ts +1258 -0
  198. package/src/physics/index.ts +1134 -0
  199. package/src/scene/index.ts +698 -0
  200. package/src/shapes/index.ts +120 -0
  201. package/src/text/index.ts +48 -0
  202. package/src/textures/index.ts +187 -0
  203. package/src/vfx/index.ts +191 -0
  204. package/src/world/index.ts +24 -0
  205. package/src/world/loader.ts +423 -0
  206. package/src/world/prefab.ts +217 -0
  207. package/src/world/render.ts +172 -0
  208. package/src/world/saver.ts +108 -0
  209. package/src/world/serialize.ts +301 -0
  210. package/src/world/terrain.ts +355 -0
  211. package/src/world/types.ts +160 -0
  212. package/src/world/validate.ts +319 -0
  213. package/src/world/version.ts +114 -0
@@ -0,0 +1,1887 @@
1
+ use bloom_shared::engine::EngineState;
2
+ use bloom_shared::renderer::Renderer;
3
+ use bloom_shared::string_header::str_from_header;
4
+
5
+ use objc2::encode::{Encode, Encoding, RefEncode};
6
+ use objc2::rc::{Allocated, Retained};
7
+ use objc2::runtime::{AnyClass, AnyObject, Bool, Sel};
8
+ use objc2::{msg_send, sel};
9
+
10
+ use raw_window_handle::{RawDisplayHandle, RawWindowHandle, UiKitDisplayHandle, UiKitWindowHandle};
11
+
12
+ use std::ffi::c_void;
13
+ use std::sync::OnceLock;
14
+
15
+ // ============================================================
16
+ // objc_msg_lookup shim for the `objc` v0.2 crate
17
+ // ============================================================
18
+ // The `objc` v0.2 crate (used by `metal` via wgpu-hal) only recognizes
19
+ // macOS and iOS as Apple platforms. On tvOS it falls through to the GNUstep
20
+ // codepath which expects `objc_msg_lookup`. We shim it to return
21
+ // `objc_msgSend`, which on arm64 is the universal message dispatcher.
22
+ extern "C" {
23
+ fn objc_msgSend();
24
+ fn objc_msgSendSuper();
25
+ }
26
+
27
+ #[repr(C)]
28
+ struct ObjcSuper {
29
+ receiver: *mut c_void,
30
+ super_class: *const c_void,
31
+ }
32
+
33
+ #[no_mangle]
34
+ pub unsafe extern "C" fn objc_msg_lookup(
35
+ _receiver: *mut c_void, _sel: *const c_void,
36
+ ) -> unsafe extern "C" fn() {
37
+ objc_msgSend
38
+ }
39
+
40
+ #[no_mangle]
41
+ pub unsafe extern "C" fn objc_msg_lookup_super(
42
+ _sup: *const ObjcSuper, _sel: *const c_void,
43
+ ) -> unsafe extern "C" fn() {
44
+ objc_msgSendSuper
45
+ }
46
+
47
+ static mut ENGINE: OnceLock<EngineState> = OnceLock::new();
48
+ static mut UI_WINDOW: Option<Retained<AnyObject>> = None;
49
+ static mut UI_VIEW: Option<Retained<AnyObject>> = None;
50
+ static mut TOUCH_MAP: [*const c_void; 10] = [std::ptr::null(); 10];
51
+ static mut BUNDLE_PATH: Option<String> = None;
52
+ static mut SCREEN_SCALE: f64 = 1.0;
53
+ static SCENE_PTR: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
54
+
55
+ // Atomic key event buffer: main thread writes, game thread reads before begin_frame
56
+ // Bit layout: bits 0-511 = key down, bits 512-1023 = key up (pending)
57
+ static PENDING_KEY_DOWN: [std::sync::atomic::AtomicU64; 8] = {
58
+ const INIT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
59
+ [INIT; 8] // 8 * 64 = 512 bits
60
+ };
61
+ static PENDING_KEY_UP: [std::sync::atomic::AtomicU64; 8] = {
62
+ const INIT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
63
+ [INIT; 8]
64
+ };
65
+
66
+ fn pending_key_down(key: usize) {
67
+ if key < 512 {
68
+ PENDING_KEY_DOWN[key / 64].fetch_or(1u64 << (key % 64), std::sync::atomic::Ordering::Release);
69
+ }
70
+ }
71
+ fn pending_key_up(key: usize) {
72
+ if key < 512 {
73
+ PENDING_KEY_UP[key / 64].fetch_or(1u64 << (key % 64), std::sync::atomic::Ordering::Release);
74
+ }
75
+ }
76
+ fn drain_pending_keys(eng: &mut EngineState) {
77
+ for i in 0..8 {
78
+ let down = PENDING_KEY_DOWN[i].swap(0, std::sync::atomic::Ordering::Acquire);
79
+ let up = PENDING_KEY_UP[i].swap(0, std::sync::atomic::Ordering::Acquire);
80
+ if down != 0 || up != 0 {
81
+ static DRAIN_LOG: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
82
+ let n = DRAIN_LOG.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
83
+ if n < 20 {
84
+ std::io::Write::write_all(&mut std::io::stderr(),
85
+ format!("[bloom-visionos] DRAIN: down=0x{:x} up=0x{:x} bucket={}\n", down, up, i).as_bytes()).ok();
86
+ }
87
+ for bit in 0..64 {
88
+ let key = i * 64 + bit;
89
+ let is_down = down & (1u64 << bit) != 0;
90
+ let is_up = up & (1u64 << bit) != 0;
91
+ if is_down && is_up {
92
+ // Both pressed and released in same frame — register as down now,
93
+ // re-queue the up for next frame
94
+ eng.input.set_key_down(key);
95
+ pending_key_up(key);
96
+ } else if is_down {
97
+ eng.input.set_key_down(key);
98
+ } else if is_up {
99
+ eng.input.set_key_up(key);
100
+ }
101
+ }
102
+ }
103
+ }
104
+ }
105
+ #[no_mangle]
106
+ static SCREEN_DIMS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
107
+
108
+
109
+ /// Resolve a relative asset path to the app bundle path.
110
+ fn resolve_path(path: &str) -> String {
111
+ if path.starts_with('/') {
112
+ return path.to_string();
113
+ }
114
+ unsafe {
115
+ if let Some(ref base) = BUNDLE_PATH {
116
+ format!("{}/{}", base, path)
117
+ } else {
118
+ path.to_string()
119
+ }
120
+ }
121
+ }
122
+
123
+ fn engine() -> &'static mut EngineState {
124
+ unsafe { ENGINE.get_mut().expect("Engine not initialized") }
125
+ }
126
+ /// Asset-path hook for define_core_ffi! — routes through this platform's
127
+ /// resolve_path (relative paths don't resolve from the app working dir here).
128
+ fn bloom_resolve_asset_path(path: &str) -> std::borrow::Cow<'_, str> {
129
+ std::borrow::Cow::Owned(resolve_path(path))
130
+ }
131
+
132
+ // The full shared (non-physics) FFI surface. See bloom_shared::ffi_core
133
+ // docs for the contract; tools/validate-ffi.js checks parity in CI.
134
+ bloom_shared::define_core_ffi!();
135
+
136
+
137
+ // ============================================================
138
+ // CG types with objc2 Encode
139
+ // ============================================================
140
+
141
+ #[repr(C)]
142
+ #[derive(Copy, Clone)]
143
+ struct CGPoint { x: f64, y: f64 }
144
+
145
+ unsafe impl Encode for CGPoint {
146
+ const ENCODING: Encoding = Encoding::Struct("CGPoint", &[Encoding::Double, Encoding::Double]);
147
+ }
148
+ unsafe impl RefEncode for CGPoint {
149
+ const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING);
150
+ }
151
+
152
+ #[repr(C)]
153
+ #[derive(Copy, Clone)]
154
+ struct CGSize { width: f64, height: f64 }
155
+
156
+ unsafe impl Encode for CGSize {
157
+ const ENCODING: Encoding = Encoding::Struct("CGSize", &[Encoding::Double, Encoding::Double]);
158
+ }
159
+ unsafe impl RefEncode for CGSize {
160
+ const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING);
161
+ }
162
+
163
+ #[repr(C)]
164
+ #[derive(Copy, Clone)]
165
+ struct CGRect { origin: CGPoint, size: CGSize }
166
+
167
+ unsafe impl Encode for CGRect {
168
+ const ENCODING: Encoding = Encoding::Struct("CGRect", &[CGPoint::ENCODING, CGSize::ENCODING]);
169
+ }
170
+ unsafe impl RefEncode for CGRect {
171
+ const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING);
172
+ }
173
+
174
+ // ============================================================
175
+ // ObjC runtime
176
+ // ============================================================
177
+
178
+ extern "C" {
179
+ fn objc_allocateClassPair(superclass: *const AnyClass, name: *const u8, extra_bytes: usize) -> *mut AnyClass;
180
+ fn objc_registerClassPair(cls: *mut AnyClass);
181
+ fn class_addMethod(cls: *mut AnyClass, sel: Sel, imp: *const c_void, types: *const u8) -> bool;
182
+
183
+ fn CFRunLoopRunInMode(mode: *const c_void, seconds: f64, return_after: u8) -> i32;
184
+ static kCFRunLoopDefaultMode: *const c_void;
185
+ }
186
+
187
+ fn pump_run_loop(seconds: f64) {
188
+ unsafe { CFRunLoopRunInMode(kCFRunLoopDefaultMode, seconds, 0); }
189
+ }
190
+
191
+ // ============================================================
192
+ // Register BloomMetalView — UIView subclass with +layerClass = CAMetalLayer
193
+ // ============================================================
194
+
195
+ unsafe extern "C" fn bloom_layer_class(_cls: *const c_void, _sel: Sel) -> *const c_void {
196
+ AnyClass::get(c"CAMetalLayer").unwrap() as *const AnyClass as *const c_void
197
+ }
198
+
199
+ unsafe extern "C" fn bloom_touches_began(_this: *mut c_void, _sel: Sel, touches: *const AnyObject, _event: *const AnyObject) {
200
+ handle_touches(touches, TouchPhase::Began);
201
+ }
202
+
203
+ unsafe extern "C" fn bloom_touches_moved(_this: *mut c_void, _sel: Sel, touches: *const AnyObject, _event: *const AnyObject) {
204
+ handle_touches(touches, TouchPhase::Moved);
205
+ }
206
+
207
+ unsafe extern "C" fn bloom_touches_ended(_this: *mut c_void, _sel: Sel, touches: *const AnyObject, _event: *const AnyObject) {
208
+ handle_touches(touches, TouchPhase::Ended);
209
+ }
210
+
211
+ unsafe extern "C" fn bloom_touches_cancelled(_this: *mut c_void, _sel: Sel, touches: *const AnyObject, _event: *const AnyObject) {
212
+ handle_touches(touches, TouchPhase::Ended);
213
+ }
214
+
215
+ enum TouchPhase { Began, Moved, Ended }
216
+
217
+ unsafe fn handle_touches(touches: *const AnyObject, phase: TouchPhase) {
218
+ if touches.is_null() { return; }
219
+
220
+ let view_ptr: *const AnyObject = match UI_VIEW.as_ref() {
221
+ Some(v) => Retained::as_ptr(v),
222
+ None => std::ptr::null(),
223
+ };
224
+
225
+ let enumerator: Retained<AnyObject> = msg_send![&*touches, objectEnumerator];
226
+ loop {
227
+ let touch: *const AnyObject = msg_send![&*enumerator, nextObject];
228
+ if touch.is_null() { break; }
229
+
230
+ let touch_id = touch as *const c_void;
231
+ let loc: CGPoint = msg_send![&*touch, locationInView: view_ptr];
232
+
233
+ let index = match phase {
234
+ TouchPhase::Began => {
235
+ let mut slot = None;
236
+ for i in 0..10 {
237
+ if TOUCH_MAP[i].is_null() {
238
+ TOUCH_MAP[i] = touch_id;
239
+ slot = Some(i);
240
+ break;
241
+ }
242
+ }
243
+ match slot {
244
+ Some(i) => i,
245
+ None => continue,
246
+ }
247
+ }
248
+ TouchPhase::Moved => {
249
+ match TOUCH_MAP.iter().position(|&p| p == touch_id) {
250
+ Some(i) => i,
251
+ None => continue,
252
+ }
253
+ }
254
+ TouchPhase::Ended => {
255
+ match TOUCH_MAP.iter().position(|&p| p == touch_id) {
256
+ Some(i) => {
257
+ TOUCH_MAP[i] = std::ptr::null();
258
+ i
259
+ }
260
+ None => continue,
261
+ }
262
+ }
263
+ };
264
+
265
+ if let Some(eng) = ENGINE.get_mut() {
266
+ let active = !matches!(phase, TouchPhase::Ended);
267
+ // Scale touch from points to pixels to match getScreenWidth/Height
268
+ let sx = loc.x * SCREEN_SCALE;
269
+ let sy = loc.y * SCREEN_SCALE;
270
+ eng.input.set_touch(index, sx, sy, active);
271
+
272
+ if index == 0 {
273
+ eng.input.set_mouse_position(sx, sy);
274
+ if active {
275
+ eng.input.set_mouse_button_down(0);
276
+ } else {
277
+ eng.input.set_mouse_button_up(0);
278
+ }
279
+ }
280
+ }
281
+ }
282
+ }
283
+
284
+ // tvOS: allow the metal view to become focused (required for remote events)
285
+ unsafe extern "C" fn bloom_can_become_focused(_this: *mut c_void, _sel: Sel) -> Bool {
286
+ Bool::YES
287
+ }
288
+
289
+ // tvOS: handle Siri Remote / game controller press events
290
+ // UIPressType values: 0=UpArrow, 1=DownArrow, 2=LeftArrow, 3=RightArrow,
291
+ // 4=Select, 5=Menu, 6=PlayPause
292
+ unsafe extern "C" fn bloom_presses_began(_this: *mut c_void, _sel: Sel, presses: *const AnyObject, _event: *const AnyObject) {
293
+ // Log to file since stderr doesn't always capture
294
+ static PRESS_COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
295
+ let n = PRESS_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
296
+ let _ = std::fs::OpenOptions::new().create(true).append(true).open("/tmp/bloom_press_log.txt")
297
+ .and_then(|mut f| std::io::Write::write_all(&mut f, format!("pressesBegan #{}\n", n).as_bytes()));
298
+ handle_presses(presses, true);
299
+ }
300
+
301
+ unsafe extern "C" fn bloom_presses_ended(_this: *mut c_void, _sel: Sel, presses: *const AnyObject, _event: *const AnyObject) {
302
+ handle_presses(presses, false);
303
+ }
304
+
305
+ unsafe fn handle_presses(presses: *const AnyObject, down: bool) {
306
+ if presses.is_null() { return; }
307
+
308
+ extern "C" { fn objc_msgSend(); }
309
+ let send_ptr: unsafe extern "C" fn(*const AnyObject, Sel) -> *const AnyObject =
310
+ std::mem::transmute(objc_msgSend as unsafe extern "C" fn());
311
+ let send_i64: unsafe extern "C" fn(*const AnyObject, Sel) -> i64 =
312
+ std::mem::transmute(objc_msgSend as unsafe extern "C" fn());
313
+
314
+ let enumerator = send_ptr(presses, sel!(objectEnumerator));
315
+ if enumerator.is_null() { return; }
316
+ loop {
317
+ let press = send_ptr(enumerator, sel!(nextObject));
318
+ if press.is_null() { break; }
319
+
320
+ let press_type = send_i64(press, Sel::register(c"type"));
321
+ // Map press types to Bloom Key codes
322
+ // Map press types to Bloom Key codes
323
+ // Remote: 0=Up 1=Down 2=Left 3=Right 4=Select 5=Menu 6=PlayPause
324
+ // Keyboard: 2040=Enter 2041=Escape 2044=Space
325
+ // 2079=Right 2080=Left 2081=Down 2082=Up
326
+ // 2000+HID for other keys
327
+ let key = match press_type {
328
+ 0 => Some(256), 1 => Some(257), 2 => Some(258), 3 => Some(259),
329
+ 4 => Some(265), 5 => Some(27), 6 => Some(27),
330
+ 2040 => Some(265), // Enter
331
+ 2041 => Some(27), // Escape
332
+ 2044 => Some(32), // Space
333
+ 2080 => Some(258), // Left arrow
334
+ 2079 => Some(259), // Right arrow
335
+ 2081 => Some(257), // Down arrow
336
+ 2082 => Some(256), // Up arrow
337
+ _ => None,
338
+ };
339
+ if let Some(k) = key {
340
+ if down { pending_key_down(k); } else { pending_key_up(k); }
341
+ } else {
342
+ static UNK_LOG: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
343
+ if UNK_LOG.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 30 {
344
+ std::io::Write::write_all(&mut std::io::stderr(),
345
+ format!("[bloom-visionos] UNKNOWN press type={} down={}\n", press_type, down).as_bytes()).ok();
346
+ }
347
+ }
348
+ // Enter/Select also triggers Space (for jump)
349
+ if press_type == 4 || press_type == 2040 || press_type == 2044 {
350
+ if down { pending_key_down(32); } else { pending_key_up(32); }
351
+ }
352
+ }
353
+ }
354
+
355
+ /// Returns an NSArray containing just the VC's view, so the focus system focuses it.
356
+ unsafe extern "C" fn bloom_vc_preferred_focus(this: *mut c_void, _sel: Sel) -> *const AnyObject {
357
+ let view: Retained<AnyObject> = msg_send![&*(this as *const AnyObject), view];
358
+ let arr_cls = AnyClass::get(c"NSArray").unwrap();
359
+ let arr: Retained<AnyObject> = msg_send![arr_cls, arrayWithObject: &*view];
360
+ let ptr = Retained::as_ptr(&arr);
361
+ std::mem::forget(arr);
362
+ ptr
363
+ }
364
+
365
+ static ORIG_SEND_EVENT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
366
+
367
+ /// BloomApplication.sendEvent: override — intercepts ALL events at the app level
368
+ unsafe extern "C" fn bloom_app_send_event(this: *mut c_void, _sel: Sel, event: *const AnyObject) {
369
+ let event_type: i64 = msg_send![&*event, type];
370
+ static APP_EVENT_COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
371
+ let count = APP_EVENT_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
372
+ if count < 100 {
373
+ let subtype: i64 = msg_send![&*event, subtype];
374
+ std::io::Write::write_all(&mut std::io::stderr(),
375
+ format!("[bloom-visionos] APP sendEvent #{} type={} subtype={}\n", count, event_type, subtype).as_bytes()).ok();
376
+ }
377
+ // Let ALL events flow through to the responder chain (UIWindow → VC).
378
+ // BloomViewController's pressesBegan handles press events.
379
+ // BloomWindow's sendEvent handles keyboard events (type 4) by eating them.
380
+
381
+ // For non-press/keyboard events, call super
382
+ extern "C" { fn objc_msgSendSuper(); }
383
+ #[repr(C)]
384
+ struct ObjcSuperCall { receiver: *mut c_void, super_class: *const c_void }
385
+ let superclass = AnyClass::get(c"UIApplication").unwrap();
386
+ let sup = ObjcSuperCall { receiver: this, super_class: superclass as *const AnyClass as *const c_void };
387
+ let send_super: unsafe extern "C" fn(*const ObjcSuperCall, Sel, *const AnyObject) = std::mem::transmute(objc_msgSendSuper as unsafe extern "C" fn());
388
+ send_super(&sup, _sel, event);
389
+ }
390
+
391
+ fn register_bloom_application_class() {
392
+ if AnyClass::get(c"BloomApplication").is_some() { return; }
393
+
394
+ unsafe {
395
+ let superclass = AnyClass::get(c"UIApplication").unwrap();
396
+ let cls = objc_allocateClassPair(superclass as *const AnyClass, b"BloomApplication\0".as_ptr(), 0);
397
+ if cls.is_null() { return; }
398
+
399
+ class_addMethod(cls, sel!(sendEvent:), bloom_app_send_event as *const c_void, b"v24@0:8@16\0".as_ptr());
400
+
401
+ objc_registerClassPair(cls);
402
+ }
403
+ }
404
+
405
+ /// Window-level sendEvent: override. Intercepts ALL events (keyboard type 4, presses type 3)
406
+ /// and maps them to Bloom key input. Eats keyboard/press events to prevent system dismissal.
407
+ unsafe extern "C" fn bloom_window_send_event(this: *mut c_void, sel: Sel, event: *const AnyObject) {
408
+ let event_type: i64 = msg_send![&*event, type];
409
+
410
+ // Type 3 = UIPresses, Type 4 = keyboard events from simulator
411
+ if event_type == 3 || event_type == 4 {
412
+ static WIN_EVENT_COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
413
+ let count = WIN_EVENT_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
414
+ if count < 10 {
415
+ std::io::Write::write_all(&mut std::io::stderr(),
416
+ format!("[bloom-visionos] window sendEvent type={}\n", event_type).as_bytes()).ok();
417
+ }
418
+
419
+ // For press events, extract key info
420
+ if event_type == 3 {
421
+ let all_presses: *const AnyObject = msg_send![&*event, allPresses];
422
+ if !all_presses.is_null() {
423
+ let enumerator: Retained<AnyObject> = msg_send![&*all_presses, objectEnumerator];
424
+ loop {
425
+ let press: *const AnyObject = msg_send![&*enumerator, nextObject];
426
+ if press.is_null() { break; }
427
+ let phase: i64 = msg_send![&*press, phase];
428
+ let press_type: i64 = {
429
+ let sel_type = Sel::register(c"type");
430
+ let send_i64: unsafe extern "C" fn(*const AnyObject, Sel) -> i64 =
431
+ std::mem::transmute(objc_msgSend as unsafe extern "C" fn());
432
+ send_i64(press, sel_type)
433
+ };
434
+ let down = phase == 0;
435
+ let up = phase == 3 || phase == 4;
436
+ let key = match press_type {
437
+ 0 => Some(256), 1 => Some(257), 2 => Some(258), 3 => Some(259),
438
+ 4 => Some(265), 5 => Some(27), 6 => Some(27),
439
+ 2040 => Some(265), 2041 => Some(27), 2044 => Some(32),
440
+ 2080 => Some(258), 2079 => Some(259), 2081 => Some(257), 2082 => Some(256),
441
+ _ => None,
442
+ };
443
+ if let Some(k) = key {
444
+ if down { pending_key_down(k); }
445
+ if up { pending_key_up(k); }
446
+ }
447
+ if press_type == 4 {
448
+ if down { pending_key_down(32); }
449
+ if up { pending_key_up(32); }
450
+ }
451
+ }
452
+ }
453
+ }
454
+
455
+ // For keyboard events (type 4), call super to dispatch through the
456
+ // responder chain. BloomViewController.pressesBegan will handle the presses
457
+ // and NOT call super, which prevents the system from dismissing the app.
458
+ // (This only works now that the r#type selector bug is fixed.)
459
+ // For type 4 keyboard events, try multiple selectors to extract key info
460
+ if event_type == 4 {
461
+ // Try _key to get the UIKey object
462
+ let responds_key: Bool = msg_send![&*event, respondsToSelector: sel!(_key)];
463
+ if responds_key.as_bool() {
464
+ let key_obj: *const AnyObject = msg_send![&*event, _key];
465
+ if !key_obj.is_null() {
466
+ let responds_keycode: Bool = msg_send![&*key_obj, respondsToSelector: sel!(keyCode)];
467
+ if responds_keycode.as_bool() {
468
+ let keycode: i64 = msg_send![&*key_obj, keyCode];
469
+ let is_down: Bool = msg_send![&*event, _isKeyDown];
470
+ let bloom_key = match keycode {
471
+ 79 => Some(259), 80 => Some(258), 81 => Some(257), 82 => Some(256),
472
+ 40 => Some(265), 41 => Some(27), 44 => Some(32), _ => None,
473
+ };
474
+ if let Some(k) = bloom_key {
475
+ if is_down.as_bool() { pending_key_down(k); }
476
+ else { pending_key_up(k); }
477
+ }
478
+ if keycode == 40 || keycode == 44 {
479
+ if is_down.as_bool() { pending_key_down(32); }
480
+ else { pending_key_up(32); }
481
+ }
482
+ }
483
+ }
484
+ }
485
+ // If _key worked, we're done. If not, fall through to call super
486
+ // so the responder chain (BloomViewController.pressesBegan) handles it.
487
+ if responds_key.as_bool() { return; }
488
+ // Call super for type 4 — dispatches to VC's pressesBegan
489
+ extern "C" { fn objc_msgSendSuper(); }
490
+ #[repr(C)]
491
+ struct Sup2 { receiver: *mut c_void, super_class: *const c_void }
492
+ let sc2 = AnyClass::get(c"UIWindow").unwrap();
493
+ let s2 = Sup2 { receiver: this, super_class: sc2 as *const AnyClass as *const c_void };
494
+ let f2: unsafe extern "C" fn(*const Sup2, Sel, *const AnyObject) =
495
+ std::mem::transmute(objc_msgSendSuper as unsafe extern "C" fn());
496
+ f2(&s2, sel, event);
497
+ return;
498
+ }
499
+
500
+ if false {
501
+ let all_presses: *const AnyObject = msg_send![&*event, allPresses];
502
+ if !all_presses.is_null() {
503
+ let enumerator: Retained<AnyObject> = msg_send![&*all_presses, objectEnumerator];
504
+ loop {
505
+ let press: *const AnyObject = msg_send![&*enumerator, nextObject];
506
+ if press.is_null() { break; }
507
+ let phase: i64 = msg_send![&*press, phase];
508
+ let press_type: i64 = {
509
+ let sel_type = Sel::register(c"type");
510
+ let send_i64: unsafe extern "C" fn(*const AnyObject, Sel) -> i64 =
511
+ std::mem::transmute(objc_msgSend as unsafe extern "C" fn());
512
+ send_i64(press, sel_type)
513
+ };
514
+ let eng_ptr = ENGINE.get().map(|e| e as *const EngineState as *mut EngineState);
515
+ if let Some(eng) = eng_ptr.map(|p| &mut *p) {
516
+ let down = phase == 0;
517
+ let up = phase == 3 || phase == 4;
518
+ // press_type for keyboard keys are large numbers (e.g. 2227)
519
+ // Map common ones: arrows, enter, escape, space
520
+ let key = match press_type {
521
+ 0 => Some(256), // Up arrow (remote)
522
+ 1 => Some(257), // Down arrow (remote)
523
+ 2 => Some(258), // Left arrow (remote)
524
+ 3 => Some(259), // Right arrow (remote)
525
+ 4 => Some(265), // Select (remote) → Enter
526
+ 5 => Some(27), // Menu (remote) → Escape
527
+ 6 => Some(27), // PlayPause → Escape
528
+ 2227 => Some(265), // Keyboard Enter
529
+ 2233 => Some(27), // Keyboard Escape
530
+ 2232 => Some(32), // Keyboard Space
531
+ 2228 => Some(9), // Keyboard Tab
532
+ 2103 => Some(256), // Keyboard Up
533
+ 2105 => Some(257), // Keyboard Down
534
+ 2104 => Some(258), // Keyboard Left
535
+ 2106 => Some(259), // Keyboard Right
536
+ _ => None,
537
+ };
538
+ if let Some(k) = key {
539
+ if down { eng.input.set_key_down(k); }
540
+ if up { eng.input.set_key_up(k); }
541
+ }
542
+ // Select/Enter also maps to Space for jump
543
+ if press_type == 4 || press_type == 2227 {
544
+ if down { eng.input.set_key_down(32); }
545
+ if up { eng.input.set_key_up(32); }
546
+ }
547
+ }
548
+ }
549
+ }
550
+ }
551
+
552
+ return; // Don't call super for type 3 — we extracted keys above
553
+ }
554
+
555
+ // For other events, call super
556
+ extern "C" { fn objc_msgSendSuper(); }
557
+ #[repr(C)]
558
+ struct ObjcSuperCall { receiver: *mut c_void, super_class: *const c_void }
559
+ let superclass = AnyClass::get(c"UIWindow").unwrap();
560
+ let sup = ObjcSuperCall { receiver: this, super_class: superclass as *const AnyClass as *const c_void };
561
+ let send_super: unsafe extern "C" fn(*const ObjcSuperCall, Sel, *const AnyObject) =
562
+ std::mem::transmute(objc_msgSendSuper as unsafe extern "C" fn());
563
+ send_super(&sup, sel, event);
564
+ }
565
+
566
+ fn register_window_class() {
567
+ if AnyClass::get(c"BloomWindow").is_some() { return; }
568
+
569
+ unsafe {
570
+ let superclass = AnyClass::get(c"UIWindow").unwrap();
571
+ let cls = objc_allocateClassPair(superclass as *const AnyClass, b"BloomWindow\0".as_ptr(), 0);
572
+ if cls.is_null() { return; }
573
+
574
+ // Override sendEvent: to intercept ALL events at the window level
575
+ class_addMethod(cls, sel!(sendEvent:), bloom_window_send_event as *const c_void, b"v24@0:8@16\0".as_ptr());
576
+
577
+ // Also override press events for responder chain
578
+ let press_types = b"v32@0:8@16@24\0".as_ptr();
579
+ class_addMethod(cls, sel!(pressesBegan:withEvent:), bloom_presses_began as *const c_void, press_types);
580
+ class_addMethod(cls, sel!(pressesEnded:withEvent:), bloom_presses_ended as *const c_void, press_types);
581
+ class_addMethod(cls, sel!(pressesCancelled:withEvent:), bloom_presses_ended as *const c_void, press_types);
582
+
583
+ objc_registerClassPair(cls);
584
+ }
585
+ }
586
+
587
+ fn register_view_controller_class() {
588
+ if AnyClass::get(c"BloomViewController").is_some() { return; }
589
+
590
+ unsafe {
591
+ // Plain UIViewController subclass — matches what works in the Swift test
592
+ let superclass = AnyClass::get(c"UIViewController").unwrap();
593
+ let cls = objc_allocateClassPair(superclass as *const AnyClass, b"BloomViewController\0".as_ptr(), 0);
594
+ if cls.is_null() { return; }
595
+
596
+ // Override pressesBegan/pressesEnded to capture remote/keyboard events
597
+ let press_types = b"v32@0:8@16@24\0".as_ptr();
598
+ class_addMethod(cls, sel!(pressesBegan:withEvent:), bloom_presses_began as *const c_void, press_types);
599
+ class_addMethod(cls, sel!(pressesEnded:withEvent:), bloom_presses_ended as *const c_void, press_types);
600
+ class_addMethod(cls, sel!(pressesCancelled:withEvent:), bloom_presses_ended as *const c_void, press_types);
601
+
602
+ objc_registerClassPair(cls);
603
+ }
604
+ }
605
+
606
+ fn register_metal_view_class() {
607
+ if AnyClass::get(c"BloomMetalView").is_some() { return; }
608
+
609
+ unsafe {
610
+ let superclass = AnyClass::get(c"UIView").unwrap();
611
+ let cls = objc_allocateClassPair(superclass as *const AnyClass, b"BloomMetalView\0".as_ptr(), 0);
612
+ if cls.is_null() { return; }
613
+
614
+ extern "C" { fn object_getClass(obj: *const c_void) -> *mut AnyClass; }
615
+ let meta = object_getClass(cls as *const c_void);
616
+
617
+ class_addMethod(meta, sel!(layerClass), bloom_layer_class as *const c_void, b"#8@0:8\0".as_ptr());
618
+
619
+ let touch_types = b"v32@0:8@16@24\0".as_ptr();
620
+ class_addMethod(cls, sel!(touchesBegan:withEvent:), bloom_touches_began as *const c_void, touch_types);
621
+ class_addMethod(cls, sel!(touchesMoved:withEvent:), bloom_touches_moved as *const c_void, touch_types);
622
+ class_addMethod(cls, sel!(touchesEnded:withEvent:), bloom_touches_ended as *const c_void, touch_types);
623
+ class_addMethod(cls, sel!(touchesCancelled:withEvent:), bloom_touches_cancelled as *const c_void, touch_types);
624
+
625
+ // tvOS focus engine — view must be focusable to receive remote events
626
+ class_addMethod(cls, sel!(canBecomeFocused), bloom_can_become_focused as *const c_void, b"B8@0:8\0".as_ptr());
627
+ class_addMethod(cls, sel!(canBecomeFirstResponder), bloom_can_become_focused as *const c_void, b"B8@0:8\0".as_ptr());
628
+
629
+ // tvOS press events — Siri Remote physical buttons
630
+ let press_types = b"v32@0:8@16@24\0".as_ptr();
631
+ class_addMethod(cls, sel!(pressesBegan:withEvent:), bloom_presses_began as *const c_void, press_types);
632
+ class_addMethod(cls, sel!(pressesEnded:withEvent:), bloom_presses_ended as *const c_void, press_types);
633
+
634
+ objc_registerClassPair(cls);
635
+ }
636
+ }
637
+
638
+ // ============================================================
639
+ // Scene delegate — creates UIWindow + Metal view + wgpu engine
640
+ // ============================================================
641
+
642
+ unsafe extern "C" fn scene_will_connect(
643
+ _this: *mut c_void,
644
+ _sel: Sel,
645
+ scene: *const AnyObject,
646
+ _session: *const AnyObject,
647
+ _options: *const AnyObject,
648
+ ) {
649
+ let _ = std::fs::write("/tmp/bloom_scene_connect.txt", format!("scene_will_connect called, scene={:?}\n", scene));
650
+ if scene.is_null() { return; }
651
+ std::io::Write::write_all(&mut std::io::stderr(), b"[bloom-visionos] scene_will_connect called\n").ok();
652
+
653
+ // Get screen bounds
654
+ let screen_cls = AnyClass::get(c"UIScreen").unwrap();
655
+ let screen: Retained<AnyObject> = msg_send![screen_cls, mainScreen];
656
+ let bounds: CGRect = msg_send![&*screen, bounds];
657
+ let scale: f64 = msg_send![&*screen, scale];
658
+ let pixel_width = (bounds.size.width * scale) as u32;
659
+ let pixel_height = (bounds.size.height * scale) as u32;
660
+ SCREEN_SCALE = scale;
661
+
662
+ // Create BloomWindow (captures press events) attached to the scene
663
+ let window_cls = AnyClass::get(c"BloomWindow").unwrap();
664
+ let window: Allocated<AnyObject> = msg_send![window_cls, alloc];
665
+ let window: Retained<AnyObject> = msg_send![window, initWithWindowScene: scene];
666
+
667
+ // Use GCEventViewController directly — it prevents the system from
668
+ // intercepting remote/keyboard events when controllerUserInteractionEnabled=NO
669
+ let gc_vc_cls = AnyClass::get(c"GCEventViewController");
670
+ std::io::Write::write_all(&mut std::io::stderr(),
671
+ format!("[bloom-visionos] GCEventViewController available: {}\n", gc_vc_cls.is_some()).as_bytes()).ok();
672
+ let vc_cls = gc_vc_cls.unwrap_or_else(|| AnyClass::get(c"UIViewController").unwrap());
673
+ let vc: Allocated<AnyObject> = msg_send![vc_cls, alloc];
674
+ let vc: Retained<AnyObject> = msg_send![vc, init];
675
+ if gc_vc_cls.is_some() {
676
+ let _: () = msg_send![&*vc, setControllerUserInteractionEnabled: Bool::NO];
677
+ std::io::Write::write_all(&mut std::io::stderr(), b"[bloom-visionos] controllerUserInteractionEnabled = NO\n").ok();
678
+ }
679
+
680
+ // Create BloomMetalView
681
+ let view_cls = AnyClass::get(c"BloomMetalView").unwrap();
682
+ let view: Allocated<AnyObject> = msg_send![view_cls, alloc];
683
+ let view: Retained<AnyObject> = msg_send![view, initWithFrame: bounds];
684
+
685
+ // Set background to black
686
+ let color_cls = AnyClass::get(c"UIColor").unwrap();
687
+ let black: Retained<AnyObject> = msg_send![color_cls, blackColor];
688
+ let _: () = msg_send![&*view, setBackgroundColor: &*black];
689
+
690
+ // Configure CAMetalLayer - set framebufferOnly=NO for screenshot capture
691
+ let layer: Retained<AnyObject> = msg_send![&*view, layer];
692
+ let drawable_size = CGSize { width: pixel_width as f64, height: pixel_height as f64 };
693
+ let _: () = msg_send![&*layer, setDrawableSize: drawable_size];
694
+ let _: () = msg_send![&*layer, setContentsScale: scale];
695
+ let _: () = msg_send![&*layer, setOpaque: Bool::YES];
696
+ let _: () = msg_send![&*layer, setFramebufferOnly: Bool::NO];
697
+ // presentsWithTransaction MUST stay NO (the default). wgpu presents its
698
+ // drawable asynchronously via -presentDrawable: on the command buffer;
699
+ // setting presentsWithTransaction:YES makes CoreAnimation wait for a
700
+ // synchronous CATransaction commit that wgpu never performs, so the layer
701
+ // never displays rendered frames (the screen stays black behind UIKit subviews).
702
+ let _: () = msg_send![&*layer, setPresentsWithTransaction: Bool::NO];
703
+
704
+ // Enable touches & focus
705
+ let _: () = msg_send![&*view, setUserInteractionEnabled: Bool::YES];
706
+ let _: () = msg_send![&*view, setMultipleTouchEnabled: Bool::YES];
707
+
708
+ // Set up window hierarchy
709
+ let _: () = msg_send![&*vc, setView: &*view];
710
+ let _: () = msg_send![&*window, setRootViewController: &*vc];
711
+ let _: () = msg_send![&*window, makeKeyAndVisible];
712
+
713
+ UI_VIEW = Some(view.clone());
714
+ UI_WINDOW = Some(window);
715
+
716
+ // Create wgpu surface and engine on the main thread (like iOS)
717
+ let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
718
+ backends: wgpu::Backends::METAL,
719
+ ..wgpu::InstanceDescriptor::new_without_display_handle()
720
+ });
721
+
722
+ let view_ptr = Retained::as_ptr(&view) as *mut c_void;
723
+ let handle = UiKitWindowHandle::new(
724
+ std::ptr::NonNull::new(view_ptr).unwrap(),
725
+ );
726
+ let raw = RawWindowHandle::UiKit(handle);
727
+ std::io::Write::write_all(&mut std::io::stderr(), b"[bloom-visionos] creating wgpu surface\n").ok();
728
+ let surface = match instance.create_surface_unsafe(wgpu::SurfaceTargetUnsafe::RawHandle {
729
+ raw_display_handle: Some(RawDisplayHandle::UiKit(UiKitDisplayHandle::new())),
730
+ raw_window_handle: raw,
731
+ }) {
732
+ Ok(s) => s,
733
+ Err(e) => panic!("[bloom-visionos] Failed to create wgpu surface: {e}"),
734
+ };
735
+
736
+ let adapter = match pollster_block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
737
+ compatible_surface: Some(&surface),
738
+ power_preference: wgpu::PowerPreference::HighPerformance,
739
+ ..Default::default()
740
+ })) {
741
+ Ok(a) => a,
742
+ Err(_) => panic!("[bloom-visionos] No GPU adapter found"),
743
+ };
744
+
745
+ // Ticket 007b: HW ray-query on RT-capable tvOS hardware (A13+).
746
+ let supported = adapter.features();
747
+ let force_sw_gi = std::env::var("BLOOM_FORCE_SW_GI")
748
+ .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
749
+ .unwrap_or(false);
750
+ let rt_mask = wgpu::Features::EXPERIMENTAL_RAY_QUERY;
751
+ let mut required_features = wgpu::Features::empty();
752
+ // Ticket 011: request TIMESTAMP_QUERY when supported so the profiler
753
+ // can record GPU timings. Optional — profiler falls back to CPU-only
754
+ // when the adapter doesn't grant it.
755
+ if supported.contains(wgpu::Features::TIMESTAMP_QUERY) {
756
+ required_features |= wgpu::Features::TIMESTAMP_QUERY;
757
+ }
758
+ // Cooked BC7 textures (bloom-cook) upload compressed when the
759
+ // adapter has BC support; without it they CPU-decode at load.
760
+ if supported.contains(wgpu::Features::TEXTURE_COMPRESSION_BC) {
761
+ required_features |= wgpu::Features::TEXTURE_COMPRESSION_BC;
762
+ }
763
+ if !force_sw_gi && supported.contains(rt_mask) {
764
+ required_features |= rt_mask;
765
+ }
766
+ let experimental_features = if required_features.intersects(rt_mask) {
767
+ unsafe { wgpu::ExperimentalFeatures::enabled() }
768
+ } else {
769
+ wgpu::ExperimentalFeatures::disabled()
770
+ };
771
+ // Base the requested limits on what the adapter actually advertises so we
772
+ // never ask for more than the backend can grant. The tvOS/iOS *simulators*
773
+ // cap several limits below wgpu's desktop default() — notably
774
+ // max_inter_stage_shader_variables (15 vs 16) — which makes request_device
775
+ // fail with LimitsExceeded. On real Apple TV hardware adapter.limits()
776
+ // meets or exceeds default(), so behaviour there is unchanged.
777
+ let adapter_limits = adapter.limits();
778
+ let mut required_limits = wgpu::Limits::default();
779
+ required_limits.max_inter_stage_shader_variables = required_limits
780
+ .max_inter_stage_shader_variables
781
+ .min(adapter_limits.max_inter_stage_shader_variables);
782
+ if required_features.intersects(rt_mask) {
783
+ required_limits = required_limits
784
+ .using_minimum_supported_acceleration_structure_values();
785
+ }
786
+ let (device, queue) = match pollster_block_on(adapter.request_device(
787
+ &wgpu::DeviceDescriptor {
788
+ label: Some("bloom_device"),
789
+ required_features,
790
+ required_limits,
791
+ experimental_features,
792
+ ..Default::default()
793
+ },
794
+ )) {
795
+ Ok(dq) => dq,
796
+ Err(e) => panic!("[bloom-visionos] Failed to create device: {e}"),
797
+ };
798
+
799
+ let surface_caps = surface.get_capabilities(&adapter);
800
+ // Use non-sRGB format to match game's sRGB color space (colors are specified as sRGB 0-255)
801
+ let format = surface_caps.formats.iter()
802
+ .find(|f| !f.is_srgb()).copied()
803
+ .unwrap_or(surface_caps.formats[0]);
804
+
805
+ let surface_config = wgpu::SurfaceConfiguration {
806
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
807
+ format,
808
+ width: pixel_width,
809
+ height: pixel_height,
810
+ present_mode: wgpu::PresentMode::Fifo,
811
+ alpha_mode: surface_caps.alpha_modes[0],
812
+ view_formats: vec![],
813
+ desired_maximum_frame_latency: 2,
814
+ };
815
+ surface.configure(&device, &surface_config);
816
+
817
+ let renderer = Renderer::new(device, queue, surface, surface_config, pixel_width, pixel_height);
818
+ let _ = ENGINE.set(EngineState::new(renderer));
819
+ std::io::Write::write_all(&mut std::io::stderr(), b"[bloom-visionos] ENGINE created on main thread\n").ok();
820
+ }
821
+
822
+ /// Called by the perry runtime's main() before UIApplicationMain to register
823
+ /// ObjC classes needed for the scene lifecycle.
824
+ #[no_mangle]
825
+ unsafe extern "C" fn configuration_for_connecting_scene(
826
+ _this: *mut c_void, _sel: Sel,
827
+ _app: *const AnyObject,
828
+ scene_session: *const AnyObject,
829
+ _options: *const AnyObject,
830
+ ) -> *const AnyObject {
831
+ let _ = std::fs::write("/tmp/bloom_config_scene.txt", "configurationForConnecting called\n");
832
+ // Get the session's role
833
+ let role: *const AnyObject = msg_send![&*scene_session, role];
834
+ // Create UISceneConfiguration
835
+ let config_cls = AnyClass::get(c"UISceneConfiguration").unwrap();
836
+ let ns_cls = AnyClass::get(c"NSString").unwrap();
837
+ let name_str: Retained<AnyObject> = msg_send![ns_cls, stringWithUTF8String: b"Default Configuration\0".as_ptr()];
838
+ let config: Allocated<AnyObject> = msg_send![config_cls, alloc];
839
+ let config: Retained<AnyObject> = msg_send![config, initWithName: &*name_str sessionRole: role];
840
+ // Use PerryGameLoopAppDelegate as scene delegate (it has scene:willConnectToSession: added)
841
+ let delegate_cls = AnyClass::get(c"PerryGameLoopAppDelegate").unwrap();
842
+ let _: () = msg_send![&*config, setDelegateClass: delegate_cls];
843
+ std::io::Write::write_all(&mut std::io::stderr(), b"[bloom-visionos] returning scene config with delegate\n").ok();
844
+ // Leak the config — UIKit retains it. We can't use autorelease pool from extern C.
845
+ let ptr = Retained::as_ptr(&config);
846
+ std::mem::forget(config);
847
+ ptr
848
+ }
849
+
850
+ #[no_mangle]
851
+ pub unsafe extern "C" fn perry_register_native_classes() {
852
+ let _ = std::fs::write("/tmp/bloom_register_classes.txt", "perry_register_native_classes called\n");
853
+ register_bloom_application_class();
854
+ register_metal_view_class();
855
+ register_window_class();
856
+ register_view_controller_class();
857
+ register_scene_delegate();
858
+
859
+ // Add press event handlers AND configurationForConnectingSceneSession to the app delegate
860
+ if let Some(app_delegate_cls) = AnyClass::get(c"PerryGameLoopAppDelegate") {
861
+ let press_types = b"v32@0:8@16@24\0".as_ptr();
862
+ class_addMethod(
863
+ app_delegate_cls as *const AnyClass as *mut AnyClass,
864
+ sel!(pressesBegan:withEvent:),
865
+ bloom_presses_began as *const c_void,
866
+ press_types,
867
+ );
868
+ class_addMethod(
869
+ app_delegate_cls as *const AnyClass as *mut AnyClass,
870
+ sel!(pressesEnded:withEvent:),
871
+ bloom_presses_ended as *const c_void,
872
+ press_types,
873
+ );
874
+ let sel = Sel::register(c"application:configurationForConnectingSceneSession:options:");
875
+ let types = b"@48@0:8@16@24@32\0".as_ptr();
876
+ class_addMethod(
877
+ app_delegate_cls as *const AnyClass as *mut AnyClass,
878
+ sel,
879
+ configuration_for_connecting_scene as *const c_void,
880
+ types,
881
+ );
882
+
883
+ // Also add scene:willConnectToSession:connectionOptions: to the app delegate
884
+ // so it can act as its own scene delegate (PerrySceneDelegate dispatch never fires)
885
+ let scene_sel = Sel::register(c"scene:willConnectToSession:connectionOptions:");
886
+ let scene_types = b"v48@0:8@16@24@32\0".as_ptr();
887
+ class_addMethod(
888
+ app_delegate_cls as *const AnyClass as *mut AnyClass,
889
+ scene_sel,
890
+ scene_will_connect as *const c_void,
891
+ scene_types,
892
+ );
893
+
894
+ // Add UIWindowSceneDelegate protocol to app delegate
895
+ extern "C" { fn objc_getProtocol(name: *const u8) -> *const c_void; }
896
+ extern "C" { fn class_addProtocol(cls: *mut c_void, protocol: *const c_void) -> bool; }
897
+ let protocol = objc_getProtocol(b"UIWindowSceneDelegate\0".as_ptr());
898
+ if !protocol.is_null() {
899
+ class_addProtocol(app_delegate_cls as *const AnyClass as *mut c_void, protocol);
900
+ }
901
+ }
902
+ std::io::Write::write_all(&mut std::io::stderr(), b"[bloom-visionos] classes registered, scene delegate ready\n").ok();
903
+ }
904
+
905
+ /// Called by the runtime's scene delegate when the UIWindowScene connects.
906
+ /// This runs on the main thread — safe for all UIKit operations.
907
+ #[no_mangle]
908
+ unsafe extern "C" fn deferred_init(_ctx: *mut c_void) {
909
+ let _ = std::fs::write("/tmp/bloom_deferred_init.txt", "deferred_init called\n");
910
+
911
+ // Find the connected scene
912
+ let app_cls = AnyClass::get(c"UIApplication").unwrap();
913
+ let app: *const AnyObject = msg_send![app_cls, sharedApplication];
914
+ let scenes: *const AnyObject = msg_send![&*app, connectedScenes];
915
+ let count: usize = msg_send![&*scenes, count];
916
+ if count == 0 {
917
+ let _ = std::fs::write("/tmp/bloom_deferred_2.txt", "scenes=0, retrying in 500ms\n");
918
+ // Retry after a delay
919
+ extern "C" {
920
+ static _dispatch_main_q: c_void;
921
+ fn dispatch_after_f(when: u64, queue: *const c_void, context: *mut c_void, work: unsafe extern "C" fn(*mut c_void));
922
+ fn dispatch_time(when: u64, delta: i64) -> u64;
923
+ }
924
+ let when = dispatch_time(0, 500_000_000); // 500ms
925
+ dispatch_after_f(when, &_dispatch_main_q as *const _, std::ptr::null_mut(), deferred_init);
926
+ return;
927
+ }
928
+
929
+ let scene: Retained<AnyObject> = msg_send![&*scenes, anyObject];
930
+ // Log the scene class name for debugging
931
+ extern "C" { fn class_getName(cls: *const c_void) -> *const u8; }
932
+ let scene_class: *const c_void = msg_send![&*scene, class];
933
+ let scene_class_name = std::ffi::CStr::from_ptr(class_getName(scene_class) as *const i8).to_str().unwrap_or("?");
934
+ let scene_state: i64 = msg_send![&*scene, activationState];
935
+ let _ = std::fs::write("/tmp/bloom_deferred_2.txt", format!("scenes={}\nclass={}\nactivationState={}\n", count, scene_class_name, scene_state));
936
+
937
+ // Get screen dimensions
938
+ let screen_cls = AnyClass::get(c"UIScreen").unwrap();
939
+ let screen: Retained<AnyObject> = msg_send![screen_cls, mainScreen];
940
+ let bounds: CGRect = msg_send![&*screen, bounds];
941
+ let scale: f64 = msg_send![&*screen, scale];
942
+ let pixel_width = (bounds.size.width * scale) as u32;
943
+ let pixel_height = (bounds.size.height * scale) as u32;
944
+ SCREEN_SCALE = scale;
945
+
946
+ // Create window WITH the scene (required on tvOS for visibility)
947
+ let window_cls = AnyClass::get(c"BloomWindow").unwrap();
948
+ let w: Allocated<AnyObject> = msg_send![window_cls, alloc];
949
+ let window: Retained<AnyObject> = msg_send![w, initWithWindowScene: &*scene];
950
+
951
+ // Create view controller
952
+ let gc_vc_cls = AnyClass::get(c"GCEventViewController");
953
+ let vc_cls = gc_vc_cls.unwrap_or_else(|| AnyClass::get(c"UIViewController").unwrap());
954
+ let vc: Allocated<AnyObject> = msg_send![vc_cls, alloc];
955
+ let vc: Retained<AnyObject> = msg_send![vc, init];
956
+ if gc_vc_cls.is_some() {
957
+ let _: () = msg_send![&*vc, setControllerUserInteractionEnabled: Bool::NO];
958
+ }
959
+
960
+ // Create BloomMetalView
961
+ let view_cls = AnyClass::get(c"BloomMetalView").unwrap();
962
+ let v: Allocated<AnyObject> = msg_send![view_cls, alloc];
963
+ let view: Retained<AnyObject> = msg_send![v, initWithFrame: bounds];
964
+
965
+ let color_cls = AnyClass::get(c"UIColor").unwrap();
966
+ let black: Retained<AnyObject> = msg_send![color_cls, blackColor];
967
+ let _: () = msg_send![&*view, setBackgroundColor: &*black];
968
+ let _: () = msg_send![&*view, setUserInteractionEnabled: Bool::YES];
969
+
970
+ // Configure CAMetalLayer
971
+ let layer: Retained<AnyObject> = msg_send![&*view, layer];
972
+ let drawable_size = CGSize { width: pixel_width as f64, height: pixel_height as f64 };
973
+ let _: () = msg_send![&*layer, setDrawableSize: drawable_size];
974
+ let _: () = msg_send![&*layer, setContentsScale: scale];
975
+ let _: () = msg_send![&*layer, setOpaque: Bool::YES];
976
+ let _: () = msg_send![&*layer, setFramebufferOnly: Bool::NO];
977
+ // presentsWithTransaction MUST stay NO (the default). wgpu presents its
978
+ // drawable asynchronously via -presentDrawable: on the command buffer;
979
+ // setting presentsWithTransaction:YES makes CoreAnimation wait for a
980
+ // synchronous CATransaction commit that wgpu never performs, so the layer
981
+ // never displays rendered frames (the screen stays black behind UIKit subviews).
982
+ let _: () = msg_send![&*layer, setPresentsWithTransaction: Bool::NO];
983
+
984
+ // Set up window hierarchy
985
+ let _: () = msg_send![&*vc, setView: &*view];
986
+ let _: () = msg_send![&*window, setRootViewController: &*vc];
987
+ let _: () = msg_send![&*window, makeKeyAndVisible];
988
+
989
+ UI_VIEW = Some(view.clone());
990
+ UI_WINDOW = Some(window.clone());
991
+
992
+ // Verify window state
993
+ let is_key: Bool = msg_send![&*window, isKeyWindow];
994
+ let is_hidden: Bool = msg_send![&*window, isHidden];
995
+ let win_scene: *const AnyObject = msg_send![&*window, windowScene];
996
+ let win_frame: CGRect = msg_send![&*window, frame];
997
+ let win_alpha: f64 = msg_send![&*window, alpha];
998
+ let root_vc: *const AnyObject = msg_send![&*window, rootViewController];
999
+ let vc_view: *const AnyObject = if !root_vc.is_null() { msg_send![&*root_vc, view] } else { std::ptr::null() };
1000
+
1001
+ // Check scene's windows
1002
+ let scene_windows: *const AnyObject = msg_send![&*scene, windows];
1003
+ let scene_win_count: usize = msg_send![&*scene_windows, count];
1004
+
1005
+ let debug = format!(
1006
+ "window+view created with scene, {}x{}\n\
1007
+ isKey={} isHidden={} alpha={}\n\
1008
+ windowScene={:?} (expected={:?})\n\
1009
+ frame=({},{},{},{})\n\
1010
+ rootVC={:?} vcView={:?}\n\
1011
+ scene.windows.count={}\n",
1012
+ pixel_width, pixel_height,
1013
+ is_key.as_bool(), is_hidden.as_bool(), win_alpha,
1014
+ win_scene, Retained::as_ptr(&scene),
1015
+ win_frame.origin.x, win_frame.origin.y, win_frame.size.width, win_frame.size.height,
1016
+ root_vc, vc_view,
1017
+ scene_win_count,
1018
+ );
1019
+ let _ = std::fs::write("/tmp/bloom_deferred_3.txt", &debug);
1020
+
1021
+ // Create wgpu engine using CAMetalLayer
1022
+ let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
1023
+ backends: wgpu::Backends::METAL,
1024
+ ..wgpu::InstanceDescriptor::new_without_display_handle()
1025
+ });
1026
+
1027
+ let layer_ptr = Retained::as_ptr(&layer) as *mut c_void;
1028
+ let surface = instance.create_surface_unsafe(
1029
+ wgpu::SurfaceTargetUnsafe::CoreAnimationLayer(layer_ptr)
1030
+ ).expect("[bloom-visionos] Failed to create wgpu surface");
1031
+
1032
+ let adapter = pollster_block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
1033
+ compatible_surface: Some(&surface),
1034
+ power_preference: wgpu::PowerPreference::HighPerformance,
1035
+ ..Default::default()
1036
+ })).expect("[bloom-visionos] No GPU adapter found");
1037
+
1038
+ // Ticket 007b: HW ray-query on RT-capable tvOS hardware (A13+).
1039
+ let supported = adapter.features();
1040
+ let force_sw_gi = std::env::var("BLOOM_FORCE_SW_GI")
1041
+ .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
1042
+ .unwrap_or(false);
1043
+ let rt_mask = wgpu::Features::EXPERIMENTAL_RAY_QUERY;
1044
+ let mut required_features = wgpu::Features::empty();
1045
+ // Ticket 011: request TIMESTAMP_QUERY when supported so the profiler
1046
+ // can record GPU timings. Optional — profiler falls back to CPU-only
1047
+ // when the adapter doesn't grant it.
1048
+ if supported.contains(wgpu::Features::TIMESTAMP_QUERY) {
1049
+ required_features |= wgpu::Features::TIMESTAMP_QUERY;
1050
+ }
1051
+ // Cooked BC7 textures (bloom-cook) upload compressed when the
1052
+ // adapter has BC support; without it they CPU-decode at load.
1053
+ if supported.contains(wgpu::Features::TEXTURE_COMPRESSION_BC) {
1054
+ required_features |= wgpu::Features::TEXTURE_COMPRESSION_BC;
1055
+ }
1056
+ if !force_sw_gi && supported.contains(rt_mask) {
1057
+ required_features |= rt_mask;
1058
+ }
1059
+ let experimental_features = if required_features.intersects(rt_mask) {
1060
+ unsafe { wgpu::ExperimentalFeatures::enabled() }
1061
+ } else {
1062
+ wgpu::ExperimentalFeatures::disabled()
1063
+ };
1064
+ // Base the requested limits on what the adapter actually advertises so we
1065
+ // never ask for more than the backend can grant. The tvOS/iOS *simulators*
1066
+ // cap several limits below wgpu's desktop default() — notably
1067
+ // max_inter_stage_shader_variables (15 vs 16) — which makes request_device
1068
+ // fail with LimitsExceeded. On real Apple TV hardware adapter.limits()
1069
+ // meets or exceeds default(), so behaviour there is unchanged.
1070
+ let adapter_limits = adapter.limits();
1071
+ let mut required_limits = wgpu::Limits::default();
1072
+ required_limits.max_inter_stage_shader_variables = required_limits
1073
+ .max_inter_stage_shader_variables
1074
+ .min(adapter_limits.max_inter_stage_shader_variables);
1075
+ if required_features.intersects(rt_mask) {
1076
+ required_limits = required_limits
1077
+ .using_minimum_supported_acceleration_structure_values();
1078
+ }
1079
+ let (device, queue) = pollster_block_on(adapter.request_device(
1080
+ &wgpu::DeviceDescriptor {
1081
+ label: Some("bloom_device"),
1082
+ required_features,
1083
+ required_limits,
1084
+ experimental_features,
1085
+ ..Default::default()
1086
+ },
1087
+ )).expect("[bloom-visionos] Failed to create device");
1088
+
1089
+ let surface_caps = surface.get_capabilities(&adapter);
1090
+ let format = surface_caps.formats.iter()
1091
+ .find(|f| !f.is_srgb()).copied()
1092
+ .unwrap_or(surface_caps.formats[0]);
1093
+
1094
+ let surface_config = wgpu::SurfaceConfiguration {
1095
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
1096
+ format,
1097
+ width: pixel_width,
1098
+ height: pixel_height,
1099
+ present_mode: wgpu::PresentMode::Fifo,
1100
+ alpha_mode: surface_caps.alpha_modes[0],
1101
+ view_formats: vec![],
1102
+ desired_maximum_frame_latency: 2,
1103
+ };
1104
+ surface.configure(&device, &surface_config);
1105
+
1106
+ let renderer = Renderer::new(device, queue, surface, surface_config, pixel_width, pixel_height);
1107
+ let _ = ENGINE.set(EngineState::new(renderer));
1108
+ let _ = std::fs::write("/tmp/bloom_tvos_debug.txt", format!("ENGINE created\nformat={:?}\nsize={}x{}\n", format, pixel_width, pixel_height));
1109
+ }
1110
+
1111
+ #[no_mangle]
1112
+ pub unsafe extern "C" fn perry_scene_will_connect(scene: *const c_void) {
1113
+ std::io::Write::write_all(&mut std::io::stderr(), format!("[bloom-visionos] perry_scene_will_connect scene={:?}\n", scene).as_bytes()).ok();
1114
+ // When scene is null (called from didFinishLaunchingWithOptions), create the
1115
+ // window synchronously so UIKit knows we handle events. Then dispatch async
1116
+ // to attach to the scene (needed for Metal rendering).
1117
+ if scene.is_null() {
1118
+ // On tvOS, windows MUST be attached to a UIWindowScene to be visible.
1119
+ // Dispatch deferred_init with a delay so the scene is fully connected.
1120
+ extern "C" {
1121
+ static _dispatch_main_q: c_void;
1122
+ fn dispatch_after_f(when: u64, queue: *const c_void, context: *mut c_void, work: unsafe extern "C" fn(*mut c_void));
1123
+ fn dispatch_time(when: u64, delta: i64) -> u64;
1124
+ }
1125
+ let when = dispatch_time(0, 500_000_000); // 500ms delay
1126
+ dispatch_after_f(when, &_dispatch_main_q as *const _, std::ptr::null_mut(), deferred_init);
1127
+ return;
1128
+ }
1129
+
1130
+ let screen_cls = AnyClass::get(c"UIScreen").expect("[bloom-visionos] UIScreen class not found");
1131
+ let screen: Retained<AnyObject> = msg_send![screen_cls, mainScreen];
1132
+ let bounds: CGRect = msg_send![&*screen, bounds];
1133
+ let scale: f64 = msg_send![&*screen, scale];
1134
+ eprintln!("[bloom-visionos] screen bounds: {}x{}, scale={}", bounds.size.width, bounds.size.height, scale);
1135
+
1136
+ let pixel_width = (bounds.size.width * scale) as u32;
1137
+ let pixel_height = (bounds.size.height * scale) as u32;
1138
+
1139
+ // Store scale for touch coordinate conversion (points → pixels)
1140
+ SCREEN_SCALE = scale;
1141
+
1142
+ // Create BloomWindow — attached to scene if available, otherwise plain
1143
+ let window_cls = AnyClass::get(c"BloomWindow").unwrap();
1144
+ let window: Retained<AnyObject> = if !scene.is_null() {
1145
+ let w: Allocated<AnyObject> = msg_send![window_cls, alloc];
1146
+ msg_send![w, initWithWindowScene: scene as *const AnyObject]
1147
+ } else {
1148
+ let w: Allocated<AnyObject> = msg_send![window_cls, alloc];
1149
+ msg_send![w, initWithFrame: bounds]
1150
+ };
1151
+
1152
+ // Use GCEventViewController to prevent system from intercepting remote events
1153
+ let gc_vc_cls = AnyClass::get(c"GCEventViewController");
1154
+ std::io::Write::write_all(&mut std::io::stderr(),
1155
+ format!("[bloom-visionos] GCEventViewController available: {}\n", gc_vc_cls.is_some()).as_bytes()).ok();
1156
+ let vc_cls = gc_vc_cls.unwrap_or_else(|| AnyClass::get(c"UIViewController").unwrap());
1157
+ let vc: Allocated<AnyObject> = msg_send![vc_cls, alloc];
1158
+ let vc: Retained<AnyObject> = msg_send![vc, init];
1159
+ if gc_vc_cls.is_some() {
1160
+ let _: () = msg_send![&*vc, setControllerUserInteractionEnabled: Bool::NO];
1161
+ std::io::Write::write_all(&mut std::io::stderr(), b"[bloom-visionos] controllerUserInteractionEnabled = NO\n").ok();
1162
+ }
1163
+
1164
+ // Create BloomMetalView
1165
+ eprintln!("[bloom-visionos] creating BloomMetalView");
1166
+ let view_cls = AnyClass::get(c"BloomMetalView").expect("[bloom-visionos] BloomMetalView class not found");
1167
+ let view: Allocated<AnyObject> = msg_send![view_cls, alloc];
1168
+ let view: Retained<AnyObject> = msg_send![view, initWithFrame: bounds];
1169
+
1170
+ // Set background to black
1171
+ let color_cls = AnyClass::get(c"UIColor").unwrap();
1172
+ let black: Retained<AnyObject> = msg_send![color_cls, blackColor];
1173
+ let _: () = msg_send![&*view, setBackgroundColor: &*black];
1174
+
1175
+ // Configure CAMetalLayer
1176
+ let layer: Retained<AnyObject> = msg_send![&*view, layer];
1177
+ let drawable_size = CGSize { width: pixel_width as f64, height: pixel_height as f64 };
1178
+ let _: () = msg_send![&*layer, setDrawableSize: drawable_size];
1179
+ let _: () = msg_send![&*layer, setContentsScale: scale];
1180
+ let _: () = msg_send![&*layer, setOpaque: Bool::YES];
1181
+
1182
+ // Enable touches
1183
+ let _: () = msg_send![&*view, setUserInteractionEnabled: Bool::YES];
1184
+ let _: () = msg_send![&*view, setMultipleTouchEnabled: Bool::YES];
1185
+
1186
+ // Set up window hierarchy
1187
+ let _: () = msg_send![&*vc, setView: &*view];
1188
+ let _: () = msg_send![&*window, setRootViewController: &*vc];
1189
+ let _: () = msg_send![&*window, makeKeyAndVisible];
1190
+
1191
+ // Store references
1192
+ UI_VIEW = Some(view.clone());
1193
+ UI_WINDOW = Some(window);
1194
+ // Add a transparent focusable button so the tvOS focus engine has something to focus
1195
+ // Without a focused element, tvOS suspends the app on any remote button press
1196
+ let btn_cls = AnyClass::get(c"UIButton").unwrap();
1197
+ let btn: Retained<AnyObject> = msg_send![btn_cls, buttonWithType: 0i64]; // UIButtonTypeCustom
1198
+ let _: () = msg_send![&*btn, setFrame: bounds];
1199
+ let _: () = msg_send![&*btn, setAlpha: 0.0f64]; // fully transparent
1200
+ let _: () = msg_send![&*view, addSubview: &*btn];
1201
+
1202
+ // Add a menu gesture recognizer to prevent the system from dismissing on Menu press
1203
+ let tap_cls = AnyClass::get(c"UITapGestureRecognizer").unwrap();
1204
+ let menu_tap: Allocated<AnyObject> = msg_send![tap_cls, alloc];
1205
+ let menu_tap: Retained<AnyObject> = msg_send![menu_tap, initWithTarget: std::ptr::null::<AnyObject>() action: std::ptr::null::<c_void>()];
1206
+ // allowedPressTypes = @[@(UIPressTypeMenu)] = @[@5]
1207
+ let num_cls = AnyClass::get(c"NSNumber").unwrap();
1208
+ let menu_num: Retained<AnyObject> = msg_send![num_cls, numberWithInteger: 5i64];
1209
+ let arr_cls = AnyClass::get(c"NSArray").unwrap();
1210
+ let press_types_arr: Retained<AnyObject> = msg_send![arr_cls, arrayWithObject: &*menu_num];
1211
+ let _: () = msg_send![&*menu_tap, setAllowedPressTypes: &*press_types_arr];
1212
+ let _: () = msg_send![&*view, addGestureRecognizer: &*menu_tap];
1213
+
1214
+ // Trigger focus
1215
+ let _: () = msg_send![&*vc, setNeedsFocusUpdate];
1216
+ let _: () = msg_send![&*vc, updateFocusIfNeeded];
1217
+ let _: () = msg_send![&*view, becomeFirstResponder];
1218
+ let is_focused: Bool = msg_send![&*view, isFocused];
1219
+ std::io::Write::write_all(&mut std::io::stderr(),
1220
+ format!("[bloom-visionos] view.isFocused={}\n", is_focused.as_bool()).as_bytes()).ok();
1221
+ // Verify GCEventViewController state
1222
+ {
1223
+ extern "C" { fn class_getName(cls: *const c_void) -> *const u8; }
1224
+ let vc_class: *const c_void = msg_send![&*vc, class];
1225
+ let vc_name = std::ffi::CStr::from_ptr(class_getName(vc_class) as *const i8).to_str().unwrap_or("?");
1226
+ // Check if responds to controllerUserInteractionEnabled
1227
+ let responds: Bool = msg_send![&*vc, respondsToSelector: sel!(controllerUserInteractionEnabled)];
1228
+ let ctrl_ui: Bool = if responds.as_bool() { msg_send![&*vc, controllerUserInteractionEnabled] } else { Bool::NO };
1229
+ std::io::Write::write_all(&mut std::io::stderr(),
1230
+ format!("[bloom-visionos] rootVC class={}, respondsToControllerUI={}, controllerUserInteractionEnabled={}\n",
1231
+ vc_name, responds.as_bool(), ctrl_ui.as_bool()).as_bytes()).ok();
1232
+ }
1233
+ // Check window state
1234
+ {
1235
+ let app_cls2 = AnyClass::get(c"UIApplication").unwrap();
1236
+ let app2: *const AnyObject = msg_send![app_cls2, sharedApplication];
1237
+ let key_win: *const AnyObject = msg_send![&*app2, keyWindow];
1238
+ let is_key = UI_WINDOW.as_ref().map(|w| Retained::as_ptr(w) as *const AnyObject == key_win).unwrap_or(false);
1239
+ // Count all windows
1240
+ let windows: *const AnyObject = msg_send![&*app2, windows];
1241
+ let win_count: usize = msg_send![&*windows, count];
1242
+ std::io::Write::write_all(&mut std::io::stderr(),
1243
+ format!("[bloom-visionos] windows={}, keyWindow==ours={}\n", win_count, is_key).as_bytes()).ok();
1244
+ }
1245
+
1246
+ eprintln!("[bloom-visionos] window hierarchy set up, signaling game thread");
1247
+ // Store the layer pointer and screen dimensions for the game thread to create wgpu
1248
+ SCENE_PTR.store(Retained::as_ptr(&layer) as u64, std::sync::atomic::Ordering::Release);
1249
+ // Store dimensions packed into u64
1250
+ SCREEN_DIMS.store(((pixel_width as u64) << 32) | (pixel_height as u64), std::sync::atomic::Ordering::Release);
1251
+ }
1252
+
1253
+ fn register_scene_delegate() {
1254
+ if AnyClass::get(c"PerrySceneDelegate").is_some() { return; }
1255
+
1256
+ unsafe {
1257
+ let superclass = AnyClass::get(c"UIResponder").unwrap();
1258
+ let cls = objc_allocateClassPair(superclass as *const AnyClass, b"PerrySceneDelegate\0".as_ptr(), 0);
1259
+ if cls.is_null() { return; }
1260
+
1261
+ // scene:willConnectToSession:connectionOptions:
1262
+ let sel = Sel::register(c"scene:willConnectToSession:connectionOptions:");
1263
+ let types = b"v48@0:8@16@24@32\0".as_ptr();
1264
+ class_addMethod(cls, sel, scene_will_connect as *const c_void, types);
1265
+
1266
+ // Add UIWindowSceneDelegate protocol
1267
+ extern "C" { fn objc_getProtocol(name: *const u8) -> *const c_void; }
1268
+ let protocol = objc_getProtocol(b"UIWindowSceneDelegate\0".as_ptr());
1269
+ if !protocol.is_null() {
1270
+ extern "C" { fn class_addProtocol(cls: *mut AnyClass, protocol: *const c_void) -> bool; }
1271
+ class_addProtocol(cls, protocol);
1272
+ }
1273
+
1274
+ objc_registerClassPair(cls);
1275
+ }
1276
+ }
1277
+
1278
+ // ============================================================
1279
+ // Minimal pollster
1280
+ // ============================================================
1281
+
1282
+ fn pollster_block_on<F: std::future::Future>(future: F) -> F::Output {
1283
+ use std::task::{Context, Poll, Wake, Waker};
1284
+ use std::pin::Pin;
1285
+ use std::sync::Arc;
1286
+ struct NoopWaker;
1287
+ impl Wake for NoopWaker { fn wake(self: Arc<Self>) {} }
1288
+ let waker = Waker::from(Arc::new(NoopWaker));
1289
+ let mut cx = Context::from_waker(&waker);
1290
+ let mut future = unsafe { Pin::new_unchecked(Box::new(future)) };
1291
+ loop {
1292
+ match future.as_mut().poll(&mut cx) {
1293
+ Poll::Ready(result) => return result,
1294
+ Poll::Pending => {
1295
+ pump_run_loop(0.001);
1296
+ }
1297
+ }
1298
+ }
1299
+ }
1300
+
1301
+ // ============================================================
1302
+ // GCController — Siri Remote and game controller monitoring
1303
+ // ============================================================
1304
+
1305
+ /// Poll connected game controllers and feed their state into the engine input system.
1306
+ /// Called once during init and also from bloom_begin_drawing to poll controller state.
1307
+ fn poll_game_controllers() {
1308
+ unsafe {
1309
+ let gc_cls = match AnyClass::get(c"GCController") {
1310
+ Some(c) => c,
1311
+ None => return,
1312
+ };
1313
+ let controllers: Retained<AnyObject> = msg_send![gc_cls, controllers];
1314
+ let count: usize = msg_send![&*controllers, count];
1315
+ if count == 0 { return; }
1316
+
1317
+ // Use the first connected controller
1318
+ let controller: Retained<AnyObject> = msg_send![&*controllers, objectAtIndex: 0usize];
1319
+
1320
+ // Try extended gamepad profile first (MFi, PS, Xbox controllers)
1321
+ let extended: *const AnyObject = msg_send![&*controller, extendedGamepad];
1322
+ if !extended.is_null() {
1323
+ if let Some(eng) = ENGINE.get_mut() {
1324
+ eng.input.gamepad_available = true;
1325
+
1326
+ // Left thumbstick
1327
+ let left_stick: Retained<AnyObject> = msg_send![&*extended, leftThumbstick];
1328
+ let lx: f64 = msg_send![&*left_stick, xAxis_value];
1329
+ let ly: f64 = msg_send![&*left_stick, yAxis_value];
1330
+ eng.input.set_gamepad_axis(0, lx as f32);
1331
+ eng.input.set_gamepad_axis(1, -ly as f32); // Invert Y
1332
+
1333
+ // Right thumbstick
1334
+ let right_stick: Retained<AnyObject> = msg_send![&*extended, rightThumbstick];
1335
+ let rx: f64 = msg_send![&*right_stick, xAxis_value];
1336
+ let ry: f64 = msg_send![&*right_stick, yAxis_value];
1337
+ eng.input.set_gamepad_axis(2, rx as f32);
1338
+ eng.input.set_gamepad_axis(3, -ry as f32);
1339
+
1340
+ // Buttons: A(0), B(1), X(2), Y(3)
1341
+ let btn_a: Retained<AnyObject> = msg_send![&*extended, buttonA];
1342
+ let btn_b: Retained<AnyObject> = msg_send![&*extended, buttonB];
1343
+ let btn_x: Retained<AnyObject> = msg_send![&*extended, buttonX];
1344
+ let btn_y: Retained<AnyObject> = msg_send![&*extended, buttonY];
1345
+ let a_pressed: Bool = msg_send![&*btn_a, isPressed];
1346
+ let b_pressed: Bool = msg_send![&*btn_b, isPressed];
1347
+ let x_pressed: Bool = msg_send![&*btn_x, isPressed];
1348
+ let y_pressed: Bool = msg_send![&*btn_y, isPressed];
1349
+ if a_pressed.as_bool() { eng.input.set_gamepad_button_down(0); }
1350
+ if b_pressed.as_bool() { eng.input.set_gamepad_button_down(1); }
1351
+ if x_pressed.as_bool() { eng.input.set_gamepad_button_down(2); }
1352
+ if y_pressed.as_bool() { eng.input.set_gamepad_button_down(3); }
1353
+
1354
+ // D-pad
1355
+ let dpad: Retained<AnyObject> = msg_send![&*extended, dpad];
1356
+ let up: Retained<AnyObject> = msg_send![&*dpad, up];
1357
+ let down: Retained<AnyObject> = msg_send![&*dpad, down];
1358
+ let left: Retained<AnyObject> = msg_send![&*dpad, left];
1359
+ let right: Retained<AnyObject> = msg_send![&*dpad, right];
1360
+ let up_p: Bool = msg_send![&*up, isPressed];
1361
+ let down_p: Bool = msg_send![&*down, isPressed];
1362
+ let left_p: Bool = msg_send![&*left, isPressed];
1363
+ let right_p: Bool = msg_send![&*right, isPressed];
1364
+ if up_p.as_bool() { eng.input.set_gamepad_button_down(12); }
1365
+ if down_p.as_bool() { eng.input.set_gamepad_button_down(13); }
1366
+ if left_p.as_bool() { eng.input.set_gamepad_button_down(14); }
1367
+ if right_p.as_bool() { eng.input.set_gamepad_button_down(15); }
1368
+
1369
+ // Shoulders and triggers
1370
+ let l_shoulder: Retained<AnyObject> = msg_send![&*extended, leftShoulder];
1371
+ let r_shoulder: Retained<AnyObject> = msg_send![&*extended, rightShoulder];
1372
+ let ls_p: Bool = msg_send![&*l_shoulder, isPressed];
1373
+ let rs_p: Bool = msg_send![&*r_shoulder, isPressed];
1374
+ if ls_p.as_bool() { eng.input.set_gamepad_button_down(4); }
1375
+ if rs_p.as_bool() { eng.input.set_gamepad_button_down(5); }
1376
+
1377
+ let l_trigger: Retained<AnyObject> = msg_send![&*extended, leftTrigger];
1378
+ let r_trigger: Retained<AnyObject> = msg_send![&*extended, rightTrigger];
1379
+ eng.input.set_gamepad_axis(4, { let v: f64 = msg_send![&*l_trigger, value]; v as f32 });
1380
+ eng.input.set_gamepad_axis(5, { let v: f64 = msg_send![&*r_trigger, value]; v as f32 });
1381
+ }
1382
+ return;
1383
+ }
1384
+
1385
+ // Fall back to micro gamepad profile (Siri Remote)
1386
+ let micro: *const AnyObject = msg_send![&*controller, microGamepad];
1387
+ if !micro.is_null() {
1388
+ if let Some(eng) = ENGINE.get_mut() {
1389
+ eng.input.gamepad_available = true;
1390
+
1391
+ // Siri Remote touchpad → axes 0/1
1392
+ let dpad: Retained<AnyObject> = msg_send![&*micro, dpad];
1393
+ let x_val: f64 = { let axis: Retained<AnyObject> = msg_send![&*dpad, xAxis]; msg_send![&*axis, value] };
1394
+ let y_val: f64 = { let axis: Retained<AnyObject> = msg_send![&*dpad, yAxis]; msg_send![&*axis, value] };
1395
+ eng.input.set_gamepad_axis(0, x_val as f32);
1396
+ eng.input.set_gamepad_axis(1, -y_val as f32);
1397
+
1398
+ // Button A (select/click) and Button X (play/pause)
1399
+ let btn_a: Retained<AnyObject> = msg_send![&*micro, buttonA];
1400
+ let btn_x: Retained<AnyObject> = msg_send![&*micro, buttonX];
1401
+ let a_pressed: Bool = msg_send![&*btn_a, isPressed];
1402
+ let x_pressed: Bool = msg_send![&*btn_x, isPressed];
1403
+ if a_pressed.as_bool() { eng.input.set_gamepad_button_down(0); }
1404
+ if x_pressed.as_bool() { eng.input.set_gamepad_button_down(9); } // start/pause
1405
+ }
1406
+ }
1407
+ }
1408
+ }
1409
+
1410
+ fn setup_game_controllers() {
1411
+ // Register for GCController connection notifications and set up input handlers.
1412
+ // This is the correct way to handle Siri Remote input on tvOS — it claims
1413
+ // the controller at the system level, preventing the OS from dismissing the app.
1414
+ unsafe {
1415
+ extern "C" {
1416
+ static _dispatch_main_q: c_void;
1417
+ fn dispatch_async_f(queue: *const c_void, context: *mut c_void, work: unsafe extern "C" fn(*mut c_void));
1418
+ }
1419
+ unsafe extern "C" fn setup_gc(_: *mut c_void) {
1420
+ let gc_cls = match AnyClass::get(c"GCController") {
1421
+ Some(c) => c,
1422
+ None => return,
1423
+ };
1424
+
1425
+ // Start wireless controller discovery (finds Siri Remote in simulator)
1426
+ let _: () = msg_send![gc_cls, startWirelessControllerDiscoveryWithCompletionHandler: std::ptr::null::<c_void>()];
1427
+
1428
+ // Check for already-connected controllers
1429
+ let controllers: Retained<AnyObject> = msg_send![gc_cls, controllers];
1430
+ let count: usize = msg_send![&*controllers, count];
1431
+ std::io::Write::write_all(&mut std::io::stderr(),
1432
+ format!("[bloom-visionos] GCControllers found: {}\n", count).as_bytes()).ok();
1433
+
1434
+ // Set up value-changed handlers on connected controllers
1435
+ for i in 0..count {
1436
+ let ctrl: Retained<AnyObject> = msg_send![&*controllers, objectAtIndex: i as usize];
1437
+ let micro: *const AnyObject = msg_send![&*ctrl, microGamepad];
1438
+ if !micro.is_null() {
1439
+ // Set reportsAbsoluteDpadValues so polled values are absolute position
1440
+ let _: () = msg_send![&*micro, setReportsAbsoluteDpadValues: Bool::YES];
1441
+ }
1442
+ }
1443
+
1444
+ // visionOS: do NOT create a GCVirtualController. Its on-screen
1445
+ // overlay sits on top of the window and swallows indirect
1446
+ // (eye+pinch) input as its own d-pad/button presses, so the
1447
+ // game's touch handlers (touchesBegan -> bloom_get_touch_*) never
1448
+ // see the pinch. We want pinches to reach the Metal view as plain
1449
+ // UITouches at the gaze location so touch/pinch controls work. A
1450
+ // *physical* Bluetooth controller (count > 0) is still picked up
1451
+ // below. (tvOS keeps the virtual controller; visionOS omits it.)
1452
+
1453
+ for i in 0..count {
1454
+ let controller: Retained<AnyObject> = msg_send![&*controllers, objectAtIndex: i as usize];
1455
+
1456
+ // Check micro gamepad (Siri Remote)
1457
+ let micro: *const AnyObject = msg_send![&*controller, microGamepad];
1458
+ if !micro.is_null() {
1459
+ std::io::Write::write_all(&mut std::io::stderr(), b"[bloom-visionos] Found micro gamepad (Siri Remote)\n").ok();
1460
+ // Set reportsAbsoluteDpadValues so we get position, not delta
1461
+ let _: () = msg_send![&*micro, setReportsAbsoluteDpadValues: Bool::YES];
1462
+ // allowsRotation for landscape usage
1463
+ let _: () = msg_send![&*micro, setAllowsRotation: Bool::YES];
1464
+ }
1465
+
1466
+ // Check extended gamepad (MFi, PS, Xbox)
1467
+ let extended: *const AnyObject = msg_send![&*controller, extendedGamepad];
1468
+ if !extended.is_null() {
1469
+ std::io::Write::write_all(&mut std::io::stderr(), b"[bloom-visionos] Found extended gamepad\n").ok();
1470
+ }
1471
+ }
1472
+ }
1473
+ dispatch_async_f(&_dispatch_main_q as *const _, std::ptr::null_mut(), setup_gc);
1474
+ }
1475
+ }
1476
+
1477
+ // ============================================================
1478
+ // FFI entry points
1479
+ // ============================================================
1480
+
1481
+ #[no_mangle]
1482
+ pub extern "C" fn bloom_init_window(_width: f64, _height: f64, title_ptr: *const u8, _fullscreen: f64) {
1483
+ let _title = str_from_header(title_ptr);
1484
+
1485
+ // Register ObjC classes for the scene delegate (window/view creation)
1486
+ register_metal_view_class();
1487
+ register_window_class();
1488
+ register_view_controller_class();
1489
+ register_scene_delegate();
1490
+
1491
+ // Signal the main thread that our ObjC classes are ready.
1492
+ // UIApplicationMain (on main thread) waits for this before starting.
1493
+ extern "C" { fn perry_ios_classes_registered(); }
1494
+ unsafe { perry_ios_classes_registered(); }
1495
+
1496
+ // Debug: write marker to confirm we reached this point
1497
+ let _ = std::fs::write("/tmp/bloom_checkpoint_1.txt", "classes registered\n");
1498
+
1499
+ // Get app bundle path for resolving relative asset paths
1500
+ unsafe {
1501
+ let bundle_cls = AnyClass::get(c"NSBundle").unwrap();
1502
+ let main_bundle: Retained<AnyObject> = msg_send![bundle_cls, mainBundle];
1503
+ let resource_path: *const AnyObject = msg_send![&*main_bundle, resourcePath];
1504
+ if !resource_path.is_null() {
1505
+ let utf8: *const u8 = msg_send![&*resource_path, UTF8String];
1506
+ if !utf8.is_null() {
1507
+ let cstr = std::ffi::CStr::from_ptr(utf8 as *const i8);
1508
+ if let Ok(s) = cstr.to_str() {
1509
+ BUNDLE_PATH = Some(s.to_string());
1510
+ }
1511
+ }
1512
+ }
1513
+ }
1514
+
1515
+ // With --features ios-game-loop, this function runs on the game thread.
1516
+ // The engine is created on the main thread by scene_will_connect (like iOS).
1517
+ // Just wait for it here.
1518
+ std::io::Write::write_all(&mut std::io::stderr(), b"[bloom-visionos] waiting for ENGINE...\n").ok();
1519
+ unsafe {
1520
+ for i in 0..3000 {
1521
+ if ENGINE.get().is_some() { break; }
1522
+ if i % 100 == 0 && i > 0 {
1523
+ let msg = format!("[bloom-visionos] still waiting for ENGINE... {}s\n", i / 100);
1524
+ std::io::Write::write_all(&mut std::io::stderr(), msg.as_bytes()).ok();
1525
+ }
1526
+ std::thread::sleep(std::time::Duration::from_millis(10));
1527
+ }
1528
+ if ENGINE.get().is_none() {
1529
+ panic!("[bloom-visionos] ENGINE not available after 30s");
1530
+ }
1531
+ }
1532
+ std::io::Write::write_all(&mut std::io::stderr(), b"[bloom-visionos] ENGINE ready on game thread\n").ok();
1533
+
1534
+ // Set up GCController monitoring for Siri Remote and game controllers
1535
+ setup_game_controllers();
1536
+ }
1537
+
1538
+ /// Attach the engine to a host-owned `UIView*` instead of creating its
1539
+ /// own UIWindow (PerryTS/perry#5519). `handle` is the raw `UIView*` the
1540
+ /// host owns; `width`/`height` are its size in points. Returns 1.0 on
1541
+ /// success, 0.0 on a null/invalid handle or surface bring-up failure.
1542
+ /// Idempotent once attached. visionOS uses a non-sRGB swapchain to match
1543
+ /// its windowed path.
1544
+ #[no_mangle]
1545
+ pub extern "C" fn bloom_attach_native(handle: i64, width: f64, height: f64) -> f64 {
1546
+ if handle == 0 {
1547
+ return 0.0;
1548
+ }
1549
+ if unsafe { ENGINE.get() }.is_some() {
1550
+ return 1.0;
1551
+ }
1552
+ let Some(view_nn) = std::ptr::NonNull::new(handle as *mut c_void) else {
1553
+ return 0.0;
1554
+ };
1555
+ let target = {
1556
+ let h = UiKitWindowHandle::new(view_nn);
1557
+ wgpu::SurfaceTargetUnsafe::RawHandle {
1558
+ raw_display_handle: Some(RawDisplayHandle::UiKit(UiKitDisplayHandle::new())),
1559
+ raw_window_handle: RawWindowHandle::UiKit(h),
1560
+ }
1561
+ };
1562
+ match unsafe {
1563
+ bloom_shared::attach::attach_engine(
1564
+ target,
1565
+ bloom_shared::attach::AttachParams {
1566
+ backends: wgpu::Backends::METAL,
1567
+ logical_w: width as u32,
1568
+ logical_h: height as u32,
1569
+ physical_w: (width as u32).max(1),
1570
+ physical_h: (height as u32).max(1),
1571
+ format: bloom_shared::attach::FormatPreference::NonSrgb,
1572
+ },
1573
+ )
1574
+ } {
1575
+ Ok(es) => {
1576
+ unsafe {
1577
+ let _ = ENGINE.set(es);
1578
+ }
1579
+ 1.0
1580
+ }
1581
+ Err(_) => 0.0,
1582
+ }
1583
+ }
1584
+
1585
+ /// Resize the engine's surface (#70 parity; used by host-driven
1586
+ /// BloomViews on layout changes). `phys_*` physical px, `log_*` logical.
1587
+ #[no_mangle]
1588
+ pub extern "C" fn bloom_resize(phys_w: f64, phys_h: f64, log_w: f64, log_h: f64) {
1589
+ if let Some(eng) = unsafe { ENGINE.get_mut() } {
1590
+ eng.renderer.resize(phys_w as u32, phys_h as u32, log_w as u32, log_h as u32);
1591
+ }
1592
+ }
1593
+
1594
+ /// HWND host-embed (#70) — Windows only; a no-op here for FFI-manifest
1595
+ /// parity. Non-Windows hosts attach via `bloom_attach_native`.
1596
+ #[no_mangle]
1597
+ pub extern "C" fn bloom_attach_hwnd(_hwnd_bits: f64, _width: f64, _height: f64) {}
1598
+
1599
+ #[no_mangle]
1600
+ pub extern "C" fn bloom_close_window() {
1601
+ unsafe { UI_VIEW = None; UI_WINDOW = None; }
1602
+ }
1603
+
1604
+ #[no_mangle]
1605
+ pub extern "C" fn bloom_window_should_close() -> f64 {
1606
+ if engine().should_close { 1.0 } else { 0.0 }
1607
+ }
1608
+
1609
+ #[no_mangle]
1610
+ pub extern "C" fn bloom_begin_drawing() {
1611
+ static FRAME_COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
1612
+ let frame = FRAME_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1613
+ if frame == 0 {
1614
+ std::io::Write::write_all(&mut std::io::stderr(), b"[bloom-visionos] first bloom_begin_drawing\n").ok();
1615
+ }
1616
+ // Poll GCController synchronously on the game thread.
1617
+ // GCController value reading is thread-safe.
1618
+ unsafe {
1619
+ if let Some(gc_cls) = AnyClass::get(c"GCController") {
1620
+ let controllers: Retained<AnyObject> = msg_send![gc_cls, controllers];
1621
+ let count: usize = msg_send![&*controllers, count];
1622
+ {
1623
+ static POLL_LOG: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
1624
+ let n = POLL_LOG.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1625
+ if n < 3 || (n % 300 == 0) {
1626
+ std::io::Write::write_all(&mut std::io::stderr(),
1627
+ format!("[bloom-visionos] GC poll: {} controllers\n", count).as_bytes()).ok();
1628
+ }
1629
+ }
1630
+ if count > 0 {
1631
+ let controller: Retained<AnyObject> = msg_send![&*controllers, objectAtIndex: 0usize];
1632
+ let eng = engine();
1633
+ eng.input.gamepad_available = true;
1634
+
1635
+ // Micro gamepad (Siri Remote)
1636
+ let micro: *const AnyObject = msg_send![&*controller, microGamepad];
1637
+ let extended_check: *const AnyObject = msg_send![&*controller, extendedGamepad];
1638
+ {
1639
+ static PROFILE_LOG: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
1640
+ if !PROFILE_LOG.swap(true, std::sync::atomic::Ordering::Relaxed) {
1641
+ std::io::Write::write_all(&mut std::io::stderr(),
1642
+ format!("[bloom-visionos] micro={} extended={}\n", !micro.is_null(), !extended_check.is_null()).as_bytes()).ok();
1643
+ }
1644
+ }
1645
+ if !micro.is_null() {
1646
+ let dpad: Retained<AnyObject> = msg_send![&*micro, dpad];
1647
+ let x_axis: Retained<AnyObject> = msg_send![&*dpad, xAxis];
1648
+ let y_axis: Retained<AnyObject> = msg_send![&*dpad, yAxis];
1649
+ let x_val: f32 = msg_send![&*x_axis, value];
1650
+ let y_val: f32 = msg_send![&*y_axis, value];
1651
+ eng.input.set_gamepad_axis(0, x_val);
1652
+ eng.input.set_gamepad_axis(1, -y_val);
1653
+ let btn_a: Retained<AnyObject> = msg_send![&*micro, buttonA];
1654
+ let btn_x: Retained<AnyObject> = msg_send![&*micro, buttonX];
1655
+ let a_val: f32 = msg_send![&*btn_a, value];
1656
+ let x_btn_val: f32 = msg_send![&*btn_x, value];
1657
+ if a_val > 0.01 || x_btn_val > 0.01 || x_val.abs() > 0.01 || y_val.abs() > 0.01 {
1658
+ static BTN_LOG: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
1659
+ let n = BTN_LOG.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1660
+ if n < 20 {
1661
+ std::io::Write::write_all(&mut std::io::stderr(),
1662
+ format!("[bloom-visionos] micro: x={:.2} y={:.2} a={:.2} x_btn={:.2}\n", x_val, y_val, a_val, x_btn_val).as_bytes()).ok();
1663
+ }
1664
+ }
1665
+ if a_val > 0.5 { eng.input.set_gamepad_button_down(0); }
1666
+ if x_btn_val > 0.5 { eng.input.set_gamepad_button_down(7); }
1667
+ }
1668
+
1669
+ // Extended gamepad (MFi/PS/Xbox)
1670
+ let extended: *const AnyObject = msg_send![&*controller, extendedGamepad];
1671
+ if !extended.is_null() {
1672
+ let left_stick: Retained<AnyObject> = msg_send![&*extended, leftThumbstick];
1673
+ let lx_axis: Retained<AnyObject> = msg_send![&*left_stick, xAxis];
1674
+ let ly_axis: Retained<AnyObject> = msg_send![&*left_stick, yAxis];
1675
+ let lx: f32 = msg_send![&*lx_axis, value];
1676
+ let ly: f32 = msg_send![&*ly_axis, value];
1677
+ eng.input.set_gamepad_axis(0, lx);
1678
+ eng.input.set_gamepad_axis(1, -ly);
1679
+ let btn_a: Retained<AnyObject> = msg_send![&*extended, buttonA];
1680
+ let a_val: f32 = msg_send![&*btn_a, value];
1681
+ if lx.abs() > 0.01 || ly.abs() > 0.01 || a_val > 0.01 {
1682
+ static EXT_LOG: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
1683
+ let n = EXT_LOG.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1684
+ if n < 20 {
1685
+ std::io::Write::write_all(&mut std::io::stderr(),
1686
+ format!("[bloom-visionos] ext: lx={:.2} ly={:.2} a={:.2}\n", lx, ly, a_val).as_bytes()).ok();
1687
+ }
1688
+ }
1689
+ if a_val > 0.5 { eng.input.set_gamepad_button_down(0); }
1690
+ }
1691
+ }
1692
+ }
1693
+ }
1694
+ // Drain pending key events from main thread BEFORE begin_frame snapshots
1695
+ drain_pending_keys(engine());
1696
+
1697
+ // Check if any pending keys were drained
1698
+ {
1699
+ static DRAIN_LOG: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
1700
+ // Check if any PENDING_KEY_DOWN bits are set (before they were drained)
1701
+ let mut any = false;
1702
+ for i in 0..8 {
1703
+ if PENDING_KEY_DOWN[i].load(std::sync::atomic::Ordering::Relaxed) != 0 { any = true; }
1704
+ }
1705
+ if any {
1706
+ let n = DRAIN_LOG.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1707
+ if n < 10 {
1708
+ std::io::Write::write_all(&mut std::io::stderr(), b"[bloom-visionos] PENDING KEYS FOUND!\n").ok();
1709
+ }
1710
+ }
1711
+ }
1712
+
1713
+ if frame == 0 {
1714
+ std::io::Write::write_all(&mut std::io::stderr(), b"[bloom-visionos] calling begin_frame\n").ok();
1715
+ }
1716
+ engine().begin_frame();
1717
+ if frame == 0 {
1718
+ std::io::Write::write_all(&mut std::io::stderr(), b"[bloom-visionos] begin_frame OK\n").ok();
1719
+ }
1720
+ }
1721
+
1722
+ #[no_mangle]
1723
+ pub extern "C" fn bloom_end_drawing() {
1724
+ static END_FRAME_COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
1725
+ let frame = END_FRAME_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1726
+ if frame == 0 {
1727
+ std::io::Write::write_all(&mut std::io::stderr(), b"[bloom-visionos] first bloom_end_drawing\n").ok();
1728
+ }
1729
+ engine().end_frame();
1730
+ if frame == 0 {
1731
+ std::io::Write::write_all(&mut std::io::stderr(), b"[bloom-visionos] end_frame OK\n").ok();
1732
+ }
1733
+ }
1734
+
1735
+ // ============================================================
1736
+ // Keyboard input
1737
+ // ============================================================
1738
+
1739
+ // ============================================================
1740
+ // Mouse input
1741
+ // ============================================================
1742
+
1743
+ // ============================================================
1744
+ // Shape drawing
1745
+ // ============================================================
1746
+
1747
+ // ============================================================
1748
+ // Text
1749
+ // ============================================================
1750
+
1751
+ // ============================================================
1752
+ // Textures
1753
+ // ============================================================
1754
+
1755
+ // ============================================================
1756
+ // Camera 2D
1757
+ // ============================================================
1758
+
1759
+ // ============================================================
1760
+ // 3D Camera and Drawing
1761
+ // ============================================================
1762
+
1763
+ // ============================================================
1764
+ // Joint test (skeletal animation debug)
1765
+ // ============================================================
1766
+
1767
+ // ============================================================
1768
+ // Lighting
1769
+ // ============================================================
1770
+
1771
+ // ============================================================
1772
+ // Models
1773
+ // ============================================================
1774
+
1775
+ // ============================================================
1776
+ // Phase 1c — material system FFI
1777
+ // ============================================================
1778
+
1779
+ // ============================================================
1780
+ mod audio_backend;
1781
+
1782
+
1783
+ // ============================================================
1784
+ // Music
1785
+ // ============================================================
1786
+
1787
+ // ============================================================
1788
+ // Staging / commit (thread-safe asset loading for ios-game-loop)
1789
+ // ============================================================
1790
+
1791
+ // ============================================================
1792
+ // Gamepad input
1793
+ // ============================================================
1794
+
1795
+ // ============================================================
1796
+ // Touch input
1797
+ // ============================================================
1798
+
1799
+ // ============================================================
1800
+ // Utility
1801
+ // ============================================================
1802
+
1803
+ #[no_mangle]
1804
+ pub extern "C" fn bloom_toggle_fullscreen() {}
1805
+
1806
+ #[no_mangle]
1807
+ pub extern "C" fn bloom_set_window_title(_title_ptr: *const u8) {}
1808
+
1809
+ #[no_mangle]
1810
+ pub extern "C" fn bloom_set_window_icon(_path_ptr: *const u8) {}
1811
+
1812
+ #[no_mangle]
1813
+ pub extern "C" fn bloom_disable_cursor() {
1814
+ engine().input.cursor_disabled = true;
1815
+ }
1816
+
1817
+ #[no_mangle]
1818
+ pub extern "C" fn bloom_enable_cursor() {
1819
+ engine().input.cursor_disabled = false;
1820
+ }
1821
+
1822
+ // E4: Clipboard (stub on this platform)
1823
+ #[no_mangle]
1824
+ pub extern "C" fn bloom_set_clipboard_text(_text_ptr: *const u8) {}
1825
+ #[no_mangle]
1826
+ pub extern "C" fn bloom_get_clipboard_text() -> *const u8 { std::ptr::null() }
1827
+
1828
+ // E5b: File dialogs (stub on this platform)
1829
+ #[no_mangle]
1830
+ pub extern "C" fn bloom_open_file_dialog(_filter_ptr: *const u8, _title_ptr: *const u8) -> *const u8 { std::ptr::null() }
1831
+ #[no_mangle]
1832
+ pub extern "C" fn bloom_save_file_dialog(_default_name_ptr: *const u8, _title_ptr: *const u8) -> *const u8 { std::ptr::null() }
1833
+
1834
+ // ============================================================
1835
+ // Input injection + platform detection
1836
+ // ============================================================
1837
+ #[no_mangle]
1838
+ pub extern "C" fn bloom_get_platform() -> f64 { 9.0 }
1839
+
1840
+ /// Preferred OS language packed as `c0*256+c1` (ISO-639 primary subtag). See macos lib for format.
1841
+ #[no_mangle]
1842
+ pub extern "C" fn bloom_get_language() -> f64 {
1843
+ fn pack(code: &str) -> f64 { let l = code.to_ascii_lowercase(); let b = l.as_bytes(); if b.len() >= 2 { (b[0] as f64) * 256.0 + (b[1] as f64) } else { 25966.0 } }
1844
+ let langs = objc2_foundation::NSLocale::preferredLanguages();
1845
+ match langs.firstObject() { Some(s) => pack(&s.to_string()), None => 25966.0 }
1846
+ }
1847
+
1848
+
1849
+ // Q6: Multi-hit picking
1850
+ // ============================================================
1851
+
1852
+ // ============================================================
1853
+ // Render quality toggles (individual + preset) — ticket 011
1854
+ // Mirror of the macOS FFI surface added in commit 95da6af; previously
1855
+ // macOS-only, now exposed on every native platform so non-macOS builds
1856
+ // don't fail at runtime (missing symbol) when the TS API invokes them.
1857
+ // ============================================================
1858
+
1859
+ // ============================================================
1860
+ // Profiler — CPU phase timings (always available) + GPU timestamps
1861
+ // (when the adapter supports TIMESTAMP_QUERY). Disabled by default.
1862
+ // ============================================================
1863
+
1864
+ // ============================================================
1865
+ // Physics (Jolt 5.x) — FFI surface generated from shared macro
1866
+ // ============================================================
1867
+
1868
+ #[cfg(feature = "jolt")]
1869
+ #[inline]
1870
+ fn bloom_jolt_ffi_physics() -> &'static mut bloom_shared::physics_jolt::JoltPhysics {
1871
+ &mut engine().jolt
1872
+ }
1873
+
1874
+ #[cfg(feature = "jolt")]
1875
+ bloom_shared::define_physics_ffi!();
1876
+
1877
+ // ============================================================
1878
+ // Screenshot + HDR env + Post-FX / resolution FFI
1879
+ // ------------------------------------------------------------
1880
+ // Ported from native/macos/src/lib.rs. These delegate to the shared
1881
+ // bloom_shared renderer (identical type used here), so they are real
1882
+ // implementations, not stubs. They were present on macOS/linux/windows
1883
+ // but missing on tvOS, which caused `ld64.lld: undefined symbol: _bloom_*`
1884
+ // link errors for any app using the post-processing API on tvOS.
1885
+ // ============================================================
1886
+
1887
+ // --- Post-FX knobs (heuristic visual layer; default-off) ---