yog-runtime 0.110.3

Yog runtime — native library bridging the Fabric host to Rust mods via JNI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
//! The low-level GPU pipeline (ABI 14): buffers, vertex arrays, shaders, textures, draws, render state.

mod consts;
use crate::gl_context::GL;
use crate::gl_context::GL_GET_PROGRAM_BINARY;
use crate::gl_context::GL_GET_PROGRAM_IV;
use crate::gl_context::GL_PROGRAM_BINARY;
use glow::HasContext;
use std::num::NonZeroU32;
use std::os::raw::c_void;
use std::path::PathBuf;
use yog_abi::YogStr;

/// A user's cache, in their home (XDG's default).
const USER_CACHE: &str = ".cache";

// ── ABI minor 14 — low-level GPU pipeline ────────────────────────────────────
//
// All raw GL calls go through `glow::Context` stored in GL.
// `draw2d_*` functions still call JNI (NativeDraw) for MC text/texture rendering.
// Everything is called on the render thread — no synchronization needed.

// ── helpers ───────────────────────────────────────────────────────────────────

pub(super) fn gl_draw_mode(mode: u8) -> u32 {
    match mode {
        1 => glow::LINES,
        2 => glow::LINE_STRIP,
        3 => glow::TRIANGLE_STRIP,
        4 => glow::TRIANGLE_FAN,
        _ => glow::TRIANGLES,
    }
}

pub(super) fn gl_attr_type(dtype: u8) -> u32 {
    match dtype {
        1 => glow::UNSIGNED_BYTE,
        2 => glow::INT,
        3 => glow::UNSIGNED_INT,
        _ => glow::FLOAT,
    }
}

pub(super) unsafe fn compile_shader(
    gl: &glow::Context,
    stage: u32,
    src: &str,
) -> Option<glow::NativeShader> {
    unsafe {
        let sh = gl.create_shader(stage).ok()?;
        gl.shader_source(sh, src);
        gl.compile_shader(sh);
        if !gl.get_shader_compile_status(sh) {
            yog_logging::error!("yog-gfx shader compile: {}", gl.get_shader_info_log(sh));
            gl.delete_shader(sh);
            return None;
        }
        Some(sh)
    }
}

// ── GPU buffers ───────────────────────────────────────────────────────────────

pub(super) unsafe extern "C" fn gfx_buf_create() -> u32 {
    crate::jni_util::guarded("gfx_buf_create", 0, || unsafe {
        let Some(g) = GL.get() else { return 0 };
        g.0.create_buffer().map(|b| b.0.get()).unwrap_or(0)
    })
}

pub(super) unsafe extern "C" fn gfx_buf_delete(handle: u32) {
    crate::jni_util::guard("gfx_buf_delete", || unsafe {
        let Some(g) = GL.get() else { return };
        let Some(n) = NonZeroU32::new(handle) else {
            return;
        };
        g.0.delete_buffer(glow::NativeBuffer(n));
    });
}

pub(super) unsafe extern "C" fn gfx_buf_data(
    handle: u32,
    bytes: *const u8,
    len: u32,
    dynamic: bool,
) {
    crate::jni_util::guard("gfx_buf_data", || unsafe {
        let Some(g) = GL.get() else { return };
        let Some(n) = NonZeroU32::new(handle) else {
            return;
        };
        let gl = &g.0;
        let data = std::slice::from_raw_parts(bytes, len as usize);
        let usage = if dynamic {
            glow::DYNAMIC_DRAW
        } else {
            glow::STATIC_DRAW
        };
        gl.bind_buffer(glow::ARRAY_BUFFER, Some(glow::NativeBuffer(n)));
        gl.buffer_data_u8_slice(glow::ARRAY_BUFFER, data, usage);
        gl.bind_buffer(glow::ARRAY_BUFFER, None);
    });
}

