Skip to main content

yog_api/
registry.rs

1//! Registration hub and mod entry-point trait.
2//!
3//! [`Registry`] wraps the [`YogApi`] C table passed to `yog_mod_register` and
4//! provides an ergonomic Rust API over it.  All closures registered here are
5//! boxed on the heap and their raw pointers handed to the runtime; the runtime
6//! then drives them via C function-pointer calls.  Closures are intentionally
7//! leaked (never freed) — they live for the entire process lifetime, which is
8//! correct for a game server.
9
10use std::os::raw::c_void;
11
12use yog_abi::{
13    YogAdvancementEvent, YogApi, YogAttackEntityEvent, YogBlockBreakEvent, YogBlockDef,
14    YogChatEvent, YogCommandEvent, YogContainerCloseEvent, YogContainerOpenEvent, YogCraftEvent,
15    YogEntityDamageEvent, YogEntityDeathEvent, YogEntityInteractEvent, YogEntitySpawnEvent,
16    YogExplosionEvent, YogGfxApi, YogInventoryDef, YogItemDef, YogItemPickupEvent,
17    YogKeyPressEvent, YogPacketEvent, YogPlaceBlockEvent, YogPlayerDeathEvent, YogPlayerEvent,
18    YogPlayerMoveEvent, YogPlayerRespawnEvent, YogProjectileHitEvent, YogServer,
19    YogStartupGrantDef, YogStr, YogUseBlockEvent, YogUseItemEvent,
20};
21use yog_book::Book;
22use yog_command::CommandContext;
23use yog_core::Server;
24use yog_dimensions::{ChunkWriter, YogDimensionDef};
25use yog_event::{
26    AdvancementEvent, AttackEntityEvent, BlockBreakEvent, ChatEvent, ClientTickEvent,
27    ContainerCloseEvent, ContainerOpenEvent, CraftEvent, EntityDamageEvent, EntityDeathEvent,
28    EntityInteractEvent, EntitySpawnEvent, EventPhase, ExplosionEvent, ItemPickupEvent,
29    KeyPressEvent, PlaceBlockEvent, PlayerDeathEvent, PlayerJoinEvent, PlayerLeaveEvent,
30    PlayerMoveEvent, PlayerRespawnEvent, ProjectileHitEvent, ScreenEvent, UseBlockEvent,
31    UseItemEvent,
32};
33use yog_gfx::GfxContext;
34use yog_network::{Packet, PacketEvent};
35use yog_registry::{BlockDef, FurnaceRecipe, ItemDef, ShapedRecipe, ShapelessRecipe, StartupGrant};
36
37// ── CServer — implements Server via the YogServer function table ──────────────
38
39/// A handle to the runtime's server actions, backed by [`YogServer`] fn pointers.
40/// Given to every handler as `&dyn Server`.
41pub struct CServer(pub *const YogServer);
42
43unsafe impl Send for CServer {}
44unsafe impl Sync for CServer {}
45
46macro_rules! srv {
47    ($self:ident) => {
48        unsafe { &*$self.0 }
49    };
50}
51
52impl Server for CServer {
53    fn broadcast(&self, message: &str) {
54        let s = srv!(self);
55        unsafe { (s.broadcast)(s.ctx, YogStr::from_str(message)) }
56    }
57
58    fn get_block(&self, dimension: &str, pos: yog_core::BlockPos) -> Option<String> {
59        let s = srv!(self);
60        let owned = unsafe {
61            (s.get_block)(
62                s.ctx,
63                YogStr::from_str(dimension),
64                yog_abi::YogBlockPos {
65                    x: pos.x,
66                    y: pos.y,
67                    z: pos.z,
68                },
69            )
70        };
71        if owned.is_none() {
72            return None;
73        }
74        let result = unsafe {
75            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
76                .ok()
77        };
78        unsafe { (s.free_str)(owned.ptr, owned.len) };
79        result
80    }
81
82    fn set_block(&self, dimension: &str, pos: yog_core::BlockPos, block_id: &str) -> bool {
83        let s = srv!(self);
84        unsafe {
85            (s.set_block)(
86                s.ctx,
87                YogStr::from_str(dimension),
88                yog_abi::YogBlockPos {
89                    x: pos.x,
90                    y: pos.y,
91                    z: pos.z,
92                },
93                YogStr::from_str(block_id),
94            )
95        }
96    }
97
98    fn give_item(&self, player: &str, item_id: &str, count: u32) -> bool {
99        let s = srv!(self);
100        unsafe {
101            (s.give_item)(
102                s.ctx,
103                YogStr::from_str(player),
104                YogStr::from_str(item_id),
105                count,
106            )
107        }
108    }
109
110    fn teleport(&self, player: &str, x: f64, y: f64, z: f64) -> bool {
111        let s = srv!(self);
112        unsafe {
113            (s.player_teleport)(
114                s.ctx,
115                YogStr::from_str(player),
116                yog_abi::YogVec3 { x, y, z },
117            )
118        }
119    }
120
121    fn send_to_player(&self, player: &str, channel: &str, payload: &[u8]) -> bool {
122        let s = srv!(self);
123        unsafe {
124            (s.send_to_player)(
125                s.ctx,
126                YogStr::from_str(player),
127                YogStr::from_str(channel),
128                payload.as_ptr(),
129                payload.len() as u32,
130            )
131        }
132    }
133
134    fn send_to_server(&self, channel: &str, payload: &[u8]) -> bool {
135        let s = srv!(self);
136        unsafe {
137            (s.send_to_server)(
138                s.ctx,
139                YogStr::from_str(channel),
140                payload.as_ptr(),
141                payload.len() as u32,
142            )
143        }
144    }
145
146    fn entity_teleport(&self, uuid: &str, x: f64, y: f64, z: f64) -> bool {
147        let s = srv!(self);
148        unsafe { (s.entity_teleport)(s.ctx, YogStr::from_str(uuid), yog_abi::YogVec3 { x, y, z }) }
149    }
150
151    fn entity_position(&self, uuid: &str) -> Option<(f64, f64, f64)> {
152        let s = srv!(self);
153        let mut out = yog_abi::YogVec3 {
154            x: 0.0,
155            y: 0.0,
156            z: 0.0,
157        };
158        if unsafe { (s.entity_position)(s.ctx, YogStr::from_str(uuid), &mut out) } {
159            Some((out.x, out.y, out.z))
160        } else {
161            None
162        }
163    }
164
165    fn entity_health(&self, uuid: &str) -> Option<f32> {
166        let s = srv!(self);
167        let mut hp = 0f32;
168        if unsafe { (s.entity_health)(s.ctx, YogStr::from_str(uuid), &mut hp) } {
169            Some(hp)
170        } else {
171            None
172        }
173    }
174
175    fn entity_set_health(&self, uuid: &str, health: f32) -> bool {
176        let s = srv!(self);
177        unsafe { (s.entity_set_health)(s.ctx, YogStr::from_str(uuid), health) }
178    }
179
180    fn entity_kill(&self, uuid: &str) -> bool {
181        let s = srv!(self);
182        unsafe { (s.entity_kill)(s.ctx, YogStr::from_str(uuid)) }
183    }
184
185    fn spawn_entity(
186        &self,
187        entity_type: &str,
188        dimension: &str,
189        x: f64,
190        y: f64,
191        z: f64,
192    ) -> Option<String> {
193        let s = srv!(self);
194        let owned = unsafe {
195            (s.spawn_entity)(
196                s.ctx,
197                YogStr::from_str(entity_type),
198                YogStr::from_str(dimension),
199                yog_abi::YogVec3 { x, y, z },
200            )
201        };
202        if owned.is_none() {
203            return None;
204        }
205        let result = unsafe {
206            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
207                .ok()
208        };
209        unsafe { (s.free_str)(owned.ptr, owned.len) };
210        result
211    }
212
213    fn entity_add_effect(
214        &self,
215        uuid: &str,
216        effect_id: &str,
217        duration_ticks: i32,
218        amplifier: u8,
219        show_particles: bool,
220    ) -> bool {
221        let s = srv!(self);
222        unsafe {
223            (s.entity_add_effect)(
224                s.ctx,
225                YogStr::from_str(uuid),
226                YogStr::from_str(effect_id),
227                duration_ticks,
228                amplifier,
229                show_particles,
230            )
231        }
232    }
233
234    fn entity_remove_effect(&self, uuid: &str, effect_id: &str) -> bool {
235        let s = srv!(self);
236        unsafe {
237            (s.entity_remove_effect)(s.ctx, YogStr::from_str(uuid), YogStr::from_str(effect_id))
238        }
239    }
240
241    fn entity_clear_effects(&self, uuid: &str) -> bool {
242        let s = srv!(self);
243        unsafe { (s.entity_clear_effects)(s.ctx, YogStr::from_str(uuid)) }
244    }
245
246    fn drop_loot(&self, table_id: &str, dimension: &str, x: f64, y: f64, z: f64) -> bool {
247        let s = srv!(self);
248        unsafe {
249            (s.drop_loot)(
250                s.ctx,
251                YogStr::from_str(table_id),
252                YogStr::from_str(dimension),
253                yog_abi::YogVec3 { x, y, z },
254            )
255        }
256    }
257
258    fn has_item_tag(&self, item_id: &str, tag_id: &str) -> bool {
259        let s = srv!(self);
260        unsafe { (s.has_item_tag)(s.ctx, YogStr::from_str(item_id), YogStr::from_str(tag_id)) }
261    }
262
263    fn has_block_tag(&self, block_id: &str, tag_id: &str) -> bool {
264        let s = srv!(self);
265        unsafe { (s.has_block_tag)(s.ctx, YogStr::from_str(block_id), YogStr::from_str(tag_id)) }
266    }
267
268    fn world_time(&self, dimension: &str) -> Option<i64> {
269        let s = srv!(self);
270        let mut t = 0i64;
271        if unsafe { (s.world_time)(s.ctx, YogStr::from_str(dimension), &mut t) } {
272            Some(t)
273        } else {
274            None
275        }
276    }
277
278    fn world_set_time(&self, dimension: &str, time: i64) -> bool {
279        let s = srv!(self);
280        unsafe { (s.set_time)(s.ctx, YogStr::from_str(dimension), time) }
281    }
282
283    fn world_is_raining(&self, dimension: &str) -> bool {
284        let s = srv!(self);
285        unsafe { (s.is_raining)(s.ctx, YogStr::from_str(dimension)) }
286    }
287
288    fn world_set_weather(&self, dimension: &str, raining: bool, duration_ticks: i32) -> bool {
289        let s = srv!(self);
290        unsafe { (s.set_weather)(s.ctx, YogStr::from_str(dimension), raining, duration_ticks) }
291    }
292
293    fn entity_velocity(&self, uuid: &str) -> Option<(f64, f64, f64)> {
294        let s = srv!(self);
295        let mut v = yog_abi::YogVec3 {
296            x: 0.0,
297            y: 0.0,
298            z: 0.0,
299        };
300        if unsafe { (s.entity_velocity)(s.ctx, YogStr::from_str(uuid), &mut v) } {
301            Some((v.x, v.y, v.z))
302        } else {
303            None
304        }
305    }
306
307    fn entity_set_velocity(&self, uuid: &str, vx: f64, vy: f64, vz: f64) -> bool {
308        let s = srv!(self);
309        unsafe {
310            (s.entity_set_velocity)(
311                s.ctx,
312                YogStr::from_str(uuid),
313                yog_abi::YogVec3 {
314                    x: vx,
315                    y: vy,
316                    z: vz,
317                },
318            )
319        }
320    }
321
322    fn entity_add_velocity(&self, uuid: &str, vx: f64, vy: f64, vz: f64) -> bool {
323        let s = srv!(self);
324        unsafe {
325            (s.entity_add_velocity)(
326                s.ctx,
327                YogStr::from_str(uuid),
328                yog_abi::YogVec3 {
329                    x: vx,
330                    y: vy,
331                    z: vz,
332                },
333            )
334        }
335    }
336
337    fn scoreboard_get(&self, objective: &str, player: &str) -> Option<i32> {
338        let s = srv!(self);
339        let mut score = 0i32;
340        if unsafe {
341            (s.scoreboard_get)(
342                s.ctx,
343                YogStr::from_str(objective),
344                YogStr::from_str(player),
345                &mut score,
346            )
347        } {
348            Some(score)
349        } else {
350            None
351        }
352    }
353
354    fn scoreboard_set(&self, objective: &str, player: &str, score: i32) -> bool {
355        let s = srv!(self);
356        unsafe {
357            (s.scoreboard_set)(
358                s.ctx,
359                YogStr::from_str(objective),
360                YogStr::from_str(player),
361                score,
362            )
363        }
364    }
365
366    fn scoreboard_add(&self, objective: &str, player: &str, delta: i32) -> Option<i32> {
367        let s = srv!(self);
368        let mut new_score = 0i32;
369        if unsafe {
370            (s.scoreboard_add)(
371                s.ctx,
372                YogStr::from_str(objective),
373                YogStr::from_str(player),
374                delta,
375                &mut new_score,
376            )
377        } {
378            Some(new_score)
379        } else {
380            None
381        }
382    }
383
384    fn game_dir(&self) -> String {
385        let s = srv!(self);
386        let owned = unsafe { (s.game_dir)(s.ctx) };
387        if owned.is_none() {
388            return String::new();
389        }
390        let result = unsafe {
391            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
392                .unwrap_or_default()
393        };
394        unsafe { (s.free_str)(owned.ptr, owned.len) };
395        result
396    }
397
398    fn play_sound(
399        &self,
400        dimension: &str,
401        x: f64,
402        y: f64,
403        z: f64,
404        sound_id: &str,
405        volume: f32,
406        pitch: f32,
407    ) -> bool {
408        let s = srv!(self);
409        unsafe {
410            (s.play_sound)(
411                s.ctx,
412                YogStr::from_str(dimension),
413                yog_abi::YogVec3 { x, y, z },
414                YogStr::from_str(sound_id),
415                volume,
416                pitch,
417            )
418        }
419    }
420
421    fn play_sound_to_player(&self, player: &str, sound_id: &str, volume: f32, pitch: f32) -> bool {
422        let s = srv!(self);
423        unsafe {
424            (s.play_sound_player)(
425                s.ctx,
426                YogStr::from_str(player),
427                YogStr::from_str(sound_id),
428                volume,
429                pitch,
430            )
431        }
432    }
433
434    fn send_title(
435        &self,
436        player: &str,
437        title: &str,
438        subtitle: &str,
439        fadein: i32,
440        stay: i32,
441        fadeout: i32,
442    ) -> bool {
443        let s = srv!(self);
444        unsafe {
445            (s.send_title)(
446                s.ctx,
447                YogStr::from_str(player),
448                YogStr::from_str(title),
449                YogStr::from_str(subtitle),
450                fadein,
451                stay,
452                fadeout,
453            )
454        }
455    }
456
457    fn entity_rotation(&self, uuid: &str) -> Option<(f32, f32)> {
458        let s = srv!(self);
459        let mut out = yog_abi::YogVec3 {
460            x: 0.0,
461            y: 0.0,
462            z: 0.0,
463        };
464        let ok = unsafe { (s.entity_rotation)(s.ctx, YogStr::from_str(uuid), &mut out) };
465        if ok {
466            Some((out.x as f32, out.y as f32))
467        } else {
468            None
469        }
470    }
471
472    fn send_actionbar(&self, player: &str, message: &str) -> bool {
473        let s = srv!(self);
474        unsafe { (s.send_actionbar)(s.ctx, YogStr::from_str(player), YogStr::from_str(message)) }
475    }
476
477    fn kick_player(&self, player: &str, reason: &str) -> bool {
478        let s = srv!(self);
479        unsafe { (s.kick_player)(s.ctx, YogStr::from_str(player), YogStr::from_str(reason)) }
480    }
481
482    fn set_gamemode(&self, player: &str, gamemode: &str) -> bool {
483        let s = srv!(self);
484        unsafe { (s.set_gamemode)(s.ctx, YogStr::from_str(player), YogStr::from_str(gamemode)) }
485    }
486
487    fn bossbar_create(&self, id: &str, title: &str, color: &str, style: &str) -> bool {
488        let s = srv!(self);
489        unsafe {
490            (s.bossbar_create)(
491                s.ctx,
492                YogStr::from_str(id),
493                YogStr::from_str(title),
494                YogStr::from_str(color),
495                YogStr::from_str(style),
496            )
497        }
498    }
499
500    fn bossbar_remove(&self, id: &str) -> bool {
501        let s = srv!(self);
502        unsafe { (s.bossbar_remove)(s.ctx, YogStr::from_str(id)) }
503    }
504
505    fn bossbar_set_title(&self, id: &str, title: &str) -> bool {
506        let s = srv!(self);
507        unsafe { (s.bossbar_set_title)(s.ctx, YogStr::from_str(id), YogStr::from_str(title)) }
508    }
509
510    fn bossbar_set_progress(&self, id: &str, progress: f32) -> bool {
511        let s = srv!(self);
512        unsafe { (s.bossbar_set_progress)(s.ctx, YogStr::from_str(id), progress) }
513    }
514
515    fn bossbar_set_color(&self, id: &str, color: &str) -> bool {
516        let s = srv!(self);
517        unsafe { (s.bossbar_set_color)(s.ctx, YogStr::from_str(id), YogStr::from_str(color)) }
518    }
519
520    fn bossbar_add_player(&self, id: &str, player: &str) -> bool {
521        let s = srv!(self);
522        unsafe { (s.bossbar_add_player)(s.ctx, YogStr::from_str(id), YogStr::from_str(player)) }
523    }
524
525    fn bossbar_remove_player(&self, id: &str, player: &str) -> bool {
526        let s = srv!(self);
527        unsafe { (s.bossbar_remove_player)(s.ctx, YogStr::from_str(id), YogStr::from_str(player)) }
528    }
529
530    fn bossbar_set_visible(&self, id: &str, visible: bool) -> bool {
531        let s = srv!(self);
532        unsafe { (s.bossbar_set_visible)(s.ctx, YogStr::from_str(id), visible) }
533    }
534
535    fn online_players(&self) -> Vec<String> {
536        let s = srv!(self);
537        let owned = unsafe { (s.online_players)(s.ctx) };
538        if owned.is_none() {
539            return Vec::new();
540        }
541        let text = unsafe {
542            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
543                .unwrap_or_default()
544        };
545        unsafe { (s.free_str)(owned.ptr, owned.len) };
546        if text.is_empty() {
547            Vec::new()
548        } else {
549            text.lines().map(str::to_owned).collect()
550        }
551    }
552
553    fn get_block_nbt(&self, dimension: &str, pos: yog_core::BlockPos) -> Option<String> {
554        let s = srv!(self);
555        let owned = unsafe {
556            (s.get_block_nbt)(
557                s.ctx,
558                YogStr::from_str(dimension),
559                yog_abi::YogBlockPos {
560                    x: pos.x,
561                    y: pos.y,
562                    z: pos.z,
563                },
564            )
565        };
566        if owned.is_none() {
567            return None;
568        }
569        let result = unsafe {
570            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
571                .ok()
572        };
573        unsafe { (s.free_str)(owned.ptr, owned.len) };
574        result
575    }
576
577    fn set_block_nbt(&self, dimension: &str, pos: yog_core::BlockPos, snbt: &str) -> bool {
578        let s = srv!(self);
579        unsafe {
580            (s.set_block_nbt)(
581                s.ctx,
582                YogStr::from_str(dimension),
583                yog_abi::YogBlockPos {
584                    x: pos.x,
585                    y: pos.y,
586                    z: pos.z,
587                },
588                YogStr::from_str(snbt),
589            )
590        }
591    }
592
593    fn get_inventory_slot(
594        &self,
595        dimension: &str,
596        pos: yog_core::BlockPos,
597        slot: u32,
598    ) -> Option<(String, u32)> {
599        let s = srv!(self);
600        let owned = unsafe {
601            (s.get_inventory_slot)(
602                s.ctx,
603                YogStr::from_str(dimension),
604                yog_abi::YogBlockPos {
605                    x: pos.x,
606                    y: pos.y,
607                    z: pos.z,
608                },
609                slot,
610            )
611        };
612        if owned.is_none() {
613            return None;
614        }
615        let text = unsafe {
616            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
617                .unwrap_or_default()
618        };
619        unsafe { (s.free_str)(owned.ptr, owned.len) };
620        let (item_id, count) = text.split_once('\t')?;
621        Some((item_id.to_owned(), count.parse().ok()?))
622    }
623
624    fn set_inventory_slot(
625        &self,
626        dimension: &str,
627        pos: yog_core::BlockPos,
628        slot: u32,
629        item_id: &str,
630        count: u32,
631    ) -> bool {
632        let s = srv!(self);
633        unsafe {
634            (s.set_inventory_slot)(
635                s.ctx,
636                YogStr::from_str(dimension),
637                yog_abi::YogBlockPos {
638                    x: pos.x,
639                    y: pos.y,
640                    z: pos.z,
641                },
642                slot,
643                YogStr::from_str(item_id),
644                count,
645            )
646        }
647    }
648
649    fn player_inventory(&self, player: &str) -> Vec<(u32, String, u32)> {
650        let s = srv!(self);
651        let owned = unsafe { (s.player_inventory)(s.ctx, YogStr::from_str(player)) };
652        if owned.is_none() {
653            return Vec::new();
654        }
655        let text = unsafe {
656            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
657                .unwrap_or_default()
658        };
659        unsafe { (s.free_str)(owned.ptr, owned.len) };
660        text.lines()
661            .filter_map(|line| {
662                let mut it = line.split('\t');
663                let slot: u32 = it.next()?.parse().ok()?;
664                let item_id = it.next()?.to_owned();
665                let count: u32 = it.next()?.parse().ok()?;
666                Some((slot, item_id, count))
667            })
668            .collect()
669    }
670
671    fn player_set_slot(&self, player: &str, slot: u32, item_id: &str, count: u32) -> bool {
672        let s = srv!(self);
673        unsafe {
674            (s.player_set_slot)(
675                s.ctx,
676                YogStr::from_str(player),
677                slot,
678                YogStr::from_str(item_id),
679                count,
680            )
681        }
682    }
683
684    fn teleport_to_dim(&self, player: &str, dimension: &str, x: f64, y: f64, z: f64) -> bool {
685        let s = srv!(self);
686        unsafe {
687            (s.player_teleport_dim)(
688                s.ctx,
689                YogStr::from_str(player),
690                YogStr::from_str(dimension),
691                yog_abi::YogVec3 { x, y, z },
692            )
693        }
694    }
695
696    fn entity_teleport_to_dim(&self, uuid: &str, dimension: &str, x: f64, y: f64, z: f64) -> bool {
697        let s = srv!(self);
698        unsafe {
699            (s.entity_teleport_dim)(
700                s.ctx,
701                YogStr::from_str(uuid),
702                YogStr::from_str(dimension),
703                yog_abi::YogVec3 { x, y, z },
704            )
705        }
706    }
707
708    fn world_entity_count(&self, dimension: &str, entity_type: &str) -> i32 {
709        let s = srv!(self);
710        unsafe {
711            (s.world_entity_count)(
712                s.ctx,
713                YogStr::from_str(dimension),
714                YogStr::from_str(entity_type),
715            )
716        }
717    }
718
719    fn entity_get_nbt(&self, uuid: &str) -> Option<String> {
720        let s = srv!(self);
721        let owned = unsafe { (s.entity_get_nbt)(s.ctx, YogStr::from_str(uuid)) };
722        if owned.is_none() {
723            return None;
724        }
725        let result = unsafe {
726            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
727                .ok()
728        };
729        unsafe { (s.free_str)(owned.ptr, owned.len) };
730        result
731    }
732
733    fn entity_set_nbt(&self, uuid: &str, snbt: &str) -> bool {
734        let s = srv!(self);
735        unsafe { (s.entity_set_nbt)(s.ctx, YogStr::from_str(uuid), YogStr::from_str(snbt)) }
736    }
737
738    fn spawn_particles(
739        &self,
740        dimension: &str,
741        x: f64,
742        y: f64,
743        z: f64,
744        particle_type: &str,
745        count: i32,
746        dx: f64,
747        dy: f64,
748        dz: f64,
749        speed: f64,
750    ) -> bool {
751        let s = srv!(self);
752        unsafe {
753            (s.spawn_particles)(
754                s.ctx,
755                YogStr::from_str(dimension),
756                yog_abi::YogVec3 { x, y, z },
757                YogStr::from_str(particle_type),
758                count,
759                dx,
760                dy,
761                dz,
762                speed,
763            )
764        }
765    }
766
767    fn entity_attribute_get(&self, uuid: &str, attribute_id: &str) -> Option<f64> {
768        let s = srv!(self);
769        let v = unsafe {
770            (s.entity_attribute_get)(
771                s.ctx,
772                YogStr::from_str(uuid),
773                YogStr::from_str(attribute_id),
774            )
775        };
776        if v.is_nan() {
777            None
778        } else {
779            Some(v)
780        }
781    }
782
783    fn entity_attribute_set(&self, uuid: &str, attribute_id: &str, value: f64) -> bool {
784        let s = srv!(self);
785        unsafe {
786            (s.entity_attribute_set)(
787                s.ctx,
788                YogStr::from_str(uuid),
789                YogStr::from_str(attribute_id),
790                value,
791            )
792        }
793    }
794
795    fn get_held_item_nbt(&self, player: &str) -> Option<String> {
796        let s = srv!(self);
797        let owned = unsafe { (s.get_held_item_nbt)(s.ctx, YogStr::from_str(player)) };
798        if owned.is_none() {
799            return None;
800        }
801        let result = unsafe {
802            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
803                .ok()
804        };
805        unsafe { (s.free_str)(owned.ptr, owned.len) };
806        result
807    }
808
809    fn set_held_item_nbt(&self, player: &str, snbt: &str) -> bool {
810        let s = srv!(self);
811        unsafe { (s.set_held_item_nbt)(s.ctx, YogStr::from_str(player), YogStr::from_str(snbt)) }
812    }
813
814    fn get_offhand_item_nbt(&self, player: &str) -> Option<String> {
815        let s = srv!(self);
816        let owned = unsafe { (s.get_offhand_item_nbt)(s.ctx, YogStr::from_str(player)) };
817        if owned.is_none() {
818            return None;
819        }
820        let result = unsafe {
821            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
822                .ok()
823        };
824        unsafe { (s.free_str)(owned.ptr, owned.len) };
825        result
826    }
827
828    fn set_offhand_item_nbt(&self, player: &str, snbt: &str) -> bool {
829        let s = srv!(self);
830        unsafe { (s.set_offhand_item_nbt)(s.ctx, YogStr::from_str(player), YogStr::from_str(snbt)) }
831    }
832
833    fn get_slot_item(&self, player: &str, slot: u32) -> Option<(String, u32, String)> {
834        let s = srv!(self);
835        let owned = unsafe { (s.get_slot_item)(s.ctx, YogStr::from_str(player), slot) };
836        if owned.is_none() {
837            return None;
838        }
839        let text = unsafe {
840            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
841                .unwrap_or_default()
842        };
843        unsafe { (s.free_str)(owned.ptr, owned.len) };
844        let mut it = text.splitn(3, '\t');
845        let item_id = it.next()?.to_owned();
846        let count: u32 = it.next()?.parse().ok()?;
847        let nbt = it.next().unwrap_or("{}").to_owned();
848        Some((item_id, count, nbt))
849    }
850
851    fn set_slot_item(
852        &self,
853        player: &str,
854        slot: u32,
855        item_id: &str,
856        count: u32,
857        snbt: &str,
858    ) -> bool {
859        let s = srv!(self);
860        unsafe {
861            (s.set_slot_item)(
862                s.ctx,
863                YogStr::from_str(player),
864                slot,
865                YogStr::from_str(item_id),
866                count,
867                YogStr::from_str(snbt),
868            )
869        }
870    }
871}
872
873// ── Trampoline helpers ────────────────────────────────────────────────────────
874//
875// Each trampoline is a `unsafe extern "C" fn` that:
876//   1. Casts `ud` back to the original boxed closure.
877//   2. Converts ABI C structs to Rust event types.
878//   3. Builds a `CServer` from the `*const YogServer`.
879//   4. Calls the closure.
880//
881// Closures are Box::into_raw'd in Registry methods — they are INTENTIONALLY
882// leaked and live for the process lifetime.
883
884// ── Trampoline helpers ────────────────────────────────────────────────────────
885//
886// All phased event trampolines share the same pattern:
887//   `phase: u8`  0 = EventPhase::Pre, 1 = EventPhase::Post
888//   Return value is meaningful only in Pre phase.
889
890macro_rules! trampoline_phased {
891    ($name:ident, $abi_ev:ty, $rust_ev:ty, |$ev:ident| $build:expr) => {
892        unsafe extern "C" fn $name<F>(
893            ud: *mut c_void,
894            srv: *const YogServer,
895            ev: *const $abi_ev,
896            phase: u8,
897        ) -> bool
898        where
899            F: Fn(&$rust_ev, EventPhase, &dyn Server) -> bool + Send + Sync,
900        {
901            let f = &*(ud as *const F);
902            let $ev = &*ev;
903            let rust_ev = $build;
904            let p = if phase == 0 {
905                EventPhase::Pre
906            } else {
907                EventPhase::Post
908            };
909            f(&rust_ev, p, &CServer(srv))
910        }
911    };
912}
913
914trampoline_phased!(
915    trampoline_block_break,
916    YogBlockBreakEvent,
917    BlockBreakEvent,
918    |ev| BlockBreakEvent {
919        player_name: ev.player.as_str().to_owned(),
920        block_id: ev.block.as_str().to_owned(),
921        pos: yog_core::BlockPos {
922            x: ev.pos.x,
923            y: ev.pos.y,
924            z: ev.pos.z
925        },
926        dimension: ev.dimension.as_str().to_owned(),
927    }
928);
929
930trampoline_phased!(trampoline_chat, YogChatEvent, ChatEvent, |ev| ChatEvent {
931    player_name: ev.player.as_str().to_owned(),
932    message: ev.message.as_str().to_owned(),
933    dimension: ev.dimension.as_str().to_owned(),
934});
935
936trampoline_phased!(
937    trampoline_player_join,
938    YogPlayerEvent,
939    PlayerJoinEvent,
940    |ev| PlayerJoinEvent {
941        player_name: ev.player.as_str().to_owned(),
942        uuid: ev.uuid.as_str().to_owned(),
943        dimension: ev.dimension.as_str().to_owned(),
944    }
945);
946
947trampoline_phased!(
948    trampoline_player_leave,
949    YogPlayerEvent,
950    PlayerLeaveEvent,
951    |ev| PlayerLeaveEvent {
952        player_name: ev.player.as_str().to_owned(),
953        uuid: ev.uuid.as_str().to_owned(),
954        dimension: ev.dimension.as_str().to_owned(),
955    }
956);
957
958trampoline_phased!(trampoline_use_item, YogUseItemEvent, UseItemEvent, |ev| {
959    UseItemEvent {
960        player_name: ev.player.as_str().to_owned(),
961        item_id: ev.item.as_str().to_owned(),
962        sneaking: ev.sneaking,
963        dimension: ev.dimension.as_str().to_owned(),
964    }
965});
966
967trampoline_phased!(
968    trampoline_use_block,
969    YogUseBlockEvent,
970    UseBlockEvent,
971    |ev| UseBlockEvent {
972        player_name: ev.player.as_str().to_owned(),
973        block_id: ev.block.as_str().to_owned(),
974        pos: yog_core::BlockPos {
975            x: ev.pos.x,
976            y: ev.pos.y,
977            z: ev.pos.z
978        },
979        dimension: ev.dimension.as_str().to_owned(),
980    }
981);
982
983trampoline_phased!(
984    trampoline_attack_entity,
985    YogAttackEntityEvent,
986    AttackEntityEvent,
987    |ev| AttackEntityEvent {
988        player_name: ev.player.as_str().to_owned(),
989        target_type: ev.target_type.as_str().to_owned(),
990        target_uuid: ev.target_uuid.as_str().to_owned(),
991        dimension: ev.dimension.as_str().to_owned(),
992    }
993);
994
995trampoline_phased!(
996    trampoline_entity_damage,
997    YogEntityDamageEvent,
998    EntityDamageEvent,
999    |ev| EntityDamageEvent {
1000        entity_type: ev.entity_type.as_str().to_owned(),
1001        uuid: ev.uuid.as_str().to_owned(),
1002        amount: ev.amount,
1003        source: ev.source.as_str().to_owned(),
1004        dimension: ev.dimension.as_str().to_owned(),
1005    }
1006);
1007
1008trampoline_phased!(
1009    trampoline_entity_death,
1010    YogEntityDeathEvent,
1011    EntityDeathEvent,
1012    |ev| EntityDeathEvent {
1013        entity_type: ev.entity_type.as_str().to_owned(),
1014        uuid: ev.uuid.as_str().to_owned(),
1015        source: ev.source.as_str().to_owned(),
1016        dimension: ev.dimension.as_str().to_owned(),
1017    }
1018);
1019
1020trampoline_phased!(
1021    trampoline_entity_spawn,
1022    YogEntitySpawnEvent,
1023    EntitySpawnEvent,
1024    |ev| EntitySpawnEvent {
1025        entity_type: ev.entity_type.as_str().to_owned(),
1026        uuid: ev.uuid.as_str().to_owned(),
1027        dimension: ev.dimension.as_str().to_owned(),
1028    }
1029);
1030
1031trampoline_phased!(
1032    trampoline_place_block,
1033    YogPlaceBlockEvent,
1034    PlaceBlockEvent,
1035    |ev| PlaceBlockEvent {
1036        player_name: ev.player.as_str().to_owned(),
1037        block_id: ev.block.as_str().to_owned(),
1038        pos: yog_core::BlockPos {
1039            x: ev.pos.x,
1040            y: ev.pos.y,
1041            z: ev.pos.z
1042        },
1043        dimension: ev.dimension.as_str().to_owned(),
1044    }
1045);
1046
1047trampoline_phased!(
1048    trampoline_player_death,
1049    YogPlayerDeathEvent,
1050    PlayerDeathEvent,
1051    |ev| PlayerDeathEvent {
1052        player_name: ev.player.as_str().to_owned(),
1053        uuid: ev.uuid.as_str().to_owned(),
1054        source: ev.source.as_str().to_owned(),
1055        dimension: ev.dimension.as_str().to_owned(),
1056    }
1057);
1058
1059trampoline_phased!(
1060    trampoline_player_respawn,
1061    YogPlayerRespawnEvent,
1062    PlayerRespawnEvent,
1063    |ev| PlayerRespawnEvent {
1064        player_name: ev.player.as_str().to_owned(),
1065        uuid: ev.uuid.as_str().to_owned(),
1066        at_anchor: ev.at_anchor,
1067        dimension: ev.dimension.as_str().to_owned(),
1068    }
1069);
1070
1071trampoline_phased!(
1072    trampoline_advancement,
1073    YogAdvancementEvent,
1074    AdvancementEvent,
1075    |ev| AdvancementEvent {
1076        player_name: ev.player.as_str().to_owned(),
1077        uuid: ev.uuid.as_str().to_owned(),
1078        advancement_id: ev.advancement.as_str().to_owned(),
1079        dimension: ev.dimension.as_str().to_owned(),
1080    }
1081);
1082
1083trampoline_phased!(
1084    trampoline_entity_interact,
1085    YogEntityInteractEvent,
1086    EntityInteractEvent,
1087    |ev| EntityInteractEvent {
1088        player_name: ev.player.as_str().to_owned(),
1089        player_uuid: ev.player_uuid.as_str().to_owned(),
1090        entity_type: ev.entity_type.as_str().to_owned(),
1091        entity_uuid: ev.entity_uuid.as_str().to_owned(),
1092        hand: ev.hand.as_str().to_owned(),
1093        dimension: ev.dimension.as_str().to_owned(),
1094    }
1095);
1096
1097trampoline_phased!(trampoline_craft, YogCraftEvent, CraftEvent, |ev| {
1098    CraftEvent {
1099        player_name: ev.player.as_str().to_owned(),
1100        player_uuid: ev.player_uuid.as_str().to_owned(),
1101        result_item: ev.result_item.as_str().to_owned(),
1102        result_count: ev.result_count,
1103        dimension: ev.dimension.as_str().to_owned(),
1104    }
1105});
1106
1107trampoline_phased!(
1108    trampoline_explosion,
1109    YogExplosionEvent,
1110    ExplosionEvent,
1111    |ev| ExplosionEvent {
1112        dimension: ev.dimension.as_str().to_owned(),
1113        x: ev.x,
1114        y: ev.y,
1115        z: ev.z,
1116        power: ev.power,
1117        cause_uuid: ev.cause_uuid.as_str().to_owned(),
1118    }
1119);
1120
1121trampoline_phased!(
1122    trampoline_item_pickup,
1123    YogItemPickupEvent,
1124    ItemPickupEvent,
1125    |ev| ItemPickupEvent {
1126        player_name: ev.player.as_str().to_owned(),
1127        player_uuid: ev.player_uuid.as_str().to_owned(),
1128        item_id: ev.item_id.as_str().to_owned(),
1129        item_count: ev.item_count,
1130        entity_uuid: ev.entity_uuid.as_str().to_owned(),
1131        dimension: ev.dimension.as_str().to_owned(),
1132    }
1133);
1134
1135trampoline_phased!(
1136    trampoline_player_move,
1137    YogPlayerMoveEvent,
1138    PlayerMoveEvent,
1139    |ev| PlayerMoveEvent {
1140        player_name: ev.player.as_str().to_owned(),
1141        player_uuid: ev.player_uuid.as_str().to_owned(),
1142        x: ev.x,
1143        y: ev.y,
1144        z: ev.z,
1145        yaw: ev.yaw,
1146        pitch: ev.pitch,
1147        dimension: ev.dimension.as_str().to_owned(),
1148    }
1149);
1150
1151trampoline_phased!(
1152    trampoline_container_open,
1153    YogContainerOpenEvent,
1154    ContainerOpenEvent,
1155    |ev| ContainerOpenEvent {
1156        player_name: ev.player.as_str().to_owned(),
1157        player_uuid: ev.player_uuid.as_str().to_owned(),
1158        container_type: ev.container_type.as_str().to_owned(),
1159        dimension: ev.dimension.as_str().to_owned(),
1160    }
1161);
1162
1163trampoline_phased!(
1164    trampoline_container_close,
1165    YogContainerCloseEvent,
1166    ContainerCloseEvent,
1167    |ev| ContainerCloseEvent {
1168        player_name: ev.player.as_str().to_owned(),
1169        player_uuid: ev.player_uuid.as_str().to_owned(),
1170        dimension: ev.dimension.as_str().to_owned(),
1171    }
1172);
1173
1174trampoline_phased!(
1175    trampoline_projectile_hit,
1176    YogProjectileHitEvent,
1177    ProjectileHitEvent,
1178    |ev| ProjectileHitEvent {
1179        projectile_type: ev.projectile_type.as_str().to_owned(),
1180        projectile_uuid: ev.projectile_uuid.as_str().to_owned(),
1181        shooter_uuid: ev.shooter_uuid.as_str().to_owned(),
1182        hit_type: ev.hit_type.as_str().to_owned(),
1183        hit_entity_uuid: ev.hit_entity_uuid.as_str().to_owned(),
1184        x: ev.x,
1185        y: ev.y,
1186        z: ev.z,
1187        dimension: ev.dimension.as_str().to_owned(),
1188    }
1189);
1190
1191unsafe extern "C" fn trampoline_server_fn<F>(ud: *mut c_void, srv: *const YogServer)
1192where
1193    F: Fn(&dyn Server) + Send + Sync,
1194{
1195    let f = &*(ud as *const F);
1196    f(&CServer(srv));
1197}
1198
1199unsafe extern "C" fn trampoline_packet<F>(
1200    ud: *mut c_void,
1201    srv: *const YogServer,
1202    ev: *const YogPacketEvent,
1203) where
1204    F: Fn(&PacketEvent, &dyn Server) + Send + Sync,
1205{
1206    let f = &*(ud as *const F);
1207    let ev = &*ev;
1208    let rust_ev = PacketEvent {
1209        channel: ev.channel.as_str().to_owned(),
1210        player: ev.player.as_str().to_owned(),
1211        payload: std::slice::from_raw_parts(ev.payload, ev.payload_len as usize).to_vec(),
1212    };
1213    f(&rust_ev, &CServer(srv));
1214}
1215
1216unsafe extern "C" fn trampoline_command<F>(
1217    ud: *mut c_void,
1218    srv: *const YogServer,
1219    ev: *const YogCommandEvent,
1220    reply_buf: *mut u8,
1221    reply_cap: u32,
1222    reply_len: *mut u32,
1223) where
1224    F: Fn(&CommandContext, &dyn Server) -> Option<String> + Send + Sync,
1225{
1226    let f = &*(ud as *const F);
1227    let ev = &*ev;
1228    let ctx = CommandContext {
1229        name: ev.name.as_str().to_owned(),
1230        args: ev.args.as_str().to_owned(),
1231        source: ev.source.as_str().to_owned(),
1232        uuid: ev.uuid.as_str().to_owned(),
1233        dimension: ev.dimension.as_str().to_owned(),
1234    };
1235    *reply_len = 0;
1236    if let Some(reply) = f(&ctx, &CServer(srv)) {
1237        let bytes = reply.as_bytes();
1238        let n = bytes.len().min(reply_cap as usize);
1239        std::ptr::copy_nonoverlapping(bytes.as_ptr(), reply_buf, n);
1240        *reply_len = n as u32;
1241    }
1242}
1243
1244unsafe extern "C" fn trampoline_scheduled<F>(ud: *mut c_void, srv: *const YogServer)
1245where
1246    F: Fn(&dyn Server) + Send + Sync,
1247{
1248    let f = &*(ud as *const F);
1249    f(&CServer(srv));
1250}
1251
1252// ── ABI minor 10 — client-side trampolines ────────────────────────────────────
1253
1254unsafe extern "C" fn trampoline_client_tick<F>(ud: *mut c_void)
1255where
1256    F: Fn(&ClientTickEvent) + Send + Sync,
1257{
1258    let f = &*(ud as *const F);
1259    f(&ClientTickEvent {});
1260}
1261
1262unsafe extern "C" fn trampoline_hud_render<F>(ud: *mut c_void, gfx: *const YogGfxApi)
1263where
1264    F: Fn(&GfxContext) + Send + Sync,
1265{
1266    let f = &*(ud as *const F);
1267    f(&GfxContext::from_raw(gfx));
1268}
1269
1270unsafe extern "C" fn trampoline_world_render<F>(ud: *mut c_void, gfx: *const YogGfxApi)
1271where
1272    F: Fn(&GfxContext) + Send + Sync,
1273{
1274    let f = &*(ud as *const F);
1275    f(&GfxContext::from_raw(gfx));
1276}
1277
1278unsafe extern "C" fn trampoline_key_press<F>(ud: *mut c_void, ev: *const YogKeyPressEvent) -> bool
1279where
1280    F: Fn(&KeyPressEvent) -> bool + Send + Sync,
1281{
1282    let f = &*(ud as *const F);
1283    let e = &*ev;
1284    f(&KeyPressEvent {
1285        key_code: e.key_code,
1286        scan_code: e.scan_code,
1287        action: e.action,
1288        modifiers: e.modifiers,
1289    })
1290}
1291
1292unsafe extern "C" fn trampoline_screen<F>(ud: *mut c_void, screen_class: YogStr) -> bool
1293where
1294    F: Fn(&ScreenEvent) + Send + Sync,
1295{
1296    let f = &*(ud as *const F);
1297    f(&ScreenEvent {
1298        screen_class: screen_class.as_str().to_owned(),
1299    });
1300    true
1301}
1302
1303// ── Registry ─────────────────────────────────────────────────────────────────
1304
1305/// Wraps the [`YogApi`] table and provides an ergonomic registration API.
1306///
1307/// Obtained inside `yog_mod_register` via `export_mod!`.  Closures registered
1308/// here are boxed and leaked — they live as long as the process (which is the
1309/// correct lifetime for a server mod).
1310/// Pointer to the runtime's `YogApi` table (a process-lifetime static in the
1311/// runtime), captured when the mod registers. Lets free functions like
1312/// [`installed_mods`] work outside of `register()` — e.g. in UI handlers.
1313static GLOBAL_API: std::sync::atomic::AtomicPtr<YogApi> =
1314    std::sync::atomic::AtomicPtr::new(std::ptr::null_mut());
1315
1316/// Metadata of an installed mod, as reported by the loader.
1317#[derive(Debug, Clone)]
1318pub struct ModInfo {
1319    /// `"yog"` for .yog mods, `"platform"` for loader (Java) mods.
1320    pub source: String,
1321    pub id: String,
1322    pub name: String,
1323    pub version: String,
1324    /// Comma-separated author list (may be empty).
1325    pub authors: String,
1326    pub description: String,
1327}
1328
1329/// All installed mods known to the loader: .yog mods plus, where the host
1330/// exposes them, platform (Java) mods. Callable at any time after this mod's
1331/// `register()` ran — including client-side UI handlers. Note that during
1332/// `register()` mods that load after this one are not in the list yet; query
1333/// lazily (e.g. on first render) for a complete view.
1334pub fn installed_mods() -> Vec<ModInfo> {
1335    let api = GLOBAL_API.load(std::sync::atomic::Ordering::Acquire);
1336    if api.is_null() {
1337        return Vec::new();
1338    }
1339    let owned = unsafe { ((*api).mods_list)((*api).ctx) };
1340    if owned.is_none() {
1341        return Vec::new();
1342    }
1343    let text = unsafe {
1344        String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
1345            .unwrap_or_default()
1346    };
1347    unsafe { ((*api).free_str)(owned.ptr, owned.len) };
1348    text.lines()
1349        .filter_map(|line| {
1350            let mut f = line.split('\t');
1351            Some(ModInfo {
1352                source: f.next()?.to_string(),
1353                id: f.next()?.to_string(),
1354                name: f.next().unwrap_or_default().to_string(),
1355                version: f.next().unwrap_or_default().to_string(),
1356                authors: f.next().unwrap_or_default().to_string(),
1357                description: f.next().unwrap_or_default().to_string(),
1358            })
1359        })
1360        .collect()
1361}
1362
1363/// Open the Yog UI registered as `ui_id` (client side; no-op on dedicated
1364/// servers). `modal` blocks game input, `pause` pauses singleplayer. Callable
1365/// from any handler after registration — e.g. an `on_client_packet` handler.
1366pub fn open_ui(ui_id: &str, modal: bool, pause: bool) {
1367    let api = GLOBAL_API.load(std::sync::atomic::Ordering::Acquire);
1368    if api.is_null() {
1369        return;
1370    }
1371    unsafe { ((*api).ui_open)((*api).ctx, YogStr::from_str(ui_id), modal, pause) }
1372}
1373
1374/// Handle to the runtime's server-action table, usable from any handler after
1375/// registration — including client-side ones that don't receive `&dyn Server`
1376/// (UI event handlers, client tick). Server-world actions are no-ops client
1377/// side, but networking (`send_to_server`) and similar client-safe calls work.
1378pub fn server() -> Option<CServer> {
1379    let api = GLOBAL_API.load(std::sync::atomic::Ordering::Acquire);
1380    if api.is_null() {
1381        return None;
1382    }
1383    let srv = unsafe { (*api).server };
1384    if srv.is_null() {
1385        return None;
1386    }
1387    Some(CServer(srv))
1388}
1389
1390pub struct Registry {
1391    api: *const YogApi,
1392}
1393
1394// SAFETY: `api` is a static provided by the runtime, valid for process lifetime.
1395unsafe impl Send for Registry {}
1396unsafe impl Sync for Registry {}
1397
1398impl Registry {
1399    /// Build from the pointer passed by the runtime. Only called by `export_mod!`.
1400    pub unsafe fn from_raw(api: *const YogApi) -> Self {
1401        GLOBAL_API.store(api as *mut YogApi, std::sync::atomic::Ordering::Release);
1402        Self { api }
1403    }
1404
1405    #[inline]
1406    fn ctx(&self) -> *mut c_void {
1407        unsafe { (*self.api).ctx }
1408    }
1409
1410    // ── helpers ──────────────────────────────────────────────────────────────
1411
1412    fn leak<F: 'static>(f: F) -> *mut c_void {
1413        Box::into_raw(Box::new(f)) as *mut c_void
1414    }
1415
1416    // ── events ───────────────────────────────────────────────────────────────
1417    //
1418    // All handlers receive `(event, EventPhase, &dyn Server) -> bool`.
1419    // In `Pre` phase, returning `false` cancels the action.
1420    // In `Post` phase, the return value is ignored.
1421    // A single registration fires for BOTH phases.
1422
1423    pub fn on_block_break<F>(&mut self, handler: F)
1424    where
1425        F: Fn(&BlockBreakEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1426    {
1427        let ud = Self::leak(handler);
1428        unsafe { ((*self.api).on_block_break)(self.ctx(), ud, trampoline_block_break::<F>) }
1429    }
1430
1431    pub fn on_chat<F>(&mut self, handler: F)
1432    where
1433        F: Fn(&ChatEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1434    {
1435        let ud = Self::leak(handler);
1436        unsafe { ((*self.api).on_chat)(self.ctx(), ud, trampoline_chat::<F>) }
1437    }
1438
1439    pub fn on_player_join<F>(&mut self, handler: F)
1440    where
1441        F: Fn(&PlayerJoinEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1442    {
1443        let ud = Self::leak(handler);
1444        unsafe { ((*self.api).on_player_join)(self.ctx(), ud, trampoline_player_join::<F>) }
1445    }
1446
1447    pub fn on_player_leave<F>(&mut self, handler: F)
1448    where
1449        F: Fn(&PlayerLeaveEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1450    {
1451        let ud = Self::leak(handler);
1452        unsafe { ((*self.api).on_player_leave)(self.ctx(), ud, trampoline_player_leave::<F>) }
1453    }
1454
1455    pub fn on_use_item<F>(&mut self, handler: F)
1456    where
1457        F: Fn(&UseItemEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1458    {
1459        let ud = Self::leak(handler);
1460        unsafe { ((*self.api).on_use_item)(self.ctx(), ud, trampoline_use_item::<F>) }
1461    }
1462
1463    pub fn on_use_block<F>(&mut self, handler: F)
1464    where
1465        F: Fn(&UseBlockEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1466    {
1467        let ud = Self::leak(handler);
1468        unsafe { ((*self.api).on_use_block)(self.ctx(), ud, trampoline_use_block::<F>) }
1469    }
1470
1471    pub fn on_attack_entity<F>(&mut self, handler: F)
1472    where
1473        F: Fn(&AttackEntityEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1474    {
1475        let ud = Self::leak(handler);
1476        unsafe { ((*self.api).on_attack_entity)(self.ctx(), ud, trampoline_attack_entity::<F>) }
1477    }
1478
1479    pub fn on_entity_damage<F>(&mut self, handler: F)
1480    where
1481        F: Fn(&EntityDamageEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1482    {
1483        let ud = Self::leak(handler);
1484        unsafe { ((*self.api).on_entity_damage)(self.ctx(), ud, trampoline_entity_damage::<F>) }
1485    }
1486
1487    pub fn on_entity_death<F>(&mut self, handler: F)
1488    where
1489        F: Fn(&EntityDeathEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1490    {
1491        let ud = Self::leak(handler);
1492        unsafe { ((*self.api).on_entity_death)(self.ctx(), ud, trampoline_entity_death::<F>) }
1493    }
1494
1495    pub fn on_entity_spawn<F>(&mut self, handler: F)
1496    where
1497        F: Fn(&EntitySpawnEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1498    {
1499        let ud = Self::leak(handler);
1500        unsafe { ((*self.api).on_entity_spawn)(self.ctx(), ud, trampoline_entity_spawn::<F>) }
1501    }
1502
1503    pub fn on_player_place_block<F>(&mut self, handler: F)
1504    where
1505        F: Fn(&PlaceBlockEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1506    {
1507        let ud = Self::leak(handler);
1508        unsafe { ((*self.api).on_player_place_block)(self.ctx(), ud, trampoline_place_block::<F>) }
1509    }
1510
1511    pub fn on_player_death<F>(&mut self, handler: F)
1512    where
1513        F: Fn(&PlayerDeathEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1514    {
1515        let ud = Self::leak(handler);
1516        unsafe { ((*self.api).on_player_death)(self.ctx(), ud, trampoline_player_death::<F>) }
1517    }
1518
1519    pub fn on_player_respawn<F>(&mut self, handler: F)
1520    where
1521        F: Fn(&PlayerRespawnEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1522    {
1523        let ud = Self::leak(handler);
1524        unsafe { ((*self.api).on_player_respawn)(self.ctx(), ud, trampoline_player_respawn::<F>) }
1525    }
1526
1527    pub fn on_advancement<F>(&mut self, handler: F)
1528    where
1529        F: Fn(&AdvancementEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1530    {
1531        let ud = Self::leak(handler);
1532        unsafe { ((*self.api).on_advancement)(self.ctx(), ud, trampoline_advancement::<F>) }
1533    }
1534
1535    pub fn on_entity_interact<F>(&mut self, handler: F)
1536    where
1537        F: Fn(&EntityInteractEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1538    {
1539        let ud = Self::leak(handler);
1540        unsafe { ((*self.api).on_entity_interact)(self.ctx(), ud, trampoline_entity_interact::<F>) }
1541    }
1542
1543    pub fn on_item_craft<F>(&mut self, handler: F)
1544    where
1545        F: Fn(&CraftEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1546    {
1547        let ud = Self::leak(handler);
1548        unsafe { ((*self.api).on_item_craft)(self.ctx(), ud, trampoline_craft::<F>) }
1549    }
1550
1551    pub fn on_explosion<F>(&mut self, handler: F)
1552    where
1553        F: Fn(&ExplosionEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1554    {
1555        let ud = Self::leak(handler);
1556        unsafe { ((*self.api).on_explosion)(self.ctx(), ud, trampoline_explosion::<F>) }
1557    }
1558
1559    pub fn on_item_pickup<F>(&mut self, handler: F)
1560    where
1561        F: Fn(&ItemPickupEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1562    {
1563        let ud = Self::leak(handler);
1564        unsafe { ((*self.api).on_item_pickup)(self.ctx(), ud, trampoline_item_pickup::<F>) }
1565    }
1566
1567    pub fn on_player_move<F>(&mut self, handler: F)
1568    where
1569        F: Fn(&PlayerMoveEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1570    {
1571        let ud = Self::leak(handler);
1572        unsafe { ((*self.api).on_player_move)(self.ctx(), ud, trampoline_player_move::<F>) }
1573    }
1574
1575    pub fn on_container_open<F>(&mut self, handler: F)
1576    where
1577        F: Fn(&ContainerOpenEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1578    {
1579        let ud = Self::leak(handler);
1580        unsafe { ((*self.api).on_container_open)(self.ctx(), ud, trampoline_container_open::<F>) }
1581    }
1582
1583    pub fn on_container_close<F>(&mut self, handler: F)
1584    where
1585        F: Fn(&ContainerCloseEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1586    {
1587        let ud = Self::leak(handler);
1588        unsafe { ((*self.api).on_container_close)(self.ctx(), ud, trampoline_container_close::<F>) }
1589    }
1590
1591    pub fn on_projectile_hit<F>(&mut self, handler: F)
1592    where
1593        F: Fn(&ProjectileHitEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1594    {
1595        let ud = Self::leak(handler);
1596        unsafe { ((*self.api).on_projectile_hit)(self.ctx(), ud, trampoline_projectile_hit::<F>) }
1597    }
1598
1599    pub fn on_tick<F>(&mut self, listener: F)
1600    where
1601        F: Fn(&dyn Server) + Send + Sync + 'static,
1602    {
1603        let ud = Self::leak(listener);
1604        unsafe { ((*self.api).on_server_tick)(self.ctx(), ud, trampoline_server_fn::<F>) }
1605    }
1606
1607    pub fn on_server_started<F>(&mut self, listener: F)
1608    where
1609        F: Fn(&dyn Server) + Send + Sync + 'static,
1610    {
1611        let ud = Self::leak(listener);
1612        unsafe { ((*self.api).on_server_started)(self.ctx(), ud, trampoline_server_fn::<F>) }
1613    }
1614
1615    pub fn on_server_stopping<F>(&mut self, listener: F)
1616    where
1617        F: Fn(&dyn Server) + Send + Sync + 'static,
1618    {
1619        let ud = Self::leak(listener);
1620        unsafe { ((*self.api).on_server_stopping)(self.ctx(), ud, trampoline_server_fn::<F>) }
1621    }
1622
1623    // ── commands ─────────────────────────────────────────────────────────────
1624
1625    pub fn on_command<F>(&mut self, name: impl AsRef<str>, handler: F)
1626    where
1627        F: Fn(&CommandContext, &dyn Server) -> Option<String> + Send + Sync + 'static,
1628    {
1629        let name_ys = YogStr::from_str(name.as_ref());
1630        let ud = Self::leak(handler);
1631        unsafe { ((*self.api).register_command)(self.ctx(), name_ys, ud, trampoline_command::<F>) }
1632    }
1633
1634    /// Register a command with Brigadier-typed arguments.
1635    ///
1636    /// `schema` is a space-separated list of argument types:
1637    /// `int`, `float`, `word`, `string` (greedy, must be last), `player`, `blockpos`.
1638    ///
1639    /// In the handler use `ctx.arg_int(0)`, `ctx.arg_blockpos(1)`, etc.
1640    pub fn on_typed_command<F>(
1641        &mut self,
1642        name: impl AsRef<str>,
1643        schema: impl AsRef<str>,
1644        handler: F,
1645    ) where
1646        F: Fn(&CommandContext, &dyn Server) -> Option<String> + Send + Sync + 'static,
1647    {
1648        let name_ys = YogStr::from_str(name.as_ref());
1649        let schema_ys = YogStr::from_str(schema.as_ref());
1650        let ud = Self::leak(handler);
1651        unsafe {
1652            ((*self.api).register_typed_command)(
1653                self.ctx(),
1654                name_ys,
1655                schema_ys,
1656                ud,
1657                trampoline_command::<F>,
1658            )
1659        }
1660    }
1661
1662    // ── networking ───────────────────────────────────────────────────────────
1663
1664    pub fn on_packet<F>(&mut self, channel: impl AsRef<str>, handler: F)
1665    where
1666        F: Fn(&PacketEvent, &dyn Server) + Send + Sync + 'static,
1667    {
1668        let ch = YogStr::from_str(channel.as_ref());
1669        let ud = Self::leak(handler);
1670        unsafe { ((*self.api).on_packet)(self.ctx(), ch, ud, trampoline_packet::<F>) }
1671    }
1672
1673    pub fn on_client_packet<F>(&mut self, channel: impl AsRef<str>, handler: F)
1674    where
1675        F: Fn(&PacketEvent, &dyn Server) + Send + Sync + 'static,
1676    {
1677        let ch = YogStr::from_str(channel.as_ref());
1678        let ud = Self::leak(handler);
1679        unsafe { ((*self.api).on_client_packet)(self.ctx(), ch, ud, trampoline_packet::<F>) }
1680    }
1681
1682    /// Register a typed-packet handler.
1683    ///
1684    /// The payload is decoded from raw bytes using `P`'s [`Packet`] impl.
1685    /// Malformed payloads are silently dropped.
1686    pub fn on_typed_packet<P, F>(&mut self, channel: impl AsRef<str>, handler: F)
1687    where
1688        P: Packet + Send + Sync + 'static,
1689        F: Fn(&P, &dyn Server) + Send + Sync + 'static,
1690    {
1691        self.on_packet(channel, move |ev, srv| {
1692            if let Some(pkt) = P::decode(&ev.payload) {
1693                handler(&pkt, srv);
1694            }
1695        });
1696    }
1697
1698    // ── recipes ──────────────────────────────────────────────────────────────
1699
1700    fn recipe(&mut self, ns: &str, name: &str, json: &str) {
1701        unsafe {
1702            ((*self.api).register_recipe_json)(
1703                self.ctx(),
1704                YogStr::from_str(ns),
1705                YogStr::from_str(name),
1706                YogStr::from_str(json),
1707            )
1708        }
1709    }
1710
1711    /// Register a shaped crafting recipe.
1712    pub fn add_shaped_recipe(&mut self, recipe: ShapedRecipe) {
1713        let json = recipe.to_json();
1714        let (ns, name) = recipe.ns_name();
1715        self.recipe(ns, name, &json);
1716    }
1717
1718    /// Register a shapeless crafting recipe.
1719    pub fn add_shapeless_recipe(&mut self, recipe: ShapelessRecipe) {
1720        let json = recipe.to_json();
1721        let (ns, name) = recipe.ns_name();
1722        self.recipe(ns, name, &json);
1723    }
1724
1725    /// Register a furnace smelting recipe.
1726    pub fn add_furnace_recipe(&mut self, recipe: FurnaceRecipe) {
1727        let json = recipe.to_json();
1728        let (ns, name) = recipe.ns_name();
1729        self.recipe(ns, name, &json);
1730    }
1731
1732    // ── content ──────────────────────────────────────────────────────────────
1733
1734    pub fn register_item(&mut self, def: ItemDef) {
1735        // Build a C-compatible YogItemDef whose YogStr fields point into `def`'s
1736        // String storage.  We then call register_item which must copy the data
1737        // before returning (the runtime stores owned Strings).
1738        let food_nutrition = def.food.as_ref().map_or(0, |f| f.nutrition);
1739        let food_saturation = def.food.as_ref().map_or(0.0, |f| f.saturation);
1740        let food_always_eat = def.food.as_ref().map_or(false, |f| f.can_always_eat);
1741        let c = YogItemDef {
1742            id: YogStr::from_str(&def.id),
1743            max_stack: def.max_stack as u32,
1744            name: def
1745                .name
1746                .as_deref()
1747                .map(YogStr::from_str)
1748                .unwrap_or(YogStr::EMPTY),
1749            tooltip: def
1750                .tooltip
1751                .as_deref()
1752                .map(YogStr::from_str)
1753                .unwrap_or(YogStr::EMPTY),
1754            max_damage: def.max_damage,
1755            fire_resistant: def.fire_resistant,
1756            fuel_ticks: def.fuel_ticks,
1757            food_nutrition,
1758            food_saturation,
1759            food_always_eat,
1760        };
1761        unsafe { ((*self.api).register_item)(self.ctx(), &c) }
1762    }
1763
1764    pub fn register_block(&mut self, def: BlockDef) {
1765        let shape = def.shape.unwrap_or([0.0; 6]);
1766        let groups_joined = def.connect_groups.join(",");
1767        let c = YogBlockDef {
1768            id: YogStr::from_str(&def.id),
1769            hardness: def.hardness,
1770            resistance: def.resistance,
1771            name: def
1772                .name
1773                .as_deref()
1774                .map(YogStr::from_str)
1775                .unwrap_or(YogStr::EMPTY),
1776            light_level: def.light_level,
1777            sound: def
1778                .sound
1779                .as_deref()
1780                .map(YogStr::from_str)
1781                .unwrap_or(YogStr::EMPTY),
1782            requires_tool: def.requires_tool,
1783            no_collision: def.no_collision,
1784            slipperiness: def.slipperiness,
1785            shape,
1786            connects: def.connects,
1787            connect_groups: YogStr::from_str(&groups_joined),
1788            inventory_id: def
1789                .inventory_id
1790                .as_deref()
1791                .map(YogStr::from_str)
1792                .unwrap_or(YogStr::EMPTY),
1793        };
1794        unsafe { ((*self.api).register_block)(self.ctx(), &c) }
1795    }
1796
1797    /// Register a real Container/Menu inventory screen — see
1798    /// `yog_inventory::InventoryDef`. Attach it to a block via
1799    /// `BlockDef::inventory(id)`.
1800    pub fn register_inventory(&mut self, def: yog_inventory::InventoryDef) {
1801        let layout = yog_inventory::encode_layout(&def.resolved_layout());
1802        let c = YogInventoryDef {
1803            id: YogStr::from_str(&def.id),
1804            slot_count: def.slot_count as u32,
1805            layout: YogStr::from_str(&layout),
1806            include_player_inventory: def.include_player_inventory,
1807            player_inv_x: def.player_inv_offset.0,
1808            player_inv_y: def.player_inv_offset.1,
1809            background_texture: def
1810                .background_texture
1811                .as_deref()
1812                .map(YogStr::from_str)
1813                .unwrap_or(YogStr::EMPTY),
1814            title: YogStr::from_str(&def.title),
1815        };
1816        unsafe { ((*self.api).register_inventory)(self.ctx(), &c) }
1817    }
1818
1819    // ── startup grants ───────────────────────────────────────────────────────
1820
1821    /// Register a startup grant: items/books to give once when a player first joins.
1822    pub fn register_startup_grant(&mut self, grant: StartupGrant) {
1823        let items_str = grant.items.join("|");
1824        let c = YogStartupGrantDef {
1825            id: YogStr::from_str(&grant.id),
1826            items: YogStr::from_str(&items_str),
1827            book: grant
1828                .book
1829                .as_deref()
1830                .map(YogStr::from_str)
1831                .unwrap_or(YogStr::EMPTY),
1832            command: grant
1833                .command
1834                .as_deref()
1835                .map(YogStr::from_str)
1836                .unwrap_or(YogStr::EMPTY),
1837        };
1838        unsafe { ((*self.api).register_startup_grant)(self.ctx(), &c) }
1839    }
1840
1841    /// Register a book with its JSON-serialized content.
1842    pub fn register_book(&mut self, book: &Book) {
1843        let json = book.to_json();
1844        let id = YogStr::from_str(&book.id);
1845        let j = YogStr::from_str(&json);
1846        unsafe { ((*self.api).register_book)(self.ctx(), id, j) }
1847    }
1848
1849    /// Register a custom dimension's *type* (sky, lighting, physics, ...).
1850    ///
1851    /// Must be called from `register()` — the same mod-init window as
1852    /// blocks/items — so the host can declare the dimension before
1853    /// Minecraft's registries freeze. See the `yog-dimensions` crate docs;
1854    /// pair with [`Registry::register_chunk_generator`] to actually
1855    /// generate terrain for it.
1856    pub fn register_dimension(&mut self, def: &YogDimensionDef) {
1857        let json = def.to_json();
1858        let id = YogStr::from_str(&def.id);
1859        let j = YogStr::from_str(&json);
1860        unsafe { ((*self.api).register_dimension_json)(self.ctx(), id, j) }
1861    }
1862
1863    /// Register a chunk generator for a dimension previously declared via
1864    /// [`Registry::register_dimension`]. `generator` is called once per
1865    /// chunk column that needs generating in that dimension — write
1866    /// whatever terrain logic you want using the [`ChunkWriter`] handle
1867    /// (combine as many noise layers as you like; this crate doesn't
1868    /// prescribe a generation style).
1869    pub fn register_chunk_generator<F>(&mut self, dimension_id: &str, generator: F)
1870    where
1871        F: Fn(&ChunkWriter) + Send + Sync + 'static,
1872    {
1873        let ud = Self::leak(generator);
1874        let id = YogStr::from_str(dimension_id);
1875        unsafe {
1876            ((*self.api).register_chunk_generator)(
1877                self.ctx(),
1878                id,
1879                ud,
1880                trampoline_chunk_generator::<F>,
1881            )
1882        }
1883    }
1884
1885    /// Register a menu entry — the host renders a button on vanilla screens
1886    /// (TitleScreen on Fabric, ModListScreen on Forge/NeoForge) that opens `ui_id`.
1887    /// `label` is the human-readable button text (e.g. "Yog Mods").
1888    /// `ui_id` is the UI to open when clicked (e.g. "yog:modlist").
1889    /// See [`installed_mods`]. During `register()` the list only contains
1890    /// mods loaded before this one.
1891    pub fn installed_mods(&self) -> Vec<ModInfo> {
1892        installed_mods()
1893    }
1894
1895    /// Access the inter-mod communication layer.
1896    ///
1897    /// Allows exporting function pointers from this mod and importing
1898    /// function pointers from other mods.
1899    pub fn interop(&self) -> crate::Interop {
1900        crate::Interop::new(self.api)
1901    }
1902
1903    /// Raw `YogApi` pointer — for passing to interop-imported functions
1904    /// that register content through the C ABI table directly.
1905    pub fn raw_api(&self) -> *const yog_abi::YogApi {
1906        self.api
1907    }
1908
1909    pub fn register_menu_entry(&mut self, label: &str, ui_id: &str) {
1910        let l = YogStr::from_str(label);
1911        let u = YogStr::from_str(ui_id);
1912        unsafe { ((*self.api).register_menu_entry)(self.ctx(), l, u) }
1913    }
1914
1915    /// Register a UI tree with an event callback.
1916    /// `ui_id` is the unique identifier (e.g. "mymod:menu").
1917    /// `handler` receives `(ui_id, event_id)` when a widget is clicked.
1918    pub fn register_ui<F>(&mut self, ui_id: &str, handler: F)
1919    where
1920        F: Fn(&str, &str) + Send + Sync + 'static,
1921    {
1922        let ud = Self::leak(handler);
1923        let id = YogStr::from_str(ui_id);
1924        let empty = YogStr::from_str("{}");
1925        unsafe { ((*self.api).register_ui)(self.ctx(), id, empty, ud, trampoline_ui_event::<F>) }
1926    }
1927
1928    // ── scheduler ────────────────────────────────────────────────────────────
1929
1930    pub fn schedule_once<F>(&self, delay_ticks: u64, handler: F)
1931    where
1932        F: Fn(&dyn Server) + Send + Sync + 'static,
1933    {
1934        let ud = Self::leak(handler);
1935        unsafe {
1936            ((*self.api).schedule_once)(self.ctx(), delay_ticks, ud, trampoline_scheduled::<F>)
1937        }
1938    }
1939
1940    pub fn schedule_repeating<F>(&self, period_ticks: u64, handler: F)
1941    where
1942        F: Fn(&dyn Server) + Send + Sync + 'static,
1943    {
1944        let ud = Self::leak(handler);
1945        unsafe {
1946            ((*self.api).schedule_repeating)(
1947                self.ctx(),
1948                period_ticks,
1949                ud,
1950                trampoline_scheduled::<F>,
1951            )
1952        }
1953    }
1954
1955    // ── client-side hooks (ABI minor 10) ─────────────────────────────────────
1956
1957    /// Register a handler called every client tick (render thread, no server).
1958    pub fn on_client_tick<F>(&mut self, handler: F)
1959    where
1960        F: Fn(&ClientTickEvent) + Send + Sync + 'static,
1961    {
1962        let ud = Self::leak(handler);
1963        unsafe { ((*self.api).on_client_tick)(self.ctx(), ud, trampoline_client_tick::<F>) }
1964    }
1965
1966    /// Register a render callback for a specific UI screen (`ui_id`).
1967    ///
1968    /// Called from `YogUIScreen.render()` — i.e. AFTER `renderBackground()` darkens
1969    /// the screen — so your UI draws on top of the dimmed world view.
1970    /// Use this instead of `on_hud_render` for book/inventory screens.
1971    ///
1972    /// Clicks are forwarded as `"click:X:Y"` via the `register_ui` handler so you
1973    /// can do hit-testing on your own stored layout.
1974    pub fn on_ui_render<F>(&mut self, ui_id: &str, handler: F)
1975    where
1976        F: Fn(&GfxContext) + Send + Sync + 'static,
1977    {
1978        let ud = Self::leak(handler);
1979        let id = YogStr::from_str(ui_id);
1980        unsafe { ((*self.api).on_ui_render)(self.ctx(), id, ud, trampoline_hud_render::<F>) }
1981    }
1982
1983    /// Register a handler called every frame when the HUD is rendered.
1984    ///
1985    /// `gfx` provides full GPU pipeline access plus 2D convenience draw calls.
1986    /// `view_proj` and `camera_pos` are zero in HUD context; use `gfx.draw2d()` for HUD elements.
1987    pub fn on_hud_render<F>(&mut self, handler: F)
1988    where
1989        F: Fn(&GfxContext) + Send + Sync + 'static,
1990    {
1991        let ud = Self::leak(handler);
1992        unsafe { ((*self.api).on_hud_render)(self.ctx(), ud, trampoline_hud_render::<F>) }
1993    }
1994
1995    /// Register a handler called every frame at the end of world rendering.
1996    ///
1997    /// `gfx.view_proj()` is the combined projection × view matrix (camera-relative).
1998    /// `gfx.camera_pos()` is the camera world position.
1999    /// To render at world position P, translate by `P - camera_pos` before drawing.
2000    pub fn on_world_render<F>(&mut self, handler: F)
2001    where
2002        F: Fn(&GfxContext) + Send + Sync + 'static,
2003    {
2004        let ud = Self::leak(handler);
2005        unsafe { ((*self.api).on_world_render)(self.ctx(), ud, trampoline_world_render::<F>) }
2006    }
2007
2008    /// Register a handler for keyboard input (client-side).
2009    /// Return `false` to prevent Minecraft from processing the key.
2010    pub fn on_key_press<F>(&mut self, handler: F)
2011    where
2012        F: Fn(&KeyPressEvent) -> bool + Send + Sync + 'static,
2013    {
2014        let ud = Self::leak(handler);
2015        unsafe { ((*self.api).on_key_press)(self.ctx(), ud, trampoline_key_press::<F>) }
2016    }
2017
2018    /// Register a handler called when a GUI screen is opened.
2019    pub fn on_screen_open<F>(&mut self, handler: F)
2020    where
2021        F: Fn(&ScreenEvent) + Send + Sync + 'static,
2022    {
2023        let ud = Self::leak(handler);
2024        unsafe { ((*self.api).on_screen_open)(self.ctx(), ud, trampoline_screen::<F>) }
2025    }
2026
2027    /// Register a handler called when a GUI screen is closed.
2028    pub fn on_screen_close<F>(&mut self, handler: F)
2029    where
2030        F: Fn(&ScreenEvent) + Send + Sync + 'static,
2031    {
2032        let ud = Self::leak(handler);
2033        unsafe { ((*self.api).on_screen_close)(self.ctx(), ud, trampoline_screen::<F>) }
2034    }
2035}
2036
2037unsafe extern "C" fn trampoline_ui_event<F>(
2038    ud: *mut c_void,
2039    ui_id: yog_abi::YogStr,
2040    event_id: yog_abi::YogStr,
2041) where
2042    F: Fn(&str, &str) + Send + Sync + 'static,
2043{
2044    let f = &*(ud as *const F);
2045    let ui = unsafe { ui_id.as_str() };
2046    let ev = unsafe { event_id.as_str() };
2047    f(ui, ev);
2048}
2049
2050unsafe extern "C" fn trampoline_chunk_generator<F>(
2051    ud: *mut c_void,
2052    writer: *const yog_abi::YogChunkWriterApi,
2053) where
2054    F: Fn(&ChunkWriter) + Send + Sync + 'static,
2055{
2056    let f = &*(ud as *const F);
2057    let writer = unsafe { ChunkWriter::from_raw(writer) };
2058    f(&writer);
2059}
2060
2061// ── Mod trait ─────────────────────────────────────────────────────────────────
2062
2063/// Implemented by every Yog mod. Called once at startup to register handlers.
2064pub trait Mod {
2065    fn register(registry: &mut Registry);
2066}