sola-raylib 6.0.0

Safe Rust bindings for raylib. sola-raylib N.x tracks raylib N.x (e.g. 5.x → raylib 5.5; 6.x → raylib 6.0).
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
//! 3D Model, Mesh, and Animation

use crate::core::math::{BoundingBox, Vector3};
use crate::core::texture::Image;
use crate::core::{RaylibHandle, RaylibThread};
use crate::error::{error, Error};
use crate::{consts, ffi};
use std::ffi::CString;
use std::os::raw::c_void;
use std::ptr::NonNull;

fn no_drop<T>(_thing: T) {}
make_thin_wrapper!(Model, ffi::Model, ffi::UnloadModel);
make_thin_wrapper!(WeakModel, ffi::Model, no_drop);
make_thin_wrapper!(Mesh, ffi::Mesh, |mesh: ffi::Mesh| ffi::UnloadMesh(mesh));
make_thin_wrapper!(WeakMesh, ffi::Mesh, no_drop);
make_thin_wrapper!(Material, ffi::Material, ffi::UnloadMaterial);
make_thin_wrapper!(WeakMaterial, ffi::Material, no_drop);
make_thin_wrapper!(BoneInfo, ffi::BoneInfo, no_drop);
// raylib 6.0 removed the single-anim `UnloadModelAnimation`; only the
// array-taking `UnloadModelAnimations` remains, and it calls
// `RL_FREE(animations)` at the end — which would free stack memory if
// called on a single owned value. Replicate the per-animation inner
// cleanup (free each keyframe's Transform array + the keyframePoses
// array) without freeing the struct itself.
make_thin_wrapper!(
    ModelAnimation,
    ffi::ModelAnimation,
    |anim: ffi::ModelAnimation| {
        for i in 0..anim.keyframeCount {
            ffi::MemFree(*anim.keyframePoses.offset(i as isize) as *mut c_void);
        }
        ffi::MemFree(anim.keyframePoses as *mut c_void);
    }
);
make_thin_wrapper!(WeakModelAnimation, ffi::ModelAnimation, no_drop);
make_thin_wrapper!(MaterialMap, ffi::MaterialMap, no_drop);

// Weak things can be clone
impl Clone for WeakModel {
    fn clone(&self) -> WeakModel {
        WeakModel(self.0)
    }
}

// Weak things can be clone
impl Clone for WeakMesh {
    fn clone(&self) -> WeakMesh {
        WeakMesh(self.0)
    }
}

// Weak things can be clone
impl Clone for WeakMaterial {
    fn clone(&self) -> WeakMaterial {
        WeakMaterial(self.0)
    }
}

// Weak things can be clone
impl Clone for WeakModelAnimation {
    fn clone(&self) -> WeakModelAnimation {
        WeakModelAnimation(self.0)
    }
}

impl RaylibHandle {
    /// Loads model from files (mesh and material).
    // #[inline]
    pub fn load_model(&mut self, _: &RaylibThread, filename: &str) -> Result<Model, Error> {
        let c_filename = CString::new(filename).unwrap();
        let m = unsafe { ffi::LoadModel(c_filename.as_ptr()) };
        if m.meshes.is_null()
            && m.materials.is_null()
            && m.skeleton.bones.is_null()
            && m.skeleton.bindPose.is_null()
        {
            return Err(error!("could not load model", filename));
        }
        // TODO check if null pointer checks are necessary.
        Ok(Model(m))
    }

    // Loads model from a generated mesh
    pub fn load_model_from_mesh(
        &mut self,
        _: &RaylibThread,
        mesh: WeakMesh,
    ) -> Result<Model, Error> {
        let m = unsafe { ffi::LoadModelFromMesh(mesh.0) };

        if m.meshes.is_null() || m.materials.is_null() {
            return Err(error!("Could not load model from mesh"));
        }

        Ok(Model(m))
    }

    pub fn load_model_animations(
        &mut self,
        _: &RaylibThread,
        filename: &str,
    ) -> Result<Vec<ModelAnimation>, Error> {
        let c_filename = CString::new(filename).unwrap();
        let mut m_size = 0;
        let m_ptr = unsafe { ffi::LoadModelAnimations(c_filename.as_ptr(), &mut m_size) };
        if m_size <= 0 {
            return Err(error!("No model animations loaded", filename));
        }
        let mut m_vec = Vec::with_capacity(m_size as usize);
        for i in 0..m_size {
            unsafe {
                m_vec.push(ModelAnimation(*m_ptr.offset(i as isize)));
            }
        }
        unsafe {
            ffi::MemFree(m_ptr as *mut ::std::os::raw::c_void);
        }
        Ok(m_vec)
    }