pub(super) unsafe extern "C" fn gfx_buf_subdata(
    handle: u32,
    offset: u32,
    bytes: *const u8,
    len: u32,
) {
    crate::jni_util::guard("gfx_buf_subdata", || unsafe {
        let Some(g) = GL.get() else { return };
        let Some(n) = NonZeroU32::new(handle) else {
            return;
        };
        let gl = &g.0;
        let data = std::slice::from_raw_parts(bytes, len as usize);
        gl.bind_buffer(glow::ARRAY_BUFFER, Some(glow::NativeBuffer(n)));
        gl.buffer_sub_data_u8_slice(glow::ARRAY_BUFFER, offset as i32, data);
        gl.bind_buffer(glow::ARRAY_BUFFER, None);
    });
}

// ── Vertex arrays ─────────────────────────────────────────────────────────────

pub(super) unsafe extern "C" fn gfx_vao_create() -> u32 {
    crate::jni_util::guarded("gfx_vao_create", 0, || unsafe {
        let Some(g) = GL.get() else { return 0 };
        g.0.create_vertex_array().map(|v| v.0.get()).unwrap_or(0)
    })
}

pub(super) unsafe extern "C" fn gfx_vao_delete(handle: u32) {
    crate::jni_util::guard("gfx_vao_delete", || unsafe {
        let Some(g) = GL.get() else { return };
        let Some(n) = NonZeroU32::new(handle) else {
            return;
        };
        g.0.delete_vertex_array(glow::NativeVertexArray(n));
    });
}

pub(super) unsafe extern "C" fn gfx_vao_attrib(
    vao: u32,
    vbo: u32,
    index: u32,
    components: u8,
    dtype: u8,
    normalized: bool,
    stride: u32,
    offset: u32,
) {
    crate::jni_util::guard("gfx_vao_attrib", || unsafe {
        let Some(g) = GL.get() else { return };
        let (Some(vn), Some(bn)) = (NonZeroU32::new(vao), NonZeroU32::new(vbo)) else {
            return;
        };
        let gl = &g.0;
        gl.bind_vertex_array(Some(glow::NativeVertexArray(vn)));
        gl.bind_buffer(glow::ARRAY_BUFFER, Some(glow::NativeBuffer(bn)));
        let gl_type = gl_attr_type(dtype);
        if dtype == 2 || dtype == 3 {
            gl.vertex_attrib_pointer_i32(
                index,
                components as i32,
                gl_type,
                stride as i32,
                offset as i32,
            );
        } else {
            gl.vertex_attrib_pointer_f32(
                index,
                components as i32,
                gl_type,
                normalized,
                stride as i32,
                offset as i32,
            );
        }
        gl.enable_vertex_attrib_array(index);
        gl.bind_vertex_array(None);
    });
}

pub(super) unsafe extern "C" fn gfx_vao_set_ebo(vao: u32, ebo: u32) {
    crate::jni_util::guard("gfx_vao_set_ebo", || unsafe {
        let Some(g) = GL.get() else { return };
        let (Some(vn), Some(en)) = (NonZeroU32::new(vao), NonZeroU32::new(ebo)) else {
            return;
        };
        let gl = &g.0;
        gl.bind_vertex_array(Some(glow::NativeVertexArray(vn)));
        gl.bind_buffer(glow::ELEMENT_ARRAY_BUFFER, Some(glow::NativeBuffer(en)));
        gl.bind_vertex_array(None);
    });
}

// ── Shader programs ───────────────────────────────────────────────────────────

/// Returns a path under `~/.cache/yog/shaders/<hash>.ysc` for the given GLSL source pair,
/// creating the directory if needed.  Returns `None` if the home directory is unknown.
pub(super) fn shader_cache_path(vert: &str, frag: &str) -> Option<PathBuf> {
    use std::hash::{Hash, Hasher};
    let mut h = std::collections::hash_map::DefaultHasher::new();
    vert.hash(&mut h);
    frag.hash(&mut h);
    let hash = h.finish();
    let dir = std::env::var("HOME")
        .map(|home| {
            PathBuf::from(home)
                .join(USER_CACHE)
                .join(consts::CACHE)
                .join(consts::SHADERS)
        })
        .ok()?;
    std::fs::create_dir_all(&dir).ok()?;
    Some(dir.join(format!("{hash:016x}.ysc")))
}

