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, 
14    YogChatEvent, YogCommandEvent, YogContainerCloseEvent, YogContainerOpenEvent, YogCraftEvent,
15    YogEntityDamageEvent, YogEntityDeathEvent, YogEntityInteractEvent, YogEntitySpawnEvent,
16    YogExplosionEvent, YogGfxApi, YogItemInsertEvent, YogItemPickupEvent, YogMachineCraftEvent,
17    YogKeyPressEvent, YogPacketEvent, YogPlaceBlockEvent, YogPlayerDeathEvent, YogPlayerEvent,
18    YogPlayerMoveEvent, YogPlayerRespawnEvent, YogProjectileHitEvent, YogServer,
19    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, ItemInsertEvent, 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::{ArmorMaterial, BlockDef, ItemDef, Recipe, SoundGroup, StartupGrant, ToolMaterial};
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
72        take_owned(s.free_str, owned)
73    }
74
75    fn set_block(&self, dimension: &str, pos: yog_core::BlockPos, block_id: &str) -> bool {
76        let s = srv!(self);
77        unsafe {
78            (s.set_block)(
79                s.ctx,
80                YogStr::from_str(dimension),
81                yog_abi::YogBlockPos {
82                    x: pos.x,
83                    y: pos.y,
84                    z: pos.z,
85                },
86                YogStr::from_str(block_id),
87            )
88        }
89    }
90
91    fn give_item(&self, player: &str, item_id: &str, count: u32) -> bool {
92        let s = srv!(self);
93        unsafe {
94            (s.give_item)(
95                s.ctx,
96                YogStr::from_str(player),
97                YogStr::from_str(item_id),
98                count,
99            )
100        }
101    }
102
103    fn teleport(&self, player: &str, x: f64, y: f64, z: f64) -> bool {
104        let s = srv!(self);
105        unsafe {
106            (s.player_teleport)(
107                s.ctx,
108                YogStr::from_str(player),
109                yog_abi::YogVec3 { x, y, z },
110            )
111        }
112    }
113
114    fn send_to_player(&self, player: &str, channel: &str, payload: &[u8]) -> bool {
115        let s = srv!(self);
116        unsafe {
117            (s.send_to_player)(
118                s.ctx,
119                YogStr::from_str(player),
120                YogStr::from_str(channel),
121                payload.as_ptr(),
122                payload.len() as u32,
123            )
124        }
125    }
126
127    fn send_to_server(&self, channel: &str, payload: &[u8]) -> bool {
128        let s = srv!(self);
129        unsafe {
130            (s.send_to_server)(
131                s.ctx,
132                YogStr::from_str(channel),
133                payload.as_ptr(),
134                payload.len() as u32,
135            )
136        }
137    }
138
139    fn entity_teleport(&self, uuid: &str, x: f64, y: f64, z: f64) -> bool {
140        let s = srv!(self);
141        unsafe { (s.entity_teleport)(s.ctx, YogStr::from_str(uuid), yog_abi::YogVec3 { x, y, z }) }
142    }
143
144    fn entity_position(&self, uuid: &str) -> Option<(f64, f64, f64)> {
145        let s = srv!(self);
146        let mut out = yog_abi::YogVec3 {
147            x: 0.0,
148            y: 0.0,
149            z: 0.0,
150        };
151        if unsafe { (s.entity_position)(s.ctx, YogStr::from_str(uuid), &mut out) } {
152            Some((out.x, out.y, out.z))
153        } else {
154            None
155        }
156    }
157
158    fn entity_health(&self, uuid: &str) -> Option<f32> {
159        let s = srv!(self);
160        let mut hp = 0f32;
161        if unsafe { (s.entity_health)(s.ctx, YogStr::from_str(uuid), &mut hp) } {
162            Some(hp)
163        } else {
164            None
165        }
166    }
167
168    fn entity_set_health(&self, uuid: &str, health: f32) -> bool {
169        let s = srv!(self);
170        unsafe { (s.entity_set_health)(s.ctx, YogStr::from_str(uuid), health) }
171    }
172
173    fn entity_kill(&self, uuid: &str) -> bool {
174        let s = srv!(self);
175        unsafe { (s.entity_kill)(s.ctx, YogStr::from_str(uuid)) }
176    }
177
178    fn spawn_entity(
179        &self,
180        entity_type: &str,
181        dimension: &str,
182        x: f64,
183        y: f64,
184        z: f64,
185    ) -> Option<String> {
186        let s = srv!(self);
187        let owned = unsafe {
188            (s.spawn_entity)(
189                s.ctx,
190                YogStr::from_str(entity_type),
191                YogStr::from_str(dimension),
192                yog_abi::YogVec3 { x, y, z },
193            )
194        };
195
196        take_owned(s.free_str, owned)
197    }
198
199    fn entity_add_effect(
200        &self,
201        uuid: &str,
202        effect_id: &str,
203        duration_ticks: i32,
204        amplifier: u8,
205        show_particles: bool,
206    ) -> bool {
207        let s = srv!(self);
208        unsafe {
209            (s.entity_add_effect)(
210                s.ctx,
211                YogStr::from_str(uuid),
212                YogStr::from_str(effect_id),
213                duration_ticks,
214                amplifier,
215                show_particles,
216            )
217        }
218    }
219
220    fn entity_remove_effect(&self, uuid: &str, effect_id: &str) -> bool {
221        let s = srv!(self);
222        unsafe {
223            (s.entity_remove_effect)(s.ctx, YogStr::from_str(uuid), YogStr::from_str(effect_id))
224        }
225    }
226
227    fn entity_clear_effects(&self, uuid: &str) -> bool {
228        let s = srv!(self);
229        unsafe { (s.entity_clear_effects)(s.ctx, YogStr::from_str(uuid)) }
230    }
231
232    fn drop_loot(&self, table_id: &str, dimension: &str, x: f64, y: f64, z: f64) -> bool {
233        let s = srv!(self);
234        unsafe {
235            (s.drop_loot)(
236                s.ctx,
237                YogStr::from_str(table_id),
238                YogStr::from_str(dimension),
239                yog_abi::YogVec3 { x, y, z },
240            )
241        }
242    }
243
244    fn has_item_tag(&self, item_id: &str, tag_id: &str) -> bool {
245        let s = srv!(self);
246        unsafe { (s.has_item_tag)(s.ctx, YogStr::from_str(item_id), YogStr::from_str(tag_id)) }
247    }
248
249    fn has_block_tag(&self, block_id: &str, tag_id: &str) -> bool {
250        let s = srv!(self);
251        unsafe { (s.has_block_tag)(s.ctx, YogStr::from_str(block_id), YogStr::from_str(tag_id)) }
252    }
253
254    fn world_time(&self, dimension: &str) -> Option<i64> {
255        let s = srv!(self);
256        let mut t = 0i64;
257        if unsafe { (s.world_time)(s.ctx, YogStr::from_str(dimension), &mut t) } {
258            Some(t)
259        } else {
260            None
261        }
262    }
263
264    fn world_set_time(&self, dimension: &str, time: i64) -> bool {
265        let s = srv!(self);
266        unsafe { (s.set_time)(s.ctx, YogStr::from_str(dimension), time) }
267    }
268
269    fn world_is_raining(&self, dimension: &str) -> bool {
270        let s = srv!(self);
271        unsafe { (s.is_raining)(s.ctx, YogStr::from_str(dimension)) }
272    }
273
274    fn world_set_weather(&self, dimension: &str, raining: bool, duration_ticks: i32) -> bool {
275        let s = srv!(self);
276        unsafe { (s.set_weather)(s.ctx, YogStr::from_str(dimension), raining, duration_ticks) }
277    }
278
279    fn entity_velocity(&self, uuid: &str) -> Option<(f64, f64, f64)> {
280        let s = srv!(self);
281        let mut v = yog_abi::YogVec3 {
282            x: 0.0,
283            y: 0.0,
284            z: 0.0,
285        };
286        if unsafe { (s.entity_velocity)(s.ctx, YogStr::from_str(uuid), &mut v) } {
287            Some((v.x, v.y, v.z))
288        } else {
289            None
290        }
291    }
292
293    fn entity_set_velocity(&self, uuid: &str, vx: f64, vy: f64, vz: f64) -> bool {
294        let s = srv!(self);
295        unsafe {
296            (s.entity_set_velocity)(
297                s.ctx,
298                YogStr::from_str(uuid),
299                yog_abi::YogVec3 {
300                    x: vx,
301                    y: vy,
302                    z: vz,
303                },
304            )
305        }
306    }
307
308    fn entity_add_velocity(&self, uuid: &str, vx: f64, vy: f64, vz: f64) -> bool {
309        let s = srv!(self);
310        unsafe {
311            (s.entity_add_velocity)(
312                s.ctx,
313                YogStr::from_str(uuid),
314                yog_abi::YogVec3 {
315                    x: vx,
316                    y: vy,
317                    z: vz,
318                },
319            )
320        }
321    }
322
323    fn scoreboard_get(&self, objective: &str, player: &str) -> Option<i32> {
324        let s = srv!(self);
325        let mut score = 0i32;
326        if unsafe {
327            (s.scoreboard_get)(
328                s.ctx,
329                YogStr::from_str(objective),
330                YogStr::from_str(player),
331                &mut score,
332            )
333        } {
334            Some(score)
335        } else {
336            None
337        }
338    }
339
340    fn scoreboard_set(&self, objective: &str, player: &str, score: i32) -> bool {
341        let s = srv!(self);
342        unsafe {
343            (s.scoreboard_set)(
344                s.ctx,
345                YogStr::from_str(objective),
346                YogStr::from_str(player),
347                score,
348            )
349        }
350    }
351
352    fn scoreboard_add(&self, objective: &str, player: &str, delta: i32) -> Option<i32> {
353        let s = srv!(self);
354        let mut new_score = 0i32;
355        if unsafe {
356            (s.scoreboard_add)(
357                s.ctx,
358                YogStr::from_str(objective),
359                YogStr::from_str(player),
360                delta,
361                &mut new_score,
362            )
363        } {
364            Some(new_score)
365        } else {
366            None
367        }
368    }
369
370    fn game_dir(&self) -> String {
371        let s = srv!(self);
372        let owned = unsafe { (s.game_dir)(s.ctx) };
373        take_owned(s.free_str, owned).unwrap_or_default()
374    }
375
376    fn world_dir(&self) -> String {
377        let s = srv!(self);
378        let owned = unsafe { (s.world_dir)(s.ctx) };
379        take_owned(s.free_str, owned).unwrap_or_default()
380    }
381
382    fn play_sound(
383        &self,
384        dimension: &str,
385        x: f64,
386        y: f64,
387        z: f64,
388        sound_id: &str,
389        volume: f32,
390        pitch: f32,
391    ) -> bool {
392        let s = srv!(self);
393        unsafe {
394            (s.play_sound)(
395                s.ctx,
396                YogStr::from_str(dimension),
397                yog_abi::YogVec3 { x, y, z },
398                YogStr::from_str(sound_id),
399                volume,
400                pitch,
401            )
402        }
403    }
404
405    fn play_sound_to_player(&self, player: &str, sound_id: &str, volume: f32, pitch: f32) -> bool {
406        let s = srv!(self);
407        unsafe {
408            (s.play_sound_player)(
409                s.ctx,
410                YogStr::from_str(player),
411                YogStr::from_str(sound_id),
412                volume,
413                pitch,
414            )
415        }
416    }
417
418    fn send_title(
419        &self,
420        player: &str,
421        title: &str,
422        subtitle: &str,
423        fadein: i32,
424        stay: i32,
425        fadeout: i32,
426    ) -> bool {
427        let s = srv!(self);
428        unsafe {
429            (s.send_title)(
430                s.ctx,
431                YogStr::from_str(player),
432                YogStr::from_str(title),
433                YogStr::from_str(subtitle),
434                fadein,
435                stay,
436                fadeout,
437            )
438        }
439    }
440
441    fn entity_rotation(&self, uuid: &str) -> Option<(f32, f32)> {
442        let s = srv!(self);
443        let mut out = yog_abi::YogVec3 {
444            x: 0.0,
445            y: 0.0,
446            z: 0.0,
447        };
448        let ok = unsafe { (s.entity_rotation)(s.ctx, YogStr::from_str(uuid), &mut out) };
449        if ok {
450            Some((out.x as f32, out.y as f32))
451        } else {
452            None
453        }
454    }
455
456    fn send_actionbar(&self, player: &str, message: &str) -> bool {
457        let s = srv!(self);
458        unsafe { (s.send_actionbar)(s.ctx, YogStr::from_str(player), YogStr::from_str(message)) }
459    }
460
461    fn kick_player(&self, player: &str, reason: &str) -> bool {
462        let s = srv!(self);
463        unsafe { (s.kick_player)(s.ctx, YogStr::from_str(player), YogStr::from_str(reason)) }
464    }
465
466    fn set_gamemode(&self, player: &str, gamemode: &str) -> bool {
467        let s = srv!(self);
468        unsafe { (s.set_gamemode)(s.ctx, YogStr::from_str(player), YogStr::from_str(gamemode)) }
469    }
470
471    fn bossbar_create(&self, id: &str, title: &str, color: &str, style: &str) -> bool {
472        let s = srv!(self);
473        unsafe {
474            (s.bossbar_create)(
475                s.ctx,
476                YogStr::from_str(id),
477                YogStr::from_str(title),
478                YogStr::from_str(color),
479                YogStr::from_str(style),
480            )
481        }
482    }
483
484    fn bossbar_remove(&self, id: &str) -> bool {
485        let s = srv!(self);
486        unsafe { (s.bossbar_remove)(s.ctx, YogStr::from_str(id)) }
487    }
488
489    fn bossbar_set_title(&self, id: &str, title: &str) -> bool {
490        let s = srv!(self);
491        unsafe { (s.bossbar_set_title)(s.ctx, YogStr::from_str(id), YogStr::from_str(title)) }
492    }
493
494    fn bossbar_set_progress(&self, id: &str, progress: f32) -> bool {
495        let s = srv!(self);
496        unsafe { (s.bossbar_set_progress)(s.ctx, YogStr::from_str(id), progress) }
497    }
498
499    fn bossbar_set_color(&self, id: &str, color: &str) -> bool {
500        let s = srv!(self);
501        unsafe { (s.bossbar_set_color)(s.ctx, YogStr::from_str(id), YogStr::from_str(color)) }
502    }
503
504    fn bossbar_add_player(&self, id: &str, player: &str) -> bool {
505        let s = srv!(self);
506        unsafe { (s.bossbar_add_player)(s.ctx, YogStr::from_str(id), YogStr::from_str(player)) }
507    }
508
509    fn bossbar_remove_player(&self, id: &str, player: &str) -> bool {
510        let s = srv!(self);
511        unsafe { (s.bossbar_remove_player)(s.ctx, YogStr::from_str(id), YogStr::from_str(player)) }
512    }
513
514    fn bossbar_set_visible(&self, id: &str, visible: bool) -> bool {
515        let s = srv!(self);
516        unsafe { (s.bossbar_set_visible)(s.ctx, YogStr::from_str(id), visible) }
517    }
518
519    fn online_players(&self) -> Vec<String> {
520        let s = srv!(self);
521        let owned = unsafe { (s.online_players)(s.ctx) };
522        let Some(text) = take_owned(s.free_str, owned) else {
523            return Vec::new();
524        };
525        if text.is_empty() {
526            Vec::new()
527        } else {
528            text.lines().map(str::to_owned).collect()
529        }
530    }
531
532    fn get_block_nbt(&self, dimension: &str, pos: yog_core::BlockPos) -> Option<String> {
533        let s = srv!(self);
534        let owned = unsafe {
535            (s.get_block_nbt)(
536                s.ctx,
537                YogStr::from_str(dimension),
538                yog_abi::YogBlockPos {
539                    x: pos.x,
540                    y: pos.y,
541                    z: pos.z,
542                },
543            )
544        };
545
546        take_owned(s.free_str, owned)
547    }
548
549    fn set_block_nbt(&self, dimension: &str, pos: yog_core::BlockPos, snbt: &str) -> bool {
550        let s = srv!(self);
551        unsafe {
552            (s.set_block_nbt)(
553                s.ctx,
554                YogStr::from_str(dimension),
555                yog_abi::YogBlockPos {
556                    x: pos.x,
557                    y: pos.y,
558                    z: pos.z,
559                },
560                YogStr::from_str(snbt),
561            )
562        }
563    }
564
565    fn get_inventory_slot(
566        &self,
567        dimension: &str,
568        pos: yog_core::BlockPos,
569        slot: u32,
570    ) -> Option<(String, u32, String)> {
571        let s = srv!(self);
572        let owned = unsafe {
573            (s.get_inventory_slot)(
574                s.ctx,
575                YogStr::from_str(dimension),
576                yog_abi::YogBlockPos {
577                    x: pos.x,
578                    y: pos.y,
579                    z: pos.z,
580                },
581                slot,
582            )
583        };
584        let text = take_owned(s.free_str, owned)?;
585        let mut it = text.splitn(3, '\t');
586        let item_id = it.next()?.to_owned();
587        let count = it.next()?.parse().ok()?;
588        let snbt = it.next().unwrap_or("{}").to_owned();
589        Some((item_id, count, snbt))
590    }
591
592    fn set_inventory_slot(
593        &self,
594        dimension: &str,
595        pos: yog_core::BlockPos,
596        slot: u32,
597        item_id: &str,
598        count: u32,
599        snbt: &str,
600    ) -> bool {
601        // The ABI's item id carries the SNBT after a tab.
602        let item = if snbt.is_empty() { item_id.to_string() } else { format!("{item_id}\t{snbt}") };
603        let s = srv!(self);
604        unsafe {
605            (s.set_inventory_slot)(
606                s.ctx,
607                YogStr::from_str(dimension),
608                yog_abi::YogBlockPos {
609                    x: pos.x,
610                    y: pos.y,
611                    z: pos.z,
612                },
613                slot,
614                YogStr::from_str(&item),
615                count,
616            )
617        }
618    }
619
620    fn player_inventory(&self, player: &str) -> Vec<(u32, String, u32)> {
621        let s = srv!(self);
622        let owned = unsafe { (s.player_inventory)(s.ctx, YogStr::from_str(player)) };
623        let Some(text) = take_owned(s.free_str, owned) else {
624            return Vec::new();
625        };
626        text.lines()
627            .filter_map(|line| {
628                let mut it = line.split('\t');
629                let slot: u32 = it.next()?.parse().ok()?;
630                let item_id = it.next()?.to_owned();
631                let count: u32 = it.next()?.parse().ok()?;
632                Some((slot, item_id, count))
633            })
634            .collect()
635    }
636
637    fn player_set_slot(&self, player: &str, slot: u32, item_id: &str, count: u32) -> bool {
638        let s = srv!(self);
639        unsafe {
640            (s.player_set_slot)(
641                s.ctx,
642                YogStr::from_str(player),
643                slot,
644                YogStr::from_str(item_id),
645                count,
646            )
647        }
648    }
649
650    fn teleport_to_dim(&self, player: &str, dimension: &str, x: f64, y: f64, z: f64) -> bool {
651        let s = srv!(self);
652        unsafe {
653            (s.player_teleport_dim)(
654                s.ctx,
655                YogStr::from_str(player),
656                YogStr::from_str(dimension),
657                yog_abi::YogVec3 { x, y, z },
658            )
659        }
660    }
661
662    fn entity_teleport_to_dim(&self, uuid: &str, dimension: &str, x: f64, y: f64, z: f64) -> bool {
663        let s = srv!(self);
664        unsafe {
665            (s.entity_teleport_dim)(
666                s.ctx,
667                YogStr::from_str(uuid),
668                YogStr::from_str(dimension),
669                yog_abi::YogVec3 { x, y, z },
670            )
671        }
672    }
673
674    fn world_entity_count(&self, dimension: &str, entity_type: &str) -> i32 {
675        let s = srv!(self);
676        unsafe {
677            (s.world_entity_count)(
678                s.ctx,
679                YogStr::from_str(dimension),
680                YogStr::from_str(entity_type),
681            )
682        }
683    }
684
685    fn entity_get_nbt(&self, uuid: &str) -> Option<String> {
686        let s = srv!(self);
687        let owned = unsafe { (s.entity_get_nbt)(s.ctx, YogStr::from_str(uuid)) };
688
689        take_owned(s.free_str, owned)
690    }
691
692    fn entity_set_nbt(&self, uuid: &str, snbt: &str) -> bool {
693        let s = srv!(self);
694        unsafe { (s.entity_set_nbt)(s.ctx, YogStr::from_str(uuid), YogStr::from_str(snbt)) }
695    }
696
697    fn spawn_particles(
698        &self,
699        dimension: &str,
700        x: f64,
701        y: f64,
702        z: f64,
703        particle_type: &str,
704        count: i32,
705        dx: f64,
706        dy: f64,
707        dz: f64,
708        speed: f64,
709    ) -> bool {
710        let s = srv!(self);
711        unsafe {
712            (s.spawn_particles)(
713                s.ctx,
714                YogStr::from_str(dimension),
715                yog_abi::YogVec3 { x, y, z },
716                YogStr::from_str(particle_type),
717                count,
718                dx,
719                dy,
720                dz,
721                speed,
722            )
723        }
724    }
725
726    fn entity_attribute_get(&self, uuid: &str, attribute_id: &str) -> Option<f64> {
727        let s = srv!(self);
728        let v = unsafe {
729            (s.entity_attribute_get)(
730                s.ctx,
731                YogStr::from_str(uuid),
732                YogStr::from_str(attribute_id),
733            )
734        };
735        if v.is_nan() { None } else { Some(v) }
736    }
737
738    fn entity_attribute_set(&self, uuid: &str, attribute_id: &str, value: f64) -> bool {
739        let s = srv!(self);
740        unsafe {
741            (s.entity_attribute_set)(
742                s.ctx,
743                YogStr::from_str(uuid),
744                YogStr::from_str(attribute_id),
745                value,
746            )
747        }
748    }
749
750    fn get_held_item_nbt(&self, player: &str) -> Option<String> {
751        let s = srv!(self);
752        let owned = unsafe { (s.get_held_item_nbt)(s.ctx, YogStr::from_str(player)) };
753
754        take_owned(s.free_str, owned)
755    }
756
757    fn set_held_item_nbt(&self, player: &str, snbt: &str) -> bool {
758        let s = srv!(self);
759        unsafe { (s.set_held_item_nbt)(s.ctx, YogStr::from_str(player), YogStr::from_str(snbt)) }
760    }
761
762    fn get_offhand_item_nbt(&self, player: &str) -> Option<String> {
763        let s = srv!(self);
764        let owned = unsafe { (s.get_offhand_item_nbt)(s.ctx, YogStr::from_str(player)) };
765
766        take_owned(s.free_str, owned)
767    }
768
769    fn set_offhand_item_nbt(&self, player: &str, snbt: &str) -> bool {
770        let s = srv!(self);
771        unsafe { (s.set_offhand_item_nbt)(s.ctx, YogStr::from_str(player), YogStr::from_str(snbt)) }
772    }
773
774    fn get_slot_item(&self, player: &str, slot: u32) -> Option<(String, u32, String)> {
775        let s = srv!(self);
776        let owned = unsafe { (s.get_slot_item)(s.ctx, YogStr::from_str(player), slot) };
777        let text = take_owned(s.free_str, owned)?;
778        let mut it = text.splitn(3, '\t');
779        let item_id = it.next()?.to_owned();
780        let count: u32 = it.next()?.parse().ok()?;
781        let nbt = it.next().unwrap_or("{}").to_owned();
782        Some((item_id, count, nbt))
783    }
784
785    fn set_slot_item(
786        &self,
787        player: &str,
788        slot: u32,
789        item_id: &str,
790        count: u32,
791        snbt: &str,
792    ) -> bool {
793        let s = srv!(self);
794        unsafe {
795            (s.set_slot_item)(
796                s.ctx,
797                YogStr::from_str(player),
798                slot,
799                YogStr::from_str(item_id),
800                count,
801                YogStr::from_str(snbt),
802            )
803        }
804    }
805
806    // ── world queries & effects (ABI minor 1) ────────────────────────────────
807
808    fn entity_info(&self, uuid: &str) -> Option<yog_core::EntityInfo> {
809        let s = srv!(self);
810        let owned = unsafe { (s.entity_info)(s.ctx, YogStr::from_str(uuid)) };
811        take_owned(s.free_str, owned).and_then(|l| yog_core::EntityInfo::decode(&l))
812    }
813
814    fn entities_in_box(
815        &self,
816        dimension: &str,
817        min: (f64, f64, f64),
818        max: (f64, f64, f64),
819    ) -> Vec<String> {
820        let s = srv!(self);
821        let owned =
822            unsafe { (s.entities_in_box)(s.ctx, YogStr::from_str(dimension), v3(min), v3(max)) };
823        take_owned(s.free_str, owned)
824            .map(|t| {
825                t.lines()
826                    .filter(|l| !l.is_empty())
827                    .map(str::to_owned)
828                    .collect()
829            })
830            .unwrap_or_default()
831    }
832
833    fn raycast_block(
834        &self,
835        dimension: &str,
836        from: (f64, f64, f64),
837        to: (f64, f64, f64),
838    ) -> Option<yog_core::BlockHit> {
839        let s = srv!(self);
840        let owned =
841            unsafe { (s.raycast_block)(s.ctx, YogStr::from_str(dimension), v3(from), v3(to)) };
842        take_owned(s.free_str, owned).and_then(|l| yog_core::BlockHit::decode(&l))
843    }
844
845    fn raycast_entity(
846        &self,
847        dimension: &str,
848        from: (f64, f64, f64),
849        to: (f64, f64, f64),
850        exclude: &str,
851    ) -> Option<String> {
852        let s = srv!(self);
853        let owned = unsafe {
854            (s.raycast_entity)(
855                s.ctx,
856                YogStr::from_str(dimension),
857                v3(from),
858                v3(to),
859                YogStr::from_str(exclude),
860            )
861        };
862        take_owned(s.free_str, owned).filter(|u| !u.is_empty())
863    }
864
865    fn block_info(&self, dimension: &str, pos: yog_core::BlockPos) -> Option<yog_core::BlockInfo> {
866        let s = srv!(self);
867        let owned = unsafe { (s.block_info)(s.ctx, YogStr::from_str(dimension), bp(pos)) };
868        take_owned(s.free_str, owned).and_then(|l| yog_core::BlockInfo::decode(&l))
869    }
870
871    fn break_block(
872        &self,
873        dimension: &str,
874        pos: yog_core::BlockPos,
875        drop: bool,
876        breaker: &str,
877    ) -> bool {
878        let s = srv!(self);
879        unsafe {
880            (s.break_block)(
881                s.ctx,
882                YogStr::from_str(dimension),
883                bp(pos),
884                drop,
885                YogStr::from_str(breaker),
886            )
887        }
888    }
889
890    fn place_block_from_slot(
891        &self,
892        player: &str,
893        slot: u32,
894        dimension: &str,
895        pos: yog_core::BlockPos,
896    ) -> bool {
897        let s = srv!(self);
898        unsafe {
899            (s.place_block_from_slot)(
900                s.ctx,
901                YogStr::from_str(player),
902                slot,
903                YogStr::from_str(dimension),
904                bp(pos),
905            )
906        }
907    }
908
909    fn bonemeal(&self, dimension: &str, pos: yog_core::BlockPos) -> bool {
910        let s = srv!(self);
911        unsafe { (s.bonemeal)(s.ctx, YogStr::from_str(dimension), bp(pos)) }
912    }
913
914    fn explode(
915        &self,
916        dimension: &str,
917        x: f64,
918        y: f64,
919        z: f64,
920        power: f32,
921        fire: bool,
922        source: &str,
923    ) -> bool {
924        let s = srv!(self);
925        unsafe {
926            (s.explode)(
927                s.ctx,
928                YogStr::from_str(dimension),
929                v3((x, y, z)),
930                power,
931                fire,
932                YogStr::from_str(source),
933            )
934        }
935    }
936
937    fn tellraw(&self, player: &str, json: &str) -> bool {
938        let s = srv!(self);
939        unsafe { (s.tellraw)(s.ctx, YogStr::from_str(player), YogStr::from_str(json)) }
940    }
941
942    fn entity_damage(&self, uuid: &str, amount: f32, damage_type: &str, attacker: &str) -> bool {
943        let s = srv!(self);
944        unsafe {
945            (s.entity_damage)(
946                s.ctx,
947                YogStr::from_str(uuid),
948                amount,
949                YogStr::from_str(damage_type),
950                YogStr::from_str(attacker),
951            )
952        }
953    }
954
955    fn entity_set_fire_ticks(&self, uuid: &str, ticks: i32) -> bool {
956        let s = srv!(self);
957        unsafe { (s.entity_set_fire_ticks)(s.ctx, YogStr::from_str(uuid), ticks) }
958    }
959
960    fn player_add_xp(&self, player: &str, amount: i32) -> bool {
961        let s = srv!(self);
962        unsafe { (s.player_add_xp)(s.ctx, YogStr::from_str(player), amount) }
963    }
964
965    fn player_set_may_fly(&self, player: &str, may_fly: bool) -> bool {
966        let s = srv!(self);
967        unsafe { (s.player_set_may_fly)(s.ctx, YogStr::from_str(player), may_fly) }
968    }
969
970    fn player_info(&self, player: &str) -> Option<yog_core::PlayerInfo> {
971        let s = srv!(self);
972        let owned = unsafe { (s.player_info)(s.ctx, YogStr::from_str(player)) };
973        take_owned(s.free_str, owned).and_then(|l| yog_core::PlayerInfo::decode(&l))
974    }
975
976    fn spawn_item(
977        &self,
978        dimension: &str,
979        pos: (f64, f64, f64),
980        vel: (f64, f64, f64),
981        item_id: &str,
982        count: u32,
983        snbt: &str,
984    ) -> Option<String> {
985        let s = srv!(self);
986        let owned = unsafe {
987            (s.spawn_item)(
988                s.ctx,
989                YogStr::from_str(dimension),
990                v3(pos),
991                v3(vel),
992                YogStr::from_str(item_id),
993                count,
994                YogStr::from_str(snbt),
995            )
996        };
997        take_owned(s.free_str, owned).filter(|u| !u.is_empty())
998    }
999
1000    fn item_entity_stack(&self, uuid: &str) -> Option<(String, u32, String)> {
1001        let s = srv!(self);
1002        let owned = unsafe { (s.item_entity_stack)(s.ctx, YogStr::from_str(uuid)) };
1003        let text = take_owned(s.free_str, owned)?;
1004        let mut it = text.splitn(3, '\t');
1005        let item_id = it.next()?.to_owned();
1006        let count = it.next()?.parse().ok()?;
1007        let nbt = it.next().unwrap_or("{}").to_owned();
1008        Some((item_id, count, nbt))
1009    }
1010
1011    fn item_entity_set_stack(&self, uuid: &str, item_id: &str, count: u32, snbt: &str) -> bool {
1012        let s = srv!(self);
1013        unsafe {
1014            (s.item_entity_set_stack)(
1015                s.ctx,
1016                YogStr::from_str(uuid),
1017                YogStr::from_str(item_id),
1018                count,
1019                YogStr::from_str(snbt),
1020            )
1021        }
1022    }
1023
1024    fn actionbar_json(&self, player: &str, json: &str) -> bool {
1025        let s = srv!(self);
1026        unsafe { (s.actionbar_json)(s.ctx, YogStr::from_str(player), YogStr::from_str(json)) }
1027    }
1028
1029    fn use_item_on_block(
1030        &self,
1031        dimension: &str,
1032        pos: yog_core::BlockPos,
1033        face: yog_core::Face,
1034        item_id: &str,
1035        player: &str,
1036    ) -> bool {
1037        let s = srv!(self);
1038        unsafe {
1039            (s.use_item_on_block)(
1040                s.ctx,
1041                YogStr::from_str(dimension),
1042                bp(pos),
1043                face.index(),
1044                YogStr::from_str(item_id),
1045                YogStr::from_str(player),
1046            )
1047        }
1048    }
1049
1050    fn pour_fluid(&self, dimension: &str, pos: yog_core::BlockPos, bucket_item_id: &str) -> bool {
1051        let s = srv!(self);
1052        unsafe {
1053            (s.pour_fluid)(
1054                s.ctx,
1055                YogStr::from_str(dimension),
1056                bp(pos),
1057                YogStr::from_str(bucket_item_id),
1058            )
1059        }
1060    }
1061
1062    fn has_entity_tag(&self, entity_type: &str, tag_id: &str) -> bool {
1063        let s = srv!(self);
1064        unsafe {
1065            (s.has_entity_tag)(
1066                s.ctx,
1067                YogStr::from_str(entity_type),
1068                YogStr::from_str(tag_id),
1069            )
1070        }
1071    }
1072
1073    fn item_block(&self, item_id: &str) -> Option<String> {
1074        let s = srv!(self);
1075        let owned = unsafe { (s.item_block)(s.ctx, YogStr::from_str(item_id)) };
1076        take_owned(s.free_str, owned).filter(|b| !b.is_empty())
1077    }
1078
1079    fn place_feature(&self, dimension: &str, pos: yog_core::BlockPos, feature_id: &str) -> bool {
1080        let s = srv!(self);
1081        unsafe {
1082            (s.place_feature)(
1083                s.ctx,
1084                YogStr::from_str(dimension),
1085                bp(pos),
1086                YogStr::from_str(feature_id),
1087            )
1088        }
1089    }
1090
1091    fn set_item_cooldown(&self, player: &str, item_id: &str, ticks: u32) -> bool {
1092        let s = srv!(self);
1093        unsafe { (s.set_item_cooldown)(s.ctx, YogStr::from_str(player), YogStr::from_str(item_id), ticks.min(i32::MAX as u32) as i32) }
1094    }
1095
1096    fn entity_vehicle(&self, uuid: &str) -> Option<String> {
1097        let s = srv!(self);
1098        let owned = unsafe { (s.entity_vehicle)(s.ctx, YogStr::from_str(uuid)) };
1099        take_owned(s.free_str, owned).filter(|v| !v.is_empty())
1100    }
1101
1102    fn entity_passengers(&self, uuid: &str) -> Vec<String> {
1103        let s = srv!(self);
1104        let owned = unsafe { (s.entity_passengers)(s.ctx, YogStr::from_str(uuid)) };
1105        take_owned(s.free_str, owned)
1106            .map(|t| t.lines().filter(|l| !l.is_empty()).map(str::to_string).collect())
1107            .unwrap_or_default()
1108    }
1109
1110    fn entity_mount(&self, rider: &str, vehicle: &str, force: bool) -> bool {
1111        let s = srv!(self);
1112        unsafe { (s.entity_mount)(s.ctx, YogStr::from_str(rider), YogStr::from_str(vehicle), force) }
1113    }
1114
1115    fn entity_dismount(&self, uuid: &str) -> bool {
1116        let s = srv!(self);
1117        unsafe { (s.entity_dismount)(s.ctx, YogStr::from_str(uuid)) }
1118    }
1119
1120    fn entity_data(&self, uuid: &str, key: &str) -> Option<Vec<u8>> {
1121        let s = srv!(self);
1122        let mut out = Vec::new();
1123        let found = unsafe {
1124            (s.entity_data_get)(s.ctx, YogStr::from_str(uuid), YogStr::from_str(key), &mut out as *mut Vec<u8> as *mut c_void, crate::body::collect)
1125        };
1126        found.then_some(out)
1127    }
1128
1129    fn set_entity_data(&self, uuid: &str, key: &str, value: Option<&[u8]>, persist: bool) -> bool {
1130        let s = srv!(self);
1131        let flags = value.map_or(0, |_| 1) | if persist { 2 } else { 0 };
1132        let v = value.unwrap_or(&[]);
1133        unsafe { (s.entity_data_set)(s.ctx, YogStr::from_str(uuid), YogStr::from_str(key), v.as_ptr(), v.len() as u32, flags) }
1134    }
1135
1136    fn entity_set_dimensions(&self, uuid: &str, size: Option<(f32, f32, f32)>) -> bool {
1137        let s = srv!(self);
1138        let (w, h, e) = size.unwrap_or((-1.0, 0.0, 0.0));
1139        unsafe { (s.entity_set_dimensions)(s.ctx, YogStr::from_str(uuid), w, h, e) }
1140    }
1141
1142    fn entity_set_fall_distance(&self, uuid: &str, distance: f32) -> bool {
1143        let s = srv!(self);
1144        unsafe { (s.entity_set_fall_distance)(s.ctx, YogStr::from_str(uuid), distance) }
1145    }
1146
1147    fn redstone_signal(&self, dimension: &str, pos: yog_core::BlockPos) -> Option<u8> {
1148        let s = srv!(self);
1149        let p = unsafe { (s.redstone_signal)(s.ctx, YogStr::from_str(dimension), bp(pos)) };
1150        (0..=15).contains(&p).then_some(p as u8)
1151    }
1152
1153    fn redstone_power(&self, dimension: &str, pos: yog_core::BlockPos) -> Option<u8> {
1154        let s = srv!(self);
1155        let p = unsafe { (s.redstone_power)(s.ctx, YogStr::from_str(dimension), bp(pos)) };
1156        (0..=15).contains(&p).then_some(p as u8)
1157    }
1158
1159    fn set_redstone_output(&self, dimension: &str, pos: yog_core::BlockPos, level: u8) -> bool {
1160        let s = srv!(self);
1161        unsafe { (s.set_redstone_output)(s.ctx, YogStr::from_str(dimension), bp(pos), level.min(15) as i32) }
1162    }
1163
1164    fn get_block_state(&self, dimension: &str, pos: yog_core::BlockPos) -> Option<String> {
1165        let s = srv!(self);
1166        let owned = unsafe { (s.get_block_state)(s.ctx, YogStr::from_str(dimension), bp(pos)) };
1167        take_owned(s.free_str, owned).filter(|b| !b.is_empty())
1168    }
1169
1170    fn set_block_state(&self, dimension: &str, pos: yog_core::BlockPos, state: &str) -> bool {
1171        let s = srv!(self);
1172        unsafe { (s.set_block_state)(s.ctx, YogStr::from_str(dimension), bp(pos), YogStr::from_str(state)) }
1173    }
1174
1175    fn world_is_thundering(&self, dimension: &str) -> bool {
1176        let s = srv!(self);
1177        unsafe { (s.world_is_thundering)(s.ctx, YogStr::from_str(dimension)) }
1178    }
1179
1180    fn world_set_thunder(&self, dimension: &str, thundering: bool, duration_ticks: i32) -> bool {
1181        let s = srv!(self);
1182        unsafe { (s.world_set_thunder)(s.ctx, YogStr::from_str(dimension), thundering, duration_ticks) }
1183    }
1184
1185    fn fill_region(&self, dimension: &str, from: yog_core::BlockPos, to: yog_core::BlockPos, state: &str) -> Option<u32> {
1186        let s = srv!(self);
1187        let n = unsafe { (s.fill_region)(s.ctx, YogStr::from_str(dimension), bp(from), bp(to), YogStr::from_str(state)) };
1188        u32::try_from(n).ok()
1189    }
1190
1191    fn scan_region(&self, dimension: &str, from: yog_core::BlockPos, to: yog_core::BlockPos) -> Vec<(yog_core::BlockPos, String)> {
1192        let s = srv!(self);
1193        let owned = unsafe { (s.scan_region)(s.ctx, YogStr::from_str(dimension), bp(from), bp(to)) };
1194        let Some(text) = take_owned(s.free_str, owned) else {
1195            return Vec::new();
1196        };
1197        text.lines()
1198            .filter_map(|line| {
1199                let mut it = line.splitn(4, ' ');
1200                let (x, y, z) = (it.next()?.parse().ok()?, it.next()?.parse().ok()?, it.next()?.parse().ok()?);
1201                Some((yog_core::BlockPos { x, y, z }, it.next()?.to_string()))
1202            })
1203            .collect()
1204    }
1205}
1206
1207/// Copy a runtime-owned string out and free it; `None` for NONE.
1208pub(crate) fn take_owned(
1209    free_str: unsafe extern "C" fn(ptr: *mut u8, len: u32),
1210    owned: yog_abi::YogOwnedStr,
1211) -> Option<String> {
1212    if owned.is_none() {
1213        return None;
1214    }
1215    // SAFETY: a non-NONE owned string is `len` valid bytes until freed.
1216    let text = unsafe {
1217        String::from_utf8_lossy(std::slice::from_raw_parts(owned.ptr, owned.len as usize))
1218            .into_owned()
1219    };
1220    unsafe { free_str(owned.ptr, owned.len) };
1221    Some(text)
1222}
1223
1224fn v3((x, y, z): (f64, f64, f64)) -> yog_abi::YogVec3 {
1225    yog_abi::YogVec3 { x, y, z }
1226}
1227
1228fn bp(pos: yog_core::BlockPos) -> yog_abi::YogBlockPos {
1229    yog_abi::YogBlockPos {
1230        x: pos.x,
1231        y: pos.y,
1232        z: pos.z,
1233    }
1234}
1235
1236// ── Trampoline helpers ────────────────────────────────────────────────────────
1237//
1238// A panic must never unwind out of a trampoline: the runtime calls them
1239// through `extern "C"`, so it would abort the whole game. `guard` stops it
1240// at the boundary — the panic message is already in the log — and the
1241// event goes on as if the mod hadn't handled it.
1242
1243fn guard<R>(fallback: R, call: impl FnOnce() -> R) -> R {
1244    std::panic::catch_unwind(std::panic::AssertUnwindSafe(call)).unwrap_or_else(|_| {
1245        crate::error!("a mod's callback panicked (see above); carrying on without it");
1246        fallback
1247    })
1248}
1249//
1250// Each trampoline is a `unsafe extern "C" fn` that:
1251//   1. Casts `ud` back to the original boxed closure.
1252//   2. Converts ABI C structs to Rust event types.
1253//   3. Builds a `CServer` from the `*const YogServer`.
1254//   4. Calls the closure.
1255//
1256// Closures are Box::into_raw'd in Registry methods — they are INTENTIONALLY
1257// leaked and live for the process lifetime.
1258
1259// ── Trampoline helpers ────────────────────────────────────────────────────────
1260//
1261// All phased event trampolines share the same pattern:
1262//   `phase: u8`  0 = EventPhase::Pre, 1 = EventPhase::Post
1263//   Return value is meaningful only in Pre phase.
1264
1265macro_rules! trampoline_phased {
1266    ($name:ident, $abi_ev:ty, $rust_ev:ty, |$ev:ident| $build:expr_2021) => {
1267        unsafe extern "C" fn $name<F>(
1268            ud: *mut c_void,
1269            srv: *const YogServer,
1270            ev: *const $abi_ev,
1271            phase: u8,
1272        ) -> bool
1273        where
1274            F: Fn(&$rust_ev, EventPhase, &dyn Server) -> bool + Send + Sync,
1275        {
1276            unsafe {
1277                let f = &*(ud as *const F);
1278                let $ev = &*ev;
1279                let rust_ev = $build;
1280                let p = if phase == 0 {
1281                    EventPhase::Pre
1282                } else {
1283                    EventPhase::Post
1284                };
1285                guard(true, || f(&rust_ev, p, &CServer(srv)))
1286            }
1287        }
1288    };
1289}
1290
1291trampoline_phased!(
1292    trampoline_block_break,
1293    YogBlockBreakEvent,
1294    BlockBreakEvent,
1295    |ev| BlockBreakEvent {
1296        player_name: ev.player.as_str().to_owned(),
1297        block_id: ev.block.as_str().to_owned(),
1298        pos: yog_core::BlockPos {
1299            x: ev.pos.x,
1300            y: ev.pos.y,
1301            z: ev.pos.z
1302        },
1303        dimension: ev.dimension.as_str().to_owned(),
1304    }
1305);
1306
1307trampoline_phased!(trampoline_chat, YogChatEvent, ChatEvent, |ev| ChatEvent {
1308    player_name: ev.player.as_str().to_owned(),
1309    message: ev.message.as_str().to_owned(),
1310    dimension: ev.dimension.as_str().to_owned(),
1311});
1312
1313trampoline_phased!(
1314    trampoline_player_join,
1315    YogPlayerEvent,
1316    PlayerJoinEvent,
1317    |ev| PlayerJoinEvent {
1318        player_name: ev.player.as_str().to_owned(),
1319        uuid: ev.uuid.as_str().to_owned(),
1320        dimension: ev.dimension.as_str().to_owned(),
1321    }
1322);
1323
1324trampoline_phased!(
1325    trampoline_player_leave,
1326    YogPlayerEvent,
1327    PlayerLeaveEvent,
1328    |ev| PlayerLeaveEvent {
1329        player_name: ev.player.as_str().to_owned(),
1330        uuid: ev.uuid.as_str().to_owned(),
1331        dimension: ev.dimension.as_str().to_owned(),
1332    }
1333);
1334
1335trampoline_phased!(trampoline_use_item, YogUseItemEvent, UseItemEvent, |ev| {
1336    UseItemEvent {
1337        player_name: ev.player.as_str().to_owned(),
1338        item_id: ev.item.as_str().to_owned(),
1339        sneaking: ev.sneaking,
1340        dimension: ev.dimension.as_str().to_owned(),
1341    }
1342});
1343
1344trampoline_phased!(
1345    trampoline_use_block,
1346    YogUseBlockEvent,
1347    UseBlockEvent,
1348    |ev| UseBlockEvent {
1349        player_name: ev.player.as_str().to_owned(),
1350        block_id: ev.block.as_str().to_owned(),
1351        pos: yog_core::BlockPos {
1352            x: ev.pos.x,
1353            y: ev.pos.y,
1354            z: ev.pos.z
1355        },
1356        dimension: ev.dimension.as_str().to_owned(),
1357        sneaking: ev.sneaking,
1358    }
1359);
1360
1361trampoline_phased!(
1362    trampoline_attack_entity,
1363    YogAttackEntityEvent,
1364    AttackEntityEvent,
1365    |ev| AttackEntityEvent {
1366        player_name: ev.player.as_str().to_owned(),
1367        target_type: ev.target_type.as_str().to_owned(),
1368        target_uuid: ev.target_uuid.as_str().to_owned(),
1369        dimension: ev.dimension.as_str().to_owned(),
1370    }
1371);
1372
1373trampoline_phased!(
1374    trampoline_entity_damage,
1375    YogEntityDamageEvent,
1376    EntityDamageEvent,
1377    |ev| EntityDamageEvent {
1378        entity_type: ev.entity_type.as_str().to_owned(),
1379        uuid: ev.uuid.as_str().to_owned(),
1380        amount: ev.amount,
1381        source: ev.source.as_str().to_owned(),
1382        dimension: ev.dimension.as_str().to_owned(),
1383    }
1384);
1385
1386trampoline_phased!(
1387    trampoline_entity_death,
1388    YogEntityDeathEvent,
1389    EntityDeathEvent,
1390    |ev| EntityDeathEvent {
1391        entity_type: ev.entity_type.as_str().to_owned(),
1392        uuid: ev.uuid.as_str().to_owned(),
1393        source: ev.source.as_str().to_owned(),
1394        dimension: ev.dimension.as_str().to_owned(),
1395    }
1396);
1397
1398trampoline_phased!(
1399    trampoline_entity_spawn,
1400    YogEntitySpawnEvent,
1401    EntitySpawnEvent,
1402    |ev| EntitySpawnEvent {
1403        entity_type: ev.entity_type.as_str().to_owned(),
1404        uuid: ev.uuid.as_str().to_owned(),
1405        dimension: ev.dimension.as_str().to_owned(),
1406    }
1407);
1408
1409trampoline_phased!(
1410    trampoline_place_block,
1411    YogPlaceBlockEvent,
1412    PlaceBlockEvent,
1413    |ev| PlaceBlockEvent {
1414        player_name: ev.player.as_str().to_owned(),
1415        block_id: ev.block.as_str().to_owned(),
1416        pos: yog_core::BlockPos {
1417            x: ev.pos.x,
1418            y: ev.pos.y,
1419            z: ev.pos.z
1420        },
1421        dimension: ev.dimension.as_str().to_owned(),
1422        sneaking: ev.sneaking,
1423    }
1424);
1425
1426trampoline_phased!(
1427    trampoline_player_death,
1428    YogPlayerDeathEvent,
1429    PlayerDeathEvent,
1430    |ev| PlayerDeathEvent {
1431        player_name: ev.player.as_str().to_owned(),
1432        uuid: ev.uuid.as_str().to_owned(),
1433        source: ev.source.as_str().to_owned(),
1434        dimension: ev.dimension.as_str().to_owned(),
1435    }
1436);
1437
1438trampoline_phased!(
1439    trampoline_player_respawn,
1440    YogPlayerRespawnEvent,
1441    PlayerRespawnEvent,
1442    |ev| PlayerRespawnEvent {
1443        player_name: ev.player.as_str().to_owned(),
1444        uuid: ev.uuid.as_str().to_owned(),
1445        at_anchor: ev.at_anchor,
1446        dimension: ev.dimension.as_str().to_owned(),
1447    }
1448);
1449
1450trampoline_phased!(
1451    trampoline_advancement,
1452    YogAdvancementEvent,
1453    AdvancementEvent,
1454    |ev| AdvancementEvent {
1455        player_name: ev.player.as_str().to_owned(),
1456        uuid: ev.uuid.as_str().to_owned(),
1457        advancement_id: ev.advancement.as_str().to_owned(),
1458        dimension: ev.dimension.as_str().to_owned(),
1459    }
1460);
1461
1462trampoline_phased!(
1463    trampoline_entity_interact,
1464    YogEntityInteractEvent,
1465    EntityInteractEvent,
1466    |ev| EntityInteractEvent {
1467        player_name: ev.player.as_str().to_owned(),
1468        player_uuid: ev.player_uuid.as_str().to_owned(),
1469        entity_type: ev.entity_type.as_str().to_owned(),
1470        entity_uuid: ev.entity_uuid.as_str().to_owned(),
1471        hand: ev.hand.as_str().to_owned(),
1472        dimension: ev.dimension.as_str().to_owned(),
1473    }
1474);
1475
1476trampoline_phased!(trampoline_craft, YogCraftEvent, CraftEvent, |ev| {
1477    CraftEvent {
1478        player_name: ev.player.as_str().to_owned(),
1479        player_uuid: ev.player_uuid.as_str().to_owned(),
1480        result_item: ev.result_item.as_str().to_owned(),
1481        result_count: ev.result_count,
1482        dimension: ev.dimension.as_str().to_owned(),
1483    }
1484});
1485
1486/// A machine — an inventory whose `.yui` has a `<RecipeArea kind="…">` —
1487/// making a recipe of its kind, like a crafting table: the result shows as
1488/// soon as its slots hold a recipe's ingredients, and taking it takes them.
1489///
1490/// - `Pre` — whether it may: `false` and the result doesn't show (a
1491///   workbench short of what the recipe's `values` cost). `player` is empty.
1492/// - `Post` — a player took the result; the host takes the ingredients, the mod
1493///   its share (the workbench's resources).
1494#[derive(Debug, Clone)]
1495pub struct MachineCraftEvent {
1496    /// The machine's inventory, e.g. `"mymod:press"`.
1497    pub machine: String,
1498    /// The recipe's kind (`"mymod:pressing"`) and id.
1499    pub kind: String,
1500    pub recipe: String,
1501    pub result_item: String,
1502    pub result_count: u32,
1503    /// The recipe's values: `{ "energy": 4 }`.
1504    pub values: yog_data::Value,
1505    pub pos: yog_core::BlockPos,
1506    pub dimension: String,
1507    pub player: String,
1508}
1509
1510trampoline_phased!(trampoline_machine_craft, YogMachineCraftEvent, MachineCraftEvent, |ev| {
1511    MachineCraftEvent {
1512        machine: ev.machine.as_str().to_owned(),
1513        kind: ev.kind.as_str().to_owned(),
1514        recipe: ev.recipe.as_str().to_owned(),
1515        result_item: ev.result_item.as_str().to_owned(),
1516        result_count: ev.result_count,
1517        values: yog_data::json::from_json_text(ev.values.as_str()).unwrap_or(yog_data::Value::Null),
1518        pos: yog_core::BlockPos { x: ev.pos.x, y: ev.pos.y, z: ev.pos.z },
1519        dimension: ev.dimension.as_str().to_owned(),
1520        player: ev.player.as_str().to_owned(),
1521    }
1522});
1523
1524trampoline_phased!(
1525    trampoline_explosion,
1526    YogExplosionEvent,
1527    ExplosionEvent,
1528    |ev| ExplosionEvent {
1529        dimension: ev.dimension.as_str().to_owned(),
1530        x: ev.x,
1531        y: ev.y,
1532        z: ev.z,
1533        power: ev.power,
1534        cause_uuid: ev.cause_uuid.as_str().to_owned(),
1535    }
1536);
1537
1538trampoline_phased!(
1539    trampoline_item_insert,
1540    YogItemInsertEvent,
1541    ItemInsertEvent,
1542    |ev| ItemInsertEvent {
1543        block_id: ev.block.as_str().to_owned(),
1544        pos: yog_core::BlockPos {
1545            x: ev.pos.x,
1546            y: ev.pos.y,
1547            z: ev.pos.z
1548        },
1549        dimension: ev.dimension.as_str().to_owned(),
1550        item_id: ev.item_id.as_str().to_owned(),
1551        count: ev.count,
1552        nbt: ev.nbt.as_str().to_owned(),
1553    }
1554);
1555
1556trampoline_phased!(
1557    trampoline_item_pickup,
1558    YogItemPickupEvent,
1559    ItemPickupEvent,
1560    |ev| ItemPickupEvent {
1561        player_name: ev.player.as_str().to_owned(),
1562        player_uuid: ev.player_uuid.as_str().to_owned(),
1563        item_id: ev.item_id.as_str().to_owned(),
1564        item_count: ev.item_count,
1565        entity_uuid: ev.entity_uuid.as_str().to_owned(),
1566        dimension: ev.dimension.as_str().to_owned(),
1567    }
1568);
1569
1570trampoline_phased!(
1571    trampoline_player_move,
1572    YogPlayerMoveEvent,
1573    PlayerMoveEvent,
1574    |ev| PlayerMoveEvent {
1575        player_name: ev.player.as_str().to_owned(),
1576        player_uuid: ev.player_uuid.as_str().to_owned(),
1577        x: ev.x,
1578        y: ev.y,
1579        z: ev.z,
1580        yaw: ev.yaw,
1581        pitch: ev.pitch,
1582        dimension: ev.dimension.as_str().to_owned(),
1583    }
1584);
1585
1586trampoline_phased!(
1587    trampoline_container_open,
1588    YogContainerOpenEvent,
1589    ContainerOpenEvent,
1590    |ev| ContainerOpenEvent {
1591        player_name: ev.player.as_str().to_owned(),
1592        player_uuid: ev.player_uuid.as_str().to_owned(),
1593        container_type: ev.container_type.as_str().to_owned(),
1594        dimension: ev.dimension.as_str().to_owned(),
1595    }
1596);
1597
1598trampoline_phased!(
1599    trampoline_container_close,
1600    YogContainerCloseEvent,
1601    ContainerCloseEvent,
1602    |ev| ContainerCloseEvent {
1603        player_name: ev.player.as_str().to_owned(),
1604        player_uuid: ev.player_uuid.as_str().to_owned(),
1605        dimension: ev.dimension.as_str().to_owned(),
1606    }
1607);
1608
1609trampoline_phased!(
1610    trampoline_projectile_hit,
1611    YogProjectileHitEvent,
1612    ProjectileHitEvent,
1613    |ev| ProjectileHitEvent {
1614        projectile_type: ev.projectile_type.as_str().to_owned(),
1615        projectile_uuid: ev.projectile_uuid.as_str().to_owned(),
1616        shooter_uuid: ev.shooter_uuid.as_str().to_owned(),
1617        hit_type: ev.hit_type.as_str().to_owned(),
1618        hit_entity_uuid: ev.hit_entity_uuid.as_str().to_owned(),
1619        x: ev.x,
1620        y: ev.y,
1621        z: ev.z,
1622        dimension: ev.dimension.as_str().to_owned(),
1623    }
1624);
1625
1626unsafe extern "C" fn trampoline_server_fn<F>(ud: *mut c_void, srv: *const YogServer)
1627where
1628    F: Fn(&dyn Server) + Send + Sync,
1629{
1630    unsafe {
1631        let f = &*(ud as *const F);
1632        guard((), || f(&CServer(srv)));
1633    }
1634}
1635
1636unsafe extern "C" fn trampoline_packet<F>(
1637    ud: *mut c_void,
1638    srv: *const YogServer,
1639    ev: *const YogPacketEvent,
1640) where
1641    F: Fn(&PacketEvent, &dyn Server) + Send + Sync,
1642{
1643    unsafe {
1644        let f = &*(ud as *const F);
1645        let ev = &*ev;
1646        let rust_ev = PacketEvent {
1647            channel: ev.channel.as_str().to_owned(),
1648            player: ev.player.as_str().to_owned(),
1649            // (A null pointer with no bytes is fine for C, not for a slice.)
1650            payload: if ev.payload.is_null() || ev.payload_len == 0 {
1651                Vec::new()
1652            } else {
1653                std::slice::from_raw_parts(ev.payload, ev.payload_len as usize).to_vec()
1654            },
1655        };
1656        guard((), || f(&rust_ev, &CServer(srv)));
1657    }
1658}
1659
1660unsafe extern "C" fn trampoline_command<F>(
1661    ud: *mut c_void,
1662    srv: *const YogServer,
1663    ev: *const YogCommandEvent,
1664    reply_buf: *mut u8,
1665    reply_cap: u32,
1666    reply_len: *mut u32,
1667) where
1668    F: Fn(&CommandContext, &dyn Server) -> Option<String> + Send + Sync,
1669{
1670    unsafe {
1671        let f = &*(ud as *const F);
1672        let ev = &*ev;
1673        let ctx = CommandContext {
1674            name: ev.name.as_str().to_owned(),
1675            args: ev.args.as_str().to_owned(),
1676            source: ev.source.as_str().to_owned(),
1677            uuid: ev.uuid.as_str().to_owned(),
1678            dimension: ev.dimension.as_str().to_owned(),
1679        };
1680        *reply_len = 0;
1681        if let Some(reply) = guard(None, || f(&ctx, &CServer(srv))) {
1682            let bytes = reply.as_bytes();
1683            // As much as fits, cut between characters (it's read as UTF-8).
1684            let mut n = bytes.len().min(reply_cap as usize);
1685            while !reply.is_char_boundary(n) {
1686                n -= 1;
1687            }
1688            std::ptr::copy_nonoverlapping(bytes.as_ptr(), reply_buf, n);
1689            *reply_len = n as u32;
1690        }
1691    }
1692}
1693
1694unsafe extern "C" fn trampoline_scheduled<F>(ud: *mut c_void, srv: *const YogServer)
1695where
1696    F: Fn(&dyn Server) + Send + Sync,
1697{
1698    unsafe {
1699        let f = &*(ud as *const F);
1700        guard((), || f(&CServer(srv)));
1701    }
1702}
1703
1704// ── ABI minor 10 — client-side trampolines ────────────────────────────────────
1705
1706unsafe extern "C" fn trampoline_client_tick<F>(ud: *mut c_void)
1707where
1708    F: Fn(&ClientTickEvent) + Send + Sync,
1709{
1710    unsafe {
1711        let f = &*(ud as *const F);
1712        guard((), || f(&ClientTickEvent {}));
1713    }
1714}
1715
1716unsafe extern "C" fn trampoline_hud_render<F>(ud: *mut c_void, gfx: *const YogGfxApi)
1717where
1718    F: Fn(&GfxContext) + Send + Sync,
1719{
1720    unsafe {
1721        let f = &*(ud as *const F);
1722        guard((), || f(&GfxContext::from_raw(gfx)));
1723    }
1724}
1725
1726/// What `Registry::on_item_tooltip` keeps: the size and the draw closures.
1727struct TooltipPicture<S, D> {
1728    size: S,
1729    draw: D,
1730}
1731
1732unsafe extern "C" fn trampoline_tooltip_size<S, D>(ud: *mut c_void, item: YogStr, snbt: YogStr, w: *mut f32, h: *mut f32) -> bool
1733where
1734    S: Fn(&str, &str) -> Option<(f32, f32)> + Send + Sync,
1735{
1736    unsafe {
1737        let t = &*(ud as *const TooltipPicture<S, D>);
1738        match guard(None, || (t.size)(item.as_str(), snbt.as_str())) {
1739            Some((pw, ph)) => {
1740                (*w, *h) = (pw, ph);
1741                true
1742            }
1743            None => false,
1744        }
1745    }
1746}
1747
1748unsafe extern "C" fn trampoline_item_text<F>(ud: *mut c_void, item: YogStr, snbt: YogStr, sink: *mut c_void, write: yog_abi::YogTextSink) -> bool
1749where
1750    F: Fn(&str, &str) -> Option<(Option<String>, Vec<String>)> + Send + Sync,
1751{
1752    unsafe {
1753        let f = &*(ud as *const F);
1754        let Some((name, lines)) = guard(None, || f(item.as_str(), snbt.as_str())) else { return false };
1755        let mut text = name.unwrap_or_default();
1756        for l in lines {
1757            text.push('\n');
1758            text.push_str(&l.replace('\n', " "));
1759        }
1760        write(sink, YogStr::from_str(&text));
1761        true
1762    }
1763}
1764
1765unsafe extern "C" fn trampoline_entity_tick<F>(ud: *mut c_void, srv: *const yog_abi::YogServer, uuid: YogStr)
1766where
1767    F: Fn(&dyn Server, &str) + Send + Sync,
1768{
1769    unsafe {
1770        let f = &*(ud as *const F);
1771        let s = CServer(srv);
1772        guard((), || f(&s, uuid.as_str()));
1773    }
1774}
1775
1776unsafe extern "C" fn trampoline_loot<F>(
1777    ud: *mut c_void,
1778    srv: *const yog_abi::YogServer,
1779    loot: *const u8,
1780    len: usize,
1781    sink: *mut c_void,
1782    write: yog_abi::YogBytesSink,
1783) where
1784    F: Fn(&dyn Server, &mut crate::loot::Loot) + Send + Sync,
1785{
1786    use yog_data::Schema;
1787    unsafe {
1788        let f = &*(ud as *const F);
1789        let Ok(mut loot) = yog_data::read_bytes::<crate::loot::Loot>(std::slice::from_raw_parts(loot, len)) else { return };
1790        let before = loot.items.clone();
1791        let s = CServer(srv);
1792        guard((), || f(&s, &mut loot));
1793        if loot.items != before {
1794            let bytes = yog_data::binary::encode(&loot.items.write());
1795            write(sink, bytes.as_ptr(), bytes.len());
1796        }
1797    }
1798}
1799
1800unsafe extern "C" fn trampoline_body<F>(ud: *mut c_void, frame: *const u8, len: usize, sink: *mut c_void, write: yog_abi::YogBytesSink)
1801where
1802    F: Fn(&yog_body::Frame, &mut yog_body::Ops) + Send + Sync,
1803{
1804    unsafe {
1805        let f = &*(ud as *const F);
1806        let Some(frame) = yog_body::Frame::decode(std::slice::from_raw_parts(frame, len)) else { return };
1807        let mut ops = yog_body::Ops::default();
1808        guard((), || f(&frame, &mut ops));
1809        if !ops.is_empty() {
1810            write(sink, ops.0.as_ptr(), ops.0.len());
1811        }
1812    }
1813}
1814
1815unsafe extern "C" fn trampoline_camera<F>(ud: *mut c_void, frame: *const yog_abi::YogCameraFrame, out: *mut yog_abi::YogCameraOut)
1816where
1817    F: Fn(&yog_body::CameraFrame, &mut yog_body::CameraOut) + Send + Sync,
1818{
1819    unsafe {
1820        let f = &*(ud as *const F);
1821        let c = &*frame;
1822        let frame = yog_body::CameraFrame {
1823            uuid: c.uuid.as_str().to_owned(),
1824            partial: c.partial,
1825            pos: c.pos,
1826            yaw: c.yaw,
1827            pitch: c.pitch,
1828            detached: c.detached,
1829            flags: c.flags,
1830        };
1831        let o = &mut *out;
1832        let mut cam = yog_body::CameraOut {
1833            local_offset: yog_body::Vec3::from_array(o.local_offset),
1834            world_offset: yog_body::Vec3::from_array(o.world_offset),
1835            yaw: o.yaw,
1836            pitch: o.pitch,
1837            roll: o.roll,
1838            fov: o.fov,
1839        };
1840        guard((), || f(&frame, &mut cam));
1841        *o = yog_abi::YogCameraOut {
1842            local_offset: cam.local_offset.to_array(),
1843            world_offset: cam.world_offset.to_array(),
1844            yaw: cam.yaw,
1845            pitch: cam.pitch,
1846            roll: cam.roll,
1847            fov: cam.fov,
1848        };
1849    }
1850}
1851
1852unsafe extern "C" fn trampoline_travel<F>(ud: *mut c_void, frame: *const yog_abi::YogTravelFrame, velocity: *mut [f32; 3]) -> bool
1853where
1854    F: Fn(&yog_body::TravelFrame) -> Option<yog_body::Vec3> + Send + Sync,
1855{
1856    unsafe {
1857        let f = &*(ud as *const F);
1858        let t = &*frame;
1859        let frame = yog_body::TravelFrame {
1860            uuid: t.uuid.as_str().to_owned(),
1861            velocity: yog_body::Vec3::from_array(t.velocity),
1862            look: yog_body::Vec3::from_array(t.look),
1863            yaw: t.yaw,
1864            pitch: t.pitch,
1865            forward: t.forward,
1866            strafe: t.strafe,
1867            jumping: t.jumping,
1868            sneaking: t.sneaking,
1869            gravity: t.gravity,
1870            flags: t.flags,
1871        };
1872        match guard(None, || f(&frame)) {
1873            Some(v) => {
1874                *velocity = v.to_array();
1875                true
1876            }
1877            None => false,
1878        }
1879    }
1880}
1881
1882#[allow(clippy::too_many_arguments)]
1883unsafe extern "C" fn trampoline_tooltip_draw<S, D>(ud: *mut c_void, gfx: *const YogGfxApi, item: YogStr, snbt: YogStr, x: f32, y: f32, w: f32, h: f32)
1884where
1885    D: Fn(&GfxContext, &str, &str, [f32; 4]) + Send + Sync,
1886{
1887    unsafe {
1888        let t = &*(ud as *const TooltipPicture<S, D>);
1889        guard((), || (t.draw)(&GfxContext::from_raw(gfx), item.as_str(), snbt.as_str(), [x, y, w, h]));
1890    }
1891}
1892
1893#[allow(clippy::too_many_arguments)]
1894unsafe extern "C" fn trampoline_book_page<F>(ud: *mut c_void, gfx: *const YogGfxApi, data: *const u8, len: usize, x: f32, y: f32, w: f32, h: f32)
1895where
1896    F: Fn(&GfxContext, &yog_data::Value, [f32; 4]) + Send + Sync,
1897{
1898    unsafe {
1899        let f = &*(ud as *const F);
1900        let bytes = if data.is_null() { &[][..] } else { std::slice::from_raw_parts(data, len) };
1901        let value = yog_data::binary::decode(bytes).unwrap_or(yog_data::Value::Null);
1902        guard((), || f(&GfxContext::from_raw(gfx), &value, [x, y, w, h]));
1903    }
1904}
1905
1906unsafe extern "C" fn trampoline_world_render<F>(ud: *mut c_void, gfx: *const YogGfxApi)
1907where
1908    F: Fn(&GfxContext) + Send + Sync,
1909{
1910    unsafe {
1911        let f = &*(ud as *const F);
1912        guard((), || f(&GfxContext::from_raw(gfx)));
1913    }
1914}
1915
1916unsafe extern "C" fn trampoline_key_press<F>(ud: *mut c_void, ev: *const YogKeyPressEvent) -> bool
1917where
1918    F: Fn(&KeyPressEvent) -> bool + Send + Sync,
1919{
1920    unsafe {
1921        let f = &*(ud as *const F);
1922        let e = &*ev;
1923        let ev = KeyPressEvent { key_code: e.key_code, scan_code: e.scan_code, action: e.action, modifiers: e.modifiers };
1924        guard(false, || f(&ev))
1925    }
1926}
1927
1928unsafe extern "C" fn trampoline_screen<F>(ud: *mut c_void, screen_class: YogStr) -> bool
1929where
1930    F: Fn(&ScreenEvent) + Send + Sync,
1931{
1932    unsafe {
1933        let f = &*(ud as *const F);
1934        let ev = ScreenEvent { screen_class: screen_class.as_str().to_owned() };
1935        guard((), || f(&ev));
1936        true
1937    }
1938}
1939
1940// ── Registry ─────────────────────────────────────────────────────────────────
1941
1942/// Wraps the [`YogApi`] table and provides an ergonomic registration API.
1943///
1944/// Obtained inside `yog_mod_register` via `export_mod!`.  Closures registered
1945/// here are boxed and leaked — they live as long as the process (which is the
1946/// correct lifetime for a server mod).
1947/// Pointer to the runtime's `YogApi` table (a process-lifetime static in the
1948/// runtime), captured when the mod registers. Lets free functions like
1949/// [`installed_mods`] work outside of `register()` — e.g. in UI handlers.
1950static GLOBAL_API: std::sync::atomic::AtomicPtr<YogApi> =
1951    std::sync::atomic::AtomicPtr::new(std::ptr::null_mut());
1952
1953/// The runtime's `YogApi` table, null before this mod registered.
1954pub(crate) fn global_api() -> *mut YogApi {
1955    GLOBAL_API.load(std::sync::atomic::Ordering::Acquire)
1956}
1957
1958/// Metadata of an installed mod, as reported by the loader.
1959#[derive(Debug, Clone)]
1960pub struct ModInfo {
1961    /// `"yog"` for .yog mods, `"platform"` for loader (Java) mods.
1962    pub source: String,
1963    pub id: String,
1964    pub name: String,
1965    pub version: String,
1966    /// Comma-separated author list (may be empty).
1967    pub authors: String,
1968    pub description: String,
1969}
1970
1971/// All installed mods known to the loader: .yog mods plus, where the host
1972/// exposes them, platform (Java) mods. Callable at any time after this mod's
1973/// `register()` ran — including client-side UI handlers. Note that during
1974/// `register()` mods that load after this one are not in the list yet; query
1975/// lazily (e.g. on first render) for a complete view.
1976pub fn installed_mods() -> Vec<ModInfo> {
1977    let api = GLOBAL_API.load(std::sync::atomic::Ordering::Acquire);
1978    if api.is_null() {
1979        return Vec::new();
1980    }
1981    let owned = unsafe { ((*api).mods_list)((*api).ctx) };
1982    let Some(text) = take_owned(unsafe { (*api).free_str }, owned) else {
1983        return Vec::new();
1984    };
1985    text.lines()
1986        .filter_map(|line| {
1987            let mut f = line.split('\t');
1988            Some(ModInfo {
1989                source: f.next()?.to_string(),
1990                id: f.next()?.to_string(),
1991                name: f.next().unwrap_or_default().to_string(),
1992                version: f.next().unwrap_or_default().to_string(),
1993                authors: f.next().unwrap_or_default().to_string(),
1994                description: f.next().unwrap_or_default().to_string(),
1995            })
1996        })
1997        .collect()
1998}
1999
2000/// Open the Yog UI registered as `ui_id` (client side; no-op on dedicated
2001/// servers). `modal` blocks game input, `pause` pauses singleplayer. Callable
2002/// from any handler after registration — e.g. an `on_client_packet` handler.
2003pub fn open_ui(ui_id: &str, modal: bool, pause: bool) {
2004    let api = GLOBAL_API.load(std::sync::atomic::Ordering::Acquire);
2005    if api.is_null() {
2006        return;
2007    }
2008    unsafe { ((*api).ui_open)((*api).ctx, YogStr::from_str(ui_id), modal, pause) }
2009}
2010
2011/// Close the Yog UI screen showing `ui_id` — e.g. from that screen's own
2012/// "Done" button. Does nothing when another screen is open. Deferred onto the
2013/// render thread, so the handler that calls it finishes first. Client side;
2014/// a no-op on dedicated servers.
2015pub fn close_ui(ui_id: &str) {
2016    let api = GLOBAL_API.load(std::sync::atomic::Ordering::Acquire);
2017    if api.is_null() {
2018        return;
2019    }
2020    unsafe { ((*api).ui_close)((*api).ctx, YogStr::from_str(ui_id)) }
2021}
2022
2023/// What a [`Registry::register_ui`] handler returns: `()` (never marks
2024/// events as used) or `bool` (`true` = the handler used this `key:`/`char:`
2025/// event — the host then doesn't, e.g. Esc doesn't close the screen).
2026pub trait UiHandled {
2027    fn handled(self) -> bool;
2028}
2029
2030impl UiHandled for () {
2031    fn handled(self) -> bool {
2032        false
2033    }
2034}
2035
2036impl UiHandled for bool {
2037    fn handled(self) -> bool {
2038        self
2039    }
2040}
2041
2042/// Handle to the runtime's server-action table, usable from any handler after
2043/// registration — including client-side ones that don't receive `&dyn Server`
2044/// (UI event handlers, client tick). Server-world actions are no-ops client
2045/// side, but networking (`send_to_server`) and similar client-safe calls work.
2046pub fn server() -> Option<CServer> {
2047    let api = GLOBAL_API.load(std::sync::atomic::Ordering::Acquire);
2048    if api.is_null() {
2049        return None;
2050    }
2051    let srv = unsafe { (*api).server };
2052    if srv.is_null() {
2053        return None;
2054    }
2055    Some(CServer(srv))
2056}
2057
2058pub struct Registry {
2059    api: *const YogApi,
2060}
2061
2062// SAFETY: `api` is a static provided by the runtime, valid for process lifetime.
2063unsafe impl Send for Registry {}
2064unsafe impl Sync for Registry {}
2065
2066impl Registry {
2067    /// Build from the pointer passed by the runtime. Only called by `export_mod!`.
2068    ///
2069    /// # Safety
2070    ///
2071    /// `api` must point to the runtime's `YogApi` table, valid for the rest of
2072    /// the process.
2073    pub unsafe fn from_raw(api: *const YogApi) -> Self {
2074        GLOBAL_API.store(api as *mut YogApi, std::sync::atomic::Ordering::Release);
2075        Self { api }
2076    }
2077
2078    #[inline]
2079    fn ctx(&self) -> *mut c_void {
2080        unsafe { (*self.api).ctx }
2081    }
2082
2083    // ── helpers ──────────────────────────────────────────────────────────────
2084
2085    fn leak<F: 'static>(f: F) -> *mut c_void {
2086        Box::into_raw(Box::new(f)) as *mut c_void
2087    }
2088
2089    // ── events ───────────────────────────────────────────────────────────────
2090    //
2091    // All handlers receive `(event, EventPhase, &dyn Server) -> bool`.
2092    // In `Pre` phase, returning `false` cancels the action.
2093    // In `Post` phase, the return value is ignored.
2094    // A single registration fires for BOTH phases.
2095
2096    pub fn on_block_break<F>(&mut self, handler: F)
2097    where
2098        F: Fn(&BlockBreakEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2099    {
2100        let ud = Self::leak(handler);
2101        unsafe { ((*self.api).on_block_break)(self.ctx(), ud, trampoline_block_break::<F>) }
2102    }
2103
2104    pub fn on_chat<F>(&mut self, handler: F)
2105    where
2106        F: Fn(&ChatEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2107    {
2108        let ud = Self::leak(handler);
2109        unsafe { ((*self.api).on_chat)(self.ctx(), ud, trampoline_chat::<F>) }
2110    }
2111
2112    pub fn on_player_join<F>(&mut self, handler: F)
2113    where
2114        F: Fn(&PlayerJoinEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2115    {
2116        let ud = Self::leak(handler);
2117        unsafe { ((*self.api).on_player_join)(self.ctx(), ud, trampoline_player_join::<F>) }
2118    }
2119
2120    pub fn on_player_leave<F>(&mut self, handler: F)
2121    where
2122        F: Fn(&PlayerLeaveEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2123    {
2124        let ud = Self::leak(handler);
2125        unsafe { ((*self.api).on_player_leave)(self.ctx(), ud, trampoline_player_leave::<F>) }
2126    }
2127
2128    pub fn on_use_item<F>(&mut self, handler: F)
2129    where
2130        F: Fn(&UseItemEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2131    {
2132        let ud = Self::leak(handler);
2133        unsafe { ((*self.api).on_use_item)(self.ctx(), ud, trampoline_use_item::<F>) }
2134    }
2135
2136    pub fn on_use_block<F>(&mut self, handler: F)
2137    where
2138        F: Fn(&UseBlockEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2139    {
2140        let ud = Self::leak(handler);
2141        unsafe { ((*self.api).on_use_block)(self.ctx(), ud, trampoline_use_block::<F>) }
2142    }
2143
2144    pub fn on_attack_entity<F>(&mut self, handler: F)
2145    where
2146        F: Fn(&AttackEntityEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2147    {
2148        let ud = Self::leak(handler);
2149        unsafe { ((*self.api).on_attack_entity)(self.ctx(), ud, trampoline_attack_entity::<F>) }
2150    }
2151
2152    pub fn on_entity_damage<F>(&mut self, handler: F)
2153    where
2154        F: Fn(&EntityDamageEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2155    {
2156        let ud = Self::leak(handler);
2157        unsafe { ((*self.api).on_entity_damage)(self.ctx(), ud, trampoline_entity_damage::<F>) }
2158    }
2159
2160    pub fn on_entity_death<F>(&mut self, handler: F)
2161    where
2162        F: Fn(&EntityDeathEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2163    {
2164        let ud = Self::leak(handler);
2165        unsafe { ((*self.api).on_entity_death)(self.ctx(), ud, trampoline_entity_death::<F>) }
2166    }
2167
2168    pub fn on_entity_spawn<F>(&mut self, handler: F)
2169    where
2170        F: Fn(&EntitySpawnEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2171    {
2172        let ud = Self::leak(handler);
2173        unsafe { ((*self.api).on_entity_spawn)(self.ctx(), ud, trampoline_entity_spawn::<F>) }
2174    }
2175
2176    pub fn on_player_place_block<F>(&mut self, handler: F)
2177    where
2178        F: Fn(&PlaceBlockEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2179    {
2180        let ud = Self::leak(handler);
2181        unsafe { ((*self.api).on_player_place_block)(self.ctx(), ud, trampoline_place_block::<F>) }
2182    }
2183
2184    pub fn on_player_death<F>(&mut self, handler: F)
2185    where
2186        F: Fn(&PlayerDeathEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2187    {
2188        let ud = Self::leak(handler);
2189        unsafe { ((*self.api).on_player_death)(self.ctx(), ud, trampoline_player_death::<F>) }
2190    }
2191
2192    pub fn on_player_respawn<F>(&mut self, handler: F)
2193    where
2194        F: Fn(&PlayerRespawnEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2195    {
2196        let ud = Self::leak(handler);
2197        unsafe { ((*self.api).on_player_respawn)(self.ctx(), ud, trampoline_player_respawn::<F>) }
2198    }
2199
2200    pub fn on_advancement<F>(&mut self, handler: F)
2201    where
2202        F: Fn(&AdvancementEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2203    {
2204        let ud = Self::leak(handler);
2205        unsafe { ((*self.api).on_advancement)(self.ctx(), ud, trampoline_advancement::<F>) }
2206    }
2207
2208    pub fn on_entity_interact<F>(&mut self, handler: F)
2209    where
2210        F: Fn(&EntityInteractEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2211    {
2212        let ud = Self::leak(handler);
2213        unsafe { ((*self.api).on_entity_interact)(self.ctx(), ud, trampoline_entity_interact::<F>) }
2214    }
2215
2216    pub fn on_item_craft<F>(&mut self, handler: F)
2217    where
2218        F: Fn(&CraftEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2219    {
2220        let ud = Self::leak(handler);
2221        unsafe { ((*self.api).on_item_craft)(self.ctx(), ud, trampoline_craft::<F>) }
2222    }
2223
2224    /// A machine making a recipe — see [`MachineCraftEvent`].
2225    pub fn on_machine_craft<F>(&mut self, handler: F)
2226    where
2227        F: Fn(&MachineCraftEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2228    {
2229        let ud = Self::leak(handler);
2230        unsafe { ((*self.api).on_machine_craft)(self.ctx(), ud, trampoline_machine_craft::<F>) }
2231    }
2232
2233    pub fn on_explosion<F>(&mut self, handler: F)
2234    where
2235        F: Fn(&ExplosionEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2236    {
2237        let ud = Self::leak(handler);
2238        unsafe { ((*self.api).on_explosion)(self.ctx(), ud, trampoline_explosion::<F>) }
2239    }
2240
2241    /// A hopper or dropper offers an item to a block that accepts items
2242    /// (`block.accepts_items`): `Pre` returns whether it takes it, `Post`
2243    /// takes it.
2244    pub fn on_item_insert<F>(&mut self, handler: F)
2245    where
2246        F: Fn(&ItemInsertEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2247    {
2248        let ud = Self::leak(handler);
2249        unsafe { ((*self.api).on_item_insert)(self.ctx(), ud, trampoline_item_insert::<F>) }
2250    }
2251
2252    pub fn on_item_pickup<F>(&mut self, handler: F)
2253    where
2254        F: Fn(&ItemPickupEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2255    {
2256        let ud = Self::leak(handler);
2257        unsafe { ((*self.api).on_item_pickup)(self.ctx(), ud, trampoline_item_pickup::<F>) }
2258    }
2259
2260    pub fn on_player_move<F>(&mut self, handler: F)
2261    where
2262        F: Fn(&PlayerMoveEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2263    {
2264        let ud = Self::leak(handler);
2265        unsafe { ((*self.api).on_player_move)(self.ctx(), ud, trampoline_player_move::<F>) }
2266    }
2267
2268    pub fn on_container_open<F>(&mut self, handler: F)
2269    where
2270        F: Fn(&ContainerOpenEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2271    {
2272        let ud = Self::leak(handler);
2273        unsafe { ((*self.api).on_container_open)(self.ctx(), ud, trampoline_container_open::<F>) }
2274    }
2275
2276    pub fn on_container_close<F>(&mut self, handler: F)
2277    where
2278        F: Fn(&ContainerCloseEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2279    {
2280        let ud = Self::leak(handler);
2281        unsafe { ((*self.api).on_container_close)(self.ctx(), ud, trampoline_container_close::<F>) }
2282    }
2283
2284    pub fn on_projectile_hit<F>(&mut self, handler: F)
2285    where
2286        F: Fn(&ProjectileHitEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2287    {
2288        let ud = Self::leak(handler);
2289        unsafe { ((*self.api).on_projectile_hit)(self.ctx(), ud, trampoline_projectile_hit::<F>) }
2290    }
2291
2292    pub fn on_tick<F>(&mut self, listener: F)
2293    where
2294        F: Fn(&dyn Server) + Send + Sync + 'static,
2295    {
2296        let ud = Self::leak(listener);
2297        unsafe { ((*self.api).on_server_tick)(self.ctx(), ud, trampoline_server_fn::<F>) }
2298    }
2299
2300    pub fn on_server_started<F>(&mut self, listener: F)
2301    where
2302        F: Fn(&dyn Server) + Send + Sync + 'static,
2303    {
2304        let ud = Self::leak(listener);
2305        unsafe { ((*self.api).on_server_started)(self.ctx(), ud, trampoline_server_fn::<F>) }
2306    }
2307
2308    pub fn on_server_stopping<F>(&mut self, listener: F)
2309    where
2310        F: Fn(&dyn Server) + Send + Sync + 'static,
2311    {
2312        let ud = Self::leak(listener);
2313        unsafe { ((*self.api).on_server_stopping)(self.ctx(), ud, trampoline_server_fn::<F>) }
2314    }
2315
2316    // ── commands ─────────────────────────────────────────────────────────────
2317
2318    pub fn on_command<F>(&mut self, name: impl AsRef<str>, handler: F)
2319    where
2320        F: Fn(&CommandContext, &dyn Server) -> Option<String> + Send + Sync + 'static,
2321    {
2322        let name_ys = YogStr::from_str(name.as_ref());
2323        let ud = Self::leak(handler);
2324        unsafe { ((*self.api).register_command)(self.ctx(), name_ys, ud, trampoline_command::<F>) }
2325    }
2326
2327    /// Register a command with Brigadier-typed arguments.
2328    ///
2329    /// `schema` is a space-separated list of argument types:
2330    /// `int`, `float`, `word`, `string` (greedy, must be last), `player`, `blockpos`.
2331    ///
2332    /// In the handler use `ctx.arg_int(0)`, `ctx.arg_blockpos(1)`, etc.
2333    pub fn on_typed_command<F>(
2334        &mut self,
2335        name: impl AsRef<str>,
2336        schema: impl AsRef<str>,
2337        handler: F,
2338    ) where
2339        F: Fn(&CommandContext, &dyn Server) -> Option<String> + Send + Sync + 'static,
2340    {
2341        let name_ys = YogStr::from_str(name.as_ref());
2342        let schema_ys = YogStr::from_str(schema.as_ref());
2343        let ud = Self::leak(handler);
2344        unsafe {
2345            ((*self.api).register_typed_command)(
2346                self.ctx(),
2347                name_ys,
2348                schema_ys,
2349                ud,
2350                trampoline_command::<F>,
2351            );
2352        }
2353    }
2354
2355    // ── networking ───────────────────────────────────────────────────────────
2356
2357    pub fn on_packet<F>(&mut self, channel: impl AsRef<str>, handler: F)
2358    where
2359        F: Fn(&PacketEvent, &dyn Server) + Send + Sync + 'static,
2360    {
2361        let ch = YogStr::from_str(channel.as_ref());
2362        let ud = Self::leak(handler);
2363        unsafe { ((*self.api).on_packet)(self.ctx(), ch, ud, trampoline_packet::<F>) }
2364    }
2365
2366    pub fn on_client_packet<F>(&mut self, channel: impl AsRef<str>, handler: F)
2367    where
2368        F: Fn(&PacketEvent, &dyn Server) + Send + Sync + 'static,
2369    {
2370        let ch = YogStr::from_str(channel.as_ref());
2371        let ud = Self::leak(handler);
2372        unsafe { ((*self.api).on_client_packet)(self.ctx(), ch, ud, trampoline_packet::<F>) }
2373    }
2374
2375    /// Register a typed-packet handler.
2376    ///
2377    /// The payload is decoded from raw bytes using `P`'s [`Packet`] impl.
2378    /// Malformed payloads are silently dropped.
2379    pub fn on_typed_packet<P, F>(&mut self, channel: impl AsRef<str>, handler: F)
2380    where
2381        P: Packet + Send + Sync + 'static,
2382        F: Fn(&P, &dyn Server) + Send + Sync + 'static,
2383    {
2384        self.on_packet(channel, move |ev, srv| {
2385            if let Some(pkt) = P::decode(&ev.payload) {
2386                handler(&pkt, srv);
2387            }
2388        });
2389    }
2390
2391    // ── content ──────────────────────────────────────────────────────────────
2392
2393    /// Hands the runtime content of `kind` named `id`: its definition as a
2394    /// Yog Data blob (`register_content`, one ABI call for every kind).
2395    fn content(&mut self, kind: &str, id: &str, def: &yog_data::Value) {
2396        let blob = yog_data::binary::encode(def);
2397        unsafe { ((*self.api).register_content)(self.ctx(), YogStr::from_str(kind), YogStr::from_str(id), blob.as_ptr(), blob.len()) }
2398    }
2399
2400    /// JSON text as Yog Data (recipes and books are written as JSON by their crates).
2401    fn json(text: &str) -> yog_data::Value {
2402        yog_data::json::from_json_text(text).unwrap_or_default()
2403    }
2404
2405    /// Register a recipe (Yog's format — see [`Recipe`]; the host writes
2406    /// its Minecraft version's JSON).
2407    pub fn add_recipe(&mut self, recipe: Recipe) {
2408        let (ns, name) = recipe.ns_name();
2409        let id = format!("{ns}:{name}");
2410        self.content("recipe", &id, &recipe.to_data());
2411    }
2412
2413    /// Register a recipe given as Yog's recipe JSON — how `yog build`
2414    /// registers the mod's own kinds (`{"type": "mymod:infusion", "slots":
2415    /// …}`), which stay the mod's data: for its machines and its books.
2416    pub fn add_recipe_json(&mut self, id: &str, json: &str) {
2417        let id = if id.contains(':') { id.to_string() } else { format!("minecraft:{id}") };
2418        self.content("recipe", &id, &Self::json(json));
2419    }
2420
2421    pub fn register_item(&mut self, def: ItemDef) {
2422        use yog_data::Schema;
2423        self.content("item", &def.id.clone(), &def.write());
2424    }
2425
2426    pub fn register_block(&mut self, def: BlockDef) {
2427        use yog_data::Schema;
2428        self.content("block", &def.id.clone(), &def.write());
2429    }
2430
2431    /// Registers an entity type (what a `.yentity` makes). With a `model`,
2432    /// the loader draws it — its body model with the clip of its state
2433    /// (`clips`: `idle`, `walk`, or entity data `yog:state`).
2434    pub fn register_entity(&mut self, def: yog_registry::EntityDef) {
2435        use yog_data::Schema;
2436        if crate::entities::drawn(&def) {
2437            self.on_body(crate::entities::draw);
2438        }
2439        self.content("entity", &def.id.clone(), &def.write());
2440    }
2441
2442    /// A compiled `.yentity` (the generated code calls this).
2443    pub fn register_entity_data(&mut self, id: &str, data: &[u8]) {
2444        match yog_data::read_bytes::<yog_registry::EntityDef>(data) {
2445            Ok(def) => self.register_entity(def),
2446            Err(e) => crate::error!("entity {id}: {e:?}"),
2447        }
2448    }
2449
2450    /// Calls `handler` each tick of every entity of `entity_type` (a mod's
2451    /// type with `ticks`), with its uuid — server side.
2452    pub fn on_entity_tick<F>(&mut self, entity_type: &str, handler: F)
2453    where
2454        F: Fn(&dyn Server, &str) + Send + Sync + 'static,
2455    {
2456        let ud = Self::leak(handler);
2457        unsafe { ((*self.api).on_entity_tick)(self.ctx(), YogStr::from_str(entity_type), ud, trampoline_entity_tick::<F>) }
2458    }
2459
2460    /// Add placed feature `feature` (the mod's datapack's, like an ore's
2461    /// `mymod:mythril_ore`) to the biomes of tag `biomes` at generation
2462    /// `step` (`underground_ores`). An ore `.ydef` does this for you.
2463    pub fn add_biome_feature(&mut self, feature: &str, biomes: &str, step: &str) {
2464        use yog_data::Schema;
2465        let f = yog_registry::BiomeFeature { feature: feature.into(), biomes: biomes.into(), step: step.into() };
2466        self.content("biome_feature", feature, &f.write());
2467    }
2468
2469    /// Register a tool material — what tool items naming it
2470    /// (`ItemDef::tool`) are made of. The game's are built in.
2471    pub fn register_tool_material(&mut self, material: ToolMaterial) {
2472        use yog_data::Schema;
2473        self.content("tool_material", &material.id.clone(), &material.write());
2474    }
2475
2476    /// Register an armor material — what armor items naming it
2477    /// (`ItemDef::armor`) are made of. The game's are built in.
2478    pub fn register_armor_material(&mut self, material: ArmorMaterial) {
2479        use yog_data::Schema;
2480        self.content("armor_material", &material.id.clone(), &material.write());
2481    }
2482
2483    /// Register a sound group — what blocks naming it (`BlockDef::sound`)
2484    /// sound like. The game's groups are built in.
2485    pub fn register_sound_group(&mut self, group: SoundGroup) {
2486        use yog_data::Schema;
2487        self.content("sound_group", &group.id.clone(), &group.write());
2488    }
2489
2490    /// Register a real Container/Menu inventory screen — see
2491    /// `yog_inventory::InventoryDef`. Attach it to a block via
2492    /// `BlockDef::inventory(id)`.
2493    pub fn register_inventory(&mut self, def: yog_inventory::InventoryDef) {
2494        use yog_data::Schema;
2495        self.content("inventory", &def.id.clone(), &def.write());
2496    }
2497
2498    // ── startup grants ───────────────────────────────────────────────────────
2499
2500    /// Register a startup grant: items/books to give once when a player first joins.
2501    pub fn register_startup_grant(&mut self, grant: StartupGrant) {
2502        use yog_data::Schema;
2503        self.content("startup_grant", &grant.id.clone(), &grant.write());
2504    }
2505
2506    /// Register a book.
2507    pub fn register_book(&mut self, book: &Book) {
2508        use yog_data::Schema;
2509        self.content("book", &book.id, &book.write());
2510    }
2511
2512    /// Register a book given as Yog Data, binary — what `yog build` makes
2513    /// of a `content/**/*.ybook`; the bytes go to the runtime as they are.
2514    pub fn register_book_data(&mut self, id: &str, data: &[u8]) {
2515        unsafe { ((*self.api).register_content)(self.ctx(), YogStr::from_str("book"), YogStr::from_str(id), data.as_ptr(), data.len()) }
2516    }
2517
2518    /// Register (or patch) a dimension's *type* (sky, lighting, physics, ...).
2519    ///
2520    /// `def.id` need not be a new custom id — pass a vanilla id
2521    /// (`"minecraft:overworld"`, `"minecraft:the_nether"`,
2522    /// `"minecraft:the_end"`) to patch that dimension's type/generator
2523    /// instead of creating a new one (e.g. to replace the overworld's
2524    /// terrain with your own generator type).
2525    ///
2526    /// Must be called from `register()` — the same mod-init window as
2527    /// blocks/items — so the host can declare/patch the dimension before
2528    /// Minecraft's registries freeze. See the `yog-dimensions` crate docs;
2529    /// set `def.generator_type` (via [`YogDimensionDef::generator_type`]) to
2530    /// pick a generator type registered with
2531    /// [`Registry::register_chunk_generator`].
2532    pub fn register_dimension(&mut self, def: &YogDimensionDef) {
2533        let value = Self::json(&def.to_json());
2534        self.content("dimension", &def.id.clone(), &value);
2535    }
2536
2537    /// Register a dimension given as Yog Data, binary — what `yog build`
2538    /// makes of a `.ydef` of kind `dimension` (its `terrain` generated by
2539    /// the runtime itself); the bytes go to the runtime as they are.
2540    pub fn register_dimension_data(&mut self, id: &str, data: &[u8]) {
2541        unsafe { ((*self.api).register_content)(self.ctx(), YogStr::from_str("dimension"), YogStr::from_str(id), data.as_ptr(), data.len()) }
2542    }
2543
2544    /// Register a named, reusable chunk-generator type under
2545    /// `generator_type_id` (e.g. `"mymod:custom_terrain"`) — analogous to
2546    /// how Biomes O'Plenty registers selectable world-type presets. Any
2547    /// dimension (custom or vanilla) can opt into this generator via
2548    /// [`YogDimensionDef::generator_type`]; the platform host may also list
2549    /// registered generator type ids as options on the world-creation screen.
2550    ///
2551    /// `generator` is called once per chunk column that needs generating in
2552    /// any dimension using this type — write whatever terrain logic you want
2553    /// using the [`ChunkWriter`] handle (combine as many noise layers as you
2554    /// like; this crate doesn't prescribe a generation style).
2555    pub fn register_chunk_generator<F>(&mut self, generator_type_id: &str, generator: F)
2556    where
2557        F: Fn(&ChunkWriter) + Send + Sync + 'static,
2558    {
2559        let ud = Self::leak(generator);
2560        let id = YogStr::from_str(generator_type_id);
2561        unsafe {
2562            ((*self.api).register_chunk_generator)(
2563                self.ctx(),
2564                id,
2565                ud,
2566                trampoline_chunk_generator::<F>,
2567            );
2568        }
2569    }
2570
2571    /// Register a menu entry — the host renders a button on vanilla screens
2572    /// (TitleScreen on Fabric, ModListScreen on Forge/NeoForge) that opens `ui_id`.
2573    /// `label` is the human-readable button text (e.g. "Yog Mods").
2574    /// `ui_id` is the UI to open when clicked (e.g. "example:menu").
2575    /// See [`installed_mods`]. During `register()` the list only contains
2576    /// mods loaded before this one.
2577    pub fn installed_mods(&self) -> Vec<ModInfo> {
2578        installed_mods()
2579    }
2580
2581    /// Access the inter-mod communication layer.
2582    ///
2583    /// Allows exporting function pointers from this mod and importing
2584    /// function pointers from other mods.
2585    pub fn interop(&self) -> crate::Interop {
2586        crate::Interop::new(self.api)
2587    }
2588
2589    /// Raw `YogApi` pointer — for passing to interop-imported functions
2590    /// that register content through the C ABI table directly.
2591    pub fn raw_api(&self) -> *const yog_abi::YogApi {
2592        self.api
2593    }
2594
2595    pub fn register_menu_entry(&mut self, label: &str, ui_id: &str) {
2596        let l = YogStr::from_str(label);
2597        let u = YogStr::from_str(ui_id);
2598        unsafe { ((*self.api).register_menu_entry)(self.ctx(), l, u) }
2599    }
2600
2601    /// Register a UI tree with an event callback.
2602    /// `ui_id` is the unique identifier (e.g. "mymod:menu").
2603    /// `handler` receives `(ui_id, event)` for the screen's input: `click:X:Y`,
2604    /// `drag:X:Y`, `release:X:Y`, `scroll:DY`, `key:KEY:MODS` (GLFW key code
2605    /// and modifier bits, on press and repeat) and `char:CODEPOINT` (a typed
2606    /// character). It returns `()` or a `bool`: `true` marks a `key:`/`char:`
2607    /// event as used, so the host skips its default handling of the key
2608    /// (Esc closing the screen, ...) — see [`UiHandled`].
2609    pub fn register_ui<F, R>(&mut self, ui_id: &str, handler: F)
2610    where
2611        F: Fn(&str, &str) -> R + Send + Sync + 'static,
2612        R: UiHandled,
2613    {
2614        let ud = Self::leak(handler);
2615        let id = YogStr::from_str(ui_id);
2616        let empty = YogStr::from_str("{}");
2617        unsafe { ((*self.api).register_ui)(self.ctx(), id, empty, ud, trampoline_ui_event::<F, R>) }
2618    }
2619
2620    // ── scheduler ────────────────────────────────────────────────────────────
2621
2622    pub fn schedule_once<F>(&self, delay_ticks: u64, handler: F)
2623    where
2624        F: Fn(&dyn Server) + Send + Sync + 'static,
2625    {
2626        let ud = Self::leak(handler);
2627        unsafe {
2628            ((*self.api).schedule_once)(self.ctx(), delay_ticks, ud, trampoline_scheduled::<F>);
2629        }
2630    }
2631
2632    pub fn schedule_repeating<F>(&self, period_ticks: u64, handler: F)
2633    where
2634        F: Fn(&dyn Server) + Send + Sync + 'static,
2635    {
2636        let ud = Self::leak(handler);
2637        unsafe {
2638            ((*self.api).schedule_repeating)(
2639                self.ctx(),
2640                period_ticks,
2641                ud,
2642                trampoline_scheduled::<F>,
2643            );
2644        }
2645    }
2646
2647    // ── client-side hooks (ABI minor 10) ─────────────────────────────────────
2648
2649    /// Register a handler called every client tick (render thread, no server).
2650    pub fn on_client_tick<F>(&mut self, handler: F)
2651    where
2652        F: Fn(&ClientTickEvent) + Send + Sync + 'static,
2653    {
2654        let ud = Self::leak(handler);
2655        unsafe { ((*self.api).on_client_tick)(self.ctx(), ud, trampoline_client_tick::<F>) }
2656    }
2657
2658    /// Register a render callback for a specific UI screen (`ui_id`).
2659    ///
2660    /// Called from `YogUIScreen.render()` — i.e. AFTER `renderBackground()` darkens
2661    /// the screen — so your UI draws on top of the dimmed world view.
2662    /// Use this instead of `on_hud_render` for book/inventory screens.
2663    ///
2664    /// Clicks are forwarded as `"click:X:Y"` via the `register_ui` handler so you
2665    /// can do hit-testing on your own stored layout.
2666    pub fn on_ui_render<F>(&mut self, ui_id: &str, handler: F)
2667    where
2668        F: Fn(&GfxContext) + Send + Sync + 'static,
2669    {
2670        let ud = Self::leak(handler);
2671        let id = YogStr::from_str(ui_id);
2672        unsafe { ((*self.api).on_ui_render)(self.ctx(), id, ud, trampoline_hud_render::<F>) }
2673    }
2674
2675    /// Draw the pictures of book pages of type `drawn` whose `drawer` is
2676    /// `drawer` (`"mymod:diagram"`): `handler` gets the page's `data` and
2677    /// the picture's box `[x, y, w, h]` in screen pixels, every frame the
2678    /// page is open.
2679    ///
2680    /// ```text
2681    /// { type: "drawn", drawer: "mymod:diagram", title: "Wiring", height: 64,
2682    ///   caption: "{u|in} → {u|out}", text: "…", data: { nodes: 3 } }
2683    /// ```
2684    pub fn on_book_page<F>(&mut self, drawer: &str, handler: F)
2685    where
2686        F: Fn(&GfxContext, &yog_data::Value, [f32; 4]) + Send + Sync + 'static,
2687    {
2688        let ud = Self::leak(handler);
2689        let id = YogStr::from_str(drawer);
2690        unsafe { ((*self.api).on_book_page)(self.ctx(), id, ud, trampoline_book_page::<F>) }
2691    }
2692
2693    /// A picture under the tooltips of `item` (as Hex Casting's scrolls show
2694    /// their pattern): `size(item, snbt)` says whether a stack — its custom
2695    /// data as SNBT — gets one and its size in GUI pixels; `draw` draws it
2696    /// in the box `[x, y, w, h]` (screen pixels) while the tooltip shows.
2697    pub fn on_item_tooltip<S, D>(&mut self, item: &str, size: S, draw: D)
2698    where
2699        S: Fn(&str, &str) -> Option<(f32, f32)> + Send + Sync + 'static,
2700        D: Fn(&GfxContext, &str, &str, [f32; 4]) + Send + Sync + 'static,
2701    {
2702        let ud = Self::leak(TooltipPicture { size, draw });
2703        let id = YogStr::from_str(item);
2704        unsafe {
2705            ((*self.api).on_item_tooltip)(self.ctx(), id, ud, trampoline_tooltip_size::<S, D>, trampoline_tooltip_draw::<S, D>)
2706        }
2707    }
2708
2709    /// A stack's own name and tooltip, from its custom data (SNBT): `text(item,
2710    /// snbt)` gives `Some((name, lines))` — `name` `None` keeps the item's;
2711    /// `lines` stand instead of the item's description — or `None` for the
2712    /// item's own. A written blueprint names its design:
2713    ///
2714    /// ```ignore
2715    /// registry.on_item_text(Items::BLUEPRINT, |_, snbt| {
2716    ///     let bp = Blueprint::from_nbt(snbt)?;
2717    ///     Some((Some(bp.name.clone()), vec![format!("{} ports", bp.ports)]))
2718    /// });
2719    /// ```
2720    pub fn on_item_text<F>(&mut self, item: &str, text: F)
2721    where
2722        F: Fn(&str, &str) -> Option<(Option<String>, Vec<String>)> + Send + Sync + 'static,
2723    {
2724        let ud = Self::leak(text);
2725        let id = YogStr::from_str(item);
2726        unsafe { ((*self.api).on_item_text)(self.ctx(), id, ud, trampoline_item_text::<F>) }
2727    }
2728
2729    /// A compiled `.ymodel` (the generated code calls this): found later by
2730    /// [`crate::body::model`].
2731    pub fn register_body_model(&mut self, id: &str, data: &[u8]) {
2732        if let Err(e) = yog_body::register_model(id, data) {
2733            crate::error!("{e}");
2734        }
2735    }
2736
2737    /// A compiled `.yanim` (the generated code calls this): its clips found
2738    /// later by [`crate::body::clip`].
2739    pub fn register_body_anims(&mut self, id: &str, data: &[u8]) {
2740        if let Err(e) = yog_body::register_anims(id, data) {
2741            crate::error!("{e}");
2742        }
2743    }
2744
2745    /// Register a handler asked each frame about the body of every tracked
2746    /// entity ([`crate::body::track`]): it answers with [`crate::body::Ops`]
2747    /// — pose vanilla parts, turn the body, draw meshes (rigs, morphs),
2748    /// disguise, hide, capture. Every mod's ops add up.
2749    pub fn on_body<F>(&mut self, handler: F)
2750    where
2751        F: Fn(&yog_body::Frame, &mut yog_body::Ops) + Send + Sync + 'static,
2752    {
2753        let ud = Self::leak(handler);
2754        unsafe { ((*self.api).on_body)(self.ctx(), ud, trampoline_body::<F>) }
2755    }
2756
2757    /// Register a handler that sees every loot table rolled — a chest's, a
2758    /// block's drops, a mob's — and may change what it gives
2759    /// ([`crate::loot::Loot::items`]); each handler sees the one before's
2760    /// result. Server side. For adding and scaling items on some tables, a
2761    /// [`crate::loot::LootModifier`] says it as data.
2762    pub fn on_loot<F>(&mut self, handler: F)
2763    where
2764        F: Fn(&dyn Server, &mut crate::loot::Loot) + Send + Sync + 'static,
2765    {
2766        let ud = Self::leak(handler);
2767        unsafe { ((*self.api).on_loot)(self.ctx(), ud, trampoline_loot::<F>) }
2768    }
2769
2770    /// Change the loot of some tables as `modifier` says.
2771    pub fn add_loot_modifier(&mut self, modifier: crate::loot::LootModifier) {
2772        self.on_loot(move |srv, loot| crate::loot::apply(srv, &modifier, loot));
2773    }
2774
2775    /// A compiled `.ydef` loot modifier (the generated code calls this).
2776    pub fn add_loot_modifier_data(&mut self, id: &str, data: &[u8]) {
2777        match yog_data::read_bytes::<crate::loot::LootModifier>(data) {
2778            Ok(m) => self.add_loot_modifier(m),
2779            Err(e) => crate::error!("loot modifier {id}: {e:?}"),
2780        }
2781    }
2782
2783    /// Register loot function `name` (`mymod:pattern_scroll`): what loot
2784    /// modifiers naming it (`function`) run on each stack they add — set
2785    /// its custom data, say.
2786    pub fn loot_function<F>(&mut self, name: &str, function: F)
2787    where
2788        F: Fn(&dyn Server, &mut crate::loot::LootStack, &crate::loot::Loot) + Send + Sync + 'static,
2789    {
2790        if let Ok(mut f) = crate::loot::functions().write() {
2791            f.insert(name.to_string(), std::sync::Arc::new(function));
2792        }
2793    }
2794
2795    /// Register a handler that moves, turns or zooms the camera each frame;
2796    /// it changes the [`crate::body::CameraOut`] the handlers before it made.
2797    pub fn on_camera<F>(&mut self, handler: F)
2798    where
2799        F: Fn(&yog_body::CameraFrame, &mut yog_body::CameraOut) + Send + Sync + 'static,
2800    {
2801        let ud = Self::leak(handler);
2802        unsafe { ((*self.api).on_camera)(self.ctx(), ud, trampoline_camera::<F>) }
2803    }
2804
2805    /// Register a handler that may replace the local player's travel step:
2806    /// `Some(velocity)` (blocks per tick, drag applied) moves the player by
2807    /// it instead of vanilla's walking, swimming, falling or gliding.
2808    pub fn on_travel<F>(&mut self, handler: F)
2809    where
2810        F: Fn(&yog_body::TravelFrame) -> Option<yog_body::Vec3> + Send + Sync + 'static,
2811    {
2812        let ud = Self::leak(handler);
2813        unsafe { ((*self.api).on_travel)(self.ctx(), ud, trampoline_travel::<F>) }
2814    }
2815
2816    /// Register a handler called every frame when the HUD is rendered.
2817    ///
2818    /// `gfx` provides full GPU pipeline access plus 2D convenience draw calls.
2819    /// `view_proj` and `camera_pos` are zero in HUD context; use `gfx.draw2d()` for HUD elements.
2820    pub fn on_hud_render<F>(&mut self, handler: F)
2821    where
2822        F: Fn(&GfxContext) + Send + Sync + 'static,
2823    {
2824        let ud = Self::leak(handler);
2825        unsafe { ((*self.api).on_hud_render)(self.ctx(), ud, trampoline_hud_render::<F>) }
2826    }
2827
2828    /// Register a handler called every frame at the end of world rendering.
2829    ///
2830    /// `gfx.view_proj()` is the combined projection × view matrix (camera-relative).
2831    /// `gfx.camera_pos()` is the camera world position.
2832    /// To render at world position P, translate by `P - camera_pos` before drawing.
2833    pub fn on_world_render<F>(&mut self, handler: F)
2834    where
2835        F: Fn(&GfxContext) + Send + Sync + 'static,
2836    {
2837        let ud = Self::leak(handler);
2838        unsafe { ((*self.api).on_world_render)(self.ctx(), ud, trampoline_world_render::<F>) }
2839    }
2840
2841    /// Register a handler for keyboard input (client-side).
2842    /// Return `false` to prevent Minecraft from processing the key.
2843    pub fn on_key_press<F>(&mut self, handler: F)
2844    where
2845        F: Fn(&KeyPressEvent) -> bool + Send + Sync + 'static,
2846    {
2847        let ud = Self::leak(handler);
2848        unsafe { ((*self.api).on_key_press)(self.ctx(), ud, trampoline_key_press::<F>) }
2849    }
2850
2851    /// Register a handler called when a GUI screen is opened.
2852    pub fn on_screen_open<F>(&mut self, handler: F)
2853    where
2854        F: Fn(&ScreenEvent) + Send + Sync + 'static,
2855    {
2856        let ud = Self::leak(handler);
2857        unsafe { ((*self.api).on_screen_open)(self.ctx(), ud, trampoline_screen::<F>) }
2858    }
2859
2860    /// Register a handler called when a GUI screen is closed.
2861    pub fn on_screen_close<F>(&mut self, handler: F)
2862    where
2863        F: Fn(&ScreenEvent) + Send + Sync + 'static,
2864    {
2865        let ud = Self::leak(handler);
2866        unsafe { ((*self.api).on_screen_close)(self.ctx(), ud, trampoline_screen::<F>) }
2867    }
2868}
2869
2870unsafe extern "C" fn trampoline_ui_event<F, R>(
2871    ud: *mut c_void,
2872    ui_id: yog_abi::YogStr,
2873    event_id: yog_abi::YogStr,
2874) where
2875    F: Fn(&str, &str) -> R + Send + Sync + 'static,
2876    R: UiHandled,
2877{
2878    let f = unsafe { &*(ud as *const F) };
2879    let ui = unsafe { ui_id.as_str() };
2880    let ev = unsafe { event_id.as_str() };
2881    if guard(false, || f(ui, ev).handled()) {
2882        let api = GLOBAL_API.load(std::sync::atomic::Ordering::Acquire);
2883        if !api.is_null() {
2884            unsafe { ((*api).ui_consume_event)((*api).ctx) }
2885        }
2886    }
2887}
2888
2889unsafe extern "C" fn trampoline_chunk_generator<F>(
2890    ud: *mut c_void,
2891    writer: *const yog_abi::YogChunkWriterApi,
2892) where
2893    F: Fn(&ChunkWriter) + Send + Sync + 'static,
2894{
2895    let f = unsafe { &*(ud as *const F) };
2896    let writer = unsafe { ChunkWriter::from_raw(writer) };
2897    guard((), || f(&writer));
2898}
2899
2900// ── Mod trait ─────────────────────────────────────────────────────────────────
2901
2902/// Implemented by every Yog mod. Called once at startup to register handlers.
2903pub trait Mod {
2904    fn register(registry: &mut Registry);
2905}
2906
2907#[cfg(test)]
2908mod trampoline_tests {
2909    use super::*;
2910    use yog_abi::{YogBlockPos, YogChatEvent, YogCommandEvent, YogPacketEvent};
2911
2912    fn ud<F>(f: &F) -> *mut c_void {
2913        f as *const F as *mut c_void
2914    }
2915
2916    fn chat<F: Fn(&ChatEvent, EventPhase, &dyn Server) -> bool + Send + Sync>(f: &F, ev: &YogChatEvent, phase: u8) -> bool {
2917        unsafe { trampoline_chat::<F>(ud(f), std::ptr::null(), ev, phase) }
2918    }
2919
2920    fn block_break<F: Fn(&BlockBreakEvent, EventPhase, &dyn Server) -> bool + Send + Sync>(f: &F, ev: &YogBlockBreakEvent) -> bool {
2921        unsafe { trampoline_block_break::<F>(ud(f), std::ptr::null(), ev, 0) }
2922    }
2923
2924    fn command<F: Fn(&CommandContext, &dyn Server) -> Option<String> + Send + Sync>(f: &F, ev: &YogCommandEvent, buf: &mut [u8]) -> u32 {
2925        let mut len = 99u32;
2926        unsafe { trampoline_command::<F>(ud(f), std::ptr::null(), ev, buf.as_mut_ptr(), buf.len() as u32, &mut len) };
2927        len
2928    }
2929
2930    fn packet<F: Fn(&PacketEvent, &dyn Server) + Send + Sync>(f: &F, ev: &YogPacketEvent) {
2931        unsafe { trampoline_packet::<F>(ud(f), std::ptr::null(), ev) }
2932    }
2933
2934    #[test]
2935    fn events_arrive_converted_with_their_phase() {
2936        let seen = std::sync::Mutex::new(Vec::new());
2937        let handler = |ev: &ChatEvent, p: EventPhase, _: &dyn Server| {
2938            seen.lock().unwrap().push((ev.player_name.clone(), ev.message.clone(), p));
2939            ev.message != "cancel me"
2940        };
2941        let ev = |msg: &'static str| YogChatEvent {
2942            player: YogStr::from_str("Dev"),
2943            message: YogStr::from_str(msg),
2944            dimension: YogStr::from_str("minecraft:overworld"),
2945        };
2946        assert!(chat(&handler, &ev("hi"), 0));
2947        assert!(!chat(&handler, &ev("cancel me"), 0));
2948        chat(&handler, &ev("after"), 1);
2949        let seen = seen.into_inner().unwrap();
2950        assert_eq!(seen[0], ("Dev".into(), "hi".into(), EventPhase::Pre));
2951        assert_eq!(seen[2].2, EventPhase::Post);
2952    }
2953
2954    #[test]
2955    fn a_panicking_handler_allows_the_action() {
2956        let handler = |_: &BlockBreakEvent, _: EventPhase, _: &dyn Server| -> bool { panic!("mod bug") };
2957        let ev = YogBlockBreakEvent {
2958            player: YogStr::from_str("Dev"),
2959            block: YogStr::from_str("minecraft:stone"),
2960            pos: YogBlockPos { x: 1, y: 2, z: 3 },
2961            dimension: YogStr::from_str("minecraft:overworld"),
2962        };
2963        assert!(block_break(&handler, &ev));
2964    }
2965
2966    #[test]
2967    fn command_replies_fit_the_buffer_whole_characters_only() {
2968        let handler = |c: &CommandContext, _: &dyn Server| Some(format!("{}: привет", c.args));
2969        let ev = YogCommandEvent {
2970            name: YogStr::from_str("hex"),
2971            args: YogStr::from_str("x"),
2972            source: YogStr::from_str("Dev"),
2973            uuid: YogStr::EMPTY,
2974            dimension: YogStr::EMPTY,
2975        };
2976        let mut buf = [0u8; 6];
2977        let len = command(&handler, &ev, &mut buf);
2978        // "x: п" is 5 bytes; "пр" wouldn't fit whole in 6.
2979        assert_eq!(std::str::from_utf8(&buf[..len as usize]), Ok("x: п"));
2980    }
2981
2982    #[test]
2983    fn empty_packets_need_no_payload_pointer() {
2984        let got = std::sync::Mutex::new(None);
2985        let handler = |p: &PacketEvent, _: &dyn Server| *got.lock().unwrap() = Some(p.payload.len());
2986        let ev = YogPacketEvent {
2987            channel: YogStr::from_str("mymod:ping"),
2988            player: YogStr::from_str("Dev"),
2989            payload: std::ptr::null(),
2990            payload_len: 0,
2991        };
2992        packet(&handler, &ev);
2993        assert_eq!(*got.lock().unwrap(), Some(0));
2994    }
2995}