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