/// Try restoring a program from a binary blob (`[4 LE bytes: GL format][binary…]`).
/// Returns `Some(handle)` if the driver accepts the binary, `None` otherwise.
///
/// Uses `glProgramBinary` (GL 4.1 / ARB_get_program_binary) via the raw pointer
/// captured in `nativeGlInit`.  Returns `None` if the extension is unavailable.
pub(super) unsafe fn load_shader_binary(
    gl: &glow::Context,
    data: &[u8],
) -> Option<glow::NativeProgram> {
    unsafe {
        if data.len() < 4 {
            return None;
        }
        type ProgramBinaryFn = unsafe extern "system" fn(u32, u32, *const c_void, i32);
        let fn_ptr = (*GL_PROGRAM_BINARY.get()?)?;
        let program_binary: ProgramBinaryFn = std::mem::transmute(fn_ptr);

        let fmt = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
        let prog = gl.create_program().ok()?;
        program_binary(
            prog.0.get(),
            fmt,
            data[4..].as_ptr() as *const c_void,
            (data.len() - 4) as i32,
        );
        if gl.get_program_link_status(prog) {
            Some(prog)
        } else {
            gl.delete_program(prog);
            None
        }
    }
}

/// Read the compiled binary of a linked program.  Returns empty `Vec` if unsupported.
pub(super) unsafe fn program_binary(prog: glow::NativeProgram) -> (Vec<u8>, u32) {
    unsafe {
        type GetProgramivFn = unsafe extern "system" fn(u32, u32, *mut i32);
        type GetProgramBinaryFn =
            unsafe extern "system" fn(u32, i32, *mut i32, *mut u32, *mut c_void);

        let Some(get_iv_raw) = GL_GET_PROGRAM_IV.get().and_then(|v| *v) else {
            return (vec![], 0);
        };
        let Some(get_bin_raw) = GL_GET_PROGRAM_BINARY.get().and_then(|v| *v) else {
            return (vec![], 0);
        };
        let get_program_iv: GetProgramivFn = std::mem::transmute(get_iv_raw);
        let get_program_binary: GetProgramBinaryFn = std::mem::transmute(get_bin_raw);

        // Query binary size via glGetProgramiv(GL_PROGRAM_BINARY_LENGTH).
        const PROGRAM_BINARY_LENGTH: u32 = 0x8741;
        let mut size: i32 = 0;
        get_program_iv(prog.0.get(), PROGRAM_BINARY_LENGTH, &mut size);
        if size <= 0 {
            return (vec![], 0);
        }

        let mut buf = vec![0u8; size as usize];
        let mut actual_len: i32 = 0;
        let mut fmt: u32 = 0;
        get_program_binary(
            prog.0.get(),
            size,
            &mut actual_len,
            &mut fmt,
            buf.as_mut_ptr() as *mut c_void,
        );
        buf.truncate(actual_len.max(0) as usize);
        (buf, fmt)
    }
}

