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