    pub fn update_model_animation(
        &mut self,
        _: &RaylibThread,
        mut model: impl AsMut<ffi::Model>,
        anim: impl AsRef<ffi::ModelAnimation>,
        frame: f32,
    ) {
        unsafe {
            ffi::UpdateModelAnimation(*model.as_mut(), *anim.as_ref(), frame);
        }
    }

    /// Update model animation pose by blending two animations.
    ///
    /// `blend` is the ratio between `anim_a` and `anim_b`: `0.0` is all
    /// `anim_a`, `1.0` is all `anim_b`. Added in raylib 6.0 alongside the
    /// skeletal animation redesign.
    // Argument list mirrors raylib's `UpdateModelAnimationEx` C API.
    #[allow(clippy::too_many_arguments)]
    pub fn update_model_animation_ex(
        &mut self,
        _: &RaylibThread,
        mut model: impl AsMut<ffi::Model>,
        anim_a: impl AsRef<ffi::ModelAnimation>,
        frame_a: f32,
        anim_b: impl AsRef<ffi::ModelAnimation>,
        frame_b: f32,
        blend: f32,
    ) {
        unsafe {
            ffi::UpdateModelAnimationEx(
                *model.as_mut(),
                *anim_a.as_ref(),
                frame_a,
                *anim_b.as_ref(),
                frame_b,
                blend,
            );
        }
    }
}

impl RaylibModel for WeakModel {}
impl RaylibModel for Model {}

impl Model {
    /// Convert into a [`WeakModel`] that does not own the underlying resource.
    ///
    /// # Safety
    ///
    /// The caller becomes responsible for ensuring the returned `WeakModel`
    /// does not outlive the GPU resources it references, and for explicitly
    /// unloading the model via [`RaylibHandle::unload_model`] when finished.
    /// Failing to do so will leak GPU memory.
    pub unsafe fn make_weak(self) -> WeakModel {
        let m = WeakModel(self.0);
        std::mem::forget(self);
        m
    }
}

pub trait RaylibModel: AsRef<ffi::Model> + AsMut<ffi::Model> {
    fn transform(&self) -> &crate::math::Matrix {
        unsafe { std::mem::transmute(&self.as_ref().transform) }
    }

    fn set_transform(&mut self, mat: &crate::math::Matrix) {
        self.as_mut().transform = mat.into();
    }

    fn meshes(&self) -> &[WeakMesh] {
        unsafe {
            std::slice::from_raw_parts(
                self.as_ref().meshes as *const WeakMesh,
                self.as_ref().meshCount as usize,
            )
        }
    }
    fn meshes_mut(&mut self) -> &mut [WeakMesh] {
        unsafe {
            std::slice::from_raw_parts_mut(
                self.as_mut().meshes as *mut WeakMesh,
                self.as_mut().meshCount as usize,
            )
        }
    }
    fn materials(&self) -> &[WeakMaterial] {
        unsafe {
            std::slice::from_raw_parts(
                self.as_ref().materials as *const WeakMaterial,
                self.as_ref().materialCount as usize,
            )
        }
    }
    fn materials_mut(&mut self) -> &mut [WeakMaterial] {
        unsafe {
            std::slice::from_raw_parts_mut(
                self.as_mut().materials as *mut WeakMaterial,
                self.as_mut().materialCount as usize,
            )
        }
    }

    fn bones(&self) -> Option<&[BoneInfo]> {
        if self.as_ref().skeleton.bones.is_null() {
            return None;
        }

        Some(unsafe {
            std::slice::from_raw_parts(
                self.as_ref().skeleton.bones as *const BoneInfo,
                self.as_ref().skeleton.boneCount as usize,
            )
        })
    }
    fn bones_mut(&mut self) -> Option<&mut [BoneInfo]> {
        if self.as_ref().skeleton.bones.is_null() {
            return None;
        }

        Some(unsafe {
            std::slice::from_raw_parts_mut(
                self.as_mut().skeleton.bones as *mut BoneInfo,
                self.as_mut().skeleton.boneCount as usize,
            )
        })
    }
    /// Bind-pose transforms — one entry per bone in the skeleton.
    fn bind_pose(&self) -> Option<&[crate::math::Transform]> {
        if self.as_ref().skeleton.bindPose.is_null() {
            return None;
        }
        Some(unsafe {
            std::slice::from_raw_parts(
                self.as_ref().skeleton.bindPose as *const crate::math::Transform,
                self.as_ref().skeleton.boneCount as usize,
            )
        })
    }