pub(super) unsafe extern "C" fn gfx_prog_create(vert: YogStr, frag: YogStr, out: *mut u32) -> bool {
    crate::jni_util::guarded("gfx_prog_create", false, || {
        unsafe {
            let Some(g) = GL.get() else { return false };
            let gl = &g.0;
            let vert_s = vert.as_str();
            let frag_s = frag.as_str();

            // Fast path: binary shader cache — avoids GLSL re-compilation on subsequent launches.
            let cache_path = shader_cache_path(vert_s, frag_s);
            if let Some(ref path) = cache_path
                && let Ok(data) = std::fs::read(path)
            {
                if let Some(prog) = load_shader_binary(gl, &data) {
                    *out = prog.0.get();
                    return true;
                }
                // Cache stale (driver updated?); remove and fall through to GLSL compile.
                if let Err(e) = std::fs::remove_file(path) {
                    yog_logging::warn!("shader cache {}: {e}", path.display());
                }
            }

            // GLSL compile path.
            let vs = match compile_shader(gl, glow::VERTEX_SHADER, vert_s) {
                Some(s) => s,
                None => return false,
            };
            let fs = match compile_shader(gl, glow::FRAGMENT_SHADER, frag_s) {
                Some(s) => s,
                None => {
                    gl.delete_shader(vs);
                    return false;
                }
            };
            let prog = match gl.create_program() {
                Ok(p) => p,
                Err(e) => {
                    yog_logging::error!("yog-gfx: create_program: {}", e);
                    gl.delete_shader(vs);
                    gl.delete_shader(fs);
                    return false;
                }
            };
            gl.attach_shader(prog, vs);
            gl.attach_shader(prog, fs);
            gl.link_program(prog);
            gl.detach_shader(prog, vs);
            gl.detach_shader(prog, fs);
            gl.delete_shader(vs);
            gl.delete_shader(fs);
            if !gl.get_program_link_status(prog) {
                yog_logging::error!("yog-gfx: shader link: {}", gl.get_program_info_log(prog));
                gl.delete_program(prog);
                return false;
            }

            // Persist binary so the next launch skips GLSL compilation entirely.
            if let Some(ref path) = cache_path {
                let (binary, fmt) = program_binary(prog);
                if !binary.is_empty() {
                    let mut blob = fmt.to_le_bytes().to_vec();
                    blob.extend_from_slice(&binary);
                    if let Err(e) = std::fs::write(path, &blob) {
                        yog_logging::warn!(
                            "shader cache {}: {e} (compiled again next launch)",
                            path.display()
                        );
                    }
                }
            }

            *out = prog.0.get();
            true
        }
    })
}

pub(super) unsafe extern "C" fn gfx_prog_delete(handle: u32) {
    crate::jni_util::guard("gfx_prog_delete", || unsafe {
        let Some(g) = GL.get() else { return };
        let Some(n) = NonZeroU32::new(handle) else {
            return;
        };
        g.0.delete_program(glow::NativeProgram(n));
    });
}

macro_rules! with_prog {
    ($handle:expr_2021, |$gl:ident, $prog:ident, $loc:ident ($name:expr_2021)| $body:expr_2021) => {{
        let Some(g) = GL.get() else { return };
        let Some(n) = NonZeroU32::new($handle) else {
            return;
        };
        let $gl = &g.0;
        let $prog = glow::NativeProgram(n);
        $gl.use_program(Some($prog));
        let $loc = $gl.get_uniform_location($prog, $name.as_str());
        $body
    }};
}

pub(super) unsafe extern "C" fn gfx_prog_uniform_1i(prog: u32, name: YogStr, v: i32) {
    crate::jni_util::guard("gfx_prog_uniform_1i", || unsafe {
        with_prog!(prog, |gl, _p, loc(name)| gl.uniform_1_i32(loc.as_ref(), v));
    });
}
pub(super) unsafe extern "C" fn gfx_prog_uniform_1f(prog: u32, name: YogStr, v: f32) {
    crate::jni_util::guard("gfx_prog_uniform_1f", || unsafe {
        with_prog!(prog, |gl, _p, loc(name)| gl.uniform_1_f32(loc.as_ref(), v));
    });
}
pub(super) unsafe extern "C" fn gfx_prog_uniform_2f(prog: u32, name: YogStr, x: f32, y: f32) {
    crate::jni_util::guard("gfx_prog_uniform_2f", || unsafe {
        with_prog!(prog, |gl, _p, loc(name)| gl.uniform_2_f32(
            loc.as_ref(),
            x,
            y
        ));
    });
}
pub(super) unsafe extern "C" fn gfx_prog_uniform_3f(
    prog: u32,
    name: YogStr,
    x: f32,
    y: f32,
    z: f32,
) {
    crate::jni_util::guard("gfx_prog_uniform_3f", || unsafe {
        with_prog!(prog, |gl, _p, loc(name)| gl.uniform_3_f32(
            loc.as_ref(),
            x,
            y,
            z
        ));
    });
}
pub(super) unsafe extern "C" fn gfx_prog_uniform_4f(
    prog: u32,
    name: YogStr,
    x: f32,
    y: f32,
    z: f32,
    w: f32,
) {
    crate::jni_util::guard("gfx_prog_uniform_4f", || unsafe {
        with_prog!(prog, |gl, _p, loc(name)| gl.uniform_4_f32(
            loc.as_ref(),
            x,
            y,
            z,
            w
        ));
    });
}
pub(super) unsafe extern "C" fn gfx_prog_uniform_mat4(
    prog: u32,
    name: YogStr,
    col_major: *const f32,
) {
    crate::jni_util::guard("gfx_prog_uniform_mat4", || unsafe {
        with_prog!(prog, |gl, _p, loc(name)| {
            let data = std::slice::from_raw_parts(col_major, 16);
            gl.uniform_matrix_4_f32_slice(loc.as_ref(), false, data);
        });
    });
}

