Skip to main content

yog_runtime/
lib.rs

1//! Yog runtime — the native library loaded by the Fabric host.
2//!
3//! Exposes JNI entry points (`Java_dev_yog_NativeBridge_*`) that the host calls,
4//! and a stable C ABI (`YogApi` / `YogServer`) that mods program against.
5//!
6//! Architecture:
7//!   - `YogServer`  — a `#[repr(C)]` table of standalone JNI-calling functions
8//!                    that mods call to mutate the world.
9//!   - `YogApi`     — a `#[repr(C)]` table of registration functions; mods call
10//!                    them inside `yog_mod_register` to subscribe to events.
11//!   - `RuntimeHandlers` — the runtime's internal event/handler storage.
12//!     Filled during `nativeInit` (write), read-only after. The scheduler sub-
13//!     state uses an inner `Mutex` for safe addition during event dispatch.
14
15use std::collections::HashMap;
16use std::num::NonZeroU32;
17use std::os::raw::c_void;
18use std::path::{Path, PathBuf};
19use std::sync::{Mutex, OnceLock};
20
21use glow::HasContext;
22use jni::objects::{JByteArray, JClass, JFloatArray, JObject, JString, JValue};
23use jni::sys::{jdouble, jfloat, jint, jstring};
24use jni::{JNIEnv, JavaVM};
25use libloading::{Library, Symbol};
26
27use yog_abi::{
28    ABI_VERSION, YogAdvancementEvent, YogAdvancementFn, YogApi, YogAttackEntityFn,
29    YogBlockBreakFn, YogBlockDef, YogBlockPos, YogChatFn, YogClientFn, YogCommandFn,
30    YogContainerCloseEvent, YogContainerCloseFn, YogContainerOpenEvent, YogContainerOpenFn,
31    YogCraftEvent, YogCraftFn, YogEntityDamageFn, YogEntityDeathFn, YogEntityInteractEvent,
32    YogEntityInteractFn, YogEntitySpawnFn, YogExplosionEvent, YogExplosionFn,
33    YogGfxApi, YogHudRenderFn, YogItemDef, YogItemPickupEvent, YogItemPickupFn,
34    YogKeyPressFn, YogKeyPressEvent, YogOwnedStr, YogPacketFn, YogPlaceBlockEvent,
35    YogPlaceBlockFn, YogPlayerDeathEvent, YogPlayerDeathFn, YogPlayerFn, YogPlayerMoveEvent,
36    YogPlayerMoveFn, YogPlayerRespawnEvent, YogPlayerRespawnFn, YogProjectileHitEvent,
37    YogProjectileHitFn, YogScheduledFn, YogScreenFn, YogServer, YogServerFn, YogStr, YogStartupGrantDef,
38    YogUseBlockFn, YogUseItemFn, YogVec3, YogWorldRenderFn,
39};
40use yog_registry::{BlockDef, FoodDef, ItemDef};
41
42// ── Static globals ────────────────────────────────────────────────────────────
43
44/// Cached JVM handle for any-thread callbacks.
45static JAVA_VM: OnceLock<JavaVM> = OnceLock::new();
46/// Loaded mod libraries — kept alive so the code pages stay mapped.
47static LOADED_MODS: Mutex<Vec<Library>> = Mutex::new(Vec::new());
48/// Metadata of loaded .yog mods: [id, name, version, authors, description].
49static MOD_INFOS: Mutex<Vec<[String; 5]>> = Mutex::new(Vec::new());
50/// Stable server table (populated once in nativeInit, then read-only).
51static SERVER: OnceLock<YogServer> = OnceLock::new();
52/// Stable api table. Mods capture this pointer at registration (yog-api's
53/// `installed_mods()` calls through it later, e.g. from UI render) — so it
54/// must outlive `nativeInit`, not live on its stack. NB: `ctx` inside points
55/// at the pre-move handlers Box and is only valid during registration; late
56/// api calls must not dereference it (api_mods_list doesn't).
57static API_TABLE: OnceLock<YogApi> = OnceLock::new();
58/// All registered handlers + content (populated during mod loading, then read-only).
59static HANDLERS: OnceLock<RuntimeHandlers> = OnceLock::new();
60
61// ── OpenGL context (client-side, render thread only) ─────────────────────────
62
63struct GlCtx(glow::Context);
64unsafe impl Send for GlCtx {}
65unsafe impl Sync for GlCtx {}
66
67/// Initialized by `nativeGlInit` on the render thread.  `None` on dedicated server.
68static GL: OnceLock<GlCtx> = OnceLock::new();
69
70// Raw GL function pointers for GL_ARB_get_program_binary (not exposed by glow 0.13).
71// Captured during the glow loader callback in `nativeGlInit`.
72// `None` when the extension is unavailable (very old drivers).
73static GL_GET_PROGRAM_BINARY: OnceLock<Option<usize>> = OnceLock::new();
74static GL_PROGRAM_BINARY:     OnceLock<Option<usize>> = OnceLock::new();
75static GL_GET_PROGRAM_IV:     OnceLock<Option<usize>> = OnceLock::new();
76
77// ── Handler storage ───────────────────────────────────────────────────────────
78
79#[derive(Debug, Clone)]
80pub struct UiLayer {
81    pub id:         String,
82    pub parent:     Option<String>,
83    pub modal:      bool,
84    pub pause_game: bool,
85    pub visible:    bool,
86    pub enabled:    bool,
87    pub z_index:    i32,
88}
89
90struct RuntimeHandlers {
91    block_break:        Vec<(*mut c_void, YogBlockBreakFn)>,
92    chat:               Vec<(*mut c_void, YogChatFn)>,
93    player_join:        Vec<(*mut c_void, YogPlayerFn)>,
94    player_leave:       Vec<(*mut c_void, YogPlayerFn)>,
95    use_item:           Vec<(*mut c_void, YogUseItemFn)>,
96    use_block:          Vec<(*mut c_void, YogUseBlockFn)>,
97    attack_entity:      Vec<(*mut c_void, YogAttackEntityFn)>,
98    entity_damage:      Vec<(*mut c_void, YogEntityDamageFn)>,
99    entity_death:       Vec<(*mut c_void, YogEntityDeathFn)>,
100    entity_spawn:       Vec<(*mut c_void, YogEntitySpawnFn)>,
101    player_place_block: Vec<(*mut c_void, YogPlaceBlockFn)>,
102    player_death:       Vec<(*mut c_void, YogPlayerDeathFn)>,
103    player_respawn:     Vec<(*mut c_void, YogPlayerRespawnFn)>,
104    advancement:        Vec<(*mut c_void, YogAdvancementFn)>,
105    entity_interact:    Vec<(*mut c_void, YogEntityInteractFn)>,
106    item_craft:         Vec<(*mut c_void, YogCraftFn)>,
107    explosion:          Vec<(*mut c_void, YogExplosionFn)>,
108    item_pickup:        Vec<(*mut c_void, YogItemPickupFn)>,
109    player_move:        Vec<(*mut c_void, YogPlayerMoveFn)>,
110    container_open:     Vec<(*mut c_void, YogContainerOpenFn)>,
111    container_close:    Vec<(*mut c_void, YogContainerCloseFn)>,
112    projectile_hit:     Vec<(*mut c_void, YogProjectileHitFn)>,
113    client_tick:        Vec<(*mut c_void, YogClientFn)>,
114    hud_render:         Vec<(*mut c_void, YogHudRenderFn)>,
115    world_render:       Vec<(*mut c_void, YogWorldRenderFn)>,
116    key_press:          Vec<(*mut c_void, YogKeyPressFn)>,
117    screen_open:        Vec<(*mut c_void, YogScreenFn)>,
118    screen_close:       Vec<(*mut c_void, YogScreenFn)>,
119    server_tick:        Vec<(*mut c_void, YogServerFn)>,
120    server_started:     Vec<(*mut c_void, YogServerFn)>,
121    server_stopping:    Vec<(*mut c_void, YogServerFn)>,
122    /// All handlers registered under one command name, in registration order.
123    /// `schema` is `None` for a plain `on_command` (bare, zero-argument)
124    /// registration and `Some(schema)` for `on_typed_command`. Kept as a
125    /// `Vec` (not a single slot) so a mod can register several subcommands —
126    /// e.g. differing arg counts, or several bare/typed registrations sharing
127    /// one top-level name — without later registrations silently clobbering
128    /// earlier ones (see `nativeOnCommand`, which tries each entry whose
129    /// schema's arg count matches the actual invocation, in order, until one
130    /// produces a reply).
131    commands:           HashMap<String, Vec<(Option<String>, *mut c_void, YogCommandFn)>>,
132    recipes:            Vec<(String, String, String)>,
133    packets:            HashMap<String, (*mut c_void, YogPacketFn)>,
134    client_packets:     HashMap<String, (*mut c_void, YogPacketFn)>,
135    items:              Vec<ItemDef>,
136    blocks:             Vec<BlockDef>,
137    inventories:        Vec<yog_inventory::InventoryDef>,
138    books:              HashMap<String, String>,
139    book_renderers:     Mutex<HashMap<String, yog_book::BookRenderer>>,
140    ui_handlers:        HashMap<String, (*mut c_void, yog_abi::YogUIEventFn)>,
141    ui_render_handlers: HashMap<String, Vec<(*mut c_void, YogHudRenderFn)>>,
142    menu_entries:       Vec<(String, String)>,  // (label, ui_id) for vanilla screen buttons
143    pub active_uis:     Mutex<Vec<UiLayer>>,
144    startup_grants:     Vec<yog_registry::StartupGrant>,
145    startup_granted:    Mutex<HashMap<String, bool>>,
146    /// Players whose startup grants are pending: (name, uuid, ticks_waited).
147    /// Granting happens on a server tick after join — giving items directly in
148    /// the join callback fails for the host of a freshly created world.
149    pending_grants:     Mutex<Vec<(String, String, u32)>>,
150    scheduler:          Mutex<SchedulerState>,
151}
152
153// All fn ptrs are C-ABI; ud pointers are from Box::into_raw of Send+Sync closures.
154unsafe impl Send for RuntimeHandlers {}
155unsafe impl Sync for RuntimeHandlers {}
156
157impl RuntimeHandlers {
158    fn new() -> Self {
159        Self {
160            block_break: Vec::new(), chat: Vec::new(),
161            player_join: Vec::new(), player_leave: Vec::new(),
162            use_item: Vec::new(), use_block: Vec::new(),
163            attack_entity: Vec::new(), entity_damage: Vec::new(),
164            entity_death: Vec::new(), entity_spawn: Vec::new(),
165            player_place_block: Vec::new(),
166            player_death: Vec::new(), player_respawn: Vec::new(), advancement: Vec::new(),
167            entity_interact: Vec::new(), item_craft: Vec::new(), explosion: Vec::new(),
168            item_pickup: Vec::new(), player_move: Vec::new(),
169            container_open: Vec::new(), container_close: Vec::new(),
170            projectile_hit: Vec::new(),
171            client_tick: Vec::new(), hud_render: Vec::new(), world_render: Vec::new(),
172            key_press: Vec::new(),
173            screen_open: Vec::new(), screen_close: Vec::new(),
174            server_tick: Vec::new(), server_started: Vec::new(), server_stopping: Vec::new(),
175            commands: HashMap::new(),
176            recipes: Vec::new(), packets: HashMap::new(),
177            client_packets: HashMap::new(), items: Vec::new(),
178            ui_handlers: HashMap::new(), ui_render_handlers: HashMap::new(),
179            menu_entries: Vec::new(),
180            active_uis: Mutex::new(Vec::new()), startup_grants: Vec::new(),
181            blocks: Vec::new(), inventories: Vec::new(), books: HashMap::new(),
182            book_renderers: Mutex::new(HashMap::new()),
183            startup_granted: Mutex::new(HashMap::new()),
184            pending_grants: Mutex::new(Vec::new()),
185            scheduler: Mutex::new(SchedulerState::new()),
186        }
187    }
188}
189
190struct SchedulerState {
191    once_tasks:       Vec<OnceTask>,
192    repeating_tasks:  Vec<RepeatingTask>,
193}
194
195struct OnceTask      { delay_remaining: u64, ud: *mut c_void, f: YogScheduledFn }
196struct RepeatingTask { period: u64, ticks_left: u64, ud: *mut c_void, f: YogScheduledFn }
197
198unsafe impl Send for SchedulerState {}
199unsafe impl Sync for SchedulerState {}
200unsafe impl Send for OnceTask {}
201unsafe impl Send for RepeatingTask {}
202
203impl SchedulerState {
204    fn new() -> Self { Self { once_tasks: Vec::new(), repeating_tasks: Vec::new() } }
205}
206
207fn handlers() -> &'static RuntimeHandlers {
208    HANDLERS.get().expect("yog: nativeInit not called yet")
209}
210
211// ── JNI helpers ──────────────────────────────────────────────────────────────
212
213fn guard(label: &str, f: impl FnOnce()) {
214    if std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).is_err() {
215        yog_logging::error!("a mod panicked handling `{}` (ignored)", label);
216    }
217}
218
219macro_rules! jstr {
220    ($env:expr, $s:expr) => {
221        match $env.get_string(&$s) { Ok(s) => String::from(s), Err(_) => return }
222    };
223}
224
225/// Convert a `YogStr` into a Java String. Caller must ensure `s` is valid UTF-8.
226unsafe fn ys_to_java<'l>(env: &mut JNIEnv<'l>, s: YogStr)
227    -> Option<jni::objects::JString<'l>>
228{
229    env.new_string(s.as_str()).ok()
230}
231
232fn get_env() -> Option<jni::AttachGuard<'static>> {
233    JAVA_VM.get()?.attach_current_thread().ok()
234}
235
236// ── Free-str allocator used by YogOwnedStr ────────────────────────────────────
237
238unsafe extern "C" fn yog_free_str(ptr: *mut u8, len: u32) {
239    if !ptr.is_null() {
240        drop(Box::from_raw(std::slice::from_raw_parts_mut(ptr, len as usize)));
241    }
242}
243
244fn jstring_to_owned(env: &mut JNIEnv, obj: jni::objects::JObject) -> YogOwnedStr {
245    if obj.as_raw().is_null() { return YogOwnedStr::NONE; }
246    match env.get_string(&JString::from(obj)) {
247        Ok(s) => YogOwnedStr::from_string(String::from(s)),
248        Err(_) => YogOwnedStr::NONE,
249    }
250}
251
252// ── YogServer standalone functions (one per action) ───────────────────────────
253//
254// ctx is unused here — all state is in the JAVA_VM static.
255
256unsafe extern "C" fn srv_broadcast(_ctx: *mut c_void, msg: YogStr) {
257    let Some(mut env) = get_env() else { return };
258    if let Some(jmsg) = ys_to_java(&mut env, msg) {
259        let _ = env.call_static_method("dev/yog/NativeBridge", "broadcast",
260            "(Ljava/lang/String;)V", &[JValue::Object(&jmsg)]);
261    }
262}
263
264unsafe extern "C" fn srv_get_block(_ctx: *mut c_void, dim: YogStr, pos: YogBlockPos) -> YogOwnedStr {
265    let Some(mut env) = get_env() else { return YogOwnedStr::NONE };
266    let (Some(jd), ) = (ys_to_java(&mut env, dim),) else { return YogOwnedStr::NONE };
267    let ret = env.call_static_method("dev/yog/NativeBridge", "getBlock",
268        "(Ljava/lang/String;III)Ljava/lang/String;",
269        &[JValue::Object(&jd), JValue::Int(pos.x), JValue::Int(pos.y), JValue::Int(pos.z)]);
270    match ret.and_then(|v| v.l()) {
271        Ok(obj) => jstring_to_owned(&mut env, obj),
272        _ => YogOwnedStr::NONE,
273    }
274}
275
276unsafe extern "C" fn srv_set_block(_ctx: *mut c_void, dim: YogStr, pos: YogBlockPos, block: YogStr) -> bool {
277    let Some(mut env) = get_env() else { return false };
278    let (Some(jd), Some(jb)) = (ys_to_java(&mut env, dim), ys_to_java(&mut env, block)) else { return false };
279    env.call_static_method("dev/yog/NativeBridge", "setBlock",
280        "(Ljava/lang/String;IIILjava/lang/String;)Z",
281        &[JValue::Object(&jd), JValue::Int(pos.x), JValue::Int(pos.y), JValue::Int(pos.z), JValue::Object(&jb)])
282    .and_then(|v| v.z()).unwrap_or(false)
283}
284
285unsafe extern "C" fn srv_world_time(_ctx: *mut c_void, dim: YogStr, out: *mut i64) -> bool {
286    let Some(mut env) = get_env() else { return false };
287    let Some(jd) = ys_to_java(&mut env, dim) else { return false };
288    match env.call_static_method("dev/yog/NativeBridge", "worldTime",
289        "(Ljava/lang/String;)J", &[JValue::Object(&jd)]).and_then(|v| v.j()) {
290        Ok(v) if v != i64::MIN => { *out = v; true }
291        _ => false,
292    }
293}
294
295unsafe extern "C" fn srv_set_time(_ctx: *mut c_void, dim: YogStr, time: i64) -> bool {
296    let Some(mut env) = get_env() else { return false };
297    let Some(jd) = ys_to_java(&mut env, dim) else { return false };
298    env.call_static_method("dev/yog/NativeBridge", "worldSetTime",
299        "(Ljava/lang/String;J)Z", &[JValue::Object(&jd), JValue::Long(time)])
300    .and_then(|v| v.z()).unwrap_or(false)
301}
302
303unsafe extern "C" fn srv_is_raining(_ctx: *mut c_void, dim: YogStr) -> bool {
304    let Some(mut env) = get_env() else { return false };
305    let Some(jd) = ys_to_java(&mut env, dim) else { return false };
306    env.call_static_method("dev/yog/NativeBridge", "worldIsRaining",
307        "(Ljava/lang/String;)Z", &[JValue::Object(&jd)])
308    .and_then(|v| v.z()).unwrap_or(false)
309}
310
311unsafe extern "C" fn srv_set_weather(_ctx: *mut c_void, dim: YogStr, raining: bool, dur: i32) -> bool {
312    let Some(mut env) = get_env() else { return false };
313    let Some(jd) = ys_to_java(&mut env, dim) else { return false };
314    env.call_static_method("dev/yog/NativeBridge", "worldSetWeather",
315        "(Ljava/lang/String;ZI)Z",
316        &[JValue::Object(&jd), JValue::Bool(raining as u8), JValue::Int(dur)])
317    .and_then(|v| v.z()).unwrap_or(false)
318}
319
320unsafe extern "C" fn srv_give_item(_ctx: *mut c_void, player: YogStr, item: YogStr, count: u32) -> bool {
321    let Some(mut env) = get_env() else { return false };
322    let (Some(jp), Some(ji)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, item)) else { return false };
323    env.call_static_method("dev/yog/NativeBridge", "giveItem",
324        "(Ljava/lang/String;Ljava/lang/String;I)Z",
325        &[JValue::Object(&jp), JValue::Object(&ji), JValue::Int(count as i32)])
326    .and_then(|v| v.z()).unwrap_or(false)
327}
328
329unsafe extern "C" fn srv_player_teleport(_ctx: *mut c_void, player: YogStr, pos: YogVec3) -> bool {
330    let Some(mut env) = get_env() else { return false };
331    let Some(jp) = ys_to_java(&mut env, player) else { return false };
332    env.call_static_method("dev/yog/NativeBridge", "teleport",
333        "(Ljava/lang/String;DDD)Z",
334        &[JValue::Object(&jp), JValue::Double(pos.x), JValue::Double(pos.y), JValue::Double(pos.z)])
335    .and_then(|v| v.z()).unwrap_or(false)
336}
337
338unsafe extern "C" fn srv_send_to_player(_ctx: *mut c_void, player: YogStr, channel: YogStr, data: *const u8, len: u32) -> bool {
339    let Some(mut env) = get_env() else { return false };
340    let (Some(jp), Some(jc)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, channel)) else { return false };
341    let payload = std::slice::from_raw_parts(data, len as usize);
342    let Ok(jdata) = env.byte_array_from_slice(payload) else { return false };
343    env.call_static_method("dev/yog/NativeBridge", "sendToPlayer",
344        "(Ljava/lang/String;Ljava/lang/String;[B)Z",
345        &[JValue::Object(&jp), JValue::Object(&jc), JValue::Object(&jdata)])
346    .and_then(|v| v.z()).unwrap_or(false)
347}
348
349unsafe extern "C" fn srv_send_to_server(_ctx: *mut c_void, channel: YogStr, data: *const u8, len: u32) -> bool {
350    let Some(mut env) = get_env() else { return false };
351    let Some(jc) = ys_to_java(&mut env, channel) else { return false };
352    let payload = std::slice::from_raw_parts(data, len as usize);
353    let Ok(jdata) = env.byte_array_from_slice(payload) else { return false };
354    let result = env.call_static_method("dev/yog/YogClient", "sendToServer",
355        "(Ljava/lang/String;[B)Z", &[JValue::Object(&jc), JValue::Object(&jdata)]);
356    let _ = env.exception_clear();
357    result.and_then(|v| v.z()).unwrap_or(false)
358}
359
360unsafe extern "C" fn srv_kick_player(_ctx: *mut c_void, player: YogStr, reason: YogStr) -> bool {
361    let Some(mut env) = get_env() else { return false };
362    let (Some(jp), Some(jr)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, reason)) else { return false };
363    env.call_static_method("dev/yog/NativeBridge", "kickPlayer",
364        "(Ljava/lang/String;Ljava/lang/String;)Z", &[JValue::Object(&jp), JValue::Object(&jr)])
365    .and_then(|v| v.z()).unwrap_or(false)
366}
367
368unsafe extern "C" fn srv_set_gamemode(_ctx: *mut c_void, player: YogStr, mode: YogStr) -> bool {
369    let Some(mut env) = get_env() else { return false };
370    let (Some(jp), Some(jg)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, mode)) else { return false };
371    env.call_static_method("dev/yog/NativeBridge", "setGamemode",
372        "(Ljava/lang/String;Ljava/lang/String;)Z", &[JValue::Object(&jp), JValue::Object(&jg)])
373    .and_then(|v| v.z()).unwrap_or(false)
374}
375
376unsafe extern "C" fn srv_send_title(_ctx: *mut c_void, player: YogStr, title: YogStr, sub: YogStr, fi: i32, stay: i32, fo: i32) -> bool {
377    let Some(mut env) = get_env() else { return false };
378    let (Some(jp), Some(jt), Some(js)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, title), ys_to_java(&mut env, sub)) else { return false };
379    env.call_static_method("dev/yog/NativeBridge", "sendTitle",
380        "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;III)Z",
381        &[JValue::Object(&jp), JValue::Object(&jt), JValue::Object(&js), JValue::Int(fi), JValue::Int(stay), JValue::Int(fo)])
382    .and_then(|v| v.z()).unwrap_or(false)
383}
384
385unsafe extern "C" fn srv_send_actionbar(_ctx: *mut c_void, player: YogStr, msg: YogStr) -> bool {
386    let Some(mut env) = get_env() else { return false };
387    let (Some(jp), Some(jm)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, msg)) else { return false };
388    env.call_static_method("dev/yog/NativeBridge", "sendActionbar",
389        "(Ljava/lang/String;Ljava/lang/String;)Z", &[JValue::Object(&jp), JValue::Object(&jm)])
390    .and_then(|v| v.z()).unwrap_or(false)
391}
392
393unsafe extern "C" fn srv_play_sound(_ctx: *mut c_void, dim: YogStr, pos: YogVec3, sound: YogStr, vol: f32, pitch: f32) -> bool {
394    let Some(mut env) = get_env() else { return false };
395    let (Some(jd), Some(js)) = (ys_to_java(&mut env, dim), ys_to_java(&mut env, sound)) else { return false };
396    env.call_static_method("dev/yog/NativeBridge", "playSound",
397        "(Ljava/lang/String;DDDLjava/lang/String;FF)Z",
398        &[JValue::Object(&jd), JValue::Double(pos.x), JValue::Double(pos.y), JValue::Double(pos.z), JValue::Object(&js), JValue::Float(vol), JValue::Float(pitch)])
399    .and_then(|v| v.z()).unwrap_or(false)
400}
401
402unsafe extern "C" fn srv_play_sound_player(_ctx: *mut c_void, player: YogStr, sound: YogStr, vol: f32, pitch: f32) -> bool {
403    let Some(mut env) = get_env() else { return false };
404    let (Some(jp), Some(js)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, sound)) else { return false };
405    env.call_static_method("dev/yog/NativeBridge", "playSoundToPlayer",
406        "(Ljava/lang/String;Ljava/lang/String;FF)Z",
407        &[JValue::Object(&jp), JValue::Object(&js), JValue::Float(vol), JValue::Float(pitch)])
408    .and_then(|v| v.z()).unwrap_or(false)
409}
410
411unsafe extern "C" fn srv_entity_teleport(_ctx: *mut c_void, uuid: YogStr, pos: YogVec3) -> bool {
412    let Some(mut env) = get_env() else { return false };
413    let Some(ju) = ys_to_java(&mut env, uuid) else { return false };
414    env.call_static_method("dev/yog/NativeBridge", "entityTeleport",
415        "(Ljava/lang/String;DDD)Z",
416        &[JValue::Object(&ju), JValue::Double(pos.x), JValue::Double(pos.y), JValue::Double(pos.z)])
417    .and_then(|v| v.z()).unwrap_or(false)
418}
419
420unsafe extern "C" fn srv_entity_rotation(_ctx: *mut c_void, uuid: YogStr, out: *mut YogVec3) -> bool {
421    let Some(mut env) = get_env() else { return false };
422    let Some(ju) = ys_to_java(&mut env, uuid) else { return false };
423    let ret = env.call_static_method("dev/yog/NativeBridge", "entityRotation",
424        "(Ljava/lang/String;)Ljava/lang/String;", &[JValue::Object(&ju)]);
425    let obj = match ret.and_then(|v| v.l()) { Ok(o) => o, Err(_) => { env.exception_clear().ok(); return false; } };
426    if obj.as_raw().is_null() { return false; }
427    let s: String = match env.get_string(&JString::from(obj)) { Ok(s) => String::from(s), Err(_) => return false };
428    let mut it = s.split('\t');
429    let (yaw, pitch) = (it.next(), it.next());
430    if let (Some(yaw), Some(pitch)) = (yaw.and_then(|v| v.parse().ok()), pitch.and_then(|v| v.parse().ok())) {
431        *out = YogVec3 { x: yaw, y: pitch, z: 0.0 }; true
432    } else { false }
433}
434
435unsafe extern "C" fn srv_entity_position(_ctx: *mut c_void, uuid: YogStr, out: *mut YogVec3) -> bool {
436    let Some(mut env) = get_env() else { return false };
437    let Some(ju) = ys_to_java(&mut env, uuid) else { return false };
438    let ret = env.call_static_method("dev/yog/NativeBridge", "entityPosition",
439        "(Ljava/lang/String;)Ljava/lang/String;", &[JValue::Object(&ju)]);
440    let obj = match ret.and_then(|v| v.l()) { Ok(o) => o, Err(_) => return false };
441    if obj.as_raw().is_null() { return false; }
442    let s: String = match env.get_string(&JString::from(obj)) { Ok(s) => String::from(s), Err(_) => return false };
443    let mut it = s.split('\t');
444    let (x, y, z) = (it.next(), it.next(), it.next());
445    if let (Some(x), Some(y), Some(z)) = (x.and_then(|v| v.parse().ok()), y.and_then(|v| v.parse().ok()), z.and_then(|v| v.parse().ok())) {
446        *out = YogVec3 { x, y, z }; true
447    } else { false }
448}
449
450unsafe extern "C" fn srv_entity_health(_ctx: *mut c_void, uuid: YogStr, out: *mut f32) -> bool {
451    let Some(mut env) = get_env() else { return false };
452    let Some(ju) = ys_to_java(&mut env, uuid) else { return false };
453    match env.call_static_method("dev/yog/NativeBridge", "entityHealth",
454        "(Ljava/lang/String;)D", &[JValue::Object(&ju)]).and_then(|v| v.d()) {
455        Ok(v) if !v.is_nan() => { *out = v as f32; true }
456        _ => false,
457    }
458}
459
460unsafe extern "C" fn srv_entity_set_health(_ctx: *mut c_void, uuid: YogStr, hp: f32) -> bool {
461    let Some(mut env) = get_env() else { return false };
462    let Some(ju) = ys_to_java(&mut env, uuid) else { return false };
463    env.call_static_method("dev/yog/NativeBridge", "entitySetHealth",
464        "(Ljava/lang/String;D)Z", &[JValue::Object(&ju), JValue::Double(hp as f64)])
465    .and_then(|v| v.z()).unwrap_or(false)
466}
467
468unsafe extern "C" fn srv_entity_kill(_ctx: *mut c_void, uuid: YogStr) -> bool {
469    let Some(mut env) = get_env() else { return false };
470    let Some(ju) = ys_to_java(&mut env, uuid) else { return false };
471    env.call_static_method("dev/yog/NativeBridge", "entityKill",
472        "(Ljava/lang/String;)Z", &[JValue::Object(&ju)])
473    .and_then(|v| v.z()).unwrap_or(false)
474}
475
476unsafe extern "C" fn srv_spawn_entity(_ctx: *mut c_void, type_id: YogStr, dim: YogStr, pos: YogVec3) -> YogOwnedStr {
477    let Some(mut env) = get_env() else { return YogOwnedStr::NONE };
478    let (Some(jt), Some(jd)) = (ys_to_java(&mut env, type_id), ys_to_java(&mut env, dim)) else { return YogOwnedStr::NONE };
479    let ret = env.call_static_method("dev/yog/NativeBridge", "spawnEntity",
480        "(Ljava/lang/String;Ljava/lang/String;DDD)Ljava/lang/String;",
481        &[JValue::Object(&jt), JValue::Object(&jd), JValue::Double(pos.x), JValue::Double(pos.y), JValue::Double(pos.z)]);
482    match ret.and_then(|v| v.l()) {
483        Ok(obj) => jstring_to_owned(&mut env, obj),
484        _ => YogOwnedStr::NONE,
485    }
486}
487
488unsafe extern "C" fn srv_entity_add_effect(_ctx: *mut c_void, uuid: YogStr, fx: YogStr, dur: i32, amp: u8, particles: bool) -> bool {
489    let Some(mut env) = get_env() else { return false };
490    let (Some(ju), Some(je)) = (ys_to_java(&mut env, uuid), ys_to_java(&mut env, fx)) else { return false };
491    env.call_static_method("dev/yog/NativeBridge", "entityAddEffect",
492        "(Ljava/lang/String;Ljava/lang/String;IIZ)Z",
493        &[JValue::Object(&ju), JValue::Object(&je), JValue::Int(dur), JValue::Int(amp as i32), JValue::Bool(particles as u8)])
494    .and_then(|v| v.z()).unwrap_or(false)
495}
496
497unsafe extern "C" fn srv_entity_remove_effect(_ctx: *mut c_void, uuid: YogStr, fx: YogStr) -> bool {
498    let Some(mut env) = get_env() else { return false };
499    let (Some(ju), Some(je)) = (ys_to_java(&mut env, uuid), ys_to_java(&mut env, fx)) else { return false };
500    env.call_static_method("dev/yog/NativeBridge", "entityRemoveEffect",
501        "(Ljava/lang/String;Ljava/lang/String;)Z", &[JValue::Object(&ju), JValue::Object(&je)])
502    .and_then(|v| v.z()).unwrap_or(false)
503}
504
505unsafe extern "C" fn srv_entity_clear_effects(_ctx: *mut c_void, uuid: YogStr) -> bool {
506    let Some(mut env) = get_env() else { return false };
507    let Some(ju) = ys_to_java(&mut env, uuid) else { return false };
508    env.call_static_method("dev/yog/NativeBridge", "entityClearEffects",
509        "(Ljava/lang/String;)Z", &[JValue::Object(&ju)])
510    .and_then(|v| v.z()).unwrap_or(false)
511}
512
513unsafe extern "C" fn srv_entity_velocity(_ctx: *mut c_void, uuid: YogStr, out: *mut YogVec3) -> bool {
514    let Some(mut env) = get_env() else { return false };
515    let Some(ju) = ys_to_java(&mut env, uuid) else { return false };
516    let ret = env.call_static_method("dev/yog/NativeBridge", "entityVelocity",
517        "(Ljava/lang/String;)Ljava/lang/String;", &[JValue::Object(&ju)]);
518    let obj = match ret.and_then(|v| v.l()) { Ok(o) => o, Err(_) => return false };
519    if obj.as_raw().is_null() { return false; }
520    let s: String = match env.get_string(&JString::from(obj)) { Ok(s) => String::from(s), Err(_) => return false };
521    let mut it = s.split('\t');
522    let (x, y, z) = (it.next(), it.next(), it.next());
523    if let (Some(x), Some(y), Some(z)) = (x.and_then(|v| v.parse().ok()), y.and_then(|v| v.parse().ok()), z.and_then(|v| v.parse().ok())) {
524        *out = YogVec3 { x, y, z }; true
525    } else { false }
526}
527
528unsafe extern "C" fn srv_entity_set_velocity(_ctx: *mut c_void, uuid: YogStr, vel: YogVec3) -> bool {
529    let Some(mut env) = get_env() else { return false };
530    let Some(ju) = ys_to_java(&mut env, uuid) else { return false };
531    env.call_static_method("dev/yog/NativeBridge", "entitySetVelocity",
532        "(Ljava/lang/String;DDD)Z",
533        &[JValue::Object(&ju), JValue::Double(vel.x), JValue::Double(vel.y), JValue::Double(vel.z)])
534    .and_then(|v| v.z()).unwrap_or(false)
535}
536
537unsafe extern "C" fn srv_entity_add_velocity(_ctx: *mut c_void, uuid: YogStr, vel: YogVec3) -> bool {
538    let Some(mut env) = get_env() else { return false };
539    let Some(ju) = ys_to_java(&mut env, uuid) else { return false };
540    env.call_static_method("dev/yog/NativeBridge", "entityAddVelocity",
541        "(Ljava/lang/String;DDD)Z",
542        &[JValue::Object(&ju), JValue::Double(vel.x), JValue::Double(vel.y), JValue::Double(vel.z)])
543    .and_then(|v| v.z()).unwrap_or(false)
544}
545
546unsafe extern "C" fn srv_has_item_tag(_ctx: *mut c_void, item: YogStr, tag: YogStr) -> bool {
547    let Some(mut env) = get_env() else { return false };
548    let (Some(ji), Some(jt)) = (ys_to_java(&mut env, item), ys_to_java(&mut env, tag)) else { return false };
549    env.call_static_method("dev/yog/NativeBridge", "hasItemTag",
550        "(Ljava/lang/String;Ljava/lang/String;)Z", &[JValue::Object(&ji), JValue::Object(&jt)])
551    .and_then(|v| v.z()).unwrap_or(false)
552}
553
554unsafe extern "C" fn srv_has_block_tag(_ctx: *mut c_void, block: YogStr, tag: YogStr) -> bool {
555    let Some(mut env) = get_env() else { return false };
556    let (Some(jb), Some(jt)) = (ys_to_java(&mut env, block), ys_to_java(&mut env, tag)) else { return false };
557    env.call_static_method("dev/yog/NativeBridge", "hasBlockTag",
558        "(Ljava/lang/String;Ljava/lang/String;)Z", &[JValue::Object(&jb), JValue::Object(&jt)])
559    .and_then(|v| v.z()).unwrap_or(false)
560}
561
562unsafe extern "C" fn srv_drop_loot(_ctx: *mut c_void, table: YogStr, dim: YogStr, pos: YogVec3) -> bool {
563    let Some(mut env) = get_env() else { return false };
564    let (Some(jt), Some(jd)) = (ys_to_java(&mut env, table), ys_to_java(&mut env, dim)) else { return false };
565    env.call_static_method("dev/yog/NativeBridge", "dropLoot",
566        "(Ljava/lang/String;Ljava/lang/String;DDD)Z",
567        &[JValue::Object(&jt), JValue::Object(&jd), JValue::Double(pos.x), JValue::Double(pos.y), JValue::Double(pos.z)])
568    .and_then(|v| v.z()).unwrap_or(false)
569}
570
571unsafe extern "C" fn srv_scoreboard_get(_ctx: *mut c_void, obj: YogStr, player: YogStr, out: *mut i32) -> bool {
572    let Some(mut env) = get_env() else { return false };
573    let (Some(jo), Some(jp)) = (ys_to_java(&mut env, obj), ys_to_java(&mut env, player)) else { return false };
574    match env.call_static_method("dev/yog/NativeBridge", "scoreboardGet",
575        "(Ljava/lang/String;Ljava/lang/String;)I", &[JValue::Object(&jo), JValue::Object(&jp)]).and_then(|v| v.i()) {
576        Ok(v) if v != i32::MIN => { *out = v; true }
577        _ => false,
578    }
579}
580
581unsafe extern "C" fn srv_scoreboard_set(_ctx: *mut c_void, obj: YogStr, player: YogStr, score: i32) -> bool {
582    let Some(mut env) = get_env() else { return false };
583    let (Some(jo), Some(jp)) = (ys_to_java(&mut env, obj), ys_to_java(&mut env, player)) else { return false };
584    env.call_static_method("dev/yog/NativeBridge", "scoreboardSet",
585        "(Ljava/lang/String;Ljava/lang/String;I)Z",
586        &[JValue::Object(&jo), JValue::Object(&jp), JValue::Int(score)])
587    .and_then(|v| v.z()).unwrap_or(false)
588}
589
590unsafe extern "C" fn srv_scoreboard_add(_ctx: *mut c_void, obj: YogStr, player: YogStr, delta: i32, out: *mut i32) -> bool {
591    let Some(mut env) = get_env() else { return false };
592    let (Some(jo), Some(jp)) = (ys_to_java(&mut env, obj), ys_to_java(&mut env, player)) else { return false };
593    match env.call_static_method("dev/yog/NativeBridge", "scoreboardAdd",
594        "(Ljava/lang/String;Ljava/lang/String;I)I",
595        &[JValue::Object(&jo), JValue::Object(&jp), JValue::Int(delta)]).and_then(|v| v.i()) {
596        Ok(v) if v != i32::MIN => { *out = v; true }
597        _ => false,
598    }
599}
600
601unsafe extern "C" fn srv_bossbar_create(_ctx: *mut c_void, id: YogStr, title: YogStr, color: YogStr, style: YogStr) -> bool {
602    let Some(mut env) = get_env() else { return false };
603    let (Some(ji), Some(jt), Some(jc), Some(js)) = (ys_to_java(&mut env, id), ys_to_java(&mut env, title), ys_to_java(&mut env, color), ys_to_java(&mut env, style)) else { return false };
604    env.call_static_method("dev/yog/NativeBridge", "bossbarCreate",
605        "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Z",
606        &[JValue::Object(&ji), JValue::Object(&jt), JValue::Object(&jc), JValue::Object(&js)])
607    .and_then(|v| v.z()).unwrap_or(false)
608}
609
610unsafe extern "C" fn srv_bossbar_remove(_ctx: *mut c_void, id: YogStr) -> bool {
611    let Some(mut env) = get_env() else { return false };
612    let Some(ji) = ys_to_java(&mut env, id) else { return false };
613    env.call_static_method("dev/yog/NativeBridge", "bossbarRemove",
614        "(Ljava/lang/String;)Z", &[JValue::Object(&ji)])
615    .and_then(|v| v.z()).unwrap_or(false)
616}
617
618unsafe extern "C" fn srv_bossbar_set_title(_ctx: *mut c_void, id: YogStr, title: YogStr) -> bool {
619    let Some(mut env) = get_env() else { return false };
620    let (Some(ji), Some(jt)) = (ys_to_java(&mut env, id), ys_to_java(&mut env, title)) else { return false };
621    env.call_static_method("dev/yog/NativeBridge", "bossbarSetTitle",
622        "(Ljava/lang/String;Ljava/lang/String;)Z", &[JValue::Object(&ji), JValue::Object(&jt)])
623    .and_then(|v| v.z()).unwrap_or(false)
624}
625
626unsafe extern "C" fn srv_bossbar_set_progress(_ctx: *mut c_void, id: YogStr, progress: f32) -> bool {
627    let Some(mut env) = get_env() else { return false };
628    let Some(ji) = ys_to_java(&mut env, id) else { return false };
629    env.call_static_method("dev/yog/NativeBridge", "bossbarSetProgress",
630        "(Ljava/lang/String;F)Z", &[JValue::Object(&ji), JValue::Float(progress)])
631    .and_then(|v| v.z()).unwrap_or(false)
632}
633
634unsafe extern "C" fn srv_bossbar_set_color(_ctx: *mut c_void, id: YogStr, color: YogStr) -> bool {
635    let Some(mut env) = get_env() else { return false };
636    let (Some(ji), Some(jc)) = (ys_to_java(&mut env, id), ys_to_java(&mut env, color)) else { return false };
637    env.call_static_method("dev/yog/NativeBridge", "bossbarSetColor",
638        "(Ljava/lang/String;Ljava/lang/String;)Z", &[JValue::Object(&ji), JValue::Object(&jc)])
639    .and_then(|v| v.z()).unwrap_or(false)
640}
641
642unsafe extern "C" fn srv_bossbar_add_player(_ctx: *mut c_void, id: YogStr, player: YogStr) -> bool {
643    let Some(mut env) = get_env() else { return false };
644    let (Some(ji), Some(jp)) = (ys_to_java(&mut env, id), ys_to_java(&mut env, player)) else { return false };
645    env.call_static_method("dev/yog/NativeBridge", "bossbarAddPlayer",
646        "(Ljava/lang/String;Ljava/lang/String;)Z", &[JValue::Object(&ji), JValue::Object(&jp)])
647    .and_then(|v| v.z()).unwrap_or(false)
648}
649
650unsafe extern "C" fn srv_bossbar_remove_player(_ctx: *mut c_void, id: YogStr, player: YogStr) -> bool {
651    let Some(mut env) = get_env() else { return false };
652    let (Some(ji), Some(jp)) = (ys_to_java(&mut env, id), ys_to_java(&mut env, player)) else { return false };
653    env.call_static_method("dev/yog/NativeBridge", "bossbarRemovePlayer",
654        "(Ljava/lang/String;Ljava/lang/String;)Z", &[JValue::Object(&ji), JValue::Object(&jp)])
655    .and_then(|v| v.z()).unwrap_or(false)
656}
657
658unsafe extern "C" fn srv_bossbar_set_visible(_ctx: *mut c_void, id: YogStr, visible: bool) -> bool {
659    let Some(mut env) = get_env() else { return false };
660    let Some(ji) = ys_to_java(&mut env, id) else { return false };
661    env.call_static_method("dev/yog/NativeBridge", "bossbarSetVisible",
662        "(Ljava/lang/String;Z)Z", &[JValue::Object(&ji), JValue::Bool(visible as u8)])
663    .and_then(|v| v.z()).unwrap_or(false)
664}
665
666unsafe extern "C" fn srv_get_block_nbt(_ctx: *mut c_void, dim: YogStr, pos: YogBlockPos) -> YogOwnedStr {
667    let Some(mut env) = get_env() else { return YogOwnedStr::NONE };
668    let Some(jd) = ys_to_java(&mut env, dim) else { return YogOwnedStr::NONE };
669    let ret = env.call_static_method("dev/yog/NativeBridge", "getBlockNbt",
670        "(Ljava/lang/String;III)Ljava/lang/String;",
671        &[JValue::Object(&jd), JValue::Int(pos.x), JValue::Int(pos.y), JValue::Int(pos.z)]);
672    match ret.and_then(|v| v.l()) {
673        Ok(obj) => jstring_to_owned(&mut env, obj),
674        _ => YogOwnedStr::NONE,
675    }
676}
677
678unsafe extern "C" fn srv_set_block_nbt(_ctx: *mut c_void, dim: YogStr, pos: YogBlockPos, snbt: YogStr) -> bool {
679    let Some(mut env) = get_env() else { return false };
680    let (Some(jd), Some(js)) = (ys_to_java(&mut env, dim), ys_to_java(&mut env, snbt)) else { return false };
681    env.call_static_method("dev/yog/NativeBridge", "setBlockNbt",
682        "(Ljava/lang/String;IIILjava/lang/String;)Z",
683        &[JValue::Object(&jd), JValue::Int(pos.x), JValue::Int(pos.y), JValue::Int(pos.z), JValue::Object(&js)])
684    .and_then(|v| v.z()).unwrap_or(false)
685}
686
687unsafe extern "C" fn srv_get_inventory_slot(_ctx: *mut c_void, dim: YogStr, pos: yog_abi::YogBlockPos, slot: u32) -> YogOwnedStr {
688    let Some(mut env) = get_env() else { return YogOwnedStr::NONE };
689    let Some(jd) = ys_to_java(&mut env, dim) else { return YogOwnedStr::NONE };
690    let ret = env.call_static_method("dev/yog/NativeBridge", "getInventorySlot",
691        "(Ljava/lang/String;IIII)Ljava/lang/String;",
692        &[JValue::Object(&jd), JValue::Int(pos.x), JValue::Int(pos.y), JValue::Int(pos.z), JValue::Int(slot as i32)]);
693    match ret.and_then(|v| v.l()) {
694        Ok(obj) => jstring_to_owned(&mut env, obj),
695        _ => YogOwnedStr::NONE,
696    }
697}
698
699unsafe extern "C" fn srv_set_inventory_slot(_ctx: *mut c_void, dim: YogStr, pos: yog_abi::YogBlockPos, slot: u32, item_id: YogStr, count: u32) -> bool {
700    let Some(mut env) = get_env() else { return false };
701    let (Some(jd), Some(ji)) = (ys_to_java(&mut env, dim), ys_to_java(&mut env, item_id)) else { return false };
702    env.call_static_method("dev/yog/NativeBridge", "setInventorySlot",
703        "(Ljava/lang/String;IIIILjava/lang/String;I)Z",
704        &[JValue::Object(&jd), JValue::Int(pos.x), JValue::Int(pos.y), JValue::Int(pos.z),
705          JValue::Int(slot as i32), JValue::Object(&ji), JValue::Int(count as i32)])
706    .and_then(|v| v.z()).unwrap_or(false)
707}
708
709unsafe extern "C" fn srv_player_inventory(_ctx: *mut c_void, player: YogStr) -> YogOwnedStr {
710    let Some(mut env) = get_env() else { return YogOwnedStr::NONE };
711    let Some(jp) = ys_to_java(&mut env, player) else { return YogOwnedStr::NONE };
712    let ret = env.call_static_method("dev/yog/NativeBridge", "playerInventory",
713        "(Ljava/lang/String;)Ljava/lang/String;", &[JValue::Object(&jp)]);
714    match ret.and_then(|v| v.l()) {
715        Ok(obj) => jstring_to_owned(&mut env, obj),
716        _ => YogOwnedStr::NONE,
717    }
718}
719
720unsafe extern "C" fn srv_player_set_slot(_ctx: *mut c_void, player: YogStr, slot: u32, item_id: YogStr, count: u32) -> bool {
721    let Some(mut env) = get_env() else { return false };
722    let (Some(jp), Some(ji)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, item_id)) else { return false };
723    env.call_static_method("dev/yog/NativeBridge", "playerSetSlot",
724        "(Ljava/lang/String;ILjava/lang/String;I)Z",
725        &[JValue::Object(&jp), JValue::Int(slot as i32), JValue::Object(&ji), JValue::Int(count as i32)])
726    .and_then(|v| v.z()).unwrap_or(false)
727}
728
729unsafe extern "C" fn srv_player_teleport_dim(_ctx: *mut c_void, player: YogStr, dim: YogStr, pos: YogVec3) -> bool {
730    let Some(mut env) = get_env() else { return false };
731    let (Some(jp), Some(jd)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, dim)) else { return false };
732    env.call_static_method("dev/yog/NativeBridge", "teleportToDim",
733        "(Ljava/lang/String;Ljava/lang/String;DDD)Z",
734        &[JValue::Object(&jp), JValue::Object(&jd), JValue::Double(pos.x), JValue::Double(pos.y), JValue::Double(pos.z)])
735    .and_then(|v| v.z()).unwrap_or(false)
736}
737
738unsafe extern "C" fn srv_entity_teleport_dim(_ctx: *mut c_void, uuid: YogStr, dim: YogStr, pos: YogVec3) -> bool {
739    let Some(mut env) = get_env() else { return false };
740    let (Some(ju), Some(jd)) = (ys_to_java(&mut env, uuid), ys_to_java(&mut env, dim)) else { return false };
741    env.call_static_method("dev/yog/NativeBridge", "entityTeleportToDim",
742        "(Ljava/lang/String;Ljava/lang/String;DDD)Z",
743        &[JValue::Object(&ju), JValue::Object(&jd), JValue::Double(pos.x), JValue::Double(pos.y), JValue::Double(pos.z)])
744    .and_then(|v| v.z()).unwrap_or(false)
745}
746
747unsafe extern "C" fn srv_online_players(_ctx: *mut c_void) -> YogOwnedStr {
748    let Some(mut env) = get_env() else { return YogOwnedStr::NONE };
749    let ret = env.call_static_method("dev/yog/NativeBridge", "onlinePlayers",
750        "()Ljava/lang/String;", &[]);
751    match ret.and_then(|v| v.l()) {
752        Ok(obj) => jstring_to_owned(&mut env, obj),
753        _ => YogOwnedStr::NONE,
754    }
755}
756
757unsafe extern "C" fn srv_world_entity_count(_ctx: *mut c_void, dim: YogStr, entity_type: YogStr) -> i32 {
758    let Some(mut env) = get_env() else { return -1 };
759    let d = dim.as_str();
760    let et = entity_type.as_str();
761    let jd  = match env.new_string(d)  { Ok(s) => s, Err(_) => return -1 };
762    let jet = match env.new_string(et) { Ok(s) => s, Err(_) => return -1 };
763    let ret = env.call_static_method("dev/yog/NativeBridge", "worldEntityCount",
764        "(Ljava/lang/String;Ljava/lang/String;)I",
765        &[JValue::Object(&jd), JValue::Object(&jet)]);
766    match ret.and_then(|v| v.i()) {
767        Ok(n) => n,
768        _ => -1,
769    }
770}
771
772unsafe extern "C" fn srv_game_dir(_ctx: *mut c_void) -> YogOwnedStr {
773    let Some(mut env) = get_env() else { return YogOwnedStr::NONE };
774    let ret = env.call_static_method("dev/yog/NativeBridge", "gameDir",
775        "()Ljava/lang/String;", &[]);
776    match ret.and_then(|v| v.l()) {
777        Ok(obj) => jstring_to_owned(&mut env, obj),
778        _ => YogOwnedStr::NONE,
779    }
780}
781
782unsafe extern "C" fn srv_entity_get_nbt(_ctx: *mut c_void, uuid: YogStr) -> YogOwnedStr {
783    let Some(mut env) = get_env() else { return YogOwnedStr::NONE };
784    let Some(ju) = ys_to_java(&mut env, uuid) else { return YogOwnedStr::NONE };
785    let ret = env.call_static_method("dev/yog/NativeBridge", "entityGetNbt",
786        "(Ljava/lang/String;)Ljava/lang/String;", &[JValue::Object(&ju)]);
787    match ret.and_then(|v| v.l()) {
788        Ok(obj) => jstring_to_owned(&mut env, obj),
789        _ => YogOwnedStr::NONE,
790    }
791}
792
793unsafe extern "C" fn srv_entity_set_nbt(_ctx: *mut c_void, uuid: YogStr, snbt: YogStr) -> bool {
794    let Some(mut env) = get_env() else { return false };
795    let (Some(ju), Some(js)) = (ys_to_java(&mut env, uuid), ys_to_java(&mut env, snbt)) else { return false };
796    env.call_static_method("dev/yog/NativeBridge", "entitySetNbt",
797        "(Ljava/lang/String;Ljava/lang/String;)Z", &[JValue::Object(&ju), JValue::Object(&js)])
798    .and_then(|v| v.z()).unwrap_or(false)
799}
800
801unsafe extern "C" fn srv_spawn_particles(
802    _ctx: *mut c_void, dim: YogStr, pos: YogVec3, particle_type: YogStr,
803    count: i32, dx: f64, dy: f64, dz: f64, speed: f64,
804) -> bool {
805    let Some(mut env) = get_env() else { return false };
806    let (Some(jd), Some(jp)) = (ys_to_java(&mut env, dim), ys_to_java(&mut env, particle_type)) else { return false };
807    env.call_static_method("dev/yog/NativeBridge", "spawnParticles",
808        "(Ljava/lang/String;DDDLjava/lang/String;IDDDD)Z",
809        &[JValue::Object(&jd), JValue::Double(pos.x), JValue::Double(pos.y), JValue::Double(pos.z),
810          JValue::Object(&jp), JValue::Int(count),
811          JValue::Double(dx), JValue::Double(dy), JValue::Double(dz), JValue::Double(speed)])
812    .and_then(|v| v.z()).unwrap_or(false)
813}
814
815unsafe extern "C" fn srv_entity_attribute_get(_ctx: *mut c_void, uuid: YogStr, attr: YogStr) -> f64 {
816    let Some(mut env) = get_env() else { return f64::NAN };
817    let (Some(ju), Some(ja)) = (ys_to_java(&mut env, uuid), ys_to_java(&mut env, attr)) else { return f64::NAN };
818    env.call_static_method("dev/yog/NativeBridge", "entityAttributeGet",
819        "(Ljava/lang/String;Ljava/lang/String;)D", &[JValue::Object(&ju), JValue::Object(&ja)])
820    .and_then(|v| v.d()).unwrap_or(f64::NAN)
821}
822
823unsafe extern "C" fn srv_entity_attribute_set(_ctx: *mut c_void, uuid: YogStr, attr: YogStr, value: f64) -> bool {
824    let Some(mut env) = get_env() else { return false };
825    let (Some(ju), Some(ja)) = (ys_to_java(&mut env, uuid), ys_to_java(&mut env, attr)) else { return false };
826    env.call_static_method("dev/yog/NativeBridge", "entityAttributeSet",
827        "(Ljava/lang/String;Ljava/lang/String;D)Z",
828        &[JValue::Object(&ju), JValue::Object(&ja), JValue::Double(value)])
829    .and_then(|v| v.z()).unwrap_or(false)
830}
831
832unsafe extern "C" fn srv_get_held_item_nbt(_ctx: *mut c_void, player: YogStr) -> YogOwnedStr {
833    let Some(mut env) = get_env() else { return YogOwnedStr::NONE };
834    let Some(jp) = ys_to_java(&mut env, player) else { return YogOwnedStr::NONE };
835    let ret = env.call_static_method("dev/yog/NativeBridge", "getHeldItemNbt",
836        "(Ljava/lang/String;)Ljava/lang/String;", &[JValue::Object(&jp)]);
837    match ret.and_then(|v| v.l()) {
838        Ok(obj) => jstring_to_owned(&mut env, obj),
839        _ => YogOwnedStr::NONE,
840    }
841}
842
843unsafe extern "C" fn srv_set_held_item_nbt(_ctx: *mut c_void, player: YogStr, snbt: YogStr) -> bool {
844    let Some(mut env) = get_env() else { return false };
845    let (Some(jp), Some(js)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, snbt)) else { return false };
846    env.call_static_method("dev/yog/NativeBridge", "setHeldItemNbt",
847        "(Ljava/lang/String;Ljava/lang/String;)Z", &[JValue::Object(&jp), JValue::Object(&js)])
848    .and_then(|v| v.z()).unwrap_or(false)
849}
850
851unsafe extern "C" fn srv_get_offhand_item_nbt(_ctx: *mut c_void, player: YogStr) -> YogOwnedStr {
852    let Some(mut env) = get_env() else { return YogOwnedStr::NONE };
853    let Some(jp) = ys_to_java(&mut env, player) else { return YogOwnedStr::NONE };
854    let ret = env.call_static_method("dev/yog/NativeBridge", "getOffhandItemNbt",
855        "(Ljava/lang/String;)Ljava/lang/String;", &[JValue::Object(&jp)]);
856    match ret.and_then(|v| v.l()) {
857        Ok(obj) => jstring_to_owned(&mut env, obj),
858        _ => YogOwnedStr::NONE,
859    }
860}
861
862unsafe extern "C" fn srv_set_offhand_item_nbt(_ctx: *mut c_void, player: YogStr, snbt: YogStr) -> bool {
863    let Some(mut env) = get_env() else { return false };
864    let (Some(jp), Some(js)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, snbt)) else { return false };
865    env.call_static_method("dev/yog/NativeBridge", "setOffhandItemNbt",
866        "(Ljava/lang/String;Ljava/lang/String;)Z", &[JValue::Object(&jp), JValue::Object(&js)])
867    .and_then(|v| v.z()).unwrap_or(false)
868}
869
870unsafe extern "C" fn srv_get_slot_item(_ctx: *mut c_void, player: YogStr, slot: u32) -> YogOwnedStr {
871    let Some(mut env) = get_env() else { return YogOwnedStr::NONE };
872    let Some(jp) = ys_to_java(&mut env, player) else { return YogOwnedStr::NONE };
873    let ret = env.call_static_method("dev/yog/NativeBridge", "getSlotItem",
874        "(Ljava/lang/String;I)Ljava/lang/String;",
875        &[JValue::Object(&jp), JValue::Int(slot as i32)]);
876    match ret.and_then(|v| v.l()) {
877        Ok(obj) => jstring_to_owned(&mut env, obj),
878        _ => YogOwnedStr::NONE,
879    }
880}
881
882unsafe extern "C" fn srv_set_slot_item(
883    _ctx: *mut c_void, player: YogStr, slot: u32,
884    item_id: YogStr, count: u32, snbt: YogStr,
885) -> bool {
886    let Some(mut env) = get_env() else { return false };
887    let (Some(jp), Some(ji), Some(js)) = (
888        ys_to_java(&mut env, player), ys_to_java(&mut env, item_id), ys_to_java(&mut env, snbt)
889    ) else { return false };
890    env.call_static_method("dev/yog/NativeBridge", "setSlotItem",
891        "(Ljava/lang/String;ILjava/lang/String;ILjava/lang/String;)Z",
892        &[JValue::Object(&jp), JValue::Int(slot as i32), JValue::Object(&ji), JValue::Int(count as i32), JValue::Object(&js)])
893    .and_then(|v| v.z()).unwrap_or(false)
894}
895
896// ── ABI minor 14 — low-level GPU pipeline ────────────────────────────────────
897//
898// All raw GL calls go through `glow::Context` stored in GL.
899// `draw2d_*` functions still call JNI (NativeDraw) for MC text/texture rendering.
900// Everything is called on the render thread — no synchronization needed.
901
902// ── helpers ───────────────────────────────────────────────────────────────────
903
904fn gl_draw_mode(mode: u8) -> u32 {
905    match mode {
906        1 => glow::LINES,
907        2 => glow::LINE_STRIP,
908        3 => glow::TRIANGLE_STRIP,
909        4 => glow::TRIANGLE_FAN,
910        _ => glow::TRIANGLES,
911    }
912}
913
914fn gl_attr_type(dtype: u8) -> u32 {
915    match dtype {
916        1 => glow::UNSIGNED_BYTE,
917        2 => glow::INT,
918        3 => glow::UNSIGNED_INT,
919        _ => glow::FLOAT,
920    }
921}
922
923unsafe fn compile_shader(gl: &glow::Context, stage: u32, src: &str) -> Option<glow::NativeShader> {
924    let sh = gl.create_shader(stage).ok()?;
925    gl.shader_source(sh, src);
926    gl.compile_shader(sh);
927    if !gl.get_shader_compile_status(sh) {
928        yog_logging::error!("yog-gfx shader compile: {}", gl.get_shader_info_log(sh));
929        gl.delete_shader(sh);
930        return None;
931    }
932    Some(sh)
933}
934
935// ── GPU buffers ───────────────────────────────────────────────────────────────
936
937unsafe extern "C" fn gfx_buf_create() -> u32 {
938    let Some(g) = GL.get() else { return 0 };
939    g.0.create_buffer().map(|b| b.0.get()).unwrap_or(0)
940}
941
942unsafe extern "C" fn gfx_buf_delete(handle: u32) {
943    let Some(g) = GL.get() else { return };
944    let Some(n) = NonZeroU32::new(handle) else { return };
945    g.0.delete_buffer(glow::NativeBuffer(n));
946}
947
948unsafe extern "C" fn gfx_buf_data(handle: u32, bytes: *const u8, len: u32, dynamic: bool) {
949    let Some(g) = GL.get() else { return };
950    let Some(n) = NonZeroU32::new(handle) else { return };
951    let gl = &g.0;
952    let data = std::slice::from_raw_parts(bytes, len as usize);
953    let usage = if dynamic { glow::DYNAMIC_DRAW } else { glow::STATIC_DRAW };
954    gl.bind_buffer(glow::ARRAY_BUFFER, Some(glow::NativeBuffer(n)));
955    gl.buffer_data_u8_slice(glow::ARRAY_BUFFER, data, usage);
956    gl.bind_buffer(glow::ARRAY_BUFFER, None);
957}
958
959unsafe extern "C" fn gfx_buf_subdata(handle: u32, offset: u32, bytes: *const u8, len: u32) {
960    let Some(g) = GL.get() else { return };
961    let Some(n) = NonZeroU32::new(handle) else { return };
962    let gl = &g.0;
963    let data = std::slice::from_raw_parts(bytes, len as usize);
964    gl.bind_buffer(glow::ARRAY_BUFFER, Some(glow::NativeBuffer(n)));
965    gl.buffer_sub_data_u8_slice(glow::ARRAY_BUFFER, offset as i32, data);
966    gl.bind_buffer(glow::ARRAY_BUFFER, None);
967}
968
969// ── Vertex arrays ─────────────────────────────────────────────────────────────
970
971unsafe extern "C" fn gfx_vao_create() -> u32 {
972    let Some(g) = GL.get() else { return 0 };
973    g.0.create_vertex_array().map(|v| v.0.get()).unwrap_or(0)
974}
975
976unsafe extern "C" fn gfx_vao_delete(handle: u32) {
977    let Some(g) = GL.get() else { return };
978    let Some(n) = NonZeroU32::new(handle) else { return };
979    g.0.delete_vertex_array(glow::NativeVertexArray(n));
980}
981
982unsafe extern "C" fn gfx_vao_attrib(
983    vao: u32, vbo: u32, index: u32, components: u8,
984    dtype: u8, normalized: bool, stride: u32, offset: u32,
985) {
986    let Some(g) = GL.get() else { return };
987    let (Some(vn), Some(bn)) = (NonZeroU32::new(vao), NonZeroU32::new(vbo)) else { return };
988    let gl = &g.0;
989    gl.bind_vertex_array(Some(glow::NativeVertexArray(vn)));
990    gl.bind_buffer(glow::ARRAY_BUFFER, Some(glow::NativeBuffer(bn)));
991    let gl_type = gl_attr_type(dtype);
992    if dtype == 2 || dtype == 3 {
993        gl.vertex_attrib_pointer_i32(index, components as i32, gl_type, stride as i32, offset as i32);
994    } else {
995        gl.vertex_attrib_pointer_f32(index, components as i32, gl_type, normalized, stride as i32, offset as i32);
996    }
997    gl.enable_vertex_attrib_array(index);
998    gl.bind_vertex_array(None);
999}
1000
1001unsafe extern "C" fn gfx_vao_set_ebo(vao: u32, ebo: u32) {
1002    let Some(g) = GL.get() else { return };
1003    let (Some(vn), Some(en)) = (NonZeroU32::new(vao), NonZeroU32::new(ebo)) else { return };
1004    let gl = &g.0;
1005    gl.bind_vertex_array(Some(glow::NativeVertexArray(vn)));
1006    gl.bind_buffer(glow::ELEMENT_ARRAY_BUFFER, Some(glow::NativeBuffer(en)));
1007    gl.bind_vertex_array(None);
1008}
1009
1010// ── Shader programs ───────────────────────────────────────────────────────────
1011
1012/// Returns a path under `~/.cache/yog/shaders/<hash>.ysc` for the given GLSL source pair,
1013/// creating the directory if needed.  Returns `None` if the home directory is unknown.
1014fn shader_cache_path(vert: &str, frag: &str) -> Option<PathBuf> {
1015    use std::hash::{Hash, Hasher};
1016    let mut h = std::collections::hash_map::DefaultHasher::new();
1017    vert.hash(&mut h);
1018    frag.hash(&mut h);
1019    let hash = h.finish();
1020    let dir = std::env::var("HOME")
1021        .map(|home| PathBuf::from(home).join(".cache").join("yog").join("shaders"))
1022        .ok()?;
1023    std::fs::create_dir_all(&dir).ok()?;
1024    Some(dir.join(format!("{hash:016x}.ysc")))
1025}
1026
1027/// Try restoring a program from a binary blob (`[4 LE bytes: GL format][binary…]`).
1028/// Returns `Some(handle)` if the driver accepts the binary, `None` otherwise.
1029///
1030/// Uses `glProgramBinary` (GL 4.1 / ARB_get_program_binary) via the raw pointer
1031/// captured in `nativeGlInit`.  Returns `None` if the extension is unavailable.
1032unsafe fn load_shader_binary(gl: &glow::Context, data: &[u8]) -> Option<glow::NativeProgram> {
1033    if data.len() < 4 { return None; }
1034    type ProgramBinaryFn = unsafe extern "system" fn(u32, u32, *const c_void, i32);
1035    let fn_ptr = (*GL_PROGRAM_BINARY.get()?)?;
1036    let program_binary: ProgramBinaryFn = std::mem::transmute(fn_ptr);
1037
1038    let fmt = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
1039    let prog = gl.create_program().ok()?;
1040    program_binary(prog.0.get(), fmt, data[4..].as_ptr() as *const c_void, (data.len() - 4) as i32);
1041    if gl.get_program_link_status(prog) { Some(prog) } else { gl.delete_program(prog); None }
1042}
1043
1044/// Read the compiled binary of a linked program.  Returns empty `Vec` if unsupported.
1045unsafe fn get_shader_binary(prog: glow::NativeProgram) -> (Vec<u8>, u32) {
1046    type GetProgramivFn       = unsafe extern "system" fn(u32, u32, *mut i32);
1047    type GetProgramBinaryFn   = unsafe extern "system" fn(u32, i32, *mut i32, *mut u32, *mut c_void);
1048
1049    let Some(get_iv_raw)  = GL_GET_PROGRAM_IV.get().and_then(|v| *v) else { return (vec![], 0) };
1050    let Some(get_bin_raw) = GL_GET_PROGRAM_BINARY.get().and_then(|v| *v) else { return (vec![], 0) };
1051    let get_program_iv:     GetProgramivFn       = std::mem::transmute(get_iv_raw);
1052    let get_program_binary: GetProgramBinaryFn   = std::mem::transmute(get_bin_raw);
1053
1054    // Query binary size via glGetProgramiv(GL_PROGRAM_BINARY_LENGTH).
1055    const PROGRAM_BINARY_LENGTH: u32 = 0x8741;
1056    let mut size: i32 = 0;
1057    get_program_iv(prog.0.get(), PROGRAM_BINARY_LENGTH, &mut size);
1058    if size <= 0 { return (vec![], 0); }
1059
1060    let mut buf = vec![0u8; size as usize];
1061    let mut actual_len: i32 = 0;
1062    let mut fmt: u32 = 0;
1063    get_program_binary(prog.0.get(), size, &mut actual_len, &mut fmt, buf.as_mut_ptr() as *mut c_void);
1064    buf.truncate(actual_len.max(0) as usize);
1065    (buf, fmt)
1066}
1067
1068unsafe extern "C" fn gfx_prog_create(vert: YogStr, frag: YogStr, out: *mut u32) -> bool {
1069    let Some(g) = GL.get() else { return false };
1070    let gl = &g.0;
1071    let vert_s = vert.as_str();
1072    let frag_s = frag.as_str();
1073
1074    // Fast path: binary shader cache — avoids GLSL re-compilation on subsequent launches.
1075    let cache_path = shader_cache_path(vert_s, frag_s);
1076    if let Some(ref path) = cache_path {
1077        if let Ok(data) = std::fs::read(path) {
1078            if let Some(prog) = load_shader_binary(gl, &data) {
1079                *out = prog.0.get();
1080                return true;
1081            }
1082            // Cache stale (driver updated?); remove and fall through to GLSL compile.
1083            let _ = std::fs::remove_file(path);
1084        }
1085    }
1086
1087    // GLSL compile path.
1088    let vs = match compile_shader(gl, glow::VERTEX_SHADER, vert_s) {
1089        Some(s) => s,
1090        None => return false,
1091    };
1092    let fs = match compile_shader(gl, glow::FRAGMENT_SHADER, frag_s) {
1093        Some(s) => s,
1094        None => { gl.delete_shader(vs); return false; }
1095    };
1096    let prog = match gl.create_program() {
1097        Ok(p) => p,
1098        Err(e) => {
1099            yog_logging::error!("yog-gfx: create_program: {}", e);
1100            gl.delete_shader(vs); gl.delete_shader(fs);
1101            return false;
1102        }
1103    };
1104    gl.attach_shader(prog, vs);
1105    gl.attach_shader(prog, fs);
1106    gl.link_program(prog);
1107    gl.detach_shader(prog, vs);
1108    gl.detach_shader(prog, fs);
1109    gl.delete_shader(vs);
1110    gl.delete_shader(fs);
1111    if !gl.get_program_link_status(prog) {
1112        yog_logging::error!("yog-gfx: shader link: {}", gl.get_program_info_log(prog));
1113        gl.delete_program(prog);
1114        return false;
1115    }
1116
1117    // Persist binary so the next launch skips GLSL compilation entirely.
1118    if let Some(ref path) = cache_path {
1119        let (binary, fmt) = get_shader_binary(prog);
1120        if !binary.is_empty() {
1121            let mut blob = fmt.to_le_bytes().to_vec();
1122            blob.extend_from_slice(&binary);
1123            let _ = std::fs::write(path, &blob);
1124        }
1125    }
1126
1127    *out = prog.0.get();
1128    true
1129}
1130
1131unsafe extern "C" fn gfx_prog_delete(handle: u32) {
1132    let Some(g) = GL.get() else { return };
1133    let Some(n) = NonZeroU32::new(handle) else { return };
1134    g.0.delete_program(glow::NativeProgram(n));
1135}
1136
1137macro_rules! with_prog {
1138    ($handle:expr, |$gl:ident, $prog:ident, $loc:ident ($name:expr)| $body:expr) => {{
1139        let Some(g) = GL.get() else { return };
1140        let Some(n) = NonZeroU32::new($handle) else { return };
1141        let $gl = &g.0;
1142        let $prog = glow::NativeProgram(n);
1143        $gl.use_program(Some($prog));
1144        let $loc = $gl.get_uniform_location($prog, $name.as_str());
1145        $body
1146    }};
1147}
1148
1149unsafe extern "C" fn gfx_prog_uniform_1i(prog: u32, name: YogStr, v: i32) {
1150    with_prog!(prog, |gl, _p, loc(name)| gl.uniform_1_i32(loc.as_ref(), v));
1151}
1152unsafe extern "C" fn gfx_prog_uniform_1f(prog: u32, name: YogStr, v: f32) {
1153    with_prog!(prog, |gl, _p, loc(name)| gl.uniform_1_f32(loc.as_ref(), v));
1154}
1155unsafe extern "C" fn gfx_prog_uniform_2f(prog: u32, name: YogStr, x: f32, y: f32) {
1156    with_prog!(prog, |gl, _p, loc(name)| gl.uniform_2_f32(loc.as_ref(), x, y));
1157}
1158unsafe extern "C" fn gfx_prog_uniform_3f(prog: u32, name: YogStr, x: f32, y: f32, z: f32) {
1159    with_prog!(prog, |gl, _p, loc(name)| gl.uniform_3_f32(loc.as_ref(), x, y, z));
1160}
1161unsafe extern "C" fn gfx_prog_uniform_4f(prog: u32, name: YogStr, x: f32, y: f32, z: f32, w: f32) {
1162    with_prog!(prog, |gl, _p, loc(name)| gl.uniform_4_f32(loc.as_ref(), x, y, z, w));
1163}
1164unsafe extern "C" fn gfx_prog_uniform_mat4(prog: u32, name: YogStr, col_major: *const f32) {
1165    with_prog!(prog, |gl, _p, loc(name)| {
1166        let data = std::slice::from_raw_parts(col_major, 16);
1167        gl.uniform_matrix_4_f32_slice(loc.as_ref(), false, data);
1168    });
1169}
1170
1171// ── Textures ──────────────────────────────────────────────────────────────────
1172
1173unsafe extern "C" fn gfx_tex_create(w: u32, h: u32, rgba: *const u8, linear: bool) -> u32 {
1174    let Some(g) = GL.get() else { return 0 };
1175    let gl = &g.0;
1176    let tex = match gl.create_texture() { Ok(t) => t, Err(_) => return 0 };
1177    gl.bind_texture(glow::TEXTURE_2D, Some(tex));
1178    let filter = if linear { glow::LINEAR } else { glow::NEAREST };
1179    gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MIN_FILTER, filter as i32);
1180    gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MAG_FILTER, filter as i32);
1181    gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_S, glow::CLAMP_TO_EDGE as i32);
1182    gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_T, glow::CLAMP_TO_EDGE as i32);
1183    let pixels = std::slice::from_raw_parts(rgba, (w * h * 4) as usize);
1184    gl.tex_image_2d(
1185        glow::TEXTURE_2D, 0, glow::RGBA8 as i32,
1186        w as i32, h as i32, 0,
1187        glow::RGBA, glow::UNSIGNED_BYTE,
1188        glow::PixelUnpackData::Slice(Some(pixels)),
1189    );
1190    gl.bind_texture(glow::TEXTURE_2D, None);
1191    tex.0.get()
1192}
1193
1194unsafe extern "C" fn gfx_tex_delete(handle: u32) {
1195    let Some(g) = GL.get() else { return };
1196    let Some(n) = NonZeroU32::new(handle) else { return };
1197    g.0.delete_texture(glow::NativeTexture(n));
1198}
1199
1200unsafe extern "C" fn gfx_tex_bind(unit: u32, handle: u32) {
1201    let Some(g) = GL.get() else { return };
1202    let gl = &g.0;
1203    gl.active_texture(glow::TEXTURE0 + unit);
1204    match NonZeroU32::new(handle) {
1205        Some(n) => gl.bind_texture(glow::TEXTURE_2D, Some(glow::NativeTexture(n))),
1206        None    => gl.bind_texture(glow::TEXTURE_2D, None),
1207    }
1208}
1209
1210unsafe extern "C" fn gfx_tex_from_mc(id: YogStr) -> u32 {
1211    let Some(mut env) = get_env() else { return 0 };
1212    let Some(ji) = ys_to_java(&mut env, id) else { return 0 };
1213    env.call_static_method("dev/yog/NativeDraw", "getMcTextureId",
1214        "(Ljava/lang/String;)I", &[JValue::Object(&ji)])
1215        .and_then(|v| v.i())
1216        .map(|id| id as u32)
1217        .unwrap_or(0)
1218}
1219
1220// ── Draw calls ────────────────────────────────────────────────────────────────
1221
1222unsafe extern "C" fn gfx_draw_arrays(vao: u32, prog: u32, mode: u8, first: u32, count: u32) {
1223    let Some(g) = GL.get() else { return };
1224    let (Some(vn), Some(pn)) = (NonZeroU32::new(vao), NonZeroU32::new(prog)) else { return };
1225    let gl = &g.0;
1226    gl.use_program(Some(glow::NativeProgram(pn)));
1227    gl.bind_vertex_array(Some(glow::NativeVertexArray(vn)));
1228    gl.draw_arrays(gl_draw_mode(mode), first as i32, count as i32);
1229    gl.bind_vertex_array(None);
1230}
1231
1232unsafe extern "C" fn gfx_draw_elements(vao: u32, ebo: u32, prog: u32, mode: u8, count: u32, u32_idx: bool) {
1233    let Some(g) = GL.get() else { return };
1234    let (Some(vn), Some(pn)) = (NonZeroU32::new(vao), NonZeroU32::new(prog)) else { return };
1235    let gl = &g.0;
1236    gl.use_program(Some(glow::NativeProgram(pn)));
1237    gl.bind_vertex_array(Some(glow::NativeVertexArray(vn)));
1238    // EBO is stored in the VAO; ebo param is informational for safety but not re-bound here.
1239    let _ = ebo;
1240    let idx_type = if u32_idx { glow::UNSIGNED_INT } else { glow::UNSIGNED_SHORT };
1241    gl.draw_elements(gl_draw_mode(mode), count as i32, idx_type, 0);
1242    gl.bind_vertex_array(None);
1243}
1244
1245// ── Render state ──────────────────────────────────────────────────────────────
1246
1247unsafe extern "C" fn gfx_set_blend(enabled: bool, src: u32, dst: u32) {
1248    let Some(g) = GL.get() else { return };
1249    let gl = &g.0;
1250    if enabled {
1251        gl.enable(glow::BLEND);
1252        gl.blend_func(src, dst);
1253    } else {
1254        gl.disable(glow::BLEND);
1255    }
1256}
1257
1258unsafe extern "C" fn gfx_set_depth(test: bool, write: bool) {
1259    let Some(g) = GL.get() else { return };
1260    let gl = &g.0;
1261    if test { gl.enable(glow::DEPTH_TEST); } else { gl.disable(glow::DEPTH_TEST); }
1262    gl.depth_mask(write);
1263    // Disable face culling: our 2D quads use CW winding (back-face) due to y-flip.
1264    if !test { gl.disable(glow::CULL_FACE); }
1265}
1266
1267unsafe extern "C" fn gfx_set_scissor(x: i32, y: i32, w: i32, h: i32) {
1268    let Some(g) = GL.get() else { return };
1269    let gl = &g.0;
1270    gl.enable(glow::SCISSOR_TEST);
1271    gl.scissor(x, y, w, h);
1272}
1273
1274unsafe extern "C" fn gfx_clear_scissor() {
1275    let Some(g) = GL.get() else { return };
1276    g.0.disable(glow::SCISSOR_TEST);
1277}
1278
1279unsafe extern "C" fn gfx_set_viewport(x: i32, y: i32, w: i32, h: i32) {
1280    let Some(g) = GL.get() else { return };
1281    g.0.viewport(x, y, w, h);
1282}
1283
1284// ── 2D convenience (JNI — uses MC's DrawContext / text renderer) ──────────────
1285
1286unsafe extern "C" fn gfx_draw2d_rect(x1: f32, y1: f32, x2: f32, y2: f32, color: u32) {
1287    let Some(mut env) = get_env() else { return };
1288    let _ = env.call_static_method("dev/yog/NativeDraw", "drawRect",
1289        "(FFFFI)V",
1290        &[JValue::Float(x1), JValue::Float(y1), JValue::Float(x2), JValue::Float(y2),
1291          JValue::Int(color as i32)]);
1292}
1293
1294unsafe extern "C" fn gfx_draw2d_gradient(x1: f32, y1: f32, x2: f32, y2: f32, top: u32, bottom: u32) {
1295    let Some(mut env) = get_env() else { return };
1296    let _ = env.call_static_method("dev/yog/NativeDraw", "drawGradientRect",
1297        "(FFFFII)V",
1298        &[JValue::Float(x1), JValue::Float(y1), JValue::Float(x2), JValue::Float(y2),
1299          JValue::Int(top as i32), JValue::Int(bottom as i32)]);
1300}
1301
1302unsafe extern "C" fn gfx_draw2d_text(text: YogStr, x: f32, y: f32, color: u32, shadow: bool) {
1303    let Some(mut env) = get_env() else { return };
1304    if let Some(jt) = ys_to_java(&mut env, text) {
1305        let _ = env.call_static_method("dev/yog/NativeDraw", "drawText",
1306            "(Ljava/lang/String;FFIZ)V",
1307            &[JValue::Object(&jt), JValue::Float(x), JValue::Float(y),
1308              JValue::Int(color as i32), JValue::Bool(shadow as u8)]);
1309    }
1310}
1311
1312unsafe extern "C" fn gfx_draw2d_mc_tex(
1313    id: YogStr, x: f32, y: f32, u0: f32, v0: f32, w: f32, h: f32, tw: f32, th: f32,
1314) {
1315    let Some(mut env) = get_env() else { return };
1316    if let Some(ji) = ys_to_java(&mut env, id) {
1317        let _ = env.call_static_method("dev/yog/NativeDraw", "drawTexture",
1318            "(Ljava/lang/String;FFFFFFFFF)V",
1319            &[JValue::Object(&ji),
1320              JValue::Float(x), JValue::Float(y), JValue::Float(u0), JValue::Float(v0),
1321              JValue::Float(w), JValue::Float(h), JValue::Float(tw), JValue::Float(th)]);
1322    }
1323}
1324
1325unsafe extern "C" fn gfx_draw2d_item(id: YogStr, x: f32, y: f32, size: f32) {
1326    let Some(mut env) = get_env() else { return };
1327    if let Some(ji) = ys_to_java(&mut env, id) {
1328        let _ = env.call_static_method("dev/yog/NativeDraw", "drawItem",
1329            "(Ljava/lang/String;FFF)V",
1330            &[JValue::Object(&ji), JValue::Float(x), JValue::Float(y), JValue::Float(size)]);
1331    }
1332}
1333
1334// ── Static GFX function table (function pointers only — per-frame data filled at call time) ──
1335
1336static GFX_FN_TABLE: YogGfxApi = YogGfxApi {
1337    // Per-frame fields zeroed in the static; actual values are set on the stack per render call.
1338    screen_w: 0, screen_h: 0, delta_tick: 0.0, scale_factor: 1.0,
1339    view_proj: [0.0; 16], camera_pos: [0.0; 3], player_pos: [0.0; 3], _pad1: 0.0,
1340    buf_create:        gfx_buf_create,
1341    buf_delete:        gfx_buf_delete,
1342    buf_data:          gfx_buf_data,
1343    buf_subdata:       gfx_buf_subdata,
1344    vao_create:        gfx_vao_create,
1345    vao_delete:        gfx_vao_delete,
1346    vao_attrib:        gfx_vao_attrib,
1347    vao_set_ebo:       gfx_vao_set_ebo,
1348    prog_create:       gfx_prog_create,
1349    prog_delete:       gfx_prog_delete,
1350    prog_uniform_1i:   gfx_prog_uniform_1i,
1351    prog_uniform_1f:   gfx_prog_uniform_1f,
1352    prog_uniform_2f:   gfx_prog_uniform_2f,
1353    prog_uniform_3f:   gfx_prog_uniform_3f,
1354    prog_uniform_4f:   gfx_prog_uniform_4f,
1355    prog_uniform_mat4: gfx_prog_uniform_mat4,
1356    tex_create:        gfx_tex_create,
1357    tex_delete:        gfx_tex_delete,
1358    tex_bind:          gfx_tex_bind,
1359    tex_from_mc:       gfx_tex_from_mc,
1360    draw_arrays:       gfx_draw_arrays,
1361    draw_elements:     gfx_draw_elements,
1362    set_blend:         gfx_set_blend,
1363    set_depth:         gfx_set_depth,
1364    set_scissor:       gfx_set_scissor,
1365    clear_scissor:     gfx_clear_scissor,
1366    set_viewport:      gfx_set_viewport,
1367    draw2d_rect:       gfx_draw2d_rect,
1368    draw2d_gradient:   gfx_draw2d_gradient,
1369    draw2d_text:       gfx_draw2d_text,
1370    draw2d_mc_tex:     gfx_draw2d_mc_tex,
1371    draw2d_item:       gfx_draw2d_item,
1372};
1373
1374// ── YogApi registration functions ─────────────────────────────────────────────
1375//
1376// ctx is *mut RuntimeHandlers (cast from *mut c_void).
1377
1378macro_rules! api_event {
1379    ($name:ident, $field:ident, $fn_ty:ty) => {
1380        unsafe extern "C" fn $name(ctx: *mut c_void, ud: *mut c_void, h: $fn_ty) {
1381            let handlers = &mut *(ctx as *mut RuntimeHandlers);
1382            handlers.$field.push((ud, h));
1383        }
1384    };
1385}
1386
1387api_event!(api_on_block_break,      block_break,        YogBlockBreakFn);
1388api_event!(api_on_chat,             chat,               YogChatFn);
1389api_event!(api_on_player_join,      player_join,        YogPlayerFn);
1390api_event!(api_on_player_leave,     player_leave,       YogPlayerFn);
1391api_event!(api_on_use_item,         use_item,           YogUseItemFn);
1392api_event!(api_on_use_block,        use_block,          YogUseBlockFn);
1393api_event!(api_on_attack_entity,    attack_entity,      YogAttackEntityFn);
1394api_event!(api_on_entity_damage,    entity_damage,      YogEntityDamageFn);
1395api_event!(api_on_entity_death,     entity_death,       YogEntityDeathFn);
1396api_event!(api_on_entity_spawn,     entity_spawn,       YogEntitySpawnFn);
1397api_event!(api_on_player_place_block, player_place_block, YogPlaceBlockFn);
1398api_event!(api_on_player_death,     player_death,       YogPlayerDeathFn);
1399api_event!(api_on_player_respawn,   player_respawn,     YogPlayerRespawnFn);
1400api_event!(api_on_advancement,      advancement,        YogAdvancementFn);
1401api_event!(api_on_entity_interact,  entity_interact,    YogEntityInteractFn);
1402api_event!(api_on_item_craft,       item_craft,         YogCraftFn);
1403api_event!(api_on_explosion,        explosion,          YogExplosionFn);
1404api_event!(api_on_item_pickup,      item_pickup,        YogItemPickupFn);
1405api_event!(api_on_player_move,      player_move,        YogPlayerMoveFn);
1406api_event!(api_on_container_open,   container_open,     YogContainerOpenFn);
1407api_event!(api_on_container_close,  container_close,    YogContainerCloseFn);
1408api_event!(api_on_projectile_hit,   projectile_hit,     YogProjectileHitFn);
1409api_event!(api_on_client_tick,      client_tick,        YogClientFn);
1410api_event!(api_on_hud_render,       hud_render,         YogHudRenderFn);
1411api_event!(api_on_world_render,     world_render,       YogWorldRenderFn);
1412api_event!(api_on_key_press,        key_press,          YogKeyPressFn);
1413api_event!(api_on_screen_open,      screen_open,        YogScreenFn);
1414api_event!(api_on_screen_close,     screen_close,       YogScreenFn);
1415api_event!(api_on_server_tick,      server_tick,        YogServerFn);
1416api_event!(api_on_server_started,   server_started,     YogServerFn);
1417api_event!(api_on_server_stopping,  server_stopping,    YogServerFn);
1418
1419unsafe extern "C" fn api_on_packet(ctx: *mut c_void, channel: YogStr, ud: *mut c_void, h: YogPacketFn) {
1420    let handlers = &mut *(ctx as *mut RuntimeHandlers);
1421    handlers.packets.insert(channel.as_str().to_owned(), (ud, h));
1422}
1423
1424unsafe extern "C" fn api_on_client_packet(ctx: *mut c_void, channel: YogStr, ud: *mut c_void, h: YogPacketFn) {
1425    let handlers = &mut *(ctx as *mut RuntimeHandlers);
1426    handlers.client_packets.insert(channel.as_str().to_owned(), (ud, h));
1427}
1428
1429unsafe extern "C" fn api_register_command(ctx: *mut c_void, name: YogStr, ud: *mut c_void, h: YogCommandFn) {
1430    let handlers = &mut *(ctx as *mut RuntimeHandlers);
1431    handlers.commands.entry(name.as_str().to_owned()).or_default().push((None, ud, h));
1432}
1433
1434unsafe extern "C" fn api_register_typed_command(ctx: *mut c_void, name: YogStr, schema: YogStr, ud: *mut c_void, h: YogCommandFn) {
1435    let handlers = &mut *(ctx as *mut RuntimeHandlers);
1436    let n = name.as_str().to_owned();
1437    handlers.commands.entry(n).or_default().push((Some(schema.as_str().to_owned()), ud, h));
1438}
1439
1440
1441unsafe extern "C" fn api_register_recipe_json(ctx: *mut c_void, namespace: YogStr, name: YogStr, json: YogStr) {
1442    let handlers = &mut *(ctx as *mut RuntimeHandlers);
1443    let ns = namespace.as_str().to_owned();
1444    let n  = name.as_str().to_owned();
1445    let j  = json.as_str().to_owned();
1446    // Feed the recipe to already-registered book renderers (crafting pages).
1447    let full_id = format!("{}:{}", ns, n);
1448    for r in handlers.book_renderers.lock().unwrap().values_mut() {
1449        r.add_recipe(full_id.clone(), &j);
1450    }
1451    handlers.recipes.push((ns, n, j));
1452}
1453
1454unsafe extern "C" fn api_register_item(ctx: *mut c_void, def: *const YogItemDef) {
1455    let handlers = &mut *(ctx as *mut RuntimeHandlers);
1456    let d = &*def;
1457    let food = if d.food_nutrition > 0 {
1458        Some(FoodDef { nutrition: d.food_nutrition, saturation: d.food_saturation, can_always_eat: d.food_always_eat })
1459    } else { None };
1460    handlers.items.push(ItemDef {
1461        id:            d.id.as_str().to_owned(),
1462        max_stack:     d.max_stack as u8,
1463        name:          if d.name.is_empty() { None } else { Some(d.name.as_str().to_owned()) },
1464        tooltip:       if d.tooltip.is_empty() { None } else { Some(d.tooltip.as_str().to_owned()) },
1465        max_damage:    d.max_damage,
1466        fire_resistant: d.fire_resistant,
1467        fuel_ticks:    d.fuel_ticks,
1468        food,
1469    });
1470}
1471
1472unsafe extern "C" fn api_register_block(ctx: *mut c_void, def: *const YogBlockDef) {
1473    let handlers = &mut *(ctx as *mut RuntimeHandlers);
1474    let d = &*def;
1475    handlers.blocks.push(BlockDef {
1476        id:            d.id.as_str().to_owned(),
1477        hardness:      d.hardness,
1478        resistance:    d.resistance,
1479        name:          if d.name.is_empty() { None } else { Some(d.name.as_str().to_owned()) },
1480        light_level:   d.light_level,
1481        sound:         if d.sound.is_empty() { None } else { Some(d.sound.as_str().to_owned()) },
1482        requires_tool: d.requires_tool,
1483        no_collision:  d.no_collision,
1484        slipperiness:  d.slipperiness,
1485        shape:         if d.shape == [0.0f32; 6] { None } else { Some(d.shape) },
1486        connects:      d.connects,
1487        connect_groups: if d.connect_groups.is_empty() { Vec::new() }
1488            else { d.connect_groups.as_str().split(',').map(str::to_owned).collect() },
1489        inventory_id:  if d.inventory_id.is_empty() { None } else { Some(d.inventory_id.as_str().to_owned()) },
1490    });
1491}
1492
1493unsafe extern "C" fn api_register_inventory(ctx: *mut c_void, def: *const yog_abi::YogInventoryDef) {
1494    let handlers = &mut *(ctx as *mut RuntimeHandlers);
1495    let d = &*def;
1496    handlers.inventories.push(yog_inventory::InventoryDef {
1497        id:            d.id.as_str().to_owned(),
1498        slot_count:    d.slot_count as usize,
1499        layout:        yog_inventory::decode_layout(d.layout.as_str()),
1500        include_player_inventory: d.include_player_inventory,
1501        player_inv_offset: (d.player_inv_x, d.player_inv_y),
1502        background_texture: if d.background_texture.is_empty() { None } else { Some(d.background_texture.as_str().to_owned()) },
1503        title:         d.title.as_str().to_owned(),
1504    });
1505}
1506
1507unsafe extern "C" fn api_schedule_once(ctx: *mut c_void, delay_ticks: u64, ud: *mut c_void, h: YogScheduledFn) {
1508    let handlers = &mut *(ctx as *mut RuntimeHandlers);
1509    handlers.scheduler.lock().expect("scheduler poisoned").once_tasks.push(OnceTask { delay_remaining: delay_ticks, ud, f: h });
1510}
1511
1512unsafe extern "C" fn api_schedule_repeating(ctx: *mut c_void, period_ticks: u64, ud: *mut c_void, h: YogScheduledFn) {
1513    let handlers = &mut *(ctx as *mut RuntimeHandlers);
1514    handlers.scheduler.lock().expect("scheduler poisoned").repeating_tasks.push(RepeatingTask { period: period_ticks, ticks_left: period_ticks, ud, f: h });
1515}
1516
1517unsafe extern "C" fn api_register_startup_grant(ctx: *mut c_void, grant: *const YogStartupGrantDef) {
1518    let handlers = &mut *(ctx as *mut RuntimeHandlers);
1519    let g = &*grant;
1520    let items: Vec<String> = if g.items.is_empty() {
1521        Vec::new()
1522    } else {
1523        unsafe { g.items.as_str().split('|').map(|s: &str| s.to_owned()).collect() }
1524    };
1525    let book = if g.book.is_empty() { None } else { Some(unsafe { g.book.as_str().to_owned() }) };
1526    let command = if g.command.is_empty() { None } else { Some(unsafe { g.command.as_str().to_owned() }) };
1527    handlers.startup_grants.push(yog_registry::StartupGrant {
1528        id: unsafe { g.id.as_str().to_owned() },
1529        items,
1530        book,
1531        command,
1532    });
1533}
1534
1535unsafe extern "C" fn api_register_book(ctx: *mut c_void, book_id: YogStr, book_json: YogStr) {
1536    let handlers = &mut *(ctx as *mut RuntimeHandlers);
1537    let id   = unsafe { book_id.as_str().to_owned() };
1538    let json = unsafe { book_json.as_str().to_owned() };
1539    handlers.books.insert(id.clone(), json.clone());
1540    // Parse JSON → Book → BookRenderer so rendering works without Java round-trip.
1541    match serde_json::from_str::<yog_book::Book>(&json) {
1542        Ok(book) => {
1543            let mut renderer = yog_book::BookRenderer::new(book);
1544            // Recipes may register before the book — replay them into the renderer.
1545            for (ns, name, j) in &handlers.recipes {
1546                renderer.add_recipe(format!("{}:{}", ns, name), j);
1547            }
1548            handlers.book_renderers.lock().unwrap().insert(id, renderer);
1549        }
1550        Err(e) => {
1551            yog_logging::warn!("book '{}': failed to parse JSON for Rust renderer: {}", id, e);
1552        }
1553    }
1554}
1555
1556unsafe extern "C" fn api_register_ui(ctx: *mut c_void, ui_id: YogStr, _layout_json: YogStr,
1557                                     ud: *mut c_void, h: yog_abi::YogUIEventFn) {
1558    let handlers = &mut *(ctx as *mut RuntimeHandlers);
1559    let id = unsafe { ui_id.as_str().to_owned() };
1560    handlers.ui_handlers.insert(id.clone(), (ud, h));
1561    yog_logging::info!("registered UI handler: {}", id);
1562}
1563
1564unsafe extern "C" fn api_on_ui_render(ctx: *mut c_void, ui_id: YogStr,
1565                                      ud: *mut c_void, h: YogHudRenderFn) {
1566    let handlers = &mut *(ctx as *mut RuntimeHandlers);
1567    let id = unsafe { ui_id.as_str().to_owned() };
1568    handlers.ui_render_handlers.entry(id).or_default().push((ud, h));
1569}
1570
1571/// Strip TSV separators so one mod can't corrupt the line format.
1572fn tsv_clean(v: &str) -> String {
1573    v.replace(['\t', '\n', '\r'], " ")
1574}
1575
1576unsafe extern "C" fn api_ui_open(_ctx: *mut c_void, ui_id: YogStr, modal: bool, pause: bool) {
1577    let id = ui_id.as_str().to_string();
1578    if id.is_empty() { return; }
1579    let Some(mut env) = get_env() else { return };
1580    let Ok(jid) = env.new_string(&id) else { return };
1581    let jid_obj: JObject = jid.into();
1582    // Java side schedules onto the render thread; no-op on dedicated servers.
1583    if env.call_static_method(
1584        "dev/yog/NativeBridge", "openUI", "(Ljava/lang/String;ZZ)V",
1585        &[JValue::Object(&jid_obj), JValue::Bool(modal as u8), JValue::Bool(pause as u8)],
1586    ).is_err() {
1587        env.exception_clear().ok();
1588    }
1589}
1590
1591unsafe extern "C" fn api_mods_list(_ctx: *mut c_void) -> YogOwnedStr {
1592    let mut lines: Vec<String> = Vec::new();
1593    for m in MOD_INFOS.lock().expect("mod infos lock poisoned").iter() {
1594        lines.push(format!("yog\t{}\t{}\t{}\t{}\t{}", m[0], m[1], m[2], m[3], m[4]));
1595    }
1596    // Loader-side (Java) mods, if the host provides them.
1597    if let Some(mut env) = get_env() {
1598        if let Ok(val) = env.call_static_method(
1599            "dev/yog/NativeBridge", "listPlatformMods", "()Ljava/lang/String;", &[],
1600        ) {
1601            if let Ok(obj) = val.l() {
1602                if !obj.as_raw().is_null() {
1603                    if let Ok(js) = env.get_string(&obj.into()) {
1604                        for line in String::from(js).lines() {
1605                            if !line.trim().is_empty() {
1606                                lines.push(format!("platform\t{line}"));
1607                            }
1608                        }
1609                    }
1610                }
1611            }
1612        } else {
1613            env.exception_clear().ok();
1614        }
1615    }
1616    YogOwnedStr::from_string(lines.join("\n"))
1617}
1618
1619unsafe extern "C" fn api_register_menu_entry(ctx: *mut c_void, label: YogStr, ui_id: YogStr) {
1620    let handlers = &mut *(ctx as *mut RuntimeHandlers);
1621    let l = unsafe { label.as_str().to_owned() };
1622    let u = unsafe { ui_id.as_str().to_owned() };
1623    handlers.menu_entries.push((l, u));
1624}
1625
1626
1627#[no_mangle]
1628pub extern "system" fn Java_dev_yog_NativeBridge_nativeBookJson<'l>(
1629    mut env: JNIEnv<'l>, _class: JClass<'l>, book_id: JString<'l>,
1630) -> jstring {
1631    let id = match env.get_string(&book_id) {
1632        Ok(s) => String::from(s),
1633        Err(_) => return std::ptr::null_mut(),
1634    };
1635    let json = handlers().books.get(&id).cloned().unwrap_or_else(|| "null".to_string());
1636    env.new_string(json).map(|s| s.into_raw()).unwrap_or(std::ptr::null_mut())
1637}
1638
1639// ── Table constructors ────────────────────────────────────────────────────────
1640
1641fn build_server_table() -> YogServer {
1642    YogServer {
1643        ctx:         std::ptr::null_mut(),
1644        abi_version: ABI_VERSION,
1645        size:        std::mem::size_of::<YogServer>() as u32,
1646        free_str:    yog_free_str,
1647        broadcast:   srv_broadcast,
1648        get_block:   srv_get_block,
1649        set_block:   srv_set_block,
1650        world_time:  srv_world_time,
1651        set_time:    srv_set_time,
1652        is_raining:  srv_is_raining,
1653        set_weather: srv_set_weather,
1654        give_item:   srv_give_item,
1655        player_teleport: srv_player_teleport,
1656        send_to_player: srv_send_to_player,
1657        send_to_server: srv_send_to_server,
1658        kick_player: srv_kick_player,
1659        set_gamemode: srv_set_gamemode,
1660        send_title:  srv_send_title,
1661        send_actionbar: srv_send_actionbar,
1662        play_sound:  srv_play_sound,
1663        play_sound_player: srv_play_sound_player,
1664        entity_teleport: srv_entity_teleport,
1665        entity_position: srv_entity_position,
1666        entity_rotation:      srv_entity_rotation,
1667        entity_health: srv_entity_health,
1668        entity_set_health: srv_entity_set_health,
1669        entity_kill: srv_entity_kill,
1670        spawn_entity: srv_spawn_entity,
1671        entity_add_effect: srv_entity_add_effect,
1672        entity_remove_effect: srv_entity_remove_effect,
1673        entity_clear_effects: srv_entity_clear_effects,
1674        entity_velocity: srv_entity_velocity,
1675        entity_set_velocity: srv_entity_set_velocity,
1676        entity_add_velocity: srv_entity_add_velocity,
1677        has_item_tag: srv_has_item_tag,
1678        has_block_tag: srv_has_block_tag,
1679        drop_loot: srv_drop_loot,
1680        scoreboard_get: srv_scoreboard_get,
1681        scoreboard_set: srv_scoreboard_set,
1682        scoreboard_add: srv_scoreboard_add,
1683        bossbar_create: srv_bossbar_create,
1684        bossbar_remove: srv_bossbar_remove,
1685        bossbar_set_title: srv_bossbar_set_title,
1686        bossbar_set_progress: srv_bossbar_set_progress,
1687        bossbar_set_color: srv_bossbar_set_color,
1688        bossbar_add_player: srv_bossbar_add_player,
1689        bossbar_remove_player: srv_bossbar_remove_player,
1690        bossbar_set_visible: srv_bossbar_set_visible,
1691        game_dir: srv_game_dir,
1692        get_block_nbt:       srv_get_block_nbt,
1693        set_block_nbt:       srv_set_block_nbt,
1694        get_inventory_slot:  srv_get_inventory_slot,
1695        set_inventory_slot:  srv_set_inventory_slot,
1696        player_inventory:    srv_player_inventory,
1697        player_set_slot:     srv_player_set_slot,
1698        player_teleport_dim: srv_player_teleport_dim,
1699        entity_teleport_dim: srv_entity_teleport_dim,
1700        online_players:      srv_online_players,
1701        world_entity_count:  srv_world_entity_count,
1702        entity_get_nbt:          srv_entity_get_nbt,
1703        entity_set_nbt:          srv_entity_set_nbt,
1704        spawn_particles:         srv_spawn_particles,
1705        entity_attribute_get:    srv_entity_attribute_get,
1706        entity_attribute_set:    srv_entity_attribute_set,
1707        get_held_item_nbt:       srv_get_held_item_nbt,
1708        set_held_item_nbt:       srv_set_held_item_nbt,
1709        get_offhand_item_nbt:    srv_get_offhand_item_nbt,
1710        set_offhand_item_nbt:    srv_set_offhand_item_nbt,
1711        get_slot_item:           srv_get_slot_item,
1712        set_slot_item:           srv_set_slot_item,
1713    }
1714}
1715
1716fn build_api_table(ctx: *mut RuntimeHandlers, server: *const YogServer) -> YogApi {
1717    YogApi {
1718        abi_version: ABI_VERSION,
1719        size:        std::mem::size_of::<YogApi>() as u32,
1720        ctx:         ctx as *mut c_void,
1721        server,
1722        on_block_break:     api_on_block_break,
1723        on_chat:            api_on_chat,
1724        on_player_join:     api_on_player_join,
1725        on_player_leave:    api_on_player_leave,
1726        on_use_item:        api_on_use_item,
1727        on_use_block:       api_on_use_block,
1728        on_attack_entity:   api_on_attack_entity,
1729        on_entity_damage:   api_on_entity_damage,
1730        on_entity_death:    api_on_entity_death,
1731        on_entity_spawn:         api_on_entity_spawn,
1732        on_player_place_block:   api_on_player_place_block,
1733        on_player_death:         api_on_player_death,
1734        on_player_respawn:       api_on_player_respawn,
1735        on_advancement:          api_on_advancement,
1736        on_entity_interact:      api_on_entity_interact,
1737        on_item_craft:           api_on_item_craft,
1738        on_explosion:            api_on_explosion,
1739        on_item_pickup:          api_on_item_pickup,
1740        on_player_move:          api_on_player_move,
1741        on_container_open:       api_on_container_open,
1742        on_container_close:      api_on_container_close,
1743        on_projectile_hit:       api_on_projectile_hit,
1744        on_server_tick:          api_on_server_tick,
1745        on_server_started:       api_on_server_started,
1746        on_server_stopping:      api_on_server_stopping,
1747        on_packet:               api_on_packet,
1748        on_client_packet:        api_on_client_packet,
1749        register_command:        api_register_command,
1750        register_typed_command:  api_register_typed_command,
1751        register_recipe_json:    api_register_recipe_json,
1752        register_item:          api_register_item,
1753        register_block:     api_register_block,
1754        schedule_once:      api_schedule_once,
1755        schedule_repeating: api_schedule_repeating,
1756        on_client_tick:     api_on_client_tick,
1757        on_hud_render:      api_on_hud_render,
1758        on_key_press:       api_on_key_press,
1759        on_screen_open:     api_on_screen_open,
1760        on_screen_close:    api_on_screen_close,
1761        on_world_render:    api_on_world_render,
1762        register_startup_grant: api_register_startup_grant,
1763        register_book:          api_register_book,
1764        register_ui:            api_register_ui,
1765        on_ui_render:           api_on_ui_render,
1766        register_menu_entry:    api_register_menu_entry,
1767        mods_list:              api_mods_list,
1768        free_str:               yog_free_str,
1769        ui_open:                api_ui_open,
1770        register_inventory:     api_register_inventory,
1771    }
1772}
1773
1774// ── Mod loading ───────────────────────────────────────────────────────────────
1775
1776fn platform_tag() -> String {
1777    format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH)
1778}
1779
1780type AbiVersionFn   = unsafe extern "C" fn() -> u32;
1781type RegisterFn     = unsafe extern "C" fn(*const YogApi, *mut c_void);
1782
1783fn load_mods(dir: &Path, api: &YogApi) {
1784    let entries = match std::fs::read_dir(dir) {
1785        Ok(e) => e,
1786        Err(_) => {
1787            yog_logging::info!("no mods directory at {} — none loaded", dir.display());
1788            return;
1789        }
1790    };
1791    let mut count = 0u32;
1792    for entry in entries.flatten() {
1793        let path = entry.path();
1794        let lib_path = match path.extension().and_then(|e| e.to_str()) {
1795            Some("yog") => match extract_yog(&path) {
1796                Some(p) => p,
1797                None => {
1798                    yog_logging::error!("no native for {} in {}", platform_tag(), path.display());
1799                    continue;
1800                }
1801            },
1802            Some("so") | Some("dll") | Some("dylib") => path.clone(),
1803            _ => continue,
1804        };
1805        if load_mod_lib(&lib_path, api) {
1806            count += 1;
1807            MOD_INFOS.lock().expect("mod infos lock poisoned").push(read_mod_info(&path));
1808        }
1809    }
1810    yog_logging::info!("loaded {} mod(s) from {}", count, dir.display());
1811}
1812
1813fn load_mod_lib(path: &Path, api: &YogApi) -> bool {
1814    unsafe {
1815        let lib = match Library::new(path) {
1816            Ok(l) => l,
1817            Err(e) => { yog_logging::error!("failed to load {}: {}", path.display(), e); return false; }
1818        };
1819        let abi: Symbol<AbiVersionFn> = match lib.get(b"yog_abi_version") {
1820            Ok(s) => s,
1821            Err(_) => { yog_logging::error!("{} is not a Yog mod (no yog_abi_version)", path.display()); return false; }
1822        };
1823        let mod_abi = abi();
1824        if mod_abi != ABI_VERSION {
1825            yog_logging::error!("{}: ABI {} incompatible with runtime ABI {}", path.display(), mod_abi, ABI_VERSION);
1826            return false;
1827        }
1828        let register: Symbol<RegisterFn> = match lib.get(b"yog_mod_register") {
1829            Ok(s) => s,
1830            Err(_) => { yog_logging::error!("{} missing yog_mod_register", path.display()); return false; }
1831        };
1832        register(api as *const YogApi, std::ptr::null_mut());
1833        drop(register);
1834        drop(abi);
1835        LOADED_MODS.lock().expect("mods lock poisoned").push(lib);
1836    }
1837    true
1838}
1839
1840/// Metadata for a mod file: [id, name, version, authors, description].
1841/// For .yog archives this comes from the bundled yog.toml; bare native libs
1842/// fall back to the file stem.
1843fn read_mod_info(path: &Path) -> [String; 5] {
1844    let stem = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
1845    let mut info = [stem.clone(), stem, String::new(), String::new(), String::new()];
1846    if path.extension().and_then(|e| e.to_str()) != Some("yog") {
1847        return info;
1848    }
1849    let Some(text) = (|| {
1850        let file = std::fs::File::open(path).ok()?;
1851        let mut archive = zip::ZipArchive::new(file).ok()?;
1852        let mut entry = archive.by_name("yog.toml").ok()?;
1853        let mut text = String::new();
1854        std::io::Read::read_to_string(&mut entry, &mut text).ok()?;
1855        Some(text)
1856    })() else { return info };
1857    // Minimal parse — enough for id/name/version/description/authors without
1858    // pulling in a TOML dependency. Source manifests keep these under [mod];
1859    // the packaged manifest (written by yog-cli) has them at top level, so
1860    // keys before any section header count too.
1861    let mut in_mod = true;
1862    for line in text.lines() {
1863        let line = line.trim();
1864        if line.starts_with('[') {
1865            in_mod = line == "[mod]";
1866            continue;
1867        }
1868        if !in_mod { continue; }
1869        let Some((key, value)) = line.split_once('=') else { continue };
1870        let key = key.trim();
1871        let value = value.trim();
1872        let unquote = |v: &str| v.trim().trim_matches('"').to_string();
1873        match key {
1874            "id"          => info[0] = tsv_clean(&unquote(value)),
1875            "name"        => info[1] = tsv_clean(&unquote(value)),
1876            "version"     => info[2] = tsv_clean(&unquote(value)),
1877            "description" => info[4] = tsv_clean(&unquote(value)),
1878            "authors" => {
1879                let list = value.trim_start_matches('[').trim_end_matches(']');
1880                let authors: Vec<String> = list.split(',')
1881                    .map(|a| unquote(a))
1882                    .filter(|a| !a.is_empty())
1883                    .collect();
1884                info[3] = tsv_clean(&authors.join(", "));
1885            }
1886            _ => {}
1887        }
1888    }
1889    info
1890}
1891
1892fn extract_yog(path: &Path) -> Option<PathBuf> {
1893    let file = std::fs::File::open(path).ok()?;
1894    let mut archive = zip::ZipArchive::new(file).ok()?;
1895    let prefix = format!("natives/{}/", platform_tag());
1896    let mut entry_name = None;
1897    for i in 0..archive.len() {
1898        let f = archive.by_index(i).ok()?;
1899        if f.name().starts_with(&prefix) && !f.name().ends_with('/') {
1900            entry_name = Some(f.name().to_string());
1901            break;
1902        }
1903    }
1904    let entry_name = entry_name?;
1905    let ext = Path::new(&entry_name).extension().and_then(|e| e.to_str()).unwrap_or("bin");
1906    let stem = path.file_stem()?.to_string_lossy().into_owned();
1907    let out = std::env::temp_dir().join(format!("yog-{}-{}.{}", stem, std::process::id(), ext));
1908    let mut entry = archive.by_name(&entry_name).ok()?;
1909    let mut out_file = std::fs::File::create(&out).ok()?;
1910    std::io::copy(&mut entry, &mut out_file).ok()?;
1911    Some(out)
1912}
1913
1914// ── Dispatcher helpers ────────────────────────────────────────────────────────
1915
1916fn srv_ptr() -> *const YogServer {
1917    SERVER.get().expect("yog: SERVER not initialised") as *const YogServer
1918}
1919
1920// ── JNI entry points ──────────────────────────────────────────────────────────
1921
1922#[no_mangle]
1923pub extern "system" fn Java_dev_yog_NativeBridge_nativeInit<'l>(
1924    mut env: JNIEnv<'l>,
1925    _class: JClass<'l>,
1926    mods_dir: JString<'l>,
1927) {
1928    if let Ok(vm) = env.get_java_vm() { let _ = JAVA_VM.set(vm); }
1929
1930    let dir = env.get_string(&mods_dir).map(String::from).unwrap_or_default();
1931
1932    // Build YogServer and store in static (gets a stable address).
1933    let _ = SERVER.set(build_server_table());
1934    let server_ptr = SERVER.get().unwrap() as *const YogServer;
1935
1936    // Build RuntimeHandlers on the heap temporarily so we have a stable pointer
1937    // to pass as ctx while mods register.
1938    let mut handlers = Box::new(RuntimeHandlers::new());
1939    let handlers_ptr = &mut *handlers as *mut RuntimeHandlers;
1940
1941    let api: &'static YogApi = API_TABLE.get_or_init(|| build_api_table(handlers_ptr, server_ptr));
1942
1943    guard("mod loading", || {
1944        load_mods(Path::new(&dir), api);
1945    });
1946
1947    // Move handlers out of Box and into the OnceLock.
1948    let _ = HANDLERS.set(*handlers);
1949
1950    yog_logging::info!("runtime initialised — the gate is open.");
1951}
1952
1953#[no_mangle]
1954pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnBlockBreak<'l>(
1955    mut env: JNIEnv<'l>, _class: JClass<'l>,
1956    player: JString<'l>, block: JString<'l>, x: jint, y: jint, z: jint,
1957) {
1958    let (p, b) = (jstr!(env, player), jstr!(env, block));
1959    let ev = yog_abi::YogBlockBreakEvent {
1960        player: YogStr::from_str(&p), block: YogStr::from_str(&b),
1961        pos: YogBlockPos { x, y, z },
1962    };
1963    let srv = srv_ptr();
1964    guard("on_block_break", || {
1965        for (ud, f) in &handlers().block_break {
1966            unsafe { f(*ud, srv, &ev, 1) };
1967        }
1968    });
1969}
1970
1971#[no_mangle]
1972pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnChat<'l>(
1973    mut env: JNIEnv<'l>, _class: JClass<'l>,
1974    player: JString<'l>, message: JString<'l>,
1975) {
1976    let (p, m) = (jstr!(env, player), jstr!(env, message));
1977    let ev = yog_abi::YogChatEvent { player: YogStr::from_str(&p), message: YogStr::from_str(&m) };
1978    let srv = srv_ptr();
1979    guard("on_chat", || {
1980        for (ud, f) in &handlers().chat {
1981            unsafe { f(*ud, srv, &ev, 1) };
1982        }
1983    });
1984}
1985
1986#[no_mangle]
1987pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerJoin<'l>(
1988    mut env: JNIEnv<'l>, _class: JClass<'l>,
1989    player: JString<'l>, uuid: JString<'l>,
1990) {
1991    let (p, u) = (jstr!(env, player), jstr!(env, uuid));
1992    let ev = yog_abi::YogPlayerEvent { player: YogStr::from_str(&p), uuid: YogStr::from_str(&u) };
1993    let srv = srv_ptr();
1994    guard("on_player_join", || {
1995        for (ud, f) in &handlers().player_join {
1996            unsafe { f(*ud, srv, &ev, 1) };
1997        }
1998    });
1999    // Queue startup grants: giving items directly inside the join callback
2000    // fails for the host of a freshly created world (player not fully in the
2001    // world yet), so grants are processed a few server ticks later.
2002    let h = handlers();
2003    if !h.startup_grants.is_empty() {
2004        h.pending_grants.lock().expect("pending_grants poisoned")
2005            .push((p, u, 0));
2006    }
2007}
2008
2009/// Try to fulfil pending startup grants. Called each server tick; a grant is
2010/// only marked as given (and persisted) after `give_item` actually succeeds.
2011fn process_pending_grants() {
2012    let h = handlers();
2013    let mut pending = match h.pending_grants.try_lock() { Ok(g) => g, Err(_) => return };
2014    if pending.is_empty() { return; }
2015    // Wait a couple of ticks after join before the first attempt.
2016    const FIRST_TRY_TICK: u32 = 2;
2017    // Give up after 30 seconds — the player probably left.
2018    const MAX_TICKS: u32 = 600;
2019
2020    let mut granted = h.startup_granted.lock().expect("startup_granted poisoned");
2021    let mut still_pending = Vec::new();
2022    let mut any_new = false;
2023
2024    for (p, u, ticks) in pending.drain(..) {
2025        if ticks < FIRST_TRY_TICK {
2026            still_pending.push((p, u, ticks + 1));
2027            continue;
2028        }
2029        let mut all_ok = true;
2030        for sg in &h.startup_grants {
2031            let key = format!("{}::{}", u, sg.id);
2032            if granted.contains_key(&key) { continue; }
2033            let mut ok = true;
2034            for item_id in &sg.items {
2035                ok &= unsafe { srv_give_item(std::ptr::null_mut(),
2036                    YogStr::from_str(&p), YogStr::from_str(item_id), 1) };
2037            }
2038            if let Some(_book) = &sg.book {
2039                ok &= unsafe { srv_give_item(std::ptr::null_mut(),
2040                    YogStr::from_str(&p), YogStr::from_str("minecraft:written_book"), 1) };
2041            }
2042            if ok {
2043                yog_logging::info!("startup grant {} given to {}", sg.id, p);
2044                granted.insert(key, true);
2045                any_new = true;
2046            } else {
2047                all_ok = false;
2048            }
2049        }
2050        if !all_ok && ticks < MAX_TICKS {
2051            still_pending.push((p, u, ticks + 1));
2052        }
2053    }
2054    *pending = still_pending;
2055    if any_new {
2056        save_startup_granted(&granted);
2057    }
2058}
2059
2060#[no_mangle]
2061pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerLeave<'l>(
2062    mut env: JNIEnv<'l>, _class: JClass<'l>,
2063    player: JString<'l>, uuid: JString<'l>,
2064) {
2065    let (p, u) = (jstr!(env, player), jstr!(env, uuid));
2066    let ev = yog_abi::YogPlayerEvent { player: YogStr::from_str(&p), uuid: YogStr::from_str(&u) };
2067    let srv = srv_ptr();
2068    guard("on_player_leave", || {
2069        for (ud, f) in &handlers().player_leave {
2070            unsafe { f(*ud, srv, &ev, 1) };
2071        }
2072    });
2073}
2074
2075#[no_mangle]
2076pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseItem<'l>(
2077    mut env: JNIEnv<'l>, _class: JClass<'l>,
2078    player: JString<'l>, item: JString<'l>, sneaking: jni::sys::jboolean,
2079) {
2080    let (p, i) = (jstr!(env, player), jstr!(env, item));
2081    let ev = yog_abi::YogUseItemEvent {
2082        player: YogStr::from_str(&p),
2083        item: YogStr::from_str(&i),
2084        sneaking: sneaking != 0,
2085    };
2086    let srv = srv_ptr();
2087    guard("on_use_item", || {
2088        for (ud, f) in &handlers().use_item {
2089            unsafe { f(*ud, srv, &ev, 1) };
2090        }
2091    });
2092}
2093
2094#[no_mangle]
2095pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseItemPre<'l>(
2096    mut env: JNIEnv<'l>, _class: JClass<'l>,
2097    player: JString<'l>, item: JString<'l>, sneaking: jni::sys::jboolean,
2098) -> jni::sys::jboolean {
2099    let h = handlers();
2100    if h.use_item.is_empty() { return 1; }
2101    let p = match env.get_string(&player) { Ok(s) => String::from(s), Err(_) => return 1 };
2102    let i = match env.get_string(&item) { Ok(s) => String::from(s), Err(_) => return 1 };
2103    let ev = yog_abi::YogUseItemEvent {
2104        player: YogStr::from_str(&p),
2105        item: YogStr::from_str(&i),
2106        sneaking: sneaking != 0,
2107    };
2108    let srv = srv_ptr();
2109    let mut allow = true;
2110    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2111        for (ud, f) in &h.use_item {
2112            if !unsafe { f(*ud, srv, &ev, 0) } { allow = false; break; }
2113        }
2114    })).ok();
2115    allow as jni::sys::jboolean
2116}
2117
2118#[no_mangle]
2119pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseBlock<'l>(
2120    mut env: JNIEnv<'l>, _class: JClass<'l>,
2121    player: JString<'l>, block: JString<'l>, x: jint, y: jint, z: jint,
2122) {
2123    let (p, b) = (jstr!(env, player), jstr!(env, block));
2124    let ev = yog_abi::YogUseBlockEvent {
2125        player: YogStr::from_str(&p), block: YogStr::from_str(&b),
2126        pos: YogBlockPos { x, y, z },
2127    };
2128    let srv = srv_ptr();
2129    guard("on_use_block", || {
2130        for (ud, f) in &handlers().use_block {
2131            unsafe { f(*ud, srv, &ev, 1) };
2132        }
2133    });
2134}
2135
2136#[no_mangle]
2137pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseBlockPre<'l>(
2138    mut env: JNIEnv<'l>, _class: JClass<'l>,
2139    player: JString<'l>, block: JString<'l>, x: jint, y: jint, z: jint,
2140) -> jni::sys::jboolean {
2141    let h = handlers();
2142    if h.use_block.is_empty() { return 1; }
2143    let p = match env.get_string(&player) { Ok(s) => String::from(s), Err(_) => return 1 };
2144    let b = match env.get_string(&block) { Ok(s) => String::from(s), Err(_) => return 1 };
2145    let ev = yog_abi::YogUseBlockEvent {
2146        player: YogStr::from_str(&p), block: YogStr::from_str(&b),
2147        pos: YogBlockPos { x, y, z },
2148    };
2149    let srv = srv_ptr();
2150    let mut allow = true;
2151    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2152        for (ud, f) in &h.use_block {
2153            if !unsafe { f(*ud, srv, &ev, 0) } { allow = false; break; }
2154        }
2155    })).ok();
2156    allow as jni::sys::jboolean
2157}
2158
2159#[no_mangle]
2160pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnAttackEntity<'l>(
2161    mut env: JNIEnv<'l>, _class: JClass<'l>,
2162    player: JString<'l>, target_type: JString<'l>, target_uuid: JString<'l>,
2163) {
2164    let (p, tt, tu) = (jstr!(env, player), jstr!(env, target_type), jstr!(env, target_uuid));
2165    let ev = yog_abi::YogAttackEntityEvent {
2166        player: YogStr::from_str(&p), target_type: YogStr::from_str(&tt), target_uuid: YogStr::from_str(&tu),
2167    };
2168    let srv = srv_ptr();
2169    guard("on_attack_entity", || {
2170        for (ud, f) in &handlers().attack_entity {
2171            unsafe { f(*ud, srv, &ev, 1) };
2172        }
2173    });
2174}
2175
2176#[no_mangle]
2177pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityDamage<'l>(
2178    mut env: JNIEnv<'l>, _class: JClass<'l>,
2179    entity_type: JString<'l>, uuid: JString<'l>, amount: jfloat, source: JString<'l>,
2180) {
2181    let (et, u, s) = (jstr!(env, entity_type), jstr!(env, uuid), jstr!(env, source));
2182    let ev = yog_abi::YogEntityDamageEvent {
2183        entity_type: YogStr::from_str(&et), uuid: YogStr::from_str(&u),
2184        amount, source: YogStr::from_str(&s),
2185    };
2186    let srv = srv_ptr();
2187    guard("on_entity_damage", || {
2188        for (ud, f) in &handlers().entity_damage {
2189            unsafe { f(*ud, srv, &ev, 1) };
2190        }
2191    });
2192}
2193
2194#[no_mangle]
2195pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityDeath<'l>(
2196    mut env: JNIEnv<'l>, _class: JClass<'l>,
2197    entity_type: JString<'l>, uuid: JString<'l>, source: JString<'l>,
2198) {
2199    let (et, u, s) = (jstr!(env, entity_type), jstr!(env, uuid), jstr!(env, source));
2200    let ev = yog_abi::YogEntityDeathEvent {
2201        entity_type: YogStr::from_str(&et), uuid: YogStr::from_str(&u), source: YogStr::from_str(&s),
2202    };
2203    let srv = srv_ptr();
2204    guard("on_entity_death", || {
2205        for (ud, f) in &handlers().entity_death {
2206            unsafe { f(*ud, srv, &ev, 1) };
2207        }
2208    });
2209}
2210
2211#[no_mangle]
2212pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnTick<'l>(
2213    _env: JNIEnv<'l>, _class: JClass<'l>,
2214) {
2215    let h = handlers();
2216    let srv = srv_ptr();
2217    guard("on_tick", || {
2218        for (ud, f) in &h.server_tick {
2219            unsafe { f(*ud, srv) };
2220        }
2221    });
2222
2223    guard("startup_grants", process_pending_grants);
2224
2225    // Scheduler — once tasks
2226    {
2227        let mut sched = h.scheduler.lock().expect("scheduler poisoned");
2228        let mut to_fire: Vec<(*mut c_void, YogScheduledFn)> = Vec::new();
2229        let mut remaining = Vec::new();
2230        for task in sched.once_tasks.drain(..) {
2231            if task.delay_remaining == 0 {
2232                to_fire.push((task.ud, task.f));
2233            } else {
2234                remaining.push(OnceTask { delay_remaining: task.delay_remaining - 1, ..task });
2235            }
2236        }
2237        sched.once_tasks = remaining;
2238        drop(sched);
2239        for (ud, f) in to_fire {
2240            guard("schedule_once", || unsafe { f(ud, srv) });
2241        }
2242    }
2243
2244    // Scheduler — repeating tasks
2245    {
2246        let mut sched = h.scheduler.lock().expect("scheduler poisoned");
2247        let mut to_fire: Vec<(*mut c_void, YogScheduledFn)> = Vec::new();
2248        for task in &mut sched.repeating_tasks {
2249            if task.ticks_left == 0 {
2250                to_fire.push((task.ud, task.f));
2251                task.ticks_left = task.period;
2252            } else {
2253                task.ticks_left -= 1;
2254            }
2255        }
2256        drop(sched);
2257        for (ud, f) in to_fire {
2258            guard("schedule_repeating", || unsafe { f(ud, srv) });
2259        }
2260    }
2261}
2262
2263/// Absolute path of the current world save folder (set on server start).
2264static WORLD_DIR: Mutex<Option<std::path::PathBuf>> = Mutex::new(None);
2265
2266/// Per-world data path: `<world>/yog-data/startup_grants.json`.
2267/// Falls back to the working directory before any server has started.
2268fn startup_grants_path() -> std::path::PathBuf {
2269    let base = WORLD_DIR.lock().ok()
2270        .and_then(|d| d.clone())
2271        .unwrap_or_else(|| std::path::PathBuf::from("."));
2272    base.join("yog-data").join("startup_grants.json")
2273}
2274
2275fn load_startup_granted() {
2276    let h = handlers();
2277    let mut granted = h.startup_granted.lock().expect("startup_granted poisoned");
2278    // Reset first — in singleplayer the process outlives individual worlds,
2279    // and grant state is per-world.
2280    granted.clear();
2281    h.pending_grants.lock().expect("pending_grants poisoned").clear();
2282    let path = startup_grants_path();
2283    let Ok(data) = std::fs::read_to_string(&path) else { return };
2284    let Ok(keys) = serde_json::from_str::<Vec<String>>(&data) else {
2285        yog_logging::warn!("startup_grants.json: invalid JSON, ignoring");
2286        return;
2287    };
2288    for k in keys {
2289        granted.insert(k, true);
2290    }
2291    yog_logging::info!("loaded {} startup grants from disk", granted.len());
2292}
2293
2294fn save_startup_granted(granted: &HashMap<String, bool>) {
2295    let path = startup_grants_path();
2296    if let Some(parent) = path.parent() {
2297        let _ = std::fs::create_dir_all(parent);
2298    }
2299    let keys: Vec<&String> = granted.keys().collect();
2300    match serde_json::to_string(&keys) {
2301        Ok(json) => { let _ = std::fs::write(&path, json); }
2302        Err(e) => yog_logging::error!("failed to save startup_grants.json: {}", e),
2303    }
2304}
2305
2306#[no_mangle]
2307pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnServerStarted<'l>(
2308    mut env: JNIEnv<'l>, _class: JClass<'l>,
2309    world_dir: JString<'l>,
2310) {
2311    let dir = jstr!(env, world_dir);
2312    *WORLD_DIR.lock().expect("WORLD_DIR poisoned") =
2313        if dir.is_empty() { None } else { Some(std::path::PathBuf::from(dir)) };
2314    load_startup_granted();
2315    let srv = srv_ptr();
2316    guard("on_server_started", || {
2317        for (ud, f) in &handlers().server_started {
2318            unsafe { f(*ud, srv) };
2319        }
2320    });
2321}
2322
2323#[no_mangle]
2324pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnServerStopping<'l>(
2325    _env: JNIEnv<'l>, _class: JClass<'l>,
2326) {
2327    let srv = srv_ptr();
2328    guard("on_server_stopping", || {
2329        for (ud, f) in &handlers().server_stopping {
2330            unsafe { f(*ud, srv) };
2331        }
2332    });
2333}
2334
2335#[no_mangle]
2336pub extern "system" fn Java_dev_yog_NativeBridge_nativeCommandNames<'l>(
2337    env: JNIEnv<'l>, _class: JClass<'l>,
2338) -> jstring {
2339    let names = handlers().commands.keys().cloned().collect::<Vec<_>>().join("\n");
2340    env.new_string(names).map(|s| s.into_raw()).unwrap_or(std::ptr::null_mut())
2341}
2342
2343#[no_mangle]
2344pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnBlockBreakPre<'l>(
2345    mut env: JNIEnv<'l>, _class: JClass<'l>,
2346    player: JString<'l>, block: JString<'l>, x: jint, y: jint, z: jint,
2347) -> jni::sys::jboolean {
2348    let h = handlers();
2349    if h.block_break.is_empty() { return 1; }
2350    let p = match env.get_string(&player) { Ok(s) => String::from(s), Err(_) => return 1 };
2351    let b = match env.get_string(&block)  { Ok(s) => String::from(s), Err(_) => return 1 };
2352    let ev = yog_abi::YogBlockBreakEvent {
2353        player: YogStr::from_str(&p), block: YogStr::from_str(&b),
2354        pos: YogBlockPos { x, y, z },
2355    };
2356    let srv = srv_ptr();
2357    let mut allow = true;
2358    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2359        for (ud, f) in &h.block_break {
2360            if !unsafe { f(*ud, srv, &ev, 0) } { allow = false; break; }
2361        }
2362    })).ok();
2363    allow as jni::sys::jboolean
2364}
2365
2366#[no_mangle]
2367pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnChatPre<'l>(
2368    mut env: JNIEnv<'l>, _class: JClass<'l>,
2369    player: JString<'l>, message: JString<'l>,
2370) -> jni::sys::jboolean {
2371    let h = handlers();
2372    if h.chat.is_empty() { return 1; }
2373    let p = match env.get_string(&player)  { Ok(s) => String::from(s), Err(_) => return 1 };
2374    let m = match env.get_string(&message) { Ok(s) => String::from(s), Err(_) => return 1 };
2375    let ev = yog_abi::YogChatEvent { player: YogStr::from_str(&p), message: YogStr::from_str(&m) };
2376    let srv = srv_ptr();
2377    let mut allow = true;
2378    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2379        for (ud, f) in &h.chat {
2380            if !unsafe { f(*ud, srv, &ev, 0) } { allow = false; break; }
2381        }
2382    })).ok();
2383    allow as jni::sys::jboolean
2384}
2385
2386#[no_mangle]
2387pub extern "system" fn Java_dev_yog_NativeBridge_nativeRecipeJsons<'l>(
2388    env: JNIEnv<'l>, _class: JClass<'l>,
2389) -> jstring {
2390    let s = handlers().recipes.iter()
2391        .map(|(ns, name, json)| format!("{}\t{}\t{}", ns, name, json))
2392        .collect::<Vec<_>>().join("\n");
2393    env.new_string(s).map(|s| s.into_raw()).unwrap_or(std::ptr::null_mut())
2394}
2395
2396#[no_mangle]
2397pub extern "system" fn Java_dev_yog_NativeBridge_nativeTypedCommandSchemas<'l>(
2398    env: JNIEnv<'l>, _class: JClass<'l>,
2399) -> jstring {
2400    // One line per DISTINCT (name, schema) pair — a name can have several
2401    // typed registrations (different arg shapes); Brigadier merges repeated
2402    // `dispatcher.register()` calls for the same literal name into one tree,
2403    // so the Java side just needs every distinct schema once each.
2404    let mut lines = Vec::new();
2405    for (name, regs) in handlers().commands.iter() {
2406        let mut seen = std::collections::HashSet::new();
2407        for (schema, _, _) in regs {
2408            if let Some(schema) = schema {
2409                if seen.insert(schema.as_str()) {
2410                    lines.push(format!("{}\t{}", name, schema));
2411                }
2412            }
2413        }
2414    }
2415    env.new_string(lines.join("\n")).map(|s| s.into_raw()).unwrap_or(std::ptr::null_mut())
2416}
2417
2418#[no_mangle]
2419pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnCommand<'l>(
2420    mut env: JNIEnv<'l>, _class: JClass<'l>,
2421    name: JString<'l>, args: JString<'l>, source: JString<'l>, uuid: JString<'l>,
2422) -> jstring {
2423    let (n, a, s, u) = (
2424        env.get_string(&name).map(String::from).unwrap_or_default(),
2425        env.get_string(&args).map(String::from).unwrap_or_default(),
2426        env.get_string(&source).map(String::from).unwrap_or_default(),
2427        env.get_string(&uuid).map(String::from).unwrap_or_default(),
2428    );
2429    let ev = yog_abi::YogCommandEvent {
2430        name: YogStr::from_str(&n), args: YogStr::from_str(&a),
2431        source: YogStr::from_str(&s), uuid: YogStr::from_str(&u),
2432    };
2433    let h = handlers();
2434    let srv = srv_ptr();
2435    // Actual arg count of this invocation (0 for a bare command with no args).
2436    let actual_argc = if a.is_empty() { 0 } else { a.split('\t').count() };
2437    let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2438        let Some(regs) = h.commands.get(&n) else { return String::new() };
2439        for (schema, ud, f) in regs {
2440            let expected_argc = schema.as_ref().map_or(0, |s| s.split_whitespace().count());
2441            if expected_argc != actual_argc { continue; }
2442            let mut buf = [0u8; 4096];
2443            let mut reply_len: u32 = 0;
2444            unsafe { f(*ud, srv, &ev, buf.as_mut_ptr(), buf.len() as u32, &mut reply_len) };
2445            if reply_len > 0 {
2446                return String::from_utf8_lossy(&buf[..reply_len as usize]).into_owned();
2447            }
2448        }
2449        String::new()
2450    }))
2451    .unwrap_or_else(|_| { yog_logging::error!("a mod panicked handling command `{}`", n); String::new() });
2452
2453    env.new_string(reply).map(|s| s.into_raw()).unwrap_or(std::ptr::null_mut())
2454}
2455
2456#[no_mangle]
2457pub extern "system" fn Java_dev_yog_NativeBridge_nativeItemDefs<'l>(
2458    env: JNIEnv<'l>, _class: JClass<'l>,
2459) -> jstring {
2460    let s = handlers().items.iter().map(|d| {
2461        let mut parts = vec![d.id.clone()];
2462        parts.push(format!("max_stack={}", d.max_stack));
2463        if let Some(n) = &d.name    { parts.push(format!("name={n}")); }
2464        if let Some(t) = &d.tooltip { parts.push(format!("tooltip={t}")); }
2465        if d.max_damage > 0         { parts.push(format!("max_damage={}", d.max_damage)); }
2466        if d.fire_resistant         { parts.push("fire_resistant=1".into()); }
2467        if d.fuel_ticks > 0         { parts.push(format!("fuel_ticks={}", d.fuel_ticks)); }
2468        if let Some(f) = &d.food {
2469            parts.push(format!("food={}:{}:{}", f.nutrition, f.saturation, if f.can_always_eat { 1 } else { 0 }));
2470        }
2471        parts.join("\t")
2472    }).collect::<Vec<_>>().join("\n");
2473    env.new_string(s).map(|s| s.into_raw()).unwrap_or(std::ptr::null_mut())
2474}
2475
2476#[no_mangle]
2477pub extern "system" fn Java_dev_yog_NativeBridge_nativeBlockDefs<'l>(
2478    env: JNIEnv<'l>, _class: JClass<'l>,
2479) -> jstring {
2480    let s = handlers().blocks.iter().map(|d| {
2481        let mut parts = vec![d.id.clone()];
2482        parts.push(format!("hardness={}", d.hardness));
2483        parts.push(format!("resistance={}", d.resistance));
2484        if let Some(n) = &d.name { parts.push(format!("name={n}")); }
2485        if let Some(sh) = d.shape {
2486            parts.push(format!("shape={}:{}:{}:{}:{}:{}", sh[0], sh[1], sh[2], sh[3], sh[4], sh[5]));
2487        }
2488        if d.light_level > 0    { parts.push(format!("light={}", d.light_level)); }
2489        if let Some(snd) = &d.sound { parts.push(format!("sound={snd}")); }
2490        if d.requires_tool       { parts.push("requires_tool=1".into()); }
2491        if d.no_collision        { parts.push("no_collision=1".into()); }
2492        if d.slipperiness > 0.0  { parts.push(format!("slipperiness={}", d.slipperiness)); }
2493        if d.connects            { parts.push("connects=1".into()); }
2494        if !d.connect_groups.is_empty() { parts.push(format!("connect_groups={}", d.connect_groups.join(","))); }
2495        if let Some(inv) = &d.inventory_id { parts.push(format!("inventory_id={inv}")); }
2496        parts.join("\t")
2497    }).collect::<Vec<_>>().join("\n");
2498    env.new_string(s).map(|s| s.into_raw()).unwrap_or(std::ptr::null_mut())
2499}
2500
2501/// Tab/newline-encoded inventory defs — one line per registered
2502/// `InventoryDef` (see `yog_inventory`): `id\tslot_count=N\tlayout=x:y,...
2503/// \tinclude_player_inventory=0|1\tplayer_inv=x:y\tbackground_texture=...\ttitle=...`
2504#[no_mangle]
2505pub extern "system" fn Java_dev_yog_NativeBridge_nativeInventoryDefs<'l>(
2506    env: JNIEnv<'l>, _class: JClass<'l>,
2507) -> jstring {
2508    let s = handlers().inventories.iter().map(|d| {
2509        let mut parts = vec![d.id.clone()];
2510        parts.push(format!("slot_count={}", d.slot_count));
2511        parts.push(format!("layout={}", yog_inventory::encode_layout(&d.resolved_layout())));
2512        parts.push(format!("include_player_inventory={}", d.include_player_inventory as u8));
2513        parts.push(format!("player_inv={}:{}", d.player_inv_offset.0, d.player_inv_offset.1));
2514        if let Some(tex) = &d.background_texture { parts.push(format!("background_texture={tex}")); }
2515        if !d.title.is_empty() { parts.push(format!("title={}", d.title)); }
2516        parts.join("\t")
2517    }).collect::<Vec<_>>().join("\n");
2518    env.new_string(s).map(|s| s.into_raw()).unwrap_or(std::ptr::null_mut())
2519}
2520
2521#[no_mangle]
2522pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPacket<'l>(
2523    mut env: JNIEnv<'l>, _class: JClass<'l>,
2524    channel: JString<'l>, player: JString<'l>, payload: JByteArray<'l>,
2525) {
2526    let ch = env.get_string(&channel).map(String::from).unwrap_or_default();
2527    let pl = env.get_string(&player).map(String::from).unwrap_or_default();
2528    let data = env.convert_byte_array(&payload).unwrap_or_default();
2529    let ev = yog_abi::YogPacketEvent {
2530        channel: YogStr::from_str(&ch), player: YogStr::from_str(&pl),
2531        payload: data.as_ptr(), payload_len: data.len() as u32,
2532    };
2533    let h = handlers();
2534    let srv = srv_ptr();
2535    guard("on_packet", || {
2536        if let Some((ud, f)) = h.packets.get(&ch) {
2537            unsafe { f(*ud, srv, &ev) };
2538        }
2539    });
2540}
2541
2542#[no_mangle]
2543pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnClientPacket<'l>(
2544    mut env: JNIEnv<'l>, _class: JClass<'l>,
2545    channel: JString<'l>, payload: JByteArray<'l>,
2546) {
2547    let ch = env.get_string(&channel).map(String::from).unwrap_or_default();
2548    let data = env.convert_byte_array(&payload).unwrap_or_default();
2549    let ev = yog_abi::YogPacketEvent {
2550        channel: YogStr::from_str(&ch), player: YogStr::EMPTY,
2551        payload: data.as_ptr(), payload_len: data.len() as u32,
2552    };
2553    let h = handlers();
2554    let srv = srv_ptr();
2555    guard("on_client_packet", || {
2556        if let Some((ud, f)) = h.client_packets.get(&ch) {
2557            unsafe { f(*ud, srv, &ev) };
2558        }
2559    });
2560}
2561
2562#[no_mangle]
2563pub extern "system" fn Java_dev_yog_NativeBridge_nativePacketChannels<'l>(
2564    env: JNIEnv<'l>, _class: JClass<'l>,
2565) -> jstring {
2566    let s = handlers().packets.keys().cloned().collect::<Vec<_>>().join("\n");
2567    env.new_string(s).map(|s| s.into_raw()).unwrap_or(std::ptr::null_mut())
2568}
2569
2570#[no_mangle]
2571pub extern "system" fn Java_dev_yog_NativeBridge_nativeClientPacketChannels<'l>(
2572    env: JNIEnv<'l>, _class: JClass<'l>,
2573) -> jstring {
2574    let s = handlers().client_packets.keys().cloned().collect::<Vec<_>>().join("\n");
2575    env.new_string(s).map(|s| s.into_raw()).unwrap_or(std::ptr::null_mut())
2576}
2577
2578#[no_mangle]
2579pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntitySpawn<'l>(
2580    mut env: JNIEnv<'l>, _class: JClass<'l>,
2581    entity_type: JString<'l>, uuid: JString<'l>, dimension: JString<'l>,
2582) {
2583    let h = handlers();
2584    if h.entity_spawn.is_empty() { return; }
2585    let (et, u, d) = (jstr!(env, entity_type), jstr!(env, uuid), jstr!(env, dimension));
2586    let ev = yog_abi::YogEntitySpawnEvent {
2587        entity_type: YogStr::from_str(&et), uuid: YogStr::from_str(&u),
2588        dimension: YogStr::from_str(&d),
2589    };
2590    let srv = srv_ptr();
2591    guard("on_entity_spawn", || {
2592        for (ud, f) in &h.entity_spawn {
2593            unsafe { f(*ud, srv, &ev, 1) };
2594        }
2595    });
2596}
2597
2598#[no_mangle]
2599pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntitySpawnPre<'l>(
2600    mut env: JNIEnv<'l>, _class: JClass<'l>,
2601    entity_type: JString<'l>, uuid: JString<'l>, dimension: JString<'l>,
2602) -> jni::sys::jboolean {
2603    let h = handlers();
2604    if h.entity_spawn.is_empty() { return 1; }
2605    let et = match env.get_string(&entity_type) { Ok(s) => String::from(s), Err(_) => return 1 };
2606    let u  = match env.get_string(&uuid)        { Ok(s) => String::from(s), Err(_) => return 1 };
2607    let d  = match env.get_string(&dimension)   { Ok(s) => String::from(s), Err(_) => return 1 };
2608    let ev = yog_abi::YogEntitySpawnEvent {
2609        entity_type: YogStr::from_str(&et), uuid: YogStr::from_str(&u),
2610        dimension: YogStr::from_str(&d),
2611    };
2612    let srv = srv_ptr();
2613    let mut allow = true;
2614    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2615        for (ud, f) in &h.entity_spawn {
2616            if !unsafe { f(*ud, srv, &ev, 0) } { allow = false; break; }
2617        }
2618    })).ok();
2619    allow as jni::sys::jboolean
2620}
2621
2622#[no_mangle]
2623pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityDamagePre<'l>(
2624    mut env: JNIEnv<'l>, _class: JClass<'l>,
2625    entity_type: JString<'l>, uuid: JString<'l>, amount: jfloat, source: JString<'l>,
2626) -> jni::sys::jboolean {
2627    let h = handlers();
2628    if h.entity_damage.is_empty() { return 1; }
2629    let et = match env.get_string(&entity_type) { Ok(s) => String::from(s), Err(_) => return 1 };
2630    let u  = match env.get_string(&uuid)        { Ok(s) => String::from(s), Err(_) => return 1 };
2631    let s  = match env.get_string(&source)      { Ok(s) => String::from(s), Err(_) => return 1 };
2632    let ev = yog_abi::YogEntityDamageEvent {
2633        entity_type: YogStr::from_str(&et), uuid: YogStr::from_str(&u),
2634        amount, source: YogStr::from_str(&s),
2635    };
2636    let srv = srv_ptr();
2637    let mut allow = true;
2638    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2639        for (ud, f) in &h.entity_damage {
2640            if !unsafe { f(*ud, srv, &ev, 0) } { allow = false; break; }
2641        }
2642    })).ok();
2643    allow as jni::sys::jboolean
2644}
2645
2646#[no_mangle]
2647pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlaceBlockPre<'l>(
2648    mut env: JNIEnv<'l>, _class: JClass<'l>,
2649    player: JString<'l>, block: JString<'l>, x: jint, y: jint, z: jint,
2650) -> jni::sys::jboolean {
2651    let h = handlers();
2652    if h.player_place_block.is_empty() { return 1; }
2653    let p = match env.get_string(&player) { Ok(s) => String::from(s), Err(_) => return 1 };
2654    let b = match env.get_string(&block)  { Ok(s) => String::from(s), Err(_) => return 1 };
2655    let ev = YogPlaceBlockEvent {
2656        player: YogStr::from_str(&p), block: YogStr::from_str(&b),
2657        pos: YogBlockPos { x, y, z },
2658    };
2659    let srv = srv_ptr();
2660    let mut allow = true;
2661    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2662        for (ud, f) in &h.player_place_block {
2663            if !unsafe { f(*ud, srv, &ev, 0) } { allow = false; break; }
2664        }
2665    })).ok();
2666    allow as jni::sys::jboolean
2667}
2668
2669#[no_mangle]
2670pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlaceBlock<'l>(
2671    mut env: JNIEnv<'l>, _class: JClass<'l>,
2672    player: JString<'l>, block: JString<'l>, x: jint, y: jint, z: jint,
2673) {
2674    let h = handlers();
2675    if h.player_place_block.is_empty() { return; }
2676    let (p, b) = (jstr!(env, player), jstr!(env, block));
2677    let ev = YogPlaceBlockEvent {
2678        player: YogStr::from_str(&p), block: YogStr::from_str(&b),
2679        pos: YogBlockPos { x, y, z },
2680    };
2681    let srv = srv_ptr();
2682    guard("on_player_place_block", || {
2683        for (ud, f) in &h.player_place_block {
2684            unsafe { f(*ud, srv, &ev, 1) };
2685        }
2686    });
2687}
2688
2689#[no_mangle]
2690pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerDeathPre<'l>(
2691    mut env: JNIEnv<'l>, _class: JClass<'l>,
2692    player: JString<'l>, uuid: JString<'l>, source: JString<'l>,
2693) -> jni::sys::jboolean {
2694    let h = handlers();
2695    if h.player_death.is_empty() { return 1; }
2696    let p  = match env.get_string(&player) { Ok(s) => String::from(s), Err(_) => return 1 };
2697    let u  = match env.get_string(&uuid)   { Ok(s) => String::from(s), Err(_) => return 1 };
2698    let s  = match env.get_string(&source) { Ok(s) => String::from(s), Err(_) => return 1 };
2699    let ev = YogPlayerDeathEvent {
2700        player: YogStr::from_str(&p), uuid: YogStr::from_str(&u), source: YogStr::from_str(&s),
2701    };
2702    let srv = srv_ptr();
2703    let mut allow = true;
2704    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2705        for (ud, f) in &h.player_death {
2706            if !unsafe { f(*ud, srv, &ev, 0) } { allow = false; break; }
2707        }
2708    })).ok();
2709    allow as jni::sys::jboolean
2710}
2711
2712#[no_mangle]
2713pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerDeath<'l>(
2714    mut env: JNIEnv<'l>, _class: JClass<'l>,
2715    player: JString<'l>, uuid: JString<'l>, source: JString<'l>,
2716) {
2717    let h = handlers();
2718    if h.player_death.is_empty() { return; }
2719    let (p, u, s) = (jstr!(env, player), jstr!(env, uuid), jstr!(env, source));
2720    let ev = YogPlayerDeathEvent {
2721        player: YogStr::from_str(&p), uuid: YogStr::from_str(&u), source: YogStr::from_str(&s),
2722    };
2723    let srv = srv_ptr();
2724    guard("on_player_death", || {
2725        for (ud, f) in &h.player_death {
2726            unsafe { f(*ud, srv, &ev, 1) };
2727        }
2728    });
2729}
2730
2731#[no_mangle]
2732pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerRespawn<'l>(
2733    mut env: JNIEnv<'l>, _class: JClass<'l>,
2734    player: JString<'l>, uuid: JString<'l>, at_anchor: jni::sys::jboolean,
2735) {
2736    let h = handlers();
2737    if h.player_respawn.is_empty() { return; }
2738    let (p, u) = (jstr!(env, player), jstr!(env, uuid));
2739    let ev = YogPlayerRespawnEvent {
2740        player: YogStr::from_str(&p), uuid: YogStr::from_str(&u), at_anchor: at_anchor != 0,
2741    };
2742    let srv = srv_ptr();
2743    guard("on_player_respawn", || {
2744        for (ud, f) in &h.player_respawn {
2745            unsafe { f(*ud, srv, &ev, 1) };
2746        }
2747    });
2748}
2749
2750#[no_mangle]
2751pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnAdvancement<'l>(
2752    mut env: JNIEnv<'l>, _class: JClass<'l>,
2753    player: JString<'l>, uuid: JString<'l>, advancement: JString<'l>,
2754) {
2755    let h = handlers();
2756    if h.advancement.is_empty() { return; }
2757    let (p, u, a) = (jstr!(env, player), jstr!(env, uuid), jstr!(env, advancement));
2758    let ev = YogAdvancementEvent {
2759        player: YogStr::from_str(&p), uuid: YogStr::from_str(&u), advancement: YogStr::from_str(&a),
2760    };
2761    let srv = srv_ptr();
2762    guard("on_advancement", || {
2763        for (ud, f) in &h.advancement {
2764            unsafe { f(*ud, srv, &ev, 1) };
2765        }
2766    });
2767}
2768
2769#[no_mangle]
2770pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityInteractPre<'l>(
2771    mut env: JNIEnv<'l>, _class: JClass<'l>,
2772    player: JString<'l>, player_uuid: JString<'l>,
2773    entity_type: JString<'l>, entity_uuid: JString<'l>, hand: JString<'l>,
2774) -> jni::sys::jboolean {
2775    let h = handlers();
2776    if h.entity_interact.is_empty() { return 1; }
2777    let p  = match env.get_string(&player)      { Ok(s) => String::from(s), Err(_) => return 1 };
2778    let pu = match env.get_string(&player_uuid)  { Ok(s) => String::from(s), Err(_) => return 1 };
2779    let et = match env.get_string(&entity_type)  { Ok(s) => String::from(s), Err(_) => return 1 };
2780    let eu = match env.get_string(&entity_uuid)  { Ok(s) => String::from(s), Err(_) => return 1 };
2781    let ha = match env.get_string(&hand)         { Ok(s) => String::from(s), Err(_) => return 1 };
2782    let ev = YogEntityInteractEvent {
2783        player: YogStr::from_str(&p), player_uuid: YogStr::from_str(&pu),
2784        entity_type: YogStr::from_str(&et), entity_uuid: YogStr::from_str(&eu),
2785        hand: YogStr::from_str(&ha),
2786    };
2787    let srv = srv_ptr();
2788    let mut allow = true;
2789    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2790        for (ud, f) in &h.entity_interact {
2791            if !unsafe { f(*ud, srv, &ev, 0) } { allow = false; break; }
2792        }
2793    })).ok();
2794    allow as jni::sys::jboolean
2795}
2796
2797#[no_mangle]
2798pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityInteract<'l>(
2799    mut env: JNIEnv<'l>, _class: JClass<'l>,
2800    player: JString<'l>, player_uuid: JString<'l>,
2801    entity_type: JString<'l>, entity_uuid: JString<'l>, hand: JString<'l>,
2802) {
2803    let h = handlers();
2804    if h.entity_interact.is_empty() { return; }
2805    let (p, pu) = (jstr!(env, player), jstr!(env, player_uuid));
2806    let (et, eu, ha) = (jstr!(env, entity_type), jstr!(env, entity_uuid), jstr!(env, hand));
2807    let ev = YogEntityInteractEvent {
2808        player: YogStr::from_str(&p), player_uuid: YogStr::from_str(&pu),
2809        entity_type: YogStr::from_str(&et), entity_uuid: YogStr::from_str(&eu),
2810        hand: YogStr::from_str(&ha),
2811    };
2812    let srv = srv_ptr();
2813    guard("on_entity_interact", || {
2814        for (ud, f) in &h.entity_interact {
2815            unsafe { f(*ud, srv, &ev, 1) };
2816        }
2817    });
2818}
2819
2820#[no_mangle]
2821pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnItemCraft<'l>(
2822    mut env: JNIEnv<'l>, _class: JClass<'l>,
2823    player: JString<'l>, player_uuid: JString<'l>,
2824    result_item: JString<'l>, result_count: jint,
2825) {
2826    let h = handlers();
2827    if h.item_craft.is_empty() { return; }
2828    let (p, pu, ri) = (jstr!(env, player), jstr!(env, player_uuid), jstr!(env, result_item));
2829    let ev = YogCraftEvent {
2830        player: YogStr::from_str(&p), player_uuid: YogStr::from_str(&pu),
2831        result_item: YogStr::from_str(&ri), result_count: result_count as u32,
2832    };
2833    let srv = srv_ptr();
2834    guard("on_item_craft", || {
2835        for (ud, f) in &h.item_craft {
2836            unsafe { f(*ud, srv, &ev, 1) };
2837        }
2838    });
2839}
2840
2841#[no_mangle]
2842pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnExplosionPre<'l>(
2843    mut env: JNIEnv<'l>, _class: JClass<'l>,
2844    dimension: JString<'l>, x: jdouble, y: jdouble, z: jdouble,
2845    power: jfloat, cause_uuid: JString<'l>,
2846) -> jni::sys::jboolean {
2847    let h = handlers();
2848    if h.explosion.is_empty() { return 1; }
2849    let d  = match env.get_string(&dimension)  { Ok(s) => String::from(s), Err(_) => return 1 };
2850    let cu = match env.get_string(&cause_uuid) { Ok(s) => String::from(s), Err(_) => return 1 };
2851    let ev = YogExplosionEvent {
2852        dimension: YogStr::from_str(&d), x, y, z, power, cause_uuid: YogStr::from_str(&cu),
2853    };
2854    let srv = srv_ptr();
2855    let mut allow = true;
2856    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2857        for (ud, f) in &h.explosion {
2858            if !unsafe { f(*ud, srv, &ev, 0) } { allow = false; break; }
2859        }
2860    })).ok();
2861    allow as jni::sys::jboolean
2862}
2863
2864#[no_mangle]
2865pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnExplosion<'l>(
2866    mut env: JNIEnv<'l>, _class: JClass<'l>,
2867    dimension: JString<'l>, x: jdouble, y: jdouble, z: jdouble,
2868    power: jfloat, cause_uuid: JString<'l>,
2869) {
2870    let h = handlers();
2871    if h.explosion.is_empty() { return; }
2872    let (d, cu) = (jstr!(env, dimension), jstr!(env, cause_uuid));
2873    let ev = YogExplosionEvent {
2874        dimension: YogStr::from_str(&d), x, y, z, power, cause_uuid: YogStr::from_str(&cu),
2875    };
2876    let srv = srv_ptr();
2877    guard("on_explosion", || {
2878        for (ud, f) in &h.explosion {
2879            unsafe { f(*ud, srv, &ev, 1) };
2880        }
2881    });
2882}
2883
2884// ── ABI minor 9 JNI entry points ─────────────────────────────────────────────
2885
2886#[no_mangle]
2887pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnItemPickupPre<'l>(
2888    mut env: JNIEnv<'l>, _class: JClass<'l>,
2889    player: JString<'l>, player_uuid: JString<'l>,
2890    item_id: JString<'l>, item_count: jint, entity_uuid: JString<'l>,
2891) -> jni::sys::jboolean {
2892    let h = handlers();
2893    if h.item_pickup.is_empty() { return 1; }
2894    let p   = match env.get_string(&player)      { Ok(s) => String::from(s), Err(_) => return 1 };
2895    let pu  = match env.get_string(&player_uuid)  { Ok(s) => String::from(s), Err(_) => return 1 };
2896    let ii  = match env.get_string(&item_id)      { Ok(s) => String::from(s), Err(_) => return 1 };
2897    let eu  = match env.get_string(&entity_uuid)  { Ok(s) => String::from(s), Err(_) => return 1 };
2898    let ev = YogItemPickupEvent {
2899        player: YogStr::from_str(&p), player_uuid: YogStr::from_str(&pu),
2900        item_id: YogStr::from_str(&ii), item_count: item_count as u32,
2901        entity_uuid: YogStr::from_str(&eu),
2902    };
2903    let srv = srv_ptr();
2904    let mut allow = true;
2905    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2906        for (ud, f) in &h.item_pickup {
2907            if !unsafe { f(*ud, srv, &ev, 0) } { allow = false; break; }
2908        }
2909    })).ok();
2910    allow as jni::sys::jboolean
2911}
2912
2913#[no_mangle]
2914pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnItemPickup<'l>(
2915    mut env: JNIEnv<'l>, _class: JClass<'l>,
2916    player: JString<'l>, player_uuid: JString<'l>,
2917    item_id: JString<'l>, item_count: jint, entity_uuid: JString<'l>,
2918) {
2919    let h = handlers();
2920    if h.item_pickup.is_empty() { return; }
2921    let (p, pu) = (jstr!(env, player), jstr!(env, player_uuid));
2922    let (ii, eu) = (jstr!(env, item_id), jstr!(env, entity_uuid));
2923    let ev = YogItemPickupEvent {
2924        player: YogStr::from_str(&p), player_uuid: YogStr::from_str(&pu),
2925        item_id: YogStr::from_str(&ii), item_count: item_count as u32,
2926        entity_uuid: YogStr::from_str(&eu),
2927    };
2928    let srv = srv_ptr();
2929    guard("on_item_pickup", || {
2930        for (ud, f) in &h.item_pickup {
2931            unsafe { f(*ud, srv, &ev, 1) };
2932        }
2933    });
2934}
2935
2936#[no_mangle]
2937pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerMove<'l>(
2938    mut env: JNIEnv<'l>, _class: JClass<'l>,
2939    player: JString<'l>, player_uuid: JString<'l>,
2940    x: jdouble, y: jdouble, z: jdouble, yaw: jfloat, pitch: jfloat,
2941) {
2942    let h = handlers();
2943    if h.player_move.is_empty() { return; }
2944    let (p, pu) = (jstr!(env, player), jstr!(env, player_uuid));
2945    let ev = YogPlayerMoveEvent {
2946        player: YogStr::from_str(&p), player_uuid: YogStr::from_str(&pu),
2947        x, y, z, yaw, pitch,
2948    };
2949    let srv = srv_ptr();
2950    guard("on_player_move", || {
2951        for (ud, f) in &h.player_move {
2952            unsafe { f(*ud, srv, &ev, 1) };
2953        }
2954    });
2955}
2956
2957#[no_mangle]
2958pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnContainerOpenPre<'l>(
2959    mut env: JNIEnv<'l>, _class: JClass<'l>,
2960    player: JString<'l>, player_uuid: JString<'l>,
2961) -> jni::sys::jboolean {
2962    let h = handlers();
2963    if h.container_open.is_empty() { return 1; }
2964    let p  = match env.get_string(&player)      { Ok(s) => String::from(s), Err(_) => return 1 };
2965    let pu = match env.get_string(&player_uuid)  { Ok(s) => String::from(s), Err(_) => return 1 };
2966    let ev = YogContainerOpenEvent {
2967        player: YogStr::from_str(&p), player_uuid: YogStr::from_str(&pu),
2968        container_type: YogStr::EMPTY,
2969    };
2970    let srv = srv_ptr();
2971    let mut allow = true;
2972    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2973        for (ud, f) in &h.container_open {
2974            if !unsafe { f(*ud, srv, &ev, 0) } { allow = false; break; }
2975        }
2976    })).ok();
2977    allow as jni::sys::jboolean
2978}
2979
2980#[no_mangle]
2981pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnContainerOpen<'l>(
2982    mut env: JNIEnv<'l>, _class: JClass<'l>,
2983    player: JString<'l>, player_uuid: JString<'l>, container_type: JString<'l>,
2984) {
2985    let h = handlers();
2986    if h.container_open.is_empty() { return; }
2987    let (p, pu, ct) = (jstr!(env, player), jstr!(env, player_uuid), jstr!(env, container_type));
2988    let ev = YogContainerOpenEvent {
2989        player: YogStr::from_str(&p), player_uuid: YogStr::from_str(&pu),
2990        container_type: YogStr::from_str(&ct),
2991    };
2992    let srv = srv_ptr();
2993    guard("on_container_open", || {
2994        for (ud, f) in &h.container_open {
2995            unsafe { f(*ud, srv, &ev, 1) };
2996        }
2997    });
2998}
2999
3000#[no_mangle]
3001pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnContainerClose<'l>(
3002    mut env: JNIEnv<'l>, _class: JClass<'l>,
3003    player: JString<'l>, player_uuid: JString<'l>,
3004) {
3005    let h = handlers();
3006    if h.container_close.is_empty() { return; }
3007    let (p, pu) = (jstr!(env, player), jstr!(env, player_uuid));
3008    let ev = YogContainerCloseEvent {
3009        player: YogStr::from_str(&p), player_uuid: YogStr::from_str(&pu),
3010    };
3011    let srv = srv_ptr();
3012    guard("on_container_close", || {
3013        for (ud, f) in &h.container_close {
3014            unsafe { f(*ud, srv, &ev, 1) };
3015        }
3016    });
3017}
3018
3019#[no_mangle]
3020pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnProjectileHitPre<'l>(
3021    mut env: JNIEnv<'l>, _class: JClass<'l>,
3022    projectile_type: JString<'l>, projectile_uuid: JString<'l>, shooter_uuid: JString<'l>,
3023    hit_type: JString<'l>, hit_entity_uuid: JString<'l>,
3024    x: jdouble, y: jdouble, z: jdouble, dimension: JString<'l>,
3025) -> jni::sys::jboolean {
3026    let h = handlers();
3027    if h.projectile_hit.is_empty() { return 1; }
3028    let pt  = match env.get_string(&projectile_type)  { Ok(s) => String::from(s), Err(_) => return 1 };
3029    let pu  = match env.get_string(&projectile_uuid)  { Ok(s) => String::from(s), Err(_) => return 1 };
3030    let su  = match env.get_string(&shooter_uuid)     { Ok(s) => String::from(s), Err(_) => return 1 };
3031    let ht  = match env.get_string(&hit_type)         { Ok(s) => String::from(s), Err(_) => return 1 };
3032    let heu = match env.get_string(&hit_entity_uuid)  { Ok(s) => String::from(s), Err(_) => return 1 };
3033    let dim = match env.get_string(&dimension)        { Ok(s) => String::from(s), Err(_) => return 1 };
3034    let ev = YogProjectileHitEvent {
3035        projectile_type: YogStr::from_str(&pt), projectile_uuid: YogStr::from_str(&pu),
3036        shooter_uuid: YogStr::from_str(&su), hit_type: YogStr::from_str(&ht),
3037        hit_entity_uuid: YogStr::from_str(&heu), x, y, z, dimension: YogStr::from_str(&dim),
3038    };
3039    let srv = srv_ptr();
3040    let mut allow = true;
3041    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
3042        for (ud, f) in &h.projectile_hit {
3043            if !unsafe { f(*ud, srv, &ev, 0) } { allow = false; break; }
3044        }
3045    })).ok();
3046    allow as jni::sys::jboolean
3047}
3048
3049#[no_mangle]
3050pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnProjectileHit<'l>(
3051    mut env: JNIEnv<'l>, _class: JClass<'l>,
3052    projectile_type: JString<'l>, projectile_uuid: JString<'l>, shooter_uuid: JString<'l>,
3053    hit_type: JString<'l>, hit_entity_uuid: JString<'l>,
3054    x: jdouble, y: jdouble, z: jdouble, dimension: JString<'l>,
3055) {
3056    let h = handlers();
3057    if h.projectile_hit.is_empty() { return; }
3058    let (pt, pu) = (jstr!(env, projectile_type), jstr!(env, projectile_uuid));
3059    let (su, ht) = (jstr!(env, shooter_uuid), jstr!(env, hit_type));
3060    let (heu, dim) = (jstr!(env, hit_entity_uuid), jstr!(env, dimension));
3061    let ev = YogProjectileHitEvent {
3062        projectile_type: YogStr::from_str(&pt), projectile_uuid: YogStr::from_str(&pu),
3063        shooter_uuid: YogStr::from_str(&su), hit_type: YogStr::from_str(&ht),
3064        hit_entity_uuid: YogStr::from_str(&heu), x, y, z, dimension: YogStr::from_str(&dim),
3065    };
3066    let srv = srv_ptr();
3067    guard("on_projectile_hit", || {
3068        for (ud, f) in &h.projectile_hit {
3069            unsafe { f(*ud, srv, &ev, 1) };
3070        }
3071    });
3072}
3073
3074// ── ABI minor 10 — client-side JNI entry points ───────────────────────────────
3075
3076#[no_mangle]
3077pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnClientTick<'l>(
3078    _env: JNIEnv<'l>, _class: JClass<'l>,
3079) {
3080    let h = handlers();
3081    if h.client_tick.is_empty() { return; }
3082    guard("on_client_tick", || {
3083        for (ud, f) in &h.client_tick {
3084            unsafe { f(*ud) };
3085        }
3086    });
3087}
3088
3089#[no_mangle]
3090pub extern "system" fn Java_dev_yog_NativeBridge_nativeGlInit<'l>(
3091    _env: JNIEnv<'l>, _class: JClass<'l>,
3092) {
3093    if GL.get().is_some() { return; }
3094    let mut raw_get_binary: usize = 0;
3095    let mut raw_prog_binary: usize = 0;
3096    let gl = unsafe {
3097        glow::Context::from_loader_function(|sym| {
3098            let Some(mut env) = get_env() else { return std::ptr::null() };
3099            let jsym = match env.new_string(sym) {
3100                Ok(s) => s,
3101                Err(_) => return std::ptr::null(),
3102            };
3103            let jsym_obj: JObject = jsym.into();
3104            let val = env.call_static_method(
3105                "dev/yog/NativeBridge",
3106                "glProcAddress",
3107                "(Ljava/lang/String;)J",
3108                &[JValue::Object(&jsym_obj)],
3109            );
3110            let ptr = match val.and_then(|v| v.j()) {
3111                Ok(p) if p != 0 => p as usize as *const _,
3112                _ => std::ptr::null(),
3113            };
3114            // Capture extension pointers while the loader runs.
3115            match sym {
3116                "glGetProgramBinary" => raw_get_binary = ptr as usize,
3117                "glProgramBinary"    => raw_prog_binary = ptr as usize,
3118                _ => {}
3119            }
3120            ptr
3121        })
3122    };
3123    let _ = GL.set(GlCtx(gl));
3124    let _ = GL_GET_PROGRAM_BINARY.set(if raw_get_binary != 0 { Some(raw_get_binary) } else { None });
3125    let _ = GL_PROGRAM_BINARY.set(if raw_prog_binary != 0 { Some(raw_prog_binary) } else { None });
3126    // `glGetProgramiv` is a core function; always available.  We look it up once here
3127    // to avoid depending on glow internals for the PROGRAM_BINARY_LENGTH query.
3128    if let Some(mut env) = get_env() {
3129        if let Ok(jsym) = env.new_string("glGetProgramiv") {
3130            let jsym_obj: JObject = jsym.into();
3131            if let Ok(jv) = env.call_static_method(
3132                "dev/yog/NativeBridge", "glProcAddress", "(Ljava/lang/String;)J",
3133                &[JValue::Object(&jsym_obj)],
3134            ) {
3135                if let Ok(ptr) = jv.j() {
3136                    let _ = GL_GET_PROGRAM_IV.set(if ptr != 0 { Some(ptr as usize) } else { None });
3137                }
3138            }
3139        }
3140    }
3141}
3142
3143#[no_mangle]
3144pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnHudRender<'l>(
3145    _env: JNIEnv<'l>, _class: JClass<'l>,
3146    delta_tick: jfloat,
3147    screen_w: jint,
3148    screen_h: jint,
3149    scale_factor: jfloat,
3150    player_x: jfloat, player_y: jfloat, player_z: jfloat,
3151) {
3152    let h = handlers();
3153    let mut gfx = GFX_FN_TABLE;
3154    gfx.screen_w    = screen_w;
3155    gfx.screen_h    = screen_h;
3156    gfx.delta_tick  = delta_tick;
3157    gfx.scale_factor = scale_factor;
3158    gfx.player_pos  = [player_x, player_y, player_z];
3159
3160    // Mod hud_render callbacks.
3161    if !h.hud_render.is_empty() {
3162        guard("on_hud_render", || {
3163            for (ud, f) in &h.hud_render {
3164                unsafe { f(*ud, &gfx) };
3165            }
3166        });
3167    }
3168
3169    // Render active book UIs.
3170    let active_layers: Vec<UiLayer> = h.active_uis.lock().unwrap().clone();
3171    let sw = screen_w as f32;
3172    let sh = screen_h as f32;
3173    let ctx = unsafe { yog_gfx::GfxContext::from_raw(&gfx as *const _) };
3174    let mut renderers = h.book_renderers.lock().unwrap();
3175    for layer in &active_layers {
3176        if !layer.visible { continue; }
3177        if let Some(renderer) = renderers.get_mut(&layer.id) {
3178            renderer.render(&ctx, sw, sh);
3179        }
3180    }
3181}
3182
3183#[no_mangle]
3184pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnWorldRender<'l>(
3185    env: JNIEnv<'l>, _class: JClass<'l>,
3186    delta_tick: jfloat,
3187    screen_w: jint,
3188    screen_h: jint,
3189    scale_factor: jfloat,
3190    view_proj_arr: JFloatArray<'l>,
3191    cam_x: jfloat, cam_y: jfloat, cam_z: jfloat,
3192    player_x: jfloat, player_y: jfloat, player_z: jfloat,
3193) {
3194    let h = handlers();
3195    if h.world_render.is_empty() { return; }
3196    let mut view_proj = [0f32; 16];
3197    if env.get_float_array_region(&view_proj_arr, 0, &mut view_proj).is_err() { return; }
3198    let mut gfx = GFX_FN_TABLE;
3199    gfx.screen_w = screen_w;
3200    gfx.screen_h = screen_h;
3201    gfx.delta_tick = delta_tick;
3202    gfx.scale_factor = scale_factor;
3203    gfx.view_proj = view_proj;
3204    gfx.camera_pos = [cam_x, cam_y, cam_z];
3205    gfx.player_pos = [player_x, player_y, player_z];
3206    guard("on_world_render", || {
3207        for (ud, f) in &h.world_render {
3208            unsafe { f(*ud, &gfx) };
3209        }
3210    });
3211}
3212
3213#[no_mangle]
3214pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnKeyPress<'l>(
3215    _env: JNIEnv<'l>, _class: JClass<'l>,
3216    key_code: jint, scan_code: jint, action: jint, modifiers: jint,
3217) -> jni::sys::jboolean {
3218    let h = handlers();
3219    if h.key_press.is_empty() { return 1; }
3220    let ev = YogKeyPressEvent { key_code, scan_code, action, modifiers };
3221    let mut allow = true;
3222    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
3223        for (ud, f) in &h.key_press {
3224            if !unsafe { f(*ud, &ev) } { allow = false; break; }
3225        }
3226    })).ok();
3227    allow as jni::sys::jboolean
3228}
3229
3230#[no_mangle]
3231pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnScreenOpen<'l>(
3232    mut env: JNIEnv<'l>, _class: JClass<'l>,
3233    screen_class: JString<'l>,
3234) {
3235    let h = handlers();
3236    if h.screen_open.is_empty() { return; }
3237    let sc = match env.get_string(&screen_class) { Ok(s) => String::from(s), Err(_) => return };
3238    guard("on_screen_open", || {
3239        for (ud, f) in &h.screen_open {
3240            unsafe { f(*ud, YogStr::from_str(&sc)) };
3241        }
3242    });
3243}
3244
3245#[no_mangle]
3246pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnScreenClose<'l>(
3247    mut env: JNIEnv<'l>, _class: JClass<'l>,
3248    screen_class: JString<'l>,
3249) {
3250    let h = handlers();
3251    if h.screen_close.is_empty() { return; }
3252    let sc = match env.get_string(&screen_class) { Ok(s) => String::from(s), Err(_) => return };
3253    guard("on_screen_close", || {
3254        for (ud, f) in &h.screen_close {
3255            unsafe { f(*ud, YogStr::from_str(&sc)) };
3256        }
3257    });
3258}
3259
3260
3261mod ui_jni;