    fn bind_pose_mut(&mut self) -> Option<&mut [crate::math::Transform]> {
        if self.as_ref().skeleton.bindPose.is_null() {
            return None;
        }
        Some(unsafe {
            std::slice::from_raw_parts_mut(
                self.as_mut().skeleton.bindPose as *mut crate::math::Transform,
                self.as_ref().skeleton.boneCount as usize,
            )
        })
    }

    /// Check model animation skeleton match
    #[inline]
    fn is_model_animation_valid(&self, anim: &ModelAnimation) -> bool {
        unsafe { ffi::IsModelAnimationValid(*self.as_ref(), anim.0) }
    }

    /// Check if a model is ready
    fn is_model_valid(&self) -> bool {
        unsafe { ffi::IsModelValid(*self.as_ref()) }
    }

    /// Compute model bounding box limits (considers all meshes)
    fn get_model_bounding_box(&self) -> BoundingBox {
        unsafe { BoundingBox::from(ffi::GetModelBoundingBox(*self.as_ref())) }
    }

    /// Set material for a mesh
    fn set_model_mesh_material(&mut self, mesh_id: i32, material_id: i32) -> Result<(), Error> {
        if mesh_id >= self.as_ref().meshCount {
            Err(error!("mesh_id greater than mesh count"))
        } else if material_id >= self.as_ref().materialCount {
            Err(error!("material_id greater than material count"))
        } else {
            unsafe { ffi::SetModelMeshMaterial(self.as_mut(), mesh_id, material_id) };
            Ok(())
        }
    }
}

impl RaylibMesh for WeakMesh {}
impl RaylibMesh for Mesh {}

