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            // Recipes may register before the book — replay them into the renderer.
3075            for (ns, name, j) in &handlers.recipes {
3076                renderer.add_recipe(format!("{}:{}", ns, name), j);
3077            }
3078            handlers.book_renderers.lock().unwrap().insert(id, renderer);
3079        }
3080        Err(e) => {
3081            yog_logging::warn!(
3082                "book '{}': failed to parse JSON for Rust renderer: {}",
3083                id,
3084                e
3085            );
3086        }
3087    }
3088}
3089
3090unsafe extern "C" fn api_register_dimension_json(ctx: *mut c_void, id: YogStr, json: YogStr) {
3091    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3092    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3093    let id = unsafe { id.as_str().to_owned() };
3094    let json = unsafe { json.as_str().to_owned() };
3095    yog_logging::info!("registered dimension type: {}", id);
3096    handlers.dimensions.insert(id, json);
3097}
3098
3099unsafe extern "C" fn api_register_chunk_generator(
3100    ctx: *mut c_void,
3101    id: YogStr,
3102    ud: *mut c_void,
3103    h: yog_abi::YogChunkGeneratorFn,
3104) {
3105    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3106    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3107    let id = unsafe { id.as_str().to_owned() };
3108    yog_logging::info!("registered chunk generator for dimension: {}", id);
3109    handlers
3110        .chunk_generators
3111        .insert(id, (current_registration(), ud, h));
3112}
3113
3114unsafe extern "C" fn api_register_ui(
3115    ctx: *mut c_void,
3116    ui_id: YogStr,
3117    _layout_json: YogStr,
3118    ud: *mut c_void,
3119    h: yog_abi::YogUIEventFn,
3120) {
3121    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3122    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3123    let id = unsafe { ui_id.as_str().to_owned() };
3124    handlers
3125        .ui_handlers
3126        .insert(id.clone(), (current_registration(), ud, h));
3127    yog_logging::info!("registered UI handler: {}", id);
3128}
3129
3130unsafe extern "C" fn api_on_ui_render(
3131    ctx: *mut c_void,
3132    ui_id: YogStr,
3133    ud: *mut c_void,
3134    h: YogHudRenderFn,
3135) {
3136    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3137    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3138    let id = unsafe { ui_id.as_str().to_owned() };
3139    handlers
3140        .ui_render_handlers
3141        .entry(id)
3142        .or_default()
3143        .push((current_registration(), ud, h));
3144}
3145
3146/// Strip TSV separators so one mod can't corrupt the line format.
3147fn tsv_clean(v: &str) -> String {
3148    v.replace(['\t', '\n', '\r'], " ")
3149}
3150
3151unsafe extern "C" fn api_ui_open(_ctx: *mut c_void, ui_id: YogStr, modal: bool, pause: bool) {
3152    let id = ui_id.as_str().to_string();
3153    if id.is_empty() {
3154        return;
3155    }
3156    let Some(mut env) = get_env() else { return };
3157    let Ok(jid) = env.new_string(&id) else { return };
3158    let jid_obj: JObject = jid.into();
3159    // Java side schedules onto the render thread; no-op on dedicated servers.
3160    if env
3161        .call_static_method(
3162            "dev/yog/NativeBridge",
3163            "openUI",
3164            "(Ljava/lang/String;ZZ)V",
3165            &[
3166                JValue::Object(&jid_obj),
3167                JValue::Bool(modal as u8),
3168                JValue::Bool(pause as u8),
3169            ],
3170        )
3171        .is_err()
3172    {
3173        env.exception_clear().ok();
3174    }
3175}
3176
3177unsafe extern "C" fn api_ui_close(_ctx: *mut c_void, ui_id: YogStr) {
3178    let id = ui_id.as_str().to_string();
3179    let Some(mut env) = get_env() else { return };
3180    let Ok(jid) = env.new_string(&id) else { return };
3181    let jid_obj: JObject = jid.into();
3182    // Java side defers onto the render thread (after the current event) and
3183    // checks the open screen is that Yog UI; no-op on dedicated servers.
3184    if env
3185        .call_static_method(
3186            "dev/yog/NativeBridge",
3187            "closeUI",
3188            "(Ljava/lang/String;)V",
3189            &[JValue::Object(&jid_obj)],
3190        )
3191        .is_err()
3192    {
3193        env.exception_clear().ok();
3194    }
3195}
3196
3197unsafe extern "C" fn api_ui_consume_event(_ctx: *mut c_void) {
3198    ui_jni::consume_event();
3199}
3200
3201unsafe extern "C" fn api_translate(_ctx: *mut c_void, key: YogStr) -> YogOwnedStr {
3202    translate(key.as_str()).map_or(YogOwnedStr::NONE, YogOwnedStr::from_string)
3203}
3204
3205/// The game's text for translation `key` in the current language — `None`
3206/// when no lang file has it (or there's no JVM).
3207fn translate(key: &str) -> Option<String> {
3208    if key.is_empty() {
3209        return None;
3210    }
3211    let mut env = get_env()?;
3212    let jkey: JObject = env.new_string(key).ok()?.into();
3213    let result = env.call_static_method(
3214        "dev/yog/NativeBridge",
3215        "translate",
3216        "(Ljava/lang/String;)Ljava/lang/String;",
3217        &[JValue::Object(&jkey)],
3218    );
3219    let text = match result.and_then(|v| v.l()) {
3220        Ok(obj) if !obj.as_raw().is_null() => env.get_string(&obj.into()).ok().map(String::from),
3221        Ok(_) => None,
3222        Err(_) => {
3223            env.exception_clear().ok();
3224            None
3225        }
3226    };
3227    let _ = env.delete_local_ref(jkey);
3228    text
3229}
3230
3231unsafe extern "C" fn api_mods_list(_ctx: *mut c_void) -> YogOwnedStr {
3232    let mut lines: Vec<String> = Vec::new();
3233    let infos = MOD_INFOS.lock().expect("mod infos lock poisoned").clone();
3234    for m in &infos {
3235        // A `.yres` name/description shows in the player's language.
3236        let localized = |text: &str, key: &str| {
3237            translate(key).map_or_else(|| text.to_string(), |t| tsv_clean(&t))
3238        };
3239        lines.push(format!(
3240            "yog\t{}\t{}\t{}\t{}\t{}",
3241            m[0],
3242            localized(&m[1], &m[5]),
3243            m[2],
3244            m[3],
3245            localized(&m[4], &m[6])
3246        ));
3247    }
3248    // Loader-side (Java) mods, if the host provides them.
3249    if let Some(mut env) = get_env() {
3250        if let Ok(val) = env.call_static_method(
3251            "dev/yog/NativeBridge",
3252            "listPlatformMods",
3253            "()Ljava/lang/String;",
3254            &[],
3255        ) {
3256            if let Ok(obj) = val.l() {
3257                if !obj.as_raw().is_null() {
3258                    if let Ok(js) = env.get_string(&obj.into()) {
3259                        for line in String::from(js).lines() {
3260                            if !line.trim().is_empty() {
3261                                lines.push(format!("platform\t{line}"));
3262                            }
3263                        }
3264                    }
3265                }
3266            }
3267        } else {
3268            env.exception_clear().ok();
3269        }
3270    }
3271    YogOwnedStr::from_string(lines.join("\n"))
3272}
3273
3274unsafe extern "C" fn api_register_menu_entry(ctx: *mut c_void, label: YogStr, ui_id: YogStr) {
3275    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3276    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3277    let l = unsafe { label.as_str().to_owned() };
3278    let u = unsafe { ui_id.as_str().to_owned() };
3279    handlers.menu_entries.push((l, u));
3280}
3281
3282#[no_mangle]
3283pub extern "system" fn Java_dev_yog_NativeBridge_nativeBookJson<'l>(
3284    mut env: JNIEnv<'l>,
3285    _class: JClass<'l>,
3286    book_id: JString<'l>,
3287) -> jstring {
3288    let id = match env.get_string(&book_id) {
3289        Ok(s) => String::from(s),
3290        Err(_) => return std::ptr::null_mut(),
3291    };
3292    let json = handlers()
3293        .books
3294        .get(&id)
3295        .cloned()
3296        .unwrap_or_else(|| "null".to_string());
3297    env.new_string(json)
3298        .map(|s| s.into_raw())
3299        .unwrap_or(std::ptr::null_mut())
3300}
3301
3302// ── Table constructors ────────────────────────────────────────────────────────
3303
3304fn build_server_table() -> YogServer {
3305    YogServer {
3306        ctx: std::ptr::null_mut(),
3307        abi_version: ABI_VERSION,
3308        size: std::mem::size_of::<YogServer>() as u32,
3309        free_str: yog_free_str,
3310        broadcast: srv_broadcast,
3311        get_block: srv_get_block,
3312        set_block: srv_set_block,
3313        world_time: srv_world_time,
3314        set_time: srv_set_time,
3315        is_raining: srv_is_raining,
3316        set_weather: srv_set_weather,
3317        give_item: srv_give_item,
3318        player_teleport: srv_player_teleport,
3319        send_to_player: srv_send_to_player,
3320        send_to_server: srv_send_to_server,
3321        kick_player: srv_kick_player,
3322        set_gamemode: srv_set_gamemode,
3323        send_title: srv_send_title,
3324        send_actionbar: srv_send_actionbar,
3325        play_sound: srv_play_sound,
3326        play_sound_player: srv_play_sound_player,
3327        entity_teleport: srv_entity_teleport,
3328        entity_position: srv_entity_position,
3329        entity_rotation: srv_entity_rotation,
3330        entity_health: srv_entity_health,
3331        entity_set_health: srv_entity_set_health,
3332        entity_kill: srv_entity_kill,
3333        spawn_entity: srv_spawn_entity,
3334        entity_add_effect: srv_entity_add_effect,
3335        entity_remove_effect: srv_entity_remove_effect,
3336        entity_clear_effects: srv_entity_clear_effects,
3337        entity_velocity: srv_entity_velocity,
3338        entity_set_velocity: srv_entity_set_velocity,
3339        entity_add_velocity: srv_entity_add_velocity,
3340        has_item_tag: srv_has_item_tag,
3341        has_block_tag: srv_has_block_tag,
3342        drop_loot: srv_drop_loot,
3343        scoreboard_get: srv_scoreboard_get,
3344        scoreboard_set: srv_scoreboard_set,
3345        scoreboard_add: srv_scoreboard_add,
3346        bossbar_create: srv_bossbar_create,
3347        bossbar_remove: srv_bossbar_remove,
3348        bossbar_set_title: srv_bossbar_set_title,
3349        bossbar_set_progress: srv_bossbar_set_progress,
3350        bossbar_set_color: srv_bossbar_set_color,
3351        bossbar_add_player: srv_bossbar_add_player,
3352        bossbar_remove_player: srv_bossbar_remove_player,
3353        bossbar_set_visible: srv_bossbar_set_visible,
3354        game_dir: srv_game_dir,
3355        get_block_nbt: srv_get_block_nbt,
3356        set_block_nbt: srv_set_block_nbt,
3357        get_inventory_slot: srv_get_inventory_slot,
3358        set_inventory_slot: srv_set_inventory_slot,
3359        player_inventory: srv_player_inventory,
3360        player_set_slot: srv_player_set_slot,
3361        player_teleport_dim: srv_player_teleport_dim,
3362        entity_teleport_dim: srv_entity_teleport_dim,
3363        online_players: srv_online_players,
3364        world_entity_count: srv_world_entity_count,
3365        entity_get_nbt: srv_entity_get_nbt,
3366        entity_set_nbt: srv_entity_set_nbt,
3367        spawn_particles: srv_spawn_particles,
3368        entity_attribute_get: srv_entity_attribute_get,
3369        entity_attribute_set: srv_entity_attribute_set,
3370        get_held_item_nbt: srv_get_held_item_nbt,
3371        set_held_item_nbt: srv_set_held_item_nbt,
3372        get_offhand_item_nbt: srv_get_offhand_item_nbt,
3373        set_offhand_item_nbt: srv_set_offhand_item_nbt,
3374        get_slot_item: srv_get_slot_item,
3375        set_slot_item: srv_set_slot_item,
3376    }
3377}
3378
3379// ── Inter-mod communication ──────────────────────────────────────────────────
3380
3381unsafe extern "C" fn interop_export_impl(
3382    _ctx: *mut c_void,
3383    mod_id: YogStr,
3384    symbol: YogStr,
3385    ptr: *const c_void,
3386) {
3387    let mod_id = mod_id.as_str();
3388    let sym = symbol.as_str();
3389    let registry = INTEROP_SYMBOLS.get_or_init(|| Mutex::new(HashMap::new()));
3390    registry
3391        .lock()
3392        .expect("interop symbols lock poisoned")
3393        .entry(mod_id.to_string())
3394        .or_default()
3395        .insert(sym.to_string(), ptr as usize);
3396}
3397
3398unsafe extern "C" fn interop_import_impl(
3399    _ctx: *mut c_void,
3400    mod_id: YogStr,
3401    symbol: YogStr,
3402) -> *const c_void {
3403    let mod_id = mod_id.as_str();
3404    let sym = symbol.as_str();
3405    let registry = INTEROP_SYMBOLS.get_or_init(|| Mutex::new(HashMap::new()));
3406    registry
3407        .lock()
3408        .expect("interop symbols lock poisoned")
3409        .get(mod_id)
3410        .and_then(|m: &HashMap<String, usize>| m.get(sym))
3411        .map(|&ptr| ptr as *const c_void)
3412        .unwrap_or(std::ptr::null())
3413}
3414
3415fn build_api_table(ctx: *const RwLock<RuntimeHandlers>, server: *const YogServer) -> YogApi {
3416    YogApi {
3417        abi_version: ABI_VERSION,
3418        size: std::mem::size_of::<YogApi>() as u32,
3419        ctx: ctx as *mut c_void,
3420        server,
3421        on_block_break: api_on_block_break,
3422        on_chat: api_on_chat,
3423        on_player_join: api_on_player_join,
3424        on_player_leave: api_on_player_leave,
3425        on_use_item: api_on_use_item,
3426        on_use_block: api_on_use_block,
3427        on_attack_entity: api_on_attack_entity,
3428        on_entity_damage: api_on_entity_damage,
3429        on_entity_death: api_on_entity_death,
3430        on_entity_spawn: api_on_entity_spawn,
3431        on_player_place_block: api_on_player_place_block,
3432        on_player_death: api_on_player_death,
3433        on_player_respawn: api_on_player_respawn,
3434        on_advancement: api_on_advancement,
3435        on_entity_interact: api_on_entity_interact,
3436        on_item_craft: api_on_item_craft,
3437        on_explosion: api_on_explosion,
3438        on_item_pickup: api_on_item_pickup,
3439        on_player_move: api_on_player_move,
3440        on_container_open: api_on_container_open,
3441        on_container_close: api_on_container_close,
3442        on_projectile_hit: api_on_projectile_hit,
3443        on_server_tick: api_on_server_tick,
3444        on_server_started: api_on_server_started,
3445        on_server_stopping: api_on_server_stopping,
3446        on_packet: api_on_packet,
3447        on_client_packet: api_on_client_packet,
3448        register_command: api_register_command,
3449        register_typed_command: api_register_typed_command,
3450        register_recipe_json: api_register_recipe_json,
3451        register_item: api_register_item,
3452        register_block: api_register_block,
3453        schedule_once: api_schedule_once,
3454        schedule_repeating: api_schedule_repeating,
3455        on_client_tick: api_on_client_tick,
3456        on_hud_render: api_on_hud_render,
3457        on_key_press: api_on_key_press,
3458        on_screen_open: api_on_screen_open,
3459        on_screen_close: api_on_screen_close,
3460        on_world_render: api_on_world_render,
3461        register_startup_grant: api_register_startup_grant,
3462        register_book: api_register_book,
3463        register_ui: api_register_ui,
3464        on_ui_render: api_on_ui_render,
3465        register_menu_entry: api_register_menu_entry,
3466        mods_list: api_mods_list,
3467        free_str: yog_free_str,
3468        ui_open: api_ui_open,
3469        register_inventory: api_register_inventory,
3470        interop_export: interop_export_impl,
3471        interop_import: interop_import_impl,
3472        register_dimension_json: api_register_dimension_json,
3473        register_chunk_generator: api_register_chunk_generator,
3474        ui_close: api_ui_close,
3475        ui_consume_event: api_ui_consume_event,
3476        translate: api_translate,
3477    }
3478}
3479
3480// ── Mod loading ───────────────────────────────────────────────────────────────
3481
3482fn platform_tag() -> String {
3483    format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH)
3484}
3485
3486type AbiVersionFn = unsafe extern "C" fn() -> u32;
3487/// Second arg is a null-terminated C string: the mod's `id` from its manifest.
3488type RegisterFn = unsafe extern "C" fn(*const YogApi, *const std::os::raw::c_char);
3489
3490fn load_mods(dir: &Path, api: &YogApi) {
3491    let entries = match std::fs::read_dir(dir) {
3492        Ok(e) => e,
3493        Err(_) => {
3494            yog_logging::info!("no mods directory at {} — none loaded", dir.display());
3495            return;
3496        }
3497    };
3498
3499    // First pass: collect (mod_id, dependencies, archive_path)
3500    struct ModMeta {
3501        id: String,
3502        deps: Vec<String>,
3503        yog_path: PathBuf,
3504    }
3505    let mut metas: Vec<ModMeta> = Vec::new();
3506    for entry in entries.flatten() {
3507        let path = entry.path();
3508        if path.extension().and_then(|e| e.to_str()) != Some("yog") {
3509            continue;
3510        }
3511        let info = read_mod_info(&path);
3512        let deps = read_mod_deps(&path);
3513        metas.push(ModMeta {
3514            id: info[0].clone(),
3515            deps,
3516            yog_path: path,
3517        });
3518    }
3519
3520    // Topological sort by dependencies (Kahn's algorithm)
3521    let ids: Vec<String> = metas.iter().map(|m| m.id.clone()).collect();
3522    let deps_list: Vec<Vec<String>> = metas.iter().map(|m| m.deps.clone()).collect();
3523    let sorted = match topo_sort_mods(&ids, &deps_list) {
3524        Some(v) => v,
3525        None => {
3526            yog_logging::error!("circular dependency detected — loading in file order");
3527            (0..metas.len()).collect()
3528        }
3529    };
3530
3531    let mut loaded: Vec<LoadedModule> = Vec::new();
3532    for idx in sorted {
3533        let meta = &metas[idx];
3534        let lib_path = match extract_yog(&meta.yog_path) {
3535            Some(p) => p,
3536            None => {
3537                yog_logging::error!(
3538                    "no native for {} in {}",
3539                    platform_tag(),
3540                    meta.yog_path.display()
3541                );
3542                continue;
3543            }
3544        };
3545        if let Some(module) = load_mod_lib(&lib_path, api, &meta.id) {
3546            loaded.push(module);
3547            MOD_INFOS
3548                .lock()
3549                .expect("mod infos lock poisoned")
3550                .push(read_mod_info(&meta.yog_path));
3551        }
3552    }
3553    yog_logging::info!("loaded {} mod(s) from {}", loaded.len(), dir.display());
3554
3555    // Final import resolution pass — after all mods loaded, each mod's pending
3556    // imports can be resolved against the now-complete interop table.
3557    resolve_all_imports(api, &loaded);
3558}
3559
3560/// After all mods loaded, call `__yog_resolve_imports_final` on each library
3561/// to resolve any imports that weren't satisfied during initial registration.
3562fn resolve_all_imports(api: &YogApi, loaded: &[LoadedModule]) {
3563    for module in loaded {
3564        module.with_library(|lib| unsafe {
3565            type ResolveFn = unsafe extern "C" fn(*const YogApi);
3566            if let Ok(resolve) = lib.get::<ResolveFn>(b"__yog_resolve_imports_final") {
3567                resolve(api as *const YogApi);
3568            }
3569        });
3570    }
3571}
3572
3573/// Kahn's algorithm — returns indices in dependency order, or None on cycle.
3574fn topo_sort_mods(ids: &[String], deps_list: &[Vec<String>]) -> Option<Vec<usize>> {
3575    let n = ids.len();
3576    let name_to_idx: HashMap<&str, usize> = ids
3577        .iter()
3578        .enumerate()
3579        .map(|(i, id)| (id.as_str(), i))
3580        .collect();
3581    let mut in_degree = vec![0u32; n];
3582    let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];
3583    for (i, deps) in deps_list.iter().enumerate() {
3584        for dep in deps {
3585            if let Some(&j) = name_to_idx.get(dep.as_str()) {
3586                adj[j].push(i);
3587                in_degree[i] += 1;
3588            }
3589        }
3590    }
3591    let mut queue: Vec<usize> = (0..n).filter(|&i| in_degree[i] == 0).collect();
3592    let mut order = Vec::with_capacity(n);
3593    while let Some(u) = queue.pop() {
3594        order.push(u);
3595        for &v in &adj[u] {
3596            in_degree[v] -= 1;
3597            if in_degree[v] == 0 {
3598                queue.push(v);
3599            }
3600        }
3601    }
3602    if order.len() == n {
3603        Some(order)
3604    } else {
3605        None
3606    }
3607}
3608
3609/// Loads `path` as a fresh generation of `mod_id` via the shared
3610/// `HotReloader`, validates its ABI, and calls its `yog_mod_register` —
3611/// tagging every handler it registers with the returned `LoadedModule` (see
3612/// `current_registration()`). On any failure the module (if it got as far
3613/// as being tracked by the `HotReloader`) is retired immediately: nothing
3614/// can be executing inside a library that never successfully registered,
3615/// so this always hard-unloads right away rather than lingering.
3616fn load_mod_lib(path: &Path, api: &YogApi, mod_id: &str) -> Option<LoadedModule> {
3617    let module = match unsafe { hot_reloader().load_initial(mod_id, path) } {
3618        Ok(m) => m,
3619        Err(e) => {
3620            yog_logging::error!("failed to load {}: {}", path.display(), e);
3621            return None;
3622        }
3623    };
3624
3625    let abi = module.with_library(|lib| unsafe {
3626        let abi: Symbol<AbiVersionFn> = lib.get(b"yog_abi_version").ok()?;
3627        Some(abi())
3628    });
3629    match abi.flatten() {
3630        Some(v) if v == ABI_VERSION => {}
3631        Some(v) => {
3632            yog_logging::error!(
3633                "{}: ABI {} incompatible with runtime ABI {}",
3634                path.display(),
3635                v,
3636                ABI_VERSION
3637            );
3638            module.retire(|| {});
3639            return None;
3640        }
3641        None => {
3642            yog_logging::error!("{} is not a Yog mod (no yog_abi_version)", path.display());
3643            module.retire(|| {});
3644            return None;
3645        }
3646    }
3647
3648    if let Err(e) = invoke_mod_register(&module, api, mod_id) {
3649        yog_logging::error!("{}: {}", path.display(), e);
3650        module.retire(|| {});
3651        return None;
3652    }
3653
3654    Some(module)
3655}
3656
3657/// Calls a loaded module's `yog_mod_register`, tagging everything it
3658/// registers with `module` via `CURRENT_REGISTRATION` for the duration of
3659/// the call — used for both a mod's initial load and a later hot-reload.
3660fn invoke_mod_register(module: &LoadedModule, api: &YogApi, mod_id: &str) -> Result<(), String> {
3661    module
3662        .with_library(|lib| unsafe {
3663            let register: Symbol<RegisterFn> = lib
3664                .get(b"yog_mod_register")
3665                .map_err(|_| "missing yog_mod_register".to_string())?;
3666            let mod_id_c = std::ffi::CString::new(mod_id).unwrap();
3667            *CURRENT_REGISTRATION.lock().unwrap() = Some(module.clone());
3668            register(api as *const YogApi, mod_id_c.as_ptr());
3669            *CURRENT_REGISTRATION.lock().unwrap() = None;
3670            Ok(())
3671        })
3672        .unwrap_or_else(|| Err("module was unloaded before registration could run".to_string()))
3673}
3674
3675/// Metadata for a mod file: [id, name, version, authors, description,
3676/// name_key, description_key].
3677/// For .yog archives this comes from the bundled yog.toml; bare native libs
3678/// fall back to the file stem.
3679fn read_mod_info(path: &Path) -> [String; 7] {
3680    let stem = path
3681        .file_stem()
3682        .map(|s| s.to_string_lossy().into_owned())
3683        .unwrap_or_default();
3684    let mut info = [
3685        stem.clone(),
3686        stem,
3687        String::new(),
3688        String::new(),
3689        String::new(),
3690        String::new(),
3691        String::new(),
3692    ];
3693    if path.extension().and_then(|e| e.to_str()) != Some("yog") {
3694        return info;
3695    }
3696    let Some(text) = (|| {
3697        let file = std::fs::File::open(path).ok()?;
3698        let mut archive = zip::ZipArchive::new(file).ok()?;
3699        let mut entry = archive.by_name("yog.toml").ok()?;
3700        let mut text = String::new();
3701        std::io::Read::read_to_string(&mut entry, &mut text).ok()?;
3702        Some(text)
3703    })() else {
3704        return info;
3705    };
3706    // Minimal parse — enough for id/name/version/description/authors without
3707    // pulling in a TOML dependency. Source manifests keep these under [mod];
3708    // the packaged manifest (written by yog-cli) has them at top level, so
3709    // keys before any section header count too.
3710    let mut in_mod = true;
3711    for line in text.lines() {
3712        let line = line.trim();
3713        if line.starts_with('[') {
3714            in_mod = line == "[mod]";
3715            continue;
3716        }
3717        if !in_mod {
3718            continue;
3719        }
3720        let Some((key, value)) = line.split_once('=') else {
3721            continue;
3722        };
3723        let key = key.trim();
3724        let value = value.trim();
3725        let unquote = |v: &str| v.trim().trim_matches('"').to_string();
3726        match key {
3727            "id" => info[0] = tsv_clean(&unquote(value)),
3728            "name" => info[1] = tsv_clean(&unquote(value)),
3729            "version" => info[2] = tsv_clean(&unquote(value)),
3730            "description" => info[4] = tsv_clean(&unquote(value)),
3731            "name_key" => info[5] = unquote(value),
3732            "description_key" => info[6] = unquote(value),
3733            "authors" => {
3734                let list = value.trim_start_matches('[').trim_end_matches(']');
3735                let authors: Vec<String> = list
3736                    .split(',')
3737                    .map(unquote)
3738                    .filter(|a| !a.is_empty())
3739                    .collect();
3740                info[3] = tsv_clean(&authors.join(", "));
3741            }
3742            _ => {}
3743        }
3744    }
3745    info
3746}
3747
3748/// Parse `[dependencies]` section from yog.toml inside a .yog archive.
3749fn read_mod_deps(path: &Path) -> Vec<String> {
3750    if path.extension().and_then(|e| e.to_str()) != Some("yog") {
3751        return Vec::new();
3752    }
3753    let text = (|| {
3754        let file = std::fs::File::open(path).ok()?;
3755        let mut archive = zip::ZipArchive::new(file).ok()?;
3756        let mut entry = archive.by_name("yog.toml").ok()?;
3757        let mut text = String::new();
3758        std::io::Read::read_to_string(&mut entry, &mut text).ok()?;
3759        Some(text)
3760    })();
3761    let Some(text) = text else { return Vec::new() };
3762    let mut deps = Vec::new();
3763    let mut in_deps = false;
3764    for line in text.lines() {
3765        let line = line.trim();
3766        if line.starts_with('[') {
3767            in_deps = line == "[dependencies]";
3768            continue;
3769        }
3770        if !in_deps {
3771            continue;
3772        }
3773        // `mod_id = "1.0"` or `mod_id = "*"` — we only care about the key (mod_id)
3774        if let Some((key, _)) = line.split_once('=') {
3775            deps.push(key.trim().to_string());
3776        }
3777    }
3778    deps
3779}
3780
3781fn extract_yog(path: &Path) -> Option<PathBuf> {
3782    let file = std::fs::File::open(path).ok()?;
3783    let mut archive = zip::ZipArchive::new(file).ok()?;
3784    let prefix = format!("natives/{}/", platform_tag());
3785    let mut entry_name = None;
3786    for i in 0..archive.len() {
3787        let f = archive.by_index(i).ok()?;
3788        if f.name().starts_with(&prefix) && !f.name().ends_with('/') {
3789            entry_name = Some(f.name().to_string());
3790            break;
3791        }
3792    }
3793    let entry_name = entry_name?;
3794    let ext = Path::new(&entry_name)
3795        .extension()
3796        .and_then(|e| e.to_str())
3797        .unwrap_or("bin");
3798    let stem = path.file_stem()?.to_string_lossy().into_owned();
3799    // A fresh name per extraction: a hot reload must never truncate the
3800    // library the game still has mapped, and `dlopen` of an already-loaded
3801    // path would just hand back the old module.
3802    static EXTRACTIONS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
3803    let n = EXTRACTIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3804    let out =
3805        std::env::temp_dir().join(format!("yog-{}-{}-{}.{}", stem, std::process::id(), n, ext));
3806    let mut entry = archive.by_name(&entry_name).ok()?;
3807    let mut out_file = std::fs::File::create(&out).ok()?;
3808    std::io::copy(&mut entry, &mut out_file).ok()?;
3809    Some(out)
3810}
3811
3812// ── Dispatcher helpers ────────────────────────────────────────────────────────
3813
3814fn srv_ptr() -> *const YogServer {
3815    SERVER.get().expect("yog: SERVER not initialised") as *const YogServer
3816}
3817
3818// ── JNI entry points ──────────────────────────────────────────────────────────
3819
3820#[no_mangle]
3821pub extern "system" fn Java_dev_yog_NativeBridge_nativeInit<'l>(
3822    mut env: JNIEnv<'l>,
3823    _class: JClass<'l>,
3824    mods_dir: JString<'l>,
3825) {
3826    if let Ok(vm) = env.get_java_vm() {
3827        let _ = JAVA_VM.set(vm);
3828    }
3829
3830    let dir = env
3831        .get_string(&mods_dir)
3832        .map(String::from)
3833        .unwrap_or_default();
3834
3835    // Build YogServer and store in static (gets a stable address).
3836    let _ = SERVER.set(build_server_table());
3837    let server_ptr = SERVER.get().unwrap() as *const YogServer;
3838
3839    // Publish HANDLERS *before* any mod registers — its address is then
3840    // `'static`-stable for the runtime's entire lifetime, unlike the old
3841    // design (a temporary heap `Box` moved into `HANDLERS` only after
3842    // `nativeInit` returned, silently invalidating the `ctx` pointer any
3843    // later re-registration — e.g. a hot-reload — would have needed).
3844    let handlers_lock = HANDLERS.get_or_init(|| RwLock::new(RuntimeHandlers::new()));
3845    let handlers_ptr = handlers_lock as *const RwLock<RuntimeHandlers>;
3846
3847    let api: &'static YogApi = API_TABLE.get_or_init(|| build_api_table(handlers_ptr, server_ptr));
3848
3849    let _ = HOT_RELOADER.get_or_init(|| HotReloader::new(RuntimeModuleRegistry));
3850
3851    guard("mod loading", || {
3852        load_mods(Path::new(&dir), api);
3853    });
3854
3855    control_socket::start_if_requested();
3856
3857    yog_logging::info!("runtime initialised — the gate is open.");
3858}
3859
3860#[no_mangle]
3861pub extern "system" fn Java_dev_yog_NativeBridge_nativeHotReload<'l>(
3862    mut env: JNIEnv<'l>,
3863    _class: JClass<'l>,
3864    mod_id: JString<'l>,
3865    new_yog_path: JString<'l>,
3866) -> jni::sys::jboolean {
3867    let Ok(mod_id) = env.get_string(&mod_id).map(String::from) else {
3868        return 0;
3869    };
3870    let Ok(yog_path) = env.get_string(&new_yog_path).map(String::from) else {
3871        return 0;
3872    };
3873    let ok = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
3874        trigger_hot_reload(&mod_id, Path::new(&yog_path))
3875    }))
3876    .unwrap_or(false);
3877    ok as jni::sys::jboolean
3878}
3879
3880/// Rebuilds and re-registers `mod_id` from a freshly built `.yog` at
3881/// `new_yog_path`: extracts the current platform's native, loads it as a
3882/// new generation via the shared `HotReloader` (which retires the previous
3883/// generation per its hybrid soft/hard-unload policy — hard-unloaded right
3884/// away if nothing's mid-call, deferred otherwise), then calls its
3885/// `yog_mod_register` again so its handlers get tagged under the new
3886/// generation. How this actually gets triggered — a keybind, a file-watch,
3887/// an IDE-driven socket — is a separate, later concern; this only needs to
3888/// work correctly once called.
3889fn trigger_hot_reload(mod_id: &str, new_yog_path: &Path) -> bool {
3890    let Some(native_path) = extract_yog(new_yog_path) else {
3891        yog_logging::error!(
3892            "hot-reload {}: no native for {} in {}",
3893            mod_id,
3894            platform_tag(),
3895            new_yog_path.display()
3896        );
3897        return false;
3898    };
3899
3900    let api = API_TABLE.get().expect("yog: nativeInit not called yet");
3901
3902    let module = match unsafe { hot_reloader().reload(mod_id, &native_path) } {
3903        Ok(m) => m,
3904        Err(e) => {
3905            yog_logging::error!(
3906                "hot-reload {}: failed to load {}: {}",
3907                mod_id,
3908                native_path.display(),
3909                e
3910            );
3911            return false;
3912        }
3913    };
3914
3915    let abi = module.with_library(|lib| unsafe {
3916        let abi: Symbol<AbiVersionFn> = lib.get(b"yog_abi_version").ok()?;
3917        Some(abi())
3918    });
3919    match abi.flatten() {
3920        Some(v) if v == ABI_VERSION => {}
3921        other => {
3922            yog_logging::error!(
3923                "hot-reload {}: ABI {:?} incompatible with runtime ABI {} — mod has no active handlers until a compatible reload succeeds",
3924                mod_id,
3925                other,
3926                ABI_VERSION
3927            );
3928            return false;
3929        }
3930    }
3931
3932    if let Err(e) = invoke_mod_register(&module, api, mod_id) {
3933        yog_logging::error!("hot-reload {}: {}", mod_id, e);
3934        return false;
3935    }
3936
3937    yog_logging::info!("hot-reloaded mod {}", mod_id);
3938    true
3939}
3940
3941#[no_mangle]
3942pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnBlockBreak<'l>(
3943    mut env: JNIEnv<'l>,
3944    _class: JClass<'l>,
3945    player: JString<'l>,
3946    block: JString<'l>,
3947    x: jint,
3948    y: jint,
3949    z: jint,
3950    dimension: JString<'l>,
3951) {
3952    let (p, b, d) = (jstr!(env, player), jstr!(env, block), jstr!(env, dimension));
3953    let ev = yog_abi::YogBlockBreakEvent {
3954        player: YogStr::from_str(&p),
3955        block: YogStr::from_str(&b),
3956        pos: YogBlockPos { x, y, z },
3957        dimension: YogStr::from_str(&d),
3958    };
3959    let srv = srv_ptr();
3960    guard("on_block_break", || {
3961        for (module, ud, f) in &handlers().block_break {
3962            if module.is_retiring() {
3963                continue;
3964            }
3965            let Some(_call) = module.enter() else {
3966                continue;
3967            };
3968            unsafe { f(*ud, srv, &ev, 1) };
3969        }
3970    });
3971}
3972
3973#[no_mangle]
3974pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnChat<'l>(
3975    mut env: JNIEnv<'l>,
3976    _class: JClass<'l>,
3977    player: JString<'l>,
3978    message: JString<'l>,
3979    dimension: JString<'l>,
3980) {
3981    let (p, m, d) = (
3982        jstr!(env, player),
3983        jstr!(env, message),
3984        jstr!(env, dimension),
3985    );
3986    let ev = yog_abi::YogChatEvent {
3987        player: YogStr::from_str(&p),
3988        message: YogStr::from_str(&m),
3989        dimension: YogStr::from_str(&d),
3990    };
3991    let srv = srv_ptr();
3992    guard("on_chat", || {
3993        for (module, ud, f) in &handlers().chat {
3994            if module.is_retiring() {
3995                continue;
3996            }
3997            let Some(_call) = module.enter() else {
3998                continue;
3999            };
4000            unsafe { f(*ud, srv, &ev, 1) };
4001        }
4002    });
4003}
4004
4005#[no_mangle]
4006pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerJoin<'l>(
4007    mut env: JNIEnv<'l>,
4008    _class: JClass<'l>,
4009    player: JString<'l>,
4010    uuid: JString<'l>,
4011    dimension: JString<'l>,
4012) {
4013    let (p, u, d) = (jstr!(env, player), jstr!(env, uuid), jstr!(env, dimension));
4014    let ev = yog_abi::YogPlayerEvent {
4015        player: YogStr::from_str(&p),
4016        uuid: YogStr::from_str(&u),
4017        dimension: YogStr::from_str(&d),
4018    };
4019    let srv = srv_ptr();
4020    guard("on_player_join", || {
4021        for (module, ud, f) in &handlers().player_join {
4022            if module.is_retiring() {
4023                continue;
4024            }
4025            let Some(_call) = module.enter() else {
4026                continue;
4027            };
4028            unsafe { f(*ud, srv, &ev, 1) };
4029        }
4030    });
4031    // Queue startup grants: giving items directly inside the join callback
4032    // fails for the host of a freshly created world (player not fully in the
4033    // world yet), so grants are processed a few server ticks later.
4034    let h = handlers();
4035    if !h.startup_grants.is_empty() {
4036        h.pending_grants
4037            .lock()
4038            .expect("pending_grants poisoned")
4039            .push((p, u, 0));
4040    }
4041}
4042
4043/// Try to fulfil pending startup grants. Called each server tick; a grant is
4044/// only marked as given (and persisted) after `give_item` actually succeeds.
4045fn process_pending_grants() {
4046    let h = handlers();
4047    let mut pending = match h.pending_grants.try_lock() {
4048        Ok(g) => g,
4049        Err(_) => return,
4050    };
4051    if pending.is_empty() {
4052        return;
4053    }
4054    // Wait a couple of ticks after join before the first attempt.
4055    const FIRST_TRY_TICK: u32 = 2;
4056    // Give up after 30 seconds — the player probably left.
4057    const MAX_TICKS: u32 = 600;
4058
4059    let mut granted = h.startup_granted.lock().expect("startup_granted poisoned");
4060    let mut still_pending = Vec::new();
4061    let mut any_new = false;
4062
4063    for (p, u, ticks) in pending.drain(..) {
4064        if ticks < FIRST_TRY_TICK {
4065            still_pending.push((p, u, ticks + 1));
4066            continue;
4067        }
4068        let mut all_ok = true;
4069        for sg in &h.startup_grants {
4070            let key = format!("{}::{}", u, sg.id);
4071            if granted.contains_key(&key) {
4072                continue;
4073            }
4074            let mut ok = true;
4075            for item_id in &sg.items {
4076                ok &= unsafe {
4077                    srv_give_item(
4078                        std::ptr::null_mut(),
4079                        YogStr::from_str(&p),
4080                        YogStr::from_str(item_id),
4081                        1,
4082                    )
4083                };
4084            }
4085            if let Some(_book) = &sg.book {
4086                ok &= unsafe {
4087                    srv_give_item(
4088                        std::ptr::null_mut(),
4089                        YogStr::from_str(&p),
4090                        YogStr::from_str("minecraft:written_book"),
4091                        1,
4092                    )
4093                };
4094            }
4095            if ok {
4096                yog_logging::info!("startup grant {} given to {}", sg.id, p);
4097                granted.insert(key, true);
4098                any_new = true;
4099            } else {
4100                all_ok = false;
4101            }
4102        }
4103        if !all_ok && ticks < MAX_TICKS {
4104            still_pending.push((p, u, ticks + 1));
4105        }
4106    }
4107    *pending = still_pending;
4108    if any_new {
4109        save_startup_granted(&granted);
4110    }
4111}
4112
4113#[no_mangle]
4114pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerLeave<'l>(
4115    mut env: JNIEnv<'l>,
4116    _class: JClass<'l>,
4117    player: JString<'l>,
4118    uuid: JString<'l>,
4119    dimension: JString<'l>,
4120) {
4121    let (p, u, d) = (jstr!(env, player), jstr!(env, uuid), jstr!(env, dimension));
4122    let ev = yog_abi::YogPlayerEvent {
4123        player: YogStr::from_str(&p),
4124        uuid: YogStr::from_str(&u),
4125        dimension: YogStr::from_str(&d),
4126    };
4127    let srv = srv_ptr();
4128    guard("on_player_leave", || {
4129        for (module, ud, f) in &handlers().player_leave {
4130            if module.is_retiring() {
4131                continue;
4132            }
4133            let Some(_call) = module.enter() else {
4134                continue;
4135            };
4136            unsafe { f(*ud, srv, &ev, 1) };
4137        }
4138    });
4139}
4140
4141#[no_mangle]
4142pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseItem<'l>(
4143    mut env: JNIEnv<'l>,
4144    _class: JClass<'l>,
4145    player: JString<'l>,
4146    item: JString<'l>,
4147    sneaking: jni::sys::jboolean,
4148    dimension: JString<'l>,
4149) {
4150    let (p, i, d) = (jstr!(env, player), jstr!(env, item), jstr!(env, dimension));
4151    let ev = yog_abi::YogUseItemEvent {
4152        player: YogStr::from_str(&p),
4153        item: YogStr::from_str(&i),
4154        sneaking: sneaking != 0,
4155        dimension: YogStr::from_str(&d),
4156    };
4157    let srv = srv_ptr();
4158    guard("on_use_item", || {
4159        for (module, ud, f) in &handlers().use_item {
4160            if module.is_retiring() {
4161                continue;
4162            }
4163            let Some(_call) = module.enter() else {
4164                continue;
4165            };
4166            unsafe { f(*ud, srv, &ev, 1) };
4167        }
4168    });
4169}
4170
4171#[no_mangle]
4172pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseItemPre<'l>(
4173    mut env: JNIEnv<'l>,
4174    _class: JClass<'l>,
4175    player: JString<'l>,
4176    item: JString<'l>,
4177    sneaking: jni::sys::jboolean,
4178    dimension: JString<'l>,
4179) -> jni::sys::jboolean {
4180    let h = handlers();
4181    if h.use_item.is_empty() {
4182        return 1;
4183    }
4184    let p = match env.get_string(&player) {
4185        Ok(s) => String::from(s),
4186        Err(_) => return 1,
4187    };
4188    let i = match env.get_string(&item) {
4189        Ok(s) => String::from(s),
4190        Err(_) => return 1,
4191    };
4192    let d = match env.get_string(&dimension) {
4193        Ok(s) => String::from(s),
4194        Err(_) => return 1,
4195    };
4196    let ev = yog_abi::YogUseItemEvent {
4197        player: YogStr::from_str(&p),
4198        item: YogStr::from_str(&i),
4199        sneaking: sneaking != 0,
4200        dimension: YogStr::from_str(&d),
4201    };
4202    let srv = srv_ptr();
4203    let mut allow = true;
4204    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4205        for (module, ud, f) in &h.use_item {
4206            if module.is_retiring() {
4207                continue;
4208            }
4209            let Some(_call) = module.enter() else {
4210                continue;
4211            };
4212            if !unsafe { f(*ud, srv, &ev, 0) } {
4213                allow = false;
4214                break;
4215            }
4216        }
4217    }))
4218    .ok();
4219    allow as jni::sys::jboolean
4220}
4221
4222#[no_mangle]
4223pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseBlock<'l>(
4224    mut env: JNIEnv<'l>,
4225    _class: JClass<'l>,
4226    player: JString<'l>,
4227    block: JString<'l>,
4228    x: jint,
4229    y: jint,
4230    z: jint,
4231    dimension: JString<'l>,
4232) {
4233    let (p, b, d) = (jstr!(env, player), jstr!(env, block), jstr!(env, dimension));
4234    let ev = yog_abi::YogUseBlockEvent {
4235        player: YogStr::from_str(&p),
4236        block: YogStr::from_str(&b),
4237        pos: YogBlockPos { x, y, z },
4238        dimension: YogStr::from_str(&d),
4239    };
4240    let srv = srv_ptr();
4241    guard("on_use_block", || {
4242        for (module, ud, f) in &handlers().use_block {
4243            if module.is_retiring() {
4244                continue;
4245            }
4246            let Some(_call) = module.enter() else {
4247                continue;
4248            };
4249            unsafe { f(*ud, srv, &ev, 1) };
4250        }
4251    });
4252}
4253
4254#[no_mangle]
4255pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseBlockPre<'l>(
4256    mut env: JNIEnv<'l>,
4257    _class: JClass<'l>,
4258    player: JString<'l>,
4259    block: JString<'l>,
4260    x: jint,
4261    y: jint,
4262    z: jint,
4263    dimension: JString<'l>,
4264) -> jni::sys::jboolean {
4265    let h = handlers();
4266    if h.use_block.is_empty() {
4267        return 1;
4268    }
4269    let p = match env.get_string(&player) {
4270        Ok(s) => String::from(s),
4271        Err(_) => return 1,
4272    };
4273    let b = match env.get_string(&block) {
4274        Ok(s) => String::from(s),
4275        Err(_) => return 1,
4276    };
4277    let d = match env.get_string(&dimension) {
4278        Ok(s) => String::from(s),
4279        Err(_) => return 1,
4280    };
4281    let ev = yog_abi::YogUseBlockEvent {
4282        player: YogStr::from_str(&p),
4283        block: YogStr::from_str(&b),
4284        pos: YogBlockPos { x, y, z },
4285        dimension: YogStr::from_str(&d),
4286    };
4287    let srv = srv_ptr();
4288    let mut allow = true;
4289    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4290        for (module, ud, f) in &h.use_block {
4291            if module.is_retiring() {
4292                continue;
4293            }
4294            let Some(_call) = module.enter() else {
4295                continue;
4296            };
4297            if !unsafe { f(*ud, srv, &ev, 0) } {
4298                allow = false;
4299                break;
4300            }
4301        }
4302    }))
4303    .ok();
4304    allow as jni::sys::jboolean
4305}
4306
4307#[no_mangle]
4308pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnAttackEntity<'l>(
4309    mut env: JNIEnv<'l>,
4310    _class: JClass<'l>,
4311    player: JString<'l>,
4312    target_type: JString<'l>,
4313    target_uuid: JString<'l>,
4314    dimension: JString<'l>,
4315) {
4316    let (p, tt, tu, d) = (
4317        jstr!(env, player),
4318        jstr!(env, target_type),
4319        jstr!(env, target_uuid),
4320        jstr!(env, dimension),
4321    );
4322    let ev = yog_abi::YogAttackEntityEvent {
4323        player: YogStr::from_str(&p),
4324        target_type: YogStr::from_str(&tt),
4325        target_uuid: YogStr::from_str(&tu),
4326        dimension: YogStr::from_str(&d),
4327    };
4328    let srv = srv_ptr();
4329    guard("on_attack_entity", || {
4330        for (module, ud, f) in &handlers().attack_entity {
4331            if module.is_retiring() {
4332                continue;
4333            }
4334            let Some(_call) = module.enter() else {
4335                continue;
4336            };
4337            unsafe { f(*ud, srv, &ev, 1) };
4338        }
4339    });
4340}
4341
4342#[no_mangle]
4343pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityDamage<'l>(
4344    mut env: JNIEnv<'l>,
4345    _class: JClass<'l>,
4346    entity_type: JString<'l>,
4347    uuid: JString<'l>,
4348    amount: jfloat,
4349    source: JString<'l>,
4350    dimension: JString<'l>,
4351) {
4352    let (et, u, s, d) = (
4353        jstr!(env, entity_type),
4354        jstr!(env, uuid),
4355        jstr!(env, source),
4356        jstr!(env, dimension),
4357    );
4358    let ev = yog_abi::YogEntityDamageEvent {
4359        entity_type: YogStr::from_str(&et),
4360        uuid: YogStr::from_str(&u),
4361        amount,
4362        source: YogStr::from_str(&s),
4363        dimension: YogStr::from_str(&d),
4364    };
4365    let srv = srv_ptr();
4366    guard("on_entity_damage", || {
4367        for (module, ud, f) in &handlers().entity_damage {
4368            if module.is_retiring() {
4369                continue;
4370            }
4371            let Some(_call) = module.enter() else {
4372                continue;
4373            };
4374            unsafe { f(*ud, srv, &ev, 1) };
4375        }
4376    });
4377}
4378
4379#[no_mangle]
4380pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityDeath<'l>(
4381    mut env: JNIEnv<'l>,
4382    _class: JClass<'l>,
4383    entity_type: JString<'l>,
4384    uuid: JString<'l>,
4385    source: JString<'l>,
4386    dimension: JString<'l>,
4387) {
4388    let (et, u, s, d) = (
4389        jstr!(env, entity_type),
4390        jstr!(env, uuid),
4391        jstr!(env, source),
4392        jstr!(env, dimension),
4393    );
4394    let ev = yog_abi::YogEntityDeathEvent {
4395        entity_type: YogStr::from_str(&et),
4396        uuid: YogStr::from_str(&u),
4397        source: YogStr::from_str(&s),
4398        dimension: YogStr::from_str(&d),
4399    };
4400    let srv = srv_ptr();
4401    guard("on_entity_death", || {
4402        for (module, ud, f) in &handlers().entity_death {
4403            if module.is_retiring() {
4404                continue;
4405            }
4406            let Some(_call) = module.enter() else {
4407                continue;
4408            };
4409            unsafe { f(*ud, srv, &ev, 1) };
4410        }
4411    });
4412}
4413
4414#[no_mangle]
4415pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnTick<'l>(
4416    _env: JNIEnv<'l>,
4417    _class: JClass<'l>,
4418) {
4419    let h = handlers();
4420    let srv = srv_ptr();
4421    guard("on_tick", || {
4422        for (module, ud, f) in &h.server_tick {
4423            if module.is_retiring() {
4424                continue;
4425            }
4426            let Some(_call) = module.enter() else {
4427                continue;
4428            };
4429            unsafe { f(*ud, srv) };
4430        }
4431    });
4432
4433    guard("startup_grants", process_pending_grants);
4434
4435    // Scheduler — once tasks
4436    {
4437        let mut sched = h.scheduler.lock().expect("scheduler poisoned");
4438        let mut to_fire: Vec<(LoadedModule, *mut c_void, YogScheduledFn)> = Vec::new();
4439        let mut remaining = Vec::new();
4440        for task in sched.once_tasks.drain(..) {
4441            if task.delay_remaining == 0 {
4442                to_fire.push((task.module.clone(), task.ud, task.f));
4443            } else {
4444                remaining.push(OnceTask {
4445                    delay_remaining: task.delay_remaining - 1,
4446                    ..task
4447                });
4448            }
4449        }
4450        sched.once_tasks = remaining;
4451        drop(sched);
4452        for (module, ud, f) in to_fire {
4453            if module.is_retiring() {
4454                continue;
4455            }
4456            let Some(_call) = module.enter() else {
4457                continue;
4458            };
4459            guard("schedule_once", || unsafe { f(ud, srv) });
4460        }
4461    }
4462
4463    // Scheduler — repeating tasks
4464    {
4465        let mut sched = h.scheduler.lock().expect("scheduler poisoned");
4466        let mut to_fire: Vec<(LoadedModule, *mut c_void, YogScheduledFn)> = Vec::new();
4467        for task in &mut sched.repeating_tasks {
4468            if task.ticks_left == 0 {
4469                to_fire.push((task.module.clone(), task.ud, task.f));
4470                task.ticks_left = task.period;
4471            } else {
4472                task.ticks_left -= 1;
4473            }
4474        }
4475        drop(sched);
4476        for (module, ud, f) in to_fire {
4477            if module.is_retiring() {
4478                continue;
4479            }
4480            let Some(_call) = module.enter() else {
4481                continue;
4482            };
4483            guard("schedule_repeating", || unsafe { f(ud, srv) });
4484        }
4485    }
4486}
4487
4488/// Absolute path of the current world save folder (set on server start).
4489static WORLD_DIR: Mutex<Option<std::path::PathBuf>> = Mutex::new(None);
4490
4491/// Per-world data path: `<world>/yog-data/startup_grants.json`.
4492/// Falls back to the working directory before any server has started.
4493fn startup_grants_path() -> std::path::PathBuf {
4494    let base = WORLD_DIR
4495        .lock()
4496        .ok()
4497        .and_then(|d| d.clone())
4498        .unwrap_or_else(|| std::path::PathBuf::from("."));
4499    base.join("yog-data").join("startup_grants.json")
4500}
4501
4502fn load_startup_granted() {
4503    let h = handlers();
4504    let mut granted = h.startup_granted.lock().expect("startup_granted poisoned");
4505    // Reset first — in singleplayer the process outlives individual worlds,
4506    // and grant state is per-world.
4507    granted.clear();
4508    h.pending_grants
4509        .lock()
4510        .expect("pending_grants poisoned")
4511        .clear();
4512    let path = startup_grants_path();
4513    let Ok(data) = std::fs::read_to_string(&path) else {
4514        return;
4515    };
4516    let Ok(keys) = serde_json::from_str::<Vec<String>>(&data) else {
4517        yog_logging::warn!("startup_grants.json: invalid JSON, ignoring");
4518        return;
4519    };
4520    for k in keys {
4521        granted.insert(k, true);
4522    }
4523    yog_logging::info!("loaded {} startup grants from disk", granted.len());
4524}
4525
4526fn save_startup_granted(granted: &HashMap<String, bool>) {
4527    let path = startup_grants_path();
4528    if let Some(parent) = path.parent() {
4529        let _ = std::fs::create_dir_all(parent);
4530    }
4531    let keys: Vec<&String> = granted.keys().collect();
4532    match serde_json::to_string(&keys) {
4533        Ok(json) => {
4534            let _ = std::fs::write(&path, json);
4535        }
4536        Err(e) => yog_logging::error!("failed to save startup_grants.json: {}", e),
4537    }
4538}
4539
4540#[no_mangle]
4541pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnServerStarted<'l>(
4542    mut env: JNIEnv<'l>,
4543    _class: JClass<'l>,
4544    world_dir: JString<'l>,
4545) {
4546    let dir = jstr!(env, world_dir);
4547    *WORLD_DIR.lock().expect("WORLD_DIR poisoned") = if dir.is_empty() {
4548        None
4549    } else {
4550        Some(std::path::PathBuf::from(dir))
4551    };
4552    load_startup_granted();
4553    let srv = srv_ptr();
4554    guard("on_server_started", || {
4555        for (module, ud, f) in &handlers().server_started {
4556            if module.is_retiring() {
4557                continue;
4558            }
4559            let Some(_call) = module.enter() else {
4560                continue;
4561            };
4562            unsafe { f(*ud, srv) };
4563        }
4564    });
4565}
4566
4567#[no_mangle]
4568pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnServerStopping<'l>(
4569    _env: JNIEnv<'l>,
4570    _class: JClass<'l>,
4571) {
4572    let srv = srv_ptr();
4573    guard("on_server_stopping", || {
4574        for (module, ud, f) in &handlers().server_stopping {
4575            if module.is_retiring() {
4576                continue;
4577            }
4578            let Some(_call) = module.enter() else {
4579                continue;
4580            };
4581            unsafe { f(*ud, srv) };
4582        }
4583    });
4584}
4585
4586#[no_mangle]
4587pub extern "system" fn Java_dev_yog_NativeBridge_nativeCommandNames<'l>(
4588    env: JNIEnv<'l>,
4589    _class: JClass<'l>,
4590) -> jstring {
4591    let names = handlers()
4592        .commands
4593        .keys()
4594        .cloned()
4595        .collect::<Vec<_>>()
4596        .join("\n");
4597    env.new_string(names)
4598        .map(|s| s.into_raw())
4599        .unwrap_or(std::ptr::null_mut())
4600}
4601
4602#[no_mangle]
4603pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnBlockBreakPre<'l>(
4604    mut env: JNIEnv<'l>,
4605    _class: JClass<'l>,
4606    player: JString<'l>,
4607    block: JString<'l>,
4608    x: jint,
4609    y: jint,
4610    z: jint,
4611    dimension: JString<'l>,
4612) -> jni::sys::jboolean {
4613    let h = handlers();
4614    if h.block_break.is_empty() {
4615        return 1;
4616    }
4617    let p = match env.get_string(&player) {
4618        Ok(s) => String::from(s),
4619        Err(_) => return 1,
4620    };
4621    let b = match env.get_string(&block) {
4622        Ok(s) => String::from(s),
4623        Err(_) => return 1,
4624    };
4625    let d = match env.get_string(&dimension) {
4626        Ok(s) => String::from(s),
4627        Err(_) => return 1,
4628    };
4629    let ev = yog_abi::YogBlockBreakEvent {
4630        player: YogStr::from_str(&p),
4631        block: YogStr::from_str(&b),
4632        pos: YogBlockPos { x, y, z },
4633        dimension: YogStr::from_str(&d),
4634    };
4635    let srv = srv_ptr();
4636    let mut allow = true;
4637    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4638        for (module, ud, f) in &h.block_break {
4639            if module.is_retiring() {
4640                continue;
4641            }
4642            let Some(_call) = module.enter() else {
4643                continue;
4644            };
4645            if !unsafe { f(*ud, srv, &ev, 0) } {
4646                allow = false;
4647                break;
4648            }
4649        }
4650    }))
4651    .ok();
4652    allow as jni::sys::jboolean
4653}
4654
4655#[no_mangle]
4656pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnChatPre<'l>(
4657    mut env: JNIEnv<'l>,
4658    _class: JClass<'l>,
4659    player: JString<'l>,
4660    message: JString<'l>,
4661    dimension: JString<'l>,
4662) -> jni::sys::jboolean {
4663    let h = handlers();
4664    if h.chat.is_empty() {
4665        return 1;
4666    }
4667    let p = match env.get_string(&player) {
4668        Ok(s) => String::from(s),
4669        Err(_) => return 1,
4670    };
4671    let m = match env.get_string(&message) {
4672        Ok(s) => String::from(s),
4673        Err(_) => return 1,
4674    };
4675    let d = match env.get_string(&dimension) {
4676        Ok(s) => String::from(s),
4677        Err(_) => return 1,
4678    };
4679    let ev = yog_abi::YogChatEvent {
4680        player: YogStr::from_str(&p),
4681        message: YogStr::from_str(&m),
4682        dimension: YogStr::from_str(&d),
4683    };
4684    let srv = srv_ptr();
4685    let mut allow = true;
4686    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4687        for (module, ud, f) in &h.chat {
4688            if module.is_retiring() {
4689                continue;
4690            }
4691            let Some(_call) = module.enter() else {
4692                continue;
4693            };
4694            if !unsafe { f(*ud, srv, &ev, 0) } {
4695                allow = false;
4696                break;
4697            }
4698        }
4699    }))
4700    .ok();
4701    allow as jni::sys::jboolean
4702}
4703
4704#[no_mangle]
4705pub extern "system" fn Java_dev_yog_NativeBridge_nativeRecipeJsons<'l>(
4706    env: JNIEnv<'l>,
4707    _class: JClass<'l>,
4708) -> jstring {
4709    let s = handlers()
4710        .recipes
4711        .iter()
4712        .map(|(ns, name, json)| format!("{}\t{}\t{}", ns, name, json))
4713        .collect::<Vec<_>>()
4714        .join("\n");
4715    env.new_string(s)
4716        .map(|s| s.into_raw())
4717        .unwrap_or(std::ptr::null_mut())
4718}
4719
4720#[no_mangle]
4721pub extern "system" fn Java_dev_yog_NativeBridge_nativeDimensionJsons<'l>(
4722    env: JNIEnv<'l>,
4723    _class: JClass<'l>,
4724) -> jstring {
4725    // One line per declared dimension: `id \t def_json`. The host converts
4726    // `def_json` (our YogDimensionDef shape) into vanilla dimension_type /
4727    // dimension datapack JSON — see `yog-dimensions` crate docs.
4728    let s = handlers()
4729        .dimensions
4730        .iter()
4731        .map(|(id, json)| format!("{}\t{}", id, json))
4732        .collect::<Vec<_>>()
4733        .join("\n");
4734    env.new_string(s)
4735        .map(|s| s.into_raw())
4736        .unwrap_or(std::ptr::null_mut())
4737}
4738
4739/// Called by a registered chunk-generator closure (via `ChunkWriter::set_block`)
4740/// to place one block in the chunk currently being generated. Calls back
4741/// into `YogCallbackChunkGenerator.setBlockInGeneratingChunk` on the Java
4742/// side — same thread, since the whole round trip is synchronous.
4743unsafe extern "C" fn chunk_writer_set_block(
4744    _ctx: *mut c_void,
4745    x: i32,
4746    y: i32,
4747    z: i32,
4748    block_id: YogStr,
4749) -> bool {
4750    let Some(mut env) = get_env() else {
4751        return false;
4752    };
4753    let Some(jb) = ys_to_java(&mut env, block_id) else {
4754        return false;
4755    };
4756    env.call_static_method(
4757        "dev/yog/NativeBridge",
4758        "setBlockInGeneratingChunk",
4759        "(IIILjava/lang/String;)Z",
4760        &[
4761            JValue::Int(x),
4762            JValue::Int(y),
4763            JValue::Int(z),
4764            JValue::Object(&jb),
4765        ],
4766    )
4767    .and_then(|v| v.z())
4768    .unwrap_or(false)
4769}
4770
4771#[no_mangle]
4772pub extern "system" fn Java_dev_yog_NativeBridge_nativeGenerateChunk<'l>(
4773    mut env: JNIEnv<'l>,
4774    _class: JClass<'l>,
4775    generator_type_id: JString<'l>,
4776    chunk_x: jint,
4777    chunk_z: jint,
4778    min_y: jint,
4779    height: jint,
4780) {
4781    let id: String = match env.get_string(&generator_type_id) {
4782        Ok(s) => String::from(s),
4783        Err(_) => return,
4784    };
4785    let Some((module, ud, cb)) = handlers().chunk_generators.get(&id).cloned() else {
4786        return;
4787    };
4788    if module.is_retiring() {
4789        return;
4790    }
4791    let Some(_call) = module.enter() else { return };
4792    let writer = yog_abi::YogChunkWriterApi {
4793        chunk_x,
4794        chunk_z,
4795        min_y,
4796        height,
4797        ctx: std::ptr::null_mut(),
4798        set_block: chunk_writer_set_block,
4799    };
4800    guard("chunk_generator", || unsafe {
4801        cb(ud, &writer as *const _);
4802    });
4803}
4804
4805#[no_mangle]
4806pub extern "system" fn Java_dev_yog_NativeBridge_nativeTypedCommandSchemas<'l>(
4807    env: JNIEnv<'l>,
4808    _class: JClass<'l>,
4809) -> jstring {
4810    // One line per DISTINCT (name, schema) pair — a name can have several
4811    // typed registrations (different arg shapes); Brigadier merges repeated
4812    // `dispatcher.register()` calls for the same literal name into one tree,
4813    // so the Java side just needs every distinct schema once each.
4814    let mut lines = Vec::new();
4815    for (name, regs) in handlers().commands.iter() {
4816        let mut seen = std::collections::HashSet::new();
4817        for (_module, schema, _, _) in regs {
4818            if let Some(schema) = schema {
4819                if seen.insert(schema.as_str()) {
4820                    lines.push(format!("{}\t{}", name, schema));
4821                }
4822            }
4823        }
4824    }
4825    env.new_string(lines.join("\n"))
4826        .map(|s| s.into_raw())
4827        .unwrap_or(std::ptr::null_mut())
4828}
4829
4830#[no_mangle]
4831pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnCommand<'l>(
4832    mut env: JNIEnv<'l>,
4833    _class: JClass<'l>,
4834    name: JString<'l>,
4835    args: JString<'l>,
4836    source: JString<'l>,
4837    uuid: JString<'l>,
4838    dimension: JString<'l>,
4839) -> jstring {
4840    let (n, a, s, u, d) = (
4841        env.get_string(&name).map(String::from).unwrap_or_default(),
4842        env.get_string(&args).map(String::from).unwrap_or_default(),
4843        env.get_string(&source)
4844            .map(String::from)
4845            .unwrap_or_default(),
4846        env.get_string(&uuid).map(String::from).unwrap_or_default(),
4847        env.get_string(&dimension)
4848            .map(String::from)
4849            .unwrap_or_default(),
4850    );
4851    let ev = yog_abi::YogCommandEvent {
4852        name: YogStr::from_str(&n),
4853        args: YogStr::from_str(&a),
4854        source: YogStr::from_str(&s),
4855        uuid: YogStr::from_str(&u),
4856        dimension: YogStr::from_str(&d),
4857    };
4858    let h = handlers();
4859    let srv = srv_ptr();
4860    // Actual arg count of this invocation (0 for a bare command with no args).
4861    let actual_argc = if a.is_empty() {
4862        0
4863    } else {
4864        a.split('\t').count()
4865    };
4866    let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4867        let Some(regs) = h.commands.get(&n) else {
4868            return String::new();
4869        };
4870        for (module, schema, ud, f) in regs {
4871            let expected_argc = schema.as_ref().map_or(0, |s| s.split_whitespace().count());
4872            if expected_argc != actual_argc {
4873                continue;
4874            }
4875            if module.is_retiring() {
4876                continue;
4877            }
4878            let Some(_call) = module.enter() else {
4879                continue;
4880            };
4881            let mut buf = [0u8; 4096];
4882            let mut reply_len: u32 = 0;
4883            unsafe {
4884                f(
4885                    *ud,
4886                    srv,
4887                    &ev,
4888                    buf.as_mut_ptr(),
4889                    buf.len() as u32,
4890                    &mut reply_len,
4891                )
4892            };
4893            if reply_len > 0 {
4894                return String::from_utf8_lossy(&buf[..reply_len as usize]).into_owned();
4895            }
4896        }
4897        String::new()
4898    }))
4899    .unwrap_or_else(|_| {
4900        yog_logging::error!("a mod panicked handling command `{}`", n);
4901        String::new()
4902    });
4903
4904    env.new_string(reply)
4905        .map(|s| s.into_raw())
4906        .unwrap_or(std::ptr::null_mut())
4907}
4908
4909#[no_mangle]
4910pub extern "system" fn Java_dev_yog_NativeBridge_nativeItemDefs<'l>(
4911    env: JNIEnv<'l>,
4912    _class: JClass<'l>,
4913) -> jstring {
4914    let s = handlers()
4915        .items
4916        .iter()
4917        .map(|d| {
4918            let mut parts = vec![d.id.clone()];
4919            parts.push(format!("max_stack={}", d.max_stack));
4920            if let Some(n) = &d.name {
4921                parts.push(format!("name={n}"));
4922            }
4923            if let Some(t) = &d.tooltip {
4924                parts.push(format!("tooltip={t}"));
4925            }
4926            if d.max_damage > 0 {
4927                parts.push(format!("max_damage={}", d.max_damage));
4928            }
4929            if d.fire_resistant {
4930                parts.push("fire_resistant=1".into());
4931            }
4932            if d.fuel_ticks > 0 {
4933                parts.push(format!("fuel_ticks={}", d.fuel_ticks));
4934            }
4935            if let Some(f) = &d.food {
4936                parts.push(format!(
4937                    "food={}:{}:{}",
4938                    f.nutrition,
4939                    f.saturation,
4940                    if f.can_always_eat { 1 } else { 0 }
4941                ));
4942            }
4943            parts.join("\t")
4944        })
4945        .collect::<Vec<_>>()
4946        .join("\n");
4947    env.new_string(s)
4948        .map(|s| s.into_raw())
4949        .unwrap_or(std::ptr::null_mut())
4950}
4951
4952#[no_mangle]
4953pub extern "system" fn Java_dev_yog_NativeBridge_nativeBlockDefs<'l>(
4954    env: JNIEnv<'l>,
4955    _class: JClass<'l>,
4956) -> jstring {
4957    let s = handlers()
4958        .blocks
4959        .iter()
4960        .map(|d| {
4961            let mut parts = vec![d.id.clone()];
4962            parts.push(format!("hardness={}", d.hardness));
4963            parts.push(format!("resistance={}", d.resistance));
4964            if let Some(n) = &d.name {
4965                parts.push(format!("name={n}"));
4966            }
4967            if let Some(sh) = d.shape {
4968                parts.push(format!(
4969                    "shape={}:{}:{}:{}:{}:{}",
4970                    sh[0], sh[1], sh[2], sh[3], sh[4], sh[5]
4971                ));
4972            }
4973            if d.light_level > 0 {
4974                parts.push(format!("light={}", d.light_level));
4975            }
4976            if let Some(snd) = &d.sound {
4977                parts.push(format!("sound={snd}"));
4978            }
4979            if d.requires_tool {
4980                parts.push("requires_tool=1".into());
4981            }
4982            if d.no_collision {
4983                parts.push("no_collision=1".into());
4984            }
4985            if d.slipperiness > 0.0 {
4986                parts.push(format!("slipperiness={}", d.slipperiness));
4987            }
4988            if d.connects {
4989                parts.push("connects=1".into());
4990            }
4991            if !d.connect_groups.is_empty() {
4992                parts.push(format!("connect_groups={}", d.connect_groups.join(",")));
4993            }
4994            if let Some(inv) = &d.inventory_id {
4995                parts.push(format!("inventory_id={inv}"));
4996            }
4997            parts.join("\t")
4998        })
4999        .collect::<Vec<_>>()
5000        .join("\n");
5001    env.new_string(s)
5002        .map(|s| s.into_raw())
5003        .unwrap_or(std::ptr::null_mut())
5004}
5005
5006/// Tab/newline-encoded inventory defs — one line per registered
5007/// `InventoryDef` (see `yog_inventory`): `id\tslot_count=N\tlayout=x:y,...
5008/// \tinclude_player_inventory=0|1\tplayer_inv=x:y\tbackground_texture=...\ttitle=...`
5009#[no_mangle]
5010pub extern "system" fn Java_dev_yog_NativeBridge_nativeInventoryDefs<'l>(
5011    env: JNIEnv<'l>,
5012    _class: JClass<'l>,
5013) -> jstring {
5014    let s = handlers()
5015        .inventories
5016        .iter()
5017        .map(|d| {
5018            let mut parts = vec![d.id.clone()];
5019            parts.push(format!("slot_count={}", d.slot_count));
5020            parts.push(format!(
5021                "layout={}",
5022                yog_inventory::encode_layout(&d.resolved_layout())
5023            ));
5024            parts.push(format!(
5025                "include_player_inventory={}",
5026                d.include_player_inventory as u8
5027            ));
5028            parts.push(format!(
5029                "player_inv={}:{}",
5030                d.player_inv_offset.0, d.player_inv_offset.1
5031            ));
5032            if let Some(tex) = &d.background_texture {
5033                parts.push(format!("background_texture={tex}"));
5034            }
5035            if !d.title.is_empty() {
5036                parts.push(format!("title={}", d.title));
5037            }
5038            if let Some((w, h)) = d.background_size {
5039                parts.push(format!("background_size={w}:{h}"));
5040            }
5041            parts.join("\t")
5042        })
5043        .collect::<Vec<_>>()
5044        .join("\n");
5045    env.new_string(s)
5046        .map(|s| s.into_raw())
5047        .unwrap_or(std::ptr::null_mut())
5048}
5049
5050#[no_mangle]
5051pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPacket<'l>(
5052    mut env: JNIEnv<'l>,
5053    _class: JClass<'l>,
5054    channel: JString<'l>,
5055    player: JString<'l>,
5056    payload: JByteArray<'l>,
5057) {
5058    let ch = env
5059        .get_string(&channel)
5060        .map(String::from)
5061        .unwrap_or_default();
5062    let pl = env
5063        .get_string(&player)
5064        .map(String::from)
5065        .unwrap_or_default();
5066    let data = env.convert_byte_array(&payload).unwrap_or_default();
5067    let ev = yog_abi::YogPacketEvent {
5068        channel: YogStr::from_str(&ch),
5069        player: YogStr::from_str(&pl),
5070        payload: data.as_ptr(),
5071        payload_len: data.len() as u32,
5072    };
5073    let h = handlers();
5074    let srv = srv_ptr();
5075    guard("on_packet", || {
5076        if let Some((module, ud, f)) = h.packets.get(&ch) {
5077            if module.is_retiring() {
5078                return;
5079            }
5080            let Some(_call) = module.enter() else { return };
5081            unsafe { f(*ud, srv, &ev) };
5082        }
5083    });
5084}
5085
5086#[no_mangle]
5087pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnClientPacket<'l>(
5088    mut env: JNIEnv<'l>,
5089    _class: JClass<'l>,
5090    channel: JString<'l>,
5091    payload: JByteArray<'l>,
5092) {
5093    let ch = env
5094        .get_string(&channel)
5095        .map(String::from)
5096        .unwrap_or_default();
5097    let data = env.convert_byte_array(&payload).unwrap_or_default();
5098    let ev = yog_abi::YogPacketEvent {
5099        channel: YogStr::from_str(&ch),
5100        player: YogStr::EMPTY,
5101        payload: data.as_ptr(),
5102        payload_len: data.len() as u32,
5103    };
5104    let h = handlers();
5105    let srv = srv_ptr();
5106    guard("on_client_packet", || {
5107        if let Some((module, ud, f)) = h.client_packets.get(&ch) {
5108            if module.is_retiring() {
5109                return;
5110            }
5111            let Some(_call) = module.enter() else { return };
5112            unsafe { f(*ud, srv, &ev) };
5113        }
5114    });
5115}
5116
5117#[no_mangle]
5118pub extern "system" fn Java_dev_yog_NativeBridge_nativePacketChannels<'l>(
5119    env: JNIEnv<'l>,
5120    _class: JClass<'l>,
5121) -> jstring {
5122    let s = handlers()
5123        .packets
5124        .keys()
5125        .cloned()
5126        .collect::<Vec<_>>()
5127        .join("\n");
5128    env.new_string(s)
5129        .map(|s| s.into_raw())
5130        .unwrap_or(std::ptr::null_mut())
5131}
5132
5133#[no_mangle]
5134pub extern "system" fn Java_dev_yog_NativeBridge_nativeClientPacketChannels<'l>(
5135    env: JNIEnv<'l>,
5136    _class: JClass<'l>,
5137) -> jstring {
5138    let s = handlers()
5139        .client_packets
5140        .keys()
5141        .cloned()
5142        .collect::<Vec<_>>()
5143        .join("\n");
5144    env.new_string(s)
5145        .map(|s| s.into_raw())
5146        .unwrap_or(std::ptr::null_mut())
5147}
5148
5149#[no_mangle]
5150pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntitySpawn<'l>(
5151    mut env: JNIEnv<'l>,
5152    _class: JClass<'l>,
5153    entity_type: JString<'l>,
5154    uuid: JString<'l>,
5155    dimension: JString<'l>,
5156) {
5157    let h = handlers();
5158    if h.entity_spawn.is_empty() {
5159        return;
5160    }
5161    let (et, u, d) = (
5162        jstr!(env, entity_type),
5163        jstr!(env, uuid),
5164        jstr!(env, dimension),
5165    );
5166    let ev = yog_abi::YogEntitySpawnEvent {
5167        entity_type: YogStr::from_str(&et),
5168        uuid: YogStr::from_str(&u),
5169        dimension: YogStr::from_str(&d),
5170    };
5171    let srv = srv_ptr();
5172    guard("on_entity_spawn", || {
5173        for (module, ud, f) in &h.entity_spawn {
5174            if module.is_retiring() {
5175                continue;
5176            }
5177            let Some(_call) = module.enter() else {
5178                continue;
5179            };
5180            unsafe { f(*ud, srv, &ev, 1) };
5181        }
5182    });
5183}
5184
5185#[no_mangle]
5186pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntitySpawnPre<'l>(
5187    mut env: JNIEnv<'l>,
5188    _class: JClass<'l>,
5189    entity_type: JString<'l>,
5190    uuid: JString<'l>,
5191    dimension: JString<'l>,
5192) -> jni::sys::jboolean {
5193    let h = handlers();
5194    if h.entity_spawn.is_empty() {
5195        return 1;
5196    }
5197    let et = match env.get_string(&entity_type) {
5198        Ok(s) => String::from(s),
5199        Err(_) => return 1,
5200    };
5201    let u = match env.get_string(&uuid) {
5202        Ok(s) => String::from(s),
5203        Err(_) => return 1,
5204    };
5205    let d = match env.get_string(&dimension) {
5206        Ok(s) => String::from(s),
5207        Err(_) => return 1,
5208    };
5209    let ev = yog_abi::YogEntitySpawnEvent {
5210        entity_type: YogStr::from_str(&et),
5211        uuid: YogStr::from_str(&u),
5212        dimension: YogStr::from_str(&d),
5213    };
5214    let srv = srv_ptr();
5215    let mut allow = true;
5216    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5217        for (module, ud, f) in &h.entity_spawn {
5218            if module.is_retiring() {
5219                continue;
5220            }
5221            let Some(_call) = module.enter() else {
5222                continue;
5223            };
5224            if !unsafe { f(*ud, srv, &ev, 0) } {
5225                allow = false;
5226                break;
5227            }
5228        }
5229    }))
5230    .ok();
5231    allow as jni::sys::jboolean
5232}
5233
5234#[no_mangle]
5235pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityDamagePre<'l>(
5236    mut env: JNIEnv<'l>,
5237    _class: JClass<'l>,
5238    entity_type: JString<'l>,
5239    uuid: JString<'l>,
5240    amount: jfloat,
5241    source: JString<'l>,
5242    dimension: JString<'l>,
5243) -> jni::sys::jboolean {
5244    let h = handlers();
5245    if h.entity_damage.is_empty() {
5246        return 1;
5247    }
5248    let et = match env.get_string(&entity_type) {
5249        Ok(s) => String::from(s),
5250        Err(_) => return 1,
5251    };
5252    let u = match env.get_string(&uuid) {
5253        Ok(s) => String::from(s),
5254        Err(_) => return 1,
5255    };
5256    let s = match env.get_string(&source) {
5257        Ok(s) => String::from(s),
5258        Err(_) => return 1,
5259    };
5260    let d = match env.get_string(&dimension) {
5261        Ok(s) => String::from(s),
5262        Err(_) => return 1,
5263    };
5264    let ev = yog_abi::YogEntityDamageEvent {
5265        entity_type: YogStr::from_str(&et),
5266        uuid: YogStr::from_str(&u),
5267        amount,
5268        source: YogStr::from_str(&s),
5269        dimension: YogStr::from_str(&d),
5270    };
5271    let srv = srv_ptr();
5272    let mut allow = true;
5273    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5274        for (module, ud, f) in &h.entity_damage {
5275            if module.is_retiring() {
5276                continue;
5277            }
5278            let Some(_call) = module.enter() else {
5279                continue;
5280            };
5281            if !unsafe { f(*ud, srv, &ev, 0) } {
5282                allow = false;
5283                break;
5284            }
5285        }
5286    }))
5287    .ok();
5288    allow as jni::sys::jboolean
5289}
5290
5291#[no_mangle]
5292pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlaceBlockPre<'l>(
5293    mut env: JNIEnv<'l>,
5294    _class: JClass<'l>,
5295    player: JString<'l>,
5296    block: JString<'l>,
5297    x: jint,
5298    y: jint,
5299    z: jint,
5300    dimension: JString<'l>,
5301) -> jni::sys::jboolean {
5302    let h = handlers();
5303    if h.player_place_block.is_empty() {
5304        return 1;
5305    }
5306    let p = match env.get_string(&player) {
5307        Ok(s) => String::from(s),
5308        Err(_) => return 1,
5309    };
5310    let b = match env.get_string(&block) {
5311        Ok(s) => String::from(s),
5312        Err(_) => return 1,
5313    };
5314    let d = match env.get_string(&dimension) {
5315        Ok(s) => String::from(s),
5316        Err(_) => return 1,
5317    };
5318    let ev = YogPlaceBlockEvent {
5319        player: YogStr::from_str(&p),
5320        block: YogStr::from_str(&b),
5321        pos: YogBlockPos { x, y, z },
5322        dimension: YogStr::from_str(&d),
5323    };
5324    let srv = srv_ptr();
5325    let mut allow = true;
5326    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5327        for (module, ud, f) in &h.player_place_block {
5328            if module.is_retiring() {
5329                continue;
5330            }
5331            let Some(_call) = module.enter() else {
5332                continue;
5333            };
5334            if !unsafe { f(*ud, srv, &ev, 0) } {
5335                allow = false;
5336                break;
5337            }
5338        }
5339    }))
5340    .ok();
5341    allow as jni::sys::jboolean
5342}
5343
5344#[no_mangle]
5345pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlaceBlock<'l>(
5346    mut env: JNIEnv<'l>,
5347    _class: JClass<'l>,
5348    player: JString<'l>,
5349    block: JString<'l>,
5350    x: jint,
5351    y: jint,
5352    z: jint,
5353    dimension: JString<'l>,
5354) {
5355    let h = handlers();
5356    if h.player_place_block.is_empty() {
5357        return;
5358    }
5359    let (p, b, d) = (jstr!(env, player), jstr!(env, block), jstr!(env, dimension));
5360    let ev = YogPlaceBlockEvent {
5361        player: YogStr::from_str(&p),
5362        block: YogStr::from_str(&b),
5363        pos: YogBlockPos { x, y, z },
5364        dimension: YogStr::from_str(&d),
5365    };
5366    let srv = srv_ptr();
5367    guard("on_player_place_block", || {
5368        for (module, ud, f) in &h.player_place_block {
5369            if module.is_retiring() {
5370                continue;
5371            }
5372            let Some(_call) = module.enter() else {
5373                continue;
5374            };
5375            unsafe { f(*ud, srv, &ev, 1) };
5376        }
5377    });
5378}
5379
5380#[no_mangle]
5381pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerDeathPre<'l>(
5382    mut env: JNIEnv<'l>,
5383    _class: JClass<'l>,
5384    player: JString<'l>,
5385    uuid: JString<'l>,
5386    source: JString<'l>,
5387    dimension: JString<'l>,
5388) -> jni::sys::jboolean {
5389    let h = handlers();
5390    if h.player_death.is_empty() {
5391        return 1;
5392    }
5393    let p = match env.get_string(&player) {
5394        Ok(s) => String::from(s),
5395        Err(_) => return 1,
5396    };
5397    let u = match env.get_string(&uuid) {
5398        Ok(s) => String::from(s),
5399        Err(_) => return 1,
5400    };
5401    let s = match env.get_string(&source) {
5402        Ok(s) => String::from(s),
5403        Err(_) => return 1,
5404    };
5405    let d = match env.get_string(&dimension) {
5406        Ok(s) => String::from(s),
5407        Err(_) => return 1,
5408    };
5409    let ev = YogPlayerDeathEvent {
5410        player: YogStr::from_str(&p),
5411        uuid: YogStr::from_str(&u),
5412        source: YogStr::from_str(&s),
5413        dimension: YogStr::from_str(&d),
5414    };
5415    let srv = srv_ptr();
5416    let mut allow = true;
5417    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5418        for (module, ud, f) in &h.player_death {
5419            if module.is_retiring() {
5420                continue;
5421            }
5422            let Some(_call) = module.enter() else {
5423                continue;
5424            };
5425            if !unsafe { f(*ud, srv, &ev, 0) } {
5426                allow = false;
5427                break;
5428            }
5429        }
5430    }))
5431    .ok();
5432    allow as jni::sys::jboolean
5433}
5434
5435#[no_mangle]
5436pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerDeath<'l>(
5437    mut env: JNIEnv<'l>,
5438    _class: JClass<'l>,
5439    player: JString<'l>,
5440    uuid: JString<'l>,
5441    source: JString<'l>,
5442    dimension: JString<'l>,
5443) {
5444    let h = handlers();
5445    if h.player_death.is_empty() {
5446        return;
5447    }
5448    let (p, u, s, d) = (
5449        jstr!(env, player),
5450        jstr!(env, uuid),
5451        jstr!(env, source),
5452        jstr!(env, dimension),
5453    );
5454    let ev = YogPlayerDeathEvent {
5455        player: YogStr::from_str(&p),
5456        uuid: YogStr::from_str(&u),
5457        source: YogStr::from_str(&s),
5458        dimension: YogStr::from_str(&d),
5459    };
5460    let srv = srv_ptr();
5461    guard("on_player_death", || {
5462        for (module, ud, f) in &h.player_death {
5463            if module.is_retiring() {
5464                continue;
5465            }
5466            let Some(_call) = module.enter() else {
5467                continue;
5468            };
5469            unsafe { f(*ud, srv, &ev, 1) };
5470        }
5471    });
5472}
5473
5474#[no_mangle]
5475pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerRespawn<'l>(
5476    mut env: JNIEnv<'l>,
5477    _class: JClass<'l>,
5478    player: JString<'l>,
5479    uuid: JString<'l>,
5480    at_anchor: jni::sys::jboolean,
5481    dimension: JString<'l>,
5482) {
5483    let h = handlers();
5484    if h.player_respawn.is_empty() {
5485        return;
5486    }
5487    let (p, u, d) = (jstr!(env, player), jstr!(env, uuid), jstr!(env, dimension));
5488    let ev = YogPlayerRespawnEvent {
5489        player: YogStr::from_str(&p),
5490        uuid: YogStr::from_str(&u),
5491        at_anchor: at_anchor != 0,
5492        dimension: YogStr::from_str(&d),
5493    };
5494    let srv = srv_ptr();
5495    guard("on_player_respawn", || {
5496        for (module, ud, f) in &h.player_respawn {
5497            if module.is_retiring() {
5498                continue;
5499            }
5500            let Some(_call) = module.enter() else {
5501                continue;
5502            };
5503            unsafe { f(*ud, srv, &ev, 1) };
5504        }
5505    });
5506}
5507
5508#[no_mangle]
5509pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnAdvancement<'l>(
5510    mut env: JNIEnv<'l>,
5511    _class: JClass<'l>,
5512    player: JString<'l>,
5513    uuid: JString<'l>,
5514    advancement: JString<'l>,
5515    dimension: JString<'l>,
5516) {
5517    let h = handlers();
5518    if h.advancement.is_empty() {
5519        return;
5520    }
5521    let (p, u, a, d) = (
5522        jstr!(env, player),
5523        jstr!(env, uuid),
5524        jstr!(env, advancement),
5525        jstr!(env, dimension),
5526    );
5527    let ev = YogAdvancementEvent {
5528        player: YogStr::from_str(&p),
5529        uuid: YogStr::from_str(&u),
5530        advancement: YogStr::from_str(&a),
5531        dimension: YogStr::from_str(&d),
5532    };
5533    let srv = srv_ptr();
5534    guard("on_advancement", || {
5535        for (module, ud, f) in &h.advancement {
5536            if module.is_retiring() {
5537                continue;
5538            }
5539            let Some(_call) = module.enter() else {
5540                continue;
5541            };
5542            unsafe { f(*ud, srv, &ev, 1) };
5543        }
5544    });
5545}
5546
5547#[no_mangle]
5548pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityInteractPre<'l>(
5549    mut env: JNIEnv<'l>,
5550    _class: JClass<'l>,
5551    player: JString<'l>,
5552    player_uuid: JString<'l>,
5553    entity_type: JString<'l>,
5554    entity_uuid: JString<'l>,
5555    hand: JString<'l>,
5556    dimension: JString<'l>,
5557) -> jni::sys::jboolean {
5558    let h = handlers();
5559    if h.entity_interact.is_empty() {
5560        return 1;
5561    }
5562    let p = match env.get_string(&player) {
5563        Ok(s) => String::from(s),
5564        Err(_) => return 1,
5565    };
5566    let pu = match env.get_string(&player_uuid) {
5567        Ok(s) => String::from(s),
5568        Err(_) => return 1,
5569    };
5570    let et = match env.get_string(&entity_type) {
5571        Ok(s) => String::from(s),
5572        Err(_) => return 1,
5573    };
5574    let eu = match env.get_string(&entity_uuid) {
5575        Ok(s) => String::from(s),
5576        Err(_) => return 1,
5577    };
5578    let ha = match env.get_string(&hand) {
5579        Ok(s) => String::from(s),
5580        Err(_) => return 1,
5581    };
5582    let d = match env.get_string(&dimension) {
5583        Ok(s) => String::from(s),
5584        Err(_) => return 1,
5585    };
5586    let ev = YogEntityInteractEvent {
5587        player: YogStr::from_str(&p),
5588        player_uuid: YogStr::from_str(&pu),
5589        entity_type: YogStr::from_str(&et),
5590        entity_uuid: YogStr::from_str(&eu),
5591        hand: YogStr::from_str(&ha),
5592        dimension: YogStr::from_str(&d),
5593    };
5594    let srv = srv_ptr();
5595    let mut allow = true;
5596    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5597        for (module, ud, f) in &h.entity_interact {
5598            if module.is_retiring() {
5599                continue;
5600            }
5601            let Some(_call) = module.enter() else {
5602                continue;
5603            };
5604            if !unsafe { f(*ud, srv, &ev, 0) } {
5605                allow = false;
5606                break;
5607            }
5608        }
5609    }))
5610    .ok();
5611    allow as jni::sys::jboolean
5612}
5613
5614#[no_mangle]
5615pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityInteract<'l>(
5616    mut env: JNIEnv<'l>,
5617    _class: JClass<'l>,
5618    player: JString<'l>,
5619    player_uuid: JString<'l>,
5620    entity_type: JString<'l>,
5621    entity_uuid: JString<'l>,
5622    hand: JString<'l>,
5623    dimension: JString<'l>,
5624) {
5625    let h = handlers();
5626    if h.entity_interact.is_empty() {
5627        return;
5628    }
5629    let (p, pu) = (jstr!(env, player), jstr!(env, player_uuid));
5630    let (et, eu, ha, d) = (
5631        jstr!(env, entity_type),
5632        jstr!(env, entity_uuid),
5633        jstr!(env, hand),
5634        jstr!(env, dimension),
5635    );
5636    let ev = YogEntityInteractEvent {
5637        player: YogStr::from_str(&p),
5638        player_uuid: YogStr::from_str(&pu),
5639        entity_type: YogStr::from_str(&et),
5640        entity_uuid: YogStr::from_str(&eu),
5641        hand: YogStr::from_str(&ha),
5642        dimension: YogStr::from_str(&d),
5643    };
5644    let srv = srv_ptr();
5645    guard("on_entity_interact", || {
5646        for (module, ud, f) in &h.entity_interact {
5647            if module.is_retiring() {
5648                continue;
5649            }
5650            let Some(_call) = module.enter() else {
5651                continue;
5652            };
5653            unsafe { f(*ud, srv, &ev, 1) };
5654        }
5655    });
5656}
5657
5658#[no_mangle]
5659pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnItemCraft<'l>(
5660    mut env: JNIEnv<'l>,
5661    _class: JClass<'l>,
5662    player: JString<'l>,
5663    player_uuid: JString<'l>,
5664    result_item: JString<'l>,
5665    result_count: jint,
5666    dimension: JString<'l>,
5667) {
5668    let h = handlers();
5669    if h.item_craft.is_empty() {
5670        return;
5671    }
5672    let (p, pu, ri, d) = (
5673        jstr!(env, player),
5674        jstr!(env, player_uuid),
5675        jstr!(env, result_item),
5676        jstr!(env, dimension),
5677    );
5678    let ev = YogCraftEvent {
5679        player: YogStr::from_str(&p),
5680        player_uuid: YogStr::from_str(&pu),
5681        result_item: YogStr::from_str(&ri),
5682        result_count: result_count as u32,
5683        dimension: YogStr::from_str(&d),
5684    };
5685    let srv = srv_ptr();
5686    guard("on_item_craft", || {
5687        for (module, ud, f) in &h.item_craft {
5688            if module.is_retiring() {
5689                continue;
5690            }
5691            let Some(_call) = module.enter() else {
5692                continue;
5693            };
5694            unsafe { f(*ud, srv, &ev, 1) };
5695        }
5696    });
5697}
5698
5699#[no_mangle]
5700pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnExplosionPre<'l>(
5701    mut env: JNIEnv<'l>,
5702    _class: JClass<'l>,
5703    dimension: JString<'l>,
5704    x: jdouble,
5705    y: jdouble,
5706    z: jdouble,
5707    power: jfloat,
5708    cause_uuid: JString<'l>,
5709) -> jni::sys::jboolean {
5710    let h = handlers();
5711    if h.explosion.is_empty() {
5712        return 1;
5713    }
5714    let d = match env.get_string(&dimension) {
5715        Ok(s) => String::from(s),
5716        Err(_) => return 1,
5717    };
5718    let cu = match env.get_string(&cause_uuid) {
5719        Ok(s) => String::from(s),
5720        Err(_) => return 1,
5721    };
5722    let ev = YogExplosionEvent {
5723        dimension: YogStr::from_str(&d),
5724        x,
5725        y,
5726        z,
5727        power,
5728        cause_uuid: YogStr::from_str(&cu),
5729    };
5730    let srv = srv_ptr();
5731    let mut allow = true;
5732    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5733        for (module, ud, f) in &h.explosion {
5734            if module.is_retiring() {
5735                continue;
5736            }
5737            let Some(_call) = module.enter() else {
5738                continue;
5739            };
5740            if !unsafe { f(*ud, srv, &ev, 0) } {
5741                allow = false;
5742                break;
5743            }
5744        }
5745    }))
5746    .ok();
5747    allow as jni::sys::jboolean
5748}
5749
5750#[no_mangle]
5751pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnExplosion<'l>(
5752    mut env: JNIEnv<'l>,
5753    _class: JClass<'l>,
5754    dimension: JString<'l>,
5755    x: jdouble,
5756    y: jdouble,
5757    z: jdouble,
5758    power: jfloat,
5759    cause_uuid: JString<'l>,
5760) {
5761    let h = handlers();
5762    if h.explosion.is_empty() {
5763        return;
5764    }
5765    let (d, cu) = (jstr!(env, dimension), jstr!(env, cause_uuid));
5766    let ev = YogExplosionEvent {
5767        dimension: YogStr::from_str(&d),
5768        x,
5769        y,
5770        z,
5771        power,
5772        cause_uuid: YogStr::from_str(&cu),
5773    };
5774    let srv = srv_ptr();
5775    guard("on_explosion", || {
5776        for (module, ud, f) in &h.explosion {
5777            if module.is_retiring() {
5778                continue;
5779            }
5780            let Some(_call) = module.enter() else {
5781                continue;
5782            };
5783            unsafe { f(*ud, srv, &ev, 1) };
5784        }
5785    });
5786}
5787
5788// ── ABI minor 9 JNI entry points ─────────────────────────────────────────────
5789
5790#[no_mangle]
5791pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnItemPickupPre<'l>(
5792    mut env: JNIEnv<'l>,
5793    _class: JClass<'l>,
5794    player: JString<'l>,
5795    player_uuid: JString<'l>,
5796    item_id: JString<'l>,
5797    item_count: jint,
5798    entity_uuid: JString<'l>,
5799    dimension: JString<'l>,
5800) -> jni::sys::jboolean {
5801    let h = handlers();
5802    if h.item_pickup.is_empty() {
5803        return 1;
5804    }
5805    let p = match env.get_string(&player) {
5806        Ok(s) => String::from(s),
5807        Err(_) => return 1,
5808    };
5809    let pu = match env.get_string(&player_uuid) {
5810        Ok(s) => String::from(s),
5811        Err(_) => return 1,
5812    };
5813    let ii = match env.get_string(&item_id) {
5814        Ok(s) => String::from(s),
5815        Err(_) => return 1,
5816    };
5817    let eu = match env.get_string(&entity_uuid) {
5818        Ok(s) => String::from(s),
5819        Err(_) => return 1,
5820    };
5821    let d = match env.get_string(&dimension) {
5822        Ok(s) => String::from(s),
5823        Err(_) => return 1,
5824    };
5825    let ev = YogItemPickupEvent {
5826        player: YogStr::from_str(&p),
5827        player_uuid: YogStr::from_str(&pu),
5828        item_id: YogStr::from_str(&ii),
5829        item_count: item_count as u32,
5830        entity_uuid: YogStr::from_str(&eu),
5831        dimension: YogStr::from_str(&d),
5832    };
5833    let srv = srv_ptr();
5834    let mut allow = true;
5835    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5836        for (module, ud, f) in &h.item_pickup {
5837            if module.is_retiring() {
5838                continue;
5839            }
5840            let Some(_call) = module.enter() else {
5841                continue;
5842            };
5843            if !unsafe { f(*ud, srv, &ev, 0) } {
5844                allow = false;
5845                break;
5846            }
5847        }
5848    }))
5849    .ok();
5850    allow as jni::sys::jboolean
5851}
5852
5853#[no_mangle]
5854pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnItemPickup<'l>(
5855    mut env: JNIEnv<'l>,
5856    _class: JClass<'l>,
5857    player: JString<'l>,
5858    player_uuid: JString<'l>,
5859    item_id: JString<'l>,
5860    item_count: jint,
5861    entity_uuid: JString<'l>,
5862    dimension: JString<'l>,
5863) {
5864    let h = handlers();
5865    if h.item_pickup.is_empty() {
5866        return;
5867    }
5868    let (p, pu) = (jstr!(env, player), jstr!(env, player_uuid));
5869    let (ii, eu, d) = (
5870        jstr!(env, item_id),
5871        jstr!(env, entity_uuid),
5872        jstr!(env, dimension),
5873    );
5874    let ev = YogItemPickupEvent {
5875        player: YogStr::from_str(&p),
5876        player_uuid: YogStr::from_str(&pu),
5877        item_id: YogStr::from_str(&ii),
5878        item_count: item_count as u32,
5879        entity_uuid: YogStr::from_str(&eu),
5880        dimension: YogStr::from_str(&d),
5881    };
5882    let srv = srv_ptr();
5883    guard("on_item_pickup", || {
5884        for (module, ud, f) in &h.item_pickup {
5885            if module.is_retiring() {
5886                continue;
5887            }
5888            let Some(_call) = module.enter() else {
5889                continue;
5890            };
5891            unsafe { f(*ud, srv, &ev, 1) };
5892        }
5893    });
5894}
5895
5896#[no_mangle]
5897pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerMove<'l>(
5898    mut env: JNIEnv<'l>,
5899    _class: JClass<'l>,
5900    player: JString<'l>,
5901    player_uuid: JString<'l>,
5902    x: jdouble,
5903    y: jdouble,
5904    z: jdouble,
5905    yaw: jfloat,
5906    pitch: jfloat,
5907    dimension: JString<'l>,
5908) {
5909    let h = handlers();
5910    if h.player_move.is_empty() {
5911        return;
5912    }
5913    let (p, pu, d) = (
5914        jstr!(env, player),
5915        jstr!(env, player_uuid),
5916        jstr!(env, dimension),
5917    );
5918    let ev = YogPlayerMoveEvent {
5919        player: YogStr::from_str(&p),
5920        player_uuid: YogStr::from_str(&pu),
5921        x,
5922        y,
5923        z,
5924        yaw,
5925        pitch,
5926        dimension: YogStr::from_str(&d),
5927    };
5928    let srv = srv_ptr();
5929    guard("on_player_move", || {
5930        for (module, ud, f) in &h.player_move {
5931            if module.is_retiring() {
5932                continue;
5933            }
5934            let Some(_call) = module.enter() else {
5935                continue;
5936            };
5937            unsafe { f(*ud, srv, &ev, 1) };
5938        }
5939    });
5940}
5941
5942#[no_mangle]
5943pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnContainerOpenPre<'l>(
5944    mut env: JNIEnv<'l>,
5945    _class: JClass<'l>,
5946    player: JString<'l>,
5947    player_uuid: JString<'l>,
5948    dimension: JString<'l>,
5949) -> jni::sys::jboolean {
5950    let h = handlers();
5951    if h.container_open.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 d = match env.get_string(&dimension) {
5963        Ok(s) => String::from(s),
5964        Err(_) => return 1,
5965    };
5966    let ev = YogContainerOpenEvent {
5967        player: YogStr::from_str(&p),
5968        player_uuid: YogStr::from_str(&pu),
5969        container_type: YogStr::EMPTY,
5970        dimension: YogStr::from_str(&d),
5971    };
5972    let srv = srv_ptr();
5973    let mut allow = true;
5974    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5975        for (module, ud, f) in &h.container_open {
5976            if module.is_retiring() {
5977                continue;
5978            }
5979            let Some(_call) = module.enter() else {
5980                continue;
5981            };
5982            if !unsafe { f(*ud, srv, &ev, 0) } {
5983                allow = false;
5984                break;
5985            }
5986        }
5987    }))
5988    .ok();
5989    allow as jni::sys::jboolean
5990}
5991
5992#[no_mangle]
5993pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnContainerOpen<'l>(
5994    mut env: JNIEnv<'l>,
5995    _class: JClass<'l>,
5996    player: JString<'l>,
5997    player_uuid: JString<'l>,
5998    container_type: JString<'l>,
5999    dimension: JString<'l>,
6000) {
6001    let h = handlers();
6002    if h.container_open.is_empty() {
6003        return;
6004    }
6005    let (p, pu, ct, d) = (
6006        jstr!(env, player),
6007        jstr!(env, player_uuid),
6008        jstr!(env, container_type),
6009        jstr!(env, dimension),
6010    );
6011    let ev = YogContainerOpenEvent {
6012        player: YogStr::from_str(&p),
6013        player_uuid: YogStr::from_str(&pu),
6014        container_type: YogStr::from_str(&ct),
6015        dimension: YogStr::from_str(&d),
6016    };
6017    let srv = srv_ptr();
6018    guard("on_container_open", || {
6019        for (module, ud, f) in &h.container_open {
6020            if module.is_retiring() {
6021                continue;
6022            }
6023            let Some(_call) = module.enter() else {
6024                continue;
6025            };
6026            unsafe { f(*ud, srv, &ev, 1) };
6027        }
6028    });
6029}
6030
6031#[no_mangle]
6032pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnContainerClose<'l>(
6033    mut env: JNIEnv<'l>,
6034    _class: JClass<'l>,
6035    player: JString<'l>,
6036    player_uuid: JString<'l>,
6037    dimension: JString<'l>,
6038) {
6039    let h = handlers();
6040    if h.container_close.is_empty() {
6041        return;
6042    }
6043    let (p, pu, d) = (
6044        jstr!(env, player),
6045        jstr!(env, player_uuid),
6046        jstr!(env, dimension),
6047    );
6048    let ev = YogContainerCloseEvent {
6049        player: YogStr::from_str(&p),
6050        player_uuid: YogStr::from_str(&pu),
6051        dimension: YogStr::from_str(&d),
6052    };
6053    let srv = srv_ptr();
6054    guard("on_container_close", || {
6055        for (module, ud, f) in &h.container_close {
6056            if module.is_retiring() {
6057                continue;
6058            }
6059            let Some(_call) = module.enter() else {
6060                continue;
6061            };
6062            unsafe { f(*ud, srv, &ev, 1) };
6063        }
6064    });
6065}
6066
6067#[no_mangle]
6068pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnProjectileHitPre<'l>(
6069    mut env: JNIEnv<'l>,
6070    _class: JClass<'l>,
6071    projectile_type: JString<'l>,
6072    projectile_uuid: JString<'l>,
6073    shooter_uuid: JString<'l>,
6074    hit_type: JString<'l>,
6075    hit_entity_uuid: JString<'l>,
6076    x: jdouble,
6077    y: jdouble,
6078    z: jdouble,
6079    dimension: JString<'l>,
6080) -> jni::sys::jboolean {
6081    let h = handlers();
6082    if h.projectile_hit.is_empty() {
6083        return 1;
6084    }
6085    let pt = match env.get_string(&projectile_type) {
6086        Ok(s) => String::from(s),
6087        Err(_) => return 1,
6088    };
6089    let pu = match env.get_string(&projectile_uuid) {
6090        Ok(s) => String::from(s),
6091        Err(_) => return 1,
6092    };
6093    let su = match env.get_string(&shooter_uuid) {
6094        Ok(s) => String::from(s),
6095        Err(_) => return 1,
6096    };
6097    let ht = match env.get_string(&hit_type) {
6098        Ok(s) => String::from(s),
6099        Err(_) => return 1,
6100    };
6101    let heu = match env.get_string(&hit_entity_uuid) {
6102        Ok(s) => String::from(s),
6103        Err(_) => return 1,
6104    };
6105    let dim = match env.get_string(&dimension) {
6106        Ok(s) => String::from(s),
6107        Err(_) => return 1,
6108    };
6109    let ev = YogProjectileHitEvent {
6110        projectile_type: YogStr::from_str(&pt),
6111        projectile_uuid: YogStr::from_str(&pu),
6112        shooter_uuid: YogStr::from_str(&su),
6113        hit_type: YogStr::from_str(&ht),
6114        hit_entity_uuid: YogStr::from_str(&heu),
6115        x,
6116        y,
6117        z,
6118        dimension: YogStr::from_str(&dim),
6119    };
6120    let srv = srv_ptr();
6121    let mut allow = true;
6122    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
6123        for (module, ud, f) in &h.projectile_hit {
6124            if module.is_retiring() {
6125                continue;
6126            }
6127            let Some(_call) = module.enter() else {
6128                continue;
6129            };
6130            if !unsafe { f(*ud, srv, &ev, 0) } {
6131                allow = false;
6132                break;
6133            }
6134        }
6135    }))
6136    .ok();
6137    allow as jni::sys::jboolean
6138}
6139
6140#[no_mangle]
6141pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnProjectileHit<'l>(
6142    mut env: JNIEnv<'l>,
6143    _class: JClass<'l>,
6144    projectile_type: JString<'l>,
6145    projectile_uuid: JString<'l>,
6146    shooter_uuid: JString<'l>,
6147    hit_type: JString<'l>,
6148    hit_entity_uuid: JString<'l>,
6149    x: jdouble,
6150    y: jdouble,
6151    z: jdouble,
6152    dimension: JString<'l>,
6153) {
6154    let h = handlers();
6155    if h.projectile_hit.is_empty() {
6156        return;
6157    }
6158    let (pt, pu) = (jstr!(env, projectile_type), jstr!(env, projectile_uuid));
6159    let (su, ht) = (jstr!(env, shooter_uuid), jstr!(env, hit_type));
6160    let (heu, dim) = (jstr!(env, hit_entity_uuid), jstr!(env, dimension));
6161    let ev = YogProjectileHitEvent {
6162        projectile_type: YogStr::from_str(&pt),
6163        projectile_uuid: YogStr::from_str(&pu),
6164        shooter_uuid: YogStr::from_str(&su),
6165        hit_type: YogStr::from_str(&ht),
6166        hit_entity_uuid: YogStr::from_str(&heu),
6167        x,
6168        y,
6169        z,
6170        dimension: YogStr::from_str(&dim),
6171    };
6172    let srv = srv_ptr();
6173    guard("on_projectile_hit", || {
6174        for (module, ud, f) in &h.projectile_hit {
6175            if module.is_retiring() {
6176                continue;
6177            }
6178            let Some(_call) = module.enter() else {
6179                continue;
6180            };
6181            unsafe { f(*ud, srv, &ev, 1) };
6182        }
6183    });
6184}
6185
6186// ── ABI minor 10 — client-side JNI entry points ───────────────────────────────
6187
6188#[no_mangle]
6189pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnClientTick<'l>(
6190    _env: JNIEnv<'l>,
6191    _class: JClass<'l>,
6192) {
6193    let h = handlers();
6194    if h.client_tick.is_empty() {
6195        return;
6196    }
6197    guard("on_client_tick", || {
6198        for (module, ud, f) in &h.client_tick {
6199            if module.is_retiring() {
6200                continue;
6201            }
6202            let Some(_call) = module.enter() else {
6203                continue;
6204            };
6205            unsafe { f(*ud) };
6206        }
6207    });
6208}
6209
6210#[no_mangle]
6211pub extern "system" fn Java_dev_yog_NativeBridge_nativeGlInit<'l>(
6212    _env: JNIEnv<'l>,
6213    _class: JClass<'l>,
6214) {
6215    if GL.get().is_some() {
6216        return;
6217    }
6218    let mut raw_get_binary: usize = 0;
6219    let mut raw_prog_binary: usize = 0;
6220    let gl = unsafe {
6221        glow::Context::from_loader_function(|sym| {
6222            let Some(mut env) = get_env() else {
6223                return std::ptr::null();
6224            };
6225            let jsym = match env.new_string(sym) {
6226                Ok(s) => s,
6227                Err(_) => return std::ptr::null(),
6228            };
6229            let jsym_obj: JObject = jsym.into();
6230            let val = env.call_static_method(
6231                "dev/yog/NativeBridge",
6232                "glProcAddress",
6233                "(Ljava/lang/String;)J",
6234                &[JValue::Object(&jsym_obj)],
6235            );
6236            let ptr = match val.and_then(|v| v.j()) {
6237                Ok(p) if p != 0 => p as usize as *const _,
6238                _ => std::ptr::null(),
6239            };
6240            // Capture extension pointers while the loader runs.
6241            match sym {
6242                "glGetProgramBinary" => raw_get_binary = ptr as usize,
6243                "glProgramBinary" => raw_prog_binary = ptr as usize,
6244                _ => {}
6245            }
6246            ptr
6247        })
6248    };
6249    let _ = GL.set(GlCtx(gl));
6250    let _ = GL_GET_PROGRAM_BINARY.set(if raw_get_binary != 0 {
6251        Some(raw_get_binary)
6252    } else {
6253        None
6254    });
6255    let _ = GL_PROGRAM_BINARY.set(if raw_prog_binary != 0 {
6256        Some(raw_prog_binary)
6257    } else {
6258        None
6259    });
6260    // `glGetProgramiv` is a core function; always available.  We look it up once here
6261    // to avoid depending on glow internals for the PROGRAM_BINARY_LENGTH query.
6262    if let Some(mut env) = get_env() {
6263        if let Ok(jsym) = env.new_string("glGetProgramiv") {
6264            let jsym_obj: JObject = jsym.into();
6265            if let Ok(jv) = env.call_static_method(
6266                "dev/yog/NativeBridge",
6267                "glProcAddress",
6268                "(Ljava/lang/String;)J",
6269                &[JValue::Object(&jsym_obj)],
6270            ) {
6271                if let Ok(ptr) = jv.j() {
6272                    let _ = GL_GET_PROGRAM_IV.set(if ptr != 0 { Some(ptr as usize) } else { None });
6273                }
6274            }
6275        }
6276    }
6277}
6278
6279#[no_mangle]
6280pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnHudRender<'l>(
6281    _env: JNIEnv<'l>,
6282    _class: JClass<'l>,
6283    delta_tick: jfloat,
6284    screen_w: jint,
6285    screen_h: jint,
6286    scale_factor: jfloat,
6287    player_x: jfloat,
6288    player_y: jfloat,
6289    player_z: jfloat,
6290) {
6291    let h = handlers();
6292    let mut gfx = GFX_FN_TABLE;
6293    gfx.screen_w = screen_w;
6294    gfx.screen_h = screen_h;
6295    gfx.delta_tick = delta_tick;
6296    gfx.scale_factor = scale_factor;
6297    gfx.player_pos = [player_x, player_y, player_z];
6298
6299    // Mod hud_render callbacks.
6300    if !h.hud_render.is_empty() {
6301        guard("on_hud_render", || {
6302            for (module, ud, f) in &h.hud_render {
6303                if module.is_retiring() {
6304                    continue;
6305                }
6306                let Some(_call) = module.enter() else {
6307                    continue;
6308                };
6309                unsafe { f(*ud, &gfx) };
6310            }
6311        });
6312    }
6313
6314    // Render active book UIs.
6315    let active_layers: Vec<UiLayer> = h.active_uis.lock().unwrap().clone();
6316    let sw = screen_w as f32;
6317    let sh = screen_h as f32;
6318    let ctx = unsafe { yog_gfx::GfxContext::from_raw(&gfx as *const _) };
6319    let mut renderers = h.book_renderers.lock().unwrap();
6320    for layer in &active_layers {
6321        if !layer.visible {
6322            continue;
6323        }
6324        if let Some(renderer) = renderers.get_mut(&layer.id) {
6325            renderer.render(&ctx, sw, sh);
6326        }
6327    }
6328}
6329
6330#[no_mangle]
6331pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnWorldRender<'l>(
6332    env: JNIEnv<'l>,
6333    _class: JClass<'l>,
6334    delta_tick: jfloat,
6335    screen_w: jint,
6336    screen_h: jint,
6337    scale_factor: jfloat,
6338    view_proj_arr: JFloatArray<'l>,
6339    cam_x: jfloat,
6340    cam_y: jfloat,
6341    cam_z: jfloat,
6342    player_x: jfloat,
6343    player_y: jfloat,
6344    player_z: jfloat,
6345) {
6346    let h = handlers();
6347    if h.world_render.is_empty() {
6348        return;
6349    }
6350    let mut view_proj = [0f32; 16];
6351    if env
6352        .get_float_array_region(&view_proj_arr, 0, &mut view_proj)
6353        .is_err()
6354    {
6355        return;
6356    }
6357    let mut gfx = GFX_FN_TABLE;
6358    gfx.screen_w = screen_w;
6359    gfx.screen_h = screen_h;
6360    gfx.delta_tick = delta_tick;
6361    gfx.scale_factor = scale_factor;
6362    gfx.view_proj = view_proj;
6363    gfx.camera_pos = [cam_x, cam_y, cam_z];
6364    gfx.player_pos = [player_x, player_y, player_z];
6365    guard("on_world_render", || {
6366        for (module, ud, f) in &h.world_render {
6367            if module.is_retiring() {
6368                continue;
6369            }
6370            let Some(_call) = module.enter() else {
6371                continue;
6372            };
6373            unsafe { f(*ud, &gfx) };
6374        }
6375    });
6376}
6377
6378#[no_mangle]
6379pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnKeyPress<'l>(
6380    _env: JNIEnv<'l>,
6381    _class: JClass<'l>,
6382    key_code: jint,
6383    scan_code: jint,
6384    action: jint,
6385    modifiers: jint,
6386) -> jni::sys::jboolean {
6387    let h = handlers();
6388    if h.key_press.is_empty() {
6389        return 1;
6390    }
6391    let ev = YogKeyPressEvent {
6392        key_code,
6393        scan_code,
6394        action,
6395        modifiers,
6396    };
6397    let mut allow = true;
6398    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
6399        for (module, ud, f) in &h.key_press {
6400            if module.is_retiring() {
6401                continue;
6402            }
6403            let Some(_call) = module.enter() else {
6404                continue;
6405            };
6406            if !unsafe { f(*ud, &ev) } {
6407                allow = false;
6408                break;
6409            }
6410        }
6411    }))
6412    .ok();
6413    allow as jni::sys::jboolean
6414}
6415
6416#[no_mangle]
6417pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnScreenOpen<'l>(
6418    mut env: JNIEnv<'l>,
6419    _class: JClass<'l>,
6420    screen_class: JString<'l>,
6421) {
6422    let h = handlers();
6423    if h.screen_open.is_empty() {
6424        return;
6425    }
6426    let sc = match env.get_string(&screen_class) {
6427        Ok(s) => String::from(s),
6428        Err(_) => return,
6429    };
6430    guard("on_screen_open", || {
6431        for (module, ud, f) in &h.screen_open {
6432            if module.is_retiring() {
6433                continue;
6434            }
6435            let Some(_call) = module.enter() else {
6436                continue;
6437            };
6438            unsafe { f(*ud, YogStr::from_str(&sc)) };
6439        }
6440    });
6441}
6442
6443#[no_mangle]
6444pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnScreenClose<'l>(
6445    mut env: JNIEnv<'l>,
6446    _class: JClass<'l>,
6447    screen_class: JString<'l>,
6448) {
6449    let h = handlers();
6450    if h.screen_close.is_empty() {
6451        return;
6452    }
6453    let sc = match env.get_string(&screen_class) {
6454        Ok(s) => String::from(s),
6455        Err(_) => return,
6456    };
6457    guard("on_screen_close", || {
6458        for (module, ud, f) in &h.screen_close {
6459            if module.is_retiring() {
6460                continue;
6461            }
6462            let Some(_call) = module.enter() else {
6463                continue;
6464            };
6465            unsafe { f(*ud, YogStr::from_str(&sc)) };
6466        }
6467    });
6468}
6469
6470mod control_socket;
6471mod images;
6472mod ui_jni;