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, RwLock};
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::Symbol;
26use yog_hot_reload::{HotReloader, LoadedModule, ModuleGeneration, ModuleRegistry};
27
28use yog_abi::{
29    YogAdvancementEvent, YogAdvancementFn, YogApi, YogAttackEntityFn, YogBlockBreakFn, YogBlockDef,
30    YogBlockPos, YogChatFn, YogClientFn, YogCommandFn, YogContainerCloseEvent, YogContainerCloseFn,
31    YogContainerOpenEvent, YogContainerOpenFn, YogCraftEvent, YogCraftFn, YogEntityDamageFn,
32    YogEntityDeathFn, YogEntityInteractEvent, YogEntityInteractFn, YogEntitySpawnFn,
33    YogExplosionEvent, YogExplosionFn, YogGfxApi, YogHudRenderFn, YogItemDef, YogItemPickupEvent,
34    YogItemPickupFn, YogKeyPressEvent, YogKeyPressFn, YogOwnedStr, YogPacketFn, YogPlaceBlockEvent,
35    YogPlaceBlockFn, YogPlayerDeathEvent, YogPlayerDeathFn, YogPlayerFn, YogPlayerMoveEvent,
36    YogPlayerMoveFn, YogPlayerRespawnEvent, YogPlayerRespawnFn, YogProjectileHitEvent,
37    YogProjectileHitFn, YogScheduledFn, YogScreenFn, YogServer, YogServerFn, YogStartupGrantDef,
38    YogStr, YogUseBlockFn, YogUseItemFn, YogVec3, YogWorldRenderFn, ABI_VERSION,
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, keyed by mod id — owns the safe `dlopen`/`dlclose`
47/// swap lifecycle (see `yog-hot-reload`) instead of a flat keep-alive `Vec`,
48/// so a reload can find "the current generation of this mod" and safely
49/// retire the previous one.
50static HOT_RELOADER: OnceLock<HotReloader<RuntimeModuleRegistry>> = OnceLock::new();
51/// The mod currently inside its own `yog_mod_register` call. Every `api_*`
52/// registration function reads this to tag what it stores with a
53/// `LoadedModule` handle, instead of requiring mods to pass a mod id
54/// through the stable C ABI (an ABI break, and edits to every mod's
55/// source). Valid because a mod's entire registration always happens
56/// synchronously inside one `yog_mod_register` call — see `load_mod_lib`
57/// and `Java_dev_yog_NativeBridge_nativeHotReload`.
58static CURRENT_REGISTRATION: Mutex<Option<LoadedModule>> = Mutex::new(None);
59/// Metadata of loaded .yog mods: [id, name, version, authors, description,
60/// name_key, description_key] (the keys empty unless the mod's yog.toml
61/// gives its name/description as `.yres` texts).
62static MOD_INFOS: Mutex<Vec<[String; 7]>> = Mutex::new(Vec::new());
63/// Inter-mod symbol registry: mod_id → (symbol_name → function pointer).
64/// Filled during `yog_mod_register` (export calls), read during import calls.
65static INTEROP_SYMBOLS: OnceLock<Mutex<HashMap<String, HashMap<String, usize>>>> = OnceLock::new();
66/// Stable server table (populated once in nativeInit, then read-only).
67static SERVER: OnceLock<YogServer> = OnceLock::new();
68/// Stable api table. Mods capture this pointer at registration (yog-api's
69/// `installed_mods()` calls through it later, e.g. from UI render) — so it
70/// must outlive `nativeInit`, not live on its stack. `ctx` inside points at
71/// `HANDLERS`' own `RwLock`, published *before* any mod registers (unlike
72/// the old design, where it pointed at a temporary pre-move `Box` that
73/// went stale the instant `nativeInit` finished) — so it stays valid for a
74/// hot-reload's later re-registration too.
75static API_TABLE: OnceLock<YogApi> = OnceLock::new();
76/// All registered handlers + content. A `RwLock`, not a plain value: unlike
77/// the original one-shot-then-immutable design, a hot-reload needs to
78/// append fresh entries for a reloaded mod after this has long been
79/// published. Read sites (`handlers()`) take a read guard; registration
80/// (initial or reload) takes a write guard — both deref straight through to
81/// `RuntimeHandlers`, so existing `handlers().field` call sites are
82/// unaffected by this type change.
83static HANDLERS: OnceLock<RwLock<RuntimeHandlers>> = OnceLock::new();
84
85// ── OpenGL context (client-side, render thread only) ─────────────────────────
86
87struct GlCtx(glow::Context);
88unsafe impl Send for GlCtx {}
89unsafe impl Sync for GlCtx {}
90
91/// Initialized by `nativeGlInit` on the render thread.  `None` on dedicated server.
92static GL: OnceLock<GlCtx> = OnceLock::new();
93
94// Raw GL function pointers for GL_ARB_get_program_binary (not exposed by glow 0.13).
95// Captured during the glow loader callback in `nativeGlInit`.
96// `None` when the extension is unavailable (very old drivers).
97static GL_GET_PROGRAM_BINARY: OnceLock<Option<usize>> = OnceLock::new();
98static GL_PROGRAM_BINARY: OnceLock<Option<usize>> = OnceLock::new();
99static GL_GET_PROGRAM_IV: OnceLock<Option<usize>> = OnceLock::new();
100
101// ── Handler storage ───────────────────────────────────────────────────────────
102
103#[derive(Debug, Clone)]
104pub struct UiLayer {
105    pub id: String,
106    pub parent: Option<String>,
107    pub modal: bool,
108    pub pause_game: bool,
109    pub visible: bool,
110    pub enabled: bool,
111    pub z_index: i32,
112}
113
114/// One command registration: owning module, typed-args schema (if any),
115/// user data and callback.
116type CommandEntry = (LoadedModule, Option<String>, *mut c_void, YogCommandFn);
117
118// Every callback table below is tagged with the `LoadedModule` that
119// registered it (see `current_registration()`), so a hot-reload's dispatch
120// sites can skip a retiring module's stale entries (`LoadedModule::
121// is_retiring()`) before they're physically swept by `RuntimeModuleRegistry
122// ::purge`. Content registries — `items`/`blocks`/`inventories`/`books`/
123// `recipes`/`dimensions`/`startup_grants`/`menu_entries` — are deliberately
124// NOT tagged: they're one-time definitions copied into Minecraft's own
125// registries at startup, not callbacks invoked later, and Minecraft itself
126// has no live registry-unregister mechanism to hot-reload them against
127// regardless of what this crate does.
128struct RuntimeHandlers {
129    block_break: Vec<(LoadedModule, *mut c_void, YogBlockBreakFn)>,
130    chat: Vec<(LoadedModule, *mut c_void, YogChatFn)>,
131    player_join: Vec<(LoadedModule, *mut c_void, YogPlayerFn)>,
132    player_leave: Vec<(LoadedModule, *mut c_void, YogPlayerFn)>,
133    use_item: Vec<(LoadedModule, *mut c_void, YogUseItemFn)>,
134    use_block: Vec<(LoadedModule, *mut c_void, YogUseBlockFn)>,
135    attack_entity: Vec<(LoadedModule, *mut c_void, YogAttackEntityFn)>,
136    entity_damage: Vec<(LoadedModule, *mut c_void, YogEntityDamageFn)>,
137    entity_death: Vec<(LoadedModule, *mut c_void, YogEntityDeathFn)>,
138    entity_spawn: Vec<(LoadedModule, *mut c_void, YogEntitySpawnFn)>,
139    player_place_block: Vec<(LoadedModule, *mut c_void, YogPlaceBlockFn)>,
140    player_death: Vec<(LoadedModule, *mut c_void, YogPlayerDeathFn)>,
141    player_respawn: Vec<(LoadedModule, *mut c_void, YogPlayerRespawnFn)>,
142    advancement: Vec<(LoadedModule, *mut c_void, YogAdvancementFn)>,
143    entity_interact: Vec<(LoadedModule, *mut c_void, YogEntityInteractFn)>,
144    item_craft: Vec<(LoadedModule, *mut c_void, YogCraftFn)>,
145    explosion: Vec<(LoadedModule, *mut c_void, YogExplosionFn)>,
146    item_pickup: Vec<(LoadedModule, *mut c_void, YogItemPickupFn)>,
147    player_move: Vec<(LoadedModule, *mut c_void, YogPlayerMoveFn)>,
148    container_open: Vec<(LoadedModule, *mut c_void, YogContainerOpenFn)>,
149    container_close: Vec<(LoadedModule, *mut c_void, YogContainerCloseFn)>,
150    projectile_hit: Vec<(LoadedModule, *mut c_void, YogProjectileHitFn)>,
151    client_tick: Vec<(LoadedModule, *mut c_void, YogClientFn)>,
152    hud_render: Vec<(LoadedModule, *mut c_void, YogHudRenderFn)>,
153    world_render: Vec<(LoadedModule, *mut c_void, YogWorldRenderFn)>,
154    key_press: Vec<(LoadedModule, *mut c_void, YogKeyPressFn)>,
155    screen_open: Vec<(LoadedModule, *mut c_void, YogScreenFn)>,
156    screen_close: Vec<(LoadedModule, *mut c_void, YogScreenFn)>,
157    server_tick: Vec<(LoadedModule, *mut c_void, YogServerFn)>,
158    server_started: Vec<(LoadedModule, *mut c_void, YogServerFn)>,
159    server_stopping: Vec<(LoadedModule, *mut c_void, YogServerFn)>,
160    /// All handlers registered under one command name, in registration order.
161    /// `schema` is `None` for a plain `on_command` (bare, zero-argument)
162    /// registration and `Some(schema)` for `on_typed_command`. Kept as a
163    /// `Vec` (not a single slot) so a mod can register several subcommands —
164    /// e.g. differing arg counts, or several bare/typed registrations sharing
165    /// one top-level name — without later registrations silently clobbering
166    /// earlier ones (see `nativeOnCommand`, which tries each entry whose
167    /// schema's arg count matches the actual invocation, in order, until one
168    /// produces a reply).
169    commands: HashMap<String, Vec<CommandEntry>>,
170    recipes: Vec<(String, String, String)>,
171    packets: HashMap<String, (LoadedModule, *mut c_void, YogPacketFn)>,
172    client_packets: HashMap<String, (LoadedModule, *mut c_void, YogPacketFn)>,
173    items: Vec<ItemDef>,
174    blocks: Vec<BlockDef>,
175    inventories: Vec<yog_inventory::InventoryDef>,
176    books: HashMap<String, String>,
177    book_renderers: Mutex<HashMap<String, yog_book::BookRenderer>>,
178    /// Declared dimension-type defs: id -> `YogDimensionDef` JSON. Actual
179    /// `LevelStem`/`ServerLevel` creation is a host (Java) responsibility —
180    /// see `yog-dimensions` crate docs.
181    dimensions: HashMap<String, String>,
182    chunk_generators: HashMap<String, (LoadedModule, *mut c_void, yog_abi::YogChunkGeneratorFn)>,
183    ui_handlers: HashMap<String, (LoadedModule, *mut c_void, yog_abi::YogUIEventFn)>,
184    ui_render_handlers: HashMap<String, Vec<(LoadedModule, *mut c_void, YogHudRenderFn)>>,
185    menu_entries: Vec<(String, String)>, // (label, ui_id) for vanilla screen buttons
186    pub active_uis: Mutex<Vec<UiLayer>>,
187    startup_grants: Vec<yog_registry::StartupGrant>,
188    startup_granted: Mutex<HashMap<String, bool>>,
189    /// Players whose startup grants are pending: (name, uuid, ticks_waited).
190    /// Granting happens on a server tick after join — giving items directly in
191    /// the join callback fails for the host of a freshly created world.
192    pending_grants: Mutex<Vec<(String, String, u32)>>,
193    scheduler: Mutex<SchedulerState>,
194}
195
196// All fn ptrs are C-ABI; ud pointers are from Box::into_raw of Send+Sync closures.
197unsafe impl Send for RuntimeHandlers {}
198unsafe impl Sync for RuntimeHandlers {}
199
200impl RuntimeHandlers {
201    fn new() -> Self {
202        Self {
203            block_break: Vec::new(),
204            chat: Vec::new(),
205            player_join: Vec::new(),
206            player_leave: Vec::new(),
207            use_item: Vec::new(),
208            use_block: Vec::new(),
209            attack_entity: Vec::new(),
210            entity_damage: Vec::new(),
211            entity_death: Vec::new(),
212            entity_spawn: Vec::new(),
213            player_place_block: Vec::new(),
214            player_death: Vec::new(),
215            player_respawn: Vec::new(),
216            advancement: Vec::new(),
217            entity_interact: Vec::new(),
218            item_craft: Vec::new(),
219            explosion: Vec::new(),
220            item_pickup: Vec::new(),
221            player_move: Vec::new(),
222            container_open: Vec::new(),
223            container_close: Vec::new(),
224            projectile_hit: Vec::new(),
225            client_tick: Vec::new(),
226            hud_render: Vec::new(),
227            world_render: Vec::new(),
228            key_press: Vec::new(),
229            screen_open: Vec::new(),
230            screen_close: Vec::new(),
231            server_tick: Vec::new(),
232            server_started: Vec::new(),
233            server_stopping: Vec::new(),
234            commands: HashMap::new(),
235            recipes: Vec::new(),
236            packets: HashMap::new(),
237            client_packets: HashMap::new(),
238            items: Vec::new(),
239            ui_handlers: HashMap::new(),
240            ui_render_handlers: HashMap::new(),
241            menu_entries: Vec::new(),
242            active_uis: Mutex::new(Vec::new()),
243            startup_grants: Vec::new(),
244            blocks: Vec::new(),
245            inventories: Vec::new(),
246            books: HashMap::new(),
247            book_renderers: Mutex::new(HashMap::new()),
248            dimensions: HashMap::new(),
249            chunk_generators: HashMap::new(),
250            startup_granted: Mutex::new(HashMap::new()),
251            pending_grants: Mutex::new(Vec::new()),
252            scheduler: Mutex::new(SchedulerState::new()),
253        }
254    }
255}
256
257struct SchedulerState {
258    once_tasks: Vec<OnceTask>,
259    repeating_tasks: Vec<RepeatingTask>,
260}
261
262struct OnceTask {
263    module: LoadedModule,
264    delay_remaining: u64,
265    ud: *mut c_void,
266    f: YogScheduledFn,
267}
268struct RepeatingTask {
269    module: LoadedModule,
270    period: u64,
271    ticks_left: u64,
272    ud: *mut c_void,
273    f: YogScheduledFn,
274}
275
276unsafe impl Send for SchedulerState {}
277unsafe impl Sync for SchedulerState {}
278unsafe impl Send for OnceTask {}
279unsafe impl Send for RepeatingTask {}
280
281impl SchedulerState {
282    fn new() -> Self {
283        Self {
284            once_tasks: Vec::new(),
285            repeating_tasks: Vec::new(),
286        }
287    }
288}
289
290fn handlers() -> std::sync::RwLockReadGuard<'static, RuntimeHandlers> {
291    HANDLERS
292        .get()
293        .expect("yog: nativeInit not called yet")
294        .read()
295        .expect("handlers lock poisoned")
296}
297
298fn current_registration() -> LoadedModule {
299    CURRENT_REGISTRATION
300        .lock()
301        .unwrap()
302        .clone()
303        .expect("a yog-runtime api_* function was called outside of yog_mod_register")
304}
305
306fn hot_reloader() -> &'static HotReloader<RuntimeModuleRegistry> {
307    HOT_RELOADER.get().expect("yog: nativeInit not called yet")
308}
309
310/// The `yog-hot-reload` host contract: `retarget` needs no work here because
311/// `LoadedModule::is_retiring()` already makes a superseded generation's
312/// dispatch-table entries inert (every `handlers().<field>` loop checks it)
313/// the instant `HotReloader::reload` calls `retire` on the old module —
314/// well before this is even invoked. `purge` is the actual safety-net
315/// sweep, dropping every entry tagged with a retired generation right
316/// before its library is hard-unloaded.
317struct RuntimeModuleRegistry;
318
319impl ModuleRegistry for RuntimeModuleRegistry {
320    fn retarget(&self, _mod_id: &str, _from: ModuleGeneration, _to: ModuleGeneration) {}
321
322    fn purge(&self, generation: ModuleGeneration) {
323        let Some(lock) = HANDLERS.get() else { return };
324        let mut h = lock.write().expect("handlers lock poisoned");
325        h.block_break.retain(|(m, ..)| m.generation() != generation);
326        h.chat.retain(|(m, ..)| m.generation() != generation);
327        h.player_join.retain(|(m, ..)| m.generation() != generation);
328        h.player_leave
329            .retain(|(m, ..)| m.generation() != generation);
330        h.use_item.retain(|(m, ..)| m.generation() != generation);
331        h.use_block.retain(|(m, ..)| m.generation() != generation);
332        h.attack_entity
333            .retain(|(m, ..)| m.generation() != generation);
334        h.entity_damage
335            .retain(|(m, ..)| m.generation() != generation);
336        h.entity_death
337            .retain(|(m, ..)| m.generation() != generation);
338        h.entity_spawn
339            .retain(|(m, ..)| m.generation() != generation);
340        h.player_place_block
341            .retain(|(m, ..)| m.generation() != generation);
342        h.player_death
343            .retain(|(m, ..)| m.generation() != generation);
344        h.player_respawn
345            .retain(|(m, ..)| m.generation() != generation);
346        h.advancement.retain(|(m, ..)| m.generation() != generation);
347        h.entity_interact
348            .retain(|(m, ..)| m.generation() != generation);
349        h.item_craft.retain(|(m, ..)| m.generation() != generation);
350        h.explosion.retain(|(m, ..)| m.generation() != generation);
351        h.item_pickup.retain(|(m, ..)| m.generation() != generation);
352        h.player_move.retain(|(m, ..)| m.generation() != generation);
353        h.container_open
354            .retain(|(m, ..)| m.generation() != generation);
355        h.container_close
356            .retain(|(m, ..)| m.generation() != generation);
357        h.projectile_hit
358            .retain(|(m, ..)| m.generation() != generation);
359        h.client_tick.retain(|(m, ..)| m.generation() != generation);
360        h.hud_render.retain(|(m, ..)| m.generation() != generation);
361        h.world_render
362            .retain(|(m, ..)| m.generation() != generation);
363        h.key_press.retain(|(m, ..)| m.generation() != generation);
364        h.screen_open.retain(|(m, ..)| m.generation() != generation);
365        h.screen_close
366            .retain(|(m, ..)| m.generation() != generation);
367        h.server_tick.retain(|(m, ..)| m.generation() != generation);
368        h.server_started
369            .retain(|(m, ..)| m.generation() != generation);
370        h.server_stopping
371            .retain(|(m, ..)| m.generation() != generation);
372        for entries in h.commands.values_mut() {
373            entries.retain(|(m, ..)| m.generation() != generation);
374        }
375        h.packets.retain(|_, (m, ..)| m.generation() != generation);
376        h.client_packets
377            .retain(|_, (m, ..)| m.generation() != generation);
378        h.chunk_generators
379            .retain(|_, (m, ..)| m.generation() != generation);
380        h.ui_handlers
381            .retain(|_, (m, ..)| m.generation() != generation);
382        for entries in h.ui_render_handlers.values_mut() {
383            entries.retain(|(m, ..)| m.generation() != generation);
384        }
385        h.scheduler
386            .lock()
387            .expect("scheduler poisoned")
388            .once_tasks
389            .retain(|t| t.module.generation() != generation);
390        h.scheduler
391            .lock()
392            .expect("scheduler poisoned")
393            .repeating_tasks
394            .retain(|t| t.module.generation() != generation);
395    }
396}
397
398// ── JNI helpers ──────────────────────────────────────────────────────────────
399
400fn guard(label: &str, f: impl FnOnce()) {
401    if std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).is_err() {
402        yog_logging::error!("a mod panicked handling `{}` (ignored)", label);
403    }
404}
405
406macro_rules! jstr {
407    ($env:expr, $s:expr) => {
408        match $env.get_string(&$s) {
409            Ok(s) => String::from(s),
410            Err(_) => return,
411        }
412    };
413}
414
415/// Convert a `YogStr` into a Java String. Caller must ensure `s` is valid UTF-8.
416unsafe fn ys_to_java<'l>(env: &mut JNIEnv<'l>, s: YogStr) -> Option<jni::objects::JString<'l>> {
417    env.new_string(s.as_str()).ok()
418}
419
420fn get_env() -> Option<jni::AttachGuard<'static>> {
421    JAVA_VM.get()?.attach_current_thread().ok()
422}
423
424// ── Free-str allocator used by YogOwnedStr ────────────────────────────────────
425
426unsafe extern "C" fn yog_free_str(ptr: *mut u8, len: u32) {
427    if !ptr.is_null() {
428        drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut(
429            ptr,
430            len as usize,
431        )));
432    }
433}
434
435fn jstring_to_owned(env: &mut JNIEnv, obj: jni::objects::JObject) -> YogOwnedStr {
436    if obj.as_raw().is_null() {
437        return YogOwnedStr::NONE;
438    }
439    match env.get_string(&JString::from(obj)) {
440        Ok(s) => YogOwnedStr::from_string(String::from(s)),
441        Err(_) => YogOwnedStr::NONE,
442    }
443}
444
445// ── YogServer standalone functions (one per action) ───────────────────────────
446//
447// ctx is unused here — all state is in the JAVA_VM static.
448
449unsafe extern "C" fn srv_broadcast(_ctx: *mut c_void, msg: YogStr) {
450    let Some(mut env) = get_env() else { return };
451    if let Some(jmsg) = ys_to_java(&mut env, msg) {
452        let _ = env.call_static_method(
453            "dev/yog/NativeBridge",
454            "broadcast",
455            "(Ljava/lang/String;)V",
456            &[JValue::Object(&jmsg)],
457        );
458    }
459}
460
461unsafe extern "C" fn srv_get_block(
462    _ctx: *mut c_void,
463    dim: YogStr,
464    pos: YogBlockPos,
465) -> YogOwnedStr {
466    let Some(mut env) = get_env() else {
467        return YogOwnedStr::NONE;
468    };
469    let (Some(jd),) = (ys_to_java(&mut env, dim),) else {
470        return YogOwnedStr::NONE;
471    };
472    let ret = env.call_static_method(
473        "dev/yog/NativeBridge",
474        "getBlock",
475        "(Ljava/lang/String;III)Ljava/lang/String;",
476        &[
477            JValue::Object(&jd),
478            JValue::Int(pos.x),
479            JValue::Int(pos.y),
480            JValue::Int(pos.z),
481        ],
482    );
483    match ret.and_then(|v| v.l()) {
484        Ok(obj) => jstring_to_owned(&mut env, obj),
485        _ => YogOwnedStr::NONE,
486    }
487}
488
489unsafe extern "C" fn srv_set_block(
490    _ctx: *mut c_void,
491    dim: YogStr,
492    pos: YogBlockPos,
493    block: YogStr,
494) -> bool {
495    let Some(mut env) = get_env() else {
496        return false;
497    };
498    let (Some(jd), Some(jb)) = (ys_to_java(&mut env, dim), ys_to_java(&mut env, block)) else {
499        return false;
500    };
501    env.call_static_method(
502        "dev/yog/NativeBridge",
503        "setBlock",
504        "(Ljava/lang/String;IIILjava/lang/String;)Z",
505        &[
506            JValue::Object(&jd),
507            JValue::Int(pos.x),
508            JValue::Int(pos.y),
509            JValue::Int(pos.z),
510            JValue::Object(&jb),
511        ],
512    )
513    .and_then(|v| v.z())
514    .unwrap_or(false)
515}
516
517unsafe extern "C" fn srv_world_time(_ctx: *mut c_void, dim: YogStr, out: *mut i64) -> bool {
518    let Some(mut env) = get_env() else {
519        return false;
520    };
521    let Some(jd) = ys_to_java(&mut env, dim) else {
522        return false;
523    };
524    match env
525        .call_static_method(
526            "dev/yog/NativeBridge",
527            "worldTime",
528            "(Ljava/lang/String;)J",
529            &[JValue::Object(&jd)],
530        )
531        .and_then(|v| v.j())
532    {
533        Ok(v) if v != i64::MIN => {
534            *out = v;
535            true
536        }
537        _ => false,
538    }
539}
540
541unsafe extern "C" fn srv_set_time(_ctx: *mut c_void, dim: YogStr, time: i64) -> bool {
542    let Some(mut env) = get_env() else {
543        return false;
544    };
545    let Some(jd) = ys_to_java(&mut env, dim) else {
546        return false;
547    };
548    env.call_static_method(
549        "dev/yog/NativeBridge",
550        "worldSetTime",
551        "(Ljava/lang/String;J)Z",
552        &[JValue::Object(&jd), JValue::Long(time)],
553    )
554    .and_then(|v| v.z())
555    .unwrap_or(false)
556}
557
558unsafe extern "C" fn srv_is_raining(_ctx: *mut c_void, dim: YogStr) -> bool {
559    let Some(mut env) = get_env() else {
560        return false;
561    };
562    let Some(jd) = ys_to_java(&mut env, dim) else {
563        return false;
564    };
565    env.call_static_method(
566        "dev/yog/NativeBridge",
567        "worldIsRaining",
568        "(Ljava/lang/String;)Z",
569        &[JValue::Object(&jd)],
570    )
571    .and_then(|v| v.z())
572    .unwrap_or(false)
573}
574
575unsafe extern "C" fn srv_set_weather(
576    _ctx: *mut c_void,
577    dim: YogStr,
578    raining: bool,
579    dur: i32,
580) -> bool {
581    let Some(mut env) = get_env() else {
582        return false;
583    };
584    let Some(jd) = ys_to_java(&mut env, dim) else {
585        return false;
586    };
587    env.call_static_method(
588        "dev/yog/NativeBridge",
589        "worldSetWeather",
590        "(Ljava/lang/String;ZI)Z",
591        &[
592            JValue::Object(&jd),
593            JValue::Bool(raining as u8),
594            JValue::Int(dur),
595        ],
596    )
597    .and_then(|v| v.z())
598    .unwrap_or(false)
599}
600
601unsafe extern "C" fn srv_give_item(
602    _ctx: *mut c_void,
603    player: YogStr,
604    item: YogStr,
605    count: u32,
606) -> bool {
607    let Some(mut env) = get_env() else {
608        return false;
609    };
610    let (Some(jp), Some(ji)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, item)) else {
611        return false;
612    };
613    env.call_static_method(
614        "dev/yog/NativeBridge",
615        "giveItem",
616        "(Ljava/lang/String;Ljava/lang/String;I)Z",
617        &[
618            JValue::Object(&jp),
619            JValue::Object(&ji),
620            JValue::Int(count as i32),
621        ],
622    )
623    .and_then(|v| v.z())
624    .unwrap_or(false)
625}
626
627unsafe extern "C" fn srv_player_teleport(_ctx: *mut c_void, player: YogStr, pos: YogVec3) -> bool {
628    let Some(mut env) = get_env() else {
629        return false;
630    };
631    let Some(jp) = ys_to_java(&mut env, player) else {
632        return false;
633    };
634    env.call_static_method(
635        "dev/yog/NativeBridge",
636        "teleport",
637        "(Ljava/lang/String;DDD)Z",
638        &[
639            JValue::Object(&jp),
640            JValue::Double(pos.x),
641            JValue::Double(pos.y),
642            JValue::Double(pos.z),
643        ],
644    )
645    .and_then(|v| v.z())
646    .unwrap_or(false)
647}
648
649unsafe extern "C" fn srv_send_to_player(
650    _ctx: *mut c_void,
651    player: YogStr,
652    channel: YogStr,
653    data: *const u8,
654    len: u32,
655) -> bool {
656    let Some(mut env) = get_env() else {
657        return false;
658    };
659    let (Some(jp), Some(jc)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, channel)) else {
660        return false;
661    };
662    let payload = std::slice::from_raw_parts(data, len as usize);
663    let Ok(jdata) = env.byte_array_from_slice(payload) else {
664        return false;
665    };
666    env.call_static_method(
667        "dev/yog/NativeBridge",
668        "sendToPlayer",
669        "(Ljava/lang/String;Ljava/lang/String;[B)Z",
670        &[
671            JValue::Object(&jp),
672            JValue::Object(&jc),
673            JValue::Object(&jdata),
674        ],
675    )
676    .and_then(|v| v.z())
677    .unwrap_or(false)
678}
679
680unsafe extern "C" fn srv_send_to_server(
681    _ctx: *mut c_void,
682    channel: YogStr,
683    data: *const u8,
684    len: u32,
685) -> bool {
686    let Some(mut env) = get_env() else {
687        return false;
688    };
689    let Some(jc) = ys_to_java(&mut env, channel) else {
690        return false;
691    };
692    let payload = std::slice::from_raw_parts(data, len as usize);
693    let Ok(jdata) = env.byte_array_from_slice(payload) else {
694        return false;
695    };
696    let result = env.call_static_method(
697        "dev/yog/YogClient",
698        "sendToServer",
699        "(Ljava/lang/String;[B)Z",
700        &[JValue::Object(&jc), JValue::Object(&jdata)],
701    );
702    let _ = env.exception_clear();
703    result.and_then(|v| v.z()).unwrap_or(false)
704}
705
706unsafe extern "C" fn srv_kick_player(_ctx: *mut c_void, player: YogStr, reason: YogStr) -> bool {
707    let Some(mut env) = get_env() else {
708        return false;
709    };
710    let (Some(jp), Some(jr)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, reason)) else {
711        return false;
712    };
713    env.call_static_method(
714        "dev/yog/NativeBridge",
715        "kickPlayer",
716        "(Ljava/lang/String;Ljava/lang/String;)Z",
717        &[JValue::Object(&jp), JValue::Object(&jr)],
718    )
719    .and_then(|v| v.z())
720    .unwrap_or(false)
721}
722
723unsafe extern "C" fn srv_set_gamemode(_ctx: *mut c_void, player: YogStr, mode: YogStr) -> bool {
724    let Some(mut env) = get_env() else {
725        return false;
726    };
727    let (Some(jp), Some(jg)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, mode)) else {
728        return false;
729    };
730    env.call_static_method(
731        "dev/yog/NativeBridge",
732        "setGamemode",
733        "(Ljava/lang/String;Ljava/lang/String;)Z",
734        &[JValue::Object(&jp), JValue::Object(&jg)],
735    )
736    .and_then(|v| v.z())
737    .unwrap_or(false)
738}
739
740unsafe extern "C" fn srv_send_title(
741    _ctx: *mut c_void,
742    player: YogStr,
743    title: YogStr,
744    sub: YogStr,
745    fi: i32,
746    stay: i32,
747    fo: i32,
748) -> bool {
749    let Some(mut env) = get_env() else {
750        return false;
751    };
752    let (Some(jp), Some(jt), Some(js)) = (
753        ys_to_java(&mut env, player),
754        ys_to_java(&mut env, title),
755        ys_to_java(&mut env, sub),
756    ) else {
757        return false;
758    };
759    env.call_static_method(
760        "dev/yog/NativeBridge",
761        "sendTitle",
762        "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;III)Z",
763        &[
764            JValue::Object(&jp),
765            JValue::Object(&jt),
766            JValue::Object(&js),
767            JValue::Int(fi),
768            JValue::Int(stay),
769            JValue::Int(fo),
770        ],
771    )
772    .and_then(|v| v.z())
773    .unwrap_or(false)
774}
775
776unsafe extern "C" fn srv_send_actionbar(_ctx: *mut c_void, player: YogStr, msg: YogStr) -> bool {
777    let Some(mut env) = get_env() else {
778        return false;
779    };
780    let (Some(jp), Some(jm)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, msg)) else {
781        return false;
782    };
783    env.call_static_method(
784        "dev/yog/NativeBridge",
785        "sendActionbar",
786        "(Ljava/lang/String;Ljava/lang/String;)Z",
787        &[JValue::Object(&jp), JValue::Object(&jm)],
788    )
789    .and_then(|v| v.z())
790    .unwrap_or(false)
791}
792
793unsafe extern "C" fn srv_play_sound(
794    _ctx: *mut c_void,
795    dim: YogStr,
796    pos: YogVec3,
797    sound: YogStr,
798    vol: f32,
799    pitch: f32,
800) -> bool {
801    let Some(mut env) = get_env() else {
802        return false;
803    };
804    let (Some(jd), Some(js)) = (ys_to_java(&mut env, dim), ys_to_java(&mut env, sound)) else {
805        return false;
806    };
807    env.call_static_method(
808        "dev/yog/NativeBridge",
809        "playSound",
810        "(Ljava/lang/String;DDDLjava/lang/String;FF)Z",
811        &[
812            JValue::Object(&jd),
813            JValue::Double(pos.x),
814            JValue::Double(pos.y),
815            JValue::Double(pos.z),
816            JValue::Object(&js),
817            JValue::Float(vol),
818            JValue::Float(pitch),
819        ],
820    )
821    .and_then(|v| v.z())
822    .unwrap_or(false)
823}
824
825unsafe extern "C" fn srv_play_sound_player(
826    _ctx: *mut c_void,
827    player: YogStr,
828    sound: YogStr,
829    vol: f32,
830    pitch: f32,
831) -> bool {
832    let Some(mut env) = get_env() else {
833        return false;
834    };
835    let (Some(jp), Some(js)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, sound)) else {
836        return false;
837    };
838    env.call_static_method(
839        "dev/yog/NativeBridge",
840        "playSoundToPlayer",
841        "(Ljava/lang/String;Ljava/lang/String;FF)Z",
842        &[
843            JValue::Object(&jp),
844            JValue::Object(&js),
845            JValue::Float(vol),
846            JValue::Float(pitch),
847        ],
848    )
849    .and_then(|v| v.z())
850    .unwrap_or(false)
851}
852
853unsafe extern "C" fn srv_entity_teleport(_ctx: *mut c_void, uuid: YogStr, pos: YogVec3) -> bool {
854    let Some(mut env) = get_env() else {
855        return false;
856    };
857    let Some(ju) = ys_to_java(&mut env, uuid) else {
858        return false;
859    };
860    env.call_static_method(
861        "dev/yog/NativeBridge",
862        "entityTeleport",
863        "(Ljava/lang/String;DDD)Z",
864        &[
865            JValue::Object(&ju),
866            JValue::Double(pos.x),
867            JValue::Double(pos.y),
868            JValue::Double(pos.z),
869        ],
870    )
871    .and_then(|v| v.z())
872    .unwrap_or(false)
873}
874
875unsafe extern "C" fn srv_entity_rotation(
876    _ctx: *mut c_void,
877    uuid: YogStr,
878    out: *mut YogVec3,
879) -> bool {
880    let Some(mut env) = get_env() else {
881        return false;
882    };
883    let Some(ju) = ys_to_java(&mut env, uuid) else {
884        return false;
885    };
886    let ret = env.call_static_method(
887        "dev/yog/NativeBridge",
888        "entityRotation",
889        "(Ljava/lang/String;)Ljava/lang/String;",
890        &[JValue::Object(&ju)],
891    );
892    let obj = match ret.and_then(|v| v.l()) {
893        Ok(o) => o,
894        Err(_) => {
895            env.exception_clear().ok();
896            return false;
897        }
898    };
899    if obj.as_raw().is_null() {
900        return false;
901    }
902    let s: String = match env.get_string(&JString::from(obj)) {
903        Ok(s) => String::from(s),
904        Err(_) => return false,
905    };
906    let mut it = s.split('\t');
907    let (yaw, pitch) = (it.next(), it.next());
908    if let (Some(yaw), Some(pitch)) = (
909        yaw.and_then(|v| v.parse().ok()),
910        pitch.and_then(|v| v.parse().ok()),
911    ) {
912        *out = YogVec3 {
913            x: yaw,
914            y: pitch,
915            z: 0.0,
916        };
917        true
918    } else {
919        false
920    }
921}
922
923unsafe extern "C" fn srv_entity_position(
924    _ctx: *mut c_void,
925    uuid: YogStr,
926    out: *mut YogVec3,
927) -> bool {
928    let Some(mut env) = get_env() else {
929        return false;
930    };
931    let Some(ju) = ys_to_java(&mut env, uuid) else {
932        return false;
933    };
934    let ret = env.call_static_method(
935        "dev/yog/NativeBridge",
936        "entityPosition",
937        "(Ljava/lang/String;)Ljava/lang/String;",
938        &[JValue::Object(&ju)],
939    );
940    let obj = match ret.and_then(|v| v.l()) {
941        Ok(o) => o,
942        Err(_) => return false,
943    };
944    if obj.as_raw().is_null() {
945        return false;
946    }
947    let s: String = match env.get_string(&JString::from(obj)) {
948        Ok(s) => String::from(s),
949        Err(_) => return false,
950    };
951    let mut it = s.split('\t');
952    let (x, y, z) = (it.next(), it.next(), it.next());
953    if let (Some(x), Some(y), Some(z)) = (
954        x.and_then(|v| v.parse().ok()),
955        y.and_then(|v| v.parse().ok()),
956        z.and_then(|v| v.parse().ok()),
957    ) {
958        *out = YogVec3 { x, y, z };
959        true
960    } else {
961        false
962    }
963}
964
965unsafe extern "C" fn srv_entity_health(_ctx: *mut c_void, uuid: YogStr, out: *mut f32) -> bool {
966    let Some(mut env) = get_env() else {
967        return false;
968    };
969    let Some(ju) = ys_to_java(&mut env, uuid) else {
970        return false;
971    };
972    match env
973        .call_static_method(
974            "dev/yog/NativeBridge",
975            "entityHealth",
976            "(Ljava/lang/String;)D",
977            &[JValue::Object(&ju)],
978        )
979        .and_then(|v| v.d())
980    {
981        Ok(v) if !v.is_nan() => {
982            *out = v as f32;
983            true
984        }
985        _ => false,
986    }
987}
988
989unsafe extern "C" fn srv_entity_set_health(_ctx: *mut c_void, uuid: YogStr, hp: f32) -> bool {
990    let Some(mut env) = get_env() else {
991        return false;
992    };
993    let Some(ju) = ys_to_java(&mut env, uuid) else {
994        return false;
995    };
996    env.call_static_method(
997        "dev/yog/NativeBridge",
998        "entitySetHealth",
999        "(Ljava/lang/String;D)Z",
1000        &[JValue::Object(&ju), JValue::Double(hp as f64)],
1001    )
1002    .and_then(|v| v.z())
1003    .unwrap_or(false)
1004}
1005
1006unsafe extern "C" fn srv_entity_kill(_ctx: *mut c_void, uuid: YogStr) -> bool {
1007    let Some(mut env) = get_env() else {
1008        return false;
1009    };
1010    let Some(ju) = ys_to_java(&mut env, uuid) else {
1011        return false;
1012    };
1013    env.call_static_method(
1014        "dev/yog/NativeBridge",
1015        "entityKill",
1016        "(Ljava/lang/String;)Z",
1017        &[JValue::Object(&ju)],
1018    )
1019    .and_then(|v| v.z())
1020    .unwrap_or(false)
1021}
1022
1023unsafe extern "C" fn srv_spawn_entity(
1024    _ctx: *mut c_void,
1025    type_id: YogStr,
1026    dim: YogStr,
1027    pos: YogVec3,
1028) -> YogOwnedStr {
1029    let Some(mut env) = get_env() else {
1030        return YogOwnedStr::NONE;
1031    };
1032    let (Some(jt), Some(jd)) = (ys_to_java(&mut env, type_id), ys_to_java(&mut env, dim)) else {
1033        return YogOwnedStr::NONE;
1034    };
1035    let ret = env.call_static_method(
1036        "dev/yog/NativeBridge",
1037        "spawnEntity",
1038        "(Ljava/lang/String;Ljava/lang/String;DDD)Ljava/lang/String;",
1039        &[
1040            JValue::Object(&jt),
1041            JValue::Object(&jd),
1042            JValue::Double(pos.x),
1043            JValue::Double(pos.y),
1044            JValue::Double(pos.z),
1045        ],
1046    );
1047    match ret.and_then(|v| v.l()) {
1048        Ok(obj) => jstring_to_owned(&mut env, obj),
1049        _ => YogOwnedStr::NONE,
1050    }
1051}
1052
1053unsafe extern "C" fn srv_entity_add_effect(
1054    _ctx: *mut c_void,
1055    uuid: YogStr,
1056    fx: YogStr,
1057    dur: i32,
1058    amp: u8,
1059    particles: bool,
1060) -> bool {
1061    let Some(mut env) = get_env() else {
1062        return false;
1063    };
1064    let (Some(ju), Some(je)) = (ys_to_java(&mut env, uuid), ys_to_java(&mut env, fx)) else {
1065        return false;
1066    };
1067    env.call_static_method(
1068        "dev/yog/NativeBridge",
1069        "entityAddEffect",
1070        "(Ljava/lang/String;Ljava/lang/String;IIZ)Z",
1071        &[
1072            JValue::Object(&ju),
1073            JValue::Object(&je),
1074            JValue::Int(dur),
1075            JValue::Int(amp as i32),
1076            JValue::Bool(particles as u8),
1077        ],
1078    )
1079    .and_then(|v| v.z())
1080    .unwrap_or(false)
1081}
1082
1083unsafe extern "C" fn srv_entity_remove_effect(_ctx: *mut c_void, uuid: YogStr, fx: YogStr) -> bool {
1084    let Some(mut env) = get_env() else {
1085        return false;
1086    };
1087    let (Some(ju), Some(je)) = (ys_to_java(&mut env, uuid), ys_to_java(&mut env, fx)) else {
1088        return false;
1089    };
1090    env.call_static_method(
1091        "dev/yog/NativeBridge",
1092        "entityRemoveEffect",
1093        "(Ljava/lang/String;Ljava/lang/String;)Z",
1094        &[JValue::Object(&ju), JValue::Object(&je)],
1095    )
1096    .and_then(|v| v.z())
1097    .unwrap_or(false)
1098}
1099
1100unsafe extern "C" fn srv_entity_clear_effects(_ctx: *mut c_void, uuid: YogStr) -> bool {
1101    let Some(mut env) = get_env() else {
1102        return false;
1103    };
1104    let Some(ju) = ys_to_java(&mut env, uuid) else {
1105        return false;
1106    };
1107    env.call_static_method(
1108        "dev/yog/NativeBridge",
1109        "entityClearEffects",
1110        "(Ljava/lang/String;)Z",
1111        &[JValue::Object(&ju)],
1112    )
1113    .and_then(|v| v.z())
1114    .unwrap_or(false)
1115}
1116
1117unsafe extern "C" fn srv_entity_velocity(
1118    _ctx: *mut c_void,
1119    uuid: YogStr,
1120    out: *mut YogVec3,
1121) -> bool {
1122    let Some(mut env) = get_env() else {
1123        return false;
1124    };
1125    let Some(ju) = ys_to_java(&mut env, uuid) else {
1126        return false;
1127    };
1128    let ret = env.call_static_method(
1129        "dev/yog/NativeBridge",
1130        "entityVelocity",
1131        "(Ljava/lang/String;)Ljava/lang/String;",
1132        &[JValue::Object(&ju)],
1133    );
1134    let obj = match ret.and_then(|v| v.l()) {
1135        Ok(o) => o,
1136        Err(_) => return false,
1137    };
1138    if obj.as_raw().is_null() {
1139        return false;
1140    }
1141    let s: String = match env.get_string(&JString::from(obj)) {
1142        Ok(s) => String::from(s),
1143        Err(_) => return false,
1144    };
1145    let mut it = s.split('\t');
1146    let (x, y, z) = (it.next(), it.next(), it.next());
1147    if let (Some(x), Some(y), Some(z)) = (
1148        x.and_then(|v| v.parse().ok()),
1149        y.and_then(|v| v.parse().ok()),
1150        z.and_then(|v| v.parse().ok()),
1151    ) {
1152        *out = YogVec3 { x, y, z };
1153        true
1154    } else {
1155        false
1156    }
1157}
1158
1159unsafe extern "C" fn srv_entity_set_velocity(
1160    _ctx: *mut c_void,
1161    uuid: YogStr,
1162    vel: YogVec3,
1163) -> bool {
1164    let Some(mut env) = get_env() else {
1165        return false;
1166    };
1167    let Some(ju) = ys_to_java(&mut env, uuid) else {
1168        return false;
1169    };
1170    env.call_static_method(
1171        "dev/yog/NativeBridge",
1172        "entitySetVelocity",
1173        "(Ljava/lang/String;DDD)Z",
1174        &[
1175            JValue::Object(&ju),
1176            JValue::Double(vel.x),
1177            JValue::Double(vel.y),
1178            JValue::Double(vel.z),
1179        ],
1180    )
1181    .and_then(|v| v.z())
1182    .unwrap_or(false)
1183}
1184
1185unsafe extern "C" fn srv_entity_add_velocity(
1186    _ctx: *mut c_void,
1187    uuid: YogStr,
1188    vel: YogVec3,
1189) -> bool {
1190    let Some(mut env) = get_env() else {
1191        return false;
1192    };
1193    let Some(ju) = ys_to_java(&mut env, uuid) else {
1194        return false;
1195    };
1196    env.call_static_method(
1197        "dev/yog/NativeBridge",
1198        "entityAddVelocity",
1199        "(Ljava/lang/String;DDD)Z",
1200        &[
1201            JValue::Object(&ju),
1202            JValue::Double(vel.x),
1203            JValue::Double(vel.y),
1204            JValue::Double(vel.z),
1205        ],
1206    )
1207    .and_then(|v| v.z())
1208    .unwrap_or(false)
1209}
1210
1211unsafe extern "C" fn srv_has_item_tag(_ctx: *mut c_void, item: YogStr, tag: YogStr) -> bool {
1212    let Some(mut env) = get_env() else {
1213        return false;
1214    };
1215    let (Some(ji), Some(jt)) = (ys_to_java(&mut env, item), ys_to_java(&mut env, tag)) else {
1216        return false;
1217    };
1218    env.call_static_method(
1219        "dev/yog/NativeBridge",
1220        "hasItemTag",
1221        "(Ljava/lang/String;Ljava/lang/String;)Z",
1222        &[JValue::Object(&ji), JValue::Object(&jt)],
1223    )
1224    .and_then(|v| v.z())
1225    .unwrap_or(false)
1226}
1227
1228unsafe extern "C" fn srv_has_block_tag(_ctx: *mut c_void, block: YogStr, tag: YogStr) -> bool {
1229    let Some(mut env) = get_env() else {
1230        return false;
1231    };
1232    let (Some(jb), Some(jt)) = (ys_to_java(&mut env, block), ys_to_java(&mut env, tag)) else {
1233        return false;
1234    };
1235    env.call_static_method(
1236        "dev/yog/NativeBridge",
1237        "hasBlockTag",
1238        "(Ljava/lang/String;Ljava/lang/String;)Z",
1239        &[JValue::Object(&jb), JValue::Object(&jt)],
1240    )
1241    .and_then(|v| v.z())
1242    .unwrap_or(false)
1243}
1244
1245unsafe extern "C" fn srv_drop_loot(
1246    _ctx: *mut c_void,
1247    table: YogStr,
1248    dim: YogStr,
1249    pos: YogVec3,
1250) -> bool {
1251    let Some(mut env) = get_env() else {
1252        return false;
1253    };
1254    let (Some(jt), Some(jd)) = (ys_to_java(&mut env, table), ys_to_java(&mut env, dim)) else {
1255        return false;
1256    };
1257    env.call_static_method(
1258        "dev/yog/NativeBridge",
1259        "dropLoot",
1260        "(Ljava/lang/String;Ljava/lang/String;DDD)Z",
1261        &[
1262            JValue::Object(&jt),
1263            JValue::Object(&jd),
1264            JValue::Double(pos.x),
1265            JValue::Double(pos.y),
1266            JValue::Double(pos.z),
1267        ],
1268    )
1269    .and_then(|v| v.z())
1270    .unwrap_or(false)
1271}
1272
1273unsafe extern "C" fn srv_scoreboard_get(
1274    _ctx: *mut c_void,
1275    obj: YogStr,
1276    player: YogStr,
1277    out: *mut i32,
1278) -> bool {
1279    let Some(mut env) = get_env() else {
1280        return false;
1281    };
1282    let (Some(jo), Some(jp)) = (ys_to_java(&mut env, obj), ys_to_java(&mut env, player)) else {
1283        return false;
1284    };
1285    match env
1286        .call_static_method(
1287            "dev/yog/NativeBridge",
1288            "scoreboardGet",
1289            "(Ljava/lang/String;Ljava/lang/String;)I",
1290            &[JValue::Object(&jo), JValue::Object(&jp)],
1291        )
1292        .and_then(|v| v.i())
1293    {
1294        Ok(v) if v != i32::MIN => {
1295            *out = v;
1296            true
1297        }
1298        _ => false,
1299    }
1300}
1301
1302unsafe extern "C" fn srv_scoreboard_set(
1303    _ctx: *mut c_void,
1304    obj: YogStr,
1305    player: YogStr,
1306    score: i32,
1307) -> bool {
1308    let Some(mut env) = get_env() else {
1309        return false;
1310    };
1311    let (Some(jo), Some(jp)) = (ys_to_java(&mut env, obj), ys_to_java(&mut env, player)) else {
1312        return false;
1313    };
1314    env.call_static_method(
1315        "dev/yog/NativeBridge",
1316        "scoreboardSet",
1317        "(Ljava/lang/String;Ljava/lang/String;I)Z",
1318        &[JValue::Object(&jo), JValue::Object(&jp), JValue::Int(score)],
1319    )
1320    .and_then(|v| v.z())
1321    .unwrap_or(false)
1322}
1323
1324unsafe extern "C" fn srv_scoreboard_add(
1325    _ctx: *mut c_void,
1326    obj: YogStr,
1327    player: YogStr,
1328    delta: i32,
1329    out: *mut i32,
1330) -> bool {
1331    let Some(mut env) = get_env() else {
1332        return false;
1333    };
1334    let (Some(jo), Some(jp)) = (ys_to_java(&mut env, obj), ys_to_java(&mut env, player)) else {
1335        return false;
1336    };
1337    match env
1338        .call_static_method(
1339            "dev/yog/NativeBridge",
1340            "scoreboardAdd",
1341            "(Ljava/lang/String;Ljava/lang/String;I)I",
1342            &[JValue::Object(&jo), JValue::Object(&jp), JValue::Int(delta)],
1343        )
1344        .and_then(|v| v.i())
1345    {
1346        Ok(v) if v != i32::MIN => {
1347            *out = v;
1348            true
1349        }
1350        _ => false,
1351    }
1352}
1353
1354unsafe extern "C" fn srv_bossbar_create(
1355    _ctx: *mut c_void,
1356    id: YogStr,
1357    title: YogStr,
1358    color: YogStr,
1359    style: YogStr,
1360) -> bool {
1361    let Some(mut env) = get_env() else {
1362        return false;
1363    };
1364    let (Some(ji), Some(jt), Some(jc), Some(js)) = (
1365        ys_to_java(&mut env, id),
1366        ys_to_java(&mut env, title),
1367        ys_to_java(&mut env, color),
1368        ys_to_java(&mut env, style),
1369    ) else {
1370        return false;
1371    };
1372    env.call_static_method(
1373        "dev/yog/NativeBridge",
1374        "bossbarCreate",
1375        "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Z",
1376        &[
1377            JValue::Object(&ji),
1378            JValue::Object(&jt),
1379            JValue::Object(&jc),
1380            JValue::Object(&js),
1381        ],
1382    )
1383    .and_then(|v| v.z())
1384    .unwrap_or(false)
1385}
1386
1387unsafe extern "C" fn srv_bossbar_remove(_ctx: *mut c_void, id: YogStr) -> bool {
1388    let Some(mut env) = get_env() else {
1389        return false;
1390    };
1391    let Some(ji) = ys_to_java(&mut env, id) else {
1392        return false;
1393    };
1394    env.call_static_method(
1395        "dev/yog/NativeBridge",
1396        "bossbarRemove",
1397        "(Ljava/lang/String;)Z",
1398        &[JValue::Object(&ji)],
1399    )
1400    .and_then(|v| v.z())
1401    .unwrap_or(false)
1402}
1403
1404unsafe extern "C" fn srv_bossbar_set_title(_ctx: *mut c_void, id: YogStr, title: YogStr) -> bool {
1405    let Some(mut env) = get_env() else {
1406        return false;
1407    };
1408    let (Some(ji), Some(jt)) = (ys_to_java(&mut env, id), ys_to_java(&mut env, title)) else {
1409        return false;
1410    };
1411    env.call_static_method(
1412        "dev/yog/NativeBridge",
1413        "bossbarSetTitle",
1414        "(Ljava/lang/String;Ljava/lang/String;)Z",
1415        &[JValue::Object(&ji), JValue::Object(&jt)],
1416    )
1417    .and_then(|v| v.z())
1418    .unwrap_or(false)
1419}
1420
1421unsafe extern "C" fn srv_bossbar_set_progress(
1422    _ctx: *mut c_void,
1423    id: YogStr,
1424    progress: f32,
1425) -> bool {
1426    let Some(mut env) = get_env() else {
1427        return false;
1428    };
1429    let Some(ji) = ys_to_java(&mut env, id) else {
1430        return false;
1431    };
1432    env.call_static_method(
1433        "dev/yog/NativeBridge",
1434        "bossbarSetProgress",
1435        "(Ljava/lang/String;F)Z",
1436        &[JValue::Object(&ji), JValue::Float(progress)],
1437    )
1438    .and_then(|v| v.z())
1439    .unwrap_or(false)
1440}
1441
1442unsafe extern "C" fn srv_bossbar_set_color(_ctx: *mut c_void, id: YogStr, color: YogStr) -> bool {
1443    let Some(mut env) = get_env() else {
1444        return false;
1445    };
1446    let (Some(ji), Some(jc)) = (ys_to_java(&mut env, id), ys_to_java(&mut env, color)) else {
1447        return false;
1448    };
1449    env.call_static_method(
1450        "dev/yog/NativeBridge",
1451        "bossbarSetColor",
1452        "(Ljava/lang/String;Ljava/lang/String;)Z",
1453        &[JValue::Object(&ji), JValue::Object(&jc)],
1454    )
1455    .and_then(|v| v.z())
1456    .unwrap_or(false)
1457}
1458
1459unsafe extern "C" fn srv_bossbar_add_player(_ctx: *mut c_void, id: YogStr, player: YogStr) -> bool {
1460    let Some(mut env) = get_env() else {
1461        return false;
1462    };
1463    let (Some(ji), Some(jp)) = (ys_to_java(&mut env, id), ys_to_java(&mut env, player)) else {
1464        return false;
1465    };
1466    env.call_static_method(
1467        "dev/yog/NativeBridge",
1468        "bossbarAddPlayer",
1469        "(Ljava/lang/String;Ljava/lang/String;)Z",
1470        &[JValue::Object(&ji), JValue::Object(&jp)],
1471    )
1472    .and_then(|v| v.z())
1473    .unwrap_or(false)
1474}
1475
1476unsafe extern "C" fn srv_bossbar_remove_player(
1477    _ctx: *mut c_void,
1478    id: YogStr,
1479    player: YogStr,
1480) -> bool {
1481    let Some(mut env) = get_env() else {
1482        return false;
1483    };
1484    let (Some(ji), Some(jp)) = (ys_to_java(&mut env, id), ys_to_java(&mut env, player)) else {
1485        return false;
1486    };
1487    env.call_static_method(
1488        "dev/yog/NativeBridge",
1489        "bossbarRemovePlayer",
1490        "(Ljava/lang/String;Ljava/lang/String;)Z",
1491        &[JValue::Object(&ji), JValue::Object(&jp)],
1492    )
1493    .and_then(|v| v.z())
1494    .unwrap_or(false)
1495}
1496
1497unsafe extern "C" fn srv_bossbar_set_visible(_ctx: *mut c_void, id: YogStr, visible: bool) -> bool {
1498    let Some(mut env) = get_env() else {
1499        return false;
1500    };
1501    let Some(ji) = ys_to_java(&mut env, id) else {
1502        return false;
1503    };
1504    env.call_static_method(
1505        "dev/yog/NativeBridge",
1506        "bossbarSetVisible",
1507        "(Ljava/lang/String;Z)Z",
1508        &[JValue::Object(&ji), JValue::Bool(visible as u8)],
1509    )
1510    .and_then(|v| v.z())
1511    .unwrap_or(false)
1512}
1513
1514unsafe extern "C" fn srv_get_block_nbt(
1515    _ctx: *mut c_void,
1516    dim: YogStr,
1517    pos: YogBlockPos,
1518) -> YogOwnedStr {
1519    let Some(mut env) = get_env() else {
1520        return YogOwnedStr::NONE;
1521    };
1522    let Some(jd) = ys_to_java(&mut env, dim) else {
1523        return YogOwnedStr::NONE;
1524    };
1525    let ret = env.call_static_method(
1526        "dev/yog/NativeBridge",
1527        "getBlockNbt",
1528        "(Ljava/lang/String;III)Ljava/lang/String;",
1529        &[
1530            JValue::Object(&jd),
1531            JValue::Int(pos.x),
1532            JValue::Int(pos.y),
1533            JValue::Int(pos.z),
1534        ],
1535    );
1536    match ret.and_then(|v| v.l()) {
1537        Ok(obj) => jstring_to_owned(&mut env, obj),
1538        _ => YogOwnedStr::NONE,
1539    }
1540}
1541
1542unsafe extern "C" fn srv_set_block_nbt(
1543    _ctx: *mut c_void,
1544    dim: YogStr,
1545    pos: YogBlockPos,
1546    snbt: YogStr,
1547) -> bool {
1548    let Some(mut env) = get_env() else {
1549        return false;
1550    };
1551    let (Some(jd), Some(js)) = (ys_to_java(&mut env, dim), ys_to_java(&mut env, snbt)) else {
1552        return false;
1553    };
1554    env.call_static_method(
1555        "dev/yog/NativeBridge",
1556        "setBlockNbt",
1557        "(Ljava/lang/String;IIILjava/lang/String;)Z",
1558        &[
1559            JValue::Object(&jd),
1560            JValue::Int(pos.x),
1561            JValue::Int(pos.y),
1562            JValue::Int(pos.z),
1563            JValue::Object(&js),
1564        ],
1565    )
1566    .and_then(|v| v.z())
1567    .unwrap_or(false)
1568}
1569
1570unsafe extern "C" fn srv_get_inventory_slot(
1571    _ctx: *mut c_void,
1572    dim: YogStr,
1573    pos: yog_abi::YogBlockPos,
1574    slot: u32,
1575) -> YogOwnedStr {
1576    let Some(mut env) = get_env() else {
1577        return YogOwnedStr::NONE;
1578    };
1579    let Some(jd) = ys_to_java(&mut env, dim) else {
1580        return YogOwnedStr::NONE;
1581    };
1582    let ret = env.call_static_method(
1583        "dev/yog/NativeBridge",
1584        "getInventorySlot",
1585        "(Ljava/lang/String;IIII)Ljava/lang/String;",
1586        &[
1587            JValue::Object(&jd),
1588            JValue::Int(pos.x),
1589            JValue::Int(pos.y),
1590            JValue::Int(pos.z),
1591            JValue::Int(slot as i32),
1592        ],
1593    );
1594    match ret.and_then(|v| v.l()) {
1595        Ok(obj) => jstring_to_owned(&mut env, obj),
1596        _ => YogOwnedStr::NONE,
1597    }
1598}
1599
1600unsafe extern "C" fn srv_set_inventory_slot(
1601    _ctx: *mut c_void,
1602    dim: YogStr,
1603    pos: yog_abi::YogBlockPos,
1604    slot: u32,
1605    item_id: YogStr,
1606    count: u32,
1607) -> bool {
1608    let Some(mut env) = get_env() else {
1609        return false;
1610    };
1611    let (Some(jd), Some(ji)) = (ys_to_java(&mut env, dim), ys_to_java(&mut env, item_id)) else {
1612        return false;
1613    };
1614    env.call_static_method(
1615        "dev/yog/NativeBridge",
1616        "setInventorySlot",
1617        "(Ljava/lang/String;IIIILjava/lang/String;I)Z",
1618        &[
1619            JValue::Object(&jd),
1620            JValue::Int(pos.x),
1621            JValue::Int(pos.y),
1622            JValue::Int(pos.z),
1623            JValue::Int(slot as i32),
1624            JValue::Object(&ji),
1625            JValue::Int(count as i32),
1626        ],
1627    )
1628    .and_then(|v| v.z())
1629    .unwrap_or(false)
1630}
1631
1632unsafe extern "C" fn srv_player_inventory(_ctx: *mut c_void, player: YogStr) -> YogOwnedStr {
1633    let Some(mut env) = get_env() else {
1634        return YogOwnedStr::NONE;
1635    };
1636    let Some(jp) = ys_to_java(&mut env, player) else {
1637        return YogOwnedStr::NONE;
1638    };
1639    let ret = env.call_static_method(
1640        "dev/yog/NativeBridge",
1641        "playerInventory",
1642        "(Ljava/lang/String;)Ljava/lang/String;",
1643        &[JValue::Object(&jp)],
1644    );
1645    match ret.and_then(|v| v.l()) {
1646        Ok(obj) => jstring_to_owned(&mut env, obj),
1647        _ => YogOwnedStr::NONE,
1648    }
1649}
1650
1651unsafe extern "C" fn srv_player_set_slot(
1652    _ctx: *mut c_void,
1653    player: YogStr,
1654    slot: u32,
1655    item_id: YogStr,
1656    count: u32,
1657) -> bool {
1658    let Some(mut env) = get_env() else {
1659        return false;
1660    };
1661    let (Some(jp), Some(ji)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, item_id)) else {
1662        return false;
1663    };
1664    env.call_static_method(
1665        "dev/yog/NativeBridge",
1666        "playerSetSlot",
1667        "(Ljava/lang/String;ILjava/lang/String;I)Z",
1668        &[
1669            JValue::Object(&jp),
1670            JValue::Int(slot as i32),
1671            JValue::Object(&ji),
1672            JValue::Int(count as i32),
1673        ],
1674    )
1675    .and_then(|v| v.z())
1676    .unwrap_or(false)
1677}
1678
1679unsafe extern "C" fn srv_player_teleport_dim(
1680    _ctx: *mut c_void,
1681    player: YogStr,
1682    dim: YogStr,
1683    pos: YogVec3,
1684) -> bool {
1685    let Some(mut env) = get_env() else {
1686        return false;
1687    };
1688    let (Some(jp), Some(jd)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, dim)) else {
1689        return false;
1690    };
1691    env.call_static_method(
1692        "dev/yog/NativeBridge",
1693        "teleportToDim",
1694        "(Ljava/lang/String;Ljava/lang/String;DDD)Z",
1695        &[
1696            JValue::Object(&jp),
1697            JValue::Object(&jd),
1698            JValue::Double(pos.x),
1699            JValue::Double(pos.y),
1700            JValue::Double(pos.z),
1701        ],
1702    )
1703    .and_then(|v| v.z())
1704    .unwrap_or(false)
1705}
1706
1707unsafe extern "C" fn srv_entity_teleport_dim(
1708    _ctx: *mut c_void,
1709    uuid: YogStr,
1710    dim: YogStr,
1711    pos: YogVec3,
1712) -> bool {
1713    let Some(mut env) = get_env() else {
1714        return false;
1715    };
1716    let (Some(ju), Some(jd)) = (ys_to_java(&mut env, uuid), ys_to_java(&mut env, dim)) else {
1717        return false;
1718    };
1719    env.call_static_method(
1720        "dev/yog/NativeBridge",
1721        "entityTeleportToDim",
1722        "(Ljava/lang/String;Ljava/lang/String;DDD)Z",
1723        &[
1724            JValue::Object(&ju),
1725            JValue::Object(&jd),
1726            JValue::Double(pos.x),
1727            JValue::Double(pos.y),
1728            JValue::Double(pos.z),
1729        ],
1730    )
1731    .and_then(|v| v.z())
1732    .unwrap_or(false)
1733}
1734
1735unsafe extern "C" fn srv_online_players(_ctx: *mut c_void) -> YogOwnedStr {
1736    let Some(mut env) = get_env() else {
1737        return YogOwnedStr::NONE;
1738    };
1739    let ret = env.call_static_method(
1740        "dev/yog/NativeBridge",
1741        "onlinePlayers",
1742        "()Ljava/lang/String;",
1743        &[],
1744    );
1745    match ret.and_then(|v| v.l()) {
1746        Ok(obj) => jstring_to_owned(&mut env, obj),
1747        _ => YogOwnedStr::NONE,
1748    }
1749}
1750
1751unsafe extern "C" fn srv_world_entity_count(
1752    _ctx: *mut c_void,
1753    dim: YogStr,
1754    entity_type: YogStr,
1755) -> i32 {
1756    let Some(mut env) = get_env() else { return -1 };
1757    let d = dim.as_str();
1758    let et = entity_type.as_str();
1759    let jd = match env.new_string(d) {
1760        Ok(s) => s,
1761        Err(_) => return -1,
1762    };
1763    let jet = match env.new_string(et) {
1764        Ok(s) => s,
1765        Err(_) => return -1,
1766    };
1767    let ret = env.call_static_method(
1768        "dev/yog/NativeBridge",
1769        "worldEntityCount",
1770        "(Ljava/lang/String;Ljava/lang/String;)I",
1771        &[JValue::Object(&jd), JValue::Object(&jet)],
1772    );
1773    ret.and_then(|v| v.i()).unwrap_or(-1)
1774}
1775
1776unsafe extern "C" fn srv_game_dir(_ctx: *mut c_void) -> YogOwnedStr {
1777    let Some(mut env) = get_env() else {
1778        return YogOwnedStr::NONE;
1779    };
1780    let ret = env.call_static_method(
1781        "dev/yog/NativeBridge",
1782        "gameDir",
1783        "()Ljava/lang/String;",
1784        &[],
1785    );
1786    match ret.and_then(|v| v.l()) {
1787        Ok(obj) => jstring_to_owned(&mut env, obj),
1788        _ => YogOwnedStr::NONE,
1789    }
1790}
1791
1792unsafe extern "C" fn srv_entity_get_nbt(_ctx: *mut c_void, uuid: YogStr) -> YogOwnedStr {
1793    let Some(mut env) = get_env() else {
1794        return YogOwnedStr::NONE;
1795    };
1796    let Some(ju) = ys_to_java(&mut env, uuid) else {
1797        return YogOwnedStr::NONE;
1798    };
1799    let ret = env.call_static_method(
1800        "dev/yog/NativeBridge",
1801        "entityGetNbt",
1802        "(Ljava/lang/String;)Ljava/lang/String;",
1803        &[JValue::Object(&ju)],
1804    );
1805    match ret.and_then(|v| v.l()) {
1806        Ok(obj) => jstring_to_owned(&mut env, obj),
1807        _ => YogOwnedStr::NONE,
1808    }
1809}
1810
1811unsafe extern "C" fn srv_entity_set_nbt(_ctx: *mut c_void, uuid: YogStr, snbt: YogStr) -> bool {
1812    let Some(mut env) = get_env() else {
1813        return false;
1814    };
1815    let (Some(ju), Some(js)) = (ys_to_java(&mut env, uuid), ys_to_java(&mut env, snbt)) else {
1816        return false;
1817    };
1818    env.call_static_method(
1819        "dev/yog/NativeBridge",
1820        "entitySetNbt",
1821        "(Ljava/lang/String;Ljava/lang/String;)Z",
1822        &[JValue::Object(&ju), JValue::Object(&js)],
1823    )
1824    .and_then(|v| v.z())
1825    .unwrap_or(false)
1826}
1827
1828unsafe extern "C" fn srv_spawn_particles(
1829    _ctx: *mut c_void,
1830    dim: YogStr,
1831    pos: YogVec3,
1832    particle_type: YogStr,
1833    count: i32,
1834    dx: f64,
1835    dy: f64,
1836    dz: f64,
1837    speed: f64,
1838) -> bool {
1839    let Some(mut env) = get_env() else {
1840        return false;
1841    };
1842    let (Some(jd), Some(jp)) = (
1843        ys_to_java(&mut env, dim),
1844        ys_to_java(&mut env, particle_type),
1845    ) else {
1846        return false;
1847    };
1848    env.call_static_method(
1849        "dev/yog/NativeBridge",
1850        "spawnParticles",
1851        "(Ljava/lang/String;DDDLjava/lang/String;IDDDD)Z",
1852        &[
1853            JValue::Object(&jd),
1854            JValue::Double(pos.x),
1855            JValue::Double(pos.y),
1856            JValue::Double(pos.z),
1857            JValue::Object(&jp),
1858            JValue::Int(count),
1859            JValue::Double(dx),
1860            JValue::Double(dy),
1861            JValue::Double(dz),
1862            JValue::Double(speed),
1863        ],
1864    )
1865    .and_then(|v| v.z())
1866    .unwrap_or(false)
1867}
1868
1869unsafe extern "C" fn srv_entity_attribute_get(
1870    _ctx: *mut c_void,
1871    uuid: YogStr,
1872    attr: YogStr,
1873) -> f64 {
1874    let Some(mut env) = get_env() else {
1875        return f64::NAN;
1876    };
1877    let (Some(ju), Some(ja)) = (ys_to_java(&mut env, uuid), ys_to_java(&mut env, attr)) else {
1878        return f64::NAN;
1879    };
1880    env.call_static_method(
1881        "dev/yog/NativeBridge",
1882        "entityAttributeGet",
1883        "(Ljava/lang/String;Ljava/lang/String;)D",
1884        &[JValue::Object(&ju), JValue::Object(&ja)],
1885    )
1886    .and_then(|v| v.d())
1887    .unwrap_or(f64::NAN)
1888}
1889
1890unsafe extern "C" fn srv_entity_attribute_set(
1891    _ctx: *mut c_void,
1892    uuid: YogStr,
1893    attr: YogStr,
1894    value: f64,
1895) -> bool {
1896    let Some(mut env) = get_env() else {
1897        return false;
1898    };
1899    let (Some(ju), Some(ja)) = (ys_to_java(&mut env, uuid), ys_to_java(&mut env, attr)) else {
1900        return false;
1901    };
1902    env.call_static_method(
1903        "dev/yog/NativeBridge",
1904        "entityAttributeSet",
1905        "(Ljava/lang/String;Ljava/lang/String;D)Z",
1906        &[
1907            JValue::Object(&ju),
1908            JValue::Object(&ja),
1909            JValue::Double(value),
1910        ],
1911    )
1912    .and_then(|v| v.z())
1913    .unwrap_or(false)
1914}
1915
1916unsafe extern "C" fn srv_get_held_item_nbt(_ctx: *mut c_void, player: YogStr) -> YogOwnedStr {
1917    let Some(mut env) = get_env() else {
1918        return YogOwnedStr::NONE;
1919    };
1920    let Some(jp) = ys_to_java(&mut env, player) else {
1921        return YogOwnedStr::NONE;
1922    };
1923    let ret = env.call_static_method(
1924        "dev/yog/NativeBridge",
1925        "getHeldItemNbt",
1926        "(Ljava/lang/String;)Ljava/lang/String;",
1927        &[JValue::Object(&jp)],
1928    );
1929    match ret.and_then(|v| v.l()) {
1930        Ok(obj) => jstring_to_owned(&mut env, obj),
1931        _ => YogOwnedStr::NONE,
1932    }
1933}
1934
1935unsafe extern "C" fn srv_set_held_item_nbt(
1936    _ctx: *mut c_void,
1937    player: YogStr,
1938    snbt: YogStr,
1939) -> bool {
1940    let Some(mut env) = get_env() else {
1941        return false;
1942    };
1943    let (Some(jp), Some(js)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, snbt)) else {
1944        return false;
1945    };
1946    env.call_static_method(
1947        "dev/yog/NativeBridge",
1948        "setHeldItemNbt",
1949        "(Ljava/lang/String;Ljava/lang/String;)Z",
1950        &[JValue::Object(&jp), JValue::Object(&js)],
1951    )
1952    .and_then(|v| v.z())
1953    .unwrap_or(false)
1954}
1955
1956unsafe extern "C" fn srv_get_offhand_item_nbt(_ctx: *mut c_void, player: YogStr) -> YogOwnedStr {
1957    let Some(mut env) = get_env() else {
1958        return YogOwnedStr::NONE;
1959    };
1960    let Some(jp) = ys_to_java(&mut env, player) else {
1961        return YogOwnedStr::NONE;
1962    };
1963    let ret = env.call_static_method(
1964        "dev/yog/NativeBridge",
1965        "getOffhandItemNbt",
1966        "(Ljava/lang/String;)Ljava/lang/String;",
1967        &[JValue::Object(&jp)],
1968    );
1969    match ret.and_then(|v| v.l()) {
1970        Ok(obj) => jstring_to_owned(&mut env, obj),
1971        _ => YogOwnedStr::NONE,
1972    }
1973}
1974
1975unsafe extern "C" fn srv_set_offhand_item_nbt(
1976    _ctx: *mut c_void,
1977    player: YogStr,
1978    snbt: YogStr,
1979) -> bool {
1980    let Some(mut env) = get_env() else {
1981        return false;
1982    };
1983    let (Some(jp), Some(js)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, snbt)) else {
1984        return false;
1985    };
1986    env.call_static_method(
1987        "dev/yog/NativeBridge",
1988        "setOffhandItemNbt",
1989        "(Ljava/lang/String;Ljava/lang/String;)Z",
1990        &[JValue::Object(&jp), JValue::Object(&js)],
1991    )
1992    .and_then(|v| v.z())
1993    .unwrap_or(false)
1994}
1995
1996unsafe extern "C" fn srv_get_slot_item(
1997    _ctx: *mut c_void,
1998    player: YogStr,
1999    slot: u32,
2000) -> YogOwnedStr {
2001    let Some(mut env) = get_env() else {
2002        return YogOwnedStr::NONE;
2003    };
2004    let Some(jp) = ys_to_java(&mut env, player) else {
2005        return YogOwnedStr::NONE;
2006    };
2007    let ret = env.call_static_method(
2008        "dev/yog/NativeBridge",
2009        "getSlotItem",
2010        "(Ljava/lang/String;I)Ljava/lang/String;",
2011        &[JValue::Object(&jp), JValue::Int(slot as i32)],
2012    );
2013    match ret.and_then(|v| v.l()) {
2014        Ok(obj) => jstring_to_owned(&mut env, obj),
2015        _ => YogOwnedStr::NONE,
2016    }
2017}
2018
2019unsafe extern "C" fn srv_set_slot_item(
2020    _ctx: *mut c_void,
2021    player: YogStr,
2022    slot: u32,
2023    item_id: YogStr,
2024    count: u32,
2025    snbt: YogStr,
2026) -> bool {
2027    let Some(mut env) = get_env() else {
2028        return false;
2029    };
2030    let (Some(jp), Some(ji), Some(js)) = (
2031        ys_to_java(&mut env, player),
2032        ys_to_java(&mut env, item_id),
2033        ys_to_java(&mut env, snbt),
2034    ) else {
2035        return false;
2036    };
2037    env.call_static_method(
2038        "dev/yog/NativeBridge",
2039        "setSlotItem",
2040        "(Ljava/lang/String;ILjava/lang/String;ILjava/lang/String;)Z",
2041        &[
2042            JValue::Object(&jp),
2043            JValue::Int(slot as i32),
2044            JValue::Object(&ji),
2045            JValue::Int(count as i32),
2046            JValue::Object(&js),
2047        ],
2048    )
2049    .and_then(|v| v.z())
2050    .unwrap_or(false)
2051}
2052
2053// ── ABI minor 14 — low-level GPU pipeline ────────────────────────────────────
2054//
2055// All raw GL calls go through `glow::Context` stored in GL.
2056// `draw2d_*` functions still call JNI (NativeDraw) for MC text/texture rendering.
2057// Everything is called on the render thread — no synchronization needed.
2058
2059// ── helpers ───────────────────────────────────────────────────────────────────
2060
2061fn gl_draw_mode(mode: u8) -> u32 {
2062    match mode {
2063        1 => glow::LINES,
2064        2 => glow::LINE_STRIP,
2065        3 => glow::TRIANGLE_STRIP,
2066        4 => glow::TRIANGLE_FAN,
2067        _ => glow::TRIANGLES,
2068    }
2069}
2070
2071fn gl_attr_type(dtype: u8) -> u32 {
2072    match dtype {
2073        1 => glow::UNSIGNED_BYTE,
2074        2 => glow::INT,
2075        3 => glow::UNSIGNED_INT,
2076        _ => glow::FLOAT,
2077    }
2078}
2079
2080unsafe fn compile_shader(gl: &glow::Context, stage: u32, src: &str) -> Option<glow::NativeShader> {
2081    let sh = gl.create_shader(stage).ok()?;
2082    gl.shader_source(sh, src);
2083    gl.compile_shader(sh);
2084    if !gl.get_shader_compile_status(sh) {
2085        yog_logging::error!("yog-gfx shader compile: {}", gl.get_shader_info_log(sh));
2086        gl.delete_shader(sh);
2087        return None;
2088    }
2089    Some(sh)
2090}
2091
2092// ── GPU buffers ───────────────────────────────────────────────────────────────
2093
2094unsafe extern "C" fn gfx_buf_create() -> u32 {
2095    let Some(g) = GL.get() else { return 0 };
2096    g.0.create_buffer().map(|b| b.0.get()).unwrap_or(0)
2097}
2098
2099unsafe extern "C" fn gfx_buf_delete(handle: u32) {
2100    let Some(g) = GL.get() else { return };
2101    let Some(n) = NonZeroU32::new(handle) else {
2102        return;
2103    };
2104    g.0.delete_buffer(glow::NativeBuffer(n));
2105}
2106
2107unsafe extern "C" fn gfx_buf_data(handle: u32, bytes: *const u8, len: u32, dynamic: bool) {
2108    let Some(g) = GL.get() else { return };
2109    let Some(n) = NonZeroU32::new(handle) else {
2110        return;
2111    };
2112    let gl = &g.0;
2113    let data = std::slice::from_raw_parts(bytes, len as usize);
2114    let usage = if dynamic {
2115        glow::DYNAMIC_DRAW
2116    } else {
2117        glow::STATIC_DRAW
2118    };
2119    gl.bind_buffer(glow::ARRAY_BUFFER, Some(glow::NativeBuffer(n)));
2120    gl.buffer_data_u8_slice(glow::ARRAY_BUFFER, data, usage);
2121    gl.bind_buffer(glow::ARRAY_BUFFER, None);
2122}
2123
2124unsafe extern "C" fn gfx_buf_subdata(handle: u32, offset: u32, bytes: *const u8, len: u32) {
2125    let Some(g) = GL.get() else { return };
2126    let Some(n) = NonZeroU32::new(handle) else {
2127        return;
2128    };
2129    let gl = &g.0;
2130    let data = std::slice::from_raw_parts(bytes, len as usize);
2131    gl.bind_buffer(glow::ARRAY_BUFFER, Some(glow::NativeBuffer(n)));
2132    gl.buffer_sub_data_u8_slice(glow::ARRAY_BUFFER, offset as i32, data);
2133    gl.bind_buffer(glow::ARRAY_BUFFER, None);
2134}
2135
2136// ── Vertex arrays ─────────────────────────────────────────────────────────────
2137
2138unsafe extern "C" fn gfx_vao_create() -> u32 {
2139    let Some(g) = GL.get() else { return 0 };
2140    g.0.create_vertex_array().map(|v| v.0.get()).unwrap_or(0)
2141}
2142
2143unsafe extern "C" fn gfx_vao_delete(handle: u32) {
2144    let Some(g) = GL.get() else { return };
2145    let Some(n) = NonZeroU32::new(handle) else {
2146        return;
2147    };
2148    g.0.delete_vertex_array(glow::NativeVertexArray(n));
2149}
2150
2151unsafe extern "C" fn gfx_vao_attrib(
2152    vao: u32,
2153    vbo: u32,
2154    index: u32,
2155    components: u8,
2156    dtype: u8,
2157    normalized: bool,
2158    stride: u32,
2159    offset: u32,
2160) {
2161    let Some(g) = GL.get() else { return };
2162    let (Some(vn), Some(bn)) = (NonZeroU32::new(vao), NonZeroU32::new(vbo)) else {
2163        return;
2164    };
2165    let gl = &g.0;
2166    gl.bind_vertex_array(Some(glow::NativeVertexArray(vn)));
2167    gl.bind_buffer(glow::ARRAY_BUFFER, Some(glow::NativeBuffer(bn)));
2168    let gl_type = gl_attr_type(dtype);
2169    if dtype == 2 || dtype == 3 {
2170        gl.vertex_attrib_pointer_i32(
2171            index,
2172            components as i32,
2173            gl_type,
2174            stride as i32,
2175            offset as i32,
2176        );
2177    } else {
2178        gl.vertex_attrib_pointer_f32(
2179            index,
2180            components as i32,
2181            gl_type,
2182            normalized,
2183            stride as i32,
2184            offset as i32,
2185        );
2186    }
2187    gl.enable_vertex_attrib_array(index);
2188    gl.bind_vertex_array(None);
2189}
2190
2191unsafe extern "C" fn gfx_vao_set_ebo(vao: u32, ebo: u32) {
2192    let Some(g) = GL.get() else { return };
2193    let (Some(vn), Some(en)) = (NonZeroU32::new(vao), NonZeroU32::new(ebo)) else {
2194        return;
2195    };
2196    let gl = &g.0;
2197    gl.bind_vertex_array(Some(glow::NativeVertexArray(vn)));
2198    gl.bind_buffer(glow::ELEMENT_ARRAY_BUFFER, Some(glow::NativeBuffer(en)));
2199    gl.bind_vertex_array(None);
2200}
2201
2202// ── Shader programs ───────────────────────────────────────────────────────────
2203
2204/// Returns a path under `~/.cache/yog/shaders/<hash>.ysc` for the given GLSL source pair,
2205/// creating the directory if needed.  Returns `None` if the home directory is unknown.
2206fn shader_cache_path(vert: &str, frag: &str) -> Option<PathBuf> {
2207    use std::hash::{Hash, Hasher};
2208    let mut h = std::collections::hash_map::DefaultHasher::new();
2209    vert.hash(&mut h);
2210    frag.hash(&mut h);
2211    let hash = h.finish();
2212    let dir = std::env::var("HOME")
2213        .map(|home| {
2214            PathBuf::from(home)
2215                .join(".cache")
2216                .join("yog")
2217                .join("shaders")
2218        })
2219        .ok()?;
2220    std::fs::create_dir_all(&dir).ok()?;
2221    Some(dir.join(format!("{hash:016x}.ysc")))
2222}
2223
2224/// Try restoring a program from a binary blob (`[4 LE bytes: GL format][binary…]`).
2225/// Returns `Some(handle)` if the driver accepts the binary, `None` otherwise.
2226///
2227/// Uses `glProgramBinary` (GL 4.1 / ARB_get_program_binary) via the raw pointer
2228/// captured in `nativeGlInit`.  Returns `None` if the extension is unavailable.
2229unsafe fn load_shader_binary(gl: &glow::Context, data: &[u8]) -> Option<glow::NativeProgram> {
2230    if data.len() < 4 {
2231        return None;
2232    }
2233    type ProgramBinaryFn = unsafe extern "system" fn(u32, u32, *const c_void, i32);
2234    let fn_ptr = (*GL_PROGRAM_BINARY.get()?)?;
2235    let program_binary: ProgramBinaryFn = std::mem::transmute(fn_ptr);
2236
2237    let fmt = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
2238    let prog = gl.create_program().ok()?;
2239    program_binary(
2240        prog.0.get(),
2241        fmt,
2242        data[4..].as_ptr() as *const c_void,
2243        (data.len() - 4) as i32,
2244    );
2245    if gl.get_program_link_status(prog) {
2246        Some(prog)
2247    } else {
2248        gl.delete_program(prog);
2249        None
2250    }
2251}
2252
2253/// Read the compiled binary of a linked program.  Returns empty `Vec` if unsupported.
2254unsafe fn get_shader_binary(prog: glow::NativeProgram) -> (Vec<u8>, u32) {
2255    type GetProgramivFn = unsafe extern "system" fn(u32, u32, *mut i32);
2256    type GetProgramBinaryFn = unsafe extern "system" fn(u32, i32, *mut i32, *mut u32, *mut c_void);
2257
2258    let Some(get_iv_raw) = GL_GET_PROGRAM_IV.get().and_then(|v| *v) else {
2259        return (vec![], 0);
2260    };
2261    let Some(get_bin_raw) = GL_GET_PROGRAM_BINARY.get().and_then(|v| *v) else {
2262        return (vec![], 0);
2263    };
2264    let get_program_iv: GetProgramivFn = std::mem::transmute(get_iv_raw);
2265    let get_program_binary: GetProgramBinaryFn = std::mem::transmute(get_bin_raw);
2266
2267    // Query binary size via glGetProgramiv(GL_PROGRAM_BINARY_LENGTH).
2268    const PROGRAM_BINARY_LENGTH: u32 = 0x8741;
2269    let mut size: i32 = 0;
2270    get_program_iv(prog.0.get(), PROGRAM_BINARY_LENGTH, &mut size);
2271    if size <= 0 {
2272        return (vec![], 0);
2273    }
2274
2275    let mut buf = vec![0u8; size as usize];
2276    let mut actual_len: i32 = 0;
2277    let mut fmt: u32 = 0;
2278    get_program_binary(
2279        prog.0.get(),
2280        size,
2281        &mut actual_len,
2282        &mut fmt,
2283        buf.as_mut_ptr() as *mut c_void,
2284    );
2285    buf.truncate(actual_len.max(0) as usize);
2286    (buf, fmt)
2287}
2288
2289unsafe extern "C" fn gfx_prog_create(vert: YogStr, frag: YogStr, out: *mut u32) -> bool {
2290    let Some(g) = GL.get() else { return false };
2291    let gl = &g.0;
2292    let vert_s = vert.as_str();
2293    let frag_s = frag.as_str();
2294
2295    // Fast path: binary shader cache — avoids GLSL re-compilation on subsequent launches.
2296    let cache_path = shader_cache_path(vert_s, frag_s);
2297    if let Some(ref path) = cache_path {
2298        if let Ok(data) = std::fs::read(path) {
2299            if let Some(prog) = load_shader_binary(gl, &data) {
2300                *out = prog.0.get();
2301                return true;
2302            }
2303            // Cache stale (driver updated?); remove and fall through to GLSL compile.
2304            let _ = std::fs::remove_file(path);
2305        }
2306    }
2307
2308    // GLSL compile path.
2309    let vs = match compile_shader(gl, glow::VERTEX_SHADER, vert_s) {
2310        Some(s) => s,
2311        None => return false,
2312    };
2313    let fs = match compile_shader(gl, glow::FRAGMENT_SHADER, frag_s) {
2314        Some(s) => s,
2315        None => {
2316            gl.delete_shader(vs);
2317            return false;
2318        }
2319    };
2320    let prog = match gl.create_program() {
2321        Ok(p) => p,
2322        Err(e) => {
2323            yog_logging::error!("yog-gfx: create_program: {}", e);
2324            gl.delete_shader(vs);
2325            gl.delete_shader(fs);
2326            return false;
2327        }
2328    };
2329    gl.attach_shader(prog, vs);
2330    gl.attach_shader(prog, fs);
2331    gl.link_program(prog);
2332    gl.detach_shader(prog, vs);
2333    gl.detach_shader(prog, fs);
2334    gl.delete_shader(vs);
2335    gl.delete_shader(fs);
2336    if !gl.get_program_link_status(prog) {
2337        yog_logging::error!("yog-gfx: shader link: {}", gl.get_program_info_log(prog));
2338        gl.delete_program(prog);
2339        return false;
2340    }
2341
2342    // Persist binary so the next launch skips GLSL compilation entirely.
2343    if let Some(ref path) = cache_path {
2344        let (binary, fmt) = get_shader_binary(prog);
2345        if !binary.is_empty() {
2346            let mut blob = fmt.to_le_bytes().to_vec();
2347            blob.extend_from_slice(&binary);
2348            let _ = std::fs::write(path, &blob);
2349        }
2350    }
2351
2352    *out = prog.0.get();
2353    true
2354}
2355
2356unsafe extern "C" fn gfx_prog_delete(handle: u32) {
2357    let Some(g) = GL.get() else { return };
2358    let Some(n) = NonZeroU32::new(handle) else {
2359        return;
2360    };
2361    g.0.delete_program(glow::NativeProgram(n));
2362}
2363
2364macro_rules! with_prog {
2365    ($handle:expr, |$gl:ident, $prog:ident, $loc:ident ($name:expr)| $body:expr) => {{
2366        let Some(g) = GL.get() else { return };
2367        let Some(n) = NonZeroU32::new($handle) else {
2368            return;
2369        };
2370        let $gl = &g.0;
2371        let $prog = glow::NativeProgram(n);
2372        $gl.use_program(Some($prog));
2373        let $loc = $gl.get_uniform_location($prog, $name.as_str());
2374        $body
2375    }};
2376}
2377
2378unsafe extern "C" fn gfx_prog_uniform_1i(prog: u32, name: YogStr, v: i32) {
2379    with_prog!(prog, |gl, _p, loc(name)| gl.uniform_1_i32(loc.as_ref(), v));
2380}
2381unsafe extern "C" fn gfx_prog_uniform_1f(prog: u32, name: YogStr, v: f32) {
2382    with_prog!(prog, |gl, _p, loc(name)| gl.uniform_1_f32(loc.as_ref(), v));
2383}
2384unsafe extern "C" fn gfx_prog_uniform_2f(prog: u32, name: YogStr, x: f32, y: f32) {
2385    with_prog!(prog, |gl, _p, loc(name)| gl.uniform_2_f32(
2386        loc.as_ref(),
2387        x,
2388        y
2389    ));
2390}
2391unsafe extern "C" fn gfx_prog_uniform_3f(prog: u32, name: YogStr, x: f32, y: f32, z: f32) {
2392    with_prog!(prog, |gl, _p, loc(name)| gl.uniform_3_f32(
2393        loc.as_ref(),
2394        x,
2395        y,
2396        z
2397    ));
2398}
2399unsafe extern "C" fn gfx_prog_uniform_4f(prog: u32, name: YogStr, x: f32, y: f32, z: f32, w: f32) {
2400    with_prog!(prog, |gl, _p, loc(name)| gl.uniform_4_f32(
2401        loc.as_ref(),
2402        x,
2403        y,
2404        z,
2405        w
2406    ));
2407}
2408unsafe extern "C" fn gfx_prog_uniform_mat4(prog: u32, name: YogStr, col_major: *const f32) {
2409    with_prog!(prog, |gl, _p, loc(name)| {
2410        let data = std::slice::from_raw_parts(col_major, 16);
2411        gl.uniform_matrix_4_f32_slice(loc.as_ref(), false, data);
2412    });
2413}
2414
2415// ── Textures ──────────────────────────────────────────────────────────────────
2416
2417unsafe extern "C" fn gfx_tex_create(w: u32, h: u32, rgba: *const u8, linear: bool) -> u32 {
2418    let Some(g) = GL.get() else { return 0 };
2419    let gl = &g.0;
2420    let tex = match gl.create_texture() {
2421        Ok(t) => t,
2422        Err(_) => return 0,
2423    };
2424    gl.bind_texture(glow::TEXTURE_2D, Some(tex));
2425    let filter = if linear { glow::LINEAR } else { glow::NEAREST };
2426    gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MIN_FILTER, filter as i32);
2427    gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MAG_FILTER, filter as i32);
2428    gl.tex_parameter_i32(
2429        glow::TEXTURE_2D,
2430        glow::TEXTURE_WRAP_S,
2431        glow::CLAMP_TO_EDGE as i32,
2432    );
2433    gl.tex_parameter_i32(
2434        glow::TEXTURE_2D,
2435        glow::TEXTURE_WRAP_T,
2436        glow::CLAMP_TO_EDGE as i32,
2437    );
2438    let pixels = std::slice::from_raw_parts(rgba, (w * h * 4) as usize);
2439    gl.tex_image_2d(
2440        glow::TEXTURE_2D,
2441        0,
2442        glow::RGBA8 as i32,
2443        w as i32,
2444        h as i32,
2445        0,
2446        glow::RGBA,
2447        glow::UNSIGNED_BYTE,
2448        glow::PixelUnpackData::Slice(Some(pixels)),
2449    );
2450    gl.bind_texture(glow::TEXTURE_2D, None);
2451    tex.0.get()
2452}
2453
2454unsafe extern "C" fn gfx_tex_delete(handle: u32) {
2455    let Some(g) = GL.get() else { return };
2456    let Some(n) = NonZeroU32::new(handle) else {
2457        return;
2458    };
2459    g.0.delete_texture(glow::NativeTexture(n));
2460}
2461
2462unsafe extern "C" fn gfx_tex_bind(unit: u32, handle: u32) {
2463    let Some(g) = GL.get() else { return };
2464    let gl = &g.0;
2465    gl.active_texture(glow::TEXTURE0 + unit);
2466    match NonZeroU32::new(handle) {
2467        Some(n) => gl.bind_texture(glow::TEXTURE_2D, Some(glow::NativeTexture(n))),
2468        None => gl.bind_texture(glow::TEXTURE_2D, None),
2469    }
2470}
2471
2472unsafe extern "C" fn gfx_tex_from_mc(id: YogStr) -> u32 {
2473    let Some(mut env) = get_env() else { return 0 };
2474    let Some(ji) = ys_to_java(&mut env, id) else {
2475        return 0;
2476    };
2477    env.call_static_method(
2478        "dev/yog/NativeDraw",
2479        "getMcTextureId",
2480        "(Ljava/lang/String;)I",
2481        &[JValue::Object(&ji)],
2482    )
2483    .and_then(|v| v.i())
2484    .map(|id| id as u32)
2485    .unwrap_or(0)
2486}
2487
2488// ── Draw calls ────────────────────────────────────────────────────────────────
2489
2490unsafe extern "C" fn gfx_draw_arrays(vao: u32, prog: u32, mode: u8, first: u32, count: u32) {
2491    let Some(g) = GL.get() else { return };
2492    let (Some(vn), Some(pn)) = (NonZeroU32::new(vao), NonZeroU32::new(prog)) else {
2493        return;
2494    };
2495    let gl = &g.0;
2496    gl.use_program(Some(glow::NativeProgram(pn)));
2497    gl.bind_vertex_array(Some(glow::NativeVertexArray(vn)));
2498    gl.draw_arrays(gl_draw_mode(mode), first as i32, count as i32);
2499    gl.bind_vertex_array(None);
2500}
2501
2502unsafe extern "C" fn gfx_draw_elements(
2503    vao: u32,
2504    ebo: u32,
2505    prog: u32,
2506    mode: u8,
2507    count: u32,
2508    u32_idx: bool,
2509) {
2510    let Some(g) = GL.get() else { return };
2511    let (Some(vn), Some(pn)) = (NonZeroU32::new(vao), NonZeroU32::new(prog)) else {
2512        return;
2513    };
2514    let gl = &g.0;
2515    gl.use_program(Some(glow::NativeProgram(pn)));
2516    gl.bind_vertex_array(Some(glow::NativeVertexArray(vn)));
2517    // EBO is stored in the VAO; ebo param is informational for safety but not re-bound here.
2518    let _ = ebo;
2519    let idx_type = if u32_idx {
2520        glow::UNSIGNED_INT
2521    } else {
2522        glow::UNSIGNED_SHORT
2523    };
2524    gl.draw_elements(gl_draw_mode(mode), count as i32, idx_type, 0);
2525    gl.bind_vertex_array(None);
2526}
2527
2528// ── Render state ──────────────────────────────────────────────────────────────
2529
2530unsafe extern "C" fn gfx_set_blend(enabled: bool, src: u32, dst: u32) {
2531    let Some(g) = GL.get() else { return };
2532    let gl = &g.0;
2533    if enabled {
2534        gl.enable(glow::BLEND);
2535        gl.blend_func(src, dst);
2536    } else {
2537        gl.disable(glow::BLEND);
2538    }
2539}
2540
2541unsafe extern "C" fn gfx_set_depth(test: bool, write: bool) {
2542    let Some(g) = GL.get() else { return };
2543    let gl = &g.0;
2544    if test {
2545        gl.enable(glow::DEPTH_TEST);
2546    } else {
2547        gl.disable(glow::DEPTH_TEST);
2548    }
2549    gl.depth_mask(write);
2550    // Disable face culling: our 2D quads use CW winding (back-face) due to y-flip.
2551    if !test {
2552        gl.disable(glow::CULL_FACE);
2553    }
2554}
2555
2556unsafe extern "C" fn gfx_set_scissor(x: i32, y: i32, w: i32, h: i32) {
2557    let Some(g) = GL.get() else { return };
2558    let gl = &g.0;
2559    gl.enable(glow::SCISSOR_TEST);
2560    gl.scissor(x, y, w, h);
2561}
2562
2563unsafe extern "C" fn gfx_clear_scissor() {
2564    let Some(g) = GL.get() else { return };
2565    g.0.disable(glow::SCISSOR_TEST);
2566}
2567
2568unsafe extern "C" fn gfx_set_viewport(x: i32, y: i32, w: i32, h: i32) {
2569    let Some(g) = GL.get() else { return };
2570    g.0.viewport(x, y, w, h);
2571}
2572
2573// ── 2D convenience (JNI — uses MC's DrawContext / text renderer) ──────────────
2574
2575unsafe extern "C" fn gfx_draw2d_rect(x1: f32, y1: f32, x2: f32, y2: f32, color: u32) {
2576    let Some(mut env) = get_env() else { return };
2577    let _ = env.call_static_method(
2578        "dev/yog/NativeDraw",
2579        "drawRect",
2580        "(FFFFI)V",
2581        &[
2582            JValue::Float(x1),
2583            JValue::Float(y1),
2584            JValue::Float(x2),
2585            JValue::Float(y2),
2586            JValue::Int(color as i32),
2587        ],
2588    );
2589}
2590
2591unsafe extern "C" fn gfx_draw2d_gradient(
2592    x1: f32,
2593    y1: f32,
2594    x2: f32,
2595    y2: f32,
2596    top: u32,
2597    bottom: u32,
2598) {
2599    let Some(mut env) = get_env() else { return };
2600    let _ = env.call_static_method(
2601        "dev/yog/NativeDraw",
2602        "drawGradientRect",
2603        "(FFFFII)V",
2604        &[
2605            JValue::Float(x1),
2606            JValue::Float(y1),
2607            JValue::Float(x2),
2608            JValue::Float(y2),
2609            JValue::Int(top as i32),
2610            JValue::Int(bottom as i32),
2611        ],
2612    );
2613}
2614
2615unsafe extern "C" fn gfx_draw2d_text(text: YogStr, x: f32, y: f32, color: u32, shadow: bool) {
2616    let Some(mut env) = get_env() else { return };
2617    if let Some(jt) = ys_to_java(&mut env, text) {
2618        let _ = env.call_static_method(
2619            "dev/yog/NativeDraw",
2620            "drawText",
2621            "(Ljava/lang/String;FFIZ)V",
2622            &[
2623                JValue::Object(&jt),
2624                JValue::Float(x),
2625                JValue::Float(y),
2626                JValue::Int(color as i32),
2627                JValue::Bool(shadow as u8),
2628            ],
2629        );
2630    }
2631}
2632
2633unsafe extern "C" fn gfx_draw2d_text_font(
2634    text: YogStr,
2635    font: YogStr,
2636    x: f32,
2637    y: f32,
2638    color: u32,
2639    shadow: bool,
2640) {
2641    let Some(mut env) = get_env() else { return };
2642    let (Some(jt), Some(jf)) = (ys_to_java(&mut env, text), ys_to_java(&mut env, font)) else {
2643        return;
2644    };
2645    let _ = env.call_static_method(
2646        "dev/yog/NativeDraw",
2647        "drawTextFont",
2648        "(Ljava/lang/String;Ljava/lang/String;FFIZ)V",
2649        &[
2650            JValue::Object(&jt),
2651            JValue::Object(&jf),
2652            JValue::Float(x),
2653            JValue::Float(y),
2654            JValue::Int(color as i32),
2655            JValue::Bool(shadow as u8),
2656        ],
2657    );
2658}
2659
2660unsafe extern "C" fn gfx_text_width(text: YogStr, font: YogStr) -> f32 {
2661    let Some(mut env) = get_env() else { return 0.0 };
2662    let (Some(jt), Some(jf)) = (ys_to_java(&mut env, text), ys_to_java(&mut env, font)) else {
2663        return 0.0;
2664    };
2665    match env.call_static_method(
2666        "dev/yog/NativeDraw",
2667        "textWidth",
2668        "(Ljava/lang/String;Ljava/lang/String;)F",
2669        &[JValue::Object(&jt), JValue::Object(&jf)],
2670    ) {
2671        Ok(v) => v.f().unwrap_or(0.0),
2672        Err(_) => {
2673            env.exception_clear().ok();
2674            0.0
2675        }
2676    }
2677}
2678
2679unsafe extern "C" fn gfx_draw2d_item(id: YogStr, x: f32, y: f32, size: f32) {
2680    let Some(mut env) = get_env() else { return };
2681    if let Some(ji) = ys_to_java(&mut env, id) {
2682        if env
2683            .call_static_method(
2684                "dev/yog/NativeDraw",
2685                "drawItem",
2686                "(Ljava/lang/String;FFF)V",
2687                &[
2688                    JValue::Object(&ji),
2689                    JValue::Float(x),
2690                    JValue::Float(y),
2691                    JValue::Float(size),
2692                ],
2693            )
2694            .is_err()
2695        {
2696            env.exception_clear().ok();
2697        }
2698    }
2699}
2700
2701// ── Static GFX function table (function pointers only — per-frame data filled at call time) ──
2702
2703static GFX_FN_TABLE: YogGfxApi = YogGfxApi {
2704    // Per-frame fields zeroed in the static; actual values are set on the stack per render call.
2705    screen_w: 0,
2706    screen_h: 0,
2707    delta_tick: 0.0,
2708    scale_factor: 1.0,
2709    view_proj: [0.0; 16],
2710    camera_pos: [0.0; 3],
2711    player_pos: [0.0; 3],
2712    _pad1: 0.0,
2713    buf_create: gfx_buf_create,
2714    buf_delete: gfx_buf_delete,
2715    buf_data: gfx_buf_data,
2716    buf_subdata: gfx_buf_subdata,
2717    vao_create: gfx_vao_create,
2718    vao_delete: gfx_vao_delete,
2719    vao_attrib: gfx_vao_attrib,
2720    vao_set_ebo: gfx_vao_set_ebo,
2721    prog_create: gfx_prog_create,
2722    prog_delete: gfx_prog_delete,
2723    prog_uniform_1i: gfx_prog_uniform_1i,
2724    prog_uniform_1f: gfx_prog_uniform_1f,
2725    prog_uniform_2f: gfx_prog_uniform_2f,
2726    prog_uniform_3f: gfx_prog_uniform_3f,
2727    prog_uniform_4f: gfx_prog_uniform_4f,
2728    prog_uniform_mat4: gfx_prog_uniform_mat4,
2729    tex_create: gfx_tex_create,
2730    tex_delete: gfx_tex_delete,
2731    tex_bind: gfx_tex_bind,
2732    tex_from_mc: gfx_tex_from_mc,
2733    draw_arrays: gfx_draw_arrays,
2734    draw_elements: gfx_draw_elements,
2735    set_blend: gfx_set_blend,
2736    set_depth: gfx_set_depth,
2737    set_scissor: gfx_set_scissor,
2738    clear_scissor: gfx_clear_scissor,
2739    set_viewport: gfx_set_viewport,
2740    draw2d_rect: gfx_draw2d_rect,
2741    draw2d_gradient: gfx_draw2d_gradient,
2742    draw2d_text: gfx_draw2d_text,
2743    draw2d_item: gfx_draw2d_item,
2744    draw2d_text_font: gfx_draw2d_text_font,
2745    text_width: gfx_text_width,
2746    draw2d_image: images::gfx_draw2d_image,
2747    image_size: images::gfx_image_size,
2748};
2749
2750// ── YogApi registration functions ─────────────────────────────────────────────
2751//
2752// ctx is *const RwLock<RuntimeHandlers> (cast from *mut c_void) — see
2753// `current_registration()` for how each entry gets tagged with the
2754// `LoadedModule` that's registering it.
2755
2756macro_rules! api_event {
2757    ($name:ident, $field:ident, $fn_ty:ty) => {
2758        unsafe extern "C" fn $name(ctx: *mut c_void, ud: *mut c_void, h: $fn_ty) {
2759            let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2760            let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2761            handlers.$field.push((current_registration(), ud, h));
2762        }
2763    };
2764}
2765
2766api_event!(api_on_block_break, block_break, YogBlockBreakFn);
2767api_event!(api_on_chat, chat, YogChatFn);
2768api_event!(api_on_player_join, player_join, YogPlayerFn);
2769api_event!(api_on_player_leave, player_leave, YogPlayerFn);
2770api_event!(api_on_use_item, use_item, YogUseItemFn);
2771api_event!(api_on_use_block, use_block, YogUseBlockFn);
2772api_event!(api_on_attack_entity, attack_entity, YogAttackEntityFn);
2773api_event!(api_on_entity_damage, entity_damage, YogEntityDamageFn);
2774api_event!(api_on_entity_death, entity_death, YogEntityDeathFn);
2775api_event!(api_on_entity_spawn, entity_spawn, YogEntitySpawnFn);
2776api_event!(
2777    api_on_player_place_block,
2778    player_place_block,
2779    YogPlaceBlockFn
2780);
2781api_event!(api_on_player_death, player_death, YogPlayerDeathFn);
2782api_event!(api_on_player_respawn, player_respawn, YogPlayerRespawnFn);
2783api_event!(api_on_advancement, advancement, YogAdvancementFn);
2784api_event!(api_on_entity_interact, entity_interact, YogEntityInteractFn);
2785api_event!(api_on_item_craft, item_craft, YogCraftFn);
2786api_event!(api_on_explosion, explosion, YogExplosionFn);
2787api_event!(api_on_item_pickup, item_pickup, YogItemPickupFn);
2788api_event!(api_on_player_move, player_move, YogPlayerMoveFn);
2789api_event!(api_on_container_open, container_open, YogContainerOpenFn);
2790api_event!(api_on_container_close, container_close, YogContainerCloseFn);
2791api_event!(api_on_projectile_hit, projectile_hit, YogProjectileHitFn);
2792api_event!(api_on_client_tick, client_tick, YogClientFn);
2793api_event!(api_on_hud_render, hud_render, YogHudRenderFn);
2794api_event!(api_on_world_render, world_render, YogWorldRenderFn);
2795api_event!(api_on_key_press, key_press, YogKeyPressFn);
2796api_event!(api_on_screen_open, screen_open, YogScreenFn);
2797api_event!(api_on_screen_close, screen_close, YogScreenFn);
2798api_event!(api_on_server_tick, server_tick, YogServerFn);
2799api_event!(api_on_server_started, server_started, YogServerFn);
2800api_event!(api_on_server_stopping, server_stopping, YogServerFn);
2801
2802unsafe extern "C" fn api_on_packet(
2803    ctx: *mut c_void,
2804    channel: YogStr,
2805    ud: *mut c_void,
2806    h: YogPacketFn,
2807) {
2808    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2809    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2810    handlers
2811        .packets
2812        .insert(channel.as_str().to_owned(), (current_registration(), ud, h));
2813}
2814
2815unsafe extern "C" fn api_on_client_packet(
2816    ctx: *mut c_void,
2817    channel: YogStr,
2818    ud: *mut c_void,
2819    h: YogPacketFn,
2820) {
2821    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2822    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2823    handlers
2824        .client_packets
2825        .insert(channel.as_str().to_owned(), (current_registration(), ud, h));
2826}
2827
2828unsafe extern "C" fn api_register_command(
2829    ctx: *mut c_void,
2830    name: YogStr,
2831    ud: *mut c_void,
2832    h: YogCommandFn,
2833) {
2834    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2835    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2836    handlers
2837        .commands
2838        .entry(name.as_str().to_owned())
2839        .or_default()
2840        .push((current_registration(), None, ud, h));
2841}
2842
2843unsafe extern "C" fn api_register_typed_command(
2844    ctx: *mut c_void,
2845    name: YogStr,
2846    schema: YogStr,
2847    ud: *mut c_void,
2848    h: YogCommandFn,
2849) {
2850    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2851    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2852    let n = name.as_str().to_owned();
2853    handlers.commands.entry(n).or_default().push((
2854        current_registration(),
2855        Some(schema.as_str().to_owned()),
2856        ud,
2857        h,
2858    ));
2859}
2860
2861unsafe extern "C" fn api_register_recipe_json(
2862    ctx: *mut c_void,
2863    namespace: YogStr,
2864    name: YogStr,
2865    json: YogStr,
2866) {
2867    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2868    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2869    let ns = namespace.as_str().to_owned();
2870    let n = name.as_str().to_owned();
2871    let j = json.as_str().to_owned();
2872    // Feed the recipe to already-registered book renderers (crafting pages).
2873    let full_id = format!("{}:{}", ns, n);
2874    for r in handlers.book_renderers.lock().unwrap().values_mut() {
2875        r.add_recipe(full_id.clone(), &j);
2876    }
2877    handlers.recipes.push((ns, n, j));
2878}
2879
2880unsafe extern "C" fn api_register_item(ctx: *mut c_void, def: *const YogItemDef) {
2881    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2882    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2883    let d = &*def;
2884    let food = if d.food_nutrition > 0 {
2885        Some(FoodDef {
2886            nutrition: d.food_nutrition,
2887            saturation: d.food_saturation,
2888            can_always_eat: d.food_always_eat,
2889        })
2890    } else {
2891        None
2892    };
2893    handlers.items.push(ItemDef {
2894        id: d.id.as_str().to_owned(),
2895        max_stack: d.max_stack as u8,
2896        name: if d.name.is_empty() {
2897            None
2898        } else {
2899            Some(d.name.as_str().to_owned())
2900        },
2901        tooltip: if d.tooltip.is_empty() {
2902            None
2903        } else {
2904            Some(d.tooltip.as_str().to_owned())
2905        },
2906        max_damage: d.max_damage,
2907        fire_resistant: d.fire_resistant,
2908        fuel_ticks: d.fuel_ticks,
2909        food,
2910    });
2911}
2912
2913unsafe extern "C" fn api_register_block(ctx: *mut c_void, def: *const YogBlockDef) {
2914    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2915    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2916    let d = &*def;
2917    handlers.blocks.push(BlockDef {
2918        id: d.id.as_str().to_owned(),
2919        hardness: d.hardness,
2920        resistance: d.resistance,
2921        name: if d.name.is_empty() {
2922            None
2923        } else {
2924            Some(d.name.as_str().to_owned())
2925        },
2926        light_level: d.light_level,
2927        sound: if d.sound.is_empty() {
2928            None
2929        } else {
2930            Some(d.sound.as_str().to_owned())
2931        },
2932        requires_tool: d.requires_tool,
2933        no_collision: d.no_collision,
2934        slipperiness: d.slipperiness,
2935        shape: if d.shape == [0.0f32; 6] {
2936            None
2937        } else {
2938            Some(d.shape)
2939        },
2940        connects: d.connects,
2941        connect_groups: if d.connect_groups.is_empty() {
2942            Vec::new()
2943        } else {
2944            d.connect_groups
2945                .as_str()
2946                .split(',')
2947                .map(str::to_owned)
2948                .collect()
2949        },
2950        inventory_id: if d.inventory_id.is_empty() {
2951            None
2952        } else {
2953            Some(d.inventory_id.as_str().to_owned())
2954        },
2955    });
2956}
2957
2958unsafe extern "C" fn api_register_inventory(
2959    ctx: *mut c_void,
2960    def: *const yog_abi::YogInventoryDef,
2961) {
2962    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2963    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2964    let d = &*def;
2965    handlers.inventories.push(yog_inventory::InventoryDef {
2966        id: d.id.as_str().to_owned(),
2967        slot_count: d.slot_count as usize,
2968        layout: yog_inventory::decode_layout(d.layout.as_str()),
2969        include_player_inventory: d.include_player_inventory,
2970        player_inv_offset: (d.player_inv_x, d.player_inv_y),
2971        background_texture: if d.background_texture.is_empty() {
2972            None
2973        } else {
2974            Some(d.background_texture.as_str().to_owned())
2975        },
2976        title: d.title.as_str().to_owned(),
2977        background_size: if d.background_w > 0.0 && d.background_h > 0.0 {
2978            Some((d.background_w, d.background_h))
2979        } else {
2980            None
2981        },
2982    });
2983}
2984
2985unsafe extern "C" fn api_schedule_once(
2986    ctx: *mut c_void,
2987    delay_ticks: u64,
2988    ud: *mut c_void,
2989    h: YogScheduledFn,
2990) {
2991    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2992    let handlers = handlers_lock.write().expect("handlers lock poisoned");
2993    handlers
2994        .scheduler
2995        .lock()
2996        .expect("scheduler poisoned")
2997        .once_tasks
2998        .push(OnceTask {
2999            module: current_registration(),
3000            delay_remaining: delay_ticks,
3001            ud,
3002            f: h,
3003        });
3004}
3005
3006unsafe extern "C" fn api_schedule_repeating(
3007    ctx: *mut c_void,
3008    period_ticks: u64,
3009    ud: *mut c_void,
3010    h: YogScheduledFn,
3011) {
3012    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3013    let handlers = handlers_lock.write().expect("handlers lock poisoned");
3014    handlers
3015        .scheduler
3016        .lock()
3017        .expect("scheduler poisoned")
3018        .repeating_tasks
3019        .push(RepeatingTask {
3020            module: current_registration(),
3021            period: period_ticks,
3022            ticks_left: period_ticks,
3023            ud,
3024            f: h,
3025        });
3026}
3027
3028unsafe extern "C" fn api_register_startup_grant(
3029    ctx: *mut c_void,
3030    grant: *const YogStartupGrantDef,
3031) {
3032    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3033    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3034    let g = &*grant;
3035    let items: Vec<String> = if g.items.is_empty() {
3036        Vec::new()
3037    } else {
3038        unsafe {
3039            g.items
3040                .as_str()
3041                .split('|')
3042                .map(|s: &str| s.to_owned())
3043                .collect()
3044        }
3045    };
3046    let book = if g.book.is_empty() {
3047        None
3048    } else {
3049        Some(unsafe { g.book.as_str().to_owned() })
3050    };
3051    let command = if g.command.is_empty() {
3052        None
3053    } else {
3054        Some(unsafe { g.command.as_str().to_owned() })
3055    };
3056    handlers.startup_grants.push(yog_registry::StartupGrant {
3057        id: unsafe { g.id.as_str().to_owned() },
3058        items,
3059        book,
3060        command,
3061    });
3062}
3063
3064unsafe extern "C" fn api_register_book(ctx: *mut c_void, book_id: YogStr, book_json: YogStr) {
3065    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3066    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3067    let id = unsafe { book_id.as_str().to_owned() };
3068    let json = unsafe { book_json.as_str().to_owned() };
3069    handlers.books.insert(id.clone(), json.clone());
3070    // Parse JSON → Book → BookRenderer so rendering works without Java round-trip.
3071    match serde_json::from_str::<yog_book::Book>(&json) {
3072        Ok(book) => {
3073            let mut renderer = yog_book::BookRenderer::new(book);
3074            // i18n books carry translation keys; shown in the game language.
3075            renderer.set_translator(translate);
3076            // Recipes may register before the book — replay them into the renderer.
3077            for (ns, name, j) in &handlers.recipes {
3078                renderer.add_recipe(format!("{}:{}", ns, name), j);
3079            }
3080            handlers.book_renderers.lock().unwrap().insert(id, renderer);
3081        }
3082        Err(e) => {
3083            yog_logging::warn!(
3084                "book '{}': failed to parse JSON for Rust renderer: {}",
3085                id,
3086                e
3087            );
3088        }
3089    }
3090}
3091
3092unsafe extern "C" fn api_register_dimension_json(ctx: *mut c_void, id: YogStr, json: YogStr) {
3093    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3094    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3095    let id = unsafe { id.as_str().to_owned() };
3096    let json = unsafe { json.as_str().to_owned() };
3097    yog_logging::info!("registered dimension type: {}", id);
3098    handlers.dimensions.insert(id, json);
3099}
3100
3101unsafe extern "C" fn api_register_chunk_generator(
3102    ctx: *mut c_void,
3103    id: YogStr,
3104    ud: *mut c_void,
3105    h: yog_abi::YogChunkGeneratorFn,
3106) {
3107    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3108    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3109    let id = unsafe { id.as_str().to_owned() };
3110    yog_logging::info!("registered chunk generator for dimension: {}", id);
3111    handlers
3112        .chunk_generators
3113        .insert(id, (current_registration(), ud, h));
3114}
3115
3116unsafe extern "C" fn api_register_ui(
3117    ctx: *mut c_void,
3118    ui_id: YogStr,
3119    _layout_json: YogStr,
3120    ud: *mut c_void,
3121    h: yog_abi::YogUIEventFn,
3122) {
3123    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3124    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3125    let id = unsafe { ui_id.as_str().to_owned() };
3126    handlers
3127        .ui_handlers
3128        .insert(id.clone(), (current_registration(), ud, h));
3129    yog_logging::info!("registered UI handler: {}", id);
3130}
3131
3132unsafe extern "C" fn api_on_ui_render(
3133    ctx: *mut c_void,
3134    ui_id: YogStr,
3135    ud: *mut c_void,
3136    h: YogHudRenderFn,
3137) {
3138    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3139    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3140    let id = unsafe { ui_id.as_str().to_owned() };
3141    handlers
3142        .ui_render_handlers
3143        .entry(id)
3144        .or_default()
3145        .push((current_registration(), ud, h));
3146}
3147
3148/// Strip TSV separators so one mod can't corrupt the line format.
3149fn tsv_clean(v: &str) -> String {
3150    v.replace(['\t', '\n', '\r'], " ")
3151}
3152
3153unsafe extern "C" fn api_ui_open(_ctx: *mut c_void, ui_id: YogStr, modal: bool, pause: bool) {
3154    let id = ui_id.as_str().to_string();
3155    if id.is_empty() {
3156        return;
3157    }
3158    let Some(mut env) = get_env() else { return };
3159    let Ok(jid) = env.new_string(&id) else { return };
3160    let jid_obj: JObject = jid.into();
3161    // Java side schedules onto the render thread; no-op on dedicated servers.
3162    if env
3163        .call_static_method(
3164            "dev/yog/NativeBridge",
3165            "openUI",
3166            "(Ljava/lang/String;ZZ)V",
3167            &[
3168                JValue::Object(&jid_obj),
3169                JValue::Bool(modal as u8),
3170                JValue::Bool(pause as u8),
3171            ],
3172        )
3173        .is_err()
3174    {
3175        env.exception_clear().ok();
3176    }
3177}
3178
3179unsafe extern "C" fn api_ui_close(_ctx: *mut c_void, ui_id: YogStr) {
3180    let id = ui_id.as_str().to_string();
3181    let Some(mut env) = get_env() else { return };
3182    let Ok(jid) = env.new_string(&id) else { return };
3183    let jid_obj: JObject = jid.into();
3184    // Java side defers onto the render thread (after the current event) and
3185    // checks the open screen is that Yog UI; no-op on dedicated servers.
3186    if env
3187        .call_static_method(
3188            "dev/yog/NativeBridge",
3189            "closeUI",
3190            "(Ljava/lang/String;)V",
3191            &[JValue::Object(&jid_obj)],
3192        )
3193        .is_err()
3194    {
3195        env.exception_clear().ok();
3196    }
3197}
3198
3199unsafe extern "C" fn api_ui_consume_event(_ctx: *mut c_void) {
3200    ui_jni::consume_event();
3201}
3202
3203unsafe extern "C" fn api_translate(_ctx: *mut c_void, key: YogStr) -> YogOwnedStr {
3204    translate(key.as_str()).map_or(YogOwnedStr::NONE, YogOwnedStr::from_string)
3205}
3206
3207/// The game's text for translation `key` in the current language — `None`
3208/// when no lang file has it (or there's no JVM).
3209fn translate(key: &str) -> Option<String> {
3210    if key.is_empty() {
3211        return None;
3212    }
3213    let mut env = get_env()?;
3214    let jkey: JObject = env.new_string(key).ok()?.into();
3215    let result = env.call_static_method(
3216        "dev/yog/NativeBridge",
3217        "translate",
3218        "(Ljava/lang/String;)Ljava/lang/String;",
3219        &[JValue::Object(&jkey)],
3220    );
3221    let text = match result.and_then(|v| v.l()) {
3222        Ok(obj) if !obj.as_raw().is_null() => env.get_string(&obj.into()).ok().map(String::from),
3223        Ok(_) => None,
3224        Err(_) => {
3225            env.exception_clear().ok();
3226            None
3227        }
3228    };
3229    let _ = env.delete_local_ref(jkey);
3230    text
3231}
3232
3233unsafe extern "C" fn api_mods_list(_ctx: *mut c_void) -> YogOwnedStr {
3234    let mut lines: Vec<String> = Vec::new();
3235    let infos = MOD_INFOS.lock().expect("mod infos lock poisoned").clone();
3236    for m in &infos {
3237        // A `.yres` name/description shows in the player's language.
3238        let localized = |text: &str, key: &str| {
3239            translate(key).map_or_else(|| text.to_string(), |t| tsv_clean(&t))
3240        };
3241        lines.push(format!(
3242            "yog\t{}\t{}\t{}\t{}\t{}",
3243            m[0],
3244            localized(&m[1], &m[5]),
3245            m[2],
3246            m[3],
3247            localized(&m[4], &m[6])
3248        ));
3249    }
3250    // Loader-side (Java) mods, if the host provides them.
3251    if let Some(mut env) = get_env() {
3252        if let Ok(val) = env.call_static_method(
3253            "dev/yog/NativeBridge",
3254            "listPlatformMods",
3255            "()Ljava/lang/String;",
3256            &[],
3257        ) {
3258            if let Ok(obj) = val.l() {
3259                if !obj.as_raw().is_null() {
3260                    if let Ok(js) = env.get_string(&obj.into()) {
3261                        for line in String::from(js).lines() {
3262                            if !line.trim().is_empty() {
3263                                lines.push(format!("platform\t{line}"));
3264                            }
3265                        }
3266                    }
3267                }
3268            }
3269        } else {
3270            env.exception_clear().ok();
3271        }
3272    }
3273    YogOwnedStr::from_string(lines.join("\n"))
3274}
3275
3276unsafe extern "C" fn api_register_menu_entry(ctx: *mut c_void, label: YogStr, ui_id: YogStr) {
3277    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3278    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3279    let l = unsafe { label.as_str().to_owned() };
3280    let u = unsafe { ui_id.as_str().to_owned() };
3281    handlers.menu_entries.push((l, u));
3282}
3283
3284#[no_mangle]
3285pub extern "system" fn Java_dev_yog_NativeBridge_nativeBookJson<'l>(
3286    mut env: JNIEnv<'l>,
3287    _class: JClass<'l>,
3288    book_id: JString<'l>,
3289) -> jstring {
3290    let id = match env.get_string(&book_id) {
3291        Ok(s) => String::from(s),
3292        Err(_) => return std::ptr::null_mut(),
3293    };
3294    let json = handlers()
3295        .books
3296        .get(&id)
3297        .cloned()
3298        .unwrap_or_else(|| "null".to_string());
3299    env.new_string(json)
3300        .map(|s| s.into_raw())
3301        .unwrap_or(std::ptr::null_mut())
3302}
3303
3304// ── World queries & effects (ABI minor 1) ────────────────────────────────────
3305//
3306// Each of these forwards to a `NativeBridge` static of the same shape; the JNI
3307// signature is derived from the argument list so the two cannot drift apart.
3308
3309#[derive(Clone, Copy)]
3310enum JArg {
3311    S(YogStr),
3312    D(f64),
3313    F(f32),
3314    I(i32),
3315    Z(bool),
3316}
3317
3318/// JNI method descriptor for `args`, returning `ret` (`"Z"` or a String).
3319fn bridge_sig(args: &[JArg], ret: &str) -> String {
3320    let mut sig = String::from("(");
3321    for a in args {
3322        sig.push_str(match a {
3323            JArg::S(_) => "Ljava/lang/String;",
3324            JArg::D(_) => "D",
3325            JArg::F(_) => "F",
3326            JArg::I(_) => "I",
3327            JArg::Z(_) => "Z",
3328        });
3329    }
3330    sig.push(')');
3331    sig.push_str(ret);
3332    sig
3333}
3334
3335/// Call `NativeBridge.<name>(args)`; `None` if the JVM is unavailable or the
3336/// call threw (the exception is cleared).
3337unsafe fn bridge_call<'l>(
3338    env: &mut JNIEnv<'l>,
3339    name: &str,
3340    args: &[JArg],
3341    ret: &str,
3342) -> Option<jni::objects::JValueOwned<'l>> {
3343    let mut strs = Vec::new();
3344    for a in args {
3345        if let JArg::S(s) = a {
3346            strs.push(ys_to_java(env, *s)?);
3347        }
3348    }
3349    let mut next_str = strs.iter();
3350    let mut vals: Vec<JValue> = Vec::with_capacity(args.len());
3351    for a in args {
3352        vals.push(match *a {
3353            JArg::S(_) => JValue::Object(next_str.next()?),
3354            JArg::D(d) => JValue::Double(d),
3355            JArg::F(f) => JValue::Float(f),
3356            JArg::I(i) => JValue::Int(i),
3357            JArg::Z(z) => JValue::Bool(z as u8),
3358        });
3359    }
3360    let sig = bridge_sig(args, ret);
3361    match env.call_static_method("dev/yog/NativeBridge", name, &sig, &vals) {
3362        Ok(v) => Some(v),
3363        Err(_) => {
3364            let _ = env.exception_clear();
3365            None
3366        }
3367    }
3368}
3369
3370unsafe fn bridge_bool(name: &str, args: &[JArg]) -> bool {
3371    let Some(mut env) = get_env() else {
3372        return false;
3373    };
3374    bridge_call(&mut env, name, args, "Z")
3375        .and_then(|v| v.z().ok())
3376        .unwrap_or(false)
3377}
3378
3379unsafe fn bridge_str(name: &str, args: &[JArg]) -> YogOwnedStr {
3380    let Some(mut env) = get_env() else {
3381        return YogOwnedStr::NONE;
3382    };
3383    match bridge_call(&mut env, name, args, "Ljava/lang/String;").and_then(|v| v.l().ok()) {
3384        Some(obj) => jstring_to_owned(&mut env, obj),
3385        None => YogOwnedStr::NONE,
3386    }
3387}
3388
3389fn vec_args(v: YogVec3) -> [JArg; 3] {
3390    [JArg::D(v.x), JArg::D(v.y), JArg::D(v.z)]
3391}
3392
3393fn pos_args(p: YogBlockPos) -> [JArg; 3] {
3394    [JArg::I(p.x), JArg::I(p.y), JArg::I(p.z)]
3395}
3396
3397unsafe extern "C" fn srv_entity_info(_ctx: *mut c_void, uuid: YogStr) -> YogOwnedStr {
3398    bridge_str("entityInfo", &[JArg::S(uuid)])
3399}
3400
3401unsafe extern "C" fn srv_entities_in_box(
3402    _ctx: *mut c_void,
3403    dim: YogStr,
3404    min: YogVec3,
3405    max: YogVec3,
3406) -> YogOwnedStr {
3407    let [a, b, c] = vec_args(min);
3408    let [d, e, f] = vec_args(max);
3409    bridge_str("entitiesInBox", &[JArg::S(dim), a, b, c, d, e, f])
3410}
3411
3412unsafe extern "C" fn srv_raycast_block(
3413    _ctx: *mut c_void,
3414    dim: YogStr,
3415    from: YogVec3,
3416    to: YogVec3,
3417) -> YogOwnedStr {
3418    let [a, b, c] = vec_args(from);
3419    let [d, e, f] = vec_args(to);
3420    bridge_str("raycastBlock", &[JArg::S(dim), a, b, c, d, e, f])
3421}
3422
3423unsafe extern "C" fn srv_raycast_entity(
3424    _ctx: *mut c_void,
3425    dim: YogStr,
3426    from: YogVec3,
3427    to: YogVec3,
3428    exclude: YogStr,
3429) -> YogOwnedStr {
3430    let [a, b, c] = vec_args(from);
3431    let [d, e, f] = vec_args(to);
3432    bridge_str(
3433        "raycastEntity",
3434        &[JArg::S(dim), a, b, c, d, e, f, JArg::S(exclude)],
3435    )
3436}
3437
3438unsafe extern "C" fn srv_block_info(
3439    _ctx: *mut c_void,
3440    dim: YogStr,
3441    pos: YogBlockPos,
3442) -> YogOwnedStr {
3443    let [x, y, z] = pos_args(pos);
3444    bridge_str("blockInfo", &[JArg::S(dim), x, y, z])
3445}
3446
3447unsafe extern "C" fn srv_break_block(
3448    _ctx: *mut c_void,
3449    dim: YogStr,
3450    pos: YogBlockPos,
3451    drop: bool,
3452    breaker: YogStr,
3453) -> bool {
3454    let [x, y, z] = pos_args(pos);
3455    bridge_bool(
3456        "breakBlock",
3457        &[JArg::S(dim), x, y, z, JArg::Z(drop), JArg::S(breaker)],
3458    )
3459}
3460
3461unsafe extern "C" fn srv_place_block_from_slot(
3462    _ctx: *mut c_void,
3463    player: YogStr,
3464    slot: u32,
3465    dim: YogStr,
3466    pos: YogBlockPos,
3467) -> bool {
3468    let [x, y, z] = pos_args(pos);
3469    bridge_bool(
3470        "placeBlockFromSlot",
3471        &[JArg::S(player), JArg::I(slot as i32), JArg::S(dim), x, y, z],
3472    )
3473}
3474
3475unsafe extern "C" fn srv_bonemeal(_ctx: *mut c_void, dim: YogStr, pos: YogBlockPos) -> bool {
3476    let [x, y, z] = pos_args(pos);
3477    bridge_bool("bonemeal", &[JArg::S(dim), x, y, z])
3478}
3479
3480unsafe extern "C" fn srv_explode(
3481    _ctx: *mut c_void,
3482    dim: YogStr,
3483    pos: YogVec3,
3484    power: f32,
3485    fire: bool,
3486    source: YogStr,
3487) -> bool {
3488    let [x, y, z] = vec_args(pos);
3489    bridge_bool(
3490        "explode",
3491        &[
3492            JArg::S(dim),
3493            x,
3494            y,
3495            z,
3496            JArg::F(power),
3497            JArg::Z(fire),
3498            JArg::S(source),
3499        ],
3500    )
3501}
3502
3503unsafe extern "C" fn srv_tellraw(_ctx: *mut c_void, player: YogStr, json: YogStr) -> bool {
3504    bridge_bool("tellraw", &[JArg::S(player), JArg::S(json)])
3505}
3506
3507unsafe extern "C" fn srv_entity_damage(
3508    _ctx: *mut c_void,
3509    uuid: YogStr,
3510    amount: f32,
3511    damage_type: YogStr,
3512    attacker: YogStr,
3513) -> bool {
3514    bridge_bool(
3515        "entityDamage",
3516        &[
3517            JArg::S(uuid),
3518            JArg::F(amount),
3519            JArg::S(damage_type),
3520            JArg::S(attacker),
3521        ],
3522    )
3523}
3524
3525unsafe extern "C" fn srv_entity_set_fire_ticks(
3526    _ctx: *mut c_void,
3527    uuid: YogStr,
3528    ticks: i32,
3529) -> bool {
3530    bridge_bool("entitySetFireTicks", &[JArg::S(uuid), JArg::I(ticks)])
3531}
3532
3533unsafe extern "C" fn srv_player_add_xp(_ctx: *mut c_void, player: YogStr, amount: i32) -> bool {
3534    bridge_bool("playerAddXp", &[JArg::S(player), JArg::I(amount)])
3535}
3536
3537unsafe extern "C" fn srv_player_set_may_fly(
3538    _ctx: *mut c_void,
3539    player: YogStr,
3540    may_fly: bool,
3541) -> bool {
3542    bridge_bool("playerSetMayFly", &[JArg::S(player), JArg::Z(may_fly)])
3543}
3544
3545unsafe extern "C" fn srv_player_info(_ctx: *mut c_void, player: YogStr) -> YogOwnedStr {
3546    bridge_str("playerInfo", &[JArg::S(player)])
3547}
3548
3549unsafe extern "C" fn srv_spawn_item(
3550    _ctx: *mut c_void,
3551    dim: YogStr,
3552    pos: YogVec3,
3553    vel: YogVec3,
3554    item_id: YogStr,
3555    count: u32,
3556    snbt: YogStr,
3557) -> YogOwnedStr {
3558    let [a, b, c] = vec_args(pos);
3559    let [d, e, f] = vec_args(vel);
3560    bridge_str(
3561        "spawnItem",
3562        &[
3563            JArg::S(dim),
3564            a,
3565            b,
3566            c,
3567            d,
3568            e,
3569            f,
3570            JArg::S(item_id),
3571            JArg::I(count as i32),
3572            JArg::S(snbt),
3573        ],
3574    )
3575}
3576
3577unsafe extern "C" fn srv_item_entity_stack(_ctx: *mut c_void, uuid: YogStr) -> YogOwnedStr {
3578    bridge_str("itemEntityStack", &[JArg::S(uuid)])
3579}
3580
3581unsafe extern "C" fn srv_actionbar_json(_ctx: *mut c_void, player: YogStr, json: YogStr) -> bool {
3582    bridge_bool("actionbarJson", &[JArg::S(player), JArg::S(json)])
3583}
3584
3585unsafe extern "C" fn srv_use_item_on_block(
3586    _ctx: *mut c_void,
3587    dim: YogStr,
3588    pos: YogBlockPos,
3589    face: u8,
3590    item_id: YogStr,
3591    player: YogStr,
3592) -> bool {
3593    let [x, y, z] = pos_args(pos);
3594    bridge_bool(
3595        "useItemOnBlock",
3596        &[
3597            JArg::S(dim),
3598            x,
3599            y,
3600            z,
3601            JArg::I(face as i32),
3602            JArg::S(item_id),
3603            JArg::S(player),
3604        ],
3605    )
3606}
3607
3608unsafe extern "C" fn srv_pour_fluid(
3609    _ctx: *mut c_void,
3610    dim: YogStr,
3611    pos: YogBlockPos,
3612    bucket_item_id: YogStr,
3613) -> bool {
3614    let [x, y, z] = pos_args(pos);
3615    bridge_bool(
3616        "pourFluid",
3617        &[JArg::S(dim), x, y, z, JArg::S(bucket_item_id)],
3618    )
3619}
3620
3621unsafe extern "C" fn srv_has_entity_tag(
3622    _ctx: *mut c_void,
3623    entity_type: YogStr,
3624    tag: YogStr,
3625) -> bool {
3626    bridge_bool("hasEntityTag", &[JArg::S(entity_type), JArg::S(tag)])
3627}
3628
3629unsafe extern "C" fn srv_item_block(_ctx: *mut c_void, item_id: YogStr) -> YogOwnedStr {
3630    bridge_str("itemBlock", &[JArg::S(item_id)])
3631}
3632
3633unsafe extern "C" fn srv_place_feature(
3634    _ctx: *mut c_void,
3635    dim: YogStr,
3636    pos: YogBlockPos,
3637    feature_id: YogStr,
3638) -> bool {
3639    let [x, y, z] = pos_args(pos);
3640    bridge_bool(
3641        "placeFeature",
3642        &[JArg::S(dim), x, y, z, JArg::S(feature_id)],
3643    )
3644}
3645
3646unsafe extern "C" fn srv_item_entity_set_stack(
3647    _ctx: *mut c_void,
3648    uuid: YogStr,
3649    item_id: YogStr,
3650    count: u32,
3651    snbt: YogStr,
3652) -> bool {
3653    bridge_bool(
3654        "itemEntitySetStack",
3655        &[
3656            JArg::S(uuid),
3657            JArg::S(item_id),
3658            JArg::I(count as i32),
3659            JArg::S(snbt),
3660        ],
3661    )
3662}
3663
3664// ── Table constructors ────────────────────────────────────────────────────────
3665
3666fn build_server_table() -> YogServer {
3667    YogServer {
3668        ctx: std::ptr::null_mut(),
3669        abi_version: ABI_VERSION,
3670        size: std::mem::size_of::<YogServer>() as u32,
3671        free_str: yog_free_str,
3672        broadcast: srv_broadcast,
3673        get_block: srv_get_block,
3674        set_block: srv_set_block,
3675        world_time: srv_world_time,
3676        set_time: srv_set_time,
3677        is_raining: srv_is_raining,
3678        set_weather: srv_set_weather,
3679        give_item: srv_give_item,
3680        player_teleport: srv_player_teleport,
3681        send_to_player: srv_send_to_player,
3682        send_to_server: srv_send_to_server,
3683        kick_player: srv_kick_player,
3684        set_gamemode: srv_set_gamemode,
3685        send_title: srv_send_title,
3686        send_actionbar: srv_send_actionbar,
3687        play_sound: srv_play_sound,
3688        play_sound_player: srv_play_sound_player,
3689        entity_teleport: srv_entity_teleport,
3690        entity_position: srv_entity_position,
3691        entity_rotation: srv_entity_rotation,
3692        entity_health: srv_entity_health,
3693        entity_set_health: srv_entity_set_health,
3694        entity_kill: srv_entity_kill,
3695        spawn_entity: srv_spawn_entity,
3696        entity_add_effect: srv_entity_add_effect,
3697        entity_remove_effect: srv_entity_remove_effect,
3698        entity_clear_effects: srv_entity_clear_effects,
3699        entity_velocity: srv_entity_velocity,
3700        entity_set_velocity: srv_entity_set_velocity,
3701        entity_add_velocity: srv_entity_add_velocity,
3702        has_item_tag: srv_has_item_tag,
3703        has_block_tag: srv_has_block_tag,
3704        drop_loot: srv_drop_loot,
3705        scoreboard_get: srv_scoreboard_get,
3706        scoreboard_set: srv_scoreboard_set,
3707        scoreboard_add: srv_scoreboard_add,
3708        bossbar_create: srv_bossbar_create,
3709        bossbar_remove: srv_bossbar_remove,
3710        bossbar_set_title: srv_bossbar_set_title,
3711        bossbar_set_progress: srv_bossbar_set_progress,
3712        bossbar_set_color: srv_bossbar_set_color,
3713        bossbar_add_player: srv_bossbar_add_player,
3714        bossbar_remove_player: srv_bossbar_remove_player,
3715        bossbar_set_visible: srv_bossbar_set_visible,
3716        game_dir: srv_game_dir,
3717        get_block_nbt: srv_get_block_nbt,
3718        set_block_nbt: srv_set_block_nbt,
3719        get_inventory_slot: srv_get_inventory_slot,
3720        set_inventory_slot: srv_set_inventory_slot,
3721        player_inventory: srv_player_inventory,
3722        player_set_slot: srv_player_set_slot,
3723        player_teleport_dim: srv_player_teleport_dim,
3724        entity_teleport_dim: srv_entity_teleport_dim,
3725        online_players: srv_online_players,
3726        world_entity_count: srv_world_entity_count,
3727        entity_get_nbt: srv_entity_get_nbt,
3728        entity_set_nbt: srv_entity_set_nbt,
3729        spawn_particles: srv_spawn_particles,
3730        entity_attribute_get: srv_entity_attribute_get,
3731        entity_attribute_set: srv_entity_attribute_set,
3732        get_held_item_nbt: srv_get_held_item_nbt,
3733        set_held_item_nbt: srv_set_held_item_nbt,
3734        get_offhand_item_nbt: srv_get_offhand_item_nbt,
3735        set_offhand_item_nbt: srv_set_offhand_item_nbt,
3736        get_slot_item: srv_get_slot_item,
3737        set_slot_item: srv_set_slot_item,
3738        entity_info: srv_entity_info,
3739        entities_in_box: srv_entities_in_box,
3740        raycast_block: srv_raycast_block,
3741        raycast_entity: srv_raycast_entity,
3742        block_info: srv_block_info,
3743        break_block: srv_break_block,
3744        place_block_from_slot: srv_place_block_from_slot,
3745        bonemeal: srv_bonemeal,
3746        explode: srv_explode,
3747        tellraw: srv_tellraw,
3748        entity_damage: srv_entity_damage,
3749        entity_set_fire_ticks: srv_entity_set_fire_ticks,
3750        player_add_xp: srv_player_add_xp,
3751        player_set_may_fly: srv_player_set_may_fly,
3752        player_info: srv_player_info,
3753        spawn_item: srv_spawn_item,
3754        item_entity_stack: srv_item_entity_stack,
3755        item_entity_set_stack: srv_item_entity_set_stack,
3756        actionbar_json: srv_actionbar_json,
3757        use_item_on_block: srv_use_item_on_block,
3758        pour_fluid: srv_pour_fluid,
3759        has_entity_tag: srv_has_entity_tag,
3760        item_block: srv_item_block,
3761        place_feature: srv_place_feature,
3762    }
3763}
3764
3765// ── Inter-mod communication ──────────────────────────────────────────────────
3766
3767unsafe extern "C" fn interop_export_impl(
3768    _ctx: *mut c_void,
3769    mod_id: YogStr,
3770    symbol: YogStr,
3771    ptr: *const c_void,
3772) {
3773    let mod_id = mod_id.as_str();
3774    let sym = symbol.as_str();
3775    let registry = INTEROP_SYMBOLS.get_or_init(|| Mutex::new(HashMap::new()));
3776    registry
3777        .lock()
3778        .expect("interop symbols lock poisoned")
3779        .entry(mod_id.to_string())
3780        .or_default()
3781        .insert(sym.to_string(), ptr as usize);
3782}
3783
3784unsafe extern "C" fn interop_import_impl(
3785    _ctx: *mut c_void,
3786    mod_id: YogStr,
3787    symbol: YogStr,
3788) -> *const c_void {
3789    let mod_id = mod_id.as_str();
3790    let sym = symbol.as_str();
3791    let registry = INTEROP_SYMBOLS.get_or_init(|| Mutex::new(HashMap::new()));
3792    registry
3793        .lock()
3794        .expect("interop symbols lock poisoned")
3795        .get(mod_id)
3796        .and_then(|m: &HashMap<String, usize>| m.get(sym))
3797        .map(|&ptr| ptr as *const c_void)
3798        .unwrap_or(std::ptr::null())
3799}
3800
3801fn build_api_table(ctx: *const RwLock<RuntimeHandlers>, server: *const YogServer) -> YogApi {
3802    YogApi {
3803        abi_version: ABI_VERSION,
3804        size: std::mem::size_of::<YogApi>() as u32,
3805        ctx: ctx as *mut c_void,
3806        server,
3807        on_block_break: api_on_block_break,
3808        on_chat: api_on_chat,
3809        on_player_join: api_on_player_join,
3810        on_player_leave: api_on_player_leave,
3811        on_use_item: api_on_use_item,
3812        on_use_block: api_on_use_block,
3813        on_attack_entity: api_on_attack_entity,
3814        on_entity_damage: api_on_entity_damage,
3815        on_entity_death: api_on_entity_death,
3816        on_entity_spawn: api_on_entity_spawn,
3817        on_player_place_block: api_on_player_place_block,
3818        on_player_death: api_on_player_death,
3819        on_player_respawn: api_on_player_respawn,
3820        on_advancement: api_on_advancement,
3821        on_entity_interact: api_on_entity_interact,
3822        on_item_craft: api_on_item_craft,
3823        on_explosion: api_on_explosion,
3824        on_item_pickup: api_on_item_pickup,
3825        on_player_move: api_on_player_move,
3826        on_container_open: api_on_container_open,
3827        on_container_close: api_on_container_close,
3828        on_projectile_hit: api_on_projectile_hit,
3829        on_server_tick: api_on_server_tick,
3830        on_server_started: api_on_server_started,
3831        on_server_stopping: api_on_server_stopping,
3832        on_packet: api_on_packet,
3833        on_client_packet: api_on_client_packet,
3834        register_command: api_register_command,
3835        register_typed_command: api_register_typed_command,
3836        register_recipe_json: api_register_recipe_json,
3837        register_item: api_register_item,
3838        register_block: api_register_block,
3839        schedule_once: api_schedule_once,
3840        schedule_repeating: api_schedule_repeating,
3841        on_client_tick: api_on_client_tick,
3842        on_hud_render: api_on_hud_render,
3843        on_key_press: api_on_key_press,
3844        on_screen_open: api_on_screen_open,
3845        on_screen_close: api_on_screen_close,
3846        on_world_render: api_on_world_render,
3847        register_startup_grant: api_register_startup_grant,
3848        register_book: api_register_book,
3849        register_ui: api_register_ui,
3850        on_ui_render: api_on_ui_render,
3851        register_menu_entry: api_register_menu_entry,
3852        mods_list: api_mods_list,
3853        free_str: yog_free_str,
3854        ui_open: api_ui_open,
3855        register_inventory: api_register_inventory,
3856        interop_export: interop_export_impl,
3857        interop_import: interop_import_impl,
3858        register_dimension_json: api_register_dimension_json,
3859        register_chunk_generator: api_register_chunk_generator,
3860        ui_close: api_ui_close,
3861        ui_consume_event: api_ui_consume_event,
3862        translate: api_translate,
3863        ui_open_flags: client_api::api_ui_open_flags,
3864        client_play_sound: client_api::api_client_play_sound,
3865        client_stop_sound: client_api::api_client_stop_sound,
3866        client_held_item: client_api::api_client_held_item,
3867        client_key_down: client_api::api_client_key_down,
3868    }
3869}
3870
3871// ── Mod loading ───────────────────────────────────────────────────────────────
3872
3873fn platform_tag() -> String {
3874    format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH)
3875}
3876
3877type AbiVersionFn = unsafe extern "C" fn() -> u32;
3878/// Second arg is a null-terminated C string: the mod's `id` from its manifest.
3879type RegisterFn = unsafe extern "C" fn(*const YogApi, *const std::os::raw::c_char);
3880
3881fn load_mods(dir: &Path, api: &YogApi) {
3882    let entries = match std::fs::read_dir(dir) {
3883        Ok(e) => e,
3884        Err(_) => {
3885            yog_logging::info!("no mods directory at {} — none loaded", dir.display());
3886            return;
3887        }
3888    };
3889
3890    // First pass: collect (mod_id, dependencies, archive_path)
3891    struct ModMeta {
3892        id: String,
3893        deps: Vec<String>,
3894        yog_path: PathBuf,
3895    }
3896    let mut metas: Vec<ModMeta> = Vec::new();
3897    for entry in entries.flatten() {
3898        let path = entry.path();
3899        if path.extension().and_then(|e| e.to_str()) != Some("yog") {
3900            continue;
3901        }
3902        let info = read_mod_info(&path);
3903        let deps = read_mod_deps(&path);
3904        metas.push(ModMeta {
3905            id: info[0].clone(),
3906            deps,
3907            yog_path: path,
3908        });
3909    }
3910
3911    // Topological sort by dependencies (Kahn's algorithm)
3912    let ids: Vec<String> = metas.iter().map(|m| m.id.clone()).collect();
3913    let deps_list: Vec<Vec<String>> = metas.iter().map(|m| m.deps.clone()).collect();
3914    let sorted = match topo_sort_mods(&ids, &deps_list) {
3915        Some(v) => v,
3916        None => {
3917            yog_logging::error!("circular dependency detected — loading in file order");
3918            (0..metas.len()).collect()
3919        }
3920    };
3921
3922    let mut loaded: Vec<LoadedModule> = Vec::new();
3923    for idx in sorted {
3924        let meta = &metas[idx];
3925        let lib_path = match extract_yog(&meta.yog_path) {
3926            Some(p) => p,
3927            None => {
3928                yog_logging::error!(
3929                    "no native for {} in {}",
3930                    platform_tag(),
3931                    meta.yog_path.display()
3932                );
3933                continue;
3934            }
3935        };
3936        if let Some(module) = load_mod_lib(&lib_path, api, &meta.id) {
3937            loaded.push(module);
3938            MOD_INFOS
3939                .lock()
3940                .expect("mod infos lock poisoned")
3941                .push(read_mod_info(&meta.yog_path));
3942        }
3943    }
3944    yog_logging::info!("loaded {} mod(s) from {}", loaded.len(), dir.display());
3945
3946    // Final import resolution pass — after all mods loaded, each mod's pending
3947    // imports can be resolved against the now-complete interop table.
3948    resolve_all_imports(api, &loaded);
3949}
3950
3951/// After all mods loaded, call `__yog_resolve_imports_final` on each library
3952/// to resolve any imports that weren't satisfied during initial registration.
3953fn resolve_all_imports(api: &YogApi, loaded: &[LoadedModule]) {
3954    for module in loaded {
3955        module.with_library(|lib| unsafe {
3956            type ResolveFn = unsafe extern "C" fn(*const YogApi);
3957            if let Ok(resolve) = lib.get::<ResolveFn>(b"__yog_resolve_imports_final") {
3958                resolve(api as *const YogApi);
3959            }
3960        });
3961    }
3962}
3963
3964/// Kahn's algorithm — returns indices in dependency order, or None on cycle.
3965fn topo_sort_mods(ids: &[String], deps_list: &[Vec<String>]) -> Option<Vec<usize>> {
3966    let n = ids.len();
3967    let name_to_idx: HashMap<&str, usize> = ids
3968        .iter()
3969        .enumerate()
3970        .map(|(i, id)| (id.as_str(), i))
3971        .collect();
3972    let mut in_degree = vec![0u32; n];
3973    let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];
3974    for (i, deps) in deps_list.iter().enumerate() {
3975        for dep in deps {
3976            if let Some(&j) = name_to_idx.get(dep.as_str()) {
3977                adj[j].push(i);
3978                in_degree[i] += 1;
3979            }
3980        }
3981    }
3982    let mut queue: Vec<usize> = (0..n).filter(|&i| in_degree[i] == 0).collect();
3983    let mut order = Vec::with_capacity(n);
3984    while let Some(u) = queue.pop() {
3985        order.push(u);
3986        for &v in &adj[u] {
3987            in_degree[v] -= 1;
3988            if in_degree[v] == 0 {
3989                queue.push(v);
3990            }
3991        }
3992    }
3993    if order.len() == n {
3994        Some(order)
3995    } else {
3996        None
3997    }
3998}
3999
4000/// Loads `path` as a fresh generation of `mod_id` via the shared
4001/// `HotReloader`, validates its ABI, and calls its `yog_mod_register` —
4002/// tagging every handler it registers with the returned `LoadedModule` (see
4003/// `current_registration()`). On any failure the module (if it got as far
4004/// as being tracked by the `HotReloader`) is retired immediately: nothing
4005/// can be executing inside a library that never successfully registered,
4006/// so this always hard-unloads right away rather than lingering.
4007fn load_mod_lib(path: &Path, api: &YogApi, mod_id: &str) -> Option<LoadedModule> {
4008    let module = match unsafe { hot_reloader().load_initial(mod_id, path) } {
4009        Ok(m) => m,
4010        Err(e) => {
4011            yog_logging::error!("failed to load {}: {}", path.display(), e);
4012            return None;
4013        }
4014    };
4015
4016    let abi = module.with_library(|lib| unsafe {
4017        let abi: Symbol<AbiVersionFn> = lib.get(b"yog_abi_version").ok()?;
4018        Some(abi())
4019    });
4020    match abi.flatten() {
4021        Some(v) if v == ABI_VERSION => {}
4022        Some(v) => {
4023            yog_logging::error!(
4024                "{}: ABI {} incompatible with runtime ABI {}",
4025                path.display(),
4026                v,
4027                ABI_VERSION
4028            );
4029            module.retire(|| {});
4030            return None;
4031        }
4032        None => {
4033            yog_logging::error!("{} is not a Yog mod (no yog_abi_version)", path.display());
4034            module.retire(|| {});
4035            return None;
4036        }
4037    }
4038
4039    if let Err(e) = invoke_mod_register(&module, api, mod_id) {
4040        yog_logging::error!("{}: {}", path.display(), e);
4041        module.retire(|| {});
4042        return None;
4043    }
4044
4045    Some(module)
4046}
4047
4048/// Calls a loaded module's `yog_mod_register`, tagging everything it
4049/// registers with `module` via `CURRENT_REGISTRATION` for the duration of
4050/// the call — used for both a mod's initial load and a later hot-reload.
4051fn invoke_mod_register(module: &LoadedModule, api: &YogApi, mod_id: &str) -> Result<(), String> {
4052    module
4053        .with_library(|lib| unsafe {
4054            let register: Symbol<RegisterFn> = lib
4055                .get(b"yog_mod_register")
4056                .map_err(|_| "missing yog_mod_register".to_string())?;
4057            let mod_id_c = std::ffi::CString::new(mod_id).unwrap();
4058            *CURRENT_REGISTRATION.lock().unwrap() = Some(module.clone());
4059            register(api as *const YogApi, mod_id_c.as_ptr());
4060            *CURRENT_REGISTRATION.lock().unwrap() = None;
4061            Ok(())
4062        })
4063        .unwrap_or_else(|| Err("module was unloaded before registration could run".to_string()))
4064}
4065
4066/// Metadata for a mod file: [id, name, version, authors, description,
4067/// name_key, description_key].
4068/// For .yog archives this comes from the bundled yog.toml; bare native libs
4069/// fall back to the file stem.
4070fn read_mod_info(path: &Path) -> [String; 7] {
4071    let stem = path
4072        .file_stem()
4073        .map(|s| s.to_string_lossy().into_owned())
4074        .unwrap_or_default();
4075    let mut info = [
4076        stem.clone(),
4077        stem,
4078        String::new(),
4079        String::new(),
4080        String::new(),
4081        String::new(),
4082        String::new(),
4083    ];
4084    if path.extension().and_then(|e| e.to_str()) != Some("yog") {
4085        return info;
4086    }
4087    let Some(text) = (|| {
4088        let file = std::fs::File::open(path).ok()?;
4089        let mut archive = zip::ZipArchive::new(file).ok()?;
4090        let mut entry = archive.by_name("yog.toml").ok()?;
4091        let mut text = String::new();
4092        std::io::Read::read_to_string(&mut entry, &mut text).ok()?;
4093        Some(text)
4094    })() else {
4095        return info;
4096    };
4097    // Minimal parse — enough for id/name/version/description/authors without
4098    // pulling in a TOML dependency. Source manifests keep these under [mod];
4099    // the packaged manifest (written by yog-cli) has them at top level, so
4100    // keys before any section header count too.
4101    let mut in_mod = true;
4102    for line in text.lines() {
4103        let line = line.trim();
4104        if line.starts_with('[') {
4105            in_mod = line == "[mod]";
4106            continue;
4107        }
4108        if !in_mod {
4109            continue;
4110        }
4111        let Some((key, value)) = line.split_once('=') else {
4112            continue;
4113        };
4114        let key = key.trim();
4115        let value = value.trim();
4116        let unquote = |v: &str| v.trim().trim_matches('"').to_string();
4117        match key {
4118            "id" => info[0] = tsv_clean(&unquote(value)),
4119            "name" => info[1] = tsv_clean(&unquote(value)),
4120            "version" => info[2] = tsv_clean(&unquote(value)),
4121            "description" => info[4] = tsv_clean(&unquote(value)),
4122            "name_key" => info[5] = unquote(value),
4123            "description_key" => info[6] = unquote(value),
4124            "authors" => {
4125                let list = value.trim_start_matches('[').trim_end_matches(']');
4126                let authors: Vec<String> = list
4127                    .split(',')
4128                    .map(unquote)
4129                    .filter(|a| !a.is_empty())
4130                    .collect();
4131                info[3] = tsv_clean(&authors.join(", "));
4132            }
4133            _ => {}
4134        }
4135    }
4136    info
4137}
4138
4139/// Parse `[dependencies]` section from yog.toml inside a .yog archive.
4140fn read_mod_deps(path: &Path) -> Vec<String> {
4141    if path.extension().and_then(|e| e.to_str()) != Some("yog") {
4142        return Vec::new();
4143    }
4144    let text = (|| {
4145        let file = std::fs::File::open(path).ok()?;
4146        let mut archive = zip::ZipArchive::new(file).ok()?;
4147        let mut entry = archive.by_name("yog.toml").ok()?;
4148        let mut text = String::new();
4149        std::io::Read::read_to_string(&mut entry, &mut text).ok()?;
4150        Some(text)
4151    })();
4152    let Some(text) = text else { return Vec::new() };
4153    let mut deps = Vec::new();
4154    let mut in_deps = false;
4155    for line in text.lines() {
4156        let line = line.trim();
4157        if line.starts_with('[') {
4158            in_deps = line == "[dependencies]";
4159            continue;
4160        }
4161        if !in_deps {
4162            continue;
4163        }
4164        // `mod_id = "1.0"` or `mod_id = "*"` — we only care about the key (mod_id)
4165        if let Some((key, _)) = line.split_once('=') {
4166            deps.push(key.trim().to_string());
4167        }
4168    }
4169    deps
4170}
4171
4172fn extract_yog(path: &Path) -> Option<PathBuf> {
4173    let file = std::fs::File::open(path).ok()?;
4174    let mut archive = zip::ZipArchive::new(file).ok()?;
4175    let prefix = format!("natives/{}/", platform_tag());
4176    let mut entry_name = None;
4177    for i in 0..archive.len() {
4178        let f = archive.by_index(i).ok()?;
4179        let name = f.name().ok()?;
4180        if name.starts_with(&prefix) && !name.ends_with('/') {
4181            entry_name = Some(name.to_string());
4182            break;
4183        }
4184    }
4185    let entry_name = entry_name?;
4186    let ext = Path::new(&entry_name)
4187        .extension()
4188        .and_then(|e| e.to_str())
4189        .unwrap_or("bin");
4190    let stem = path.file_stem()?.to_string_lossy().into_owned();
4191    // A fresh name per extraction: a hot reload must never truncate the
4192    // library the game still has mapped, and `dlopen` of an already-loaded
4193    // path would just hand back the old module.
4194    static EXTRACTIONS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
4195    let n = EXTRACTIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4196    let out =
4197        std::env::temp_dir().join(format!("yog-{}-{}-{}.{}", stem, std::process::id(), n, ext));
4198    let mut entry = archive.by_name(&entry_name).ok()?;
4199    let mut out_file = std::fs::File::create(&out).ok()?;
4200    std::io::copy(&mut entry, &mut out_file).ok()?;
4201    Some(out)
4202}
4203
4204// ── Dispatcher helpers ────────────────────────────────────────────────────────
4205
4206fn srv_ptr() -> *const YogServer {
4207    SERVER.get().expect("yog: SERVER not initialised") as *const YogServer
4208}
4209
4210// ── JNI entry points ──────────────────────────────────────────────────────────
4211
4212#[no_mangle]
4213pub extern "system" fn Java_dev_yog_NativeBridge_nativeInit<'l>(
4214    mut env: JNIEnv<'l>,
4215    _class: JClass<'l>,
4216    mods_dir: JString<'l>,
4217) {
4218    if let Ok(vm) = env.get_java_vm() {
4219        let _ = JAVA_VM.set(vm);
4220    }
4221
4222    let dir = env
4223        .get_string(&mods_dir)
4224        .map(String::from)
4225        .unwrap_or_default();
4226
4227    // Build YogServer and store in static (gets a stable address).
4228    let _ = SERVER.set(build_server_table());
4229    let server_ptr = SERVER.get().unwrap() as *const YogServer;
4230
4231    // Publish HANDLERS *before* any mod registers — its address is then
4232    // `'static`-stable for the runtime's entire lifetime, unlike the old
4233    // design (a temporary heap `Box` moved into `HANDLERS` only after
4234    // `nativeInit` returned, silently invalidating the `ctx` pointer any
4235    // later re-registration — e.g. a hot-reload — would have needed).
4236    let handlers_lock = HANDLERS.get_or_init(|| RwLock::new(RuntimeHandlers::new()));
4237    let handlers_ptr = handlers_lock as *const RwLock<RuntimeHandlers>;
4238
4239    let api: &'static YogApi = API_TABLE.get_or_init(|| build_api_table(handlers_ptr, server_ptr));
4240
4241    let _ = HOT_RELOADER.get_or_init(|| HotReloader::new(RuntimeModuleRegistry));
4242
4243    guard("mod loading", || {
4244        load_mods(Path::new(&dir), api);
4245    });
4246
4247    control_socket::start_if_requested();
4248
4249    yog_logging::info!("runtime initialised — the gate is open.");
4250}
4251
4252#[no_mangle]
4253pub extern "system" fn Java_dev_yog_NativeBridge_nativeHotReload<'l>(
4254    mut env: JNIEnv<'l>,
4255    _class: JClass<'l>,
4256    mod_id: JString<'l>,
4257    new_yog_path: JString<'l>,
4258) -> jni::sys::jboolean {
4259    let Ok(mod_id) = env.get_string(&mod_id).map(String::from) else {
4260        return 0;
4261    };
4262    let Ok(yog_path) = env.get_string(&new_yog_path).map(String::from) else {
4263        return 0;
4264    };
4265    let ok = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4266        trigger_hot_reload(&mod_id, Path::new(&yog_path))
4267    }))
4268    .unwrap_or(false);
4269    ok as jni::sys::jboolean
4270}
4271
4272/// Rebuilds and re-registers `mod_id` from a freshly built `.yog` at
4273/// `new_yog_path`: extracts the current platform's native, loads it as a
4274/// new generation via the shared `HotReloader` (which retires the previous
4275/// generation per its hybrid soft/hard-unload policy — hard-unloaded right
4276/// away if nothing's mid-call, deferred otherwise), then calls its
4277/// `yog_mod_register` again so its handlers get tagged under the new
4278/// generation. How this actually gets triggered — a keybind, a file-watch,
4279/// an IDE-driven socket — is a separate, later concern; this only needs to
4280/// work correctly once called.
4281fn trigger_hot_reload(mod_id: &str, new_yog_path: &Path) -> bool {
4282    let Some(native_path) = extract_yog(new_yog_path) else {
4283        yog_logging::error!(
4284            "hot-reload {}: no native for {} in {}",
4285            mod_id,
4286            platform_tag(),
4287            new_yog_path.display()
4288        );
4289        return false;
4290    };
4291
4292    let api = API_TABLE.get().expect("yog: nativeInit not called yet");
4293
4294    let module = match unsafe { hot_reloader().reload(mod_id, &native_path) } {
4295        Ok(m) => m,
4296        Err(e) => {
4297            yog_logging::error!(
4298                "hot-reload {}: failed to load {}: {}",
4299                mod_id,
4300                native_path.display(),
4301                e
4302            );
4303            return false;
4304        }
4305    };
4306
4307    let abi = module.with_library(|lib| unsafe {
4308        let abi: Symbol<AbiVersionFn> = lib.get(b"yog_abi_version").ok()?;
4309        Some(abi())
4310    });
4311    match abi.flatten() {
4312        Some(v) if v == ABI_VERSION => {}
4313        other => {
4314            yog_logging::error!(
4315                "hot-reload {}: ABI {:?} incompatible with runtime ABI {} — mod has no active handlers until a compatible reload succeeds",
4316                mod_id,
4317                other,
4318                ABI_VERSION
4319            );
4320            return false;
4321        }
4322    }
4323
4324    if let Err(e) = invoke_mod_register(&module, api, mod_id) {
4325        yog_logging::error!("hot-reload {}: {}", mod_id, e);
4326        return false;
4327    }
4328
4329    yog_logging::info!("hot-reloaded mod {}", mod_id);
4330    true
4331}
4332
4333#[no_mangle]
4334pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnBlockBreak<'l>(
4335    mut env: JNIEnv<'l>,
4336    _class: JClass<'l>,
4337    player: JString<'l>,
4338    block: JString<'l>,
4339    x: jint,
4340    y: jint,
4341    z: jint,
4342    dimension: JString<'l>,
4343) {
4344    let (p, b, d) = (jstr!(env, player), jstr!(env, block), jstr!(env, dimension));
4345    let ev = yog_abi::YogBlockBreakEvent {
4346        player: YogStr::from_str(&p),
4347        block: YogStr::from_str(&b),
4348        pos: YogBlockPos { x, y, z },
4349        dimension: YogStr::from_str(&d),
4350    };
4351    let srv = srv_ptr();
4352    guard("on_block_break", || {
4353        for (module, ud, f) in &handlers().block_break {
4354            if module.is_retiring() {
4355                continue;
4356            }
4357            let Some(_call) = module.enter() else {
4358                continue;
4359            };
4360            unsafe { f(*ud, srv, &ev, 1) };
4361        }
4362    });
4363}
4364
4365#[no_mangle]
4366pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnChat<'l>(
4367    mut env: JNIEnv<'l>,
4368    _class: JClass<'l>,
4369    player: JString<'l>,
4370    message: JString<'l>,
4371    dimension: JString<'l>,
4372) {
4373    let (p, m, d) = (
4374        jstr!(env, player),
4375        jstr!(env, message),
4376        jstr!(env, dimension),
4377    );
4378    let ev = yog_abi::YogChatEvent {
4379        player: YogStr::from_str(&p),
4380        message: YogStr::from_str(&m),
4381        dimension: YogStr::from_str(&d),
4382    };
4383    let srv = srv_ptr();
4384    guard("on_chat", || {
4385        for (module, ud, f) in &handlers().chat {
4386            if module.is_retiring() {
4387                continue;
4388            }
4389            let Some(_call) = module.enter() else {
4390                continue;
4391            };
4392            unsafe { f(*ud, srv, &ev, 1) };
4393        }
4394    });
4395}
4396
4397#[no_mangle]
4398pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerJoin<'l>(
4399    mut env: JNIEnv<'l>,
4400    _class: JClass<'l>,
4401    player: JString<'l>,
4402    uuid: JString<'l>,
4403    dimension: JString<'l>,
4404) {
4405    let (p, u, d) = (jstr!(env, player), jstr!(env, uuid), jstr!(env, dimension));
4406    let ev = yog_abi::YogPlayerEvent {
4407        player: YogStr::from_str(&p),
4408        uuid: YogStr::from_str(&u),
4409        dimension: YogStr::from_str(&d),
4410    };
4411    let srv = srv_ptr();
4412    guard("on_player_join", || {
4413        for (module, ud, f) in &handlers().player_join {
4414            if module.is_retiring() {
4415                continue;
4416            }
4417            let Some(_call) = module.enter() else {
4418                continue;
4419            };
4420            unsafe { f(*ud, srv, &ev, 1) };
4421        }
4422    });
4423    // Queue startup grants: giving items directly inside the join callback
4424    // fails for the host of a freshly created world (player not fully in the
4425    // world yet), so grants are processed a few server ticks later.
4426    let h = handlers();
4427    if !h.startup_grants.is_empty() {
4428        h.pending_grants
4429            .lock()
4430            .expect("pending_grants poisoned")
4431            .push((p, u, 0));
4432    }
4433}
4434
4435/// Try to fulfil pending startup grants. Called each server tick; a grant is
4436/// only marked as given (and persisted) after `give_item` actually succeeds.
4437fn process_pending_grants() {
4438    let h = handlers();
4439    let mut pending = match h.pending_grants.try_lock() {
4440        Ok(g) => g,
4441        Err(_) => return,
4442    };
4443    if pending.is_empty() {
4444        return;
4445    }
4446    // Wait a couple of ticks after join before the first attempt.
4447    const FIRST_TRY_TICK: u32 = 2;
4448    // Give up after 30 seconds — the player probably left.
4449    const MAX_TICKS: u32 = 600;
4450
4451    let mut granted = h.startup_granted.lock().expect("startup_granted poisoned");
4452    let mut still_pending = Vec::new();
4453    let mut any_new = false;
4454
4455    for (p, u, ticks) in pending.drain(..) {
4456        if ticks < FIRST_TRY_TICK {
4457            still_pending.push((p, u, ticks + 1));
4458            continue;
4459        }
4460        let mut all_ok = true;
4461        for sg in &h.startup_grants {
4462            let key = format!("{}::{}", u, sg.id);
4463            if granted.contains_key(&key) {
4464                continue;
4465            }
4466            let mut ok = true;
4467            for item_id in &sg.items {
4468                ok &= unsafe {
4469                    srv_give_item(
4470                        std::ptr::null_mut(),
4471                        YogStr::from_str(&p),
4472                        YogStr::from_str(item_id),
4473                        1,
4474                    )
4475                };
4476            }
4477            if let Some(_book) = &sg.book {
4478                ok &= unsafe {
4479                    srv_give_item(
4480                        std::ptr::null_mut(),
4481                        YogStr::from_str(&p),
4482                        YogStr::from_str("minecraft:written_book"),
4483                        1,
4484                    )
4485                };
4486            }
4487            if ok {
4488                yog_logging::info!("startup grant {} given to {}", sg.id, p);
4489                granted.insert(key, true);
4490                any_new = true;
4491            } else {
4492                all_ok = false;
4493            }
4494        }
4495        if !all_ok && ticks < MAX_TICKS {
4496            still_pending.push((p, u, ticks + 1));
4497        }
4498    }
4499    *pending = still_pending;
4500    if any_new {
4501        save_startup_granted(&granted);
4502    }
4503}
4504
4505#[no_mangle]
4506pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerLeave<'l>(
4507    mut env: JNIEnv<'l>,
4508    _class: JClass<'l>,
4509    player: JString<'l>,
4510    uuid: JString<'l>,
4511    dimension: JString<'l>,
4512) {
4513    let (p, u, d) = (jstr!(env, player), jstr!(env, uuid), jstr!(env, dimension));
4514    let ev = yog_abi::YogPlayerEvent {
4515        player: YogStr::from_str(&p),
4516        uuid: YogStr::from_str(&u),
4517        dimension: YogStr::from_str(&d),
4518    };
4519    let srv = srv_ptr();
4520    guard("on_player_leave", || {
4521        for (module, ud, f) in &handlers().player_leave {
4522            if module.is_retiring() {
4523                continue;
4524            }
4525            let Some(_call) = module.enter() else {
4526                continue;
4527            };
4528            unsafe { f(*ud, srv, &ev, 1) };
4529        }
4530    });
4531}
4532
4533#[no_mangle]
4534pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseItem<'l>(
4535    mut env: JNIEnv<'l>,
4536    _class: JClass<'l>,
4537    player: JString<'l>,
4538    item: JString<'l>,
4539    sneaking: jni::sys::jboolean,
4540    dimension: JString<'l>,
4541) {
4542    let (p, i, d) = (jstr!(env, player), jstr!(env, item), jstr!(env, dimension));
4543    let ev = yog_abi::YogUseItemEvent {
4544        player: YogStr::from_str(&p),
4545        item: YogStr::from_str(&i),
4546        sneaking: sneaking != 0,
4547        dimension: YogStr::from_str(&d),
4548    };
4549    let srv = srv_ptr();
4550    guard("on_use_item", || {
4551        for (module, ud, f) in &handlers().use_item {
4552            if module.is_retiring() {
4553                continue;
4554            }
4555            let Some(_call) = module.enter() else {
4556                continue;
4557            };
4558            unsafe { f(*ud, srv, &ev, 1) };
4559        }
4560    });
4561}
4562
4563#[no_mangle]
4564pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseItemPre<'l>(
4565    mut env: JNIEnv<'l>,
4566    _class: JClass<'l>,
4567    player: JString<'l>,
4568    item: JString<'l>,
4569    sneaking: jni::sys::jboolean,
4570    dimension: JString<'l>,
4571) -> jni::sys::jboolean {
4572    let h = handlers();
4573    if h.use_item.is_empty() {
4574        return 1;
4575    }
4576    let p = match env.get_string(&player) {
4577        Ok(s) => String::from(s),
4578        Err(_) => return 1,
4579    };
4580    let i = match env.get_string(&item) {
4581        Ok(s) => String::from(s),
4582        Err(_) => return 1,
4583    };
4584    let d = match env.get_string(&dimension) {
4585        Ok(s) => String::from(s),
4586        Err(_) => return 1,
4587    };
4588    let ev = yog_abi::YogUseItemEvent {
4589        player: YogStr::from_str(&p),
4590        item: YogStr::from_str(&i),
4591        sneaking: sneaking != 0,
4592        dimension: YogStr::from_str(&d),
4593    };
4594    let srv = srv_ptr();
4595    let mut allow = true;
4596    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4597        for (module, ud, f) in &h.use_item {
4598            if module.is_retiring() {
4599                continue;
4600            }
4601            let Some(_call) = module.enter() else {
4602                continue;
4603            };
4604            if !unsafe { f(*ud, srv, &ev, 0) } {
4605                allow = false;
4606                break;
4607            }
4608        }
4609    }))
4610    .ok();
4611    allow as jni::sys::jboolean
4612}
4613
4614#[no_mangle]
4615pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseBlock<'l>(
4616    mut env: JNIEnv<'l>,
4617    _class: JClass<'l>,
4618    player: JString<'l>,
4619    block: JString<'l>,
4620    x: jint,
4621    y: jint,
4622    z: jint,
4623    dimension: JString<'l>,
4624) {
4625    let (p, b, d) = (jstr!(env, player), jstr!(env, block), jstr!(env, dimension));
4626    let ev = yog_abi::YogUseBlockEvent {
4627        player: YogStr::from_str(&p),
4628        block: YogStr::from_str(&b),
4629        pos: YogBlockPos { x, y, z },
4630        dimension: YogStr::from_str(&d),
4631    };
4632    let srv = srv_ptr();
4633    guard("on_use_block", || {
4634        for (module, ud, f) in &handlers().use_block {
4635            if module.is_retiring() {
4636                continue;
4637            }
4638            let Some(_call) = module.enter() else {
4639                continue;
4640            };
4641            unsafe { f(*ud, srv, &ev, 1) };
4642        }
4643    });
4644}
4645
4646#[no_mangle]
4647pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseBlockPre<'l>(
4648    mut env: JNIEnv<'l>,
4649    _class: JClass<'l>,
4650    player: JString<'l>,
4651    block: JString<'l>,
4652    x: jint,
4653    y: jint,
4654    z: jint,
4655    dimension: JString<'l>,
4656) -> jni::sys::jboolean {
4657    let h = handlers();
4658    if h.use_block.is_empty() {
4659        return 1;
4660    }
4661    let p = match env.get_string(&player) {
4662        Ok(s) => String::from(s),
4663        Err(_) => return 1,
4664    };
4665    let b = match env.get_string(&block) {
4666        Ok(s) => String::from(s),
4667        Err(_) => return 1,
4668    };
4669    let d = match env.get_string(&dimension) {
4670        Ok(s) => String::from(s),
4671        Err(_) => return 1,
4672    };
4673    let ev = yog_abi::YogUseBlockEvent {
4674        player: YogStr::from_str(&p),
4675        block: YogStr::from_str(&b),
4676        pos: YogBlockPos { x, y, z },
4677        dimension: YogStr::from_str(&d),
4678    };
4679    let srv = srv_ptr();
4680    let mut allow = true;
4681    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4682        for (module, ud, f) in &h.use_block {
4683            if module.is_retiring() {
4684                continue;
4685            }
4686            let Some(_call) = module.enter() else {
4687                continue;
4688            };
4689            if !unsafe { f(*ud, srv, &ev, 0) } {
4690                allow = false;
4691                break;
4692            }
4693        }
4694    }))
4695    .ok();
4696    allow as jni::sys::jboolean
4697}
4698
4699#[no_mangle]
4700pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnAttackEntity<'l>(
4701    mut env: JNIEnv<'l>,
4702    _class: JClass<'l>,
4703    player: JString<'l>,
4704    target_type: JString<'l>,
4705    target_uuid: JString<'l>,
4706    dimension: JString<'l>,
4707) {
4708    let (p, tt, tu, d) = (
4709        jstr!(env, player),
4710        jstr!(env, target_type),
4711        jstr!(env, target_uuid),
4712        jstr!(env, dimension),
4713    );
4714    let ev = yog_abi::YogAttackEntityEvent {
4715        player: YogStr::from_str(&p),
4716        target_type: YogStr::from_str(&tt),
4717        target_uuid: YogStr::from_str(&tu),
4718        dimension: YogStr::from_str(&d),
4719    };
4720    let srv = srv_ptr();
4721    guard("on_attack_entity", || {
4722        for (module, ud, f) in &handlers().attack_entity {
4723            if module.is_retiring() {
4724                continue;
4725            }
4726            let Some(_call) = module.enter() else {
4727                continue;
4728            };
4729            unsafe { f(*ud, srv, &ev, 1) };
4730        }
4731    });
4732}
4733
4734#[no_mangle]
4735pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityDamage<'l>(
4736    mut env: JNIEnv<'l>,
4737    _class: JClass<'l>,
4738    entity_type: JString<'l>,
4739    uuid: JString<'l>,
4740    amount: jfloat,
4741    source: JString<'l>,
4742    dimension: JString<'l>,
4743) {
4744    let (et, u, s, d) = (
4745        jstr!(env, entity_type),
4746        jstr!(env, uuid),
4747        jstr!(env, source),
4748        jstr!(env, dimension),
4749    );
4750    let ev = yog_abi::YogEntityDamageEvent {
4751        entity_type: YogStr::from_str(&et),
4752        uuid: YogStr::from_str(&u),
4753        amount,
4754        source: YogStr::from_str(&s),
4755        dimension: YogStr::from_str(&d),
4756    };
4757    let srv = srv_ptr();
4758    guard("on_entity_damage", || {
4759        for (module, ud, f) in &handlers().entity_damage {
4760            if module.is_retiring() {
4761                continue;
4762            }
4763            let Some(_call) = module.enter() else {
4764                continue;
4765            };
4766            unsafe { f(*ud, srv, &ev, 1) };
4767        }
4768    });
4769}
4770
4771#[no_mangle]
4772pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityDeath<'l>(
4773    mut env: JNIEnv<'l>,
4774    _class: JClass<'l>,
4775    entity_type: JString<'l>,
4776    uuid: JString<'l>,
4777    source: JString<'l>,
4778    dimension: JString<'l>,
4779) {
4780    let (et, u, s, d) = (
4781        jstr!(env, entity_type),
4782        jstr!(env, uuid),
4783        jstr!(env, source),
4784        jstr!(env, dimension),
4785    );
4786    let ev = yog_abi::YogEntityDeathEvent {
4787        entity_type: YogStr::from_str(&et),
4788        uuid: YogStr::from_str(&u),
4789        source: YogStr::from_str(&s),
4790        dimension: YogStr::from_str(&d),
4791    };
4792    let srv = srv_ptr();
4793    guard("on_entity_death", || {
4794        for (module, ud, f) in &handlers().entity_death {
4795            if module.is_retiring() {
4796                continue;
4797            }
4798            let Some(_call) = module.enter() else {
4799                continue;
4800            };
4801            unsafe { f(*ud, srv, &ev, 1) };
4802        }
4803    });
4804}
4805
4806#[no_mangle]
4807pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnTick<'l>(
4808    _env: JNIEnv<'l>,
4809    _class: JClass<'l>,
4810) {
4811    let h = handlers();
4812    let srv = srv_ptr();
4813    guard("on_tick", || {
4814        for (module, ud, f) in &h.server_tick {
4815            if module.is_retiring() {
4816                continue;
4817            }
4818            let Some(_call) = module.enter() else {
4819                continue;
4820            };
4821            unsafe { f(*ud, srv) };
4822        }
4823    });
4824
4825    guard("startup_grants", process_pending_grants);
4826
4827    // Scheduler — once tasks
4828    {
4829        let mut sched = h.scheduler.lock().expect("scheduler poisoned");
4830        let mut to_fire: Vec<(LoadedModule, *mut c_void, YogScheduledFn)> = Vec::new();
4831        let mut remaining = Vec::new();
4832        for task in sched.once_tasks.drain(..) {
4833            if task.delay_remaining == 0 {
4834                to_fire.push((task.module.clone(), task.ud, task.f));
4835            } else {
4836                remaining.push(OnceTask {
4837                    delay_remaining: task.delay_remaining - 1,
4838                    ..task
4839                });
4840            }
4841        }
4842        sched.once_tasks = remaining;
4843        drop(sched);
4844        for (module, ud, f) in to_fire {
4845            if module.is_retiring() {
4846                continue;
4847            }
4848            let Some(_call) = module.enter() else {
4849                continue;
4850            };
4851            guard("schedule_once", || unsafe { f(ud, srv) });
4852        }
4853    }
4854
4855    // Scheduler — repeating tasks
4856    {
4857        let mut sched = h.scheduler.lock().expect("scheduler poisoned");
4858        let mut to_fire: Vec<(LoadedModule, *mut c_void, YogScheduledFn)> = Vec::new();
4859        for task in &mut sched.repeating_tasks {
4860            if task.ticks_left == 0 {
4861                to_fire.push((task.module.clone(), task.ud, task.f));
4862                task.ticks_left = task.period;
4863            } else {
4864                task.ticks_left -= 1;
4865            }
4866        }
4867        drop(sched);
4868        for (module, ud, f) in to_fire {
4869            if module.is_retiring() {
4870                continue;
4871            }
4872            let Some(_call) = module.enter() else {
4873                continue;
4874            };
4875            guard("schedule_repeating", || unsafe { f(ud, srv) });
4876        }
4877    }
4878}
4879
4880/// Absolute path of the current world save folder (set on server start).
4881static WORLD_DIR: Mutex<Option<std::path::PathBuf>> = Mutex::new(None);
4882
4883/// Per-world data path: `<world>/yog-data/startup_grants.json`.
4884/// Falls back to the working directory before any server has started.
4885fn startup_grants_path() -> std::path::PathBuf {
4886    let base = WORLD_DIR
4887        .lock()
4888        .ok()
4889        .and_then(|d| d.clone())
4890        .unwrap_or_else(|| std::path::PathBuf::from("."));
4891    base.join("yog-data").join("startup_grants.json")
4892}
4893
4894fn load_startup_granted() {
4895    let h = handlers();
4896    let mut granted = h.startup_granted.lock().expect("startup_granted poisoned");
4897    // Reset first — in singleplayer the process outlives individual worlds,
4898    // and grant state is per-world.
4899    granted.clear();
4900    h.pending_grants
4901        .lock()
4902        .expect("pending_grants poisoned")
4903        .clear();
4904    let path = startup_grants_path();
4905    let Ok(data) = std::fs::read_to_string(&path) else {
4906        return;
4907    };
4908    let Ok(keys) = serde_json::from_str::<Vec<String>>(&data) else {
4909        yog_logging::warn!("startup_grants.json: invalid JSON, ignoring");
4910        return;
4911    };
4912    for k in keys {
4913        granted.insert(k, true);
4914    }
4915    yog_logging::info!("loaded {} startup grants from disk", granted.len());
4916}
4917
4918fn save_startup_granted(granted: &HashMap<String, bool>) {
4919    let path = startup_grants_path();
4920    if let Some(parent) = path.parent() {
4921        let _ = std::fs::create_dir_all(parent);
4922    }
4923    let keys: Vec<&String> = granted.keys().collect();
4924    match serde_json::to_string(&keys) {
4925        Ok(json) => {
4926            let _ = std::fs::write(&path, json);
4927        }
4928        Err(e) => yog_logging::error!("failed to save startup_grants.json: {}", e),
4929    }
4930}
4931
4932#[no_mangle]
4933pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnServerStarted<'l>(
4934    mut env: JNIEnv<'l>,
4935    _class: JClass<'l>,
4936    world_dir: JString<'l>,
4937) {
4938    let dir = jstr!(env, world_dir);
4939    *WORLD_DIR.lock().expect("WORLD_DIR poisoned") = if dir.is_empty() {
4940        None
4941    } else {
4942        Some(std::path::PathBuf::from(dir))
4943    };
4944    load_startup_granted();
4945    let srv = srv_ptr();
4946    guard("on_server_started", || {
4947        for (module, ud, f) in &handlers().server_started {
4948            if module.is_retiring() {
4949                continue;
4950            }
4951            let Some(_call) = module.enter() else {
4952                continue;
4953            };
4954            unsafe { f(*ud, srv) };
4955        }
4956    });
4957}
4958
4959#[no_mangle]
4960pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnServerStopping<'l>(
4961    _env: JNIEnv<'l>,
4962    _class: JClass<'l>,
4963) {
4964    let srv = srv_ptr();
4965    guard("on_server_stopping", || {
4966        for (module, ud, f) in &handlers().server_stopping {
4967            if module.is_retiring() {
4968                continue;
4969            }
4970            let Some(_call) = module.enter() else {
4971                continue;
4972            };
4973            unsafe { f(*ud, srv) };
4974        }
4975    });
4976}
4977
4978#[no_mangle]
4979pub extern "system" fn Java_dev_yog_NativeBridge_nativeCommandNames<'l>(
4980    env: JNIEnv<'l>,
4981    _class: JClass<'l>,
4982) -> jstring {
4983    let names = handlers()
4984        .commands
4985        .keys()
4986        .cloned()
4987        .collect::<Vec<_>>()
4988        .join("\n");
4989    env.new_string(names)
4990        .map(|s| s.into_raw())
4991        .unwrap_or(std::ptr::null_mut())
4992}
4993
4994#[no_mangle]
4995pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnBlockBreakPre<'l>(
4996    mut env: JNIEnv<'l>,
4997    _class: JClass<'l>,
4998    player: JString<'l>,
4999    block: JString<'l>,
5000    x: jint,
5001    y: jint,
5002    z: jint,
5003    dimension: JString<'l>,
5004) -> jni::sys::jboolean {
5005    let h = handlers();
5006    if h.block_break.is_empty() {
5007        return 1;
5008    }
5009    let p = match env.get_string(&player) {
5010        Ok(s) => String::from(s),
5011        Err(_) => return 1,
5012    };
5013    let b = match env.get_string(&block) {
5014        Ok(s) => String::from(s),
5015        Err(_) => return 1,
5016    };
5017    let d = match env.get_string(&dimension) {
5018        Ok(s) => String::from(s),
5019        Err(_) => return 1,
5020    };
5021    let ev = yog_abi::YogBlockBreakEvent {
5022        player: YogStr::from_str(&p),
5023        block: YogStr::from_str(&b),
5024        pos: YogBlockPos { x, y, z },
5025        dimension: YogStr::from_str(&d),
5026    };
5027    let srv = srv_ptr();
5028    let mut allow = true;
5029    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5030        for (module, ud, f) in &h.block_break {
5031            if module.is_retiring() {
5032                continue;
5033            }
5034            let Some(_call) = module.enter() else {
5035                continue;
5036            };
5037            if !unsafe { f(*ud, srv, &ev, 0) } {
5038                allow = false;
5039                break;
5040            }
5041        }
5042    }))
5043    .ok();
5044    allow as jni::sys::jboolean
5045}
5046
5047#[no_mangle]
5048pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnChatPre<'l>(
5049    mut env: JNIEnv<'l>,
5050    _class: JClass<'l>,
5051    player: JString<'l>,
5052    message: JString<'l>,
5053    dimension: JString<'l>,
5054) -> jni::sys::jboolean {
5055    let h = handlers();
5056    if h.chat.is_empty() {
5057        return 1;
5058    }
5059    let p = match env.get_string(&player) {
5060        Ok(s) => String::from(s),
5061        Err(_) => return 1,
5062    };
5063    let m = match env.get_string(&message) {
5064        Ok(s) => String::from(s),
5065        Err(_) => return 1,
5066    };
5067    let d = match env.get_string(&dimension) {
5068        Ok(s) => String::from(s),
5069        Err(_) => return 1,
5070    };
5071    let ev = yog_abi::YogChatEvent {
5072        player: YogStr::from_str(&p),
5073        message: YogStr::from_str(&m),
5074        dimension: YogStr::from_str(&d),
5075    };
5076    let srv = srv_ptr();
5077    let mut allow = true;
5078    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5079        for (module, ud, f) in &h.chat {
5080            if module.is_retiring() {
5081                continue;
5082            }
5083            let Some(_call) = module.enter() else {
5084                continue;
5085            };
5086            if !unsafe { f(*ud, srv, &ev, 0) } {
5087                allow = false;
5088                break;
5089            }
5090        }
5091    }))
5092    .ok();
5093    allow as jni::sys::jboolean
5094}
5095
5096#[no_mangle]
5097pub extern "system" fn Java_dev_yog_NativeBridge_nativeRecipeJsons<'l>(
5098    env: JNIEnv<'l>,
5099    _class: JClass<'l>,
5100) -> jstring {
5101    let s = handlers()
5102        .recipes
5103        .iter()
5104        .map(|(ns, name, json)| format!("{}\t{}\t{}", ns, name, json))
5105        .collect::<Vec<_>>()
5106        .join("\n");
5107    env.new_string(s)
5108        .map(|s| s.into_raw())
5109        .unwrap_or(std::ptr::null_mut())
5110}
5111
5112#[no_mangle]
5113pub extern "system" fn Java_dev_yog_NativeBridge_nativeDimensionJsons<'l>(
5114    env: JNIEnv<'l>,
5115    _class: JClass<'l>,
5116) -> jstring {
5117    // One line per declared dimension: `id \t def_json`. The host converts
5118    // `def_json` (our YogDimensionDef shape) into vanilla dimension_type /
5119    // dimension datapack JSON — see `yog-dimensions` crate docs.
5120    let s = handlers()
5121        .dimensions
5122        .iter()
5123        .map(|(id, json)| format!("{}\t{}", id, json))
5124        .collect::<Vec<_>>()
5125        .join("\n");
5126    env.new_string(s)
5127        .map(|s| s.into_raw())
5128        .unwrap_or(std::ptr::null_mut())
5129}
5130
5131/// Called by a registered chunk-generator closure (via `ChunkWriter::set_block`)
5132/// to place one block in the chunk currently being generated. Calls back
5133/// into `YogCallbackChunkGenerator.setBlockInGeneratingChunk` on the Java
5134/// side — same thread, since the whole round trip is synchronous.
5135unsafe extern "C" fn chunk_writer_set_block(
5136    _ctx: *mut c_void,
5137    x: i32,
5138    y: i32,
5139    z: i32,
5140    block_id: YogStr,
5141) -> bool {
5142    let Some(mut env) = get_env() else {
5143        return false;
5144    };
5145    let Some(jb) = ys_to_java(&mut env, block_id) else {
5146        return false;
5147    };
5148    env.call_static_method(
5149        "dev/yog/YogCallbackChunkGenerator",
5150        "setBlockInGeneratingChunk",
5151        "(IIILjava/lang/String;)Z",
5152        &[
5153            JValue::Int(x),
5154            JValue::Int(y),
5155            JValue::Int(z),
5156            JValue::Object(&jb),
5157        ],
5158    )
5159    .and_then(|v| v.z())
5160    .unwrap_or(false)
5161}
5162
5163#[no_mangle]
5164pub extern "system" fn Java_dev_yog_NativeBridge_nativeGenerateChunk<'l>(
5165    mut env: JNIEnv<'l>,
5166    _class: JClass<'l>,
5167    generator_type_id: JString<'l>,
5168    chunk_x: jint,
5169    chunk_z: jint,
5170    min_y: jint,
5171    height: jint,
5172) {
5173    let id: String = match env.get_string(&generator_type_id) {
5174        Ok(s) => String::from(s),
5175        Err(_) => return,
5176    };
5177    let Some((module, ud, cb)) = handlers().chunk_generators.get(&id).cloned() else {
5178        return;
5179    };
5180    if module.is_retiring() {
5181        return;
5182    }
5183    let Some(_call) = module.enter() else { return };
5184    let writer = yog_abi::YogChunkWriterApi {
5185        chunk_x,
5186        chunk_z,
5187        min_y,
5188        height,
5189        ctx: std::ptr::null_mut(),
5190        set_block: chunk_writer_set_block,
5191    };
5192    guard("chunk_generator", || unsafe {
5193        cb(ud, &writer as *const _);
5194    });
5195}
5196
5197#[no_mangle]
5198pub extern "system" fn Java_dev_yog_NativeBridge_nativeTypedCommandSchemas<'l>(
5199    env: JNIEnv<'l>,
5200    _class: JClass<'l>,
5201) -> jstring {
5202    // One line per DISTINCT (name, schema) pair — a name can have several
5203    // typed registrations (different arg shapes); Brigadier merges repeated
5204    // `dispatcher.register()` calls for the same literal name into one tree,
5205    // so the Java side just needs every distinct schema once each.
5206    let mut lines = Vec::new();
5207    for (name, regs) in handlers().commands.iter() {
5208        let mut seen = std::collections::HashSet::new();
5209        for (_module, schema, _, _) in regs {
5210            if let Some(schema) = schema {
5211                if seen.insert(schema.as_str()) {
5212                    lines.push(format!("{}\t{}", name, schema));
5213                }
5214            }
5215        }
5216    }
5217    env.new_string(lines.join("\n"))
5218        .map(|s| s.into_raw())
5219        .unwrap_or(std::ptr::null_mut())
5220}
5221
5222#[no_mangle]
5223pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnCommand<'l>(
5224    mut env: JNIEnv<'l>,
5225    _class: JClass<'l>,
5226    name: JString<'l>,
5227    args: JString<'l>,
5228    source: JString<'l>,
5229    uuid: JString<'l>,
5230    dimension: JString<'l>,
5231) -> jstring {
5232    let (n, a, s, u, d) = (
5233        env.get_string(&name).map(String::from).unwrap_or_default(),
5234        env.get_string(&args).map(String::from).unwrap_or_default(),
5235        env.get_string(&source)
5236            .map(String::from)
5237            .unwrap_or_default(),
5238        env.get_string(&uuid).map(String::from).unwrap_or_default(),
5239        env.get_string(&dimension)
5240            .map(String::from)
5241            .unwrap_or_default(),
5242    );
5243    let ev = yog_abi::YogCommandEvent {
5244        name: YogStr::from_str(&n),
5245        args: YogStr::from_str(&a),
5246        source: YogStr::from_str(&s),
5247        uuid: YogStr::from_str(&u),
5248        dimension: YogStr::from_str(&d),
5249    };
5250    let h = handlers();
5251    let srv = srv_ptr();
5252    // Actual arg count of this invocation (0 for a bare command with no args).
5253    let actual_argc = if a.is_empty() {
5254        0
5255    } else {
5256        a.split('\t').count()
5257    };
5258    let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5259        let Some(regs) = h.commands.get(&n) else {
5260            return String::new();
5261        };
5262        for (module, schema, ud, f) in regs {
5263            let expected_argc = schema.as_ref().map_or(0, |s| s.split_whitespace().count());
5264            if expected_argc != actual_argc {
5265                continue;
5266            }
5267            if module.is_retiring() {
5268                continue;
5269            }
5270            let Some(_call) = module.enter() else {
5271                continue;
5272            };
5273            let mut buf = [0u8; 4096];
5274            let mut reply_len: u32 = 0;
5275            unsafe {
5276                f(
5277                    *ud,
5278                    srv,
5279                    &ev,
5280                    buf.as_mut_ptr(),
5281                    buf.len() as u32,
5282                    &mut reply_len,
5283                )
5284            };
5285            if reply_len > 0 {
5286                return String::from_utf8_lossy(&buf[..reply_len as usize]).into_owned();
5287            }
5288        }
5289        String::new()
5290    }))
5291    .unwrap_or_else(|_| {
5292        yog_logging::error!("a mod panicked handling command `{}`", n);
5293        String::new()
5294    });
5295
5296    env.new_string(reply)
5297        .map(|s| s.into_raw())
5298        .unwrap_or(std::ptr::null_mut())
5299}
5300
5301#[no_mangle]
5302pub extern "system" fn Java_dev_yog_NativeBridge_nativeItemDefs<'l>(
5303    env: JNIEnv<'l>,
5304    _class: JClass<'l>,
5305) -> jstring {
5306    let s = handlers()
5307        .items
5308        .iter()
5309        .map(|d| {
5310            let mut parts = vec![d.id.clone()];
5311            parts.push(format!("max_stack={}", d.max_stack));
5312            if let Some(n) = &d.name {
5313                parts.push(format!("name={n}"));
5314            }
5315            if let Some(t) = &d.tooltip {
5316                parts.push(format!("tooltip={t}"));
5317            }
5318            if d.max_damage > 0 {
5319                parts.push(format!("max_damage={}", d.max_damage));
5320            }
5321            if d.fire_resistant {
5322                parts.push("fire_resistant=1".into());
5323            }
5324            if d.fuel_ticks > 0 {
5325                parts.push(format!("fuel_ticks={}", d.fuel_ticks));
5326            }
5327            if let Some(f) = &d.food {
5328                parts.push(format!(
5329                    "food={}:{}:{}",
5330                    f.nutrition,
5331                    f.saturation,
5332                    if f.can_always_eat { 1 } else { 0 }
5333                ));
5334            }
5335            parts.join("\t")
5336        })
5337        .collect::<Vec<_>>()
5338        .join("\n");
5339    env.new_string(s)
5340        .map(|s| s.into_raw())
5341        .unwrap_or(std::ptr::null_mut())
5342}
5343
5344#[no_mangle]
5345pub extern "system" fn Java_dev_yog_NativeBridge_nativeBlockDefs<'l>(
5346    env: JNIEnv<'l>,
5347    _class: JClass<'l>,
5348) -> jstring {
5349    let s = handlers()
5350        .blocks
5351        .iter()
5352        .map(|d| {
5353            let mut parts = vec![d.id.clone()];
5354            parts.push(format!("hardness={}", d.hardness));
5355            parts.push(format!("resistance={}", d.resistance));
5356            if let Some(n) = &d.name {
5357                parts.push(format!("name={n}"));
5358            }
5359            if let Some(sh) = d.shape {
5360                parts.push(format!(
5361                    "shape={}:{}:{}:{}:{}:{}",
5362                    sh[0], sh[1], sh[2], sh[3], sh[4], sh[5]
5363                ));
5364            }
5365            if d.light_level > 0 {
5366                parts.push(format!("light={}", d.light_level));
5367            }
5368            if let Some(snd) = &d.sound {
5369                parts.push(format!("sound={snd}"));
5370            }
5371            if d.requires_tool {
5372                parts.push("requires_tool=1".into());
5373            }
5374            if d.no_collision {
5375                parts.push("no_collision=1".into());
5376            }
5377            if d.slipperiness > 0.0 {
5378                parts.push(format!("slipperiness={}", d.slipperiness));
5379            }
5380            if d.connects {
5381                parts.push("connects=1".into());
5382            }
5383            if !d.connect_groups.is_empty() {
5384                parts.push(format!("connect_groups={}", d.connect_groups.join(",")));
5385            }
5386            if let Some(inv) = &d.inventory_id {
5387                parts.push(format!("inventory_id={inv}"));
5388            }
5389            parts.join("\t")
5390        })
5391        .collect::<Vec<_>>()
5392        .join("\n");
5393    env.new_string(s)
5394        .map(|s| s.into_raw())
5395        .unwrap_or(std::ptr::null_mut())
5396}
5397
5398/// Tab/newline-encoded inventory defs — one line per registered
5399/// `InventoryDef` (see `yog_inventory`): `id\tslot_count=N\tlayout=x:y,...
5400/// \tinclude_player_inventory=0|1\tplayer_inv=x:y\tbackground_texture=...\ttitle=...`
5401#[no_mangle]
5402pub extern "system" fn Java_dev_yog_NativeBridge_nativeInventoryDefs<'l>(
5403    env: JNIEnv<'l>,
5404    _class: JClass<'l>,
5405) -> jstring {
5406    let s = handlers()
5407        .inventories
5408        .iter()
5409        .map(|d| {
5410            let mut parts = vec![d.id.clone()];
5411            parts.push(format!("slot_count={}", d.slot_count));
5412            parts.push(format!(
5413                "layout={}",
5414                yog_inventory::encode_layout(&d.resolved_layout())
5415            ));
5416            parts.push(format!(
5417                "include_player_inventory={}",
5418                d.include_player_inventory as u8
5419            ));
5420            parts.push(format!(
5421                "player_inv={}:{}",
5422                d.player_inv_offset.0, d.player_inv_offset.1
5423            ));
5424            if let Some(tex) = &d.background_texture {
5425                parts.push(format!("background_texture={tex}"));
5426            }
5427            if !d.title.is_empty() {
5428                parts.push(format!("title={}", d.title));
5429            }
5430            if let Some((w, h)) = d.background_size {
5431                parts.push(format!("background_size={w}:{h}"));
5432            }
5433            parts.join("\t")
5434        })
5435        .collect::<Vec<_>>()
5436        .join("\n");
5437    env.new_string(s)
5438        .map(|s| s.into_raw())
5439        .unwrap_or(std::ptr::null_mut())
5440}
5441
5442#[no_mangle]
5443pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPacket<'l>(
5444    mut env: JNIEnv<'l>,
5445    _class: JClass<'l>,
5446    channel: JString<'l>,
5447    player: JString<'l>,
5448    payload: JByteArray<'l>,
5449) {
5450    let ch = env
5451        .get_string(&channel)
5452        .map(String::from)
5453        .unwrap_or_default();
5454    let pl = env
5455        .get_string(&player)
5456        .map(String::from)
5457        .unwrap_or_default();
5458    let data = env.convert_byte_array(&payload).unwrap_or_default();
5459    let ev = yog_abi::YogPacketEvent {
5460        channel: YogStr::from_str(&ch),
5461        player: YogStr::from_str(&pl),
5462        payload: data.as_ptr(),
5463        payload_len: data.len() as u32,
5464    };
5465    let h = handlers();
5466    let srv = srv_ptr();
5467    guard("on_packet", || {
5468        if let Some((module, ud, f)) = h.packets.get(&ch) {
5469            if module.is_retiring() {
5470                return;
5471            }
5472            let Some(_call) = module.enter() else { return };
5473            unsafe { f(*ud, srv, &ev) };
5474        }
5475    });
5476}
5477
5478#[no_mangle]
5479pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnClientPacket<'l>(
5480    mut env: JNIEnv<'l>,
5481    _class: JClass<'l>,
5482    channel: JString<'l>,
5483    payload: JByteArray<'l>,
5484) {
5485    let ch = env
5486        .get_string(&channel)
5487        .map(String::from)
5488        .unwrap_or_default();
5489    let data = env.convert_byte_array(&payload).unwrap_or_default();
5490    let ev = yog_abi::YogPacketEvent {
5491        channel: YogStr::from_str(&ch),
5492        player: YogStr::EMPTY,
5493        payload: data.as_ptr(),
5494        payload_len: data.len() as u32,
5495    };
5496    let h = handlers();
5497    let srv = srv_ptr();
5498    guard("on_client_packet", || {
5499        if let Some((module, ud, f)) = h.client_packets.get(&ch) {
5500            if module.is_retiring() {
5501                return;
5502            }
5503            let Some(_call) = module.enter() else { return };
5504            unsafe { f(*ud, srv, &ev) };
5505        }
5506    });
5507}
5508
5509#[no_mangle]
5510pub extern "system" fn Java_dev_yog_NativeBridge_nativePacketChannels<'l>(
5511    env: JNIEnv<'l>,
5512    _class: JClass<'l>,
5513) -> jstring {
5514    let s = handlers()
5515        .packets
5516        .keys()
5517        .cloned()
5518        .collect::<Vec<_>>()
5519        .join("\n");
5520    env.new_string(s)
5521        .map(|s| s.into_raw())
5522        .unwrap_or(std::ptr::null_mut())
5523}
5524
5525#[no_mangle]
5526pub extern "system" fn Java_dev_yog_NativeBridge_nativeClientPacketChannels<'l>(
5527    env: JNIEnv<'l>,
5528    _class: JClass<'l>,
5529) -> jstring {
5530    let s = handlers()
5531        .client_packets
5532        .keys()
5533        .cloned()
5534        .collect::<Vec<_>>()
5535        .join("\n");
5536    env.new_string(s)
5537        .map(|s| s.into_raw())
5538        .unwrap_or(std::ptr::null_mut())
5539}
5540
5541#[no_mangle]
5542pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntitySpawn<'l>(
5543    mut env: JNIEnv<'l>,
5544    _class: JClass<'l>,
5545    entity_type: JString<'l>,
5546    uuid: JString<'l>,
5547    dimension: JString<'l>,
5548) {
5549    let h = handlers();
5550    if h.entity_spawn.is_empty() {
5551        return;
5552    }
5553    let (et, u, d) = (
5554        jstr!(env, entity_type),
5555        jstr!(env, uuid),
5556        jstr!(env, dimension),
5557    );
5558    let ev = yog_abi::YogEntitySpawnEvent {
5559        entity_type: YogStr::from_str(&et),
5560        uuid: YogStr::from_str(&u),
5561        dimension: YogStr::from_str(&d),
5562    };
5563    let srv = srv_ptr();
5564    guard("on_entity_spawn", || {
5565        for (module, ud, f) in &h.entity_spawn {
5566            if module.is_retiring() {
5567                continue;
5568            }
5569            let Some(_call) = module.enter() else {
5570                continue;
5571            };
5572            unsafe { f(*ud, srv, &ev, 1) };
5573        }
5574    });
5575}
5576
5577#[no_mangle]
5578pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntitySpawnPre<'l>(
5579    mut env: JNIEnv<'l>,
5580    _class: JClass<'l>,
5581    entity_type: JString<'l>,
5582    uuid: JString<'l>,
5583    dimension: JString<'l>,
5584) -> jni::sys::jboolean {
5585    let h = handlers();
5586    if h.entity_spawn.is_empty() {
5587        return 1;
5588    }
5589    let et = match env.get_string(&entity_type) {
5590        Ok(s) => String::from(s),
5591        Err(_) => return 1,
5592    };
5593    let u = match env.get_string(&uuid) {
5594        Ok(s) => String::from(s),
5595        Err(_) => return 1,
5596    };
5597    let d = match env.get_string(&dimension) {
5598        Ok(s) => String::from(s),
5599        Err(_) => return 1,
5600    };
5601    let ev = yog_abi::YogEntitySpawnEvent {
5602        entity_type: YogStr::from_str(&et),
5603        uuid: YogStr::from_str(&u),
5604        dimension: YogStr::from_str(&d),
5605    };
5606    let srv = srv_ptr();
5607    let mut allow = true;
5608    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5609        for (module, ud, f) in &h.entity_spawn {
5610            if module.is_retiring() {
5611                continue;
5612            }
5613            let Some(_call) = module.enter() else {
5614                continue;
5615            };
5616            if !unsafe { f(*ud, srv, &ev, 0) } {
5617                allow = false;
5618                break;
5619            }
5620        }
5621    }))
5622    .ok();
5623    allow as jni::sys::jboolean
5624}
5625
5626#[no_mangle]
5627pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityDamagePre<'l>(
5628    mut env: JNIEnv<'l>,
5629    _class: JClass<'l>,
5630    entity_type: JString<'l>,
5631    uuid: JString<'l>,
5632    amount: jfloat,
5633    source: JString<'l>,
5634    dimension: JString<'l>,
5635) -> jni::sys::jboolean {
5636    let h = handlers();
5637    if h.entity_damage.is_empty() {
5638        return 1;
5639    }
5640    let et = match env.get_string(&entity_type) {
5641        Ok(s) => String::from(s),
5642        Err(_) => return 1,
5643    };
5644    let u = match env.get_string(&uuid) {
5645        Ok(s) => String::from(s),
5646        Err(_) => return 1,
5647    };
5648    let s = match env.get_string(&source) {
5649        Ok(s) => String::from(s),
5650        Err(_) => return 1,
5651    };
5652    let d = match env.get_string(&dimension) {
5653        Ok(s) => String::from(s),
5654        Err(_) => return 1,
5655    };
5656    let ev = yog_abi::YogEntityDamageEvent {
5657        entity_type: YogStr::from_str(&et),
5658        uuid: YogStr::from_str(&u),
5659        amount,
5660        source: YogStr::from_str(&s),
5661        dimension: YogStr::from_str(&d),
5662    };
5663    let srv = srv_ptr();
5664    let mut allow = true;
5665    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5666        for (module, ud, f) in &h.entity_damage {
5667            if module.is_retiring() {
5668                continue;
5669            }
5670            let Some(_call) = module.enter() else {
5671                continue;
5672            };
5673            if !unsafe { f(*ud, srv, &ev, 0) } {
5674                allow = false;
5675                break;
5676            }
5677        }
5678    }))
5679    .ok();
5680    allow as jni::sys::jboolean
5681}
5682
5683#[no_mangle]
5684pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlaceBlockPre<'l>(
5685    mut env: JNIEnv<'l>,
5686    _class: JClass<'l>,
5687    player: JString<'l>,
5688    block: JString<'l>,
5689    x: jint,
5690    y: jint,
5691    z: jint,
5692    dimension: JString<'l>,
5693) -> jni::sys::jboolean {
5694    let h = handlers();
5695    if h.player_place_block.is_empty() {
5696        return 1;
5697    }
5698    let p = match env.get_string(&player) {
5699        Ok(s) => String::from(s),
5700        Err(_) => return 1,
5701    };
5702    let b = match env.get_string(&block) {
5703        Ok(s) => String::from(s),
5704        Err(_) => return 1,
5705    };
5706    let d = match env.get_string(&dimension) {
5707        Ok(s) => String::from(s),
5708        Err(_) => return 1,
5709    };
5710    let ev = YogPlaceBlockEvent {
5711        player: YogStr::from_str(&p),
5712        block: YogStr::from_str(&b),
5713        pos: YogBlockPos { x, y, z },
5714        dimension: YogStr::from_str(&d),
5715    };
5716    let srv = srv_ptr();
5717    let mut allow = true;
5718    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5719        for (module, ud, f) in &h.player_place_block {
5720            if module.is_retiring() {
5721                continue;
5722            }
5723            let Some(_call) = module.enter() else {
5724                continue;
5725            };
5726            if !unsafe { f(*ud, srv, &ev, 0) } {
5727                allow = false;
5728                break;
5729            }
5730        }
5731    }))
5732    .ok();
5733    allow as jni::sys::jboolean
5734}
5735
5736#[no_mangle]
5737pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlaceBlock<'l>(
5738    mut env: JNIEnv<'l>,
5739    _class: JClass<'l>,
5740    player: JString<'l>,
5741    block: JString<'l>,
5742    x: jint,
5743    y: jint,
5744    z: jint,
5745    dimension: JString<'l>,
5746) {
5747    let h = handlers();
5748    if h.player_place_block.is_empty() {
5749        return;
5750    }
5751    let (p, b, d) = (jstr!(env, player), jstr!(env, block), jstr!(env, dimension));
5752    let ev = YogPlaceBlockEvent {
5753        player: YogStr::from_str(&p),
5754        block: YogStr::from_str(&b),
5755        pos: YogBlockPos { x, y, z },
5756        dimension: YogStr::from_str(&d),
5757    };
5758    let srv = srv_ptr();
5759    guard("on_player_place_block", || {
5760        for (module, ud, f) in &h.player_place_block {
5761            if module.is_retiring() {
5762                continue;
5763            }
5764            let Some(_call) = module.enter() else {
5765                continue;
5766            };
5767            unsafe { f(*ud, srv, &ev, 1) };
5768        }
5769    });
5770}
5771
5772#[no_mangle]
5773pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerDeathPre<'l>(
5774    mut env: JNIEnv<'l>,
5775    _class: JClass<'l>,
5776    player: JString<'l>,
5777    uuid: JString<'l>,
5778    source: JString<'l>,
5779    dimension: JString<'l>,
5780) -> jni::sys::jboolean {
5781    let h = handlers();
5782    if h.player_death.is_empty() {
5783        return 1;
5784    }
5785    let p = match env.get_string(&player) {
5786        Ok(s) => String::from(s),
5787        Err(_) => return 1,
5788    };
5789    let u = match env.get_string(&uuid) {
5790        Ok(s) => String::from(s),
5791        Err(_) => return 1,
5792    };
5793    let s = match env.get_string(&source) {
5794        Ok(s) => String::from(s),
5795        Err(_) => return 1,
5796    };
5797    let d = match env.get_string(&dimension) {
5798        Ok(s) => String::from(s),
5799        Err(_) => return 1,
5800    };
5801    let ev = YogPlayerDeathEvent {
5802        player: YogStr::from_str(&p),
5803        uuid: YogStr::from_str(&u),
5804        source: YogStr::from_str(&s),
5805        dimension: YogStr::from_str(&d),
5806    };
5807    let srv = srv_ptr();
5808    let mut allow = true;
5809    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5810        for (module, ud, f) in &h.player_death {
5811            if module.is_retiring() {
5812                continue;
5813            }
5814            let Some(_call) = module.enter() else {
5815                continue;
5816            };
5817            if !unsafe { f(*ud, srv, &ev, 0) } {
5818                allow = false;
5819                break;
5820            }
5821        }
5822    }))
5823    .ok();
5824    allow as jni::sys::jboolean
5825}
5826
5827#[no_mangle]
5828pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerDeath<'l>(
5829    mut env: JNIEnv<'l>,
5830    _class: JClass<'l>,
5831    player: JString<'l>,
5832    uuid: JString<'l>,
5833    source: JString<'l>,
5834    dimension: JString<'l>,
5835) {
5836    let h = handlers();
5837    if h.player_death.is_empty() {
5838        return;
5839    }
5840    let (p, u, s, d) = (
5841        jstr!(env, player),
5842        jstr!(env, uuid),
5843        jstr!(env, source),
5844        jstr!(env, dimension),
5845    );
5846    let ev = YogPlayerDeathEvent {
5847        player: YogStr::from_str(&p),
5848        uuid: YogStr::from_str(&u),
5849        source: YogStr::from_str(&s),
5850        dimension: YogStr::from_str(&d),
5851    };
5852    let srv = srv_ptr();
5853    guard("on_player_death", || {
5854        for (module, ud, f) in &h.player_death {
5855            if module.is_retiring() {
5856                continue;
5857            }
5858            let Some(_call) = module.enter() else {
5859                continue;
5860            };
5861            unsafe { f(*ud, srv, &ev, 1) };
5862        }
5863    });
5864}
5865
5866#[no_mangle]
5867pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerRespawn<'l>(
5868    mut env: JNIEnv<'l>,
5869    _class: JClass<'l>,
5870    player: JString<'l>,
5871    uuid: JString<'l>,
5872    at_anchor: jni::sys::jboolean,
5873    dimension: JString<'l>,
5874) {
5875    let h = handlers();
5876    if h.player_respawn.is_empty() {
5877        return;
5878    }
5879    let (p, u, d) = (jstr!(env, player), jstr!(env, uuid), jstr!(env, dimension));
5880    let ev = YogPlayerRespawnEvent {
5881        player: YogStr::from_str(&p),
5882        uuid: YogStr::from_str(&u),
5883        at_anchor: at_anchor != 0,
5884        dimension: YogStr::from_str(&d),
5885    };
5886    let srv = srv_ptr();
5887    guard("on_player_respawn", || {
5888        for (module, ud, f) in &h.player_respawn {
5889            if module.is_retiring() {
5890                continue;
5891            }
5892            let Some(_call) = module.enter() else {
5893                continue;
5894            };
5895            unsafe { f(*ud, srv, &ev, 1) };
5896        }
5897    });
5898}
5899
5900#[no_mangle]
5901pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnAdvancement<'l>(
5902    mut env: JNIEnv<'l>,
5903    _class: JClass<'l>,
5904    player: JString<'l>,
5905    uuid: JString<'l>,
5906    advancement: JString<'l>,
5907    dimension: JString<'l>,
5908) {
5909    let h = handlers();
5910    if h.advancement.is_empty() {
5911        return;
5912    }
5913    let (p, u, a, d) = (
5914        jstr!(env, player),
5915        jstr!(env, uuid),
5916        jstr!(env, advancement),
5917        jstr!(env, dimension),
5918    );
5919    let ev = YogAdvancementEvent {
5920        player: YogStr::from_str(&p),
5921        uuid: YogStr::from_str(&u),
5922        advancement: YogStr::from_str(&a),
5923        dimension: YogStr::from_str(&d),
5924    };
5925    let srv = srv_ptr();
5926    guard("on_advancement", || {
5927        for (module, ud, f) in &h.advancement {
5928            if module.is_retiring() {
5929                continue;
5930            }
5931            let Some(_call) = module.enter() else {
5932                continue;
5933            };
5934            unsafe { f(*ud, srv, &ev, 1) };
5935        }
5936    });
5937}
5938
5939#[no_mangle]
5940pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityInteractPre<'l>(
5941    mut env: JNIEnv<'l>,
5942    _class: JClass<'l>,
5943    player: JString<'l>,
5944    player_uuid: JString<'l>,
5945    entity_type: JString<'l>,
5946    entity_uuid: JString<'l>,
5947    hand: JString<'l>,
5948    dimension: JString<'l>,
5949) -> jni::sys::jboolean {
5950    let h = handlers();
5951    if h.entity_interact.is_empty() {
5952        return 1;
5953    }
5954    let p = match env.get_string(&player) {
5955        Ok(s) => String::from(s),
5956        Err(_) => return 1,
5957    };
5958    let pu = match env.get_string(&player_uuid) {
5959        Ok(s) => String::from(s),
5960        Err(_) => return 1,
5961    };
5962    let et = match env.get_string(&entity_type) {
5963        Ok(s) => String::from(s),
5964        Err(_) => return 1,
5965    };
5966    let eu = match env.get_string(&entity_uuid) {
5967        Ok(s) => String::from(s),
5968        Err(_) => return 1,
5969    };
5970    let ha = match env.get_string(&hand) {
5971        Ok(s) => String::from(s),
5972        Err(_) => return 1,
5973    };
5974    let d = match env.get_string(&dimension) {
5975        Ok(s) => String::from(s),
5976        Err(_) => return 1,
5977    };
5978    let ev = YogEntityInteractEvent {
5979        player: YogStr::from_str(&p),
5980        player_uuid: YogStr::from_str(&pu),
5981        entity_type: YogStr::from_str(&et),
5982        entity_uuid: YogStr::from_str(&eu),
5983        hand: YogStr::from_str(&ha),
5984        dimension: YogStr::from_str(&d),
5985    };
5986    let srv = srv_ptr();
5987    let mut allow = true;
5988    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5989        for (module, ud, f) in &h.entity_interact {
5990            if module.is_retiring() {
5991                continue;
5992            }
5993            let Some(_call) = module.enter() else {
5994                continue;
5995            };
5996            if !unsafe { f(*ud, srv, &ev, 0) } {
5997                allow = false;
5998                break;
5999            }
6000        }
6001    }))
6002    .ok();
6003    allow as jni::sys::jboolean
6004}
6005
6006#[no_mangle]
6007pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityInteract<'l>(
6008    mut env: JNIEnv<'l>,
6009    _class: JClass<'l>,
6010    player: JString<'l>,
6011    player_uuid: JString<'l>,
6012    entity_type: JString<'l>,
6013    entity_uuid: JString<'l>,
6014    hand: JString<'l>,
6015    dimension: JString<'l>,
6016) {
6017    let h = handlers();
6018    if h.entity_interact.is_empty() {
6019        return;
6020    }
6021    let (p, pu) = (jstr!(env, player), jstr!(env, player_uuid));
6022    let (et, eu, ha, d) = (
6023        jstr!(env, entity_type),
6024        jstr!(env, entity_uuid),
6025        jstr!(env, hand),
6026        jstr!(env, dimension),
6027    );
6028    let ev = YogEntityInteractEvent {
6029        player: YogStr::from_str(&p),
6030        player_uuid: YogStr::from_str(&pu),
6031        entity_type: YogStr::from_str(&et),
6032        entity_uuid: YogStr::from_str(&eu),
6033        hand: YogStr::from_str(&ha),
6034        dimension: YogStr::from_str(&d),
6035    };
6036    let srv = srv_ptr();
6037    guard("on_entity_interact", || {
6038        for (module, ud, f) in &h.entity_interact {
6039            if module.is_retiring() {
6040                continue;
6041            }
6042            let Some(_call) = module.enter() else {
6043                continue;
6044            };
6045            unsafe { f(*ud, srv, &ev, 1) };
6046        }
6047    });
6048}
6049
6050#[no_mangle]
6051pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnItemCraft<'l>(
6052    mut env: JNIEnv<'l>,
6053    _class: JClass<'l>,
6054    player: JString<'l>,
6055    player_uuid: JString<'l>,
6056    result_item: JString<'l>,
6057    result_count: jint,
6058    dimension: JString<'l>,
6059) {
6060    let h = handlers();
6061    if h.item_craft.is_empty() {
6062        return;
6063    }
6064    let (p, pu, ri, d) = (
6065        jstr!(env, player),
6066        jstr!(env, player_uuid),
6067        jstr!(env, result_item),
6068        jstr!(env, dimension),
6069    );
6070    let ev = YogCraftEvent {
6071        player: YogStr::from_str(&p),
6072        player_uuid: YogStr::from_str(&pu),
6073        result_item: YogStr::from_str(&ri),
6074        result_count: result_count as u32,
6075        dimension: YogStr::from_str(&d),
6076    };
6077    let srv = srv_ptr();
6078    guard("on_item_craft", || {
6079        for (module, ud, f) in &h.item_craft {
6080            if module.is_retiring() {
6081                continue;
6082            }
6083            let Some(_call) = module.enter() else {
6084                continue;
6085            };
6086            unsafe { f(*ud, srv, &ev, 1) };
6087        }
6088    });
6089}
6090
6091#[no_mangle]
6092pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnExplosionPre<'l>(
6093    mut env: JNIEnv<'l>,
6094    _class: JClass<'l>,
6095    dimension: JString<'l>,
6096    x: jdouble,
6097    y: jdouble,
6098    z: jdouble,
6099    power: jfloat,
6100    cause_uuid: JString<'l>,
6101) -> jni::sys::jboolean {
6102    let h = handlers();
6103    if h.explosion.is_empty() {
6104        return 1;
6105    }
6106    let d = match env.get_string(&dimension) {
6107        Ok(s) => String::from(s),
6108        Err(_) => return 1,
6109    };
6110    let cu = match env.get_string(&cause_uuid) {
6111        Ok(s) => String::from(s),
6112        Err(_) => return 1,
6113    };
6114    let ev = YogExplosionEvent {
6115        dimension: YogStr::from_str(&d),
6116        x,
6117        y,
6118        z,
6119        power,
6120        cause_uuid: YogStr::from_str(&cu),
6121    };
6122    let srv = srv_ptr();
6123    let mut allow = true;
6124    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
6125        for (module, ud, f) in &h.explosion {
6126            if module.is_retiring() {
6127                continue;
6128            }
6129            let Some(_call) = module.enter() else {
6130                continue;
6131            };
6132            if !unsafe { f(*ud, srv, &ev, 0) } {
6133                allow = false;
6134                break;
6135            }
6136        }
6137    }))
6138    .ok();
6139    allow as jni::sys::jboolean
6140}
6141
6142#[no_mangle]
6143pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnExplosion<'l>(
6144    mut env: JNIEnv<'l>,
6145    _class: JClass<'l>,
6146    dimension: JString<'l>,
6147    x: jdouble,
6148    y: jdouble,
6149    z: jdouble,
6150    power: jfloat,
6151    cause_uuid: JString<'l>,
6152) {
6153    let h = handlers();
6154    if h.explosion.is_empty() {
6155        return;
6156    }
6157    let (d, cu) = (jstr!(env, dimension), jstr!(env, cause_uuid));
6158    let ev = YogExplosionEvent {
6159        dimension: YogStr::from_str(&d),
6160        x,
6161        y,
6162        z,
6163        power,
6164        cause_uuid: YogStr::from_str(&cu),
6165    };
6166    let srv = srv_ptr();
6167    guard("on_explosion", || {
6168        for (module, ud, f) in &h.explosion {
6169            if module.is_retiring() {
6170                continue;
6171            }
6172            let Some(_call) = module.enter() else {
6173                continue;
6174            };
6175            unsafe { f(*ud, srv, &ev, 1) };
6176        }
6177    });
6178}
6179
6180// ── ABI minor 9 JNI entry points ─────────────────────────────────────────────
6181
6182#[no_mangle]
6183pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnItemPickupPre<'l>(
6184    mut env: JNIEnv<'l>,
6185    _class: JClass<'l>,
6186    player: JString<'l>,
6187    player_uuid: JString<'l>,
6188    item_id: JString<'l>,
6189    item_count: jint,
6190    entity_uuid: JString<'l>,
6191    dimension: JString<'l>,
6192) -> jni::sys::jboolean {
6193    let h = handlers();
6194    if h.item_pickup.is_empty() {
6195        return 1;
6196    }
6197    let p = match env.get_string(&player) {
6198        Ok(s) => String::from(s),
6199        Err(_) => return 1,
6200    };
6201    let pu = match env.get_string(&player_uuid) {
6202        Ok(s) => String::from(s),
6203        Err(_) => return 1,
6204    };
6205    let ii = match env.get_string(&item_id) {
6206        Ok(s) => String::from(s),
6207        Err(_) => return 1,
6208    };
6209    let eu = match env.get_string(&entity_uuid) {
6210        Ok(s) => String::from(s),
6211        Err(_) => return 1,
6212    };
6213    let d = match env.get_string(&dimension) {
6214        Ok(s) => String::from(s),
6215        Err(_) => return 1,
6216    };
6217    let ev = YogItemPickupEvent {
6218        player: YogStr::from_str(&p),
6219        player_uuid: YogStr::from_str(&pu),
6220        item_id: YogStr::from_str(&ii),
6221        item_count: item_count as u32,
6222        entity_uuid: YogStr::from_str(&eu),
6223        dimension: YogStr::from_str(&d),
6224    };
6225    let srv = srv_ptr();
6226    let mut allow = true;
6227    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
6228        for (module, ud, f) in &h.item_pickup {
6229            if module.is_retiring() {
6230                continue;
6231            }
6232            let Some(_call) = module.enter() else {
6233                continue;
6234            };
6235            if !unsafe { f(*ud, srv, &ev, 0) } {
6236                allow = false;
6237                break;
6238            }
6239        }
6240    }))
6241    .ok();
6242    allow as jni::sys::jboolean
6243}
6244
6245#[no_mangle]
6246pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnItemPickup<'l>(
6247    mut env: JNIEnv<'l>,
6248    _class: JClass<'l>,
6249    player: JString<'l>,
6250    player_uuid: JString<'l>,
6251    item_id: JString<'l>,
6252    item_count: jint,
6253    entity_uuid: JString<'l>,
6254    dimension: JString<'l>,
6255) {
6256    let h = handlers();
6257    if h.item_pickup.is_empty() {
6258        return;
6259    }
6260    let (p, pu) = (jstr!(env, player), jstr!(env, player_uuid));
6261    let (ii, eu, d) = (
6262        jstr!(env, item_id),
6263        jstr!(env, entity_uuid),
6264        jstr!(env, dimension),
6265    );
6266    let ev = YogItemPickupEvent {
6267        player: YogStr::from_str(&p),
6268        player_uuid: YogStr::from_str(&pu),
6269        item_id: YogStr::from_str(&ii),
6270        item_count: item_count as u32,
6271        entity_uuid: YogStr::from_str(&eu),
6272        dimension: YogStr::from_str(&d),
6273    };
6274    let srv = srv_ptr();
6275    guard("on_item_pickup", || {
6276        for (module, ud, f) in &h.item_pickup {
6277            if module.is_retiring() {
6278                continue;
6279            }
6280            let Some(_call) = module.enter() else {
6281                continue;
6282            };
6283            unsafe { f(*ud, srv, &ev, 1) };
6284        }
6285    });
6286}
6287
6288#[no_mangle]
6289pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerMove<'l>(
6290    mut env: JNIEnv<'l>,
6291    _class: JClass<'l>,
6292    player: JString<'l>,
6293    player_uuid: JString<'l>,
6294    x: jdouble,
6295    y: jdouble,
6296    z: jdouble,
6297    yaw: jfloat,
6298    pitch: jfloat,
6299    dimension: JString<'l>,
6300) {
6301    let h = handlers();
6302    if h.player_move.is_empty() {
6303        return;
6304    }
6305    let (p, pu, d) = (
6306        jstr!(env, player),
6307        jstr!(env, player_uuid),
6308        jstr!(env, dimension),
6309    );
6310    let ev = YogPlayerMoveEvent {
6311        player: YogStr::from_str(&p),
6312        player_uuid: YogStr::from_str(&pu),
6313        x,
6314        y,
6315        z,
6316        yaw,
6317        pitch,
6318        dimension: YogStr::from_str(&d),
6319    };
6320    let srv = srv_ptr();
6321    guard("on_player_move", || {
6322        for (module, ud, f) in &h.player_move {
6323            if module.is_retiring() {
6324                continue;
6325            }
6326            let Some(_call) = module.enter() else {
6327                continue;
6328            };
6329            unsafe { f(*ud, srv, &ev, 1) };
6330        }
6331    });
6332}
6333
6334#[no_mangle]
6335pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnContainerOpenPre<'l>(
6336    mut env: JNIEnv<'l>,
6337    _class: JClass<'l>,
6338    player: JString<'l>,
6339    player_uuid: JString<'l>,
6340    dimension: JString<'l>,
6341) -> jni::sys::jboolean {
6342    let h = handlers();
6343    if h.container_open.is_empty() {
6344        return 1;
6345    }
6346    let p = match env.get_string(&player) {
6347        Ok(s) => String::from(s),
6348        Err(_) => return 1,
6349    };
6350    let pu = match env.get_string(&player_uuid) {
6351        Ok(s) => String::from(s),
6352        Err(_) => return 1,
6353    };
6354    let d = match env.get_string(&dimension) {
6355        Ok(s) => String::from(s),
6356        Err(_) => return 1,
6357    };
6358    let ev = YogContainerOpenEvent {
6359        player: YogStr::from_str(&p),
6360        player_uuid: YogStr::from_str(&pu),
6361        container_type: YogStr::EMPTY,
6362        dimension: YogStr::from_str(&d),
6363    };
6364    let srv = srv_ptr();
6365    let mut allow = true;
6366    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
6367        for (module, ud, f) in &h.container_open {
6368            if module.is_retiring() {
6369                continue;
6370            }
6371            let Some(_call) = module.enter() else {
6372                continue;
6373            };
6374            if !unsafe { f(*ud, srv, &ev, 0) } {
6375                allow = false;
6376                break;
6377            }
6378        }
6379    }))
6380    .ok();
6381    allow as jni::sys::jboolean
6382}
6383
6384#[no_mangle]
6385pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnContainerOpen<'l>(
6386    mut env: JNIEnv<'l>,
6387    _class: JClass<'l>,
6388    player: JString<'l>,
6389    player_uuid: JString<'l>,
6390    container_type: JString<'l>,
6391    dimension: JString<'l>,
6392) {
6393    let h = handlers();
6394    if h.container_open.is_empty() {
6395        return;
6396    }
6397    let (p, pu, ct, d) = (
6398        jstr!(env, player),
6399        jstr!(env, player_uuid),
6400        jstr!(env, container_type),
6401        jstr!(env, dimension),
6402    );
6403    let ev = YogContainerOpenEvent {
6404        player: YogStr::from_str(&p),
6405        player_uuid: YogStr::from_str(&pu),
6406        container_type: YogStr::from_str(&ct),
6407        dimension: YogStr::from_str(&d),
6408    };
6409    let srv = srv_ptr();
6410    guard("on_container_open", || {
6411        for (module, ud, f) in &h.container_open {
6412            if module.is_retiring() {
6413                continue;
6414            }
6415            let Some(_call) = module.enter() else {
6416                continue;
6417            };
6418            unsafe { f(*ud, srv, &ev, 1) };
6419        }
6420    });
6421}
6422
6423#[no_mangle]
6424pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnContainerClose<'l>(
6425    mut env: JNIEnv<'l>,
6426    _class: JClass<'l>,
6427    player: JString<'l>,
6428    player_uuid: JString<'l>,
6429    dimension: JString<'l>,
6430) {
6431    let h = handlers();
6432    if h.container_close.is_empty() {
6433        return;
6434    }
6435    let (p, pu, d) = (
6436        jstr!(env, player),
6437        jstr!(env, player_uuid),
6438        jstr!(env, dimension),
6439    );
6440    let ev = YogContainerCloseEvent {
6441        player: YogStr::from_str(&p),
6442        player_uuid: YogStr::from_str(&pu),
6443        dimension: YogStr::from_str(&d),
6444    };
6445    let srv = srv_ptr();
6446    guard("on_container_close", || {
6447        for (module, ud, f) in &h.container_close {
6448            if module.is_retiring() {
6449                continue;
6450            }
6451            let Some(_call) = module.enter() else {
6452                continue;
6453            };
6454            unsafe { f(*ud, srv, &ev, 1) };
6455        }
6456    });
6457}
6458
6459#[no_mangle]
6460pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnProjectileHitPre<'l>(
6461    mut env: JNIEnv<'l>,
6462    _class: JClass<'l>,
6463    projectile_type: JString<'l>,
6464    projectile_uuid: JString<'l>,
6465    shooter_uuid: JString<'l>,
6466    hit_type: JString<'l>,
6467    hit_entity_uuid: JString<'l>,
6468    x: jdouble,
6469    y: jdouble,
6470    z: jdouble,
6471    dimension: JString<'l>,
6472) -> jni::sys::jboolean {
6473    let h = handlers();
6474    if h.projectile_hit.is_empty() {
6475        return 1;
6476    }
6477    let pt = match env.get_string(&projectile_type) {
6478        Ok(s) => String::from(s),
6479        Err(_) => return 1,
6480    };
6481    let pu = match env.get_string(&projectile_uuid) {
6482        Ok(s) => String::from(s),
6483        Err(_) => return 1,
6484    };
6485    let su = match env.get_string(&shooter_uuid) {
6486        Ok(s) => String::from(s),
6487        Err(_) => return 1,
6488    };
6489    let ht = match env.get_string(&hit_type) {
6490        Ok(s) => String::from(s),
6491        Err(_) => return 1,
6492    };
6493    let heu = match env.get_string(&hit_entity_uuid) {
6494        Ok(s) => String::from(s),
6495        Err(_) => return 1,
6496    };
6497    let dim = match env.get_string(&dimension) {
6498        Ok(s) => String::from(s),
6499        Err(_) => return 1,
6500    };
6501    let ev = YogProjectileHitEvent {
6502        projectile_type: YogStr::from_str(&pt),
6503        projectile_uuid: YogStr::from_str(&pu),
6504        shooter_uuid: YogStr::from_str(&su),
6505        hit_type: YogStr::from_str(&ht),
6506        hit_entity_uuid: YogStr::from_str(&heu),
6507        x,
6508        y,
6509        z,
6510        dimension: YogStr::from_str(&dim),
6511    };
6512    let srv = srv_ptr();
6513    let mut allow = true;
6514    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
6515        for (module, ud, f) in &h.projectile_hit {
6516            if module.is_retiring() {
6517                continue;
6518            }
6519            let Some(_call) = module.enter() else {
6520                continue;
6521            };
6522            if !unsafe { f(*ud, srv, &ev, 0) } {
6523                allow = false;
6524                break;
6525            }
6526        }
6527    }))
6528    .ok();
6529    allow as jni::sys::jboolean
6530}
6531
6532#[no_mangle]
6533pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnProjectileHit<'l>(
6534    mut env: JNIEnv<'l>,
6535    _class: JClass<'l>,
6536    projectile_type: JString<'l>,
6537    projectile_uuid: JString<'l>,
6538    shooter_uuid: JString<'l>,
6539    hit_type: JString<'l>,
6540    hit_entity_uuid: JString<'l>,
6541    x: jdouble,
6542    y: jdouble,
6543    z: jdouble,
6544    dimension: JString<'l>,
6545) {
6546    let h = handlers();
6547    if h.projectile_hit.is_empty() {
6548        return;
6549    }
6550    let (pt, pu) = (jstr!(env, projectile_type), jstr!(env, projectile_uuid));
6551    let (su, ht) = (jstr!(env, shooter_uuid), jstr!(env, hit_type));
6552    let (heu, dim) = (jstr!(env, hit_entity_uuid), jstr!(env, dimension));
6553    let ev = YogProjectileHitEvent {
6554        projectile_type: YogStr::from_str(&pt),
6555        projectile_uuid: YogStr::from_str(&pu),
6556        shooter_uuid: YogStr::from_str(&su),
6557        hit_type: YogStr::from_str(&ht),
6558        hit_entity_uuid: YogStr::from_str(&heu),
6559        x,
6560        y,
6561        z,
6562        dimension: YogStr::from_str(&dim),
6563    };
6564    let srv = srv_ptr();
6565    guard("on_projectile_hit", || {
6566        for (module, ud, f) in &h.projectile_hit {
6567            if module.is_retiring() {
6568                continue;
6569            }
6570            let Some(_call) = module.enter() else {
6571                continue;
6572            };
6573            unsafe { f(*ud, srv, &ev, 1) };
6574        }
6575    });
6576}
6577
6578// ── ABI minor 10 — client-side JNI entry points ───────────────────────────────
6579
6580#[no_mangle]
6581pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnClientTick<'l>(
6582    _env: JNIEnv<'l>,
6583    _class: JClass<'l>,
6584) {
6585    let h = handlers();
6586    if h.client_tick.is_empty() {
6587        return;
6588    }
6589    guard("on_client_tick", || {
6590        for (module, ud, f) in &h.client_tick {
6591            if module.is_retiring() {
6592                continue;
6593            }
6594            let Some(_call) = module.enter() else {
6595                continue;
6596            };
6597            unsafe { f(*ud) };
6598        }
6599    });
6600}
6601
6602#[no_mangle]
6603pub extern "system" fn Java_dev_yog_NativeBridge_nativeGlInit<'l>(
6604    _env: JNIEnv<'l>,
6605    _class: JClass<'l>,
6606) {
6607    if GL.get().is_some() {
6608        return;
6609    }
6610    let mut raw_get_binary: usize = 0;
6611    let mut raw_prog_binary: usize = 0;
6612    let gl = unsafe {
6613        glow::Context::from_loader_function(|sym| {
6614            let Some(mut env) = get_env() else {
6615                return std::ptr::null();
6616            };
6617            let jsym = match env.new_string(sym) {
6618                Ok(s) => s,
6619                Err(_) => return std::ptr::null(),
6620            };
6621            let jsym_obj: JObject = jsym.into();
6622            let val = env.call_static_method(
6623                "dev/yog/NativeBridge",
6624                "glProcAddress",
6625                "(Ljava/lang/String;)J",
6626                &[JValue::Object(&jsym_obj)],
6627            );
6628            let ptr = match val.and_then(|v| v.j()) {
6629                Ok(p) if p != 0 => p as usize as *const _,
6630                _ => std::ptr::null(),
6631            };
6632            // Capture extension pointers while the loader runs.
6633            match sym {
6634                "glGetProgramBinary" => raw_get_binary = ptr as usize,
6635                "glProgramBinary" => raw_prog_binary = ptr as usize,
6636                _ => {}
6637            }
6638            ptr
6639        })
6640    };
6641    let _ = GL.set(GlCtx(gl));
6642    let _ = GL_GET_PROGRAM_BINARY.set(if raw_get_binary != 0 {
6643        Some(raw_get_binary)
6644    } else {
6645        None
6646    });
6647    let _ = GL_PROGRAM_BINARY.set(if raw_prog_binary != 0 {
6648        Some(raw_prog_binary)
6649    } else {
6650        None
6651    });
6652    // `glGetProgramiv` is a core function; always available.  We look it up once here
6653    // to avoid depending on glow internals for the PROGRAM_BINARY_LENGTH query.
6654    if let Some(mut env) = get_env() {
6655        if let Ok(jsym) = env.new_string("glGetProgramiv") {
6656            let jsym_obj: JObject = jsym.into();
6657            if let Ok(jv) = env.call_static_method(
6658                "dev/yog/NativeBridge",
6659                "glProcAddress",
6660                "(Ljava/lang/String;)J",
6661                &[JValue::Object(&jsym_obj)],
6662            ) {
6663                if let Ok(ptr) = jv.j() {
6664                    let _ = GL_GET_PROGRAM_IV.set(if ptr != 0 { Some(ptr as usize) } else { None });
6665                }
6666            }
6667        }
6668    }
6669}
6670
6671#[no_mangle]
6672pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnHudRender<'l>(
6673    _env: JNIEnv<'l>,
6674    _class: JClass<'l>,
6675    delta_tick: jfloat,
6676    screen_w: jint,
6677    screen_h: jint,
6678    scale_factor: jfloat,
6679    player_x: jfloat,
6680    player_y: jfloat,
6681    player_z: jfloat,
6682) {
6683    let h = handlers();
6684    let mut gfx = GFX_FN_TABLE;
6685    gfx.screen_w = screen_w;
6686    gfx.screen_h = screen_h;
6687    gfx.delta_tick = delta_tick;
6688    gfx.scale_factor = scale_factor;
6689    gfx.player_pos = [player_x, player_y, player_z];
6690
6691    // Mod hud_render callbacks.
6692    if !h.hud_render.is_empty() {
6693        guard("on_hud_render", || {
6694            for (module, ud, f) in &h.hud_render {
6695                if module.is_retiring() {
6696                    continue;
6697                }
6698                let Some(_call) = module.enter() else {
6699                    continue;
6700                };
6701                unsafe { f(*ud, &gfx) };
6702            }
6703        });
6704    }
6705
6706    // Render active book UIs.
6707    let active_layers: Vec<UiLayer> = h.active_uis.lock().unwrap().clone();
6708    let sw = screen_w as f32;
6709    let sh = screen_h as f32;
6710    let ctx = unsafe { yog_gfx::GfxContext::from_raw(&gfx as *const _) };
6711    let mut renderers = h.book_renderers.lock().unwrap();
6712    for layer in &active_layers {
6713        if !layer.visible {
6714            continue;
6715        }
6716        if let Some(renderer) = renderers.get_mut(&layer.id) {
6717            renderer.render(&ctx, sw, sh);
6718        }
6719    }
6720}
6721
6722#[no_mangle]
6723pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnWorldRender<'l>(
6724    env: JNIEnv<'l>,
6725    _class: JClass<'l>,
6726    delta_tick: jfloat,
6727    screen_w: jint,
6728    screen_h: jint,
6729    scale_factor: jfloat,
6730    view_proj_arr: JFloatArray<'l>,
6731    cam_x: jfloat,
6732    cam_y: jfloat,
6733    cam_z: jfloat,
6734    player_x: jfloat,
6735    player_y: jfloat,
6736    player_z: jfloat,
6737) {
6738    let h = handlers();
6739    if h.world_render.is_empty() {
6740        return;
6741    }
6742    let mut view_proj = [0f32; 16];
6743    if env
6744        .get_float_array_region(&view_proj_arr, 0, &mut view_proj)
6745        .is_err()
6746    {
6747        return;
6748    }
6749    let mut gfx = GFX_FN_TABLE;
6750    gfx.screen_w = screen_w;
6751    gfx.screen_h = screen_h;
6752    gfx.delta_tick = delta_tick;
6753    gfx.scale_factor = scale_factor;
6754    gfx.view_proj = view_proj;
6755    gfx.camera_pos = [cam_x, cam_y, cam_z];
6756    gfx.player_pos = [player_x, player_y, player_z];
6757    guard("on_world_render", || {
6758        for (module, ud, f) in &h.world_render {
6759            if module.is_retiring() {
6760                continue;
6761            }
6762            let Some(_call) = module.enter() else {
6763                continue;
6764            };
6765            unsafe { f(*ud, &gfx) };
6766        }
6767    });
6768}
6769
6770#[no_mangle]
6771pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnKeyPress<'l>(
6772    _env: JNIEnv<'l>,
6773    _class: JClass<'l>,
6774    key_code: jint,
6775    scan_code: jint,
6776    action: jint,
6777    modifiers: jint,
6778) -> jni::sys::jboolean {
6779    let h = handlers();
6780    if h.key_press.is_empty() {
6781        return 1;
6782    }
6783    let ev = YogKeyPressEvent {
6784        key_code,
6785        scan_code,
6786        action,
6787        modifiers,
6788    };
6789    let mut allow = true;
6790    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
6791        for (module, ud, f) in &h.key_press {
6792            if module.is_retiring() {
6793                continue;
6794            }
6795            let Some(_call) = module.enter() else {
6796                continue;
6797            };
6798            if !unsafe { f(*ud, &ev) } {
6799                allow = false;
6800                break;
6801            }
6802        }
6803    }))
6804    .ok();
6805    allow as jni::sys::jboolean
6806}
6807
6808#[no_mangle]
6809pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnScreenOpen<'l>(
6810    mut env: JNIEnv<'l>,
6811    _class: JClass<'l>,
6812    screen_class: JString<'l>,
6813) {
6814    let h = handlers();
6815    if h.screen_open.is_empty() {
6816        return;
6817    }
6818    let sc = match env.get_string(&screen_class) {
6819        Ok(s) => String::from(s),
6820        Err(_) => return,
6821    };
6822    guard("on_screen_open", || {
6823        for (module, ud, f) in &h.screen_open {
6824            if module.is_retiring() {
6825                continue;
6826            }
6827            let Some(_call) = module.enter() else {
6828                continue;
6829            };
6830            unsafe { f(*ud, YogStr::from_str(&sc)) };
6831        }
6832    });
6833}
6834
6835#[no_mangle]
6836pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnScreenClose<'l>(
6837    mut env: JNIEnv<'l>,
6838    _class: JClass<'l>,
6839    screen_class: JString<'l>,
6840) {
6841    let h = handlers();
6842    if h.screen_close.is_empty() {
6843        return;
6844    }
6845    let sc = match env.get_string(&screen_class) {
6846        Ok(s) => String::from(s),
6847        Err(_) => return,
6848    };
6849    guard("on_screen_close", || {
6850        for (module, ud, f) in &h.screen_close {
6851            if module.is_retiring() {
6852                continue;
6853            }
6854            let Some(_call) = module.enter() else {
6855                continue;
6856            };
6857            unsafe { f(*ud, YogStr::from_str(&sc)) };
6858        }
6859    });
6860}
6861
6862mod client_api;
6863mod control_socket;
6864mod images;
6865mod ui_jni;