impl Mesh {
    /// Convert into a [`WeakMesh`] that does not own the underlying resource.
    ///
    /// # Safety
    ///
    /// The caller becomes responsible for ensuring the returned `WeakMesh`
    /// does not outlive the GPU resources it references, and for explicitly
    /// unloading the mesh via [`RaylibHandle::unload_mesh`] when finished.
    /// Failing to do so will leak GPU memory.
    pub unsafe fn make_weak(self) -> WeakMesh {
        let m = WeakMesh(self.0);
        std::mem::forget(self);
        m
    }
}
pub trait RaylibMesh: AsRef<ffi::Mesh> + AsMut<ffi::Mesh> {
    /// Upload mesh vertex data to the GPU.
    ///
    /// # Safety
    ///
    /// Must be called on the main thread while a valid raylib context exists,
    /// as this calls into OpenGL via raylib. The mesh's CPU-side buffers must
    /// be valid and fully initialized.
    unsafe fn upload(&mut self, dynamic: bool) {
        ffi::UploadMesh(self.as_mut(), dynamic);
    }
    /// Update a GPU mesh buffer with new data.
    ///
    /// # Safety
    ///
    /// Must be called on the main thread while a valid raylib context exists.
    /// `index` must identify a valid buffer that has previously been uploaded
    /// with [`upload`], and `offset + data.len()` must not exceed the size of
    /// that buffer on the GPU.
    unsafe fn update_buffer<A>(&mut self, index: i32, data: &[u8], offset: i32) {
        ffi::UpdateMeshBuffer(
            *self.as_ref(),
            index,
            data.as_ptr() as *const c_void,
            data.len() as i32,
            offset,
        );
    }
    fn vertices(&self) -> &[Vector3] {
        NonNull::new(self.as_ref().vertices.cast()).map_or(&[], |data| unsafe {
            NonNull::slice_from_raw_parts(data, self.as_ref().vertexCount as usize).as_ref()
        })
    }
    fn vertices_mut(&mut self) -> &mut [Vector3] {
        NonNull::new(self.as_ref().vertices.cast()).map_or(&mut [], |data| unsafe {
            NonNull::slice_from_raw_parts(data, self.as_ref().vertexCount as usize).as_mut()
        })
    }
    fn normals(&self) -> &[Vector3] {
        NonNull::new(self.as_ref().normals.cast()).map_or(&[], |data| unsafe {
            NonNull::slice_from_raw_parts(data, self.as_ref().vertexCount as usize).as_ref()
        })
    }
    fn normals_mut(&mut self) -> &mut [Vector3] {
        NonNull::new(self.as_ref().normals.cast()).map_or(&mut [], |data| unsafe {
            NonNull::slice_from_raw_parts(data, self.as_ref().vertexCount as usize).as_mut()
        })
    }
    /// Per-vertex tangents. Each element is `(x, y, z, w)` where `w` carries
    /// the sign of the bitangent (mirror handedness). Previously returned
    /// `&[Vector3]`, which sliced only 3 of every 4 floats and produced
    /// misaligned reads. Corrected to `&[Vector4]` to match the underlying
    /// `float tangents[4 * vertexCount]` layout.
    fn tangents(&self) -> &[crate::math::Vector4] {
        NonNull::new(self.as_ref().tangents.cast()).map_or(&[], |data| unsafe {
            NonNull::slice_from_raw_parts(data, self.as_ref().vertexCount as usize).as_ref()
        })
    }
    fn tangents_mut(&mut self) -> &mut [crate::math::Vector4] {
        NonNull::new(self.as_ref().tangents.cast()).map_or(&mut [], |data| unsafe {
            NonNull::slice_from_raw_parts(data, self.as_ref().vertexCount as usize).as_mut()
        })
    }
    fn colors(&self) -> &[crate::color::Color] {
        NonNull::new(self.as_ref().colors as *mut crate::color::Color).map_or(&[], |data| unsafe {
            NonNull::slice_from_raw_parts(data, self.as_ref().vertexCount as usize).as_ref()
        })
    }
    fn colors_mut(&mut self) -> &mut [crate::color::Color] {
        NonNull::new(self.as_ref().colors as *mut crate::color::Color).map_or(
            &mut [],
            |data| unsafe {
                NonNull::slice_from_raw_parts(data, self.as_ref().vertexCount as usize).as_mut()
            },
        )
    }
    fn indices(&self) -> &[u16] {
        NonNull::new(self.as_ref().indices).map_or(&[], |data| unsafe {
            NonNull::slice_from_raw_parts(data, self.as_ref().triangleCount as usize * 3).as_ref()
        })
    }
    fn indices_mut(&mut self) -> &mut [u16] {
        NonNull::new(self.as_ref().indices).map_or(&mut [], |data| unsafe {
            NonNull::slice_from_raw_parts(data, self.as_ref().triangleCount as usize * 3).as_mut()
        })
    }

    /// Generate polygonal mesh
    #[inline]
    fn gen_mesh_poly(_: &RaylibThread, sides: i32, radius: f32) -> Mesh {
        unsafe { Mesh(ffi::GenMeshPoly(sides, radius)) }
    }

    /// Generates plane mesh (with subdivisions).
    #[inline]
    fn gen_mesh_plane(_: &RaylibThread, width: f32, length: f32, res_x: i32, res_z: i32) -> Mesh {
        unsafe { Mesh(ffi::GenMeshPlane(width, length, res_x, res_z)) }
    }

    /// Generates cuboid mesh.
    #[inline]
    fn gen_mesh_cube(_: &RaylibThread, width: f32, height: f32, length: f32) -> Mesh {
        unsafe { Mesh(ffi::GenMeshCube(width, height, length)) }
    }

    /// Generates sphere mesh (standard sphere).
    #[inline]
    fn gen_mesh_sphere(_: &RaylibThread, radius: f32, rings: i32, slices: i32) -> Mesh {
        unsafe { Mesh(ffi::GenMeshSphere(radius, rings, slices)) }
    }

    /// Generates half-sphere mesh (no bottom cap).
    #[inline]
    fn gen_mesh_hemisphere(_: &RaylibThread, radius: f32, rings: i32, slices: i32) -> Mesh {
        unsafe { Mesh(ffi::GenMeshHemiSphere(radius, rings, slices)) }
    }

    /// Generates cylinder mesh.
    #[inline]
    fn gen_mesh_cylinder(_: &RaylibThread, radius: f32, height: f32, slices: i32) -> Mesh {
        unsafe { Mesh(ffi::GenMeshCylinder(radius, height, slices)) }
    }

    /// Generates torus mesh.
    #[inline]
    fn gen_mesh_torus(_: &RaylibThread, radius: f32, size: f32, rad_seg: i32, sides: i32) -> Mesh {
        unsafe { Mesh(ffi::GenMeshTorus(radius, size, rad_seg, sides)) }
    }

