Skip to main content

yog_api/
lib.rs

1//! Yog API — the single crate mod authors depend on.
2//!
3//! A facade that re-exports every Yog domain plus the central [`Registry`] hub.
4//! Add a new domain crate, re-export it here, and mods pick it up via
5//! `yog_api::*`. Items are available both flat (`yog_api::Registry`) and
6//! namespaced by domain (`yog_api::world::World`).
7
8pub mod advancements;
9pub mod body;
10mod bus;
11pub mod client;
12mod draw;
13pub mod entities;
14pub mod java;
15pub mod loot;
16pub mod vanilla;
17pub use bus::{EventCx, Flow, IntoFlow, emit};
18pub use service::call;
19mod interop;
20mod lang;
21mod registry;
22mod scheduler;
23mod service;
24
25#[doc(hidden)]
26pub use interop::{__yog_export_registry, __yog_serve, YogExportEntry};
27pub use interop::{call_export, export_address};
28pub use lang::{format_translation, tag_name, tr, tr_args, translation};
29pub use registry::{Mod, ModInfo, Registry, UiHandled, close_ui, installed_mods, open_ui};
30pub use yog_gfx::{
31    GfxContext, core as gfx_core, draw2d as gfx_draw2d, gl as gfx_gl, image as gfx_image,
32};
33
34/// Stable C ABI — re-exported so mods don't need a direct `yog-abi` dependency.
35pub use yog_abi::{ABI_VERSION, YogApi};
36#[doc(hidden)]
37pub use yog_abi::{YogBytes, YogReply, YogStatus};
38
39/// Yog Data — what content definitions and book pages' `data`
40/// (`Registry::on_book_page`) are; re-exported for mods.
41pub use yog_data;
42/// `#[derive(Schema)]`: a type read and written as Yog Data (stores, packets, frames).
43pub use yog_data::Schema;
44/// The names Yog shares — kinds, namespaces, lang keys — for a mod to use as the loader does.
45pub use yog_ids;
46/// The sync primitives Yog code uses (locks that outlive a panic) — a mod's too.
47pub use yog_sync as sync;
48
49pub use java::mod_loaded;
50
51/// Inter-mod communication proc-macros.
52pub use yog_interop::{bench, import, yog_export};
53
54/// Re-exported so `#[yog_export]`-generated code can emit `#[::yog_api::ctor::ctor(unsafe)]`
55/// without mods needing a direct `ctor` dependency. Constructors run when the
56/// mod's `cdylib` is loaded — guaranteed to complete before the runtime calls
57/// `yog_mod_register`, so the export registry is fully populated by then.
58pub use ctor;
59
60#[doc(hidden)]
61pub use std::os::raw::c_void as __c_void;
62#[doc(hidden)]
63pub use yog_abi::{YogGfxApi as __YogGfxApi, YogStr as __YogStr};
64
65/// Export a [`Mod`] as a dynamically loadable Yog mod.
66///
67/// Generates the two C-ABI entry points the runtime looks up:
68/// - `yog_abi_version() -> u32`  — version check before loading
69/// - `yog_mod_register(*const YogApi, *const c_char)` — registration entry point,
70///   receives the mod's `id` from its manifest
71///
72/// Put this once at the crate root of a `cdylib` mod:
73///
74/// ```ignore
75/// yog_api::export_mod!(MyMod);
76/// ```
77#[macro_export]
78macro_rules! export_mod {
79    ($mod_ty:ty) => {
80        #[unsafe(no_mangle)]
81        pub extern "C" fn yog_abi_version() -> u32 {
82            $crate::ABI_VERSION
83        }
84
85        #[unsafe(no_mangle)]
86        pub unsafe extern "C" fn yog_mod_register(
87            api: *const $crate::YogApi,
88            mod_id_ptr: *const ::std::os::raw::c_char,
89        ) {
90            // Parse mod_id from the C string passed by the runtime.
91            let mod_id: &str = if mod_id_ptr.is_null() {
92                "unknown"
93            } else {
94                // SAFETY: a non-null id is a NUL-terminated string from the runtime.
95                match unsafe { ::std::ffi::CStr::from_ptr(mod_id_ptr) }.to_str() {
96                    Ok(s) => s,
97                    Err(_) => "unknown",
98                }
99            };
100            // Store for interop use (yog_api::interop::current_mod_id()).
101            $crate::__set_current_mod_id(mod_id);
102            // Every mod is handed the same global `YogApi` table, so any
103            // mod's own pointer works for reconstructing a `Registry` inside
104            // an exported function later — even when called from a thread
105            // that never ran `yog_mod_register` itself.
106            $crate::__set_current_api_ptr(api as usize);
107
108            // Catch panics so they never unwind across this `extern "C"` boundary
109            // back into the runtime (which would be undefined behaviour).
110            let outcome = ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| {
111                // SAFETY: the runtime passes a valid YogApi pointer, verified via
112                // yog_abi_version() and abi_version/size checks before this call.
113                let mut registry = unsafe { $crate::Registry::from_raw(api) };
114                // The world's folder known before the mod's own handlers run.
115                $crate::storage::__know_world(&mut registry);
116                <$mod_ty as $crate::Mod>::register(&mut registry);
117
118                // Blocks and items of `content/**/*.yblock|*.yitem`
119                // (`yog_api::content!()`, self-registered by `ctor`).
120                let content: ::std::vec::Vec<fn(&mut $crate::Registry)> =
121                    $crate::__yog_content_registrars().lock().clone();
122                for register in content {
123                    register(&mut registry);
124                }
125
126                // Every #[yog_export] function (registered by its `ctor`
127                // when the library loaded) provides `mod_id:name`.
128                for entry in $crate::__yog_export_registry().lock().iter() {
129                    registry.provide_export(mod_id, entry);
130                }
131
132                // What it keeps, saved with the world (after the mod's own handlers).
133                $crate::storage::__save_with_world(&mut registry);
134            }));
135            if outcome.is_err() {
136                $crate::error!(
137                    "mod {} panicked during register",
138                    ::core::stringify!($mod_ty)
139                );
140            }
141        }
142
143        /// Yog-IDLE's screen designer: the version of the protocol below.
144        #[unsafe(no_mangle)]
145        pub extern "C" fn yog_ui_designer_abi() -> u32 {
146            $crate::ui::component::designer::ABI
147        }
148
149        /// Yog-IDLE's screen designer: lists this mod's custom components
150        /// and draws them (see `yog_ui::component::designer`). Never called
151        /// in game — only by the designer host, which loads the mod's
152        /// library built for the developer's machine.
153        #[unsafe(no_mangle)]
154        pub unsafe extern "C" fn yog_ui_designer(
155            request: $crate::YogBytes,
156            gfx: *const $crate::__YogGfxApi,
157            user_data: *mut $crate::__c_void,
158            write: $crate::ui::component::designer::WriteFn,
159        ) -> bool {
160            // SAFETY: forwarded under the same contract.
161            unsafe { $crate::ui::component::designer::call(request, gfx, user_data, write) }
162        }
163    };
164}
165
166/// Registers `.yui` components (types implementing
167/// [`ui::component::Component`]) when the mod's library loads, so screens
168/// can use `<Name …/>` and Yog-IDLE's designer host can draw them. The code
169/// `yog build` generates from a `<Component>` `.yui` calls this — mods
170/// don't write it themselves.
171#[macro_export]
172macro_rules! ui_component {
173    ($($ty:ty),+ $(,)?) => {
174        const _: () = {
175            #[$crate::ctor::ctor(unsafe, crate_path = $crate::ctor)]
176            fn __yog_register_ui_components() {
177                $( $crate::ui::component::register::<$ty>(); )+
178            }
179        };
180    };
181}
182
183/// Compiles in the mod's component `.yui` files that have no code-behind
184/// `.rs` (those with one are pulled in by its `ui_include!`) — call it once,
185/// in `src/lib.rs`:
186///
187/// ```ignore
188/// yog_api::ui_components!();
189/// ```
190///
191/// `yog build`, `yog check` and `yog ui gen` write the list to
192/// `.yog-build/generated/components.g.rs` (a module per component).
193#[macro_export]
194macro_rules! ui_components {
195    () => {
196        include!(concat!(
197            env!("CARGO_MANIFEST_DIR"),
198            "/generated/components.g.rs"
199        ));
200    };
201}
202
203/// Internal: set by `export_mod!` before calling `Mod::register`.
204/// Used by `yog_api::interop::current_mod_id()` so `Interop::export` knows
205/// which mod is calling.
206#[doc(hidden)]
207pub fn __set_current_mod_id(id: &str) {
208    CURRENT_MOD_ID.with(|cell| cell.replace(Some(id.to_string())));
209    let _ = MOD_ID.set(id.to_owned());
210}
211
212/// This mod's id (its manifest's), once the runtime has loaded it.
213pub fn mod_id() -> &'static str {
214    MOD_ID.get().map_or("", String::as_str)
215}
216
217/// This mod's id: each mod's library has its own copy of this crate.
218static MOD_ID: yog_sync::OnceLock<String> = yog_sync::OnceLock::new();
219
220/// Internal: the current mod's id, set during `yog_mod_register`.
221#[doc(hidden)]
222pub fn __current_mod_id() -> Option<String> {
223    CURRENT_MOD_ID.with(|cell| cell.borrow().clone())
224}
225
226/// Internal: the global `YogApi` pointer, set by every mod's `yog_mod_register`
227/// (it's the same singleton table for the whole process). Process-wide (not
228/// thread-local) because `#[yog_export]`-generated wrappers read it whenever
229/// an exported function is *called*, which may happen on any thread, long
230/// after the loading thread's `yog_mod_register` returned.
231#[doc(hidden)]
232pub fn __set_current_api_ptr(ptr: usize) {
233    API_PTR.store(ptr, yog_sync::atomic::Ordering::Release);
234}
235
236/// The `register` functions of `yog_api::content!()` — the content of
237/// `content/**` the build generates — run by `export_mod!` after
238/// `Mod::register`.
239#[doc(hidden)]
240pub fn __yog_content_registrars() -> &'static yog_sync::Mutex<Vec<fn(&mut Registry)>> {
241    static REG: yog_sync::Mutex<Vec<fn(&mut Registry)>> = yog_sync::Mutex::new(Vec::new());
242    &REG
243}
244
245#[doc(hidden)]
246pub fn __current_api_ptr() -> usize {
247    API_PTR.load(yog_sync::atomic::Ordering::Acquire)
248}
249
250static API_PTR: yog_sync::atomic::AtomicUsize = yog_sync::atomic::AtomicUsize::new(0);
251
252std::thread_local! {
253    static CURRENT_MOD_ID: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
254}
255
256pub use yog_book::BookRenderer;
257pub use yog_command::CommandContext;
258pub use yog_config::Config;
259pub use yog_core::{
260    BlockHit, BlockInfo, BlockPos, EntityInfo, Face, PlacedBlock, PlayerInfo, Point, Rotation,
261    ScreenSlot, SlotStack, Stack, entity_flags, split_state,
262};
263pub use yog_dimensions::{GeneratedChunk, YogDimensionDef, YogDimensionTypeDef};
264pub use yog_event::{Entity, Event, EventPhase, Message, Player, Service, World};
265/// A packet the server or the client received (`on_packet` / `on_client_packet`).
266pub use yog_event::{client::net::Packet as ClientPacketEvent, server::net::Packet as PacketEvent};
267pub use yog_formats::book::{Book, BookCategory, BookEntry, BookPage};
268pub use yog_inventory::{InventoryDef, SlotLayout};
269pub use yog_network::Packet;
270pub use yog_registry::{
271    ArmorDefense, ArmorMaterial, ArmorPiece, ArmorSlot, BlockDef, BlockProperty, Cooking,
272    EntityDef, EntityKind, Facing, FoodDef, ItemDef, Placement, Recipe, RecipeKind, SoundGroup,
273    StartupGrant, ToolItem, ToolMaterial,
274};
275pub use yog_ui::{
276    Align, Dock, FlexDir, FocusStyle, LayoutNode, Rect, Stretch, UiRoot, Units, widget,
277};
278
279/// Logging macros (`yog_api::info!`, `warn!`, `error!`).
280pub use yog_logging::{error, info, warn};
281
282/// Core types and handles.
283pub mod core {
284    pub use yog_core::*;
285}
286
287/// Events by plane — `event::player::session::Join`, `event::block::Break`, … —
288/// subscribed with `Registry::on` / `before` / `after`.
289pub mod event {
290    pub use yog_event::*;
291}
292
293/// The bus's domains: each one's actions as functions
294/// (`world::get_block(dim, pos)`, `entity::position(uuid)`,
295/// `player::give_item(name, item, count)`) beside its events.
296pub use yog_event::{
297    block, bossbar, chat, entity, game, item, net, particle, player, scoreboard, sound, tag, world,
298};
299
300/// Content registration (custom items / blocks / food).
301pub mod content {
302    pub use yog_registry::*;
303}
304
305/// Networking (raw-byte packets over channels).
306pub mod network {
307    pub use yog_network::*;
308}
309
310/// Commands.
311pub mod command {
312    pub use yog_command::*;
313}
314
315/// Custom dimensions — dimension-type definitions and runtime chunk generation.
316pub mod dimension {
317    pub use yog_dimensions::*;
318}
319
320/// Where the mod keeps its data (typed stores by scope, values kept with the world).
321pub mod storage;
322
323/// Mod configuration (typed key/value files).
324pub mod config {
325    pub use yog_config::*;
326}
327
328/// Guide books: the `.ybook` format and its renderer.
329pub mod book {
330    pub use yog_book::*;
331    pub use yog_formats::book::*;
332}
333
334/// UI framework — flexbox layout + widgets on top of yog-gfx.
335pub mod ui {
336    pub use yog_ui::*;
337}
338
339/// Pulls a `.yui` screen's generated code into the current module — the
340/// code-behind's half of `src/<name>.yui`:
341///
342/// ```ignore
343/// // src/mod_list.rs, next to src/mod_list.yui
344/// yog_api::ui_include!("mod_list");
345/// ```
346///
347/// `<name>` is the `.yui` file's path under `src/` without the extension
348/// (`"screens/options"` for `src/screens/options.yui`). `yog build`,
349/// `yog check` and `yog ui gen` write the code to
350/// `.yog-build/generated/<name>.g.rs` (the build crate's own directory,
351/// `CARGO_MANIFEST_DIR`), so it's never committed and never stale.
352#[macro_export]
353macro_rules! ui_include {
354    ($name:literal) => {
355        include!(concat!(
356            env!("CARGO_MANIFEST_DIR"),
357            "/generated/",
358            $name,
359            ".g.rs"
360        ));
361    };
362}
363
364/// Pulls the mod's `.yres` resources in as module `res` — one type per
365/// resource set, with an accessor per entry:
366///
367/// ```ignore
368/// // src/lib.rs
369/// yog_api::resources!();
370///
371/// use crate::res::{Icons, Strings};
372/// let title = Strings::screen_title();        // the text in the player's language
373/// let count = Strings::mods_count(58);        // "{count} mods" → "58 mods"
374/// let logo = Icons::logo();                   // an image source, "mymod:images/logo"
375/// ```
376///
377/// `yog build`, `yog check` and `yog res check` generate one
378/// `.yog-build/generated/resources/<Set>.g.rs` per `resources/**/<Set>.yres`
379/// plus `.yog-build/generated/resources.g.rs` including them all (see
380/// Yog-IDLE's `docs/yres.md`); never committed, never stale.
381#[macro_export]
382macro_rules! resources {
383    () => {
384        pub mod res {
385            include!(concat!(
386                env!("CARGO_MANIFEST_DIR"),
387                "/generated/resources.g.rs"
388            ));
389        }
390    };
391}
392
393/// Pulls the mod's blocks and items — `content/**/*.yblock` and `*.yitem`,
394/// made in Yog-IDLE's model editor — in as module `content`, and registers
395/// them (every file without `"register": "manual"`) right after
396/// `Mod::register`:
397///
398/// ```ignore
399/// // src/lib.rs — that's all it takes
400/// yog_api::content!();
401///
402/// // Ids and definitions, for code that needs them:
403/// use crate::content::{Blocks, Items};
404/// let id: &str = Blocks::RUBY_ORE;                 // "mymod:ruby_ore"
405/// registry.register_item(Items::ruby().max_stack(16)); // a "manual" one, tweaked
406/// ```
407///
408/// `yog build`, `yog check` and `yog content check` generate
409/// `.yog-build/generated/yog-content.g.rs` — never committed, never stale.
410/// The models, blockstates, loot tables, tags and lang entries go into the
411/// `.yog` as assets. See Yog-IDLE's `docs/blocks-items.md`.
412#[macro_export]
413macro_rules! content {
414    () => {
415        pub mod content {
416            include!(concat!(
417                env!("CARGO_MANIFEST_DIR"),
418                "/generated/yog-content.g.rs"
419            ));
420        }
421    };
422}
423
424/// Inventory framework — real Container/Menu screens (BlockEntity-backed),
425/// as opposed to `ui`'s HUD-drawn overlays. See `yog-inventory`'s DESIGN.md.
426pub mod inventory {
427    pub use yog_inventory::*;
428}