// ── Textures ──────────────────────────────────────────────────────────────────

pub(super) unsafe extern "C" fn gfx_tex_create(
    w: u32,
    h: u32,
    rgba: *const u8,
    linear: bool,
) -> u32 {
    crate::jni_util::guarded("gfx_tex_create", 0, || {
        unsafe {
            let Some(g) = GL.get() else { return 0 };
            let gl = &g.0;
            let tex = match gl.create_texture() {
                Ok(t) => t,
                Err(_) => return 0,
            };
            gl.bind_texture(glow::TEXTURE_2D, Some(tex));
            let filter = if linear { glow::LINEAR } else { glow::NEAREST };
            gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MIN_FILTER, filter as i32);
            gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MAG_FILTER, filter as i32);
            gl.tex_parameter_i32(
                glow::TEXTURE_2D,
                glow::TEXTURE_WRAP_S,
                glow::CLAMP_TO_EDGE as i32,
            );
            gl.tex_parameter_i32(
                glow::TEXTURE_2D,
                glow::TEXTURE_WRAP_T,
                glow::CLAMP_TO_EDGE as i32,
            );
            let pixels = std::slice::from_raw_parts(rgba, (w * h * 4) as usize);
            // The game leaves its own unpacking (row length, skips) set from its
            // atlas uploads: read with those, a tight buffer is overrun.
            unpack_tightly(gl);
            gl.tex_image_2d(
                glow::TEXTURE_2D,
                0,
                glow::RGBA8 as i32,
                w as i32,
                h as i32,
                0,
                glow::RGBA,
                glow::UNSIGNED_BYTE,
                glow::PixelUnpackData::Slice(Some(pixels)),
            );
            gl.bind_texture(glow::TEXTURE_2D, None);
            tex.0.get()
        }
    })
}

/// Pixel unpacking as a tightly packed client buffer needs it.
pub(super) unsafe fn unpack_tightly(gl: &glow::Context) {
    unsafe {
        gl.bind_buffer(glow::PIXEL_UNPACK_BUFFER, None);
        gl.pixel_store_i32(glow::UNPACK_ROW_LENGTH, 0);
        gl.pixel_store_i32(glow::UNPACK_SKIP_ROWS, 0);
        gl.pixel_store_i32(glow::UNPACK_SKIP_PIXELS, 0);
        gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, 4);
    }
}

pub(super) unsafe extern "C" fn gfx_tex_delete(handle: u32) {
    crate::jni_util::guard("gfx_tex_delete", || unsafe {
        let Some(g) = GL.get() else { return };
        let Some(n) = NonZeroU32::new(handle) else {
            return;
        };
        g.0.delete_texture(glow::NativeTexture(n));
    });
}

pub(super) unsafe extern "C" fn gfx_tex_bind(unit: u32, handle: u32) {
    crate::jni_util::guard("gfx_tex_bind", || unsafe {
        let Some(g) = GL.get() else { return };
        let gl = &g.0;
        gl.active_texture(glow::TEXTURE0 + unit);
        match NonZeroU32::new(handle) {
            Some(n) => gl.bind_texture(glow::TEXTURE_2D, Some(glow::NativeTexture(n))),
            None => gl.bind_texture(glow::TEXTURE_2D, None),
        }
    });
}

