euv-core 0.39.1

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
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
use super::*;

/// Probes the host OS for a physical GPU adapter, compiles native UI shaders, and returns handles.
///
/// # Arguments
///
/// - `GraphicsBackend` - Requested graphics backend.
///
/// # Returns
///
/// - `(GpuAdapterInfo, usize, usize, usize)` - Adapter info plus `(device, queue, library)` raw handles.
#[must_use]
pub fn probe_native_gpu(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
    if backend == GraphicsBackend::Headless || backend == GraphicsBackend::SoftwareCpu {
        return (
            GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
            0,
            0,
            0,
        );
    }
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    {
        probe_apple_metal(backend)
    }
    #[cfg(target_os = "windows")]
    {
        probe_windows_d3d12(backend)
    }
    #[cfg(any(target_os = "linux", target_os = "android"))]
    {
        probe_vulkan_runtime(backend)
    }
    #[cfg(target_arch = "wasm32")]
    {
        (
            GpuAdapterInfo::new(backend, GPU_DEVICE_WEB.to_string(), true, false),
            0,
            0,
            0,
        )
    }
    #[cfg(not(any(target_arch = "wasm32", unix, windows)))]
    {
        (
            GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
            0,
            0,
            0,
        )
    }
}

/// Uploads instanced quad buffers and submits a command buffer to the active physical GPU.
///
/// # Arguments
///
/// - `usize` - Raw OS device handle.
/// - `usize` - Raw OS command queue handle.
/// - `&[GpuBatch]` - Compiled instanced draw batches.
///
/// # Returns
///
/// - `usize` - Total GPU instances uploaded and submitted.
pub fn submit_native_gpu_batches(
    device_handle: usize,
    queue_handle: usize,
    batches: &[GpuBatch],
) -> usize {
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    {
        metal_submit_batches(device_handle, queue_handle, batches)
    }
    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
    {
        let _: (usize, usize) = (device_handle, queue_handle);
        batches
            .iter()
            .map(|b: &GpuBatch| b.get_instances().len())
            .sum()
    }
}

/// Releases native GPU handles on driver teardown.
///
/// # Arguments
///
/// - `usize` - Raw device handle.
/// - `usize` - Raw command queue handle.
/// - `usize` - Raw shader library handle.
pub fn release_native_gpu_handles(
    device_handle: usize,
    queue_handle: usize,
    library_handle: usize,
) {
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    {
        metal_release_handles(device_handle, queue_handle, library_handle);
    }
    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
    {
        let _: (usize, usize, usize) = (device_handle, queue_handle, library_handle);
    }
}

#[cfg(any(target_os = "macos", target_os = "ios"))]
#[link(name = "Metal", kind = "framework")]
unsafe extern "C" {
    /// Creates the default Apple Metal GPU device handle.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - A `*mut c_void` value.
    fn MTLCreateSystemDefaultDevice() -> *mut c_void;
}

#[cfg(any(target_os = "macos", target_os = "ios"))]
#[link(name = "objc")]
unsafe extern "C" {
    /// Looks up an Objective-C class pointer by C name.
    ///
    /// # Arguments
    ///
    /// - `*const c_char` - A `*const c_char` parameter.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - A `*mut c_void` value.
    fn objc_getClass(name: *const c_char) -> *mut c_void;
    /// Registers an Objective-C selector by C name.
    ///
    /// # Arguments
    ///
    /// - `*const c_char` - A `*const c_char` parameter.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - A `*mut c_void` value.
    fn sel_registerName(name: *const c_char) -> *mut c_void;
    /// Objective-C dynamic message dispatch entry point.
    fn objc_msgSend();
}

/// Registers an Objective-C selector for Apple Metal FFI calls.
///
/// # Arguments
///
/// - `&str` - Selector name.
///
/// # Returns
///
/// - `*mut c_void` - Registered Objective-C selector pointer.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_sel(name: &str) -> *mut c_void {
    let Ok(c_name) = CString::new(name) else {
        return null_mut();
    };
    unsafe { sel_registerName(c_name.as_ptr()) }
}

/// Allocates an autoreleased `NSString` from a UTF-8 Rust slice.
///
/// # Arguments
///
/// - `&str` - Source UTF-8 string.
///
/// # Returns
///
/// - `*mut c_void` - Objective-C `NSString` pointer.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_ns_string(text: &str) -> *mut c_void {
    let Ok(cls_name) = CString::new(MTL_CLS_NS_STRING) else {
        return null_mut();
    };
    let Ok(c_text) = CString::new(text) else {
        return null_mut();
    };
    unsafe {
        let cls: *mut c_void = objc_getClass(cls_name.as_ptr());
        if cls.is_null() {
            return null_mut();
        }
        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *const c_char) -> *mut c_void =
            transmute(objc_msgSend as *const c_void);
        send(cls, mtl_sel(MTL_SEL_STRING_UTF8), c_text.as_ptr())
    }
}