    /// Generates trefoil knot mesh.
    #[inline]
    fn gen_mesh_knot(_: &RaylibThread, radius: f32, size: f32, rad_seg: i32, sides: i32) -> Mesh {
        unsafe { Mesh(ffi::GenMeshKnot(radius, size, rad_seg, sides)) }
    }

    /// Generates heightmap mesh from image data.
    #[inline]
    fn gen_mesh_heightmap(
        _: &RaylibThread,
        heightmap: &Image,
        size: impl Into<ffi::Vector3>,
    ) -> Mesh {
        unsafe { Mesh(ffi::GenMeshHeightmap(heightmap.0, size.into())) }
    }

    /// Generates cubes-based map mesh from image data.
    #[inline]
    fn gen_mesh_cubicmap(
        _: &RaylibThread,
        cubicmap: &Image,
        cube_size: impl Into<ffi::Vector3>,
    ) -> Mesh {
        unsafe { Mesh(ffi::GenMeshCubicmap(cubicmap.0, cube_size.into())) }
    }

    /// Generate cone/pyramid mesh
    fn gen_mesh_cone(_: &RaylibThread, radius: f32, height: f32, slices: i32) -> Mesh {
        unsafe { Mesh(ffi::GenMeshCone(radius, height, slices)) }
    }

    /// Computes mesh bounding box limits.
    #[inline]
    fn get_mesh_bounding_box(&self) -> BoundingBox {
        unsafe { ffi::GetMeshBoundingBox(*self.as_ref()).into() }
    }

    /// Computes mesh tangents.
    // NOTE: New VBO for tangents is generated at default location and also binded to mesh VAO
    #[inline]
    fn gen_mesh_tangents(&mut self, _: &RaylibThread) {
        unsafe {
            ffi::GenMeshTangents(self.as_mut());
        }
    }

    /// Exports mesh as an OBJ file.
    #[inline]
    fn export(&self, filename: &str) {
        let c_filename = CString::new(filename).unwrap();
        unsafe {
            ffi::ExportMesh(*self.as_ref(), c_filename.as_ptr());
        }
    }

    /// Export mesh as code file (.h) defining multiple arrays of vertex attributes
    #[inline]
    fn export_as_code(&self, filename: &str) {
        let c_filename = CString::new(filename).unwrap();
        unsafe {
            ffi::ExportMeshAsCode(*self.as_ref(), c_filename.as_ptr());
        }
    }
}

impl Material {
    /// Convert into a [`WeakMaterial`] that does not own the underlying resource.
    ///
    /// # Safety
    ///
    /// The caller becomes responsible for ensuring the returned `WeakMaterial`
    /// does not outlive the GPU resources it references, and for explicitly
    /// unloading the material via [`RaylibHandle::unload_material`] when
    /// finished. Failing to do so will leak GPU memory.
    pub unsafe fn make_weak(self) -> WeakMaterial {
        let m = WeakMaterial(self.0);
        std::mem::forget(self);
        m
    }

    pub fn load_materials(filename: &str) -> Result<Vec<Material>, Error> {
        let c_filename = CString::new(filename).unwrap();
        let mut m_size = 0;
        let m_ptr = unsafe { ffi::LoadMaterials(c_filename.as_ptr(), &mut m_size) };
        if m_size <= 0 {
            return Err(error!("No materials loaded", filename));
        }
        let mut m_vec = Vec::with_capacity(m_size as usize);
        for i in 0..m_size {
            unsafe {
                m_vec.push(Material(*m_ptr.offset(i as isize)));
            }
        }
        unsafe {
            ffi::MemFree(m_ptr as *mut ::std::os::raw::c_void);
        }
        Ok(m_vec)
    }
}

impl RaylibMaterial for WeakMaterial {}
impl RaylibMaterial for Material {}

pub trait RaylibMaterial: AsRef<ffi::Material> + AsMut<ffi::Material> {
    fn shader(&self) -> &crate::shaders::WeakShader {
        unsafe { std::mem::transmute(&self.as_ref().shader) }
    }

    fn shader_mut(&mut self) -> &mut crate::shaders::WeakShader {
        unsafe { std::mem::transmute(&mut self.as_mut().shader) }
    }

    fn maps(&self) -> &[MaterialMap] {
        unsafe {
            std::slice::from_raw_parts(
                self.as_ref().maps as *const MaterialMap,
                consts::MAX_MATERIAL_MAPS as usize,
            )
        }
    }

