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