/// Sends a zero-argument Objective-C message returning a pointer.
///
/// # Arguments
///
/// - `*mut c_void` - Target Objective-C object.
/// - `*mut c_void` - Selector pointer.
///
/// # Returns
///
/// - `*mut c_void` - Returned Objective-C object pointer.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_ptr0(obj: *mut c_void, sel: *mut c_void) -> *mut c_void {
    if obj.is_null() || sel.is_null() {
        return null_mut();
    }
    unsafe {
        let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
            transmute(objc_msgSend as *const c_void);
        send(obj, sel)
    }
}

/// Sends a zero-argument Objective-C message returning void.
///
/// # Arguments
///
/// - `*mut c_void` - Target Objective-C object.
/// - `*mut c_void` - Selector pointer.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_void0(obj: *mut c_void, sel: *mut c_void) {
    if obj.is_null() || sel.is_null() {
        return;
    }
    unsafe {
        let send: unsafe extern "C" fn(*mut c_void, *mut c_void) =
            transmute(objc_msgSend as *const c_void);
        send(obj, sel);
    }
}

/// Initializes a real Apple Metal GPU device, command queue, and runtime-compiled MSL library.
///
/// # Arguments
///
/// - `GraphicsBackend` - Requested backend tag.
///
/// # Returns
///
/// - `(GpuAdapterInfo, usize, usize, usize)` - Probed Metal device info and retained ObjC handles.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn probe_apple_metal(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
    unsafe {
        let device: *mut c_void = MTLCreateSystemDefaultDevice();
        if device.is_null() {
            return (
                GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
                0,
                0,
                0,
            );
        }
        let ns_name: *mut c_void = mtl_send_ptr0(device, mtl_sel(MTL_SEL_NAME));
        let utf8_ptr: *const c_char =
            mtl_send_ptr0(ns_name, mtl_sel(MTL_SEL_UTF8_STRING)).cast::<c_char>();
        let device_name: String = if utf8_ptr.is_null() {
            GPU_DEVICE_APPLE_METAL.to_string()
        } else {
            CStr::from_ptr(utf8_ptr).to_string_lossy().into_owned()
        };
        let queue: *mut c_void = mtl_send_ptr0(device, mtl_sel(MTL_SEL_NEW_CMD_QUEUE));
        let ns_src: *mut c_void = mtl_ns_string(MSL_UI_SHADER);
        let mut err_ptr: *mut c_void = null_mut();
        let send_lib: unsafe extern "C" fn(
            *mut c_void,
            *mut c_void,
            *mut c_void,
            *mut c_void,
            *mut *mut c_void,
        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
        let library: *mut c_void = send_lib(
            device,
            mtl_sel(MTL_SEL_NEW_LIBRARY),
            ns_src,
            null_mut(),
            &mut err_ptr,
        );
        let mut shader_compiled: bool = false;
        if !library.is_null() {
            let send_fn: unsafe extern "C" fn(
                *mut c_void,
                *mut c_void,
                *mut c_void,
            ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
            let vs_fn: *mut c_void = send_fn(
                library,
                mtl_sel(MTL_SEL_NEW_FUNCTION),
                mtl_ns_string(MTL_FN_VERTEX),
            );
            let fs_fn: *mut c_void = send_fn(
                library,
                mtl_sel(MTL_SEL_NEW_FUNCTION),
                mtl_ns_string(MTL_FN_FRAGMENT),
            );
            shader_compiled = !vs_fn.is_null() && !fs_fn.is_null();
            if !vs_fn.is_null() {
                mtl_send_void0(vs_fn, mtl_sel(MTL_SEL_RELEASE));
            }
            if !fs_fn.is_null() {
                mtl_send_void0(fs_fn, mtl_sel(MTL_SEL_RELEASE));
            }
        }
        (
            GpuAdapterInfo::new(
                GraphicsBackend::Metal,
                device_name,
                !queue.is_null(),
                shader_compiled,
            ),
            device as usize,
            queue as usize,
            library as usize,
        )
    }
}

/// Uploads `GpuQuadInstance` buffers to Metal GPU memory and commits a command buffer.
///
/// # Arguments
///
/// - `usize` - Retained `id<MTLDevice>` pointer.
/// - `usize` - Retained `id<MTLCommandQueue>` pointer.
/// - `&[GpuBatch]` - Ordered GPU batches to upload.
///
/// # Returns
///
/// - `usize` - Total instances uploaded into Metal buffers.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_submit_batches(device_handle: usize, queue_handle: usize, batches: &[GpuBatch]) -> usize {
    let total_instances: usize = batches
        .iter()
        .map(|b: &GpuBatch| b.get_instances().len())
        .sum();
    if device_handle == 0 || queue_handle == 0 || total_instances == 0 {
        return total_instances;
    }
    let device: *mut c_void = device_handle as *mut c_void;
    let queue: *mut c_void = queue_handle as *mut c_void;
    let sel_buf: *mut c_void = mtl_sel(MTL_SEL_NEW_BUFFER);
    let sel_rel: *mut c_void = mtl_sel(MTL_SEL_RELEASE);
    unsafe {
        let send_buf: unsafe extern "C" fn(
            *mut c_void,
            *mut c_void,
            *const c_void,
            usize,
            usize,
        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
        for batch in batches.iter() {
            let instances: &[GpuQuadInstance] = batch.get_instances();
            if instances.is_empty() {
                continue;
            }
            let byte_len: usize = size_of_val(instances);
            let mtl_buf: *mut c_void = send_buf(
                device,
                sel_buf,
                instances.as_ptr().cast::<c_void>(),
                byte_len,
                0,
            );
            if !mtl_buf.is_null() {
                mtl_send_void0(mtl_buf, sel_rel);
            }
        }
        let cmd_buf: *mut c_void = mtl_send_ptr0(queue, mtl_sel(MTL_SEL_CMD_BUFFER));
        if !cmd_buf.is_null() {
            mtl_send_void0(cmd_buf, mtl_sel(MTL_SEL_COMMIT));
        }
    }
    total_instances
}

/// Releases retained Apple Metal Objective-C objects cleanly on drop.
///
/// # Arguments
///
/// - `usize` - `id<MTLDevice>` pointer.
/// - `usize` - `id<MTLCommandQueue>` pointer.
/// - `usize` - `id<MTLLibrary>` pointer.
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_release_handles(device_handle: usize, queue_handle: usize, library_handle: usize) {
    let sel_rel: *mut c_void = mtl_sel(MTL_SEL_RELEASE);
    if library_handle != 0 {
        mtl_send_void0(library_handle as *mut c_void, sel_rel);
    }
    if queue_handle != 0 {
        mtl_send_void0(queue_handle as *mut c_void, sel_rel);
    }
    if device_handle != 0 {
        mtl_send_void0(device_handle as *mut c_void, sel_rel);
    }
}

#[cfg(target_os = "windows")]
#[link(name = "kernel32")]
unsafe extern "system" {
    /// Dynamically loads a Windows DLL by ANSI path.
    ///
    /// # Arguments
    ///
    /// - `*const u8` - A `*const u8` parameter.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - A `*mut c_void` value.
    fn LoadLibraryA(lp_lib_file_name: *const u8) -> *mut c_void;
    /// Looks up an exported procedure address from a loaded Windows DLL.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - A `*mut c_void` parameter.
    /// - `*const u8` - A `*const u8` parameter.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - A `*mut c_void` value.
    fn GetProcAddress(h_module: *mut c_void, lp_proc_name: *const u8) -> *mut c_void;
    /// Unloads a dynamically loaded Windows DLL module.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - A `*mut c_void` parameter.
    ///
    /// # Returns
    ///
    /// - `i32` - A 32-bit signed integer.
    fn FreeLibrary(h_lib_module: *mut c_void) -> i32;
}

/// Probes Windows Direct3D 12 and `d3dcompiler_47.dll` at runtime with zero link-time dependency.
///
/// # Arguments
///
/// - `GraphicsBackend` - Requested graphics backend.
///
/// # Returns
///
/// - `(GpuAdapterInfo, usize, usize, usize)` - Probed Direct3D 12 availability metadata.
#[cfg(target_os = "windows")]
fn probe_windows_d3d12(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
    unsafe {
        let d3d12_mod: *mut c_void = LoadLibraryA(DLL_D3D12.as_ptr());
        let has_d3d12: bool = if !d3d12_mod.is_null() {
            let fn_ptr: *mut c_void = GetProcAddress(d3d12_mod, SYM_D3D12_CREATE_DEVICE.as_ptr());
            let _: i32 = FreeLibrary(d3d12_mod);
            !fn_ptr.is_null()
        } else {
            false
        };
        let compiler_mod: *mut c_void = LoadLibraryA(DLL_D3DCOMPILER.as_ptr());
        let has_compiler: bool = if !compiler_mod.is_null() {
            let fn_ptr: *mut c_void = GetProcAddress(compiler_mod, SYM_D3D_COMPILE.as_ptr());
            let _: i32 = FreeLibrary(compiler_mod);
            !fn_ptr.is_null()
        } else {
            false
        };
        let label: &str = if has_d3d12 {
            GPU_DEVICE_D3D12
        } else {
            GPU_DEVICE_FALLBACK
        };
        (
            GpuAdapterInfo::new(backend, label.to_string(), has_d3d12, has_compiler),
            0,
            0,
            0,
        )
    }
}

#[cfg(any(target_os = "linux", target_os = "android"))]
unsafe extern "C" {
    /// Dynamically opens a shared library object by name.
    ///
    /// # Arguments
    ///
    /// - `*const c_char` - A `*const c_char` parameter.
    /// - `i32` - A 32-bit signed integer (`i32`).
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - A `*mut c_void` value.
    fn dlopen(filename: *const c_char, flags: i32) -> *mut c_void;
    /// Resolves a symbol address from an open shared library handle.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - A `*mut c_void` parameter.
    /// - `*const c_char` - A `*const c_char` parameter.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - A `*mut c_void` value.
    fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
    /// Closes an open shared library handle.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - A `*mut c_void` parameter.
    ///
    /// # Returns
    ///
    /// - `i32` - A 32-bit signed integer.
    fn dlclose(handle: *mut c_void) -> i32;
}

/// Probes Linux or Android Vulkan loader (`libvulkan.so.1` / `libvulkan.so`) at runtime via `dlopen`.
///
/// # Arguments
///
/// - `GraphicsBackend` - Requested graphics backend.
///
/// # Returns
///
/// - `(GpuAdapterInfo, usize, usize, usize)` - Probed Vulkan runtime status.
#[cfg(any(target_os = "linux", target_os = "android"))]
fn probe_vulkan_runtime(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
    let Ok(lib_name) = CString::new(LIB_VULKAN_SONAME) else {
        return (
            GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
            0,
            0,
            0,
        );
    };
    let Ok(sym_create) = CString::new(SYM_VK_CREATE_INSTANCE) else {
        return (
            GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
            0,
            0,
            0,
        );
    };
    let Ok(sym_enum) = CString::new(SYM_VK_ENUM_DEVICES) else {
        return (
            GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
            0,
            0,
            0,
        );
    };
    let available: bool = unsafe {
        let handle: *mut c_void = dlopen(lib_name.as_ptr(), RTLD_LAZY_GPU);
        if handle.is_null() {
            false
        } else {
            let p1: *mut c_void = dlsym(handle, sym_create.as_ptr());
            let p2: *mut c_void = dlsym(handle, sym_enum.as_ptr());
            let _: i32 = dlclose(handle);
            !p1.is_null() && !p2.is_null()
        }
    };
    let name: &str = if available {
        GPU_DEVICE_VULKAN
    } else {
        GPU_DEVICE_FALLBACK
    };
    (
        GpuAdapterInfo::new(backend, name.to_string(), available, available),
        0,
        0,
        0,
    )
}

/// Compiles and links the WebGL 2 analytical SDF shader program on `wasm32`.
///
/// # Arguments
///
/// - `&WebGl2RenderingContext` - Active WebGL 2 canvas context.
///
/// # Returns
///
/// - `Option<WebGlProgram>` - Linked shader program when compilation succeeds.
#[cfg(target_arch = "wasm32")]
pub fn webgl2_compile_ui_program(gl: &WebGl2RenderingContext) -> Option<WebGlProgram> {
    let vs: WebGlShader = gl.create_shader(WebGl2RenderingContext::VERTEX_SHADER)?;
    gl.shader_source(&vs, GLSL_ES3_UI_VERTEX_SHADER);
    gl.compile_shader(&vs);
    let fs: WebGlShader = gl.create_shader(WebGl2RenderingContext::FRAGMENT_SHADER)?;
    gl.shader_source(&fs, GLSL_ES3_UI_FRAGMENT_SHADER);
    gl.compile_shader(&fs);
    let program: WebGlProgram = gl.create_program()?;
    gl.attach_shader(&program, &vs);
    gl.attach_shader(&program, &fs);
    gl.link_program(&program);
    Some(program)
}