Skip to main content

yog_runtime/
lib.rs

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