pub(super) unsafe extern "C" fn gfx_tex_from_mc(id: YogStr) -> u32 {
    crate::jni_util::guarded("gfx_tex_from_mc", 0, || unsafe {
        host!("dev/yog/NativeDraw", "getMcTextureId", [S(id)]).map_or(0, |id: i32| id as u32)
    })
}

// ── Draw calls ────────────────────────────────────────────────────────────────

pub(super) unsafe extern "C" fn gfx_draw_arrays(
    vao: u32,
    prog: u32,
    mode: u8,
    first: u32,
    count: u32,
) {
    crate::jni_util::guard("gfx_draw_arrays", || unsafe {
        let Some(g) = GL.get() else { return };
        let (Some(vn), Some(pn)) = (NonZeroU32::new(vao), NonZeroU32::new(prog)) else {
            return;
        };
        let gl = &g.0;
        gl.use_program(Some(glow::NativeProgram(pn)));
        gl.bind_vertex_array(Some(glow::NativeVertexArray(vn)));
        gl.draw_arrays(gl_draw_mode(mode), first as i32, count as i32);
        gl.bind_vertex_array(None);
    });
}

pub(super) unsafe extern "C" fn gfx_draw_elements(
    vao: u32,
    ebo: u32,
    prog: u32,
    mode: u8,
    count: u32,
    u32_idx: bool,
) {
    crate::jni_util::guard("gfx_draw_elements", || {
        unsafe {
            let Some(g) = GL.get() else { return };
            let (Some(vn), Some(pn)) = (NonZeroU32::new(vao), NonZeroU32::new(prog)) else {
                return;
            };
            let gl = &g.0;
            gl.use_program(Some(glow::NativeProgram(pn)));
            gl.bind_vertex_array(Some(glow::NativeVertexArray(vn)));
            // EBO is stored in the VAO; ebo param is informational for safety but not re-bound here.
            let _ = ebo;
            let idx_type = if u32_idx {
                glow::UNSIGNED_INT
            } else {
                glow::UNSIGNED_SHORT
            };
            gl.draw_elements(gl_draw_mode(mode), count as i32, idx_type, 0);
            gl.bind_vertex_array(None);
        }
    });
}

// ── Render state ──────────────────────────────────────────────────────────────

pub(super) unsafe extern "C" fn gfx_set_blend(enabled: bool, src: u32, dst: u32) {
    crate::jni_util::guard("gfx_set_blend", || unsafe {
        let Some(g) = GL.get() else { return };
        let gl = &g.0;
        if enabled {
            gl.enable(glow::BLEND);
            gl.blend_func(src, dst);
        } else {
            gl.disable(glow::BLEND);
        }
    });
}

pub(super) unsafe extern "C" fn gfx_set_depth(test: bool, write: bool) {
    crate::jni_util::guard("gfx_set_depth", || {
        unsafe {
            let Some(g) = GL.get() else { return };
            let gl = &g.0;
            if test {
                gl.enable(glow::DEPTH_TEST);
            } else {
                gl.disable(glow::DEPTH_TEST);
            }
            gl.depth_mask(write);
            // Disable face culling: our 2D quads use CW winding (back-face) due to y-flip.
            if !test {
                gl.disable(glow::CULL_FACE);
            }
        }
    });
}

pub(super) unsafe extern "C" fn gfx_set_scissor(x: i32, y: i32, w: i32, h: i32) {
    crate::jni_util::guard("gfx_set_scissor", || unsafe {
        let Some(g) = GL.get() else { return };
        let gl = &g.0;
        gl.enable(glow::SCISSOR_TEST);
        gl.scissor(x, y, w, h);
    });
}

pub(super) unsafe extern "C" fn gfx_clear_scissor() {
    crate::jni_util::guard("gfx_clear_scissor", || unsafe {
        let Some(g) = GL.get() else { return };
        g.0.disable(glow::SCISSOR_TEST);
    });
}

pub(super) unsafe extern "C" fn gfx_set_viewport(x: i32, y: i32, w: i32, h: i32) {
    crate::jni_util::guard("gfx_set_viewport", || unsafe {
        let Some(g) = GL.get() else { return };
        g.0.viewport(x, y, w, h);
    });
}