yog_gfx/lib.rs
1//! Yog graphics — low-level GPU pipeline access for mods.
2//!
3//! Provides ergonomic wrappers around `YogGfxApi`, the stable C ABI table for
4//! GPU operations (VAO/VBO, GLSL shaders, textures, draw calls, render state).
5//!
6//! # Render contexts
7//!
8//! Mods receive a [`GfxContext`] in two places:
9//!
10//! - `on_hud_render(|ctx| { ... })` — called every frame after the HUD is drawn.
11//! `ctx.view_proj()` is zeroed; `ctx.draw2d()` works.
12//! - `on_world_render(|ctx| { ... })` — called after world geometry.
13//! `ctx.view_proj()` holds the camera view-projection matrix in camera-relative
14//! space; `ctx.camera_pos()` is the world-space camera position.
15//!
16//! # GPU resource lifetime
17//!
18//! GPU handles (`u32`) must be created and destroyed on the render thread.
19//! Store handles between frames; pass `ctx` on every render call.
20//!
21//! ```ignore
22//! use yog_gfx::{GfxContext, gl::{Buffer, ShaderProgram, VertexArray}};
23//!
24//! struct MyRenderer {
25//! vbo: Option<Buffer>,
26//! vao: Option<VertexArray>,
27//! prog: Option<ShaderProgram>,
28//! }
29//!
30//! impl MyRenderer {
31//! fn ensure_init(&mut self, ctx: &GfxContext) {
32//! if self.vbo.is_some() { return; }
33//! let vbo = ctx.create_buffer();
34//! vbo.upload(ctx, &MY_VERTICES, false);
35//! let prog = ctx.create_shader(VERT_SRC, FRAG_SRC).unwrap();
36//! let vao = ctx.create_vao();
37//! vao.attrib(ctx, &vbo, 0, 3, yog_gfx::core::DataType::F32, false, 24, 0);
38//! self.vbo = Some(vbo);
39//! self.vao = Some(vao);
40//! self.prog = Some(prog);
41//! }
42//!
43//! fn render(&mut self, ctx: &GfxContext) {
44//! self.ensure_init(ctx);
45//! let vao = self.vao.as_ref().unwrap();
46//! let prog = self.prog.as_ref().unwrap();
47//! prog.uniform_mat4(ctx, "uViewProj", &ctx.view_proj());
48//! ctx.draw_arrays(vao, prog, yog_gfx::core::DrawMode::Triangles, 0, 3);
49//! }
50//! }
51//! ```
52
53pub mod core;
54pub mod draw2d;
55pub mod gl;
56pub mod image;
57
58use yog_abi::YogGfxApi;
59
60/// Handle to the GPU and draw capabilities for a single render frame.
61///
62/// Valid only within an `on_hud_render` or `on_world_render` callback.
63/// Do **not** store across frames — store GPU resource handles (`u32`) instead.
64#[derive(Copy, Clone)]
65pub struct GfxContext(*const YogGfxApi);
66
67unsafe impl Send for GfxContext {}
68unsafe impl Sync for GfxContext {}
69
70/// See [`GfxContext::text_width_fn`]: `(text, font) -> width` in GUI pixels.
71pub type TextWidthFn = unsafe extern "C" fn(text: yog_abi::YogStr, font: yog_abi::YogStr) -> f32;
72
73/// See [`GfxContext::image_size_fn`]: `(source, *w, *h) -> resolved`.
74pub type ImageSizeFn =
75 unsafe extern "C" fn(source: yog_abi::YogStr, w: *mut f32, h: *mut f32) -> bool;
76
77impl GfxContext {
78 #[doc(hidden)]
79 pub unsafe fn from_raw(raw: *const YogGfxApi) -> Self {
80 Self(raw)
81 }
82
83 #[inline]
84 fn api(&self) -> &YogGfxApi {
85 unsafe { &*self.0 }
86 }
87
88 // ── Frame info ────────────────────────────────────────────────────────────
89
90 /// GUI pixel dimensions of the screen for this frame.
91 pub fn screen_size(&self) -> (i32, i32) {
92 let a = self.api();
93 (a.screen_w, a.screen_h)
94 }
95
96 /// Partial-tick interpolation factor (0.0–1.0).
97 pub fn delta_tick(&self) -> f32 {
98 self.api().delta_tick
99 }
100
101 /// View-projection matrix in camera-relative space (column-major, 16 × f32).
102 /// Zeros during `on_hud_render`; filled during `on_world_render`.
103 pub fn view_proj(&self) -> [f32; 16] {
104 self.api().view_proj
105 }
106
107 /// Camera world-space position. All zeros during `on_hud_render`.
108 pub fn camera_pos(&self) -> [f32; 3] {
109 self.api().camera_pos
110 }
111
112 /// Local player world-space position (eye height). All zeros during `on_hud_render`.
113 /// Use this to anchor geometry to the player; differs from `camera_pos` in third-person.
114 pub fn player_pos(&self) -> [f32; 3] {
115 self.api().player_pos
116 }
117
118 // ── GPU buffer ───────────────────────────────────────────────────────────
119
120 /// Allocate a new GPU buffer (VBO or EBO). Returns handle 0 on failure.
121 pub fn create_buffer(&self) -> gl::Buffer {
122 gl::Buffer {
123 handle: unsafe { (self.api().buf_create)() },
124 }
125 }
126
127 /// Delete a buffer allocated by `create_buffer`.
128 pub fn delete_buffer(&self, buf: gl::Buffer) {
129 unsafe { (self.api().buf_delete)(buf.handle) }
130 }
131
132 // ── Vertex array ─────────────────────────────────────────────────────────
133
134 /// Allocate a new vertex array object. Returns handle 0 on failure.
135 pub fn create_vao(&self) -> gl::VertexArray {
136 gl::VertexArray {
137 handle: unsafe { (self.api().vao_create)() },
138 }
139 }
140
141 /// Delete a vertex array allocated by `create_vao`.
142 pub fn delete_vao(&self, vao: gl::VertexArray) {
143 unsafe { (self.api().vao_delete)(vao.handle) }
144 }
145
146 // ── Shader program ────────────────────────────────────────────────────────
147
148 /// Compile and link a GLSL shader program.
149 /// Returns `Err(())` and logs on compile/link failure.
150 #[allow(clippy::result_unit_err)] // public API; the log carries the details
151 pub fn create_shader(&self, vert_src: &str, frag_src: &str) -> Result<gl::ShaderProgram, ()> {
152 use yog_abi::YogStr;
153 let mut handle = 0u32;
154 let ok = unsafe {
155 (self.api().prog_create)(
156 YogStr::from_str(vert_src),
157 YogStr::from_str(frag_src),
158 &mut handle,
159 )
160 };
161 if ok && handle != 0 {
162 Ok(gl::ShaderProgram { handle })
163 } else {
164 Err(())
165 }
166 }
167
168 /// Delete a shader program.
169 pub fn delete_shader(&self, prog: gl::ShaderProgram) {
170 unsafe { (self.api().prog_delete)(prog.handle) }
171 }
172
173 // ── Texture ───────────────────────────────────────────────────────────────
174
175 /// Upload RGBA8 pixel data as a new GPU texture.
176 /// `linear`: `true` = bilinear filter, `false` = nearest.
177 pub fn create_texture_rgba(&self, w: u32, h: u32, pixels: &[u8], linear: bool) -> gl::Texture {
178 gl::Texture {
179 handle: unsafe { (self.api().tex_create)(w, h, pixels.as_ptr(), linear) },
180 }
181 }
182
183 /// Get the GL texture handle that Minecraft uses for an identifier
184 /// (e.g. `"minecraft:textures/gui/icons.png"`). Returns handle 0 if not found.
185 pub fn texture_from_mc(&self, id: &str) -> gl::Texture {
186 use yog_abi::YogStr;
187 gl::Texture {
188 handle: unsafe { (self.api().tex_from_mc)(YogStr::from_str(id)) },
189 }
190 }
191
192 /// Delete a texture.
193 pub fn delete_texture(&self, tex: gl::Texture) {
194 unsafe { (self.api().tex_delete)(tex.handle) }
195 }
196
197 /// Bind a texture to the given sampler unit (0–7).
198 pub fn bind_texture(&self, unit: u32, tex: &gl::Texture) {
199 unsafe { (self.api().tex_bind)(unit, tex.handle) }
200 }
201
202 // ── Draw calls ────────────────────────────────────────────────────────────
203
204 /// Draw primitives using a vertex array (no index buffer).
205 pub fn draw_arrays(
206 &self,
207 vao: &gl::VertexArray,
208 prog: &gl::ShaderProgram,
209 mode: core::DrawMode,
210 first: u32,
211 count: u32,
212 ) {
213 unsafe { (self.api().draw_arrays)(vao.handle, prog.handle, mode as u8, first, count) }
214 }
215
216 /// Draw primitives via an index buffer.
217 /// `u32_indices`: `true` = `u32` indices, `false` = `u16` indices.
218 pub fn draw_elements(
219 &self,
220 vao: &gl::VertexArray,
221 ebo: &gl::Buffer,
222 prog: &gl::ShaderProgram,
223 mode: core::DrawMode,
224 count: u32,
225 u32_indices: bool,
226 ) {
227 unsafe {
228 (self.api().draw_elements)(
229 vao.handle,
230 ebo.handle,
231 prog.handle,
232 mode as u8,
233 count,
234 u32_indices,
235 )
236 }
237 }
238
239 // ── Render state ──────────────────────────────────────────────────────────
240
241 /// Enable or disable alpha blending.
242 /// `src`/`dst`: GL blend factor constants from [`core::blend`].
243 pub fn set_blend(&self, enabled: bool, src: u32, dst: u32) {
244 unsafe { (self.api().set_blend)(enabled, src, dst) }
245 }
246
247 /// Enable or disable depth testing and writing.
248 pub fn set_depth(&self, test: bool, write: bool) {
249 unsafe { (self.api().set_depth)(test, write) }
250 }
251
252 /// Enable scissor clipping to a GUI-pixel rectangle.
253 pub fn set_scissor(&self, x: i32, y: i32, w: i32, h: i32) {
254 unsafe { (self.api().set_scissor)(x, y, w, h) }
255 }
256
257 /// Disable scissor clipping.
258 pub fn clear_scissor(&self) {
259 unsafe { (self.api().clear_scissor)() }
260 }
261
262 /// Set the GL viewport in physical pixels (x, y, width, height).
263 pub fn set_viewport(&self, x: i32, y: i32, w: i32, h: i32) {
264 unsafe { (self.api().set_viewport)(x, y, w, h) }
265 }
266
267 // ── 2D convenience ────────────────────────────────────────────────────────
268
269 /// The host's text-width function (see [`draw2d::Draw2D::text_width`]) as
270 /// a plain function pointer — valid for the life of the process, so it
271 /// can be kept for measuring outside render callbacks (on the render
272 /// thread), e.g. by a layout engine.
273 pub fn text_width_fn(&self) -> TextWidthFn {
274 self.api().text_width
275 }
276
277 /// The host's image-size function (see [`draw2d::Draw2D::image_size`])
278 /// as a plain function pointer, valid for the life of the process — for
279 /// a layout engine sizing images outside render callbacks.
280 pub fn image_size_fn(&self) -> ImageSizeFn {
281 self.api().image_size
282 }
283
284 /// Access the 2D drawing helpers (text, rectangles, MC textures).
285 /// These only work during `on_hud_render`.
286 pub fn draw2d(&self) -> draw2d::Draw2D<'_> {
287 draw2d::Draw2D::new(self)
288 }
289}