    fn maps_mut(&mut self) -> &mut [MaterialMap] {
        unsafe {
            std::slice::from_raw_parts_mut(
                self.as_mut().maps as *mut MaterialMap,
                consts::MAX_MATERIAL_MAPS as usize,
            )
        }
    }

    fn set_material_texture(
        &mut self,
        map_type: crate::consts::MaterialMapIndex,
        texture: impl AsRef<ffi::Texture2D>,
    ) {
        unsafe {
            ffi::SetMaterialTexture(self.as_mut(), (map_type as u32) as i32, *texture.as_ref())
        }
    }

    fn is_material_valid(&mut self) -> bool {
        unsafe { ffi::IsMaterialValid(*self.as_ref()) }
    }
}

impl RaylibModelAnimation for ModelAnimation {}
impl RaylibModelAnimation for WeakModelAnimation {}

impl ModelAnimation {
    /// Convert into a [`WeakModelAnimation`] that does not own the underlying
    /// resource.
    ///
    /// # Safety
    ///
    /// The caller becomes responsible for ensuring the returned
    /// `WeakModelAnimation` does not outlive the underlying data, and for
    /// explicitly unloading the animation via
    /// [`RaylibHandle::unload_model_animation`] when finished. Failing to do
    /// so will leak memory.
    pub unsafe fn make_weak(self) -> WeakModelAnimation {
        let m = WeakModelAnimation(self.0);
        std::mem::forget(self);
        m
    }
}

pub trait RaylibModelAnimation: AsRef<ffi::ModelAnimation> + AsMut<ffi::ModelAnimation> {
    // raylib 6.0 removed `bones` from `ModelAnimation` — bones now live on
    // the parent `Model`'s `skeleton`. Access via `RaylibModel::bones()`.
    fn keyframe_poses(&self) -> Vec<&[crate::math::Transform]> {
        let anim = self.as_ref();
        let mut top = Vec::with_capacity(anim.keyframeCount as usize);

        for i in 0..anim.keyframeCount {
            top.push(unsafe {
                std::slice::from_raw_parts(
                    *(anim.keyframePoses.offset(i as isize)
                        as *const *const crate::math::Transform),
                    anim.boneCount as usize,
                )
            });
        }

        top
    }

    fn keyframe_poses_mut(&mut self) -> Vec<&mut [crate::math::Transform]> {
        let anim = self.as_ref();
        let mut top = Vec::with_capacity(anim.keyframeCount as usize);

        for i in 0..anim.keyframeCount {
            top.push(unsafe {
                std::slice::from_raw_parts_mut(
                    *(anim.keyframePoses.offset(i as isize) as *mut *mut crate::math::Transform),
                    anim.boneCount as usize,
                )
            });
        }

        top
    }
}

impl MaterialMap {
    pub fn texture(&self) -> &crate::texture::WeakTexture2D {
        unsafe { std::mem::transmute(&self.0.texture) }
    }
    pub fn texture_mut(&mut self) -> &mut crate::texture::WeakTexture2D {
        unsafe { std::mem::transmute(&mut self.0.texture) }
    }

    pub fn color(&self) -> &crate::color::Color {
        unsafe { std::mem::transmute(&self.0.color) }
    }
    pub fn color_mut(&mut self) -> &mut crate::color::Color {
        unsafe { std::mem::transmute(&mut self.0.color) }
    }

    pub fn value(&self) -> &f32 {
        unsafe { std::mem::transmute(&self.0.value) }
    }
    pub fn value_mut(&mut self) -> &mut f32 {
        unsafe { std::mem::transmute(&mut self.0.value) }
    }
}

impl RaylibHandle {
    pub fn load_material_default(&self, _: &RaylibThread) -> WeakMaterial {
        WeakMaterial(unsafe { ffi::LoadMaterialDefault() })
    }

    /// Weak materials will leak memeory if they are not unlaoded
    /// Unload material from GPU memory (VRAM)
    ///
    /// # Safety
    ///
    /// `material` must be a valid, currently-loaded material that has not
    /// already been unloaded. After this call the GPU resources backing
    /// `material` are freed, so any other `WeakMaterial` copies referring to
    /// the same material must no longer be used.
    pub unsafe fn unload_material(&mut self, _: &RaylibThread, material: WeakMaterial) {
        {
            ffi::UnloadMaterial(*material.as_ref())
        }
    }

