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