Using Rc reference counter smart pointer, to have shared resources

This commit is contained in:
Stephan Rehfeld 2026-05-27 18:20:19 +02:00
parent 585af00665
commit 50eabecfe9

View File

@ -1,6 +1,8 @@
use hello::geometry::{self, Geometry, Sphere}; use hello::geometry::{self, Geometry, Sphere};
use hello::math::{Mat4x4, Point3}; use hello::math::{Mat4x4, Point3};
use std::rc::Rc;
#[derive(Clone)] #[derive(Clone)]
struct RGB { struct RGB {
red: f64, red: f64,
@ -43,11 +45,11 @@ impl Texture {
struct RenderableGeometry { struct RenderableGeometry {
transform: Mat4x4, transform: Mat4x4,
geometry: Geometry, geometry: Geometry,
texture: Texture, texture: Rc<Texture>,
} }
impl RenderableGeometry { impl RenderableGeometry {
fn new(transform: Mat4x4, geometry: Geometry, texture: Texture) -> RenderableGeometry { fn new(transform: Mat4x4, geometry: Geometry, texture: Rc<Texture>) -> RenderableGeometry {
RenderableGeometry { RenderableGeometry {
transform, transform,
geometry, geometry,
@ -57,7 +59,7 @@ impl RenderableGeometry {
} }
fn main() { fn main() {
let tex = Texture::load_texture(); let tex = Rc::new(Texture::load_texture());
let geo1 = RenderableGeometry::new( let geo1 = RenderableGeometry::new(
Mat4x4::ident(), Mat4x4::ident(),
@ -76,4 +78,6 @@ fn main() {
Geometry::Sphere(Sphere::new(Point3::new(2.0, 0.0, 0.0), 1.0)), Geometry::Sphere(Sphere::new(Point3::new(2.0, 0.0, 0.0), 1.0)),
tex.clone(), tex.clone(),
); );
println!("Reference counter = {}", Rc::strong_count(&tex));
} }