    /// Weak models will leak memeory if they are not unlaoded
    /// Unload model from GPU memory (VRAM)
    ///
    /// # Safety
    ///
    /// `model` must be a valid, currently-loaded model that has not already
    /// been unloaded. After this call the GPU resources backing `model` are
    /// freed, so any other `WeakModel` copies referring to the same model
    /// must no longer be used.
    pub unsafe fn unload_model(&mut self, _: &RaylibThread, model: WeakModel) {
        {
            ffi::UnloadModel(*model.as_ref())
        }
    }

    /// Weak model_animations will leak memeory if they are not unlaoded
    /// Unload model_animation from GPU memory (VRAM)
    ///
    /// # Safety
    ///
    /// `model_animation` must be a valid, currently-loaded animation that has
    /// not already been unloaded. After this call the memory backing
    /// `model_animation` is freed, so any other `WeakModelAnimation` copies
    /// referring to the same animation must no longer be used.
    pub unsafe fn unload_model_animation(
        &mut self,
        _: &RaylibThread,
        model_animation: WeakModelAnimation,
    ) {
        // Mirror the per-animation inner cleanup from raylib 6.0's
        // `UnloadModelAnimations` without freeing the struct itself.
        let anim = *model_animation.as_ref();
        for i in 0..anim.keyframeCount {
            ffi::MemFree(*anim.keyframePoses.offset(i as isize) as *mut c_void);
        }
        ffi::MemFree(anim.keyframePoses as *mut c_void);
    }

    /// Weak meshs will leak memeory if they are not unlaoded
    /// Unload mesh from GPU memory (VRAM)
    ///
    /// # Safety
    ///
    /// `mesh` must be a valid, currently-loaded mesh that has not already
    /// been unloaded. After this call the GPU resources backing `mesh` are
    /// freed, so any other `WeakMesh` copies referring to the same mesh must
    /// no longer be used.
    pub unsafe fn unload_mesh(&mut self, _: &RaylibThread, mesh: WeakMesh) {
        {
            ffi::UnloadMesh(*mesh.as_ref())
        }
    }
}

#[cfg(test)]
mod mesh_tests {
    use super::{RaylibMesh, WeakMesh};
    use crate::ffi;
    use crate::math::Vector4;

    /// Regression test for the pre-6.0.0 tangents bug: raylib stores
    /// tangents as `float[4 * vertexCount]` (XYZW), but the safe wrapper
    /// used to cast the buffer to `*const Vector3` and read 3/4 of each
    /// tangent with wrong component alignment. Now returns `&[Vector4]`
    /// with `vertexCount` elements, each holding the full XYZW.
    #[test]
    fn tangents_returns_vector4_per_vertex() {
        const N: i32 = 3;
        let mut buf: Vec<f32> = vec![
            1.0, 2.0, 3.0, 4.0, //
            5.0, 6.0, 7.0, 8.0, //
            9.0, 10.0, 11.0, 12.0,
        ];

        // SAFETY: `ffi::Mesh` is POD-shaped (primitives + raw pointers), so
        // `zeroed` yields a valid value. `WeakMesh` has a no-op `Drop`, so
        // nothing tries to free the borrowed buffer.
        let mesh = unsafe {
            let mut m: ffi::Mesh = std::mem::zeroed();
            m.vertexCount = N;
            m.tangents = buf.as_mut_ptr();
            WeakMesh::from_raw(m)
        };

        let tangents = mesh.tangents();
        assert_eq!(tangents.len(), N as usize);
        assert_eq!(
            tangents[0],
            Vector4 {
                x: 1.0,
                y: 2.0,
                z: 3.0,
                w: 4.0
            }
        );
        assert_eq!(
            tangents[1],
            Vector4 {
                x: 5.0,
                y: 6.0,
                z: 7.0,
                w: 8.0
            }
        );
        assert_eq!(
            tangents[2],
            Vector4 {
                x: 9.0,
                y: 10.0,
                z: 11.0,
                w: 12.0
            }
        );
    }

    #[test]
    fn tangents_empty_when_pointer_null() {
        let mesh = unsafe {
            let mut m: ffi::Mesh = std::mem::zeroed();
            m.vertexCount = 42;
            m.tangents = std::ptr::null_mut();
            WeakMesh::from_raw(m)
        };
        assert!(mesh.tangents().is_empty());
    }
}