From d50f3ed019eb8a36fc676d01e074006262571f7e Mon Sep 17 00:00:00 2001 From: bitten2up Date: Wed, 13 Dec 2023 20:58:35 +0000 Subject: [PATCH 01/93] well that also works ig --- raylib-sys/Cargo.toml | 2 +- raylib-test/Cargo.toml | 4 ++-- raylib/Cargo.toml | 4 ++-- samples/Cargo.toml | 4 ++-- showcase/Cargo.toml | 4 ++-- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/raylib-sys/Cargo.toml b/raylib-sys/Cargo.toml index f1ec1a0e..d62e2f73 100644 --- a/raylib-sys/Cargo.toml +++ b/raylib-sys/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "raylib-sys" -version = "5.0.0" +version = "5.1.0" authors = ["DeltaPHC "] license = "Zlib" description = "Raw FFI bindings for Raylib" diff --git a/raylib-test/Cargo.toml b/raylib-test/Cargo.toml index 187aa789..909b04b1 100644 --- a/raylib-test/Cargo.toml +++ b/raylib-test/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "raylib-test" -version = "5.0.0" +version = "5.1.0" authors = ["David Ayeke"] edition = "2018" license = "Zlib" @@ -9,5 +9,5 @@ repository = "https://github.com/deltaphc/raylib-rs" [dependencies] -raylib = { version = "5.0.0", path = "../raylib" } +raylib = { version = "5.1.0", path = "../raylib" } lazy_static = "1.2.0" diff --git a/raylib/Cargo.toml b/raylib/Cargo.toml index 472510e0..a9585863 100644 --- a/raylib/Cargo.toml +++ b/raylib/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "raylib" -version = "5.0.0" +version = "5.1.0" authors = ["DeltaPHC "] license = "Zlib" readme = "../README.md" @@ -12,7 +12,7 @@ categories = ["api-bindings", "game-engines", "graphics"] edition = "2018" [dependencies] -raylib-sys = { version = "5.0.0", path = "../raylib-sys" } +raylib-sys = { version = "5.1.0", path = "../raylib-sys" } libc = "0.2.45" lazy_static = "1.2.0" cfg-if = "1.0.0" diff --git a/samples/Cargo.toml b/samples/Cargo.toml index 3660c34c..5955f037 100644 --- a/samples/Cargo.toml +++ b/samples/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "raylib-examples" -version = "5.0.0" +version = "5.1.0" authors = ["David Ayeke"] edition = "2018" license = "Zlib" @@ -9,7 +9,7 @@ repository = "https://github.com/deltaphc/raylib-rs" [dependencies] -raylib = { version = "5.0.0", path = "../raylib" } +raylib = { version = "5.1-dev", path = "../raylib" } structopt = "0.2" specs-derive = "0.4.1" rand = "0.8.5" diff --git a/showcase/Cargo.toml b/showcase/Cargo.toml index 7d625c19..0cdb9d0f 100644 --- a/showcase/Cargo.toml +++ b/showcase/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "raylib-showcase" -version = "5.0.0" +version = "5.1.0" authors = ["David Ayeke"] edition = "2018" license = "Zlib" @@ -10,4 +10,4 @@ repository = "https://github.com/deltaphc/raylib-rs" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -raylib = { version = "5.0", path = "../raylib" } \ No newline at end of file +raylib = { version = "5.1.0", path = "../raylib" } \ No newline at end of file From 7494295b2fd8672825a39eaf5b825d48d36b519e Mon Sep 17 00:00:00 2001 From: bitten2up Date: Wed, 13 Dec 2023 21:00:45 +0000 Subject: [PATCH 02/93] oops --- raylib-sys/raylib | 2 +- raylib/src/core/drawing.rs | 20 -------------------- 2 files changed, 1 insertion(+), 21 deletions(-) diff --git a/raylib-sys/raylib b/raylib-sys/raylib index 1327b570..9322ad0f 160000 --- a/raylib-sys/raylib +++ b/raylib-sys/raylib @@ -1 +1 @@ -Subproject commit 1327b570e3aac6111ebdb3b233b9c60cdc12ee9f +Subproject commit 9322ad0f9bbc7ce1a7f94109dd89c5082ac483fe diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index b915974c..079ef69b 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -375,26 +375,6 @@ pub trait RaylibDraw { ffi::DrawLineBezier(start_pos.into(), end_pos.into(), thick, color.into()); } } - /// Draw line using quadratic bezier curves with a control point - #[inline] - fn draw_line_bezier_quad( - &mut self, - start_pos: impl Into, - end_pos: impl Into, - control_pos: impl Into, - thick: f32, - color: impl Into, - ) { - unsafe { - ffi::DrawLineBezierQuad( - start_pos.into(), - end_pos.into(), - control_pos.into(), - thick, - color.into(), - ); - } - } /// Draw lines sequence #[inline] From 6a9e404b5c977f34b2116d5460769febcaa53ba1 Mon Sep 17 00:00:00 2001 From: bitten2up Date: Thu, 14 Dec 2023 09:36:30 -0600 Subject: [PATCH 03/93] remove some documentation --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 3ec45f24..6583d93a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,3 @@ -# Remember to fix the examples befor creating a pullrequest, also rename the branch to 2.5.0 ![logo](logo/raylib-rust_256x256.png) ![rust](https://img.shields.io/badge/rust-1.31+-orange.svg?style=flat-square&logo=rust) From 2ac057b05491f4a830e5c91d5ab280f3512e124a Mon Sep 17 00:00:00 2001 From: IoIxD <30945097+IoIxD@users.noreply.github.com> Date: Sun, 2 Jun 2024 15:25:12 -0700 Subject: [PATCH 04/93] Merge old 5.1.0 commits into new 5.1.0 branch (#52) * well that also works ig * oops * remove some documentation --------- Co-authored-by: bitten2up --- README.md | 6 ++++++ raylib-sys/Cargo.toml | 2 +- raylib-test/Cargo.toml | 4 ++-- raylib/Cargo.toml | 4 ++-- samples/Cargo.toml | 6 +++++- showcase/Cargo.toml | 6 +++++- 6 files changed, 21 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 602a788e..70670da3 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,12 @@ +<<<<<<< HEAD +![logo](logo/raylib-rust_256x256.png) + +![rust](https://img.shields.io/badge/rust-1.31+-orange.svg?style=flat-square&logo=rust) +=======

![rust](https://img.shields.io/badge/rust-1.77+-orange.svg?style=flat-square&logo=rust) +>>>>>>> origin/5.1.0 [![crates.io](https://img.shields.io/crates/v/raylib.svg?style=flat-square)](https://crates.io/crates/raylib) [![docs](https://docs.rs/raylib/badge.svg)](https://docs.rs/raylib) [![discord](https://img.shields.io/discord/426912293134270465)](https://discord.gg/VkzNHUE) diff --git a/raylib-sys/Cargo.toml b/raylib-sys/Cargo.toml index ec764e76..90ee6b95 100644 --- a/raylib-sys/Cargo.toml +++ b/raylib-sys/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "raylib-sys" -version = "5.0.1" +version = "5.1.0" authors = ["DeltaPHC "] license = "Zlib" description = "Raw FFI bindings for Raylib" diff --git a/raylib-test/Cargo.toml b/raylib-test/Cargo.toml index 14fe4b17..f389105f 100644 --- a/raylib-test/Cargo.toml +++ b/raylib-test/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "raylib-test" -version = "5.0.1" +version = "5.1.0" authors = ["David Ayeke"] edition = "2018" license = "Zlib" @@ -9,7 +9,7 @@ repository = "https://github.com/raylib-rs/raylib-rs" [dependencies] -raylib = { version = "5.0.0", path = "../raylib" } +raylib = { version = "5.1.0", path = "../raylib" } lazy_static = "1.2.0" colored = "2.1.0" diff --git a/raylib/Cargo.toml b/raylib/Cargo.toml index 3a5cb773..05ecb63f 100644 --- a/raylib/Cargo.toml +++ b/raylib/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "raylib" -version = "5.0.1" +version = "5.1.0" authors = ["DeltaPHC "] license = "Zlib" readme = "../README.md" @@ -13,7 +13,7 @@ edition = "2018" autoexamples = false [dependencies] -raylib-sys = { version = "5.0.0", path = "../raylib-sys" } +raylib-sys = { version = "5.1.0", path = "../raylib-sys" } libc = "0.2.45" lazy_static = "1.2.0" cfg-if = "1.0.0" diff --git a/samples/Cargo.toml b/samples/Cargo.toml index 03e18c9f..dd4a4969 100644 --- a/samples/Cargo.toml +++ b/samples/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "raylib-examples" -version = "5.0.1" +version = "5.1.0" authors = ["David Ayeke"] edition = "2018" license = "Zlib" @@ -9,7 +9,11 @@ repository = "https://github.com/raylib-rs/raylib-rs" [dependencies] +<<<<<<< HEAD +raylib = { version = "5.1-dev", path = "../raylib" } +======= raylib = { version = "5.0", path = "../raylib" } +>>>>>>> origin/5.1.0 structopt = "0.2" specs-derive = "0.4.1" rand = "0.7" diff --git a/showcase/Cargo.toml b/showcase/Cargo.toml index f13c6e92..68808cb6 100644 --- a/showcase/Cargo.toml +++ b/showcase/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "raylib-showcase" -version = "5.0.1" +version = "5.1.0" authors = ["David Ayeke"] edition = "2018" license = "Zlib" @@ -10,4 +10,8 @@ repository = "https://github.com/raylib-rs/raylib-rs" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +<<<<<<< HEAD +raylib = { version = "5.1.0", path = "../raylib" } +======= raylib = { version = "5.0", path = "../raylib" } +>>>>>>> origin/5.1.0 From 3efccc29d484eedc3e2afa0ea589830ad76cf611 Mon Sep 17 00:00:00 2001 From: IoIxD Date: Sun, 2 Jun 2024 15:34:29 -0700 Subject: [PATCH 05/93] left some merge conflicts in by accident --- README.md | 8 +------- samples/Cargo.toml | 6 +----- showcase/Cargo.toml | 4 ---- 3 files changed, 2 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 70670da3..2ca33af3 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,6 @@ -<<<<<<< HEAD -![logo](logo/raylib-rust_256x256.png) - -![rust](https://img.shields.io/badge/rust-1.31+-orange.svg?style=flat-square&logo=rust) -=======

-![rust](https://img.shields.io/badge/rust-1.77+-orange.svg?style=flat-square&logo=rust) ->>>>>>> origin/5.1.0 +![rust](https://img.shields.io/badge/rust-1.78+-orange.svg?style=flat-square&logo=rust) [![crates.io](https://img.shields.io/crates/v/raylib.svg?style=flat-square)](https://crates.io/crates/raylib) [![docs](https://docs.rs/raylib/badge.svg)](https://docs.rs/raylib) [![discord](https://img.shields.io/discord/426912293134270465)](https://discord.gg/VkzNHUE) diff --git a/samples/Cargo.toml b/samples/Cargo.toml index dd4a4969..2e616830 100644 --- a/samples/Cargo.toml +++ b/samples/Cargo.toml @@ -9,11 +9,7 @@ repository = "https://github.com/raylib-rs/raylib-rs" [dependencies] -<<<<<<< HEAD -raylib = { version = "5.1-dev", path = "../raylib" } -======= -raylib = { version = "5.0", path = "../raylib" } ->>>>>>> origin/5.1.0 +raylib = { version = "5.1.0", path = "../raylib" } structopt = "0.2" specs-derive = "0.4.1" rand = "0.7" diff --git a/showcase/Cargo.toml b/showcase/Cargo.toml index 68808cb6..60ff0031 100644 --- a/showcase/Cargo.toml +++ b/showcase/Cargo.toml @@ -10,8 +10,4 @@ repository = "https://github.com/raylib-rs/raylib-rs" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -<<<<<<< HEAD raylib = { version = "5.1.0", path = "../raylib" } -======= -raylib = { version = "5.0", path = "../raylib" } ->>>>>>> origin/5.1.0 From 29cb99e43cc431866d36a0686e009761937afd06 Mon Sep 17 00:00:00 2001 From: IoIxD Date: Sun, 2 Jun 2024 15:36:46 -0700 Subject: [PATCH 06/93] submodule bump --- raylib-sys/raylib | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/raylib-sys/raylib b/raylib-sys/raylib index ae50bfa2..11202bf2 160000 --- a/raylib-sys/raylib +++ b/raylib-sys/raylib @@ -1 +1 @@ -Subproject commit ae50bfa2cc569c0f8d5bc4315d39db64005b1b08 +Subproject commit 11202bf299a70a8ef30e28ab99a8184bbb119a99 From b3911511586b5f14e14f6c4eb0aebf3eb781daef Mon Sep 17 00:00:00 2001 From: Orangethewell Date: Sun, 2 Jun 2024 19:45:03 -0300 Subject: [PATCH 07/93] Fix: `draw_mesh` receives reference instead of owned value --- raylib/src/core/drawing.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index 079ef69b..8094140b 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -7,6 +7,8 @@ use crate::core::texture::Texture2D; use crate::core::vr::VrStereoConfig; use crate::core::{RaylibHandle, RaylibThread}; use crate::ffi; +use crate::math::Matrix; +use crate::models::WeakMaterial; use std::convert::AsRef; use std::ffi::CString; @@ -1120,6 +1122,22 @@ pub trait RaylibDraw3D { } } + /// Draw a 3d mesh with material and transform + #[inline] + fn draw_mesh(&mut self, mesh: impl AsRef, material: WeakMaterial, transform: Matrix) { + unsafe { ffi::DrawMesh(*mesh.as_ref(), material.0, transform.into()) } + } + + /// Draw multiple mesh instances with material and different transforms + #[inline] + fn draw_mesh_instanced(&mut self, mesh: impl AsRef, material: WeakMaterial, transforms: &[Matrix]) { + let tr = transforms + .iter() + .map(|f| f.into()) + .collect::>() + .as_ptr(); + unsafe { ffi::DrawMeshInstanced(*mesh.as_ref(), material.0, tr, transforms.len() as i32) } + } /// Draws a sphere. #[inline] From 39f5a12baceaf2795be621f5f5ad417a54e2b11a Mon Sep 17 00:00:00 2001 From: bitten2up Date: Wed, 13 Dec 2023 20:58:35 +0000 Subject: [PATCH 08/93] well that also works ig --- samples/Cargo.toml | 4 ++++ showcase/Cargo.toml | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/samples/Cargo.toml b/samples/Cargo.toml index 2e616830..5bf1f3fb 100644 --- a/samples/Cargo.toml +++ b/samples/Cargo.toml @@ -9,7 +9,11 @@ repository = "https://github.com/raylib-rs/raylib-rs" [dependencies] +<<<<<<< HEAD raylib = { version = "5.1.0", path = "../raylib" } +======= +raylib = { version = "5.1-dev", path = "../raylib" } +>>>>>>> d50f3ed (well that also works ig) structopt = "0.2" specs-derive = "0.4.1" rand = "0.7" diff --git a/showcase/Cargo.toml b/showcase/Cargo.toml index 60ff0031..646671e0 100644 --- a/showcase/Cargo.toml +++ b/showcase/Cargo.toml @@ -10,4 +10,8 @@ repository = "https://github.com/raylib-rs/raylib-rs" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +<<<<<<< HEAD raylib = { version = "5.1.0", path = "../raylib" } +======= +raylib = { version = "5.1.0", path = "../raylib" } +>>>>>>> d50f3ed (well that also works ig) From 774560ae941487a6587dc502800fa2ee51d73428 Mon Sep 17 00:00:00 2001 From: bitten2up Date: Thu, 14 Dec 2023 09:36:30 -0600 Subject: [PATCH 09/93] remove some documentation --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 2ca33af3..5413c56e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,12 @@ +<<<<<<< HEAD

![rust](https://img.shields.io/badge/rust-1.78+-orange.svg?style=flat-square&logo=rust) +======= +![logo](logo/raylib-rust_256x256.png) + +![rust](https://img.shields.io/badge/rust-1.31+-orange.svg?style=flat-square&logo=rust) +>>>>>>> 6a9e404 (remove some documentation) [![crates.io](https://img.shields.io/crates/v/raylib.svg?style=flat-square)](https://crates.io/crates/raylib) [![docs](https://docs.rs/raylib/badge.svg)](https://docs.rs/raylib) [![discord](https://img.shields.io/discord/426912293134270465)](https://discord.gg/VkzNHUE) From 13b8c5e58d9d5fbe2781c72ede39235796cd6fdd Mon Sep 17 00:00:00 2001 From: Orangethewell Date: Sun, 2 Jun 2024 19:45:03 -0300 Subject: [PATCH 10/93] Fix: `draw_mesh` receives reference instead of owned value --- raylib/src/core/drawing.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index a73514d4..6d4ddc04 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -9,8 +9,12 @@ use crate::core::vr::VrStereoConfig; use crate::core::{RaylibHandle, RaylibThread}; use crate::ffi; use crate::math::Matrix; +<<<<<<< HEAD use crate::models::{Mesh, WeakMaterial}; use crate::text::Codepoints; +======= +use crate::models::WeakMaterial; +>>>>>>> b391151 (Fix: `draw_mesh` receives reference instead of owned value) use std::convert::AsRef; use std::ffi::CString; @@ -1435,19 +1439,32 @@ pub trait RaylibDraw3D { /// Draw a 3d mesh with material and transform #[inline] +<<<<<<< HEAD fn draw_mesh(&mut self, mesh: Mesh, material: WeakMaterial, transform: Matrix) { unsafe { ffi::DrawMesh(mesh.0, material.0, transform.into()) } +======= + fn draw_mesh(&mut self, mesh: impl AsRef, material: WeakMaterial, transform: Matrix) { + unsafe { ffi::DrawMesh(*mesh.as_ref(), material.0, transform.into()) } +>>>>>>> b391151 (Fix: `draw_mesh` receives reference instead of owned value) } /// Draw multiple mesh instances with material and different transforms #[inline] +<<<<<<< HEAD fn draw_mesh_instanced(&mut self, mesh: Mesh, material: WeakMaterial, transforms: &[Matrix]) { +======= + fn draw_mesh_instanced(&mut self, mesh: impl AsRef, material: WeakMaterial, transforms: &[Matrix]) { +>>>>>>> b391151 (Fix: `draw_mesh` receives reference instead of owned value) let tr = transforms .iter() .map(|f| f.into()) .collect::>() .as_ptr(); +<<<<<<< HEAD unsafe { ffi::DrawMeshInstanced(mesh.0, material.0, tr, transforms.len() as i32) } +======= + unsafe { ffi::DrawMeshInstanced(*mesh.as_ref(), material.0, tr, transforms.len() as i32) } +>>>>>>> b391151 (Fix: `draw_mesh` receives reference instead of owned value) } /// Draws a sphere. From f8a3fc280be6706d1cc26f334c5f0fc3153d0427 Mon Sep 17 00:00:00 2001 From: Orangethewell Date: Sun, 2 Jun 2024 20:11:52 -0300 Subject: [PATCH 11/93] fix conflicts --- README.md | 10 +--------- raylib/src/core/drawing.rs | 34 ---------------------------------- samples/Cargo.toml | 8 -------- showcase/Cargo.toml | 8 -------- 4 files changed, 1 insertion(+), 59 deletions(-) diff --git a/README.md b/README.md index 9b868455..0ee3a9d9 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,7 @@ -<<<<<<< HEAD -======= -<<<<<<< HEAD

- + ![rust](https://img.shields.io/badge/rust-1.78+-orange.svg?style=flat-square&logo=rust) -======= ->>>>>>> raylib-rs-5.1.0 ![logo](logo/raylib-rust_256x256.png) - -![rust](https://img.shields.io/badge/rust-1.31+-orange.svg?style=flat-square&logo=rust) ->>>>>>> 6a9e404 (remove some documentation) [![crates.io](https://img.shields.io/crates/v/raylib.svg?style=flat-square)](https://crates.io/crates/raylib) [![docs](https://docs.rs/raylib/badge.svg)](https://docs.rs/raylib) [![discord](https://img.shields.io/discord/426912293134270465)](https://discord.gg/VkzNHUE) diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index d736ae29..be1f50cc 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -9,16 +9,8 @@ use crate::core::vr::VrStereoConfig; use crate::core::{RaylibHandle, RaylibThread}; use crate::ffi; use crate::math::Matrix; -<<<<<<< HEAD -use crate::models::WeakMaterial; -======= -<<<<<<< HEAD use crate::models::{Mesh, WeakMaterial}; use crate::text::Codepoints; -======= -use crate::models::WeakMaterial; ->>>>>>> b391151 (Fix: `draw_mesh` receives reference instead of owned value) ->>>>>>> raylib-rs-5.1.0 use std::convert::AsRef; use std::ffi::CString; @@ -1443,45 +1435,19 @@ pub trait RaylibDraw3D { /// Draw a 3d mesh with material and transform #[inline] -<<<<<<< HEAD fn draw_mesh(&mut self, mesh: impl AsRef, material: WeakMaterial, transform: Matrix) { unsafe { ffi::DrawMesh(*mesh.as_ref(), material.0, transform.into()) } -======= -<<<<<<< HEAD - fn draw_mesh(&mut self, mesh: Mesh, material: WeakMaterial, transform: Matrix) { - unsafe { ffi::DrawMesh(mesh.0, material.0, transform.into()) } -======= - fn draw_mesh(&mut self, mesh: impl AsRef, material: WeakMaterial, transform: Matrix) { - unsafe { ffi::DrawMesh(*mesh.as_ref(), material.0, transform.into()) } ->>>>>>> b391151 (Fix: `draw_mesh` receives reference instead of owned value) ->>>>>>> raylib-rs-5.1.0 } /// Draw multiple mesh instances with material and different transforms #[inline] -<<<<<<< HEAD fn draw_mesh_instanced(&mut self, mesh: impl AsRef, material: WeakMaterial, transforms: &[Matrix]) { -======= -<<<<<<< HEAD - fn draw_mesh_instanced(&mut self, mesh: Mesh, material: WeakMaterial, transforms: &[Matrix]) { -======= - fn draw_mesh_instanced(&mut self, mesh: impl AsRef, material: WeakMaterial, transforms: &[Matrix]) { ->>>>>>> b391151 (Fix: `draw_mesh` receives reference instead of owned value) ->>>>>>> raylib-rs-5.1.0 let tr = transforms .iter() .map(|f| f.into()) .collect::>() .as_ptr(); -<<<<<<< HEAD - unsafe { ffi::DrawMeshInstanced(*mesh.as_ref(), material.0, tr, transforms.len() as i32) } -======= -<<<<<<< HEAD - unsafe { ffi::DrawMeshInstanced(mesh.0, material.0, tr, transforms.len() as i32) } -======= unsafe { ffi::DrawMeshInstanced(*mesh.as_ref(), material.0, tr, transforms.len() as i32) } ->>>>>>> b391151 (Fix: `draw_mesh` receives reference instead of owned value) ->>>>>>> raylib-rs-5.1.0 } /// Draws a sphere. diff --git a/samples/Cargo.toml b/samples/Cargo.toml index 78b254e5..2e616830 100644 --- a/samples/Cargo.toml +++ b/samples/Cargo.toml @@ -9,15 +9,7 @@ repository = "https://github.com/raylib-rs/raylib-rs" [dependencies] -<<<<<<< HEAD -raylib = { version = "5.1-dev", path = "../raylib" } -======= -<<<<<<< HEAD raylib = { version = "5.1.0", path = "../raylib" } -======= -raylib = { version = "5.1-dev", path = "../raylib" } ->>>>>>> d50f3ed (well that also works ig) ->>>>>>> raylib-rs-5.1.0 structopt = "0.2" specs-derive = "0.4.1" rand = "0.7" diff --git a/showcase/Cargo.toml b/showcase/Cargo.toml index c4d8c0dd..60ff0031 100644 --- a/showcase/Cargo.toml +++ b/showcase/Cargo.toml @@ -10,12 +10,4 @@ repository = "https://github.com/raylib-rs/raylib-rs" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -<<<<<<< HEAD raylib = { version = "5.1.0", path = "../raylib" } -======= -<<<<<<< HEAD -raylib = { version = "5.1.0", path = "../raylib" } -======= -raylib = { version = "5.1.0", path = "../raylib" } ->>>>>>> d50f3ed (well that also works ig) ->>>>>>> raylib-rs-5.1.0 From 11112ee418aab624acb0adc9fb59a45d8f0f7a20 Mon Sep 17 00:00:00 2001 From: IoIxD Date: Sun, 2 Jun 2024 16:47:01 -0700 Subject: [PATCH 12/93] Initial fixes to get 5.1 building --- raylib/src/core/automation.rs | 4 ++-- raylib/src/core/drawing.rs | 9 +-------- raylib/src/core/vr.rs | 10 ++++------ raylib/src/core/window.rs | 11 ++++++++++- 4 files changed, 17 insertions(+), 17 deletions(-) diff --git a/raylib/src/core/automation.rs b/raylib/src/core/automation.rs index 375c79e6..8b5f51ba 100644 --- a/raylib/src/core/automation.rs +++ b/raylib/src/core/automation.rs @@ -1,5 +1,5 @@ use std::{ - ffi::{CString, OsString}, + ffi::CString, path::{Path, PathBuf}, ptr::null, }; @@ -8,7 +8,7 @@ use crate::{ffi, RaylibHandle}; fn unload_automation_event_list(mut s: ffi::AutomationEventList) { unsafe { - (ffi::UnloadAutomationEventList)(&mut s); + ffi::UnloadAutomationEventList(s); } } diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index a73514d4..3570106f 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -729,17 +729,10 @@ pub trait RaylibDraw { rec: impl Into, roundness: f32, segments: i32, - line_thickness: f32, color: impl Into, ) { unsafe { - ffi::DrawRectangleRoundedLines( - rec.into(), - roundness, - segments, - line_thickness, - color.into(), - ); + ffi::DrawRectangleRoundedLines(rec.into(), roundness, segments, color.into()); } } diff --git a/raylib/src/core/vr.rs b/raylib/src/core/vr.rs index d9a77c4e..8dac85c3 100644 --- a/raylib/src/core/vr.rs +++ b/raylib/src/core/vr.rs @@ -15,7 +15,6 @@ pub struct VrDeviceInfo { pub v_esolution: i32, // Vertical resolution in pixels pub h_screen_size: f32, // Horizontal size in meters pub v_screen_size: f32, // Vertical size in meters - pub v_screen_center: f32, // Screen center in meters pub eye_to_screen_distance: f32, // Distance between eye and display in meters pub lens_separation_distance: f32, // Lens separation distance in meters pub interpupillary_distance: f32, // IPD (distance between pupils) in meters @@ -38,11 +37,10 @@ impl Into for VrDeviceInfo { impl Into for &VrDeviceInfo { fn into(self) -> ffi::VrDeviceInfo { ffi::VrDeviceInfo { - hResolution: self.h_resolution, // Horizontal resolution in pixels - vResolution: self.v_esolution, // Vertical resolution in pixels - hScreenSize: self.h_screen_size, // Horizontal size in meters - vScreenSize: self.v_screen_size, // Vertical size in meters - vScreenCenter: self.v_screen_center, // Screen center in meters + hResolution: self.h_resolution, // Horizontal resolution in pixels + vResolution: self.v_esolution, // Vertical resolution in pixels + hScreenSize: self.h_screen_size, // Horizontal size in meters + vScreenSize: self.v_screen_size, // Vertical size in meters eyeToScreenDistance: self.eye_to_screen_distance, // Distance between eye and display in meters lensSeparationDistance: self.lens_separation_distance, // Lens separation distance in meters interpupillaryDistance: self.interpupillary_distance, // IPD (distance between pupils) in meters diff --git a/raylib/src/core/window.rs b/raylib/src/core/window.rs index 78f473ea..c034a8ff 100644 --- a/raylib/src/core/window.rs +++ b/raylib/src/core/window.rs @@ -422,12 +422,21 @@ impl RaylibHandle { // Screen-space-related functions impl RaylibHandle { /// Returns a ray trace from mouse position + #[deprecated = "Renamed to RaylibHandle::get_screen_to_world_ray"] pub fn get_mouse_ray( &self, mouse_position: impl Into, camera: impl Into, ) -> Ray { - unsafe { ffi::GetMouseRay(mouse_position.into(), camera.into()).into() } + unsafe { ffi::GetScreenToWorldRay(mouse_position.into(), camera.into()).into() } + } + + pub fn get_screen_to_world_ray( + &self, + mouse_position: impl Into, + camera: impl Into, + ) -> Ray { + unsafe { ffi::GetScreenToWorldRay(mouse_position.into(), camera.into()).into() } } /// Returns the screen space position for a 3d world space position From 256584c0217539f13bd579f651a04460aa91dd2d Mon Sep 17 00:00:00 2001 From: IoIxD Date: Sun, 2 Jun 2024 16:48:01 -0700 Subject: [PATCH 13/93] get rid of the lint --- .github/workflows/ci.yml | 26 -------------------------- 1 file changed, 26 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c1d0c100..23a1a72e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,29 +28,3 @@ jobs: run: sudo apt-get update; sudo apt-get install --no-install-recommends libasound2-dev libudev-dev libglfw3-dev libwayland-dev libsdl2-dev - name: Run doc tests with all features (this also compiles README examples) run: cargo test --doc --all-features - lint: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: actions/cache@v2 - with: - path: | - ~/.cargo/bin/ - ~/.cargo/registry/index/ - ~/.cargo/registry/cache/ - ~/.cargo/git/db/ - target/ - key: ubuntu-latest-cargo-build-stable-${{ hashFiles('**/Cargo.toml') }} - - uses: actions-rs/toolchain@v1 - with: - toolchain: stable - components: rustfmt, clippy - override: true - - name: Setup git submodules - run: git submodule init; git submodule update - - name: Install alsa, udev, glfw3, sdl, and wayland - run: sudo apt-get update; sudo apt-get install --no-install-recommends libasound2-dev libudev-dev libglfw3-dev libwayland-dev libsdl2-dev - - name: Run clippy - run: cargo clippy --workspace --all-targets --all-features - - name: Check format - run: cargo fmt --all -- --check From 3716554e423930cd2e2afd070a22ca16092344b0 Mon Sep 17 00:00:00 2001 From: IoIxD Date: Sun, 2 Jun 2024 17:06:00 -0700 Subject: [PATCH 14/93] wrote a small python script to check what functions need to be implemented --- find_unimplemented.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 find_unimplemented.py diff --git a/find_unimplemented.py b/find_unimplemented.py new file mode 100644 index 00000000..9c1fe547 --- /dev/null +++ b/find_unimplemented.py @@ -0,0 +1,22 @@ +import os + +src = os.scandir("./raylib/src/core/") +src_files = [] + +for file in src: + if file.is_file(follow_symlinks=True): + f = open(file.path) + src_files.append("\n".join(f.readlines())) + +d = open("./raylib-sys/raylib/src/raylib.h") +lines = list(filter(lambda f: f.startswith("RLAPI"),d.readlines())) + +for line in lines: + func_name = list(filter(lambda f: "(" in f, line.split(" ")))[0].split("(")[0].replace("*","") + in_a_file = False + for file in src_files: + if func_name in file: + in_a_file = True + break + if not in_a_file: + print("- [ ] "+func_name) \ No newline at end of file From ee6d42b2609bbe4c669baab973fa6e175139cb80 Mon Sep 17 00:00:00 2001 From: Orangethewell Date: Mon, 3 Jun 2024 09:34:32 -0300 Subject: [PATCH 15/93] Add `isShaderReady()` wrapper #56 --- raylib/src/core/shaders.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/raylib/src/core/shaders.rs b/raylib/src/core/shaders.rs index 221fde21..0b813453 100644 --- a/raylib/src/core/shaders.rs +++ b/raylib/src/core/shaders.rs @@ -184,6 +184,16 @@ impl Shader { m } + /// Check if shader is ready for usage + #[inline] + pub fn is_shader_ready(&self) { + unsafe { + ffi::IsShaderReady( + self.0, + ); + } + } + /// Sets shader uniform value #[inline] pub fn set_shader_value(&mut self, uniform_loc: i32, value: S) { @@ -197,7 +207,7 @@ impl Shader { } } - /// et shader uniform value vector + /// Set shader uniform value vector #[inline] pub fn set_shader_value_v(&mut self, uniform_loc: i32, value: &[S]) { unsafe { From 6172a7c7aecf8e97a810bf1704f40fec4520bf9d Mon Sep 17 00:00:00 2001 From: Orangethewell Date: Mon, 3 Jun 2024 09:38:07 -0300 Subject: [PATCH 16/93] Add `GetShaderLocationAttrib()` wrapper --- raylib/src/core/shaders.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/raylib/src/core/shaders.rs b/raylib/src/core/shaders.rs index 0b813453..ebf432c6 100644 --- a/raylib/src/core/shaders.rs +++ b/raylib/src/core/shaders.rs @@ -268,6 +268,18 @@ pub trait RaylibShader: AsRef + AsMut { unsafe { ffi::GetShaderLocation(*self.as_ref(), c_uniform_name.as_ptr()) } } + /// Gets shader attribute location by name. + #[inline] + fn get_shader_location_attribute(&self, attribute_name: &str) -> i32 { + let c_attribute_name = CString::new(attribute_name).unwrap(); + println!( + "Getting shader attribute {:?} {}", + c_attribute_name, + attribute_name.len() + ); + unsafe { ffi::GetShaderLocationAttrib(*self.as_ref(), c_attribute_name.as_ptr()) } + } + /// Sets shader uniform value #[inline] fn set_shader_value(&mut self, uniform_loc: i32, value: S) { From 80205cfa9ee37c1bd0156d756406e5e19b481008 Mon Sep 17 00:00:00 2001 From: Orangethewell Date: Mon, 3 Jun 2024 09:42:18 -0300 Subject: [PATCH 17/93] Add `DrawCircleLinesV()` wrapper --- raylib/src/core/drawing.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index cc5af0c4..d351e759 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -492,6 +492,19 @@ pub trait RaylibDraw { } } + /// Draws circle outline. (Vector Version) + #[inline] + fn draw_circle_lines( + &mut self, + center: impl Into, + radius: f32, + color: impl Into, + ) { + unsafe { + ffi::DrawCircleLinesV(center.into(), radius, color.into()); + } + } + /// Draws ellipse. #[inline] fn draw_ellipse( From c36dd4cb22f1a68be0d1ec976d0859a63586677f Mon Sep 17 00:00:00 2001 From: Orangethewell Date: Mon, 3 Jun 2024 09:44:04 -0300 Subject: [PATCH 18/93] Add `DrawCubeWiresV()` wrapper --- raylib/src/core/drawing.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index d351e759..11030cab 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -1439,6 +1439,19 @@ pub trait RaylibDraw3D { } } + /// Draws a cube in wireframe. (Vector Version) + #[inline] + fn draw_cube_wires_v( + &mut self, + position: impl Into, + size: impl Into, + color: impl Into, + ) { + unsafe { + ffi::DrawCubeWiresV(position.into(), size.into(), color.into()); + } + } + /// Draw a 3d mesh with material and transform #[inline] fn draw_mesh(&mut self, mesh: impl AsRef, material: WeakMaterial, transform: Matrix) { From 35d58119d70d0b769f20487c08791f0d67959090 Mon Sep 17 00:00:00 2001 From: Orangethewell Date: Mon, 3 Jun 2024 09:47:29 -0300 Subject: [PATCH 19/93] Add `DrawCylinderEx()` wrapper --- raylib/src/core/drawing.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index 11030cab..aadff01b 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -1535,6 +1535,29 @@ pub trait RaylibDraw3D { } } + /// Draws a cylinder with extended parameters. + #[inline] + fn draw_cylinder_ex( + &mut self, + start_position: impl Into, + end_position: impl Into, + radius_start: f32, + radius_end: f32, + slices: i32, + color: impl Into, + ) { + unsafe { + ffi::DrawCylinderEx( + start_position.into(), + end_position.into(), + radius_start, + radius_end, + slices, + color.into(), + ); + } + } + /// Draws a cylinder in wireframe. #[inline] fn draw_cylinder_wires( From 6127d2aaa82e9e0179b70013fba9b758be0f35b8 Mon Sep 17 00:00:00 2001 From: Orangethewell Date: Mon, 3 Jun 2024 09:49:31 -0300 Subject: [PATCH 20/93] Add `DrawCylinderWiresEx()` wrapper --- raylib/src/core/drawing.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index aadff01b..cdcaae10 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -1581,6 +1581,30 @@ pub trait RaylibDraw3D { } } + /// Draws a cylinder in wireframe with extended parameters. + #[inline] + fn draw_cylinder_wires_ex( + &mut self, + start_position: impl Into, + end_position: impl Into, + radius_start: f32, + radius_end: f32, + slices: i32, + color: impl Into, + ) { + unsafe { + ffi::DrawCylinderWiresEx( + start_position.into(), + end_position.into(), + radius_start, + radius_end, + slices, + color.into(), + ); + } + } + + /// Draws an X/Z plane. #[inline] fn draw_plane( From f0dfc5613cea3a969301c9219766d49e35b570de Mon Sep 17 00:00:00 2001 From: Orangethewell Date: Mon, 3 Jun 2024 09:52:42 -0300 Subject: [PATCH 21/93] Fix docs for `draw_rectangle_rounded_*` functions --- raylib/src/core/drawing.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index cdcaae10..92f2096f 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -721,7 +721,7 @@ pub trait RaylibDraw { ffi::DrawRectangleLinesEx(rec.into(), line_thick, color.into()); } } - /// Draws rectangle outline with extended parameters. + /// Draws rectangle with rounded edges. #[inline] fn draw_rectangle_rounded( &mut self, @@ -735,7 +735,7 @@ pub trait RaylibDraw { } } - /// Draws rectangle outline with extended parameters. + /// Draws rectangle outline with rounded edges included. #[inline] fn draw_rectangle_rounded_lines( &mut self, From d57f11602c40bb400d10baa33a058838e98b3df7 Mon Sep 17 00:00:00 2001 From: Orangethewell Date: Mon, 3 Jun 2024 09:55:30 -0300 Subject: [PATCH 22/93] Fix `draw_circle_lines_v()` missing name --- raylib/src/core/drawing.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index 92f2096f..af3434ad 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -494,7 +494,7 @@ pub trait RaylibDraw { /// Draws circle outline. (Vector Version) #[inline] - fn draw_circle_lines( + fn draw_circle_lines_v( &mut self, center: impl Into, radius: f32, From d8cc4d5f128f88834b729cf96a79e0bc4641858c Mon Sep 17 00:00:00 2001 From: Orangethewell Date: Tue, 4 Jun 2024 22:29:23 -0300 Subject: [PATCH 23/93] fix shader `is_ready` function name --- raylib/src/core/shaders.rs | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/raylib/src/core/shaders.rs b/raylib/src/core/shaders.rs index ebf432c6..2b5ddc5e 100644 --- a/raylib/src/core/shaders.rs +++ b/raylib/src/core/shaders.rs @@ -186,7 +186,7 @@ impl Shader { /// Check if shader is ready for usage #[inline] - pub fn is_shader_ready(&self) { + pub fn is_ready(&self) { unsafe { ffi::IsShaderReady( self.0, @@ -260,11 +260,6 @@ pub trait RaylibShader: AsRef + AsMut { #[inline] fn get_shader_location(&self, uniform_name: &str) -> i32 { let c_uniform_name = CString::new(uniform_name).unwrap(); - println!( - "Getting shader location {:?} {}", - c_uniform_name, - uniform_name.len() - ); unsafe { ffi::GetShaderLocation(*self.as_ref(), c_uniform_name.as_ptr()) } } @@ -272,11 +267,6 @@ pub trait RaylibShader: AsRef + AsMut { #[inline] fn get_shader_location_attribute(&self, attribute_name: &str) -> i32 { let c_attribute_name = CString::new(attribute_name).unwrap(); - println!( - "Getting shader attribute {:?} {}", - c_attribute_name, - attribute_name.len() - ); unsafe { ffi::GetShaderLocationAttrib(*self.as_ref(), c_attribute_name.as_ptr()) } } From 0dd73a03f4f66394078b32b47714c6023ea5d772 Mon Sep 17 00:00:00 2001 From: IoIxD Date: Wed, 5 Jun 2024 18:31:08 -0700 Subject: [PATCH 24/93] all: added basic functions --- find_unimplemented.py | 2 +- raylib/src/core/collision.rs | 11 +++++ raylib/src/core/drawing.rs | 88 +++++++++++++++++++++++++++++++++++- raylib/src/core/input.rs | 11 +++++ raylib/src/core/texture.rs | 12 ++++- raylib/src/core/window.rs | 44 ++++++++++++++++++ 6 files changed, 164 insertions(+), 4 deletions(-) diff --git a/find_unimplemented.py b/find_unimplemented.py index 9c1fe547..efee25ed 100644 --- a/find_unimplemented.py +++ b/find_unimplemented.py @@ -15,7 +15,7 @@ func_name = list(filter(lambda f: "(" in f, line.split(" ")))[0].split("(")[0].replace("*","") in_a_file = False for file in src_files: - if func_name in file: + if "ffi::"+func_name in file: in_a_file = True break if not in_a_file: diff --git a/raylib/src/core/collision.rs b/raylib/src/core/collision.rs index 581cb482..a19cfc55 100644 --- a/raylib/src/core/collision.rs +++ b/raylib/src/core/collision.rs @@ -41,6 +41,17 @@ impl Rectangle { pub fn check_collision_point_rec(&self, point: impl Into) -> bool { unsafe { ffi::CheckCollisionPointRec(point.into(), self.into()) } } + + /// Check if circle collides with a line created betweeen two points [p1] and [p2] + pub fn check_collision_circle_line( + &self, + center: impl Into, + radius: f32, + p1: impl Into, + p2: impl Into, + ) -> bool { + unsafe { ffi::CheckCollisionCircleLine(center.into(), radius, p1.into(), p2.into()) } + } } // Collision Handling diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index af3434ad..a1d610d1 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -1,5 +1,7 @@ //! Contains code related to drawing. Types that can be set as a surface to draw will implement the [`RaylibDraw`] trait +use raylib_sys::Rectangle; + use crate::core::camera::Camera3D; use crate::core::math::Ray; use crate::core::math::{Vector2, Vector3}; @@ -293,6 +295,16 @@ pub trait RaylibDraw { } } + /// Get texture that is used for shapes drawing + fn get_shapes_texture(&self) -> Texture2D { + Texture2D(unsafe { ffi::GetShapesTexture() }) + } + + /// Get texture source rectangle that is used for shapes drawing + fn get_shapes_texture_rectangle(&self) -> Rectangle { + unsafe { ffi::GetShapesTextureRectangle() } + } + /// Define default texture used to draw shapes fn set_shapes_texture( &mut self, @@ -749,6 +761,25 @@ pub trait RaylibDraw { } } + /// Draw rectangle with rounded edges outline + fn draw_rectangle_rounded_lines_ex( + &mut self, + rec: impl Into, + roundness: f32, + segments: i32, + line_thickness: f32, + color: impl Into, + ) { + unsafe { + ffi::DrawRectangleRoundedLinesEx( + rec.into(), + roundness, + segments, + line_thickness, + color.into(), + ) + }; + } /// Draws a triangle. #[inline] fn draw_triangle( @@ -1454,13 +1485,23 @@ pub trait RaylibDraw3D { /// Draw a 3d mesh with material and transform #[inline] - fn draw_mesh(&mut self, mesh: impl AsRef, material: WeakMaterial, transform: Matrix) { + fn draw_mesh( + &mut self, + mesh: impl AsRef, + material: WeakMaterial, + transform: Matrix, + ) { unsafe { ffi::DrawMesh(*mesh.as_ref(), material.0, transform.into()) } } /// Draw multiple mesh instances with material and different transforms #[inline] - fn draw_mesh_instanced(&mut self, mesh: impl AsRef, material: WeakMaterial, transforms: &[Matrix]) { + fn draw_mesh_instanced( + &mut self, + mesh: impl AsRef, + material: WeakMaterial, + transforms: &[Matrix], + ) { let tr = transforms .iter() .map(|f| f.into()) @@ -1604,6 +1645,49 @@ pub trait RaylibDraw3D { } } + /// Draw capsule with the center of its sphere caps at startPos and endPos + fn draw_capsule( + &mut self, + start_pos: impl Into, + end_pos: impl Into, + radius: f32, + slices: i32, + rings: i32, + color: impl Into, + ) { + unsafe { + ffi::DrawCapsule( + start_pos.into(), + end_pos.into(), + radius, + slices, + rings, + color.into(), + ) + } + } + + ///Draw capsule wireframe with the center of its sphere caps at startPos and endPos + fn draw_capsule_wires( + &mut self, + start_pos: impl Into, + end_pos: impl Into, + radius: f32, + slices: i32, + rings: i32, + color: impl Into, + ) { + unsafe { + ffi::DrawCapsule( + start_pos.into(), + end_pos.into(), + radius, + slices, + rings, + color.into(), + ) + } + } /// Draws an X/Z plane. #[inline] diff --git a/raylib/src/core/input.rs b/raylib/src/core/input.rs index ee11c6bf..af3c1823 100644 --- a/raylib/src/core/input.rs +++ b/raylib/src/core/input.rs @@ -15,6 +15,12 @@ impl RaylibHandle { unsafe { ffi::IsKeyPressed((key as u32) as i32) } } + /// Check if a key has been pressed again + #[inline] + pub fn is_key_pressed_repeat(&self, key: crate::consts::KeyboardKey) -> bool { + unsafe { ffi::IsKeyPressedRepeat((key as u32) as i32) } + } + /// Detect if a key is being pressed. #[inline] pub fn is_key_down(&self, key: crate::consts::KeyboardKey) -> bool { @@ -276,6 +282,11 @@ impl RaylibHandle { unsafe { ffi::SetGamepadMappings(bind.as_ptr()) } } + /// Set gamepad vibration for both motors + pub fn set_gamepad_vibration(&self, gamepad: i32, left_motor: f32, right_motor: f32) { + unsafe { ffi::SetGamepadVibration(gamepad, left_motor, right_motor) } + } + /// Checks if a gesture have been detected. #[inline] pub fn is_gesture_detected(&self, gesture: Gesture) -> bool { diff --git a/raylib/src/core/texture.rs b/raylib/src/core/texture.rs index 18b2845a..1741c2de 100644 --- a/raylib/src/core/texture.rs +++ b/raylib/src/core/texture.rs @@ -612,7 +612,17 @@ impl Image { pub fn gen_image_color(width: i32, height: i32, color: impl Into) -> Image { unsafe { Image(ffi::GenImageColor(width, height, color.into())) } } - /// TODO: add the new image gradent functions + /// Generate image: perlin noise + pub fn gen_image_perlin_noise( + &self, + width: i32, + height: i32, + offset_x: i32, + offset_y: i32, + scale: f32, + ) -> Image { + Image(unsafe { ffi::GenImagePerlinNoise(width, height, offset_x, offset_y, scale) }) + } /// Generates an Image containing a radial gradient. #[inline] diff --git a/raylib/src/core/window.rs b/raylib/src/core/window.rs index c034a8ff..23752c58 100644 --- a/raylib/src/core/window.rs +++ b/raylib/src/core/window.rs @@ -431,6 +431,7 @@ impl RaylibHandle { unsafe { ffi::GetScreenToWorldRay(mouse_position.into(), camera.into()).into() } } + /// Get a ray trace from screen position (i.e mouse) pub fn get_screen_to_world_ray( &self, mouse_position: impl Into, @@ -439,6 +440,19 @@ impl RaylibHandle { unsafe { ffi::GetScreenToWorldRay(mouse_position.into(), camera.into()).into() } } + /// Get a ray trace from screen position (i.e mouse) in a viewport + pub fn get_screen_to_world_ray_ex( + &self, + mouse_position: impl Into, + camera: impl Into, + width: i32, + height: i32, + ) -> Ray { + unsafe { + ffi::GetScreenToWorldRayEx(mouse_position.into(), camera.into(), width, height).into() + } + } + /// Returns the screen space position for a 3d world space position pub fn get_world_to_screen( &self, @@ -520,6 +534,30 @@ impl RaylibHandle { unsafe { ffi::IsWindowReady() } } + /// Set window state: maximized, if resizable + #[inline] + pub fn maximize_window(&self) { + unsafe { ffi::MaximizeWindow() } + } + + /// Set window state: minimized, if resizable + #[inline] + pub fn minimize_window(&self) { + unsafe { ffi::MinimizeWindow() } + } + + /// Set window state: not minimized/maximized + #[inline] + pub fn restore_window(&self) { + unsafe { ffi::RestoreWindow() } + } + + /// Check if window is currently maximized + #[inline] + pub fn is_window_maximized(&self) -> bool { + unsafe { ffi::IsWindowMaximized() } + } + /// Checks if window has been minimized (or lost focus). #[inline] pub fn is_window_minimized(&self) -> bool { @@ -714,6 +752,12 @@ impl RaylibHandle { unsafe { ffi::GetRenderWidth() } } + /// Get current render width which is equal to screen height * dpi scale + #[inline] + pub fn get_render_height(&self) -> i32 { + unsafe { ffi::GetRenderHeight() } + } + /// Get current screen height which is equal to screen height * dpi scale #[inline] pub fn get_screen_width(&self) -> i32 { From 1774f9cd401402bc8904679314d086e041ba6a24 Mon Sep 17 00:00:00 2001 From: IoIxD Date: Wed, 5 Jun 2024 18:33:17 -0700 Subject: [PATCH 25/93] drawing: accidentally had draw_capsule_wires call DrawCapsule --- raylib/src/core/drawing.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index a1d610d1..91430c2e 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -1678,7 +1678,7 @@ pub trait RaylibDraw3D { color: impl Into, ) { unsafe { - ffi::DrawCapsule( + ffi::DrawCapsuleWires( start_pos.into(), end_pos.into(), radius, From beafa784e16bad3c28d3b5954e034573c935475d Mon Sep 17 00:00:00 2001 From: IoIxD Date: Wed, 5 Jun 2024 18:42:42 -0700 Subject: [PATCH 26/93] audio: oh, we don't drop sound alias --- raylib/src/core/audio.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/raylib/src/core/audio.rs b/raylib/src/core/audio.rs index 1cb2f48d..618103d4 100644 --- a/raylib/src/core/audio.rs +++ b/raylib/src/core/audio.rs @@ -428,6 +428,12 @@ impl<'aud, 'bind> SoundAlias<'aud, 'bind> { } } +impl Drop for SoundAlias<'_, '_> { + fn drop(&mut self) { + unsafe { ffi::UnloadSoundAlias(self.0) } + } +} + impl<'aud> Music<'aud> { /// Starts music playing. #[inline] From ad0dccf8ed782b5ab42379f34a00b6a2bda3d9fe Mon Sep 17 00:00:00 2001 From: fooeyround Date: Wed, 5 Jun 2024 19:05:59 -0700 Subject: [PATCH 27/93] Fix update_camera_pro update_camera_pro would edit a copy of the camera, but not update the actual camera after. --- raylib/src/core/camera.rs | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/raylib/src/core/camera.rs b/raylib/src/core/camera.rs index dd2c53d2..23528b21 100644 --- a/raylib/src/core/camera.rs +++ b/raylib/src/core/camera.rs @@ -106,20 +106,12 @@ impl RaylibHandle { *camera = fficam.into(); } } - - pub fn update_camera_pro( - &self, - camera: &mut Camera3D, - movement: Vector3, - rotation: Vector3, - zoom: f32, - ) { - let mut fficam: ffi::Camera3D = (*camera).into(); - let ffimov: ffi::Vector3 = (movement).into(); - let ffirot: ffi::Vector3 = (rotation).into(); - + + pub fn update_camera_pro(&self, camera: &mut Camera3D, movement: Vector3, rotation: Vector3, zoom: f32) { unsafe { - ffi::UpdateCameraPro(&mut fficam, ffimov, ffirot, zoom); + let mut fficam: ffi::Camera3D = (*camera).into(); + ffi::UpdateCameraPro(&mut fficam, movement.into(), rotation.into(), zoom); + *camera = fficam.into(); } } } From c251ddeb7330d7fae04ab47183d3b14dd09e76b3 Mon Sep 17 00:00:00 2001 From: TSnake41 Date: Sat, 6 Jul 2024 11:47:45 +0200 Subject: [PATCH 28/93] Rework callback system to use atomic instead of Mutex. --- raylib/Cargo.toml | 1 - raylib/src/core/callbacks.rs | 203 ++++++++++++++++------------------- 2 files changed, 93 insertions(+), 111 deletions(-) diff --git a/raylib/Cargo.toml b/raylib/Cargo.toml index 05ecb63f..a73e4ac0 100644 --- a/raylib/Cargo.toml +++ b/raylib/Cargo.toml @@ -20,7 +20,6 @@ cfg-if = "1.0.0" serde = { version = "1.0.125", features = ["derive"], optional = true } serde_json = { version = "1.0.64", optional = true } nalgebra = { version = "0.26", optional = true } -parking_lot = "0.12.1" specs-derive = "0.4.1" [dev-dependencies] diff --git a/raylib/src/core/callbacks.rs b/raylib/src/core/callbacks.rs index c03f983a..6d3161d3 100644 --- a/raylib/src/core/callbacks.rs +++ b/raylib/src/core/callbacks.rs @@ -1,12 +1,15 @@ #![allow(non_camel_case_types)] use crate::{audio::AudioStream, ffi, RaylibHandle}; -use libc::c_void; -use parking_lot::Mutex; -use raylib_sys::TraceLogLevel; +pub use raylib_sys::TraceLogLevel; use std::{ - ffi::{CStr, CString}, - ptr, + borrow::Cow, + convert::TryInto, + ffi::{c_char, c_int, c_void, CStr, CString}, + mem::{size_of, transmute}, + ptr::null_mut, + slice::from_raw_parts_mut, + sync::atomic::{AtomicUsize, Ordering}, }; type TraceLogCallback = unsafe extern "C" fn(*mut i8, *const i8, ...); @@ -14,106 +17,94 @@ extern "C" { fn SetTraceLogCallback(cb: Option); } -type RustTraceLogCallback = Option; -type RustSaveFileDataCallback = Option bool>; -type RustLoadFileDataCallback = Option Vec>; -type RustSaveFileTextCallback = Option bool>; -type RustLoadFileTextCallback = Option String>; -type RustAudioStreamCallback = Option; +type RustTraceLogCallback = fn(TraceLogLevel, &str); +type RustSaveFileDataCallback = fn(&str, &[u8]) -> bool; +type RustLoadFileDataCallback = fn(&str) -> Vec; +type RustSaveFileTextCallback = fn(&str, &str) -> bool; +type RustLoadFileTextCallback = fn(&str) -> String; +type RustAudioStreamCallback = fn(&[u8]); -static __TRACE_LOG_CALLBACK: Mutex = Mutex::new(None); -static __SAVE_FILE_DATA_CALLBACK: Mutex = Mutex::new(None); -static __LOAD_FILE_DATA_CALLBACK: Mutex = Mutex::new(None); -static __SAVE_FILE_TEXT_CALLBACK: Mutex = Mutex::new(None); -static __LOAD_FILE_TEXT_CALLBACK: Mutex = Mutex::new(None); -static __AUDIO_STREAM_CALLBACK: Mutex = Mutex::new(None); +static TRACE_LOG_CALLBACK: AtomicUsize = AtomicUsize::new(0); +static SAVE_FILE_DATA_CALLBACK: AtomicUsize = AtomicUsize::new(0); +static LOAD_FILE_DATA_CALLBACK: AtomicUsize = AtomicUsize::new(0); +static SAVE_FILE_TEXT_CALLBACK: AtomicUsize = AtomicUsize::new(0); +static LOAD_FILE_TEXT_CALLBACK: AtomicUsize = AtomicUsize::new(0); +static AUDIO_STREAM_CALLBACK: AtomicUsize = AtomicUsize::new(0); -fn trace_log_callback() -> RustTraceLogCallback { - *__TRACE_LOG_CALLBACK.lock() -} -fn set_trace_log_callback(f: RustTraceLogCallback) { - *__TRACE_LOG_CALLBACK.lock() = f -} -fn save_file_data_callback() -> RustSaveFileDataCallback { - *__SAVE_FILE_DATA_CALLBACK.lock() -} -fn set_save_file_data_callback(f: RustSaveFileDataCallback) { - *__SAVE_FILE_DATA_CALLBACK.lock() = f -} -fn load_file_data_callback() -> RustLoadFileDataCallback { - *__LOAD_FILE_DATA_CALLBACK.lock() -} -fn set_load_file_data_callback(f: RustLoadFileDataCallback) { - *__LOAD_FILE_DATA_CALLBACK.lock() = f +fn trace_log_callback() -> Option { + const { assert!(size_of::() == size_of::()) }; + unsafe { transmute(TRACE_LOG_CALLBACK.load(Ordering::Relaxed)) } } -fn save_file_text_callback() -> RustSaveFileTextCallback { - *__SAVE_FILE_TEXT_CALLBACK.lock() +fn save_file_data_callback() -> Option { + const { assert!(size_of::() == size_of::()) }; + unsafe { transmute(SAVE_FILE_DATA_CALLBACK.load(Ordering::Relaxed)) } } -fn set_save_file_text_callback(f: RustSaveFileTextCallback) { - *__SAVE_FILE_TEXT_CALLBACK.lock() = f -} -fn load_file_text_callback() -> RustLoadFileTextCallback { - *__LOAD_FILE_TEXT_CALLBACK.lock() + +fn load_file_data_callback() -> Option { + const { assert!(size_of::() == size_of::()) }; + unsafe { transmute(LOAD_FILE_DATA_CALLBACK.load(Ordering::Relaxed)) } } -fn set_load_file_text_callback(f: RustLoadFileTextCallback) { - *__LOAD_FILE_TEXT_CALLBACK.lock() = f + +fn save_file_text_callback() -> Option { + const { assert!(size_of::() == size_of::()) }; + unsafe { transmute(SAVE_FILE_TEXT_CALLBACK.load(Ordering::Relaxed)) } } -fn audio_stream_callback() -> RustAudioStreamCallback { - *__AUDIO_STREAM_CALLBACK.lock() +fn load_file_text_callback() -> Option { + const { assert!(size_of::() == size_of::()) }; + unsafe { transmute(LOAD_FILE_TEXT_CALLBACK.load(Ordering::Relaxed)) } } -fn set_audio_stream_callback(f: RustAudioStreamCallback) { - *__AUDIO_STREAM_CALLBACK.lock() = f + +fn audio_stream_callback() -> Option { + const { assert!(size_of::() == size_of::()) }; + unsafe { transmute(AUDIO_STREAM_CALLBACK.load(Ordering::Relaxed)) } } #[no_mangle] -#[link_name = "custom_trace_log_callback"] -pub extern "C" fn custom_trace_log_callback( - log_level: ::std::os::raw::c_int, - text: *const ::std::os::raw::c_char, -) { +pub extern "C" fn custom_trace_log_callback(level: TraceLogLevel, text: *const c_char) { if let Some(trace_log) = trace_log_callback() { - let a = match log_level { - 0 => TraceLogLevel::LOG_ALL, - 1 => TraceLogLevel::LOG_TRACE, - 2 => TraceLogLevel::LOG_DEBUG, - 3 => TraceLogLevel::LOG_INFO, - 4 => TraceLogLevel::LOG_WARNING, - 5 => TraceLogLevel::LOG_ERROR, - 6 => TraceLogLevel::LOG_FATAL, - 7 => TraceLogLevel::LOG_NONE, - _ => unreachable!("raylib gave invalid log level {}", log_level), - }; - let b = if text.is_null() { - CStr::from_bytes_until_nul("(MESSAGE WAS NULL)\0".as_bytes()).unwrap() + let text = if text.is_null() { + Cow::Borrowed("(MESSAGE WAS NULL)") } else { - unsafe { CStr::from_ptr(text) } + unsafe { CStr::from_ptr(text).to_string_lossy() } }; - trace_log(a, b.to_string_lossy().as_ref()) + trace_log(level, &text) } } -extern "C" fn custom_save_file_data_callback(a: *const i8, b: *mut c_void, c: i32) -> bool { - let save_file_data = save_file_data_callback().unwrap(); - let a = unsafe { CStr::from_ptr(a) }; - let b = unsafe { std::slice::from_raw_parts_mut(b as *mut u8, c as usize) }; - return save_file_data(a.to_str().unwrap(), b); +extern "C" fn custom_save_file_data_callback( + path: *const c_char, + buffer: *mut c_void, + size: c_int, +) -> bool { + let save_file_data = save_file_data_callback().expect("no callback"); + let path = unsafe { CStr::from_ptr(path) }; + let buffer = unsafe { from_raw_parts_mut(buffer as *mut u8, size as usize) }; + + save_file_data(path.to_str().expect("path is non utf-8"), buffer) } -extern "C" fn custom_load_file_data_callback(a: *const i8, b: *mut i32) -> *mut u8 { - let load_file_data = load_file_data_callback().unwrap(); - let a = unsafe { CStr::from_ptr(a) }; - let b = unsafe { b.as_mut().unwrap() }; - let d = load_file_data(a.to_str().unwrap()); - *b = d.len() as i32; - if *b == 0 { - return ptr::null_mut(); +extern "C" fn custom_load_file_data_callback(path: *const c_char, size: *mut c_int) -> *mut u8 { + let load_file_data = load_file_data_callback().expect("no callback"); + + if let Some(size) = unsafe { size.as_mut() } { + let path = unsafe { CStr::from_ptr(path) }; + let buffer = load_file_data(path.to_str().expect("path is non utf-8")); + *size = buffer.len().try_into().expect("out of range buffer size"); + + // Copy everything to the raylib world + unsafe { + let buffer_ffi = + ffi::MemAlloc((*size).try_into().expect("non representable buffer size")) + as *mut u8; + buffer_ffi.copy_from_nonoverlapping(buffer.as_ptr(), buffer.len()); + + buffer_ffi + } } else { - // Leak the data that we just created. It's in Raylib's hands now. - let uh = Box::leak(Box::new(d)).as_mut_ptr(); - return uh; + null_mut() } } @@ -148,15 +139,13 @@ impl<'a> std::fmt::Display for SetLogError<'a> { impl<'a> std::error::Error for SetLogError<'a> {} macro_rules! safe_callback_set_func { - ($cb:expr, $getter:expr, $setter:expr, $rawsetter:expr, $ogfunc:expr, $ty:literal) => { - if let None = $getter() { - $setter(Some($cb)); - unsafe { - $rawsetter(Some($ogfunc)); - } - return Ok(()); + ($cb:expr, $target_cb:expr, $rawsetter:expr, $ogfunc:expr, $ty:literal) => { + if $target_cb.load(Ordering::Acquire) == 0 { + $target_cb.store($cb as usize, Ordering::Release); + unsafe { $rawsetter(Some($ogfunc)) }; + Ok(()) } else { - return Err(SetLogError($ty)); + Err(SetLogError($ty)) } }; } @@ -167,9 +156,9 @@ impl RaylibHandle { &mut self, cb: fn(TraceLogLevel, &str), ) -> Result<(), SetLogError> { - set_trace_log_callback(Some(cb)); + TRACE_LOG_CALLBACK.store(cb as usize, Ordering::Relaxed); unsafe { ffi::setLogCallbackWrapper() }; - return Ok(()); + Ok(()) } /// Set custom file binary data saver pub fn set_save_file_data_callback( @@ -178,12 +167,11 @@ impl RaylibHandle { ) -> Result<(), SetLogError> { safe_callback_set_func!( cb, - save_file_data_callback, - set_save_file_data_callback, + SAVE_FILE_DATA_CALLBACK, ffi::SetSaveFileDataCallback, custom_save_file_data_callback, "save file data" - ); + ) } /// Set custom file binary data loader /// @@ -194,12 +182,11 @@ impl RaylibHandle { ) -> Result<(), SetLogError> { safe_callback_set_func!( cb, - load_file_data_callback, - set_load_file_data_callback, + LOAD_FILE_DATA_CALLBACK, ffi::SetLoadFileDataCallback, custom_load_file_data_callback, "load file data" - ); + ) } /// Set custom file text data saver pub fn set_save_file_text_callback( @@ -208,8 +195,7 @@ impl RaylibHandle { ) -> Result<(), SetLogError> { safe_callback_set_func!( cb, - save_file_text_callback, - set_save_file_text_callback, + SAVE_FILE_TEXT_CALLBACK, ffi::SetSaveFileTextCallback, custom_save_file_text_callback, "load file data" @@ -224,8 +210,7 @@ impl RaylibHandle { ) -> Result<(), SetLogError> { safe_callback_set_func!( cb, - load_file_text_callback, - set_load_file_text_callback, + LOAD_FILE_TEXT_CALLBACK, ffi::SetLoadFileTextCallback, custom_load_file_text_callback, "load file text" @@ -238,14 +223,12 @@ impl RaylibHandle { stream: AudioStream, cb: fn(&[u8]), ) -> Result<(), SetLogError> { - if let None = audio_stream_callback() { - set_audio_stream_callback(Some(cb)); - unsafe { - ffi::SetAudioStreamCallback(stream.0, Some(custom_audio_stream_callback)); - } - return Ok(()); + if AUDIO_STREAM_CALLBACK.load(Ordering::Acquire) == 0 { + AUDIO_STREAM_CALLBACK.store(cb as _, Ordering::Release); + unsafe { ffi::SetAudioStreamCallback(stream.0, Some(custom_audio_stream_callback)) } + Ok(()) } else { - return Err(SetLogError("audio stream")); + Err(SetLogError("audio stream")) } } } From dfd1ae0c1983208f2418efc9337a56ee317c239b Mon Sep 17 00:00:00 2001 From: Kacper-Kondracki <43544435+Kacper-Kondracki@users.noreply.github.com> Date: Mon, 22 Jul 2024 09:06:01 +0200 Subject: [PATCH 29/93] Relax &mut self requirements on Audio types &mut self is not required, because behind, raylib uses mutexes and miniaudio atomics. --- raylib/src/core/audio.rs | 60 ++++++++++++++++++++-------------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/raylib/src/core/audio.rs b/raylib/src/core/audio.rs index 618103d4..48c22b61 100644 --- a/raylib/src/core/audio.rs +++ b/raylib/src/core/audio.rs @@ -67,7 +67,7 @@ impl RaylibAudio { } /// Get master volume (listener) - pub fn get_master_volume(&mut self) -> f32 { + pub fn get_master_volume(&self) -> f32 { unsafe { ffi::GetMasterVolume() } } @@ -291,7 +291,7 @@ impl<'aud> Sound<'aud> { /// Pauses a sound. #[inline] - pub fn pause(&mut self) { + pub fn pause(&self) { unsafe { ffi::PauseSound(self.0); } @@ -299,7 +299,7 @@ impl<'aud> Sound<'aud> { /// Resumes a paused sound. #[inline] - pub fn resume(&mut self) { + pub fn resume(&self) { unsafe { ffi::ResumeSound(self.0); } @@ -307,7 +307,7 @@ impl<'aud> Sound<'aud> { /// Stops playing a sound. #[inline] - pub fn stop(&mut self) { + pub fn stop(&self) { unsafe { ffi::StopSound(self.0); } @@ -321,7 +321,7 @@ impl<'aud> Sound<'aud> { /// Sets volume for a sound (`1.0` is max level). #[inline] - pub fn set_volume(&mut self, volume: f32) { + pub fn set_volume(&self, volume: f32) { unsafe { ffi::SetSoundVolume(self.0, volume); } @@ -329,12 +329,12 @@ impl<'aud> Sound<'aud> { /// Sets pitch for a sound (`1.0` is base level). #[inline] - pub fn set_pitch(&mut self, pitch: f32) { + pub fn set_pitch(&self, pitch: f32) { unsafe { ffi::SetSoundPitch(self.0, pitch); } } - pub fn set_pan(&mut self, pan: f32) { + pub fn set_pan(&self, pan: f32) { unsafe { ffi::SetSoundPan(self.0, pan); } @@ -378,7 +378,7 @@ impl<'aud, 'bind> SoundAlias<'aud, 'bind> { /// Pauses a sound. #[inline] - pub fn pause(&mut self) { + pub fn pause(&self) { unsafe { ffi::PauseSound(self.0); } @@ -386,7 +386,7 @@ impl<'aud, 'bind> SoundAlias<'aud, 'bind> { /// Resumes a paused sound. #[inline] - pub fn resume(&mut self) { + pub fn resume(&self) { unsafe { ffi::ResumeSound(self.0); } @@ -394,7 +394,7 @@ impl<'aud, 'bind> SoundAlias<'aud, 'bind> { /// Stops playing a sound. #[inline] - pub fn stop(&mut self) { + pub fn stop(&self) { unsafe { ffi::StopSound(self.0); } @@ -408,7 +408,7 @@ impl<'aud, 'bind> SoundAlias<'aud, 'bind> { /// Sets volume for a sound (`1.0` is max level). #[inline] - pub fn set_volume(&mut self, volume: f32) { + pub fn set_volume(&self, volume: f32) { unsafe { ffi::SetSoundVolume(self.0, volume); } @@ -416,12 +416,12 @@ impl<'aud, 'bind> SoundAlias<'aud, 'bind> { /// Sets pitch for a sound (`1.0` is base level). #[inline] - pub fn set_pitch(&mut self, pitch: f32) { + pub fn set_pitch(&self, pitch: f32) { unsafe { ffi::SetSoundPitch(self.0, pitch); } } - pub fn set_pan(&mut self, pan: f32) { + pub fn set_pan(&self, pan: f32) { unsafe { ffi::SetSoundPan(self.0, pan); } @@ -437,7 +437,7 @@ impl Drop for SoundAlias<'_, '_> { impl<'aud> Music<'aud> { /// Starts music playing. #[inline] - pub fn play_stream(&mut self) { + pub fn play_stream(&self) { unsafe { ffi::PlayMusicStream(self.0); } @@ -445,7 +445,7 @@ impl<'aud> Music<'aud> { /// Updates buffers for music streaming. #[inline] - pub fn update_stream(&mut self) { + pub fn update_stream(&self) { unsafe { ffi::UpdateMusicStream(self.0); } @@ -453,7 +453,7 @@ impl<'aud> Music<'aud> { /// Stops music playing. #[inline] - pub fn stop_stream(&mut self) { + pub fn stop_stream(&self) { unsafe { ffi::StopMusicStream(self.0); } @@ -461,7 +461,7 @@ impl<'aud> Music<'aud> { /// Pauses music playing. #[inline] - pub fn pause_stream(&mut self) { + pub fn pause_stream(&self) { unsafe { ffi::PauseMusicStream(self.0); } @@ -469,7 +469,7 @@ impl<'aud> Music<'aud> { /// Resumes playing paused music. #[inline] - pub fn resume_stream(&mut self) { + pub fn resume_stream(&self) { unsafe { ffi::ResumeMusicStream(self.0); } @@ -483,7 +483,7 @@ impl<'aud> Music<'aud> { /// Sets volume for music (`1.0` is max level). #[inline] - pub fn set_volume(&mut self, volume: f32) { + pub fn set_volume(&self, volume: f32) { unsafe { ffi::SetMusicVolume(self.0, volume); } @@ -491,7 +491,7 @@ impl<'aud> Music<'aud> { /// Sets pitch for music (`1.0` is base level). #[inline] - pub fn set_pitch(&mut self, pitch: f32) { + pub fn set_pitch(&self, pitch: f32) { unsafe { ffi::SetMusicPitch(self.0, pitch); } @@ -509,13 +509,13 @@ impl<'aud> Music<'aud> { unsafe { ffi::GetMusicTimePlayed(self.0) } } - pub fn seek_stream(&mut self, position: f32) { + pub fn seek_stream(&self, position: f32) { unsafe { ffi::SeekMusicStream(self.0, position); } } - pub fn set_pan(&mut self, pan: f32) { + pub fn set_pan(&self, pan: f32) { unsafe { ffi::SetMusicPan(self.0, pan); } @@ -556,7 +556,7 @@ impl<'aud> AudioStream<'aud> { /// Plays audio stream. #[inline] - pub fn play(&mut self) { + pub fn play(&self) { unsafe { ffi::PlayAudioStream(self.0); } @@ -564,7 +564,7 @@ impl<'aud> AudioStream<'aud> { /// Pauses audio stream. #[inline] - pub fn pause(&mut self) { + pub fn pause(&self) { unsafe { ffi::PauseAudioStream(self.0); } @@ -572,7 +572,7 @@ impl<'aud> AudioStream<'aud> { /// Resumes audio stream. #[inline] - pub fn resume(&mut self) { + pub fn resume(&self) { unsafe { ffi::ResumeAudioStream(self.0); } @@ -586,7 +586,7 @@ impl<'aud> AudioStream<'aud> { /// Stops audio stream. #[inline] - pub fn stop(&mut self) { + pub fn stop(&self) { unsafe { ffi::StopAudioStream(self.0); } @@ -594,7 +594,7 @@ impl<'aud> AudioStream<'aud> { /// Sets volume for audio stream (`1.0` is max level). #[inline] - pub fn set_volume(&mut self, volume: f32) { + pub fn set_volume(&self, volume: f32) { unsafe { ffi::SetAudioStreamVolume(self.0, volume); } @@ -602,7 +602,7 @@ impl<'aud> AudioStream<'aud> { /// Sets pitch for audio stream (`1.0` is base level). #[inline] - pub fn set_pitch(&mut self, pitch: f32) { + pub fn set_pitch(&self, pitch: f32) { unsafe { ffi::SetAudioStreamPitch(self.0, pitch); } @@ -610,11 +610,11 @@ impl<'aud> AudioStream<'aud> { /// Sets pitch for audio stream (`1.0` is base level). #[inline] - pub fn is_processed(&mut self) -> bool { + pub fn is_processed(&self) -> bool { unsafe { ffi::IsAudioStreamProcessed(self.0) } } - pub fn set_pan(&mut self, pan: f32) { + pub fn set_pan(&self, pan: f32) { unsafe { ffi::SetAudioStreamPan(self.0, pan); } From 6643a545d5cb3fe317e839369bd4718b4e7fe4d2 Mon Sep 17 00:00:00 2001 From: Alexei Mozaidze Date: Sun, 7 Jul 2024 23:11:42 +0400 Subject: [PATCH 30/93] feat(error)!: add designated error type Added an error type that implement the `Error` trait, along with replacing every instance of `Result<_, String>` with `Result<_, Error>`. Also, added `error!` macro to easily construct the error type. --- raylib/Cargo.toml | 1 + raylib/src/core/audio.rs | 29 ++++++++++++++------------- raylib/src/core/data.rs | 13 +++++++----- raylib/src/core/error.rs | 41 ++++++++++++++++++++++++++++++++++++++ raylib/src/core/mod.rs | 1 + raylib/src/core/models.rs | 17 ++++++++-------- raylib/src/core/shaders.rs | 10 +++++----- raylib/src/core/text.rs | 31 ++++++++++++++-------------- raylib/src/core/texture.rs | 41 +++++++++++++++++++------------------- 9 files changed, 117 insertions(+), 67 deletions(-) create mode 100644 raylib/src/core/error.rs diff --git a/raylib/Cargo.toml b/raylib/Cargo.toml index a73e4ac0..ce7e603c 100644 --- a/raylib/Cargo.toml +++ b/raylib/Cargo.toml @@ -21,6 +21,7 @@ serde = { version = "1.0.125", features = ["derive"], optional = true } serde_json = { version = "1.0.64", optional = true } nalgebra = { version = "0.26", optional = true } specs-derive = "0.4.1" +thiserror = "1.0.61" [dev-dependencies] structopt = "0.3" diff --git a/raylib/src/core/audio.rs b/raylib/src/core/audio.rs index 48c22b61..2eae3592 100644 --- a/raylib/src/core/audio.rs +++ b/raylib/src/core/audio.rs @@ -1,5 +1,6 @@ //! Contains code related to audio. [`RaylibAudio`] plays sounds and music. +use crate::error::{error, Error}; use crate::ffi; use std::ffi::CString; use std::marker::PhantomData; @@ -80,31 +81,31 @@ impl RaylibAudio { } /// Loads a new sound from file. - pub fn new_sound<'aud>(&'aud self, filename: &str) -> Result, String> { + pub fn new_sound<'aud>(&'aud self, filename: &str) -> Result, Error> { let c_filename = CString::new(filename).unwrap(); let s = unsafe { ffi::LoadSound(c_filename.as_ptr()) }; if s.stream.buffer.is_null() { - return Err(format!("failed to load sound {}", filename)); + return Err(error!("failed to load sound", filename)); } Ok(Sound(s, self)) } /// Loads sound from wave data. - pub fn new_sound_from_wave<'aud>(&'aud self, wave: &Wave) -> Result, String> { + pub fn new_sound_from_wave<'aud>(&'aud self, wave: &Wave) -> Result, Error> { let s = unsafe { ffi::LoadSoundFromWave(wave.0) }; if s.stream.buffer.is_null() { - return Err(format!("failed to load sound from wave")); + return Err(error!("failed to load sound from wave")); } Ok(Sound(s, self)) } /// Loads wave data from file into RAM. #[inline] - pub fn new_wave<'aud>(&'aud self, filename: &str) -> Result, String> { + pub fn new_wave<'aud>(&'aud self, filename: &str) -> Result, Error> { let c_filename = CString::new(filename).unwrap(); let w = unsafe { ffi::LoadWave(c_filename.as_ptr()) }; if w.data.is_null() { - return Err(format!("Cannot load wave {}", filename)); + return Err(error!("Cannot load wave {}", filename)); } Ok(Wave(w, self)) } @@ -114,24 +115,24 @@ impl RaylibAudio { &'aud self, filetype: &str, bytes: &[u8], - ) -> Result, String> { + ) -> Result, Error> { let c_filetype = CString::new(filetype).unwrap(); let c_bytes = bytes.as_ptr(); let w = unsafe { ffi::LoadWaveFromMemory(c_filetype.as_ptr(), c_bytes, bytes.len() as i32) }; if w.data.is_null() { - return Err(format!("Wave data is null. Check provided buffer data")); + return Err(error!("Wave data is null. Check provided buffer data")); }; Ok(Wave(w, self)) } /// Loads music stream from file. // #[inline] - pub fn new_music<'aud>(&'aud self, filename: &str) -> Result, String> { + pub fn new_music<'aud>(&'aud self, filename: &str) -> Result, Error> { let c_filename = CString::new(filename).unwrap(); let m = unsafe { ffi::LoadMusicStream(c_filename.as_ptr()) }; if m.stream.buffer.is_null() { - return Err(format!("music could not be loaded from file {}", filename)); + return Err(error!("music could not be loaded from file", filename)); } Ok(Music(m, self)) } @@ -141,14 +142,14 @@ impl RaylibAudio { &'aud self, filetype: &str, bytes: &Vec, - ) -> Result, String> { + ) -> Result, Error> { let c_filetype = CString::new(filetype).unwrap(); let c_bytes = bytes.as_ptr(); let w = unsafe { ffi::LoadMusicStreamFromMemory(c_filetype.as_ptr(), c_bytes, bytes.len() as i32) }; if w.stream.buffer.is_null() { - return Err(format!( + return Err(error!( "Music's buffer data data is null. Check provided buffer data" )); }; @@ -622,10 +623,10 @@ impl<'aud> AudioStream<'aud> { } impl<'bind> Sound<'_> { - pub fn alias<'snd>(&'snd self) -> Result, String> { + pub fn alias<'snd>(&'snd self) -> Result, Error> { let s = unsafe { ffi::LoadSoundAlias(self.0) }; if s.stream.buffer.is_null() { - return Err("failed to load sound from wave".to_string()); + return Err(error!("failed to load sound from wave")); } Ok(SoundAlias(s, PhantomData)) } diff --git a/raylib/src/core/data.rs b/raylib/src/core/data.rs index 0e654ce4..5c93c381 100644 --- a/raylib/src/core/data.rs +++ b/raylib/src/core/data.rs @@ -1,7 +1,10 @@ //! Data manipulation functions. Compress and Decompress with DEFLATE use std::{ffi::CString, path::Path}; -use crate::ffi; +use crate::{ + error::{error, Error}, + ffi, +}; /// Compress data (DEFLATE algorythm) /// ```rust @@ -10,14 +13,14 @@ use crate::ffi; /// let expected: &[u8] = &[1, 5, 0, 250, 255, 49, 49, 49, 49, 49]; /// assert_eq!(data, Ok(expected)); /// ``` -pub fn compress_data(data: &[u8]) -> Result<&'static [u8], String> { +pub fn compress_data(data: &[u8]) -> Result<&'static [u8], Error> { let mut out_length: i32 = 0; // CompressData doesn't actually modify the data, but the header is wrong let buffer = { unsafe { ffi::CompressData(data.as_ptr() as *mut _, data.len() as i32, &mut out_length) } }; if buffer.is_null() { - return Err("could not compress data".to_string()); + return Err(error!("could not compress data")); } let buffer = unsafe { std::slice::from_raw_parts(buffer, out_length as usize) }; return Ok(buffer); @@ -31,7 +34,7 @@ pub fn compress_data(data: &[u8]) -> Result<&'static [u8], String> { /// let data = decompress_data(input); /// assert_eq!(data, Ok(expected)); /// ``` -pub fn decompress_data(data: &[u8]) -> Result<&'static [u8], String> { +pub fn decompress_data(data: &[u8]) -> Result<&'static [u8], Error> { println!("{:?}", data.len()); let mut out_length: i32 = 0; @@ -40,7 +43,7 @@ pub fn decompress_data(data: &[u8]) -> Result<&'static [u8], String> { unsafe { ffi::DecompressData(data.as_ptr() as *mut _, data.len() as i32, &mut out_length) } }; if buffer.is_null() { - return Err("could not compress data".to_string()); + return Err(error!("could not compress data")); } let buffer = unsafe { std::slice::from_raw_parts(buffer, out_length as usize) }; return Ok(buffer); diff --git a/raylib/src/core/error.rs b/raylib/src/core/error.rs new file mode 100644 index 00000000..c57cec2a --- /dev/null +++ b/raylib/src/core/error.rs @@ -0,0 +1,41 @@ +//! Definitions for error types used throught the crate + +use std::path::PathBuf; + +use thiserror::Error; + +#[derive(Error, Debug)] +#[error( + "{message}{path}", + path = path.as_ref().map(|p| format!("\npath: {}", p.display())).unwrap_or("".to_owned()), +)] +pub struct Error { + // NOTE(alexmozaidze): There is not a single instance of the message being dynamic in this crate, + // so if there occurs an instance where the message is to be determined at runtime, then + // use `Cow<'static, str>`. + // + // One could also use generics, but that would make the error type much more complex to use + // and to reason about for the user. + pub(crate) message: &'static str, + pub(crate) path: Option, +} + +impl Error { + pub(crate) const fn new(message: &'static str, path: Option) -> Self { + Self { message, path } + } +} + +macro_rules! error { + ($message:expr $(,)?) => {{ + $crate::core::error::Error::new($message, ::core::option::Option::None) + }}; + ($message:expr, $path:expr $(,)?) => {{ + $crate::core::error::Error::new( + $message, + ::core::option::Option::Some(::std::path::PathBuf::from($path)), + ) + }}; +} + +pub(crate) use error; diff --git a/raylib/src/core/mod.rs b/raylib/src/core/mod.rs index 52e35ced..30f22ff9 100644 --- a/raylib/src/core/mod.rs +++ b/raylib/src/core/mod.rs @@ -9,6 +9,7 @@ pub mod collision; pub mod color; pub mod data; pub mod drawing; +pub mod error; pub mod file; pub mod input; pub mod logging; diff --git a/raylib/src/core/models.rs b/raylib/src/core/models.rs index 6f7d790f..7c81bdbf 100644 --- a/raylib/src/core/models.rs +++ b/raylib/src/core/models.rs @@ -2,6 +2,7 @@ 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; @@ -53,12 +54,12 @@ impl Clone for WeakModelAnimation { impl RaylibHandle { /// Loads model from files (mesh and material). // #[inline] - pub fn load_model(&mut self, _: &RaylibThread, filename: &str) -> Result { + pub fn load_model(&mut self, _: &RaylibThread, filename: &str) -> Result { 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.bones.is_null() && m.bindPose.is_null() { - return Err(format!("could not load model {}", filename)); + return Err(error!("could not load model", filename)); } // TODO check if null pointer checks are necessary. Ok(Model(m)) @@ -69,11 +70,11 @@ impl RaylibHandle { &mut self, _: &RaylibThread, mesh: WeakMesh, - ) -> Result { + ) -> Result { let m = unsafe { ffi::LoadModelFromMesh(mesh.0) }; if m.meshes.is_null() || m.materials.is_null() { - return Err("Could not load model from mesh".to_owned()); + return Err(error!("Could not load model from mesh")); } Ok(Model(m)) @@ -83,12 +84,12 @@ impl RaylibHandle { &mut self, _: &RaylibThread, filename: &str, - ) -> Result, String> { + ) -> Result, 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(format!("No model animations loaded from {}", filename)); + 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 { @@ -417,12 +418,12 @@ impl Material { m } - pub fn load_materials(filename: &str) -> Result, String> { + pub fn load_materials(filename: &str) -> Result, 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(format!("No materials loaded from {}", filename)); + return Err(error!("No materials loaded", filename)); } let mut m_vec = Vec::with_capacity(m_size as usize); for i in 0..m_size { diff --git a/raylib/src/core/shaders.rs b/raylib/src/core/shaders.rs index 2b5ddc5e..ec56f947 100644 --- a/raylib/src/core/shaders.rs +++ b/raylib/src/core/shaders.rs @@ -1,4 +1,6 @@ //! Code for the safe manipulation of shaders +use thiserror::Error; + use crate::consts::ShaderUniformDataType; use crate::core::math::Matrix; use crate::core::math::{Vector2, Vector3, Vector4}; @@ -23,7 +25,7 @@ impl RaylibHandle { _: &RaylibThread, vs_filename: Option<&str>, fs_filename: Option<&str>, - ) -> Result { + ) -> Shader { let c_vs_filename = vs_filename.map(|f| CString::new(f).unwrap()); let c_fs_filename = fs_filename.map(|f| CString::new(f).unwrap()); @@ -36,7 +38,7 @@ impl RaylibHandle { (None, None) => unsafe { Shader(ffi::LoadShader(std::ptr::null(), std::ptr::null())) }, }; - return Ok(shader); + return shader; } /// Loads shader from code strings and binds default locations. @@ -188,9 +190,7 @@ impl Shader { #[inline] pub fn is_ready(&self) { unsafe { - ffi::IsShaderReady( - self.0, - ); + ffi::IsShaderReady(self.0); } } diff --git a/raylib/src/core/text.rs b/raylib/src/core/text.rs index 02940571..e362c9dc 100644 --- a/raylib/src/core/text.rs +++ b/raylib/src/core/text.rs @@ -5,6 +5,7 @@ use raylib_sys::LoadUTF8; use crate::core::math::Vector2; use crate::core::texture::{Image, Texture2D}; use crate::core::{RaylibHandle, RaylibThread}; +use crate::error::{error, Error}; use crate::ffi; use crate::math::Rectangle; @@ -118,13 +119,13 @@ impl RaylibHandle { /// Loads font from file into GPU memory (VRAM). #[inline] - pub fn load_font(&mut self, _: &RaylibThread, filename: &str) -> Result { + pub fn load_font(&mut self, _: &RaylibThread, filename: &str) -> Result { let c_filename = CString::new(filename).unwrap(); let f = unsafe { ffi::LoadFont(c_filename.as_ptr()) }; if f.glyphs.is_null() || f.texture.id == 0 { - return Err(format!( - "Error loading font {}. Does it exist? Is it the right type?", - filename + return Err(error!( + "Error loading font. Check if the file exists and if it's the right type", + filename, )); } Ok(Font(f)) @@ -139,7 +140,7 @@ impl RaylibHandle { filename: &str, font_size: i32, chars: Option<&str>, - ) -> Result { + ) -> Result { let c_filename = CString::new(filename).unwrap(); let f = unsafe { match chars { @@ -156,9 +157,9 @@ impl RaylibHandle { } }; if f.glyphs.is_null() || f.texture.id == 0 { - return Err(format!( - "Error loading font {}. Does it exist? Is it the right type?", - filename + return Err(error!( + "Error loading font. Check if the file exists and if it's the right type", + filename, )); } Ok(Font(f)) @@ -172,10 +173,10 @@ impl RaylibHandle { image: &Image, key: impl Into, first_char: i32, - ) -> Result { + ) -> Result { let f = unsafe { ffi::LoadFontFromImage(image.0, key.into(), first_char) }; if f.glyphs.is_null() { - return Err(format!("Error loading font from image.")); + return Err(error!("Error loading font from image.")); } Ok(Font(f)) } @@ -190,7 +191,7 @@ impl RaylibHandle { file_data: &[u8], font_size: i32, chars: Option<&str>, - ) -> Result { + ) -> Result { let c_file_type = CString::new(file_type).unwrap(); let f = unsafe { match chars { @@ -216,8 +217,8 @@ impl RaylibHandle { } }; if f.glyphs.is_null() || f.texture.id == 0 { - return Err(format!( - "Error loading font from memory. Is it the right type?" + return Err(error!( + "Error loading font from memory. Check if the file's type is correct" )); } Ok(Font(f)) @@ -340,7 +341,7 @@ impl Font { base_size: i32, padding: i32, pack_method: i32, - ) -> Result { + ) -> Result { let f = unsafe { let mut f = std::mem::zeroed::(); f.baseSize = base_size; @@ -359,7 +360,7 @@ impl Font { f }; if f.0.glyphs.is_null() || f.0.texture.id == 0 { - return Err(format!("Error loading font from image.")); + return Err(error!("Error loading font from image.")); } Ok(f) } diff --git a/raylib/src/core/texture.rs b/raylib/src/core/texture.rs index 1741c2de..af6e8b52 100644 --- a/raylib/src/core/texture.rs +++ b/raylib/src/core/texture.rs @@ -3,6 +3,7 @@ use crate::core::color::Color; use crate::core::math::Rectangle; use crate::core::{RaylibHandle, RaylibThread}; +use crate::error::{error, Error}; use crate::ffi; use std::convert::TryInto; use std::ffi::CString; @@ -724,13 +725,13 @@ impl Image { } /// Loads image from file into CPU memory (RAM). - pub fn load_image(filename: &str) -> Result { + pub fn load_image(filename: &str) -> Result { let c_filename = CString::new(filename).unwrap(); let i = unsafe { ffi::LoadImage(c_filename.as_ptr()) }; if i.data.is_null() { - return Err(format!( - "Image data is null. Either the file doesnt exist or the image type is unsupported." - )); + return Err(error!( + "Image data is null. Either the file doesnt exist or the image type is unsupported." + )); } Ok(Image(i)) } @@ -738,7 +739,7 @@ impl Image { /// Loads image from a given memory buffer /// The input data is expected to be in a supported file format such as png. Which formats are /// supported depend on the build flags used for the raylib (C) library. - pub fn load_image_from_mem(filetype: &str, bytes: &[u8]) -> Result { + pub fn load_image_from_mem(filetype: &str, bytes: &[u8]) -> Result { let c_filetype = CString::new(filetype).unwrap(); let i = unsafe { ffi::LoadImageFromMemory( @@ -748,7 +749,7 @@ impl Image { ) }; if i.data.is_null() { - return Err(format!("Image data is null. Check provided buffer data")); + return Err(error!("Image data is null. Check provided buffer data")); }; Ok(Image(i)) } @@ -760,14 +761,14 @@ impl Image { height: i32, format: i32, header_size: i32, - ) -> Result { + ) -> Result { let c_filename = CString::new(filename).unwrap(); let i = unsafe { ffi::LoadImageRaw(c_filename.as_ptr(), width, height, format, header_size) }; if i.data.is_null() { - return Err(format!( - "Image data is null. Either the file doesnt exist or the image type is unsupported." - )); + return Err(error!( + "Image data is null. Either the file doesnt exist or the image type is unsupported." + )); } Ok(Image(i)) } @@ -863,10 +864,10 @@ pub trait RaylibTexture2D: AsRef + AsMut { /// Gets pixel data from GPU texture and returns an `Image`. /// Fairly sure this would never fail. If it does wrap in result. #[inline] - fn load_image(&self) -> Result { + fn load_image(&self) -> Result { let i = unsafe { ffi::LoadImageFromTexture(*self.as_ref()) }; if i.data.is_null() { - return Err(format!("Texture cannot be rendered to an image")); + return Err(error!("Texture cannot be rendered to an image")); } Ok(Image(i)) } @@ -908,11 +909,11 @@ pub fn get_pixel_data_size(width: i32, height: i32, format: ffi::PixelFormat) -> impl RaylibHandle { /// Loads texture from file into GPU memory (VRAM). - pub fn load_texture(&mut self, _: &RaylibThread, filename: &str) -> Result { + pub fn load_texture(&mut self, _: &RaylibThread, filename: &str) -> Result { let c_filename = CString::new(filename).unwrap(); let t = unsafe { ffi::LoadTexture(c_filename.as_ptr()) }; if t.id == 0 { - return Err(format!("failed to load {} as a texture.", filename)); + return Err(error!("failed to load the texture.", filename)); } Ok(Texture2D(t)) } @@ -923,10 +924,10 @@ impl RaylibHandle { _: &RaylibThread, image: &Image, layout: crate::consts::CubemapLayout, - ) -> Result { + ) -> Result { let t = unsafe { ffi::LoadTextureCubemap(image.0, layout as i32) }; if t.id == 0 { - return Err(format!("failed to load image as a texture cubemap.")); + return Err(error!("failed to load image as a texture cubemap.")); } Ok(Texture2D(t)) } @@ -937,10 +938,10 @@ impl RaylibHandle { &mut self, _: &RaylibThread, image: &Image, - ) -> Result { + ) -> Result { let t = unsafe { ffi::LoadTextureFromImage(image.0) }; if t.id == 0 { - return Err(format!("failed to load image as a texture.")); + return Err(error!("failed to load image as a texture.")); } Ok(Texture2D(t)) } @@ -951,10 +952,10 @@ impl RaylibHandle { _: &RaylibThread, width: u32, height: u32, - ) -> Result { + ) -> Result { let t = unsafe { ffi::LoadRenderTexture(width as i32, height as i32) }; if t.id == 0 { - return Err(format!("failed to create render texture.")); + return Err(error!("failed to create render texture.")); } Ok(RenderTexture2D(t)) } From aa6f9711b70b41990cd905ac27180ee593309c86 Mon Sep 17 00:00:00 2001 From: computermouth Date: Fri, 9 Aug 2024 12:07:07 -0600 Subject: [PATCH 31/93] fix matrix rotation on axis --- raylib/src/core/math.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/raylib/src/core/math.rs b/raylib/src/core/math.rs index ff49c338..5da22067 100644 --- a/raylib/src/core/math.rs +++ b/raylib/src/core/math.rs @@ -1456,8 +1456,8 @@ impl Matrix { let sinres = angle.sin(); result.m5 = cosres; - result.m6 = -sinres; - result.m9 = sinres; + result.m6 = sinres; + result.m9 = -sinres; result.m10 = cosres; result } @@ -1470,8 +1470,8 @@ impl Matrix { let sinres = angle.sin(); result.m0 = cosres; - result.m2 = sinres; - result.m8 = -sinres; + result.m2 = -sinres; + result.m8 = sinres; result.m10 = cosres; result } @@ -1484,8 +1484,8 @@ impl Matrix { let sinres = angle.sin(); result.m0 = cosres; - result.m1 = -sinres; - result.m4 = sinres; + result.m1 = sinres; + result.m4 = -sinres; result.m5 = cosres; result } From f799b09de08bafc84e87bb5f5772d1ef4c69a5e8 Mon Sep 17 00:00:00 2001 From: "Nikhil R." Date: Sun, 4 Aug 2024 12:11:23 +0530 Subject: [PATCH 32/93] Replaced `naglebra_interop` with `convert_mint` feature. --- raylib/Cargo.toml | 4 +- raylib/src/core/math.rs | 264 ++++++++++++++++++++-------------------- 2 files changed, 133 insertions(+), 135 deletions(-) diff --git a/raylib/Cargo.toml b/raylib/Cargo.toml index 3a5cb773..52ceaf78 100644 --- a/raylib/Cargo.toml +++ b/raylib/Cargo.toml @@ -19,7 +19,7 @@ lazy_static = "1.2.0" cfg-if = "1.0.0" serde = { version = "1.0.125", features = ["derive"], optional = true } serde_json = { version = "1.0.64", optional = true } -nalgebra = { version = "0.26", optional = true } +mint = { version = "0.5.9", optional = true } parking_lot = "0.12.1" specs-derive = "0.4.1" @@ -35,8 +35,8 @@ default-features = false [features] nightly = [] with_serde = ["serde", "serde_json"] -nalgebra_interop = ["nalgebra"] wayland = ["raylib-sys/wayland"] +convert_mint = ["mint"] custom_frame_control = ["raylib-sys/custom_frame_control"] opengl_33 = ["raylib-sys/opengl_33"] opengl_21 = ["raylib-sys/opengl_21"] diff --git a/raylib/src/core/math.rs b/raylib/src/core/math.rs index 5da22067..7d90c317 100644 --- a/raylib/src/core/math.rs +++ b/raylib/src/core/math.rs @@ -19,8 +19,6 @@ use crate::misc::AsF32; use std::f32::consts::PI; use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Range, Sub, SubAssign}; -#[cfg(feature = "nalgebra_interop")] -use nalgebra as na; #[cfg(feature = "with_serde")] use serde::{Deserialize, Serialize}; @@ -49,24 +47,24 @@ optional_serde_struct! { } } -#[cfg(feature = "nalgebra_interop")] -impl From> for Vector2 { - fn from(v: na::Vector2) -> Vector2 { +#[cfg(feature = "convert_mint")] +impl From> for Vector2 { + fn from(v: mint::Vector2) -> Vector2 { Vector2 { x: v.x, y: v.y } } } -#[cfg(feature = "nalgebra_interop")] -impl From> for Vector2 { - fn from(v: na::base::coordinates::XY) -> Vector2 { +#[cfg(feature = "convert_mint")] +impl From> for Vector2 { + fn from(v: mint::Point2) -> Vector2 { Vector2 { x: v.x, y: v.y } } } -#[cfg(feature = "nalgebra_interop")] -impl Into> for Vector2 { - fn into(self) -> na::Vector2 { - na::Vector2::new(self.x, self.y) +#[cfg(feature = "convert_mint")] +impl From for mint::Vector2 { + fn from(v: Vector2) -> Self { + Self { x: v.x, y: v.y } } } @@ -76,17 +74,17 @@ impl From for Vector2 { } } -impl Into for Vector2 { - fn into(self) -> ffi::Vector2 { - unsafe { std::mem::transmute(self) } +impl From for ffi::Vector2 { + fn from(v: Vector2) -> Self { + unsafe { std::mem::transmute(v) } } } -impl Into for &Vector2 { - fn into(self) -> ffi::Vector2 { +impl From<&Vector2> for ffi::Vector2 { + fn from(v: &Vector2) -> ffi::Vector2 { ffi::Vector2 { - x: self.x, - y: self.y, + x: v.x, + y: v.y, } } } @@ -94,7 +92,7 @@ impl Into for &Vector2 { /// A convenience function for linearly interpolating an `f32`. #[inline] pub fn lerp(v0: f32, v1: f32, amount: f32) -> f32 { - return v0 + amount * (v1 - v0); + v0 + amount * (v1 - v0) } /// A convenience function for making a new `Vector2`. @@ -398,9 +396,9 @@ optional_serde_struct! { } } -#[cfg(feature = "nalgebra_interop")] -impl From> for Vector3 { - fn from(v: na::Vector3) -> Vector3 { +#[cfg(feature = "convert_mint")] +impl From> for Vector3 { + fn from(v: mint::Vector3) -> Vector3 { Vector3 { x: v.x, y: v.y, @@ -409,9 +407,9 @@ impl From> for Vector3 { } } -#[cfg(feature = "nalgebra_interop")] -impl From> for Vector3 { - fn from(v: na::base::coordinates::XYZ) -> Vector3 { +#[cfg(feature = "convert_mint")] +impl From> for Vector3 { + fn from(v: mint::Point3) -> Vector3 { Vector3 { x: v.x, y: v.y, @@ -420,10 +418,14 @@ impl From> for Vector3 { } } -#[cfg(feature = "nalgebra_interop")] -impl Into> for Vector3 { - fn into(self) -> na::Vector3 { - na::Vector3::new(self.x, self.y, self.z) +#[cfg(feature = "convert_mint")] +impl From for mint::Vector3 { + fn from(v: Vector3) -> Self { + Self { + x: v.x, + y: v.y, + z: v.z + } } } @@ -433,18 +435,18 @@ impl From for Vector3 { } } -impl Into for Vector3 { - fn into(self) -> ffi::Vector3 { - unsafe { std::mem::transmute(self) } +impl From for ffi::Vector3 { + fn from(v: Vector3) -> Self { + unsafe { std::mem::transmute(v) } } } -impl Into for &Vector3 { - fn into(self) -> ffi::Vector3 { +impl From<&Vector3> for ffi::Vector3 { + fn from(v: &Vector3) -> ffi::Vector3 { ffi::Vector3 { - x: self.x, - y: self.y, - z: self.z, + x: v.x, + y: v.y, + z: v.z, } } } @@ -859,9 +861,9 @@ optional_serde_struct! { pub type Quaternion = Vector4; -#[cfg(feature = "nalgebra_interop")] -impl From> for Vector4 { - fn from(v: na::Vector4) -> Vector4 { +#[cfg(feature = "convert_mint")] +impl From> for Vector4 { + fn from(v: mint::Vector4) -> Vector4 { Vector4 { x: v.x, y: v.y, @@ -871,10 +873,10 @@ impl From> for Vector4 { } } -#[cfg(feature = "nalgebra_interop")] -impl From> for Vector4 { - fn from(v: na::base::coordinates::XYZW) -> Vector4 { - Vector4 { +#[cfg(feature = "convert_mint")] +impl From for mint::Vector4 { + fn from(v: Vector4) -> Self { + mint::Vector4 { x: v.x, y: v.y, z: v.z, @@ -883,32 +885,25 @@ impl From> for Vector4 { } } -#[cfg(feature = "nalgebra_interop")] -impl Into> for Vector4 { - fn into(self) -> na::Vector4 { - na::Vector4::new(self.x, self.y, self.z, self.w) - } -} - impl From for Vector4 { fn from(v: ffi::Vector4) -> Vector4 { unsafe { std::mem::transmute(v) } } } -impl Into for Vector4 { - fn into(self) -> ffi::Vector4 { - unsafe { std::mem::transmute(self) } +impl From for ffi::Vector4 { + fn from(v: Vector4) -> ffi::Vector4 { + unsafe { std::mem::transmute(v) } } } -impl Into for &Vector4 { - fn into(self) -> ffi::Vector4 { +impl From<&Vector4> for ffi::Vector4 { + fn from(v: &Vector4) -> ffi::Vector4 { ffi::Vector4 { - x: self.x, - y: self.y, - z: self.z, - w: self.w, + x: v.x, + y: v.y, + z: v.z, + w: v.w, } } } @@ -1231,22 +1226,25 @@ impl Quaternion { } } -#[cfg(feature = "nalgebra_interop")] -impl From> for Quaternion { - fn from(q: na::geometry::Quaternion) -> Quaternion { +#[cfg(feature = "convert_mint")] +impl From> for Quaternion { + fn from(q: mint::Quaternion) -> Quaternion { Quaternion { - x: q.coords.x, - y: q.coords.y, - z: q.coords.z, - w: q.coords.w, + x: q.v.x, + y: q.v.y, + z: q.v.z, + w: q.s, } } } -#[cfg(feature = "nalgebra_interop")] -impl Into> for Quaternion { - fn into(self) -> na::geometry::Quaternion { - na::geometry::Quaternion::new(self.x, self.y, self.z, self.w) +#[cfg(feature = "convert_mint")] +impl From for mint::Quaternion { + fn from(q: Quaternion) -> Self { + Self { + v: mint::Vector3 { x: q.x, y: q.y, z: q.z }, + s: q.w, + } } } @@ -1311,31 +1309,31 @@ impl From for Matrix { } } -impl Into for Matrix { - fn into(self) -> ffi::Matrix { - unsafe { std::mem::transmute(self) } +impl From for ffi::Matrix { + fn from(v: Matrix) -> Self { + unsafe { std::mem::transmute(v) } } } -impl Into for &Matrix { - fn into(self) -> ffi::Matrix { +impl From<&Matrix> for ffi::Matrix { + fn from(v: &Matrix) -> Self { ffi::Matrix { - m0: self.m0, - m4: self.m4, - m8: self.m8, - m12: self.m12, - m1: self.m1, - m5: self.m5, - m9: self.m9, - m13: self.m13, - m2: self.m2, - m6: self.m6, - m10: self.m10, - m14: self.m14, - m3: self.m3, - m7: self.m7, - m11: self.m11, - m15: self.m15, + m0: v.m0, + m4: v.m4, + m8: v.m8, + m12: v.m12, + m1: v.m1, + m5: v.m5, + m9: v.m9, + m13: v.m13, + m2: v.m2, + m6: v.m6, + m10: v.m10, + m14: v.m14, + m3: v.m3, + m7: v.m7, + m11: v.m11, + m15: v.m15, } } } @@ -1887,17 +1885,17 @@ impl From for Ray { } } -impl Into for Ray { - fn into(self) -> ffi::Ray { - unsafe { std::mem::transmute(self) } +impl From for ffi::Ray { + fn from(v: Ray) -> ffi::Ray { + unsafe { std::mem::transmute(v) } } } -impl Into for &Ray { - fn into(self) -> ffi::Ray { +impl From<&Ray> for ffi::Ray { + fn from(v: &Ray) -> ffi::Ray { ffi::Ray { - position: self.position.into(), - direction: self.direction.into(), + position: v.position.into(), + direction: v.direction.into(), } } } @@ -1917,19 +1915,19 @@ impl From for Rectangle { } } -impl Into for Rectangle { - fn into(self) -> ffi::Rectangle { - unsafe { std::mem::transmute(self) } +impl From for ffi::Rectangle { + fn from(v: Rectangle) -> ffi::Rectangle { + unsafe { std::mem::transmute(v) } } } -impl Into for &Rectangle { - fn into(self) -> ffi::Rectangle { +impl From<&Rectangle> for ffi::Rectangle { + fn from(v: &Rectangle) -> ffi::Rectangle { ffi::Rectangle { - x: self.x, - y: self.y, - width: self.width, - height: self.height, + x: v.x, + y: v.y, + width: v.width, + height: v.height, } } } @@ -1965,17 +1963,17 @@ impl From for BoundingBox { } } -impl Into for BoundingBox { - fn into(self) -> ffi::BoundingBox { - unsafe { std::mem::transmute(self) } +impl From for ffi::BoundingBox { + fn from(v: BoundingBox) -> ffi::BoundingBox { + unsafe { std::mem::transmute(v) } } } -impl Into for &BoundingBox { - fn into(self) -> ffi::BoundingBox { +impl From<&BoundingBox> for ffi::BoundingBox { + fn from(v: &BoundingBox) -> ffi::BoundingBox { ffi::BoundingBox { - min: self.min.into(), - max: self.max.into(), + min: v.min.into(), + max: v.max.into(), } } } @@ -1995,19 +1993,19 @@ impl From for RayCollision { } } -impl Into for RayCollision { - fn into(self) -> ffi::RayCollision { - unsafe { std::mem::transmute(self) } +impl From for ffi::RayCollision { + fn from(v: RayCollision) -> ffi::RayCollision { + unsafe { std::mem::transmute(v) } } } -impl Into for &RayCollision { - fn into(self) -> ffi::RayCollision { +impl From<&RayCollision> for ffi::RayCollision { + fn from(v: &RayCollision) -> ffi::RayCollision { ffi::RayCollision { - hit: self.hit.into(), - distance: self.distance.into(), - point: self.point.into(), - normal: self.normal.into(), + hit: v.hit, + distance: v.distance, + point: v.point.into(), + normal: v.normal.into(), } } } @@ -2026,18 +2024,18 @@ impl From for Transform { } } -impl Into for Transform { - fn into(self) -> ffi::Transform { - unsafe { std::mem::transmute(self) } +impl From for ffi::Transform { + fn from(v: Transform) -> ffi::Transform { + unsafe { std::mem::transmute(v) } } } -impl Into for &Transform { - fn into(self) -> ffi::Transform { +impl From<&Transform> for ffi::Transform { + fn from(v: &Transform) -> ffi::Transform { ffi::Transform { - translation: self.translation.into(), - rotation: self.rotation.into(), - scale: self.scale.into(), + translation: v.translation.into(), + rotation: v.rotation.into(), + scale: v.scale.into(), } } } From 4b1da95cbfab8e3d96fdcb186478330035fc9490 Mon Sep 17 00:00:00 2001 From: IoIxD <30945097+IoIxD@users.noreply.github.com> Date: Thu, 15 Aug 2024 20:05:50 -0700 Subject: [PATCH 33/93] readme: fixed readme --- README.md | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/README.md b/README.md index 0ee3a9d9..97e3f89e 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,3 @@ -

- -![rust](https://img.shields.io/badge/rust-1.78+-orange.svg?style=flat-square&logo=rust) -![logo](logo/raylib-rust_256x256.png) -[![crates.io](https://img.shields.io/crates/v/raylib.svg?style=flat-square)](https://crates.io/crates/raylib) -[![docs](https://docs.rs/raylib/badge.svg)](https://docs.rs/raylib) -[![discord](https://img.shields.io/discord/426912293134270465)](https://discord.gg/VkzNHUE) - -

-
@@ -19,7 +9,7 @@ # raylib-rs -raylib-rs is a Rust binding for [raylib](http://www.raylib.com/) 5.0. It currently targets the _stable_ Rust toolchain, version 1.78 or higher. +raylib-rs is a Rust binding for [raylib](http://www.raylib.com/) 5.1. It currently targets Rust toolchain version 1.78 or higher. Please checkout the showcase directory to find usage examples! From 172810ab5f7446c97a47c1636eca2963d6e9de1d Mon Sep 17 00:00:00 2001 From: Mathys-Gasnier Date: Fri, 16 Aug 2024 10:11:03 +0200 Subject: [PATCH 34/93] Implementing DerefMut for most RaylibDrawHandle Modes --- raylib/src/core/drawing.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index 91430c2e..d88d0d01 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -133,6 +133,11 @@ impl<'a, T> std::ops::Deref for RaylibMode2D<'a, T> { &self.0 } } +impl<'a, T> std::ops::DerefMut for RaylibMode2D<'a, T> { + fn deref_mut(&mut self) -> &mut T { + self.0 + } +} pub trait RaylibMode2DExt where @@ -166,6 +171,11 @@ impl<'a, T> std::ops::Deref for RaylibMode3D<'a, T> { &self.0 } } +impl<'a, T> std::ops::DerefMut for RaylibMode3D<'a, T> { + fn deref_mut(&mut self) -> &mut T { + self.0 + } +} pub trait RaylibMode3DExt where @@ -200,6 +210,11 @@ impl<'a, T> std::ops::Deref for RaylibShaderMode<'a, T> { &self.0 } } +impl<'a, T> std::ops::DerefMut for RaylibShaderMode<'a, T> { + fn deref_mut(&mut self) -> &mut T { + self.0 + } +} pub trait RaylibShaderModeExt where @@ -231,6 +246,11 @@ impl<'a, T> std::ops::Deref for RaylibBlendMode<'a, T> { &self.0 } } +impl<'a, T> std::ops::DerefMut for RaylibBlendMode<'a, T> { + fn deref_mut(&mut self) -> &mut T { + self.0 + } +} pub trait RaylibBlendModeExt where @@ -262,6 +282,11 @@ impl<'a, T> std::ops::Deref for RaylibScissorMode<'a, T> { &self.0 } } +impl<'a, T> std::ops::DerefMut for RaylibScissorMode<'a, T> { + fn deref_mut(&mut self) -> &mut T { + self.0 + } +} pub trait RaylibScissorModeExt where From 2eafc33c5fec4dd97be74da50b0bd433be347e0a Mon Sep 17 00:00:00 2001 From: IoIxD <30945097+IoIxD@users.noreply.github.com> Date: Tue, 20 Aug 2024 20:12:41 -0700 Subject: [PATCH 35/93] Merge the changes just made to stable back into unstable (#82) * should allow you to disable it * enable customize build * unmatched \) * forgot ; * [general] version bump * rolled back the git submodule --------- Co-authored-by: bitten2up --- raylib-sys/Cargo.toml | 6 +++++- raylib-sys/build.rs | 20 ++++++++++++++++++++ raylib-test/Cargo.toml | 4 ++-- raylib/Cargo.toml | 6 ++++-- samples/Cargo.toml | 4 ++-- showcase/Cargo.toml | 4 ++-- 6 files changed, 35 insertions(+), 9 deletions(-) diff --git a/raylib-sys/Cargo.toml b/raylib-sys/Cargo.toml index 90ee6b95..7285a856 100644 --- a/raylib-sys/Cargo.toml +++ b/raylib-sys/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "raylib-sys" -version = "5.1.0" +version = "5.5.0" authors = ["DeltaPHC "] license = "Zlib" description = "Raw FFI bindings for Raylib" @@ -31,5 +31,9 @@ opengl_21 = [] # opengl_11 = [] I couldn't get this one working, the others were fine in my limited testing (unsure about wayland compatibility) opengl_es_20 = [] +# Allow disabling screenshots and gifs on f12 +noscreenshot = [] +nogif = [] + # config.h's SUPPORT_CUSTOM_FRAME_CONTROL custom_frame_control = [] diff --git a/raylib-sys/build.rs b/raylib-sys/build.rs index b28c550d..0399146a 100644 --- a/raylib-sys/build.rs +++ b/raylib-sys/build.rs @@ -126,6 +126,26 @@ fn build_with_cmake(src_path: &str) { builder.define("OPENGL_VERSION", "OFF"); } + // Allows disabling the default maping of screenshot and gif recording in raylib + { + #[cfg(any( + feature = "noscreenshot", + feature = "nogif" + ))] + builder.define("CUSTOMIZE_BUILD", "ON"); + + #[cfg(feature = "noscreenshot")] + builder.define("SUPPORT_SCREEN_CAPTURE", "OFF"); + #[cfg(feature = "nogif")] + builder.define("SUPPORT_GIF_RECORDING", "OFF"); + + // Once again felt this was necessary incase a default was changed :) + #[cfg(not(feature = "noscreenshot"))] + builder.define("SUPPORT_SCREEN_CAPTURE", "ON"); + #[cfg(not(feature = "nogif"))] + builder.define("SUPPORT_GIF_RECORDING", "ON"); + } + match platform { Platform::Desktop => conf.define("PLATFORM", "Desktop"), Platform::Web => conf diff --git a/raylib-test/Cargo.toml b/raylib-test/Cargo.toml index f389105f..5594848b 100644 --- a/raylib-test/Cargo.toml +++ b/raylib-test/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "raylib-test" -version = "5.1.0" +version = "5.5.0" authors = ["David Ayeke"] edition = "2018" license = "Zlib" @@ -9,7 +9,7 @@ repository = "https://github.com/raylib-rs/raylib-rs" [dependencies] -raylib = { version = "5.1.0", path = "../raylib" } +raylib = { version = "5.5.0", path = "../raylib" } lazy_static = "1.2.0" colored = "2.1.0" diff --git a/raylib/Cargo.toml b/raylib/Cargo.toml index 970c5559..ca88baaf 100644 --- a/raylib/Cargo.toml +++ b/raylib/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "raylib" -version = "5.1.0" +version = "5.5.0" authors = ["DeltaPHC "] license = "Zlib" readme = "../README.md" @@ -13,7 +13,7 @@ edition = "2018" autoexamples = false [dependencies] -raylib-sys = { version = "5.1.0", path = "../raylib-sys" } +raylib-sys = { version = "5.5.0", path = "../raylib-sys" } libc = "0.2.45" lazy_static = "1.2.0" cfg-if = "1.0.0" @@ -44,6 +44,8 @@ custom_frame_control = ["raylib-sys/custom_frame_control"] opengl_33 = ["raylib-sys/opengl_33"] opengl_21 = ["raylib-sys/opengl_21"] opengl_es_20 = ["raylib-sys/opengl_es_20"] +noscreenshot = ["raylib-sys/noscreenshot"] +nogif = ["raylib-sys/nogif"] [[example]] name = "specs" diff --git a/samples/Cargo.toml b/samples/Cargo.toml index 2e616830..9c134d75 100644 --- a/samples/Cargo.toml +++ b/samples/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "raylib-examples" -version = "5.1.0" +version = "5.5.0" authors = ["David Ayeke"] edition = "2018" license = "Zlib" @@ -9,7 +9,7 @@ repository = "https://github.com/raylib-rs/raylib-rs" [dependencies] -raylib = { version = "5.1.0", path = "../raylib" } +raylib = { version = "5.5.0", path = "../raylib" } structopt = "0.2" specs-derive = "0.4.1" rand = "0.7" diff --git a/showcase/Cargo.toml b/showcase/Cargo.toml index 60ff0031..1b972a16 100644 --- a/showcase/Cargo.toml +++ b/showcase/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "raylib-showcase" -version = "5.1.0" +version = "5.5.0" authors = ["David Ayeke"] edition = "2018" license = "Zlib" @@ -10,4 +10,4 @@ repository = "https://github.com/raylib-rs/raylib-rs" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -raylib = { version = "5.1.0", path = "../raylib" } +raylib = { version = "5.5.0", path = "../raylib" } From dd266a4db470f242a258cfae3a622acd3e40c5e9 Mon Sep 17 00:00:00 2001 From: IoIxD <30945097+IoIxD@users.noreply.github.com> Date: Tue, 20 Aug 2024 20:28:00 -0700 Subject: [PATCH 36/93] Added more 5.5 functions (#78) * [file] removed. * [window] window mod functions should be mut * [input] SetGamepadVibration should be mut * [general] the rest of the owl * [ci] fix ci * [test] fix drawing * [data] fix example * [general] we DO need to specify the branch because otherwise when cloning the repo to work on it it isn't specified and defaults to 5.0. --- .github/workflows/ci.yml | 6 +- .gitmodules | 1 + raylib-sys/raylib | 2 +- raylib-test/src/data.rs | 32 ----- raylib-test/src/drawing.rs | 2 +- raylib-test/src/random.rs | 2 +- raylib/src/core/audio.rs | 5 + raylib/src/core/color.rs | 22 ++- raylib/src/core/data.rs | 8 +- raylib/src/core/drawing.rs | 28 ++++ raylib/src/core/error.rs | 24 ++-- raylib/src/core/file.rs | 139 ------------------- raylib/src/core/input.rs | 2 +- raylib/src/core/mod.rs | 1 - raylib/src/core/models.rs | 65 ++++++++- raylib/src/core/texture.rs | 278 +++++++++++++++++++++++++++++++++++-- raylib/src/core/window.rs | 6 +- raylib/src/lib.rs | 1 - raylib/src/prelude.rs | 1 - 19 files changed, 414 insertions(+), 211 deletions(-) delete mode 100644 raylib/src/core/file.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 23a1a72e..4716166b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,8 +8,8 @@ jobs: test: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - uses: actions/cache@v2 + - uses: actions/checkout@v4 + - uses: actions/cache@v4 with: path: | ~/.cargo/bin/ @@ -26,5 +26,7 @@ jobs: run: git submodule init; git submodule update - name: Install alsa, udev, glfw3, sdl, and wayland run: sudo apt-get update; sudo apt-get install --no-install-recommends libasound2-dev libudev-dev libglfw3-dev libwayland-dev libsdl2-dev + - name: Clone latest GLFW3 + run: git clone https://github.com/glfw/glfw; cd glfw; mkdir build; cd build; cmake ..; make -j$(nproc); sudo make install; cd ../..; - name: Run doc tests with all features (this also compiles README examples) run: cargo test --doc --all-features diff --git a/.gitmodules b/.gitmodules index a25d66a8..d0e3f3e8 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,4 @@ [submodule "raylib-sys/raylib"] path = raylib-sys/raylib url = https://github.com/raysan5/raylib + commit = "039df36f" diff --git a/raylib-sys/raylib b/raylib-sys/raylib index 11202bf2..039df36f 160000 --- a/raylib-sys/raylib +++ b/raylib-sys/raylib @@ -1 +1 @@ -Subproject commit 11202bf299a70a8ef30e28ab99a8184bbb119a99 +Subproject commit 039df36f4b73cfd685c143f47e71abf93270e709 diff --git a/raylib-test/src/data.rs b/raylib-test/src/data.rs index 7c60884f..a588c836 100644 --- a/raylib-test/src/data.rs +++ b/raylib-test/src/data.rs @@ -15,38 +15,6 @@ mod data_test { ); } - ray_test!(application_dir); - fn application_dir(_: &RaylibThread) { - let mut handle = TEST_HANDLE.write().unwrap(); - let rl = handle.as_mut().unwrap(); - - println!( - "{} {}\n", - "Application directory is ".bold(), - rl.application_directory().bold() - ); - } - - ray_test!(file_length_test); - fn file_length_test(_: &RaylibThread) { - let mut handle = TEST_HANDLE.write().unwrap(); - let rl = handle.as_mut().unwrap(); - - let len = rl.get_file_length("./resources/just_exists.txt"); - assert!(len == 18); - } - - ray_test!(is_path_file); - fn is_path_file(_: &RaylibThread) { - let mut handle = TEST_HANDLE.write().unwrap(); - let rl = handle.as_mut().unwrap(); - - let len = rl.is_path_file("./resources/just_exists.txt"); - assert!(len == true); - let len = rl.is_path_file("./resources/"); - assert!(len == false); - } - ray_test!(base64); fn base64(_: &RaylibThread) { let encoded = encode_data_base64("This is a test".as_bytes()); diff --git a/raylib-test/src/drawing.rs b/raylib-test/src/drawing.rs index 9f4c8b0e..76b2d4f9 100644 --- a/raylib-test/src/drawing.rs +++ b/raylib-test/src/drawing.rs @@ -92,7 +92,7 @@ mod draw_test { 5, Color::BLUE, ); - d.draw_rectangle_rounded_lines( + d.draw_rectangle_rounded_lines_ex( Rectangle::new(220.0, 30.0, 100.0, 100.0), 0.10, 5, diff --git a/raylib-test/src/random.rs b/raylib-test/src/random.rs index 2716d6bd..0899df62 100644 --- a/raylib-test/src/random.rs +++ b/raylib-test/src/random.rs @@ -22,7 +22,7 @@ mod random_test { rl.set_random_seed(1); let rnd = rl.load_random_sequence(1..10, 10); - let exp_rnd = vec![-8, 7, 0, 4, 8, -6, -3, 5, 6, 10]; + let exp_rnd = vec![8, 7, 6, 4, 10, 3, 5, 1, 2, 9]; let mut i = 0; for r in rnd { assert!(r == *exp_rnd.get(i).unwrap()); diff --git a/raylib/src/core/audio.rs b/raylib/src/core/audio.rs index 2eae3592..8d3f3586 100644 --- a/raylib/src/core/audio.rs +++ b/raylib/src/core/audio.rs @@ -521,6 +521,11 @@ impl<'aud> Music<'aud> { ffi::SetMusicPan(self.0, pan); } } + + /// Checks if a music stream is ready + pub fn is_ready(&self) -> bool { + unsafe { ffi::IsMusicReady(self.0) } + } } impl<'aud> AudioStream<'aud> { diff --git a/raylib/src/core/color.rs b/raylib/src/core/color.rs index f7780e2a..c74ad3d3 100644 --- a/raylib/src/core/color.rs +++ b/raylib/src/core/color.rs @@ -1,7 +1,10 @@ //! [`Color`] manipulation helpers +use std::os::raw::c_void; + use crate::core::math::{Vector3, Vector4}; use crate::ffi; +use raylib_sys::{ColorIsEqual, GetPixelColor, PixelFormat}; #[cfg(not(feature = "with_serde"))] #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; @@ -14,8 +17,10 @@ use serde::{Deserialize, Serialize}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; +use super::RaylibHandle; + #[repr(C)] -#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)] +#[derive(Debug, Copy, Clone, Default)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct Color { pub r: u8, @@ -145,7 +150,7 @@ impl Color { /// Color fade-in or fade-out, alpha goes from 0.0f to 1.0f #[inline] - #[deprecated = "Has been superseded by .fade()"] + #[deprecated = "Has been superseded by Color::alpha()"] pub fn fade(&self, alpha: f32) -> Color { unsafe { ffi::Fade(self.into(), alpha).into() } } @@ -171,7 +176,20 @@ impl Color { pub fn color_alpha_blend(dst: &Color, src: &Color, tint: &Color) -> Color { unsafe { ffi::ColorAlphaBlend(dst.into(), src.into(), tint.into()).into() } } + /// Check if color is equal to another. + pub fn is_equal(&self, rhs: impl Into) -> bool { + unsafe { ffi::ColorIsEqual(self.into(), rhs.into()) } + } +} + +/// NOTE(IOI_XD): We manually implement PartialEq as of 5.5 to use Raylib's function. It's very unlikely it will ever +/// change or do anything different, but in the ultra rare case that it does, we want to mimick Raylib's behavior. +impl PartialEq for Color { + fn eq(&self, other: &Self) -> bool { + return self.is_equal(other); + } } +impl Eq for Color {} /// Color constants impl Color { diff --git a/raylib/src/core/data.rs b/raylib/src/core/data.rs index 5c93c381..d6386464 100644 --- a/raylib/src/core/data.rs +++ b/raylib/src/core/data.rs @@ -9,9 +9,9 @@ use crate::{ /// Compress data (DEFLATE algorythm) /// ```rust /// use raylib::prelude::*; -/// let data = compress_data(b"11111"); +/// let data = compress_data(b"11111").unwrap(); /// let expected: &[u8] = &[1, 5, 0, 250, 255, 49, 49, 49, 49, 49]; -/// assert_eq!(data, Ok(expected)); +/// assert_eq!(data, expected); /// ``` pub fn compress_data(data: &[u8]) -> Result<&'static [u8], Error> { let mut out_length: i32 = 0; @@ -31,8 +31,8 @@ pub fn compress_data(data: &[u8]) -> Result<&'static [u8], Error> { /// use raylib::prelude::*; /// let input: &[u8] = &[1, 5, 0, 250, 255, 49, 49, 49, 49, 49]; /// let expected: &[u8] = b"11111"; -/// let data = decompress_data(input); -/// assert_eq!(data, Ok(expected)); +/// let data = decompress_data(input).unwrap(); +/// assert_eq!(data, expected); /// ``` pub fn decompress_data(data: &[u8]) -> Result<&'static [u8], Error> { println!("{:?}", data.len()); diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index d88d0d01..cd43ee4e 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -1866,4 +1866,32 @@ pub trait RaylibDraw3D { ); } } + + /// Draw a billboard texture defined by source and rotation + fn draw_billboard_pro( + &mut self, + camera: impl Into, + texture: impl Into, + source: impl Into, + position: impl Into, + up: impl Into, + size: impl Into, + origin: impl Into, + rotation: f32, + tint: impl Into, + ) { + unsafe { + ffi::DrawBillboardPro( + camera.into(), + texture.into(), + source.into(), + position.into(), + up.into(), + size.into(), + origin.into(), + rotation, + tint.into(), + ) + } + } } diff --git a/raylib/src/core/error.rs b/raylib/src/core/error.rs index c57cec2a..2cdd68a1 100644 --- a/raylib/src/core/error.rs +++ b/raylib/src/core/error.rs @@ -1,6 +1,6 @@ //! Definitions for error types used throught the crate -use std::path::PathBuf; +use std::{borrow::Cow, path::PathBuf}; use thiserror::Error; @@ -10,26 +10,32 @@ use thiserror::Error; path = path.as_ref().map(|p| format!("\npath: {}", p.display())).unwrap_or("".to_owned()), )] pub struct Error { - // NOTE(alexmozaidze): There is not a single instance of the message being dynamic in this crate, - // so if there occurs an instance where the message is to be determined at runtime, then - // use `Cow<'static, str>`. - // - // One could also use generics, but that would make the error type much more complex to use - // and to reason about for the user. - pub(crate) message: &'static str, + pub(crate) message: Cow<'static, str>, pub(crate) path: Option, } impl Error { - pub(crate) const fn new(message: &'static str, path: Option) -> Self { + pub(crate) const fn new(message: Cow<'static, str>, path: Option) -> Self { Self { message, path } } } macro_rules! error { + ($message:literal) => {{ + $crate::core::error::Error::new( + std::borrow::Cow::Borrowed($message), + ::core::option::Option::None, + ) + }}; ($message:expr $(,)?) => {{ $crate::core::error::Error::new($message, ::core::option::Option::None) }}; + ($message:literal, $path:expr $(,)?) => {{ + $crate::core::error::Error::new( + std::borrow::Cow::Borrowed($message), + ::core::option::Option::Some(::std::path::PathBuf::from($path)), + ) + }}; ($message:expr, $path:expr $(,)?) => {{ $crate::core::error::Error::new( $message, diff --git a/raylib/src/core/file.rs b/raylib/src/core/file.rs deleted file mode 100644 index abe3dfaa..00000000 --- a/raylib/src/core/file.rs +++ /dev/null @@ -1,139 +0,0 @@ -//! File manipulation functions. Should be parity with std::fs except on emscripten -use crate::ffi; - -use crate::core::RaylibHandle; -use std::ffi::{CStr, CString, OsString}; - -make_thin_wrapper!(FilePathList, ffi::FilePathList, ffi::UnloadDirectoryFiles); -make_thin_wrapper!( - DroppedFilePathList, - ffi::FilePathList, - ffi::UnloadDroppedFiles -); - -impl FilePathList { - /// Length of the file path list - pub const fn count(&self) -> u32 { - self.0.count - } - /// The amount of files that can be held in this list. - pub const fn capacity(&self) -> u32 { - self.0.capacity - } - /// The paths held in this list. - /// This function is NOT constant and the inner array will be copied into the returned Vec every time you call this. - pub fn paths(&self) -> Vec<&str> { - unsafe { std::slice::from_raw_parts(self.0.paths, self.count() as usize) } - .iter() - .map(|f| unsafe { CStr::from_ptr(*f) }.to_str().unwrap()) - .collect() - } -} - -impl DroppedFilePathList { - /// Length of the file path list - pub const fn count(&self) -> u32 { - self.0.count - } - /// The amount of files that can be held in this list. - pub const fn capacity(&self) -> u32 { - self.0.capacity - } - /// The paths held in this list. - /// This function is NOT constant and the inner array will be copied into the returned Vec every time you call this. - pub fn paths(&self) -> Vec<&str> { - unsafe { std::slice::from_raw_parts(self.0.paths, self.count() as usize) } - .iter() - .map(|f| unsafe { CStr::from_ptr(*f) }.to_str().unwrap()) - .collect() - } -} - -impl RaylibHandle { - /// Checks if a file has been dropped into the window. - #[inline] - pub fn is_file_dropped(&self) -> bool { - unsafe { ffi::IsFileDropped() } - } - - /// Checks a file's extension. - #[inline] - pub fn is_file_extension(&self, file_name: A, file_ext: A) -> bool - where - A: Into, - { - let file_name = CString::new(file_name.into().to_string_lossy().as_bytes()).unwrap(); - let file_ext = CString::new(file_ext.into().to_string_lossy().as_bytes()).unwrap(); - unsafe { ffi::IsFileExtension(file_name.as_ptr(), file_ext.as_ptr()) } - } - /// Get the directory of the running application. - pub fn application_directory(&self) -> String { - unsafe { - let st = ffi::GetApplicationDirectory(); - let c_str = CStr::from_ptr(st); - - // If this ever errors out, yell at @ioi_xd on Discord, - c_str.to_str().unwrap().to_string() - } - } - - /// Get file length in bytes. - /// - /// # Errors - /// This function will return an error if the supplied bytes contain an internal 0 byte. The NulError returned will contain the bytes as well as the position of the nul byte. - pub fn get_file_length(&self, filename: A) -> i32 - where - A: Into, - { - let c_str = CString::new(filename.into().to_string_lossy().as_bytes()).unwrap(); - unsafe { ffi::GetFileLength(c_str.as_ptr()) } - } - - /// Check if a given path is a file or a directory - /// # Errors - /// This function will return an error if the supplied bytes contain an internal 0 byte. The NulError returned will contain the bytes as well as the position of the nul byte. - pub fn is_path_file(&self, filename: A) -> bool - where - A: Into, - { - let c_str = CString::new(filename.into().to_string_lossy().as_bytes()).unwrap(); - unsafe { ffi::IsPathFile(c_str.as_ptr()) } - } - - /// Load directory filepaths - pub fn load_directory_files(&self, dir_path: A) -> FilePathList - where - A: Into, - { - unsafe { - let c_str = CString::new(dir_path.into().to_string_lossy().as_bytes()).unwrap(); // .unwrap() is okay here because any nul bytes placed into the actual string should be cleared out by to_string_lossy. - FilePathList(ffi::LoadDirectoryFiles(c_str.as_ptr())) - } - } - - /// Load directory filepaths with extension filtering and recursive directory scan - pub fn load_directory_files_ex( - &self, - dir_path: A, - filter: String, - scan_sub_dirs: bool, - ) -> FilePathList - where - A: Into, - { - unsafe { - let dir_c_str = CString::new(dir_path.into().to_string_lossy().as_bytes()).unwrap(); // .unwrap() is okay here because any nul bytes placed into the actual string should be cleared out by to_string_lossy. - let filter_c_str = CString::new(filter.replace("\0", "").as_bytes()).unwrap(); - FilePathList(ffi::LoadDirectoryFilesEx( - dir_c_str.as_ptr(), - filter_c_str.as_ptr(), - scan_sub_dirs, - )) - } - } - - /// Check if a file has been dropped into window - pub fn load_dropped_files(&self) -> DroppedFilePathList { - unsafe { DroppedFilePathList(ffi::LoadDroppedFiles()) } - } -} diff --git a/raylib/src/core/input.rs b/raylib/src/core/input.rs index af3c1823..c7c10052 100644 --- a/raylib/src/core/input.rs +++ b/raylib/src/core/input.rs @@ -283,7 +283,7 @@ impl RaylibHandle { } /// Set gamepad vibration for both motors - pub fn set_gamepad_vibration(&self, gamepad: i32, left_motor: f32, right_motor: f32) { + pub fn set_gamepad_vibration(&mut self, gamepad: i32, left_motor: f32, right_motor: f32) { unsafe { ffi::SetGamepadVibration(gamepad, left_motor, right_motor) } } diff --git a/raylib/src/core/mod.rs b/raylib/src/core/mod.rs index 30f22ff9..847e8807 100644 --- a/raylib/src/core/mod.rs +++ b/raylib/src/core/mod.rs @@ -10,7 +10,6 @@ pub mod color; pub mod data; pub mod drawing; pub mod error; -pub mod file; pub mod input; pub mod logging; pub mod math; diff --git a/raylib/src/core/models.rs b/raylib/src/core/models.rs index 7c81bdbf..b2fd462d 100644 --- a/raylib/src/core/models.rs +++ b/raylib/src/core/models.rs @@ -1,4 +1,6 @@ //! 3D Model, Mesh, and Animation +use raylib_sys::GetModelBoundingBox; + use crate::core::math::{BoundingBox, Vector3}; use crate::core::texture::Image; use crate::core::{RaylibHandle, RaylibThread}; @@ -59,7 +61,10 @@ impl RaylibHandle { let m = unsafe { ffi::LoadModel(c_filename.as_ptr()) }; if m.meshes.is_null() && m.materials.is_null() && m.bones.is_null() && m.bindPose.is_null() { - return Err(error!("could not load model", filename)); + return Err(error!( + "could not load model", + filename + )); } // TODO check if null pointer checks are necessary. Ok(Model(m)) @@ -74,7 +79,9 @@ impl RaylibHandle { 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")); + return Err(error!( + "Could not load model from mesh" + )); } Ok(Model(m)) @@ -89,7 +96,10 @@ impl RaylibHandle { 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)); + 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 { @@ -212,6 +222,32 @@ pub trait RaylibModel: AsRef + AsMut { 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_ready(&self) -> bool { + unsafe { ffi::IsModelReady(*self.as_ref()) } + } + + /// Compute model bounding box limits (considers all meshes) + fn get_model_bounding_box(&self) -> BoundingBox { + unsafe { BoundingBox::from(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 { + return Err(error!( + "mesh_id greater than mesh count" + )); + } else if material_id >= self.as_ref().materialCount { + return Err(error!( + "material_id greater than material count" + )); + } else { + unsafe { ffi::SetModelMeshMaterial(self.as_mut(), mesh_id, material_id) }; + return Ok(()); + }; + } } impl RaylibMesh for WeakMesh {} @@ -386,6 +422,11 @@ pub trait RaylibMesh: AsRef + AsMut { 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 { @@ -409,6 +450,15 @@ pub trait RaylibMesh: AsRef + AsMut { 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 { @@ -423,7 +473,10 @@ impl Material { 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)); + return Err(error!( + "No materials loaded", + filename + )); } let mut m_vec = Vec::with_capacity(m_size as usize); for i in 0..m_size { @@ -477,6 +530,10 @@ pub trait RaylibMaterial: AsRef + AsMut { ffi::SetMaterialTexture(self.as_mut(), (map_type as u32) as i32, *texture.as_ref()) } } + + fn is_ready(&mut self) -> bool { + unsafe { ffi::IsMaterialReady(*self.as_ref()) } + } } impl RaylibModelAnimation for ModelAnimation {} diff --git a/raylib/src/core/texture.rs b/raylib/src/core/texture.rs index af6e8b52..1a84c435 100644 --- a/raylib/src/core/texture.rs +++ b/raylib/src/core/texture.rs @@ -1,5 +1,10 @@ //! Image and texture related functions +use raylib_sys::{ + ExportImageToMemory, GetPixelColor, ImageKernelConvolution, LoadImageAnim, + LoadImageAnimFromMemory, PixelFormat, +}; + use crate::core::color::Color; use crate::core::math::Rectangle; use crate::core::{RaylibHandle, RaylibThread}; @@ -8,6 +13,10 @@ use crate::ffi; use std::convert::TryInto; use std::ffi::CString; use std::mem::ManuallyDrop; +use std::os::raw::c_void; +use std::ptr::{null, null_mut}; + +use super::math::Vector2; make_rslice!(ImagePalette, Color, ffi::UnloadImagePalette); make_rslice!(ImageColors, Color, ffi::UnloadImageColors); @@ -189,6 +198,9 @@ impl Image { unsafe { Image(ffi::ImageFromImage(self.0, rec.into())) } } + pub fn from_channel(&self, selected_channel: i32) -> Image { + unsafe { Image(ffi::ImageFromChannel(self.0, selected_channel)) } + } /// Exports image as a PNG file. #[inline] pub fn export_image(&self, filename: &str) { @@ -418,6 +430,17 @@ impl Image { } } + /// Draw a line (using triangles/quads) + pub fn draw_line_ex( + &mut self, + start_pos: impl Into, + end_pos: impl Into, + thick: f32, + color: impl Into, + ) { + unsafe { ffi::DrawLineEx(start_pos.into(), end_pos.into(), thick, color.into()) } + } + /// Draw line within an image (Vector version) #[inline] pub fn draw_line_v( @@ -429,6 +452,87 @@ impl Image { unsafe { ffi::ImageDrawLineV(&mut self.0, start.into(), end.into(), color.into()) } } + /// Draw triangle within an image + pub fn draw_triangle( + &mut self, + v1: impl Into, + v2: impl Into, + v3: impl Into, + color: impl Into, + ) { + unsafe { + ffi::ImageDrawTriangle(&mut self.0, v1.into(), v2.into(), v3.into(), color.into()) + } + } + + /// Draw triangle with interpolated colors within an image + pub fn draw_triangle_ex( + &mut self, + v1: impl Into, + v2: impl Into, + v3: impl Into, + c1: impl Into, + c2: impl Into, + c3: impl Into, + ) { + unsafe { + ffi::ImageDrawTriangleEx( + &mut self.0, + v1.into(), + v2.into(), + v3.into(), + c1.into(), + c2.into(), + c3.into(), + ) + } + } + + /// Draw triangle outline within an image + pub fn draw_triangle_lines( + &mut self, + v1: impl Into, + v2: impl Into, + v3: impl Into, + color: impl Into, + ) { + unsafe { + ffi::ImageDrawTriangleLines(&mut self.0, v1.into(), v2.into(), v3.into(), color.into()) + } + } + + /// Draw a triangle fan defined by points within an image (first vertex is the center) + pub fn draw_triangle_fan(&mut self, points: Vec, color: impl Into) { + unsafe { + ffi::ImageDrawTriangleFan( + &mut self.0, + points + .iter() + .map(|f| f.into()) + .collect::>() + .as_ptr() as *mut ffi::Vector2, + points.len() as i32, + color.into(), + ) + } + } + + /// Draw a triangle strip defined by points within an image + pub fn draw_triangle_strip(&mut self, points: Vec, color: impl Into) { + unsafe { + ffi::ImageDrawTriangleStrip( + &mut self.0, + points + .iter() + .map(|f| f.into()) + .collect::>() + .as_ptr() as *mut ffi::Vector2, + points.len() as i32, + color.into(), + ) + } + } + /// Draw circle within an image #[inline] pub fn draw_circle( @@ -467,6 +571,29 @@ impl Image { } } + /// Draw rectangle within an image (Vector version) + pub fn draw_rectangle_v( + &mut self, + position: impl Into, + size: impl Into, + color: impl Into, + ) { + unsafe { + ffi::DrawRectangleV(position.into(), size.into(), color.into()); + } + } + + /// Draw rectangle within an image (Rectangle version) + pub fn draw_rectangle_rec( + &mut self, + rectangle: impl Into, + color: impl Into, + ) { + unsafe { + ffi::DrawRectangleRec(rectangle.into(), color.into()); + } + } + /// Draws a rectangle within an image. #[inline] pub fn draw_rectangle_lines( @@ -608,6 +735,68 @@ impl Image { } } + /// Export image to memory buffer. + pub fn export_image_to_memory(&self, file_type: &str) -> Result<&[u8], Error> { + if self.width == 0 { + return Err(error!( + "Invalid image; width == 0" + )); + } + if self.height == 0 { + return Err(error!( + "Invalid image; height == 0" + )); + } + if self.data == null_mut() { + return Err(error!( + "Invalid image; data == null" + )); + } + + let c_filetype = CString::new(file_type).unwrap(); + let data_size: &mut i32 = &mut 0; + let data = unsafe { ExportImageToMemory(self.0, c_filetype.as_ptr(), data_size) }; + + // The actual function returns null if the code for converting to a file type never goes off. + if data == null_mut() { + return Err(error!("Unsupported format.")); + } + + return Ok(unsafe { std::slice::from_raw_parts(data as *const u8, *data_size as usize) }); + } + + /// Apply custom square convolution kernel to image + /// NOTE: The convolution kernel matrix is expected to be square + pub fn kernel_convolution(&mut self, kernel: &[f32]) -> Result<(), Error> { + if self.width == 0 { + return Err(error!( + "Invalid image; width == 0" + )); + } + if self.height == 0 { + return Err(error!( + "Invalid image; height == 0" + )); + } + if self.data == null_mut() { + return Err(error!( + "Invalid image; data == null" + )); + } + + let kernel_width = (kernel.len() as f32).sqrt() as i32; + + if (kernel_width * kernel_width) as usize != kernel.len() { + return Err(error!( + "Convolution kernel must be square to be applied" + )); + } + + unsafe { ImageKernelConvolution(&mut self.0, kernel.as_ptr(), kernel.len() as i32) } + + Ok(()) + } + /// Generates a plain `color` Image. #[inline] pub fn gen_image_color(width: i32, height: i32, color: impl Into) -> Image { @@ -749,11 +938,38 @@ impl Image { ) }; if i.data.is_null() { - return Err(error!("Image data is null. Check provided buffer data")); + return Err(error!( + "Image data is null. Check provided buffer data" + )); }; Ok(Image(i)) } + /// Load image sequence from file, with the number of frames loaded saved to frame_num. + /// Image.data buffer includes all frames. + /// All frames returned are in RGBA format. + /// Frames delay data is discarded + pub fn load_image_anim(filename: &str, frame_num: &mut i32) -> Self { + let c_filename = CString::new(filename).unwrap(); + + unsafe { Image(LoadImageAnim(c_filename.as_ptr(), frame_num)) } + } + + /// Load image from memory buffer, with the number of frames loaded saved to frame_num. + /// fileType refers to extension: i.e. ".png". File extension must be provided in lower-case + pub fn load_image_anim_from_memory(filetype: &str, data: &[u8], frame_num: &mut i32) -> Self { + let c_filetype = CString::new(filetype).unwrap(); + + unsafe { + Image(LoadImageAnimFromMemory( + c_filetype.as_ptr(), + data.as_ptr(), + data.len() as i32, + frame_num, + )) + } + } + /// Loads image from RAW file data. pub fn load_image_raw( filename: &str, @@ -838,7 +1054,7 @@ pub trait RaylibTexture2D: AsRef + AsMut { /// Updates GPU texture with new data. #[inline] - fn update_texture(&mut self, pixels: &[u8]) { + fn update_texture(&mut self, pixels: &[u8]) -> Result<(), Error> { let expected_len = unsafe { get_pixel_data_size( self.as_ref().width, @@ -847,11 +1063,11 @@ pub trait RaylibTexture2D: AsRef + AsMut { ) as usize }; if pixels.len() != expected_len { - panic!( + return Err(error!(std::borrow::Cow::Owned(format!( "update_texture: Data is wrong size. Expected {}, got {}", expected_len, pixels.len() - ); + )))); } unsafe { ffi::UpdateTexture( @@ -859,6 +1075,39 @@ pub trait RaylibTexture2D: AsRef + AsMut { pixels.as_ptr() as *const std::os::raw::c_void, ); } + + Ok(()) + } + + /// Update GPU texture rectangle with new data + fn update_texture_rec( + &mut self, + rec: impl Into, + pixels: &[u8], + ) -> Result<(), Error> { + let expected_len = unsafe { + get_pixel_data_size( + self.as_ref().width, + self.as_ref().height, + std::mem::transmute::(self.as_ref().format), + ) as usize + }; + if pixels.len() != expected_len { + return Err(error!(std::borrow::Cow::Owned(format!( + "update_texture: Data is wrong size. Expected {}, got {}", + expected_len, + pixels.len() + )))); + } + unsafe { + ffi::UpdateTextureRec( + *self.as_ref(), + rec.into(), + pixels.as_ptr() as *const std::os::raw::c_void, + ) + } + + Ok(()) } /// Gets pixel data from GPU texture and returns an `Image`. @@ -867,7 +1116,9 @@ pub trait RaylibTexture2D: AsRef + AsMut { fn load_image(&self) -> Result { let i = unsafe { ffi::LoadImageFromTexture(*self.as_ref()) }; if i.data.is_null() { - return Err(error!("Texture cannot be rendered to an image")); + return Err(error!( + "Texture cannot be rendered to an image" + )); } Ok(Image(i)) } @@ -913,7 +1164,10 @@ impl RaylibHandle { let c_filename = CString::new(filename).unwrap(); let t = unsafe { ffi::LoadTexture(c_filename.as_ptr()) }; if t.id == 0 { - return Err(error!("failed to load the texture.", filename)); + return Err(error!( + "failed to load the texture.", + filename + )); } Ok(Texture2D(t)) } @@ -927,7 +1181,9 @@ impl RaylibHandle { ) -> Result { let t = unsafe { ffi::LoadTextureCubemap(image.0, layout as i32) }; if t.id == 0 { - return Err(error!("failed to load image as a texture cubemap.")); + return Err(error!( + "failed to load image as a texture cubemap." + )); } Ok(Texture2D(t)) } @@ -941,7 +1197,9 @@ impl RaylibHandle { ) -> Result { let t = unsafe { ffi::LoadTextureFromImage(image.0) }; if t.id == 0 { - return Err(error!("failed to load image as a texture.")); + return Err(error!( + "failed to load image as a texture." + )); } Ok(Texture2D(t)) } @@ -955,7 +1213,9 @@ impl RaylibHandle { ) -> Result { let t = unsafe { ffi::LoadRenderTexture(width as i32, height as i32) }; if t.id == 0 { - return Err(error!("failed to create render texture.")); + return Err(error!( + "failed to create render texture." + )); } Ok(RenderTexture2D(t)) } diff --git a/raylib/src/core/window.rs b/raylib/src/core/window.rs index 23752c58..571c7e40 100644 --- a/raylib/src/core/window.rs +++ b/raylib/src/core/window.rs @@ -536,19 +536,19 @@ impl RaylibHandle { /// Set window state: maximized, if resizable #[inline] - pub fn maximize_window(&self) { + pub fn maximize_window(&mut self) { unsafe { ffi::MaximizeWindow() } } /// Set window state: minimized, if resizable #[inline] - pub fn minimize_window(&self) { + pub fn minimize_window(&mut self) { unsafe { ffi::MinimizeWindow() } } /// Set window state: not minimized/maximized #[inline] - pub fn restore_window(&self) { + pub fn restore_window(&mut self) { unsafe { ffi::RestoreWindow() } } diff --git a/raylib/src/lib.rs b/raylib/src/lib.rs index f12f262e..e88eabad 100644 --- a/raylib/src/lib.rs +++ b/raylib/src/lib.rs @@ -69,7 +69,6 @@ pub mod ffi { } pub use crate::core::collision::*; -pub use crate::core::file::*; pub use crate::core::logging::*; pub use crate::core::misc::open_url; pub use crate::core::*; diff --git a/raylib/src/prelude.rs b/raylib/src/prelude.rs index a3b58ac9..e0482845 100644 --- a/raylib/src/prelude.rs +++ b/raylib/src/prelude.rs @@ -33,7 +33,6 @@ pub use crate::core::collision::*; pub use crate::core::color::*; pub use crate::core::data::*; pub use crate::core::drawing::*; -pub use crate::core::file::*; pub use crate::core::input::*; pub use crate::core::logging::*; pub use crate::core::math::*; From a170ceed3b4453c3b5287fbc049f2472d3d3425a Mon Sep 17 00:00:00 2001 From: IoIxD <30945097+IoIxD@users.noreply.github.com> Date: Sun, 15 Sep 2024 19:32:36 -0700 Subject: [PATCH 37/93] Add closure equivalants to the begin_... functions (#84) * [general] add closure equivalants to the begin functions * allow disabling the deprecation warning * [drawing] removed the End... calls from the new functions, remembering that they get called implicitly * don't do a deprecation warning * Prevent recursive start-drawing calls --- .gitignore | 2 +- raylib-test/Cargo.toml | 2 +- raylib-test/src/callbacks.rs | 13 +- raylib/src/core/drawing.rs | 149 ++++++++++++++- raylib/src/core/shaders.rs | 1 + samples/3d_camera_first_person.rs | 56 +++--- samples/Cargo.toml | 4 + samples/arkanoid.rs | 121 ++++++------ samples/asteroids.rs | 144 +++++++------- samples/camera2D.rs | 96 +++++----- samples/extensions.rs | 7 +- samples/floppy.rs | 112 +++++------ samples/font.rs | 44 ++--- samples/input.rs | 15 +- samples/logo.rs | 14 +- samples/model_shader.rs | 35 ++-- samples/raymarch.rs | 37 ++-- samples/shader_multisample.rs | 52 ++++++ samples/specs.rs | 35 ++-- samples/static/shader/color_mix.fs | 27 +++ samples/texture.rs | 7 +- samples/yaw_pitch_roll.rs | 291 ++++++++++++++--------------- 22 files changed, 731 insertions(+), 533 deletions(-) create mode 100644 samples/shader_multisample.rs create mode 100644 samples/static/shader/color_mix.fs diff --git a/.gitignore b/.gitignore index e6c5103c..713eacc3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -/target +target **/*.rs.bk Cargo.lock /.vscode diff --git a/raylib-test/Cargo.toml b/raylib-test/Cargo.toml index 5594848b..29b0e992 100644 --- a/raylib-test/Cargo.toml +++ b/raylib-test/Cargo.toml @@ -9,7 +9,7 @@ repository = "https://github.com/raylib-rs/raylib-rs" [dependencies] -raylib = { version = "5.5.0", path = "../raylib" } +raylib = { version = "5.5.0", path = "../raylib", features=["use_begin_functions"] } lazy_static = "1.2.0" colored = "2.1.0" diff --git a/raylib-test/src/callbacks.rs b/raylib-test/src/callbacks.rs index a2473423..3187f041 100644 --- a/raylib-test/src/callbacks.rs +++ b/raylib-test/src/callbacks.rs @@ -149,16 +149,5 @@ pub mod callback_tests { } } - pub fn set_file_text_loader(_: &RaylibThread) { - println!( - "\n{}\n", - "Setting file text loader callback".bold().underline(), - ); - let mut handle = TEST_HANDLE.write().unwrap(); - let rl = handle.as_mut().unwrap(); - { - rl.set_load_file_text_callback(custom_read_file_text_callback) - .unwrap(); - } - } + pub fn set_file_text_loader(_: &RaylibThread) {} } diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index cd43ee4e..e7ba0e1b 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -16,10 +16,14 @@ use crate::text::Codepoints; use std::convert::AsRef; use std::ffi::CString; +use super::camera::Camera2D; +use super::shaders::{Shader, ShaderV}; + /// Seems like all draw commands must be issued from the main thread impl RaylibHandle { - /// Setup canvas (framebuffer) to start drawing #[must_use] + /// Setup canvas (framebuffer) to start drawing. + /// Prefer using the closure version, [RaylibHandle::begin_drawing]. This version returns a handle that calls [raylib_sys::EndDrawing] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) pub fn begin_drawing(&mut self, _: &RaylibThread) -> RaylibDrawHandle { unsafe { ffi::BeginDrawing(); @@ -27,10 +31,30 @@ impl RaylibHandle { let d = RaylibDrawHandle(self); d } + pub fn start_drawing(&mut self, _: &RaylibThread, mut func: impl FnMut(RaylibDrawHandle)) { + unsafe { + ffi::BeginDrawing(); + }; + func(RaylibDrawHandle(self)); + unsafe { + ffi::EndDrawing(); + }; + } } pub struct RaylibDrawHandle<'a>(&'a mut RaylibHandle); +impl<'a> RaylibDrawHandle<'a> { + #[deprecated = "Calling begin_drawing within itself will result in a runtime error."] + pub fn begin_drawing(&mut self, _: &RaylibThread) -> RaylibDrawHandle { + panic!("Nested begin_drawing call") + } + #[deprecated = "Calling start_drawing within itself will result in a runtime error."] + pub fn start_drawing(&mut self, _: &RaylibThread, mut _func: impl FnMut(RaylibDrawHandle)) { + panic!("Nested start_drawing call") + } +} + impl<'a> Drop for RaylibDrawHandle<'a> { fn drop(&mut self) { unsafe { @@ -47,11 +71,17 @@ impl<'a> std::ops::Deref for RaylibDrawHandle<'a> { } } +impl<'a> std::ops::DerefMut for RaylibDrawHandle<'a> { + fn deref_mut(&mut self) -> &mut RaylibHandle { + self.0 + } +} impl<'a> RaylibDraw for RaylibDrawHandle<'a> {} // Texture2D Stuff -pub struct RaylibTextureMode<'a, T>(&'a T, &'a mut ffi::RenderTexture2D); +pub struct RaylibTextureMode<'a, T>(&'a mut T, Option<&'a mut ffi::RenderTexture2D>); + impl<'a, T> Drop for RaylibTextureMode<'a, T> { fn drop(&mut self) { unsafe { ffi::EndTextureMode() } @@ -64,11 +94,19 @@ impl<'a, T> std::ops::Deref for RaylibTextureMode<'a, T> { &self.0 } } +impl<'a, T> std::ops::DerefMut for RaylibTextureMode<'a, T> { + fn deref_mut(&mut self) -> &mut T { + self.0 + } +} +// framebuffer: &'a mut ffi::RenderTexture2D, pub trait RaylibTextureModeExt where Self: Sized, { + /// Begin drawing to render texture. + /// Prefer using the closure version, [RaylibTextureModeExt::start_texture_mode] . This version returns a handle that calls [raylib_sys::EndTextureMode] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) #[must_use] fn begin_texture_mode<'a>( &'a mut self, @@ -76,7 +114,17 @@ where framebuffer: &'a mut ffi::RenderTexture2D, ) -> RaylibTextureMode { unsafe { ffi::BeginTextureMode(*framebuffer) } - RaylibTextureMode(self, framebuffer) + RaylibTextureMode(self, Some(framebuffer)) + } + + fn start_texture_mode<'a>( + &'a mut self, + _: &RaylibThread, + framebuffer: &'a mut ffi::RenderTexture2D, + mut func: impl FnMut(RaylibTextureMode, &'a mut ffi::RenderTexture2D), + ) { + unsafe { ffi::BeginTextureMode(*framebuffer) } + func(RaylibTextureMode(self, None), framebuffer); } } @@ -87,7 +135,7 @@ impl<'a, T> RaylibDraw for RaylibTextureMode<'a, T> {} // VR Stuff -pub struct RaylibVRMode<'a, T>(&'a T, &'a mut VrStereoConfig); +pub struct RaylibVRMode<'a, T>(&'a T, Option<&'a mut VrStereoConfig>); impl<'a, T> Drop for RaylibVRMode<'a, T> { fn drop(&mut self) { unsafe { ffi::EndVrStereoMode() } @@ -105,13 +153,25 @@ pub trait RaylibVRModeExt where Self: Sized, { + /// Begin stereo rendering (requires VR simulator). + /// Prefer using the closure version, [RaylibVRModeExt::start_vr_stereo_mode] . This version returns a handle that calls [raylib_sys::EndVrStereoMode] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) #[must_use] fn begin_vr_stereo_mode<'a>( &'a mut self, + _: &RaylibThread, vr_config: &'a mut VrStereoConfig, ) -> RaylibVRMode { unsafe { ffi::BeginVrStereoMode(*vr_config.as_ref()) } - RaylibVRMode(self, vr_config) + RaylibVRMode(self, Some(vr_config)) + } + + fn start_vr_stereo_mode<'a>( + &'a mut self, + vr_config: &'a mut VrStereoConfig, + mut func: impl FnMut(RaylibVRMode, &'a mut VrStereoConfig), + ) { + unsafe { ffi::BeginVrStereoMode(*vr_config.as_ref()) } + func(RaylibVRMode(&self, None), vr_config); } } @@ -143,6 +203,8 @@ pub trait RaylibMode2DExt where Self: Sized, { + /// Begin 2D mode with custom camera (2D). + /// Prefer using the closure version, [RaylibMode2DExt::begin_mode2D]. This version returns a handle that calls [raylib_sys::EndMode2D] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) #[allow(non_snake_case)] #[must_use] fn begin_mode2D(&mut self, camera: impl Into) -> RaylibMode2D { @@ -151,6 +213,21 @@ where } RaylibMode2D(self) } + + #[allow(non_snake_case)] + fn start_mode2D( + &mut self, + camera: Camera2D, + mut func: impl FnMut(RaylibMode2D, Camera2D), + ) { + unsafe { + ffi::BeginMode2D(camera.into()); + } + func(RaylibMode2D(self), camera); + unsafe { + ffi::EndMode2D(); + } + } } impl RaylibMode2DExt for D {} @@ -181,6 +258,8 @@ pub trait RaylibMode3DExt where Self: Sized, { + /// Begin 3D mode with custom camera (3D). + /// Prefer using the closure version, [RaylibMode3DExt::begin_mode3D]. This version returns a handle that calls [raylib_sys::EndMode3D] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) #[allow(non_snake_case)] #[must_use] fn begin_mode3D(&mut self, camera: impl Into) -> RaylibMode3D { @@ -189,6 +268,21 @@ where } RaylibMode3D(self) } + + #[allow(non_snake_case)] + fn start_mode3D( + &mut self, + camera: Camera3D, + mut func: impl FnMut(RaylibMode3D, Camera3D), + ) { + unsafe { + ffi::BeginMode3D(camera.into()); + } + func(RaylibMode3D(self), camera); + unsafe { + ffi::EndMode3D(); + } + } } impl RaylibMode3DExt for D {} @@ -197,7 +291,8 @@ impl<'a, T> RaylibDraw3D for RaylibMode3D<'a, T> {} // shader Mode -pub struct RaylibShaderMode<'a, T>(&'a mut T, &'a ffi::Shader); +pub struct RaylibShaderMode<'a, T>(&'a mut T, Option<&'a mut Shader>); + impl<'a, T> Drop for RaylibShaderMode<'a, T> { fn drop(&mut self) { unsafe { ffi::EndShaderMode() } @@ -220,10 +315,21 @@ pub trait RaylibShaderModeExt where Self: Sized, { + /// Begin custom shader drawing. + /// Prefer using the closure version, [RaylibShaderModeExt::begin_shader_mode]. This version returns a handle that calls [raylib_sys::EndShaderMode] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) #[must_use] - fn begin_shader_mode<'a>(&'a mut self, shader: &'a ffi::Shader) -> RaylibShaderMode { - unsafe { ffi::BeginShaderMode(*shader) } - RaylibShaderMode(self, shader) + fn begin_shader_mode<'a>(&'a mut self, shader: &'a mut Shader) -> RaylibShaderMode { + unsafe { ffi::BeginShaderMode(*shader.as_ref()) } + RaylibShaderMode(self, Some(shader)) + } + + fn start_shader_mode<'a>( + &'a mut self, + shader: &'a mut Shader, + mut func: impl FnMut(RaylibShaderMode, &'a mut Shader), + ) { + unsafe { ffi::BeginShaderMode(*shader.as_ref()) } + func(RaylibShaderMode(self, None), shader); } } @@ -256,11 +362,22 @@ pub trait RaylibBlendModeExt where Self: Sized, { + /// Begin blending mode (alpha, additive, multiplied, subtract, custom). + /// Prefer using the closure version, [RaylibBlendModeExt::begin_blend_mode]. This version returns a handle that calls [raylib_sys::EndBlendMode] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) #[must_use] fn begin_blend_mode(&mut self, blend_mode: crate::consts::BlendMode) -> RaylibBlendMode { unsafe { ffi::BeginBlendMode((blend_mode as u32) as i32) } RaylibBlendMode(self) } + + fn start_blend_mode( + &mut self, + blend_mode: crate::consts::BlendMode, + mut func: impl FnMut(RaylibBlendMode), + ) { + unsafe { ffi::BeginBlendMode((blend_mode as u32) as i32) } + func(RaylibBlendMode(self)); + } } impl RaylibBlendModeExt for D {} @@ -292,6 +409,8 @@ pub trait RaylibScissorModeExt where Self: Sized, { + /// Begin scissor mode (define screen area for following drawing). + /// Prefer using the closure version, [RaylibScissorModeExt::begin_scissor_mode]. This version returns a handle that calls [raylib_sys::EndScissorMode] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) #[must_use] fn begin_scissor_mode( &mut self, @@ -303,6 +422,18 @@ where unsafe { ffi::BeginScissorMode(x, y, width, height) } RaylibScissorMode(self) } + + fn start_scissor_mode( + &mut self, + x: i32, + y: i32, + width: i32, + height: i32, + mut func: impl FnMut(RaylibScissorMode), + ) { + unsafe { ffi::BeginScissorMode(x, y, width, height) } + func(RaylibScissorMode(self)); + } } impl RaylibScissorModeExt for D {} diff --git a/raylib/src/core/shaders.rs b/raylib/src/core/shaders.rs index ec56f947..6584b2cd 100644 --- a/raylib/src/core/shaders.rs +++ b/raylib/src/core/shaders.rs @@ -31,6 +31,7 @@ impl RaylibHandle { // Trust me, I have tried ALL the RUST option ergonamics. This is the only way // to get this to work without raylib breaking for whatever reason + // UPDATE FOR 2024 FROM ANOTHER PERSON: Yes this is still true, doing although "for some reason" is likely due to the pointer getting freed too early if you don't do it this way. let shader = match (c_vs_filename, c_fs_filename) { (Some(vs), Some(fs)) => unsafe { Shader(ffi::LoadShader(vs.as_ptr(), fs.as_ptr())) }, (None, Some(fs)) => unsafe { Shader(ffi::LoadShader(std::ptr::null(), fs.as_ptr())) }, diff --git a/samples/3d_camera_first_person.rs b/samples/3d_camera_first_person.rs index bf603232..08b993cb 100644 --- a/samples/3d_camera_first_person.rs +++ b/samples/3d_camera_first_person.rs @@ -49,36 +49,34 @@ fn main() { while !rl.window_should_close() { rl.update_camera(&mut camera, CameraMode::CAMERA_FIRST_PERSON); - let mut d = rl.begin_drawing(&thread); + rl.start_drawing(&thread, |mut d| { + d.clear_background(Color::DARKGREEN); + d.start_mode3D(camera, |mut d2, _camera| { + d2.draw_plane( + Vector3::new(0.0, 0.0, 0.0), + Vector2::new(32.0, 32.0), + Color::LIGHTGRAY, + ); + d2.draw_cube(Vector3::new(-16.0, 2.5, 0.0), 1.0, 5.0, 32.0, Color::BLUE); + d2.draw_cube(Vector3::new(16.0, 2.5, 0.0), 1.0, 5.0, 32.0, Color::LIME); + d2.draw_cube(Vector3::new(0.0, 2.5, 16.0), 32.0, 5.0, 1.0, Color::GOLD); - d.clear_background(Color::DARKGREEN); - { - let mut d2 = d.begin_mode3D(camera); - - d2.draw_plane( - Vector3::new(0.0, 0.0, 0.0), - Vector2::new(32.0, 32.0), - Color::LIGHTGRAY, + for column in columns.iter() { + d2.draw_cube(column.position, 2.0, column.height, 2.0, column.color); + d2.draw_cube_wires(column.position, 2.0, column.height, 2.0, Color::MAROON); + } + }); + d.draw_rectangle(10, 10, 220, 70, Color::SKYBLUE); + d.draw_rectangle_lines(10, 10, 220, 70, Color::BLUE); + d.draw_text( + "First person camera default controls:", + 20, + 20, + 10, + Color::BLACK, ); - d2.draw_cube(Vector3::new(-16.0, 2.5, 0.0), 1.0, 5.0, 32.0, Color::BLUE); - d2.draw_cube(Vector3::new(16.0, 2.5, 0.0), 1.0, 5.0, 32.0, Color::LIME); - d2.draw_cube(Vector3::new(0.0, 2.5, 16.0), 32.0, 5.0, 1.0, Color::GOLD); - - for column in columns.iter() { - d2.draw_cube(column.position, 2.0, column.height, 2.0, column.color); - d2.draw_cube_wires(column.position, 2.0, column.height, 2.0, Color::MAROON); - } - } - d.draw_rectangle(10, 10, 220, 70, Color::SKYBLUE); - d.draw_rectangle_lines(10, 10, 220, 70, Color::BLUE); - d.draw_text( - "First person camera default controls:", - 20, - 20, - 10, - Color::BLACK, - ); - d.draw_text("- Move with keys: W, A, S, D", 40, 40, 10, Color::DARKGRAY); - d.draw_text("- Mouse move to look around", 40, 60, 10, Color::DARKGRAY); + d.draw_text("- Move with keys: W, A, S, D", 40, 40, 10, Color::DARKGRAY); + d.draw_text("- Mouse move to look around", 40, 60, 10, Color::DARKGRAY); + }); } } diff --git a/samples/Cargo.toml b/samples/Cargo.toml index 9c134d75..7030c2be 100644 --- a/samples/Cargo.toml +++ b/samples/Cargo.toml @@ -87,3 +87,7 @@ path = "./asteroids.rs" [[bin]] name = "floppy" path = "./floppy.rs" + +[[bin]] +name = "shader_multisample" +path = "./shader_multisample.rs" \ No newline at end of file diff --git a/samples/arkanoid.rs b/samples/arkanoid.rs index 78e5830c..00257d17 100644 --- a/samples/arkanoid.rs +++ b/samples/arkanoid.rs @@ -73,6 +73,8 @@ fn main() { let _game_over = false; let _pause = false; + rl.set_target_fps(60); + let mut game = Game::default(); init_game(&mut game, &rl); @@ -120,7 +122,7 @@ fn update_game(game: &mut Game, rl: &RaylibHandle) { let (w, h) = (rl.get_screen_width() as f32, rl.get_screen_height() as f32); if !game.game_over { - if rl.is_key_pressed(KEY_P) { + if rl.is_key_released(KEY_P) { game.pause = !game.pause; } @@ -140,7 +142,7 @@ fn update_game(game: &mut Game, rl: &RaylibHandle) { } // Ball launching logic - if !game.ball.active && rl.is_key_pressed(KEY_SPACE) { + if !game.ball.active && rl.is_key_released(KEY_SPACE) { game.ball.active = true; game.ball.speed = Vector2::new(0.0, -5.0); } @@ -174,7 +176,9 @@ fn update_game(game: &mut Game, rl: &RaylibHandle) { game.player.size.x, game.player.size.y, ); - if r.check_collision_circle_rec(game.ball.position, game.ball.radius as f32) && game.ball.speed.y > 0.0 { + if r.check_collision_circle_rec(game.ball.position, game.ball.radius as f32) + && game.ball.speed.y > 0.0 + { game.ball.speed.y *= -1.0; game.ball.speed.x = (game.ball.position.x - game.player.position.x) / (game.player.size.x / 2.0) @@ -261,7 +265,7 @@ fn update_game(game: &mut Game, rl: &RaylibHandle) { } } } - } else if rl.is_key_pressed(KEY_ENTER) { + } else if rl.is_key_released(KEY_ENTER) { init_game(game, rl); game.game_over = false; } @@ -269,67 +273,68 @@ fn update_game(game: &mut Game, rl: &RaylibHandle) { fn draw_game(game: &Game, rl: &mut RaylibHandle, thread: &RaylibThread) { let (w, h) = (rl.get_screen_width() as f32, rl.get_screen_height() as f32); - let mut d = rl.begin_drawing(thread); - d.clear_background(Color::RAYWHITE); - if !game.game_over { - // Draw player bar - d.draw_rectangle( - (game.player.position.x - game.player.size.x / 2.0) as i32, - (game.player.position.y - game.player.size.y / 2.0) as i32, - game.player.size.x as i32, - game.player.size.y as i32, - Color::BLACK, - ); - - // Draw player lives - for i in 0..game.player.life { - d.draw_rectangle(20 + 30 * i, h as i32 - 30, 35, 10, Color::LIGHTGRAY); - } + rl.start_drawing(thread, |mut d| { + d.clear_background(Color::RAYWHITE); + if !game.game_over { + // Draw player bar + d.draw_rectangle( + (game.player.position.x - game.player.size.x / 2.0) as i32, + (game.player.position.y - game.player.size.y / 2.0) as i32, + game.player.size.x as i32, + game.player.size.y as i32, + Color::BLACK, + ); + + // Draw player lives + for i in 0..game.player.life { + d.draw_rectangle(20 + 30 * i, h as i32 - 30, 35, 10, Color::LIGHTGRAY); + } + + // Draw ball + d.draw_circle_v(game.ball.position, game.ball.radius as f32, Color::MAROON); - // Draw ball - d.draw_circle_v(game.ball.position, game.ball.radius as f32, Color::MAROON); - - // Draw bricks - for i in 0..LINES_OF_BRICKS { - for j in 0..BRICKS_PER_LINE { - if game.bricks[i][j].active { - if (i + j) % 2 == 0 { - d.draw_rectangle( - (game.bricks[i][j].position.x - game.brick_size.x / 2.0) as i32, - (game.bricks[i][j].position.y - game.brick_size.y / 2.0) as i32, - game.brick_size.x as i32, - game.brick_size.y as i32, - Color::GRAY, - ); - } else { - d.draw_rectangle( - (game.bricks[i][j].position.x - game.brick_size.x / 2.0) as i32, - (game.bricks[i][j].position.y - game.brick_size.y / 2.0) as i32, - game.brick_size.x as i32, - game.brick_size.y as i32, - Color::DARKGRAY, - ); + // Draw bricks + for i in 0..LINES_OF_BRICKS { + for j in 0..BRICKS_PER_LINE { + if game.bricks[i][j].active { + if (i + j) % 2 == 0 { + d.draw_rectangle( + (game.bricks[i][j].position.x - game.brick_size.x / 2.0) as i32, + (game.bricks[i][j].position.y - game.brick_size.y / 2.0) as i32, + game.brick_size.x as i32, + game.brick_size.y as i32, + Color::GRAY, + ); + } else { + d.draw_rectangle( + (game.bricks[i][j].position.x - game.brick_size.x / 2.0) as i32, + (game.bricks[i][j].position.y - game.brick_size.y / 2.0) as i32, + game.brick_size.x as i32, + game.brick_size.y as i32, + Color::DARKGRAY, + ); + } } } } - } - if game.pause { + if game.pause { + d.draw_text( + "Game Pause", + (w / 2.0) as i32 - d.measure_text("Game Paused", 40) / 2, + (h / 2.0 - 40.0) as i32, + 40, + Color::GRAY, + ); + } + } else { d.draw_text( - "Game Pause", - (w / 2.0) as i32 - d.measure_text("Game Paused", 40) / 2, - (h / 2.0 - 40.0) as i32, - 40, + "PRESS [ENTER] TO PLAY AGAIN", + (w / 2.0) as i32 - d.measure_text("PRESS [ENTER] TO PLAY AGAIN", 20) / 2, + (h / 2.0) as i32 - 50, + 20, Color::GRAY, ); } - } else { - d.draw_text( - "PRESS [ENTER] TO PLAY AGAIN", - (w / 2.0) as i32 - d.measure_text("PRESS [ENTER] TO PLAY AGAIN", 20) / 2, - (h / 2.0) as i32 - 50, - 20, - Color::GRAY, - ); - } + }) } diff --git a/samples/asteroids.rs b/samples/asteroids.rs index f9ead277..3dad6c8d 100644 --- a/samples/asteroids.rs +++ b/samples/asteroids.rs @@ -536,98 +536,86 @@ fn update_game(game: &mut Game, rl: &RaylibHandle) { fn draw_game(game: &Game, rl: &mut RaylibHandle, thread: &RaylibThread) { let (width, height) = (rl.get_screen_width(), rl.get_screen_height()); - let mut d = rl.begin_drawing(thread); + rl.start_drawing(thread, |mut d| { + let half_width = width / 2; + let half_height = height / 2; + + d.clear_background(Color::RAYWHITE); + + if !game.game_over { + let cosf = f32::cos(game.player.rotation.to_radians()); + let sinf = f32::sin(game.player.rotation.to_radians()); + let v1 = Vector2::new( + game.player.position.x + sinf * SHIP_HEIGHT, + game.player.position.y - cosf * SHIP_HEIGHT, + ); + let v2 = Vector2::new( + game.player.position.x - cosf * 10f32, + game.player.position.y - sinf * 10f32, + ); + let v3 = Vector2::new( + game.player.position.x + cosf * 10f32, + game.player.position.y + sinf * 10f32, + ); + d.draw_triangle(v1, v2, v3, game.player.color); - let half_width = width / 2; - let half_height = height / 2; + for meteor in &game.big_meteors { + if meteor.active { + d.draw_circle_v(meteor.position, meteor.radius, meteor.color); + } else { + d.draw_circle_v(meteor.position, meteor.radius, Color::LIGHTGRAY.alpha(0.3)); + } + } - d.clear_background(Color::RAYWHITE); + for meteor in &game.medium_meteors { + if meteor.active { + d.draw_circle_v(meteor.position, meteor.radius, meteor.color); + } else { + d.draw_circle_v(meteor.position, meteor.radius, Color::LIGHTGRAY.alpha(0.3)); + } + } - if !game.game_over { - let cosf = f32::cos(game.player.rotation.to_radians()); - let sinf = f32::sin(game.player.rotation.to_radians()); - let v1 = Vector2::new( - game.player.position.x + sinf * SHIP_HEIGHT, - game.player.position.y - cosf * SHIP_HEIGHT, - ); - let v2 = Vector2::new( - game.player.position.x - cosf * 10f32, - game.player.position.y - sinf * 10f32, - ); - let v3 = Vector2::new( - game.player.position.x + cosf * 10f32, - game.player.position.y + sinf * 10f32, - ); - d.draw_triangle(v1, v2, v3, game.player.color); - - for meteor in &game.big_meteors { - if meteor.active { - d.draw_circle_v(meteor.position, meteor.radius, meteor.color); - } else { - d.draw_circle_v( - meteor.position, - meteor.radius, - Color::fade(&Color::LIGHTGRAY, 0.3), - ); + for meteor in &game.small_meteors { + if meteor.active { + d.draw_circle_v(meteor.position, meteor.radius, meteor.color); + } else { + d.draw_circle_v(meteor.position, meteor.radius, Color::LIGHTGRAY.alpha(0.3)); + } } - } - for meteor in &game.medium_meteors { - if meteor.active { - d.draw_circle_v(meteor.position, meteor.radius, meteor.color); - } else { - d.draw_circle_v( - meteor.position, - meteor.radius, - Color::fade(&Color::LIGHTGRAY, 0.3), - ); + for shot in &game.shots { + if shot.active { + d.draw_circle_v(shot.position, shot.radius, shot.color); + } } - } - for meteor in &game.small_meteors { - if meteor.active { - d.draw_circle_v(meteor.position, meteor.radius, meteor.color); - } else { - d.draw_circle_v( - meteor.position, - meteor.radius, - Color::fade(&Color::LIGHTGRAY, 0.3), + if game.victory { + d.draw_text( + "VICTORY", + half_width - d.measure_text("VICTORY", 20), + half_height, + 20, + Color::LIGHTGRAY, ); } - } - for shot in &game.shots { - if shot.active { - d.draw_circle_v(shot.position, shot.radius, shot.color); + if game.pause { + d.draw_text( + "GAME PAUSED", + half_width - d.measure_text("GAME PAUSED", 40), + half_height - 40, + 40, + Color::GRAY, + ); } - } - - if game.victory { + } else { d.draw_text( - "VICTORY", - half_width - d.measure_text("VICTORY", 20), - half_height, + "PRESS [ENTER] TO PLAY AGAIN", + half_width - d.measure_text("PRESS [ENTER] TO PLAY AGAIN", 20), + half_height - 50, 20, - Color::LIGHTGRAY, - ); - } - - if game.pause { - d.draw_text( - "GAME PAUSED", - half_width - d.measure_text("GAME PAUSED", 40), - half_height - 40, - 40, Color::GRAY, ); } - } else { - d.draw_text( - "PRESS [ENTER] TO PLAY AGAIN", - half_width - d.measure_text("PRESS [ENTER] TO PLAY AGAIN", 20), - half_height - 50, - 20, - Color::GRAY, - ); - } + }); } diff --git a/samples/camera2D.rs b/samples/camera2D.rs index 7c64acdb..0ad1da1e 100644 --- a/samples/camera2D.rs +++ b/samples/camera2D.rs @@ -44,7 +44,7 @@ fn main() { while !rl.window_should_close() { if rl.is_key_down(KEY_RIGHT) { - player.x += 2.0; + player.x += 2.0; } else if rl.is_key_down(KEY_LEFT) { player.x -= 2.0; } @@ -71,53 +71,53 @@ fn main() { camera.rotation = 0.0; } - let mut d = rl.begin_drawing(&thread); - d.clear_background(Color::RAYWHITE); - { - let mut d2 = d.begin_mode2D(camera); - d2.draw_rectangle(-6000, 320, 13000, 8000, Color::DARKGRAY); - - for i in 0..MAX_BUILDINGS { - d2.draw_rectangle_rec(buildings[i], build_colors[i]); - } - d2.draw_rectangle_rec(player, Color::RED); - - d2.draw_line( - camera.target.x as i32, - -h * 10, - camera.target.x as i32, - h * 10, - Color::GREEN, + rl.start_drawing(&thread, |mut d| { + d.clear_background(Color::RAYWHITE); + d.start_mode2D(camera, |mut d2, _camera| { + d2.draw_rectangle(-6000, 320, 13000, 8000, Color::DARKGRAY); + + for i in 0..MAX_BUILDINGS { + d2.draw_rectangle_rec(buildings[i], build_colors[i]); + } + d2.draw_rectangle_rec(player, Color::RED); + + d2.draw_line( + camera.target.x as i32, + -h * 10, + camera.target.x as i32, + h * 10, + Color::GREEN, + ); + d2.draw_line( + -w * 10, + camera.target.y as i32, + w * 10, + camera.target.y as i32, + Color::GREEN, + ); + }); + + d.draw_text("SCREEN AREA", 640, 10, 20, Color::RED); + + d.draw_rectangle(0, 0, w, 5, Color::RED); + d.draw_rectangle(0, 5, 5, h - 10, Color::RED); + d.draw_rectangle(w - 5, 5, 5, h - 10, Color::RED); + d.draw_rectangle(0, h - 5, w, 5, Color::RED); + + d.draw_rectangle(10, 10, 250, 113, Color::SKYBLUE.alpha(0.5)); + d.draw_rectangle_lines(10, 10, 250, 113, Color::BLUE); + + d.draw_text("Free 2d camera controls:", 20, 20, 10, Color::BLACK); + d.draw_text("- Right/Left to move Offset", 40, 40, 10, Color::DARKGRAY); + d.draw_text("- Mouse Wheel to Zoom in-out", 40, 60, 10, Color::DARKGRAY); + d.draw_text("- A / S to Rotate", 40, 80, 10, Color::DARKGRAY); + d.draw_text( + "- R to reset Zoom and Rotation", + 40, + 100, + 10, + Color::DARKGRAY, ); - d2.draw_line( - -w * 10, - camera.target.y as i32, - w * 10, - camera.target.y as i32, - Color::GREEN, - ); - } - - d.draw_text("SCREEN AREA", 640, 10, 20, Color::RED); - - d.draw_rectangle(0, 0, w, 5, Color::RED); - d.draw_rectangle(0, 5, 5, h - 10, Color::RED); - d.draw_rectangle(w - 5, 5, 5, h - 10, Color::RED); - d.draw_rectangle(0, h - 5, w, 5, Color::RED); - - d.draw_rectangle(10, 10, 250, 113, Color::SKYBLUE.fade(0.5)); - d.draw_rectangle_lines(10, 10, 250, 113, Color::BLUE); - - d.draw_text("Free 2d camera controls:", 20, 20, 10, Color::BLACK); - d.draw_text("- Right/Left to move Offset", 40, 40, 10, Color::DARKGRAY); - d.draw_text("- Mouse Wheel to Zoom in-out", 40, 60, 10, Color::DARKGRAY); - d.draw_text("- A / S to Rotate", 40, 80, 10, Color::DARKGRAY); - d.draw_text( - "- R to reset Zoom and Rotation", - 40, - 100, - 10, - Color::DARKGRAY, - ); + }); } } diff --git a/samples/extensions.rs b/samples/extensions.rs index 142a1ef5..33d0cb30 100644 --- a/samples/extensions.rs +++ b/samples/extensions.rs @@ -18,8 +18,9 @@ fn main() { let font = rl.get_font_default(); while !rl.window_should_close() { // Detect window close button or ESC key - let mut d = rl.begin_drawing(&thread); - d.clear_background(Color::WHITE); - d.custom_draw(&font); + rl.start_drawing(&thread, |mut d| { + d.clear_background(Color::WHITE); + d.custom_draw(&font); + }); } } diff --git a/samples/floppy.rs b/samples/floppy.rs index ca55266c..3e13ce55 100644 --- a/samples/floppy.rs +++ b/samples/floppy.rs @@ -175,73 +175,73 @@ fn update_game(game: &mut Game, rl: &RaylibHandle) { // // // Draw game (one frame) fn draw_game(game: &mut Game, rl: &mut RaylibHandle, thread: &RaylibThread) { - let mut d = rl.begin_drawing(thread); - - d.clear_background(Color::RAYWHITE); - - if !game.game_over { - d.draw_circle( - game.floppy.position.x as i32, - game.floppy.position.y as i32, - game.floppy.radius, - game.floppy.color, - ); - - // Draw tubes - for i in 0..MAX_TUBES { - d.draw_rectangle( - game.tubes[i * 2].rec.x as i32, - game.tubes[i * 2].rec.y as i32, - game.tubes[i * 2].rec.width as i32, - game.tubes[i * 2].rec.height as i32, - game.tubes[i * 2].color, - ); - d.draw_rectangle( - game.tubes[i * 2 + 1].rec.x as i32, - game.tubes[i * 2 + 1].rec.y as i32, - game.tubes[i * 2 + 1].rec.width as i32, - game.tubes[i * 2 + 1].rec.height as i32, - game.tubes[i * 2 + 1].color, + rl.start_drawing(thread, |mut d| { + d.clear_background(Color::RAYWHITE); + + if !game.game_over { + d.draw_circle( + game.floppy.position.x as i32, + game.floppy.position.y as i32, + game.floppy.radius, + game.floppy.color, ); - } - // Draw flashing fx (one frame only) - if game.superfx { - d.draw_rectangle(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, Color::WHITE); - game.superfx = false; - } + // Draw tubes + for i in 0..MAX_TUBES { + d.draw_rectangle( + game.tubes[i * 2].rec.x as i32, + game.tubes[i * 2].rec.y as i32, + game.tubes[i * 2].rec.width as i32, + game.tubes[i * 2].rec.height as i32, + game.tubes[i * 2].color, + ); + d.draw_rectangle( + game.tubes[i * 2 + 1].rec.x as i32, + game.tubes[i * 2 + 1].rec.y as i32, + game.tubes[i * 2 + 1].rec.width as i32, + game.tubes[i * 2 + 1].rec.height as i32, + game.tubes[i * 2 + 1].color, + ); + } - d.draw_text(&format!("{:04}", game.score), 20, 20, 40, Color::GRAY); - d.draw_text( - &format!("HI-SCORE: {:04}", game.hi_score), - 20, - 70, - 20, - Color::LIGHTGRAY, - ); + // Draw flashing fx (one frame only) + if game.superfx { + d.draw_rectangle(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, Color::WHITE); + game.superfx = false; + } - if game.pause { + d.draw_text(&format!("{:04}", game.score), 20, 20, 40, Color::GRAY); d.draw_text( - "GAME PAUSED", - SCREEN_WIDTH / 2 - d.measure_text("GAME PAUSED", 40) / 2, - SCREEN_HEIGHT / 2 - 40, - 40, + &format!("HI-SCORE: {:04}", game.hi_score), + 20, + 70, + 20, + Color::LIGHTGRAY, + ); + + if game.pause { + d.draw_text( + "GAME PAUSED", + SCREEN_WIDTH / 2 - d.measure_text("GAME PAUSED", 40) / 2, + SCREEN_HEIGHT / 2 - 40, + 40, + Color::GRAY, + ); + } + } else { + d.draw_text( + "PRESS [ENTER] TO PLAY AGAIN", + d.get_screen_width() / 2 - d.measure_text("PRESS [ENTER] TO PLAY AGAIN", 20) / 2, + d.get_screen_height() / 2 - 50, + 20, Color::GRAY, ); } - } else { - d.draw_text( - "PRESS [ENTER] TO PLAY AGAIN", - d.get_screen_width() / 2 - d.measure_text("PRESS [ENTER] TO PLAY AGAIN", 20) / 2, - d.get_screen_height() / 2 - 50, - 20, - Color::GRAY, - ); - } + }); } // Update and Draw (one frame) fn update_draw_frame(game: &mut Game, rl: &mut RaylibHandle, thread: &RaylibThread) { update_game(game, rl); draw_game(game, rl, thread); -} \ No newline at end of file +} diff --git a/samples/font.rs b/samples/font.rs index 2b093f33..130b31f3 100644 --- a/samples/font.rs +++ b/samples/font.rs @@ -12,27 +12,27 @@ fn main() { .load_font(&thread, "static/alagard.png") .expect("couldn't load font"); while !rl.window_should_close() { - // Detect window close button or ESC key - let mut d = rl.begin_drawing(&thread); - d.clear_background(ray_white); - d.draw_rectangle(w / 2 - 128, h / 2 - 128, 256, 256, rust_orange); - d.draw_rectangle(w / 2 - 112, h / 2 - 112, 224, 224, ray_white); - d.draw_text_ex( - &font, - "rust", - Vector2::new((w / 2 - 69) as f32, (h / 2 + 18) as f32), - 50.0, - 1.0, - rust_orange, - ); - d.draw_text_ex( - &font, - "raylib", - Vector2::new((w / 2 - 44) as f32, (h / 2 + 48) as f32), - 50.0, - 1.0, - rust_orange, - ); - // rl.take_screenshot(&thread, "logo.png"); + rl.start_drawing(&thread, |mut d| { + d.clear_background(ray_white); + d.draw_rectangle(w / 2 - 128, h / 2 - 128, 256, 256, rust_orange); + d.draw_rectangle(w / 2 - 112, h / 2 - 112, 224, 224, ray_white); + d.draw_text_ex( + &font, + "rust", + Vector2::new((w / 2 - 69) as f32, (h / 2 + 18) as f32), + 50.0, + 1.0, + rust_orange, + ); + d.draw_text_ex( + &font, + "raylib", + Vector2::new((w / 2 - 44) as f32, (h / 2 + 48) as f32), + 50.0, + 1.0, + rust_orange, + ); + // rl.take_screenshot(&thread, "logo.png"); + }); } } diff --git a/samples/input.rs b/samples/input.rs index c2e58150..7ea634ad 100644 --- a/samples/input.rs +++ b/samples/input.rs @@ -14,12 +14,13 @@ fn main() { rl.set_target_fps(60); while !rl.window_should_close() { let pressed_key = rl.get_key_pressed(); - let mut d = rl.begin_drawing(&thread); - d.clear_background(Color::WHITE); - if let Some(pressed_key) = pressed_key { - // Certain keyboards may have keys raylib does not expect. Uncomment this line if so. - // let pressed_key: u32 = unsafe { std::mem::transmute(pressed_key) }; - d.draw_text(&format!("{:?}", pressed_key), 100, 12, 10, Color::BLACK); - } + rl.start_drawing(&thread, |mut d| { + d.clear_background(Color::WHITE); + if let Some(pressed_key) = pressed_key { + // Certain keyboards may have keys raylib does not expect. Uncomment this line if so. + // let pressed_key: u32 = unsafe { std::mem::transmute(pressed_key) }; + d.draw_text(&format!("{:?}", pressed_key), 100, 12, 10, Color::BLACK); + } + }); } } diff --git a/samples/logo.rs b/samples/logo.rs index 6f21798e..fc927325 100644 --- a/samples/logo.rs +++ b/samples/logo.rs @@ -14,11 +14,13 @@ fn main() { rl.set_target_fps(60); while !rl.window_should_close() { // Detect window close button or ESC key - let mut d = rl.begin_drawing(&thread); - d.clear_background(ray_white); - d.draw_rectangle(w / 2 - 128, h / 2 - 128, 256, 256, rust_orange); - d.draw_rectangle(w / 2 - 112, h / 2 - 112, 224, 224, ray_white); - d.draw_text("rust", w / 2 - 69, h / 2 + 18, 50, rust_orange); - d.draw_text("raylib", w / 2 - 44, h / 2 + 48, 50, rust_orange); + + rl.start_drawing(&thread, |mut d| { + d.clear_background(ray_white); + d.draw_rectangle(w / 2 - 128, h / 2 - 128, 256, 256, rust_orange); + d.draw_rectangle(w / 2 - 112, h / 2 - 112, 224, 224, ray_white); + d.draw_text("rust", w / 2 - 69, h / 2 + 18, 50, rust_orange); + d.draw_text("raylib", w / 2 - 44, h / 2 + 48, 50, rust_orange); + }); } } diff --git a/samples/model_shader.rs b/samples/model_shader.rs index e3c5f405..efc07911 100644 --- a/samples/model_shader.rs +++ b/samples/model_shader.rs @@ -18,9 +18,7 @@ fn main() { rl.set_target_fps(60); // Load shader - let shader = rl - .load_shader(&thread, None, Some("static/model_shader/grayscale.fs")) - .unwrap(); + let shader = rl.load_shader(&thread, None, Some("static/model_shader/grayscale.fs")); // Load model let mut model = rl @@ -51,22 +49,21 @@ fn main() { while !rl.window_should_close() { rl.update_camera(&mut camera, CameraMode::CAMERA_FREE); - let mut drawing = rl.begin_drawing(&thread); - drawing.clear_background(Color::WHITE); - { - let mut mode_3d = drawing.begin_mode3D(camera); - - mode_3d.draw_model(&model, model_position, 0.2, Color::WHITE); - mode_3d.draw_grid(10, 1.0); - } + rl.start_drawing(&thread, |mut drawing| { + drawing.clear_background(Color::WHITE); + drawing.start_mode3D(camera, |mut mode_3d, _camera| { + mode_3d.draw_model(&model, model_position, 0.2, Color::WHITE); + mode_3d.draw_grid(10, 1.0); + }); - drawing.draw_text( - "(c) Watermill 3D model by Alberto Cano", - w - 210, - h - 20, - 10, - Color::GRAY, - ); - drawing.draw_fps(10, 10) + drawing.draw_text( + "(c) Watermill 3D model by Alberto Cano", + w - 210, + h - 20, + 10, + Color::GRAY, + ); + drawing.draw_fps(10, 10) + }); } } diff --git a/samples/raymarch.rs b/samples/raymarch.rs index c2a272a9..e8e82d48 100644 --- a/samples/raymarch.rs +++ b/samples/raymarch.rs @@ -56,24 +56,25 @@ pub fn main() { // Draw //---------------------------------------------------------------------------------- - let mut d = rl.begin_drawing(&thread); - - d.clear_background(Color::RAYWHITE); - - // We only draw a white full-screen rectangle, - // frame is generated in shader using raymarching - { - let mut d = d.begin_shader_mode(&shader); - d.draw_rectangle(0, 0, w, h, Color::WHITE); - } - - d.draw_text( - "(c) Raymarching shader by Iñigo Quilez. MIT License.", - w - 280, - h - 20, - 10, - Color::GRAY, - ); + rl.start_drawing(&thread, |mut d| { + d.clear_background(Color::RAYWHITE); + + // We only draw a white full-screen rectangle, + // frame is generated in shader using raymarching + { + d.start_shader_mode(&mut shader, |mut d, _shader| { + d.draw_rectangle(0, 0, w, h, Color::WHITE); + }); + } + + d.draw_text( + "(c) Raymarching shader by Iñigo Quilez. MIT License.", + w - 280, + h - 20, + 10, + Color::GRAY, + ); + }); //---------------------------------------------------------------------------------- } diff --git a/samples/shader_multisample.rs b/samples/shader_multisample.rs new file mode 100644 index 00000000..5f658310 --- /dev/null +++ b/samples/shader_multisample.rs @@ -0,0 +1,52 @@ +use raylib::prelude::*; +pub fn main() { + let (mut rl, thread) = raylib::init().width(800).height(450).build(); + let im_red = Image::gen_image_color(800, 450, Color::new(255, 0, 0, 255)); + let tex_red = rl.load_texture_from_image(&thread, &im_red).unwrap(); + + let im_blue = Image::gen_image_color(800, 450, Color::new(0, 0, 255, 255)); + let tex_blue = rl.load_texture_from_image(&thread, &im_blue).unwrap(); + + let mut shader = rl.load_shader(&thread, None, Some("static/shader/color_mix.fs")); + + // Get an additional sampler2D location to be enabled on drawing + let tex_blue_loc = shader.get_shader_location("texture1"); + + // Get shader uniform for divider + let divider_loc = shader.get_shader_location("divider"); + let mut divider_value = 0.5; + + rl.set_target_fps(60); + + while !rl.window_should_close() { + if rl.is_key_down(KeyboardKey::KEY_RIGHT) { + divider_value += 0.01; + } + if rl.is_key_down(KeyboardKey::KEY_LEFT) { + divider_value -= 0.01; + } + + if (divider_value < 0.0) { + divider_value = 0.0; + } else if (divider_value > 1.0) { + divider_value = 1.0; + }; + rl.start_drawing(&thread, |mut d| { + d.start_shader_mode(&mut shader, |mut d, shader| { + shader.set_shader_value(divider_loc, divider_value); + shader.set_shader_value_texture(tex_blue_loc, &tex_blue); + + d.clear_background(Color::WHITE); + d.draw_texture(&tex_red, 0, 0, Color::WHITE); + }); + + d.draw_text( + "Use KEY_LEFT/KEY_RIGHT to move texture mixing in shader!", + 80, + d.get_screen_height() - 40, + 20, + Color::RAYWHITE, + ); + }) + } +} diff --git a/samples/specs.rs b/samples/specs.rs index db807058..67ccc1af 100644 --- a/samples/specs.rs +++ b/samples/specs.rs @@ -125,23 +125,24 @@ impl<'a> System<'a> for DrawSys { let size = Vector2::new(tw as f32, tw as f32) + margin; let tile_size = Vector2::new(tw as f32, tw as f32); - let mut d = rl.begin_drawing(&self.thread); - d.clear_background(Color::BLACK); - // draw the tiles - for (pos, _) in (&pos, &tiles).join() { - let p: Vector2 = pos.into(); - d.draw_rectangle_v(p * size + margin, tile_size, Color::RAYWHITE); - } - // draw the fire tiles - for (pos, _, _) in (&pos, &tiles, &fire).join() { - let p: Vector2 = pos.into(); - d.draw_rectangle_v(p * size + margin, tile_size, Color::RED); - } - // draw the player tiles - for (pos, _, _) in (&pos, &tiles, &player).join() { - let p: Vector2 = pos.into(); - d.draw_rectangle_v(p * size + margin, tile_size, Color::GREEN); - } + rl.start_drawing(&mut self.thread, |mut d| { + d.clear_background(Color::BLACK); + // draw the tiles + for (pos, _) in (&pos, &tiles).join() { + let p: Vector2 = pos.into(); + d.draw_rectangle_v(p * size + margin, tile_size, Color::RAYWHITE); + } + // draw the fire tiles + for (pos, _, _) in (&pos, &tiles, &fire).join() { + let p: Vector2 = pos.into(); + d.draw_rectangle_v(p * size + margin, tile_size, Color::RED); + } + // draw the player tiles + for (pos, _, _) in (&pos, &tiles, &player).join() { + let p: Vector2 = pos.into(); + d.draw_rectangle_v(p * size + margin, tile_size, Color::GREEN); + } + }); } } diff --git a/samples/static/shader/color_mix.fs b/samples/static/shader/color_mix.fs new file mode 100644 index 00000000..e794d32f --- /dev/null +++ b/samples/static/shader/color_mix.fs @@ -0,0 +1,27 @@ +#version 330 + +// Input vertex attributes (from vertex shader) +in vec3 vertexPos; +in vec2 fragTexCoord; +in vec4 fragColor; + +// Input uniform values +uniform sampler2D texture0; +uniform sampler2D texture1; +uniform vec4 colDiffuse; + +uniform float divider = 0.5; + +out vec4 finalColor; + +void main() +{ + // Texel color fetching from texture sampler + vec4 texelColor0 = texture(texture0, fragTexCoord); + vec4 texelColor1 = texture(texture1, fragTexCoord); + + float x = fract(fragTexCoord.s); + float final = smoothstep(divider - 0.1, divider + 0.1, x); + + finalColor = mix(texelColor0, texelColor1, final); +} \ No newline at end of file diff --git a/samples/texture.rs b/samples/texture.rs index c95f89de..f1b50958 100644 --- a/samples/texture.rs +++ b/samples/texture.rs @@ -19,8 +19,9 @@ fn main() { rl.set_target_fps(60); while !rl.window_should_close() { // Detect window close button or ESC key - let mut d = rl.begin_drawing(&thread); - d.clear_background(Color::BLACK); - d.draw_texture(&t, 0, 0, Color::WHITE); + rl.start_drawing(&thread, |mut d| { + d.clear_background(Color::BLACK); + d.draw_texture(&t, 0, 0, Color::WHITE); + }); } } diff --git a/samples/yaw_pitch_roll.rs b/samples/yaw_pitch_roll.rs index eed91b0d..e8a700af 100644 --- a/samples/yaw_pitch_roll.rs +++ b/samples/yaw_pitch_roll.rs @@ -95,162 +95,161 @@ fn main() { pitch_offset *= 10.0; // Detect window close button or ESC key - let mut d = rl.begin_drawing(&thread); - d.clear_background(ray_white); + rl.start_drawing(&thread, |mut d| { + d.clear_background(ray_white); - let mat = Matrix::rotate_xyz(Vector3::new( - pitch.to_radians(), - yaw.to_radians(), - roll.to_radians(), - )); + let mat = Matrix::rotate_xyz(Vector3::new( + pitch.to_radians(), + yaw.to_radians(), + roll.to_radians(), + )); - model.set_transform(&mat); + model.set_transform(&mat); - // Draw framebuffer texture (Ahrs Display) - let center_x = (framebuffer.texture().width() / 2) as f32; - let center_y = (framebuffer.texture().height() / 2) as f32; - let scale_factor = 0.5; - { - let mut d = d.begin_texture_mode(&thread, &mut framebuffer); + // Draw framebuffer texture (Ahrs Display) + let center_x = (framebuffer.texture().width() / 2) as f32; + let center_y = (framebuffer.texture().height() / 2) as f32; + let scale_factor = 0.5; { - let mut d = d.begin_blend_mode(raylib::consts::BlendMode::BLEND_ALPHA); - d.draw_texture_pro( - &tex_background, - Rectangle::new( - 0.0, - 0.0, - tex_background.width() as f32, - tex_background.height() as f32, - ), - Rectangle::new( - center_x, - center_y, - tex_background.width() as f32 * scale_factor, - tex_background.height() as f32 * scale_factor, - ), - Vector2::new( - tex_background.width() as f32 / 2.0 * scale_factor, - tex_background.height() as f32 / 2.0 * scale_factor - + pitch_offset * scale_factor, - ), - roll, - Color::WHITE, - ); + d.start_texture_mode(&thread, &mut framebuffer, |mut d, _framebuffer| { + d.start_blend_mode(BlendMode::BLEND_ALPHA, |mut d| { + d.draw_texture_pro( + &tex_background, + Rectangle::new( + 0.0, + 0.0, + tex_background.width() as f32, + tex_background.height() as f32, + ), + Rectangle::new( + center_x, + center_y, + tex_background.width() as f32 * scale_factor, + tex_background.height() as f32 * scale_factor, + ), + Vector2::new( + tex_background.width() as f32 / 2.0 * scale_factor, + tex_background.height() as f32 / 2.0 * scale_factor + + pitch_offset * scale_factor, + ), + roll, + Color::WHITE, + ); - d.draw_texture_pro( - &tex_pitch, - Rectangle::new( - 0.0, - 0.0, - tex_pitch.width() as f32, - tex_pitch.height() as f32, - ), - Rectangle::new( - center_x, - center_y, - tex_pitch.width() as f32 * scale_factor, - tex_pitch.height() as f32 * scale_factor, - ), - Vector2::new( - tex_pitch.width() as f32 / 2.0 * scale_factor, - tex_pitch.height() as f32 / 2.0 * scale_factor - + pitch_offset * scale_factor, - ), - roll, - Color::WHITE, - ); + d.draw_texture_pro( + &tex_pitch, + Rectangle::new( + 0.0, + 0.0, + tex_pitch.width() as f32, + tex_pitch.height() as f32, + ), + Rectangle::new( + center_x, + center_y, + tex_pitch.width() as f32 * scale_factor, + tex_pitch.height() as f32 * scale_factor, + ), + Vector2::new( + tex_pitch.width() as f32 / 2.0 * scale_factor, + tex_pitch.height() as f32 / 2.0 * scale_factor + + pitch_offset * scale_factor, + ), + roll, + Color::WHITE, + ); - d.draw_texture_pro( - &tex_plane, - Rectangle::new( - 0.0, - 0.0, - tex_plane.width() as f32, - tex_plane.height() as f32, - ), - Rectangle::new( - center_x, - center_y, - tex_plane.width() as f32 * scale_factor, - tex_plane.height() as f32 * scale_factor, - ), - Vector2::new( - tex_plane.width() as f32 / 2.0 * scale_factor, - tex_plane.height() as f32 / 2.0 * scale_factor, - ), - 0.0, - Color::WHITE, - ); + d.draw_texture_pro( + &tex_plane, + Rectangle::new( + 0.0, + 0.0, + tex_plane.width() as f32, + tex_plane.height() as f32, + ), + Rectangle::new( + center_x, + center_y, + tex_plane.width() as f32 * scale_factor, + tex_plane.height() as f32 * scale_factor, + ), + Vector2::new( + tex_plane.width() as f32 / 2.0 * scale_factor, + tex_plane.height() as f32 / 2.0 * scale_factor, + ), + 0.0, + Color::WHITE, + ); + }) + }); } - } - // Draw 3D model (recomended to draw 3D always before 2D) - { - let mut d = d.begin_mode3D(camera); - - d.draw_model(&model, Vector3::new(0.0, 6.0, 0.0), 1.0, Color::WHITE); // Draw 3d model with texture - d.draw_grid(10, 10.0); - } + // Draw 3D model (recomended to draw 3D always before 2D) + d.start_mode3D(camera, |mut d, _camera| { + d.draw_model(&model, Vector3::new(0.0, 6.0, 0.0), 1.0, Color::WHITE); // Draw 3d model with texture + d.draw_grid(10, 10.0); + }); - // Draw 2D GUI stuff - draw_angle_gauge(&mut d, &tex_angle_gauge, 80, 70, roll, "roll", Color::RED); - draw_angle_gauge( - &mut d, - &tex_angle_gauge, - 190, - 70, - pitch, - "pitch", - Color::GREEN, - ); - draw_angle_gauge( - &mut d, - &tex_angle_gauge, - 300, - 70, - yaw, - "yaw", - Color::SKYBLUE, - ); + // Draw 2D GUI stuff + draw_angle_gauge(&mut d, &tex_angle_gauge, 80, 70, roll, "roll", Color::RED); + draw_angle_gauge( + &mut d, + &tex_angle_gauge, + 190, + 70, + pitch, + "pitch", + Color::GREEN, + ); + draw_angle_gauge( + &mut d, + &tex_angle_gauge, + 300, + 70, + yaw, + "yaw", + Color::SKYBLUE, + ); - d.draw_rectangle(30, 360, 260, 70, Color::SKYBLUE.fade(0.5)); - d.draw_rectangle_lines(30, 360, 260, 70, Color::DARKBLUE.fade(0.5)); - d.draw_text( - "Pitch controlled with: KEY_UP / KEY_DOWN", - 40, - 370, - 10, - Color::DARKGRAY, - ); - d.draw_text( - "Roll controlled with: KEY_LEFT / KEY_RIGHT", - 40, - 390, - 10, - Color::DARKGRAY, - ); - d.draw_text( - "Yaw controlled with: KEY_A / KEY_S", - 40, - 410, - 10, - Color::DARKGRAY, - ); + d.draw_rectangle(30, 360, 260, 70, Color::SKYBLUE.alpha(0.5)); + d.draw_rectangle_lines(30, 360, 260, 70, Color::DARKBLUE.alpha(0.5)); + d.draw_text( + "Pitch controlled with: KEY_UP / KEY_DOWN", + 40, + 370, + 10, + Color::DARKGRAY, + ); + d.draw_text( + "Roll controlled with: KEY_LEFT / KEY_RIGHT", + 40, + 390, + 10, + Color::DARKGRAY, + ); + d.draw_text( + "Yaw controlled with: KEY_A / KEY_S", + 40, + 410, + 10, + Color::DARKGRAY, + ); - // Draw framebuffer texture - d.draw_texture_rec( - framebuffer.texture(), - Rectangle::new( - 0.0, - 0.0, - framebuffer.texture.width as f32, - -framebuffer.texture.height as f32, - ), - Vector2::new( - screen_width as f32 - framebuffer.texture.width as f32 - 20.0, - 20.0, - ), - Color::WHITE.fade(0.8), - ); + // Draw framebuffer texture + d.draw_texture_rec( + framebuffer.texture(), + Rectangle::new( + 0.0, + 0.0, + framebuffer.texture.width as f32, + -framebuffer.texture.height as f32, + ), + Vector2::new( + screen_width as f32 - framebuffer.texture.width as f32 - 20.0, + 20.0, + ), + Color::WHITE.alpha(0.8), + ); + }); } } From f9f435d8f9e9cbc9d55ec05228a4ede00fe42dc0 Mon Sep 17 00:00:00 2001 From: Theo Paris Date: Thu, 24 Oct 2024 10:33:48 -0700 Subject: [PATCH 38/93] fix: fix build on arm (#88) --- raylib/src/core/callbacks.rs | 6 +++--- raylib/src/core/data.rs | 9 ++++++--- raylib/src/core/input.rs | 3 ++- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/raylib/src/core/callbacks.rs b/raylib/src/core/callbacks.rs index 6d3161d3..62c1a6b4 100644 --- a/raylib/src/core/callbacks.rs +++ b/raylib/src/core/callbacks.rs @@ -108,18 +108,18 @@ extern "C" fn custom_load_file_data_callback(path: *const c_char, size: *mut c_i } } -extern "C" fn custom_save_file_text_callback(a: *const i8, b: *mut i8) -> bool { +extern "C" fn custom_save_file_text_callback(a: *const c_char, b: *mut c_char) -> bool { let save_file_text = save_file_text_callback().unwrap(); let a = unsafe { CStr::from_ptr(a) }; let b = unsafe { CStr::from_ptr(b) }; return save_file_text(a.to_str().unwrap(), b.to_str().unwrap()); } -extern "C" fn custom_load_file_text_callback(a: *const i8) -> *mut i8 { +extern "C" fn custom_load_file_text_callback(a: *const c_char) -> *mut c_char { let load_file_text = load_file_text_callback().unwrap(); let a = unsafe { CStr::from_ptr(a) }; let st = load_file_text(a.to_str().unwrap()); let oh = Box::leak(Box::new(CString::new(st).unwrap())); - oh.as_ptr() as *mut i8 + oh.as_ptr() as *mut c_char } extern "C" fn custom_audio_stream_callback(a: *mut c_void, b: u32) { diff --git a/raylib/src/core/data.rs b/raylib/src/core/data.rs index d6386464..edc96535 100644 --- a/raylib/src/core/data.rs +++ b/raylib/src/core/data.rs @@ -1,5 +1,8 @@ //! Data manipulation functions. Compress and Decompress with DEFLATE -use std::{ffi::CString, path::Path}; +use std::{ + ffi::{c_char, CString}, + path::Path, +}; use crate::{ error::{error, Error}, @@ -68,7 +71,7 @@ pub fn export_data_as_code(data: &[u8], file_name: impl AsRef) -> bool { } /// Encode data to Base64 string -pub fn encode_data_base64(data: &[u8]) -> Vec { +pub fn encode_data_base64(data: &[u8]) -> Vec { let mut output_size = 0; let bytes = unsafe { ffi::EncodeDataBase64(data.as_ptr(), data.len() as i32, &mut output_size) }; @@ -77,7 +80,7 @@ pub fn encode_data_base64(data: &[u8]) -> Vec { if s.contains(&0) { // Work around a bug in Rust's from_raw_parts function let mut keep = true; - let b: Vec = s + let b: Vec = s .iter() .filter(|f| { if **f == 0 { diff --git a/raylib/src/core/input.rs b/raylib/src/core/input.rs index c7c10052..7d4bb568 100644 --- a/raylib/src/core/input.rs +++ b/raylib/src/core/input.rs @@ -6,6 +6,7 @@ use crate::core::math::Vector2; use crate::core::RaylibHandle; use crate::ffi; +use std::ffi::c_char; use std::ffi::CStr; impl RaylibHandle { @@ -278,7 +279,7 @@ impl RaylibHandle { } /// Set internal gamepad mappings (SDL_GameControllerDB) - pub fn set_gamepad_mappings(&self, bind: &[i8]) -> i32 { + pub fn set_gamepad_mappings(&self, bind: &[c_char]) -> i32 { unsafe { ffi::SetGamepadMappings(bind.as_ptr()) } } From 0f239c90380319f8e3ec06a9499cd00caefcdaed Mon Sep 17 00:00:00 2001 From: IoIxD <30945097+IoIxD@users.noreply.github.com> Date: Thu, 24 Oct 2024 12:56:36 -0700 Subject: [PATCH 39/93] Routine 5.5 update (#91) * [general] update to 5.5, add rotation to set_gamepad_vibration, rename appropriate is_..._ready functions to is_valid, as Raylib did * [general] remove the deprecations, both from the last commit and 5.5 --- raylib-sys/raylib | 2 +- raylib/src/core/audio.rs | 21 ++++++------ raylib/src/core/color.rs | 7 ---- raylib/src/core/input.rs | 10 ++++-- raylib/src/core/models.rs | 35 ++++++-------------- raylib/src/core/shaders.rs | 8 ++--- raylib/src/core/text.rs | 9 +++--- raylib/src/core/texture.rs | 65 +++++++++++--------------------------- raylib/src/core/window.rs | 10 ------ 9 files changed, 56 insertions(+), 111 deletions(-) diff --git a/raylib-sys/raylib b/raylib-sys/raylib index 039df36f..15f6c47f 160000 --- a/raylib-sys/raylib +++ b/raylib-sys/raylib @@ -1 +1 @@ -Subproject commit 039df36f4b73cfd685c143f47e71abf93270e709 +Subproject commit 15f6c47f0715afd1fce52d760053026c2b92214c diff --git a/raylib/src/core/audio.rs b/raylib/src/core/audio.rs index 8d3f3586..e801fb07 100644 --- a/raylib/src/core/audio.rs +++ b/raylib/src/core/audio.rs @@ -200,8 +200,8 @@ impl<'aud> Wave<'aud> { inner } - pub fn is_wave_ready(&self) -> bool { - unsafe { ffi::IsWaveReady(self.0) } + pub fn is_wave_valid(&self) -> bool { + unsafe { ffi::IsWaveValid(self.0) } } /// Export wave file. Extension must be .wav or .raw @@ -269,8 +269,8 @@ impl<'aud> AsMut for Sound<'aud> { } impl<'aud> Sound<'aud> { - pub fn is_sound_ready(&self) -> bool { - unsafe { ffi::IsSoundReady(self.0) } + pub fn is_sound_valid(&self) -> bool { + unsafe { ffi::IsSoundValid(self.0) } } pub fn frame_count(&self) -> u32 { @@ -356,8 +356,8 @@ impl<'aud> Sound<'aud> { } impl<'aud, 'bind> SoundAlias<'aud, 'bind> { - pub fn is_sound_ready(&self) -> bool { - unsafe { ffi::IsSoundReady(self.0) } + pub fn is_sound_valid(&self) -> bool { + unsafe { ffi::IsSoundValid(self.0) } } pub fn frame_count(&self) -> u32 { @@ -522,15 +522,14 @@ impl<'aud> Music<'aud> { } } - /// Checks if a music stream is ready - pub fn is_ready(&self) -> bool { - unsafe { ffi::IsMusicReady(self.0) } + pub fn is_music_valid(&self) -> bool { + unsafe { ffi::IsMusicValid(self.0) } } } impl<'aud> AudioStream<'aud> { - pub fn is_audio_stream_ready(&self) -> bool { - unsafe { ffi::IsAudioStreamReady(self.0) } + pub fn is_audio_stream_valid(&self) -> bool { + unsafe { ffi::IsAudioStreamValid(self.0) } } pub fn sample_rate(&self) -> u32 { self.0.sampleRate diff --git a/raylib/src/core/color.rs b/raylib/src/core/color.rs index c74ad3d3..93553923 100644 --- a/raylib/src/core/color.rs +++ b/raylib/src/core/color.rs @@ -148,13 +148,6 @@ impl Color { unsafe { ffi::GetColor(hex_value).into() } } - /// Color fade-in or fade-out, alpha goes from 0.0f to 1.0f - #[inline] - #[deprecated = "Has been superseded by Color::alpha()"] - pub fn fade(&self, alpha: f32) -> Color { - unsafe { ffi::Fade(self.into(), alpha).into() } - } - /// Get color multiplied with another color pub fn tint(&self, color: Self) -> Self { unsafe { ffi::ColorTint(self.into(), color.into()).into() } diff --git a/raylib/src/core/input.rs b/raylib/src/core/input.rs index 7d4bb568..e607f427 100644 --- a/raylib/src/core/input.rs +++ b/raylib/src/core/input.rs @@ -284,8 +284,14 @@ impl RaylibHandle { } /// Set gamepad vibration for both motors - pub fn set_gamepad_vibration(&mut self, gamepad: i32, left_motor: f32, right_motor: f32) { - unsafe { ffi::SetGamepadVibration(gamepad, left_motor, right_motor) } + pub fn set_gamepad_vibration( + &mut self, + gamepad: i32, + left_motor: f32, + right_motor: f32, + duration: f32, + ) { + unsafe { ffi::SetGamepadVibration(gamepad, left_motor, right_motor, duration) } } /// Checks if a gesture have been detected. diff --git a/raylib/src/core/models.rs b/raylib/src/core/models.rs index b2fd462d..7cffcedd 100644 --- a/raylib/src/core/models.rs +++ b/raylib/src/core/models.rs @@ -61,10 +61,7 @@ impl RaylibHandle { let m = unsafe { ffi::LoadModel(c_filename.as_ptr()) }; if m.meshes.is_null() && m.materials.is_null() && m.bones.is_null() && m.bindPose.is_null() { - return Err(error!( - "could not load model", - filename - )); + return Err(error!("could not load model", filename)); } // TODO check if null pointer checks are necessary. Ok(Model(m)) @@ -79,9 +76,7 @@ impl RaylibHandle { 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" - )); + return Err(error!("Could not load model from mesh")); } Ok(Model(m)) @@ -96,10 +91,7 @@ impl RaylibHandle { 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 - )); + 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 { @@ -224,8 +216,8 @@ pub trait RaylibModel: AsRef + AsMut { } /// Check if a model is ready - fn is_ready(&self) -> bool { - unsafe { ffi::IsModelReady(*self.as_ref()) } + fn is_model_valid(&self) -> bool { + unsafe { ffi::IsModelValid(*self.as_ref()) } } /// Compute model bounding box limits (considers all meshes) @@ -236,13 +228,9 @@ pub trait RaylibModel: AsRef + AsMut { /// 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 { - return Err(error!( - "mesh_id greater than mesh count" - )); + return Err(error!("mesh_id greater than mesh count")); } else if material_id >= self.as_ref().materialCount { - return Err(error!( - "material_id greater than material count" - )); + return Err(error!("material_id greater than material count")); } else { unsafe { ffi::SetModelMeshMaterial(self.as_mut(), mesh_id, material_id) }; return Ok(()); @@ -473,10 +461,7 @@ impl Material { 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 - )); + return Err(error!("No materials loaded", filename)); } let mut m_vec = Vec::with_capacity(m_size as usize); for i in 0..m_size { @@ -531,8 +516,8 @@ pub trait RaylibMaterial: AsRef + AsMut { } } - fn is_ready(&mut self) -> bool { - unsafe { ffi::IsMaterialReady(*self.as_ref()) } + fn is_material_valid(&mut self) -> bool { + unsafe { ffi::IsMaterialValid(*self.as_ref()) } } } diff --git a/raylib/src/core/shaders.rs b/raylib/src/core/shaders.rs index 6584b2cd..b841a875 100644 --- a/raylib/src/core/shaders.rs +++ b/raylib/src/core/shaders.rs @@ -187,12 +187,10 @@ impl Shader { m } - /// Check if shader is ready for usage + /// Check if shader is valid #[inline] - pub fn is_ready(&self) { - unsafe { - ffi::IsShaderReady(self.0); - } + pub fn is_shader_valid(&self) -> bool { + unsafe { ffi::IsShaderValid(self.0) } } /// Sets shader uniform value diff --git a/raylib/src/core/text.rs b/raylib/src/core/text.rs index e362c9dc..b7210c7d 100644 --- a/raylib/src/core/text.rs +++ b/raylib/src/core/text.rs @@ -293,13 +293,14 @@ pub trait RaylibFont: AsRef + AsMut { ) } } - /// Check if a font is ready - fn is_ready(&self) -> bool { - unsafe { ffi::IsFontReady(*self.as_ref()) } + + /// Check if a font is valid + fn is_font_valid(&self) -> bool { + unsafe { ffi::IsFontValid(*self.as_ref()) } } /// Export font as code file, returns true on success - fn export_as_code(&self, filename: A) -> bool + fn export_font_as_code(&self, filename: A) -> bool where A: Into, { diff --git a/raylib/src/core/texture.rs b/raylib/src/core/texture.rs index 1a84c435..eeb18481 100644 --- a/raylib/src/core/texture.rs +++ b/raylib/src/core/texture.rs @@ -116,8 +116,8 @@ impl RenderTexture2D { m } - pub fn is_ready(&self) -> bool { - unsafe { ffi::IsRenderTextureReady(self.0) } + pub fn is_render_texture_valid(&self) -> bool { + unsafe { ffi::IsRenderTextureValid(self.0) } } } @@ -738,19 +738,13 @@ impl Image { /// Export image to memory buffer. pub fn export_image_to_memory(&self, file_type: &str) -> Result<&[u8], Error> { if self.width == 0 { - return Err(error!( - "Invalid image; width == 0" - )); + return Err(error!("Invalid image; width == 0")); } if self.height == 0 { - return Err(error!( - "Invalid image; height == 0" - )); + return Err(error!("Invalid image; height == 0")); } if self.data == null_mut() { - return Err(error!( - "Invalid image; data == null" - )); + return Err(error!("Invalid image; data == null")); } let c_filetype = CString::new(file_type).unwrap(); @@ -769,27 +763,19 @@ impl Image { /// NOTE: The convolution kernel matrix is expected to be square pub fn kernel_convolution(&mut self, kernel: &[f32]) -> Result<(), Error> { if self.width == 0 { - return Err(error!( - "Invalid image; width == 0" - )); + return Err(error!("Invalid image; width == 0")); } if self.height == 0 { - return Err(error!( - "Invalid image; height == 0" - )); + return Err(error!("Invalid image; height == 0")); } if self.data == null_mut() { - return Err(error!( - "Invalid image; data == null" - )); + return Err(error!("Invalid image; data == null")); } let kernel_width = (kernel.len() as f32).sqrt() as i32; if (kernel_width * kernel_width) as usize != kernel.len() { - return Err(error!( - "Convolution kernel must be square to be applied" - )); + return Err(error!("Convolution kernel must be square to be applied")); } unsafe { ImageKernelConvolution(&mut self.0, kernel.as_ptr(), kernel.len() as i32) } @@ -938,9 +924,7 @@ impl Image { ) }; if i.data.is_null() { - return Err(error!( - "Image data is null. Check provided buffer data" - )); + return Err(error!("Image data is null. Check provided buffer data")); }; Ok(Image(i)) } @@ -1017,8 +1001,8 @@ impl Image { } } - pub fn is_ready(&self) -> bool { - unsafe { ffi::IsImageReady(self.0) } + pub fn is_image_valid(&self) -> bool { + unsafe { ffi::IsImageValid(self.0) } } } @@ -1116,9 +1100,7 @@ pub trait RaylibTexture2D: AsRef + AsMut { fn load_image(&self) -> Result { let i = unsafe { ffi::LoadImageFromTexture(*self.as_ref()) }; if i.data.is_null() { - return Err(error!( - "Texture cannot be rendered to an image" - )); + return Err(error!("Texture cannot be rendered to an image")); } Ok(Image(i)) } @@ -1147,8 +1129,8 @@ pub trait RaylibTexture2D: AsRef + AsMut { } } - fn is_ready(&self) -> bool { - unsafe { ffi::IsTextureReady(*self.as_ref()) } + fn is_texture_valid(&self) -> bool { + unsafe { ffi::IsTextureValid(*self.as_ref()) } } } @@ -1164,10 +1146,7 @@ impl RaylibHandle { let c_filename = CString::new(filename).unwrap(); let t = unsafe { ffi::LoadTexture(c_filename.as_ptr()) }; if t.id == 0 { - return Err(error!( - "failed to load the texture.", - filename - )); + return Err(error!("failed to load the texture.", filename)); } Ok(Texture2D(t)) } @@ -1181,9 +1160,7 @@ impl RaylibHandle { ) -> Result { let t = unsafe { ffi::LoadTextureCubemap(image.0, layout as i32) }; if t.id == 0 { - return Err(error!( - "failed to load image as a texture cubemap." - )); + return Err(error!("failed to load image as a texture cubemap.")); } Ok(Texture2D(t)) } @@ -1197,9 +1174,7 @@ impl RaylibHandle { ) -> Result { let t = unsafe { ffi::LoadTextureFromImage(image.0) }; if t.id == 0 { - return Err(error!( - "failed to load image as a texture." - )); + return Err(error!("failed to load image as a texture.")); } Ok(Texture2D(t)) } @@ -1213,9 +1188,7 @@ impl RaylibHandle { ) -> Result { let t = unsafe { ffi::LoadRenderTexture(width as i32, height as i32) }; if t.id == 0 { - return Err(error!( - "failed to create render texture." - )); + return Err(error!("failed to create render texture.")); } Ok(RenderTexture2D(t)) } diff --git a/raylib/src/core/window.rs b/raylib/src/core/window.rs index 571c7e40..d38f0bde 100644 --- a/raylib/src/core/window.rs +++ b/raylib/src/core/window.rs @@ -421,16 +421,6 @@ impl RaylibHandle { // Screen-space-related functions impl RaylibHandle { - /// Returns a ray trace from mouse position - #[deprecated = "Renamed to RaylibHandle::get_screen_to_world_ray"] - pub fn get_mouse_ray( - &self, - mouse_position: impl Into, - camera: impl Into, - ) -> Ray { - unsafe { ffi::GetScreenToWorldRay(mouse_position.into(), camera.into()).into() } - } - /// Get a ray trace from screen position (i.e mouse) pub fn get_screen_to_world_ray( &self, From e831eab4484e9de82743321e9e1dbe74bbe06858 Mon Sep 17 00:00:00 2001 From: Jayda <129673690+NewGirlJade@users.noreply.github.com> Date: Thu, 24 Oct 2024 13:56:50 -0600 Subject: [PATCH 40/93] remove double &mut (#61) --- raylib/src/core/drawing.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index e7ba0e1b..4ab1a139 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -130,7 +130,7 @@ where // Only the DrawHandle and the RaylibHandle can start a texture impl<'a> RaylibTextureModeExt for RaylibDrawHandle<'a> {} -impl RaylibTextureModeExt for &mut RaylibHandle {} +impl RaylibTextureModeExt for RaylibHandle {} impl<'a, T> RaylibDraw for RaylibTextureMode<'a, T> {} // VR Stuff From 0c8d134df3e7eec4d650d9c21da59056137c8a27 Mon Sep 17 00:00:00 2001 From: IoIxD <30945097+IoIxD@users.noreply.github.com> Date: Thu, 24 Oct 2024 16:19:33 -0700 Subject: [PATCH 41/93] unremove the file module (#92) * [file] accidentally removed file * [file] accidentally removed file --- raylib/src/core/file.rs | 139 ++++++++++++++++++++++++++++++++++++++++ raylib/src/core/mod.rs | 1 + raylib/src/prelude.rs | 1 + 3 files changed, 141 insertions(+) create mode 100644 raylib/src/core/file.rs diff --git a/raylib/src/core/file.rs b/raylib/src/core/file.rs new file mode 100644 index 00000000..abe3dfaa --- /dev/null +++ b/raylib/src/core/file.rs @@ -0,0 +1,139 @@ +//! File manipulation functions. Should be parity with std::fs except on emscripten +use crate::ffi; + +use crate::core::RaylibHandle; +use std::ffi::{CStr, CString, OsString}; + +make_thin_wrapper!(FilePathList, ffi::FilePathList, ffi::UnloadDirectoryFiles); +make_thin_wrapper!( + DroppedFilePathList, + ffi::FilePathList, + ffi::UnloadDroppedFiles +); + +impl FilePathList { + /// Length of the file path list + pub const fn count(&self) -> u32 { + self.0.count + } + /// The amount of files that can be held in this list. + pub const fn capacity(&self) -> u32 { + self.0.capacity + } + /// The paths held in this list. + /// This function is NOT constant and the inner array will be copied into the returned Vec every time you call this. + pub fn paths(&self) -> Vec<&str> { + unsafe { std::slice::from_raw_parts(self.0.paths, self.count() as usize) } + .iter() + .map(|f| unsafe { CStr::from_ptr(*f) }.to_str().unwrap()) + .collect() + } +} + +impl DroppedFilePathList { + /// Length of the file path list + pub const fn count(&self) -> u32 { + self.0.count + } + /// The amount of files that can be held in this list. + pub const fn capacity(&self) -> u32 { + self.0.capacity + } + /// The paths held in this list. + /// This function is NOT constant and the inner array will be copied into the returned Vec every time you call this. + pub fn paths(&self) -> Vec<&str> { + unsafe { std::slice::from_raw_parts(self.0.paths, self.count() as usize) } + .iter() + .map(|f| unsafe { CStr::from_ptr(*f) }.to_str().unwrap()) + .collect() + } +} + +impl RaylibHandle { + /// Checks if a file has been dropped into the window. + #[inline] + pub fn is_file_dropped(&self) -> bool { + unsafe { ffi::IsFileDropped() } + } + + /// Checks a file's extension. + #[inline] + pub fn is_file_extension(&self, file_name: A, file_ext: A) -> bool + where + A: Into, + { + let file_name = CString::new(file_name.into().to_string_lossy().as_bytes()).unwrap(); + let file_ext = CString::new(file_ext.into().to_string_lossy().as_bytes()).unwrap(); + unsafe { ffi::IsFileExtension(file_name.as_ptr(), file_ext.as_ptr()) } + } + /// Get the directory of the running application. + pub fn application_directory(&self) -> String { + unsafe { + let st = ffi::GetApplicationDirectory(); + let c_str = CStr::from_ptr(st); + + // If this ever errors out, yell at @ioi_xd on Discord, + c_str.to_str().unwrap().to_string() + } + } + + /// Get file length in bytes. + /// + /// # Errors + /// This function will return an error if the supplied bytes contain an internal 0 byte. The NulError returned will contain the bytes as well as the position of the nul byte. + pub fn get_file_length(&self, filename: A) -> i32 + where + A: Into, + { + let c_str = CString::new(filename.into().to_string_lossy().as_bytes()).unwrap(); + unsafe { ffi::GetFileLength(c_str.as_ptr()) } + } + + /// Check if a given path is a file or a directory + /// # Errors + /// This function will return an error if the supplied bytes contain an internal 0 byte. The NulError returned will contain the bytes as well as the position of the nul byte. + pub fn is_path_file(&self, filename: A) -> bool + where + A: Into, + { + let c_str = CString::new(filename.into().to_string_lossy().as_bytes()).unwrap(); + unsafe { ffi::IsPathFile(c_str.as_ptr()) } + } + + /// Load directory filepaths + pub fn load_directory_files(&self, dir_path: A) -> FilePathList + where + A: Into, + { + unsafe { + let c_str = CString::new(dir_path.into().to_string_lossy().as_bytes()).unwrap(); // .unwrap() is okay here because any nul bytes placed into the actual string should be cleared out by to_string_lossy. + FilePathList(ffi::LoadDirectoryFiles(c_str.as_ptr())) + } + } + + /// Load directory filepaths with extension filtering and recursive directory scan + pub fn load_directory_files_ex( + &self, + dir_path: A, + filter: String, + scan_sub_dirs: bool, + ) -> FilePathList + where + A: Into, + { + unsafe { + let dir_c_str = CString::new(dir_path.into().to_string_lossy().as_bytes()).unwrap(); // .unwrap() is okay here because any nul bytes placed into the actual string should be cleared out by to_string_lossy. + let filter_c_str = CString::new(filter.replace("\0", "").as_bytes()).unwrap(); + FilePathList(ffi::LoadDirectoryFilesEx( + dir_c_str.as_ptr(), + filter_c_str.as_ptr(), + scan_sub_dirs, + )) + } + } + + /// Check if a file has been dropped into window + pub fn load_dropped_files(&self) -> DroppedFilePathList { + unsafe { DroppedFilePathList(ffi::LoadDroppedFiles()) } + } +} diff --git a/raylib/src/core/mod.rs b/raylib/src/core/mod.rs index 847e8807..f3e988b4 100644 --- a/raylib/src/core/mod.rs +++ b/raylib/src/core/mod.rs @@ -20,6 +20,7 @@ pub mod text; pub mod texture; pub mod vr; pub mod window; +pub mod file; use raylib_sys::TraceLogLevel; diff --git a/raylib/src/prelude.rs b/raylib/src/prelude.rs index e0482845..9b359d0b 100644 --- a/raylib/src/prelude.rs +++ b/raylib/src/prelude.rs @@ -44,5 +44,6 @@ pub use crate::core::texture::*; pub use crate::core::vr::*; pub use crate::core::window::*; pub use crate::core::*; +pub use crate::core::file::*; pub use crate::rgui::*; pub use crate::*; From 17142a6e0e5dd13094c80e755ae837694dfe9535 Mon Sep 17 00:00:00 2001 From: jestarray <34615798+jestarray@users.noreply.github.com> Date: Sun, 27 Oct 2024 12:22:01 -0700 Subject: [PATCH 42/93] remove unused dependencies (#94) * remove raylib src directory copy to out dir * fix callback.rs not compiling due to inline-const experimental * remove libc dependency refactor: libc::c_void -> std::is::raw:::c_void libc::malloc -> ffi::MemAlloc (using raylibs bindings to malloc instead) * removed unused crate lazy_static remove unused crate parking_lot make specs-derive optional remove arr_macro which was only needed for the examples * make specs an optional dependency * bump bindgen 0.69 -> 0.70 * raylib-sys remove fs_extra dependency update cmake 0.1.49 -> 0.1.51 * remove arr_macro from samples fix 3d_camera_first_person to compile --- raylib-sys/Cargo.toml | 5 ++--- raylib-sys/build.rs | 31 +++++++++++++------------------ raylib/Cargo.toml | 11 ++--------- raylib/src/core/callbacks.rs | 14 +++++++------- raylib/src/core/models.rs | 4 ++-- raylib/src/core/text.rs | 6 +++--- samples/3d_camera_first_person.rs | 15 +++++++++------ samples/Cargo.toml | 1 - 8 files changed, 38 insertions(+), 49 deletions(-) diff --git a/raylib-sys/Cargo.toml b/raylib-sys/Cargo.toml index 7285a856..42fe2d71 100644 --- a/raylib-sys/Cargo.toml +++ b/raylib-sys/Cargo.toml @@ -12,10 +12,9 @@ edition = "2018" exclude = ["raylib/examples/*", "raylib/projects/*", "raylib/templates/*"] [build-dependencies] -fs_extra = "1.2" -cmake = "0.1.49" +cmake = "0.1.51" cc = "1.0" -bindgen = "0.69.0" +bindgen = "0.70" [features] default = [] diff --git a/raylib-sys/build.rs b/raylib-sys/build.rs index 0399146a..456a5374 100644 --- a/raylib-sys/build.rs +++ b/raylib-sys/build.rs @@ -128,10 +128,7 @@ fn build_with_cmake(src_path: &str) { // Allows disabling the default maping of screenshot and gif recording in raylib { - #[cfg(any( - feature = "noscreenshot", - feature = "nogif" - ))] + #[cfg(any(feature = "noscreenshot", feature = "nogif"))] builder.define("CUSTOMIZE_BUILD", "ON"); #[cfg(feature = "noscreenshot")] @@ -333,9 +330,11 @@ fn main() { } let (platform, platform_os) = platform_from_target(&target); - // Donwload raylib source - let src = cp_raylib(); - build_with_cmake(&src); + let raylib_src = "./raylib"; + if is_directory_empty(raylib_src) { + panic!("raylib source does not exist in: `raylib-sys/raylib`. Please copy it in"); + } + build_with_cmake(raylib_src); gen_bindings(); @@ -344,17 +343,13 @@ fn main() { gen_rgui(); } -// cp_raylib copy raylib to an out dir -fn cp_raylib() -> String { - let out = env::var("OUT_DIR").unwrap(); - let out = Path::new(&out); //.join("raylib_source"); - - let mut options = fs_extra::dir::CopyOptions::new(); - options.skip_exist = true; - fs_extra::dir::copy("raylib", out, &options) - .unwrap_or_else(|_| panic!("failed to copy raylib source to {}", &out.to_string_lossy())); - - out.join("raylib").to_string_lossy().to_string() +#[must_use] +/// returns false if the directory does not exist +fn is_directory_empty(path: &str) -> bool { + match std::fs::read_dir(path) { + Ok(mut dir) => dir.next().is_none(), + Err(_) => true, + } } // run_command runs a command to completion or panics. Used for running curl and powershell. diff --git a/raylib/Cargo.toml b/raylib/Cargo.toml index ca88baaf..99250daf 100644 --- a/raylib/Cargo.toml +++ b/raylib/Cargo.toml @@ -14,26 +14,19 @@ autoexamples = false [dependencies] raylib-sys = { version = "5.5.0", path = "../raylib-sys" } -libc = "0.2.45" -lazy_static = "1.2.0" cfg-if = "1.0.0" serde = { version = "1.0.125", features = ["derive"], optional = true } serde_json = { version = "1.0.64", optional = true } mint = { version = "0.5.9", optional = true } -parking_lot = "0.12.1" -specs-derive = "0.4.1" +specs = { version = "0.16.1", default = false, optional = true } +specs-derive = { version = "0.4.1", optional = true } thiserror = "1.0.61" [dev-dependencies] structopt = "0.3" rand = "0.8.5" -arr_macro = "0.1.3" - -[dependencies.specs] -version = "0.16.1" -default-features = false [features] nightly = [] diff --git a/raylib/src/core/callbacks.rs b/raylib/src/core/callbacks.rs index 62c1a6b4..88a06ffa 100644 --- a/raylib/src/core/callbacks.rs +++ b/raylib/src/core/callbacks.rs @@ -32,37 +32,37 @@ static LOAD_FILE_TEXT_CALLBACK: AtomicUsize = AtomicUsize::new(0); static AUDIO_STREAM_CALLBACK: AtomicUsize = AtomicUsize::new(0); fn trace_log_callback() -> Option { - const { assert!(size_of::() == size_of::()) }; + debug_assert!(size_of::() == size_of::()); unsafe { transmute(TRACE_LOG_CALLBACK.load(Ordering::Relaxed)) } } fn save_file_data_callback() -> Option { - const { assert!(size_of::() == size_of::()) }; + debug_assert!(size_of::() == size_of::()); unsafe { transmute(SAVE_FILE_DATA_CALLBACK.load(Ordering::Relaxed)) } } fn load_file_data_callback() -> Option { - const { assert!(size_of::() == size_of::()) }; + debug_assert!(size_of::() == size_of::()); unsafe { transmute(LOAD_FILE_DATA_CALLBACK.load(Ordering::Relaxed)) } } fn save_file_text_callback() -> Option { - const { assert!(size_of::() == size_of::()) }; + debug_assert!(size_of::() == size_of::()); unsafe { transmute(SAVE_FILE_TEXT_CALLBACK.load(Ordering::Relaxed)) } } fn load_file_text_callback() -> Option { - const { assert!(size_of::() == size_of::()) }; + debug_assert!(size_of::() == size_of::()); unsafe { transmute(LOAD_FILE_TEXT_CALLBACK.load(Ordering::Relaxed)) } } fn audio_stream_callback() -> Option { - const { assert!(size_of::() == size_of::()) }; + debug_assert!(size_of::() == size_of::()); unsafe { transmute(AUDIO_STREAM_CALLBACK.load(Ordering::Relaxed)) } } #[no_mangle] -pub extern "C" fn custom_trace_log_callback(level: TraceLogLevel, text: *const c_char) { +pub unsafe extern "C" fn custom_trace_log_callback(level: TraceLogLevel, text: *const c_char) { if let Some(trace_log) = trace_log_callback() { let text = if text.is_null() { Cow::Borrowed("(MESSAGE WAS NULL)") diff --git a/raylib/src/core/models.rs b/raylib/src/core/models.rs index 7cffcedd..1fd3c79f 100644 --- a/raylib/src/core/models.rs +++ b/raylib/src/core/models.rs @@ -100,7 +100,7 @@ impl RaylibHandle { } } unsafe { - ffi::MemFree(m_ptr as *mut libc::c_void); + ffi::MemFree(m_ptr as *mut ::std::os::raw::c_void); } Ok(m_vec) } @@ -470,7 +470,7 @@ impl Material { } } unsafe { - ffi::MemFree(m_ptr as *mut libc::c_void); + ffi::MemFree(m_ptr as *mut ::std::os::raw::c_void); } Ok(m_vec) } diff --git a/raylib/src/core/text.rs b/raylib/src/core/text.rs index b7210c7d..9d2e77a1 100644 --- a/raylib/src/core/text.rs +++ b/raylib/src/core/text.rs @@ -9,7 +9,7 @@ use crate::error::{error, Error}; use crate::ffi; use crate::math::Rectangle; -use std::convert::{AsMut, AsRef}; +use std::convert::{AsMut, AsRef, TryInto}; use std::ffi::{CString, OsString}; use std::mem::ManuallyDrop; use std::ops::Deref; @@ -371,7 +371,7 @@ impl Font { unsafe { self.glyphCount = chars.len() as i32; let data_size = self.glyphCount as usize * std::mem::size_of::(); - let ci_arr_ptr = libc::malloc(data_size); // raylib frees this data in UnloadFont + let ci_arr_ptr = ffi::MemAlloc(data_size.try_into().unwrap()); // raylib frees this data in UnloadFont std::ptr::copy( chars.as_ptr(), ci_arr_ptr as *mut ffi::GlyphInfo, @@ -415,7 +415,7 @@ pub fn gen_image_font_atlas( #[allow(clippy::uninit_vec)] recs.set_len(chars.len()); std::ptr::copy(ptr, recs.as_mut_ptr(), chars.len()); - ffi::MemFree(ptr as *mut libc::c_void); + ffi::MemFree(ptr as *mut ::std::os::raw::c_void); return (img, recs); } } diff --git a/samples/3d_camera_first_person.rs b/samples/3d_camera_first_person.rs index 08b993cb..ded4e87d 100644 --- a/samples/3d_camera_first_person.rs +++ b/samples/3d_camera_first_person.rs @@ -1,10 +1,10 @@ -use arr_macro::arr; use rand::prelude::*; use raylib::prelude::*; const WINDOW_WIDTH: i32 = 1280; const WINDOW_HEIGHT: i32 = 720; +#[derive(Copy, Clone, Default)] struct Column { height: f32, position: Vector3, @@ -14,13 +14,13 @@ struct Column { impl Column { fn create_random() -> Column { let mut rng = rand::thread_rng(); - let height: f32 = rng.gen_range(1.0, 12.0); + let height: f32 = rng.gen_range(1.0..12.0); let position = Vector3::new( - rng.gen_range(-15.0, 15.0), + rng.gen_range(-15.0..15.0), height / 2.0, - rng.gen_range(-15.0, 15.0), + rng.gen_range(-15.0..15.0), ); - let color = Color::new(rng.gen_range(20, 255), rng.gen_range(10, 55), 30, 255); + let color = Color::new(rng.gen_range(20..255), rng.gen_range(10..55), 30, 255); Column { height, @@ -42,7 +42,10 @@ fn main() { Vector3::new(0.0, 1.0, 0.0), 60.0, ); - let columns: [Column; 20] = arr![Column::create_random(); 20]; + let mut columns = [Column::default(); 20]; + for col in columns.iter_mut() { + *col = Column::create_random(); + } rl.set_target_fps(60); diff --git a/samples/Cargo.toml b/samples/Cargo.toml index 7030c2be..190dc8c2 100644 --- a/samples/Cargo.toml +++ b/samples/Cargo.toml @@ -16,7 +16,6 @@ rand = "0.7" #tcod = "0.14" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" -arr_macro = "0.1.3" [dependencies.specs] version = "0.16.1" From 3592c299615fbe5fa9ed364fef1f78b65844f391 Mon Sep 17 00:00:00 2001 From: jestarray <34615798+jestarray@users.noreply.github.com> Date: Tue, 29 Oct 2024 10:56:42 -0700 Subject: [PATCH 43/93] partial android support (#98) * partial android support * remove `RAYMATH_STATIC_INLINE` --- raylib-sys/build.rs | 54 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 52 insertions(+), 2 deletions(-) diff --git a/raylib-sys/build.rs b/raylib-sys/build.rs index 456a5374..4375b999 100644 --- a/raylib-sys/build.rs +++ b/raylib-sys/build.rs @@ -82,8 +82,7 @@ fn build_with_cmake(src_path: &str) { .define("CMAKE_BUILD_TYPE", profile) // turn off until this is fixed .define("SUPPORT_BUSY_WAIT_LOOP", "OFF") - .define("SUPPORT_FILEFORMAT_JPG", "ON") - .define("RAYMATH_STATIC_INLINE", "ON"); + .define("SUPPORT_FILEFORMAT_JPG", "ON"); #[cfg(feature = "custom_frame_control")] { @@ -149,6 +148,44 @@ fn build_with_cmake(src_path: &str) { .define("PLATFORM", "Web") .define("CMAKE_C_FLAGS", "-s ASYNCIFY"), Platform::RPI => conf.define("PLATFORM", "Raspberry Pi"), + Platform::Android => { + // get required env variables + let android_ndk_home = env::var("ANDROID_NDK_HOME") + .expect("Please set the environment variable: ANDROID_NDK_HOME:(e.g /home/u/Android/Sdk/ndk/VXXX/)"); + let android_platform = target.split("-").last().expect("fail to parse the android version of the target triple, example:'aarch64-linux-android25'"); + let abi_version = android_platform + .split("-") + .last() + .expect("Could not get abi version. Is ANDROID_PLATFORM valid?"); + let toolchain_file = + format!("{}/build/cmake/android.toolchain.cmake", &android_ndk_home); + // Detect ANDROID_ABI using the target triple + let android_arch_abi = match target.as_str() { + "aarch64-linux-android" => "arm64-v8a", + "armv7-linux-androideabi" => "armeabi-v7a", + _ => panic!("Unsupported target triple for Android"), + }; + // we'll set as many variables as possible according to: + // https://developer.android.com/ndk/guides/cmake#command-line_1 + // https://cmake.org/cmake/help/v3.31/manual/cmake-toolchains.7.html#cross-compiling-for-android-with-the-ndk + // how to build: + // 0) set the correct linker in your game project's Cargo.toml (note: platform number should match): + // [target.aarch64-linux-android] + // linker = "/home/u/Android/Sdk/ndk/28.0.12433566/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android-clang" + + // 1) set env variable ANDROID_NDK_HOME + // 2) compile with: `cargo ndk -t -p -o ./jniLibs build` + // example(cargo ndk -t arm64-v8a -p 25 -o ./jniLibs build) + + conf.define("CMAKE_SYSTEM_NAME", "Android") + .define("PLATFORM", "Android") + .define("CMAKE_SYSTEM_VERSION", abi_version) + .define("ANDROID_ABI", android_arch_abi) + .define("CMAKE_ANDROID_ARCH_ABI", android_arch_abi) + .define("CMAKE_ANDROID_NDK", &android_ndk_home) + .define("ANDROID_PLATFORM", android_platform) + .define("CMAKE_TOOLCHAIN_FILE", &toolchain_file) + } }; let dst = conf.build(); @@ -181,6 +218,15 @@ fn build_with_cmake(src_path: &str) { } // println!("cmake build {}", c.display()); println!("cargo:rustc-link-search=native={}", dst_lib.display()); + if platform == Platform::Android { + println!("cargo:rustc-link-lib=log"); + println!("cargo:rustc-link-lib=android"); + println!("cargo:rustc-link-lib=EGL"); + println!("cargo:rustc-link-lib=GLESv2"); + println!("cargo:rustc-link-lib=OpenSLES"); + println!("cargo:rustc-link-lib=c"); + println!("cargo:rustc-link-lib=m"); + } } fn gen_bindings() { @@ -190,6 +236,7 @@ fn gen_bindings() { let plat = match platform { Platform::Desktop => "-DPLATFORM_DESKTOP", Platform::RPI => "-DPLATFORM_RPI", + Platform::Android => "-DPLATFORM_ANDROID", Platform::Web => "-DPLATFORM_WEB", }; @@ -373,6 +420,8 @@ fn platform_from_target(target: &str) -> (Platform, PlatformOS) { Platform::Web } else if target.contains("armv7-unknown-linux") { Platform::RPI + } else if target.contains("android") { + Platform::Android } else { Platform::Desktop }; @@ -431,6 +480,7 @@ fn uname() -> String { enum Platform { Web, Desktop, + Android, RPI, // raspberry pi } From 230012acfed333038459d745320b03f972eb4639 Mon Sep 17 00:00:00 2001 From: jestarray <34615798+jestarray@users.noreply.github.com> Date: Thu, 31 Oct 2024 01:54:29 -0700 Subject: [PATCH 44/93] make raylib-sys/raylib submodule shallow (#99) --- .gitmodules | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitmodules b/.gitmodules index d0e3f3e8..d6cfeec7 100644 --- a/.gitmodules +++ b/.gitmodules @@ -2,3 +2,4 @@ path = raylib-sys/raylib url = https://github.com/raysan5/raylib commit = "039df36f" + shallow = true From a2e41258db7f667aa18ae5f0e7e62a4cfc3a8d7b Mon Sep 17 00:00:00 2001 From: jestarray <34615798+jestarray@users.noreply.github.com> Date: Sat, 2 Nov 2024 12:12:35 -0700 Subject: [PATCH 45/93] make sure gles2 links to needed libs and added gles3 (#100) --- raylib-sys/Cargo.toml | 1 + raylib-sys/build.rs | 16 ++++++++++++++-- raylib/Cargo.toml | 1 + 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/raylib-sys/Cargo.toml b/raylib-sys/Cargo.toml index 42fe2d71..aed181e4 100644 --- a/raylib-sys/Cargo.toml +++ b/raylib-sys/Cargo.toml @@ -29,6 +29,7 @@ opengl_33 = [] opengl_21 = [] # opengl_11 = [] I couldn't get this one working, the others were fine in my limited testing (unsure about wayland compatibility) opengl_es_20 = [] +opengl_es_30 = [] # Allow disabling screenshots and gifs on f12 noscreenshot = [] diff --git a/raylib-sys/build.rs b/raylib-sys/build.rs index 4375b999..9c374f6f 100644 --- a/raylib-sys/build.rs +++ b/raylib-sys/build.rs @@ -113,14 +113,26 @@ fn build_with_cmake(src_path: &str) { // builder.define("OPENGL_VERSION", "1.1"); #[cfg(feature = "opengl_es_20")] - builder.define("OPENGL_VERSION", "ES 2.0"); + { + builder.define("OPENGL_VERSION", "ES 2.0"); + println!("cargo:rustc-link-lib=GLESv2"); + println!("cargo:rustc-link-lib=GLdispatch"); + } + + #[cfg(feature = "opengl_es_30")] + { + builder.define("OPENGL_VERSION", "ES 3.0"); + println!("cargo:rustc-link-lib=GLESv2"); + println!("cargo:rustc-link-lib=GLdispatch"); + } // Once again felt this was necessary incase a default was changed :) #[cfg(not(any( feature = "opengl_33", feature = "opengl_21", // feature = "opengl_11", - feature = "opengl_es_20" + feature = "opengl_es_20", + feature = "opengl_es_30" )))] builder.define("OPENGL_VERSION", "OFF"); } diff --git a/raylib/Cargo.toml b/raylib/Cargo.toml index 99250daf..60f30070 100644 --- a/raylib/Cargo.toml +++ b/raylib/Cargo.toml @@ -37,6 +37,7 @@ custom_frame_control = ["raylib-sys/custom_frame_control"] opengl_33 = ["raylib-sys/opengl_33"] opengl_21 = ["raylib-sys/opengl_21"] opengl_es_20 = ["raylib-sys/opengl_es_20"] +opengl_es_30 = ["raylib-sys/opengl_es_30"] noscreenshot = ["raylib-sys/noscreenshot"] nogif = ["raylib-sys/nogif"] From 8683f0a0718cf7ae09844d0c8cda72fd8054db3e Mon Sep 17 00:00:00 2001 From: jestarray <34615798+jestarray@users.noreply.github.com> Date: Sun, 3 Nov 2024 10:09:46 -0800 Subject: [PATCH 46/93] added desktop sdl backend support (#101) --- raylib-sys/Cargo.toml | 1 + raylib-sys/build.rs | 12 +++++++++++- raylib/Cargo.toml | 1 + 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/raylib-sys/Cargo.toml b/raylib-sys/Cargo.toml index aed181e4..c2790608 100644 --- a/raylib-sys/Cargo.toml +++ b/raylib-sys/Cargo.toml @@ -30,6 +30,7 @@ opengl_21 = [] # opengl_11 = [] I couldn't get this one working, the others were fine in my limited testing (unsure about wayland compatibility) opengl_es_20 = [] opengl_es_30 = [] +sdl = [] # Allow disabling screenshots and gifs on f12 noscreenshot = [] diff --git a/raylib-sys/build.rs b/raylib-sys/build.rs index 9c374f6f..397d8421 100644 --- a/raylib-sys/build.rs +++ b/raylib-sys/build.rs @@ -155,7 +155,17 @@ fn build_with_cmake(src_path: &str) { } match platform { - Platform::Desktop => conf.define("PLATFORM", "Desktop"), + Platform::Desktop => { + #[cfg(feature = "sdl")] + { + println!("cargo:rustc-link-lib=SDL2"); + conf.define("PLATFORM", "SDL") + } + #[cfg(not(feature = "sdl"))] + { + conf.define("PLATFORM", "Desktop") + } + } Platform::Web => conf .define("PLATFORM", "Web") .define("CMAKE_C_FLAGS", "-s ASYNCIFY"), diff --git a/raylib/Cargo.toml b/raylib/Cargo.toml index 60f30070..42463edc 100644 --- a/raylib/Cargo.toml +++ b/raylib/Cargo.toml @@ -38,6 +38,7 @@ opengl_33 = ["raylib-sys/opengl_33"] opengl_21 = ["raylib-sys/opengl_21"] opengl_es_20 = ["raylib-sys/opengl_es_20"] opengl_es_30 = ["raylib-sys/opengl_es_30"] +sdl = ["raylib-sys/sdl"] noscreenshot = ["raylib-sys/noscreenshot"] nogif = ["raylib-sys/nogif"] From 654544542abaa76ebd53f2dbe946e2b18240b756 Mon Sep 17 00:00:00 2001 From: IoIxD Date: Mon, 2 Dec 2024 08:50:38 -0700 Subject: [PATCH 47/93] [general] bumped submodule to 5.5 --- raylib-sys/raylib | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/raylib-sys/raylib b/raylib-sys/raylib index 15f6c47f..c1ab645c 160000 --- a/raylib-sys/raylib +++ b/raylib-sys/raylib @@ -1 +1 @@ -Subproject commit 15f6c47f0715afd1fce52d760053026c2b92214c +Subproject commit c1ab645ca298a2801097931d1079b10ff7eb9df8 From 19dcfd1bd892694181eb27695e2be87e3c09ea55 Mon Sep 17 00:00:00 2001 From: IoIxD <30945097+IoIxD@users.noreply.github.com> Date: Mon, 2 Dec 2024 14:31:52 -0700 Subject: [PATCH 48/93] Rest of 5.5 (#103) * [general] finishing 5.5 functions * [color] fade is still deprecated --- .gitmodules | 2 +- find_unimplemented.py | 57 +++++++++++++++++++++++++++++++++++++- raylib/src/core/color.rs | 12 ++++++++ raylib/src/core/drawing.rs | 35 +++++++++++++++++++++++ raylib/src/core/models.rs | 17 ++++++++++-- raylib/src/core/texture.rs | 41 ++++++++++++++++++--------- 6 files changed, 146 insertions(+), 18 deletions(-) diff --git a/.gitmodules b/.gitmodules index d6cfeec7..fa0b22c7 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,5 +1,5 @@ [submodule "raylib-sys/raylib"] path = raylib-sys/raylib url = https://github.com/raysan5/raylib - commit = "039df36f" + commit = "5.5" shallow = true diff --git a/find_unimplemented.py b/find_unimplemented.py index efee25ed..b92823a3 100644 --- a/find_unimplemented.py +++ b/find_unimplemented.py @@ -3,6 +3,61 @@ src = os.scandir("./raylib/src/core/") src_files = [] +# Functions we won't implement. +wont_impl = [ + # We have this implemented in a C file so it's not caught. + "SetTraceLogCallback", + # UTF-8 functions + "GetCodepointNext", + "GetCodepointPrevious", + "CodepointToUTF8", + "LoadUTF8", + "UnloadUTF8", + # Text functions + "TextCopy", + "TextIsEqual", + "TextLength", + "TextFormat", + "TextSubtext", + "TextReplace", + "TextInsert", + "TextJoin", + "TextSplit", + "TextAppend", + "TextFindIndex", + "TextToUpper", + "TextToLower", + "TextToPascal", + "TextToSnake", + "TextToCamel", + "TextToInteger", + "TextToFloat", + # file functions + "LoadFileData", + "UnloadFileData", + "SaveFileData", + "LoadFileText", + "UnloadFileText", + "SaveFileText", + "FileExists", + "DirectoryExists", + "GetFileExtension", + "GetFileName", + "GetFileNameWithoutExt", + "GetDirectoryPath", + "GetPrevDirectoryPath", + "GetWorkingDirectory", + "MakeDirectory", + "ChangeDirectory", + "IsFileNameValid", + "GetFileModTime", + "ComputeCRC32", + "ComputeMD5", + "ComputeSHA1", + # Misc functions that aren't needed. + "MemRealloc", +] + for file in src: if file.is_file(follow_symlinks=True): f = open(file.path) @@ -15,7 +70,7 @@ func_name = list(filter(lambda f: "(" in f, line.split(" ")))[0].split("(")[0].replace("*","") in_a_file = False for file in src_files: - if "ffi::"+func_name in file: + if func_name in wont_impl or "ffi::"+func_name in file: in_a_file = True break if not in_a_file: diff --git a/raylib/src/core/color.rs b/raylib/src/core/color.rs index 93553923..fd97d5aa 100644 --- a/raylib/src/core/color.rs +++ b/raylib/src/core/color.rs @@ -164,6 +164,13 @@ impl Color { pub fn alpha(&self, alpha: f32) -> Self { unsafe { ffi::ColorAlpha(self.into(), alpha).into() } } + + /// Get color with alpha applied, alpha goes from 0.0f to 1.0f + #[deprecated = "Use Color::alpha instead"] + pub fn fade(&self, alpha: f32) -> Self { + unsafe { ffi::Fade(self.into(), alpha).into() } + } + /// Color fade-in or fade-out, alpha goes from 0.0f to 1.0f #[inline] pub fn color_alpha_blend(dst: &Color, src: &Color, tint: &Color) -> Color { @@ -173,6 +180,11 @@ impl Color { pub fn is_equal(&self, rhs: impl Into) -> bool { unsafe { ffi::ColorIsEqual(self.into(), rhs.into()) } } + + /// Get color lerp interpolation between two colors, factor [0.0f..1.0f] + pub fn lerp(&self, rhs: Color, factor: f32) -> Color { + unsafe { ffi::ColorLerp(self.into(), rhs.into(), factor).into() } + } } /// NOTE(IOI_XD): We manually implement PartialEq as of 5.5 to use Raylib's function. It's very unlikely it will ever diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index 4ab1a139..b32ec556 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -2025,4 +2025,39 @@ pub trait RaylibDraw3D { ) } } + + /// Draw a model as points + fn draw_model_points( + &mut self, + model: impl Into, + position: impl Into, + scale: f32, + tint: impl Into, + ) { + unsafe { + ffi::DrawModelPoints(model.into(), position.into(), scale, tint.into()); + } + } + + /// Draw a model as points with extended parameters + fn draw_model_points_ex( + &mut self, + model: impl Into, + position: impl Into, + rotation_axis: impl Into, + angle: f32, + scale: impl Into, + tint: impl Into, + ) { + unsafe { + ffi::DrawModelPointsEx( + model.into(), + position.into(), + rotation_axis.into(), + angle, + scale.into(), + tint.into(), + ); + } + } } diff --git a/raylib/src/core/models.rs b/raylib/src/core/models.rs index 1fd3c79f..f8555d1b 100644 --- a/raylib/src/core/models.rs +++ b/raylib/src/core/models.rs @@ -1,5 +1,4 @@ //! 3D Model, Mesh, and Animation -use raylib_sys::GetModelBoundingBox; use crate::core::math::{BoundingBox, Vector3}; use crate::core::texture::Image; @@ -100,7 +99,7 @@ impl RaylibHandle { } } unsafe { - ffi::MemFree(m_ptr as *mut ::std::os::raw::c_void); + ffi::UnloadModelAnimations(m_ptr, m_size); } Ok(m_vec) } @@ -116,6 +115,18 @@ impl RaylibHandle { ffi::UpdateModelAnimation(*model.as_mut(), *anim.as_ref(), frame); } } + + pub fn update_model_animation_bones( + &mut self, + _: &RaylibThread, + mut model: impl AsMut, + anim: impl AsRef, + frame: i32, + ) { + unsafe { + ffi::UpdateModelAnimationBones(*model.as_mut(), *anim.as_ref(), frame); + } + } } impl RaylibModel for WeakModel {} @@ -222,7 +233,7 @@ pub trait RaylibModel: AsRef + AsMut { /// Compute model bounding box limits (considers all meshes) fn get_model_bounding_box(&self) -> BoundingBox { - unsafe { BoundingBox::from(GetModelBoundingBox(*self.as_ref())) } + unsafe { BoundingBox::from(ffi::GetModelBoundingBox(*self.as_ref())) } } /// Set material for a mesh diff --git a/raylib/src/core/texture.rs b/raylib/src/core/texture.rs index eeb18481..d3edd5e2 100644 --- a/raylib/src/core/texture.rs +++ b/raylib/src/core/texture.rs @@ -1,10 +1,5 @@ //! Image and texture related functions -use raylib_sys::{ - ExportImageToMemory, GetPixelColor, ImageKernelConvolution, LoadImageAnim, - LoadImageAnimFromMemory, PixelFormat, -}; - use crate::core::color::Color; use crate::core::math::Rectangle; use crate::core::{RaylibHandle, RaylibThread}; @@ -435,10 +430,18 @@ impl Image { &mut self, start_pos: impl Into, end_pos: impl Into, - thick: f32, + thick: i32, color: impl Into, ) { - unsafe { ffi::DrawLineEx(start_pos.into(), end_pos.into(), thick, color.into()) } + unsafe { + ffi::ImageDrawLineEx( + &mut self.0, + start_pos.into(), + end_pos.into(), + thick, + color.into(), + ) + } } /// Draw line within an image (Vector version) @@ -579,7 +582,7 @@ impl Image { color: impl Into, ) { unsafe { - ffi::DrawRectangleV(position.into(), size.into(), color.into()); + ffi::ImageDrawRectangleV(&mut self.0, position.into(), size.into(), color.into()); } } @@ -590,7 +593,7 @@ impl Image { color: impl Into, ) { unsafe { - ffi::DrawRectangleRec(rectangle.into(), color.into()); + ffi::ImageDrawRectangleRec(&mut self.0, rectangle.into(), color.into()); } } @@ -749,7 +752,7 @@ impl Image { let c_filetype = CString::new(file_type).unwrap(); let data_size: &mut i32 = &mut 0; - let data = unsafe { ExportImageToMemory(self.0, c_filetype.as_ptr(), data_size) }; + let data = unsafe { ffi::ExportImageToMemory(self.0, c_filetype.as_ptr(), data_size) }; // The actual function returns null if the code for converting to a file type never goes off. if data == null_mut() { @@ -778,7 +781,7 @@ impl Image { return Err(error!("Convolution kernel must be square to be applied")); } - unsafe { ImageKernelConvolution(&mut self.0, kernel.as_ptr(), kernel.len() as i32) } + unsafe { ffi::ImageKernelConvolution(&mut self.0, kernel.as_ptr(), kernel.len() as i32) } Ok(()) } @@ -899,6 +902,18 @@ impl Image { unsafe { Image(ffi::GenImageCellular(width, height, tile_size)) } } + /// Get clipboard image. + /// + /// NOTE: Only avaliable on Windows. Do not use if you plan to compile to other platforms. + #[cfg(target_os = "windows")] + pub fn get_clipboard_image(&mut self) -> Result { + let i = unsafe { ffi::GetClipboardImage() }; + if i.data.is_null() { + return Err(error!("Image data is null.")); + } + Ok(Image(i)) + } + /// Loads image from file into CPU memory (RAM). pub fn load_image(filename: &str) -> Result { let c_filename = CString::new(filename).unwrap(); @@ -936,7 +951,7 @@ impl Image { pub fn load_image_anim(filename: &str, frame_num: &mut i32) -> Self { let c_filename = CString::new(filename).unwrap(); - unsafe { Image(LoadImageAnim(c_filename.as_ptr(), frame_num)) } + unsafe { Image(ffi::LoadImageAnim(c_filename.as_ptr(), frame_num)) } } /// Load image from memory buffer, with the number of frames loaded saved to frame_num. @@ -945,7 +960,7 @@ impl Image { let c_filetype = CString::new(filetype).unwrap(); unsafe { - Image(LoadImageAnimFromMemory( + Image(ffi::LoadImageAnimFromMemory( c_filetype.as_ptr(), data.as_ptr(), data.len() as i32, From cae1e5d6a8f0fa9a6b714469a01f85cfc0054f30 Mon Sep 17 00:00:00 2001 From: IoIxD <30945097+IoIxD@users.noreply.github.com> Date: Mon, 2 Dec 2024 17:57:17 -0700 Subject: [PATCH 49/93] [build] we will not be getting better wasm compilation after all (#105) --- raylib-sys/build.rs | 16 +++++++--------- raylib-sys/raylib | 2 +- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/raylib-sys/build.rs b/raylib-sys/build.rs index 397d8421..32e7672d 100644 --- a/raylib-sys/build.rs +++ b/raylib-sys/build.rs @@ -166,9 +166,7 @@ fn build_with_cmake(src_path: &str) { conf.define("PLATFORM", "Desktop") } } - Platform::Web => conf - .define("PLATFORM", "Web") - .define("CMAKE_C_FLAGS", "-s ASYNCIFY"), + Platform::Web => conf.define("PLATFORM", "Web"), Platform::RPI => conf.define("PLATFORM", "Raspberry Pi"), Platform::Android => { // get required env variables @@ -382,21 +380,21 @@ fn main() { println!("cargo:rerun-if-changed=./binding/binding.h"); let target = env::var("TARGET").expect("Cargo build scripts always have TARGET"); - // make sure cmake knows that it should bundle glfw in - if target.contains("wasm") { + if target.contains("wasm32-unknown-emscripten") { if let Err(e) = env::var("EMCC_CFLAGS") { if e == std::env::VarError::NotPresent { - panic!("\nYou must set the following environment variables yourself to compile for WASM. We are sorry for the inconvienence; this will be fixed in 5.1.0.\n{}{}\"\n",{ + panic!("\nYou must have to set EMCC_CFLAGS yourself to compile for WASM.\n{}{}\"\n",{ #[cfg(target_family = "windows")] - {"Paste this before executing the command: set EMCC_CFLAGS="} + {"set EMCC_CFLAGS="} #[cfg(not(target_family = "windows"))] - {"Prefix your command with this (you may want to make a build script for obvious reasons...): EMCC_CFLAGS="} - },"\"-O3 -sUSE_GLFW=3 -sGL_ENABLE_GET_PROC_ADDRESS -sWASM=1 -sALLOW_MEMORY_GROWTH=1 -sWASM_MEM_MAX=512MB -sTOTAL_MEMORY=512MB -sABORTING_MALLOC=0 -sASYNCIFY -sFORCE_FILESYSTEM=1 -sASSERTIONS=1 -sERROR_ON_UNDEFINED_SYMBOLS=0 -sEXPORTED_RUNTIME_METHODS=ccallcwrap\""); + {"export EMCC_CFLAGS="} + },"\"-O3 -sUSE_GLFW=3 -sASSERTIONS=1 -sWASM=1 -sASYNCIFY -sGL_ENABLE_GET_PROC_ADDRESS=1\""); } else { panic!("\nError regarding EMCC_CFLAGS: {:?}\n", e); } } } + let (platform, platform_os) = platform_from_target(&target); let raylib_src = "./raylib"; diff --git a/raylib-sys/raylib b/raylib-sys/raylib index c1ab645c..83587e94 160000 --- a/raylib-sys/raylib +++ b/raylib-sys/raylib @@ -1 +1 @@ -Subproject commit c1ab645ca298a2801097931d1079b10ff7eb9df8 +Subproject commit 83587e94c844c61b455a48d2f8d9ce872ffc92b6 From 181e473537ace62922232965cb2e589dc89dff1a Mon Sep 17 00:00:00 2001 From: IoIxD <30945097+IoIxD@users.noreply.github.com> Date: Mon, 2 Dec 2024 18:07:27 -0700 Subject: [PATCH 50/93] [readme] version bump, remove outdated "future changes" section, moved cross section to wiki. --- README.md | 60 +++---------------------------------------------------- 1 file changed, 3 insertions(+), 57 deletions(-) diff --git a/README.md b/README.md index 3d916597..41056f94 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ # raylib-rs -raylib-rs is a Rust binding for [raylib](http://www.raylib.com/) 5.1. It currently targets Rust toolchain version 1.78 or higher. +raylib-rs is a Rust binding for [raylib](http://www.raylib.com/) 5.5. It currently targets Rust toolchain version 1.78 or higher. Please checkout the showcase directory to find usage examples! @@ -50,7 +50,7 @@ Follow instructions for building raylib for your platform [here](https://github. ```toml [dependencies] -raylib = { version = "5.0" } +raylib = { version = "5.5" } ``` 2. Start coding! @@ -98,53 +98,7 @@ fn main() { ## Cross-compiling using `cross` -The [@rust-embedded](https://github.com/rust-embedded) project provides a handy tool called [`cross`](https://github.com/rust-embedded/cross) that uses docker to cross-compile any cargo project to one of their many [supported platforms](https://github.com/rust-embedded/cross#supported-targets). This tool makes it easy to cross-compile `raylib-rs` for binary distribution (in cases where you are producing a pre-compiled game for example). - -### Anything to Windows - -Cross-compiling from other platforms to Windows is the simplest. Just build your project with this command instead of the usual `cargo build`: - -```sh -cross build --target x86_64-pc-windows-gnu --release -``` - -It should be noted that the resulting exe will likely not run under `wine` due to an issue with Raylib's audio handling. - -### Anything to Linux - -Cross-compiling from any platform to Linux, or from Linux to Linux requires a little extra work since `raylib-sys` has some system dependencies not provided by `cross`. This following example assumes you are compiling for `x86_64-unknown-linux-gnu`, but it can be any Linux-y triple. - -Firstly, a custom build container must be defined. The following `Dockerfile` is the minimum setup for compiling `raylib-sys`: - -```Dockerfile -FROM rustembedded/cross:x86_64-unknown-linux-gnu-0.2.1 - -RUN apt-get update -y -RUN apt-get install libasound2-dev mesa-common-dev libx11-dev libxrandr-dev libxi-dev xorg-dev libgl1-mesa-dev libglu1-mesa-dev -y -``` - -With the image defined, build it locally with: - -```sh -docker build -t raylib_rs_env . -``` - -This will produce a local docker image called `raylib_rs_env` which `cross` will use instead of the default Linux image(s). To tell `cross` to use this image, create a `Cross.toml` file beside your `Cargo.toml`, and add the following (remembering to change things to suit your setup): - -```toml -[target.x86_64-unknown-linux-gnu] -image = "raylib_rs_env" -``` - -The Linux build can now be produced with: - -```sh -cross build --target x86_64-unknown-linux-gnu --release -``` - -# MacOS / Darwin / IOS - -`cross` does not support cross-compilation to any of Apple's operating systems as of now. Keep an eye on their repository in case this ever changes. +Cross compiling with raylib-rs can be made easier with cross. [See more on the wiki](https://github.com/raylib-rs/raylib-rs/wiki/Cross%E2%80%90compiling-using-cross) # Extras @@ -155,14 +109,6 @@ cross build --target x86_64-unknown-linux-gnu --release The raylib-test crate tests the bindings by opening a window, and checking the results of various functions. It requires nightly to use. -# Future Goals - -- Port raylib examples over to Rust. -- More tests. -- More platform testing. -- Even more testing. -- Physac port? - # Contribution & Support All contributions are welcome. Chat about raylib on [discord](https://discord.gg/VkzNHUE) From 64a16f939d165bd62ddd24331ccd2fb683ac1d65 Mon Sep 17 00:00:00 2001 From: IoIxD Date: Tue, 3 Dec 2024 12:22:18 -0700 Subject: [PATCH 51/93] [find_unimplemented] raygui functions --- find_unimplemented.py | 105 ++++++++++++++++++++++++++++++++++-------- 1 file changed, 85 insertions(+), 20 deletions(-) diff --git a/find_unimplemented.py b/find_unimplemented.py index efee25ed..77b724d9 100644 --- a/find_unimplemented.py +++ b/find_unimplemented.py @@ -1,22 +1,87 @@ import os -src = os.scandir("./raylib/src/core/") -src_files = [] - -for file in src: - if file.is_file(follow_symlinks=True): - f = open(file.path) - src_files.append("\n".join(f.readlines())) - -d = open("./raylib-sys/raylib/src/raylib.h") -lines = list(filter(lambda f: f.startswith("RLAPI"),d.readlines())) - -for line in lines: - func_name = list(filter(lambda f: "(" in f, line.split(" ")))[0].split("(")[0].replace("*","") - in_a_file = False - for file in src_files: - if "ffi::"+func_name in file: - in_a_file = True - break - if not in_a_file: - print("- [ ] "+func_name) \ No newline at end of file +# Functions we won't implement. +wont_impl = [ + # We have this implemented in a C file so it's not caught. + "SetTraceLogCallback", + # UTF-8 functions + "GetCodepointNext", + "GetCodepointPrevious", + "CodepointToUTF8", + "LoadUTF8", + "UnloadUTF8", + # Text functions + "TextCopy", + "TextIsEqual", + "TextLength", + "TextFormat", + "TextSubtext", + "TextReplace", + "TextInsert", + "TextJoin", + "TextSplit", + "TextAppend", + "TextFindIndex", + "TextToUpper", + "TextToLower", + "TextToPascal", + "TextToSnake", + "TextToCamel", + "TextToInteger", + "TextToFloat", + # file functions + "LoadFileData", + "UnloadFileData", + "SaveFileData", + "LoadFileText", + "UnloadFileText", + "SaveFileText", + "FileExists", + "DirectoryExists", + "GetFileExtension", + "GetFileName", + "GetFileNameWithoutExt", + "GetDirectoryPath", + "GetPrevDirectoryPath", + "GetWorkingDirectory", + "MakeDirectory", + "ChangeDirectory", + "IsFileNameValid", + "GetFileModTime", + "ComputeCRC32", + "ComputeMD5", + "ComputeSHA1", + # Misc functions that aren't needed. + "MemRealloc", +] + + + +def file_find(lib, src, dest, opener): + print("=====",lib,"=====") + + files = os.scandir(dest) + src_files = [] + + for file in files: + if file.is_file(follow_symlinks=True): + f = open(file.path) + src_files.append("\n".join(f.readlines())) + + d = open(src) + lines = list(filter(lambda f: f.startswith(opener),d.readlines())) + + for line in lines: + func_name = list(filter(lambda f: "(" in f, line.split(" ")))[0].split("(")[0].replace("*","") + + in_a_file = False + for file in src_files: + if func_name in wont_impl or "ffi::"+func_name in file: + in_a_file = True + break + if not in_a_file: + print("- [ ] "+func_name) + print("") + +file_find("Raylib","./raylib-sys/raylib/src/raylib.h", "./raylib/src/core/", "RLAPI") +file_find("Raygui","./raylib-sys/binding/raygui.h","./raylib/src/rgui", " RAYGUIAPI") \ No newline at end of file From 2491aeea79aa4dfac21e960ba2660db2c70b6b19 Mon Sep 17 00:00:00 2001 From: IoIxD Date: Tue, 3 Dec 2024 12:22:55 -0700 Subject: [PATCH 52/93] [raygui] Remove IntoCStr, add a few more functions. --- raylib/src/rgui/safe.rs | 288 ++++++++++++++++++++++++++-------------- 1 file changed, 186 insertions(+), 102 deletions(-) diff --git a/raylib/src/rgui/safe.rs b/raylib/src/rgui/safe.rs index 0c46419d..bdfa685c 100644 --- a/raylib/src/rgui/safe.rs +++ b/raylib/src/rgui/safe.rs @@ -5,32 +5,7 @@ use crate::core::text::WeakFont; use crate::core::RaylibHandle; use crate::ffi; -use std::ffi::CStr; - -pub trait IntoCStr { - fn as_cstr_ptr(&self) -> *const std::os::raw::c_char; -} - -impl IntoCStr for dyn AsRef { - fn as_cstr_ptr(&self) -> *const std::os::raw::c_char { - std::ffi::CString::new(self.as_ref()) - .unwrap() - .as_c_str() - .as_ptr() - } -} - -impl IntoCStr for dyn AsRef { - fn as_cstr_ptr(&self) -> *const std::os::raw::c_char { - self.as_ref().as_ptr() - } -} - -impl IntoCStr for Option<&CStr> { - fn as_cstr_ptr(&self) -> *const std::os::raw::c_char { - self.map(CStr::as_ptr).unwrap_or(std::ptr::null()) - } -} +use std::ffi::{CStr, CString}; /// Global gui modification functions impl RaylibHandle { @@ -94,14 +69,36 @@ impl RaylibHandle { } /// Load style file (.rgs) #[inline] - pub fn gui_load_style(&mut self, filename: impl IntoCStr) { - unsafe { ffi::GuiLoadStyle(filename.as_cstr_ptr()) } + pub fn gui_load_style(&mut self, filename: impl Into) { + let c_filename = CString::new(filename.into()).unwrap(); + unsafe { ffi::GuiLoadStyle(c_filename.as_ptr()) } } /// Load style default over global style #[inline] pub fn gui_load_style_default(&mut self) { unsafe { ffi::GuiLoadStyleDefault() } } + + /// Enable gui tooltips (global state) + #[inline] + pub fn gui_enable_tooltip(&mut self) { + unsafe { ffi::GuiEnableTooltip() }; + } + + /// Disable gui tooltips (global state) + #[inline] + pub fn gui_disable_tooltip(&mut self) { + unsafe { ffi::GuiDisableTooltip() }; + } + + /// Set tooltip string + #[inline] + pub fn gui_set_tooltip(&mut self, tooltip: impl Into) { + let c_text = CString::new(tooltip.into()).unwrap(); + unsafe { + ffi::GuiSetTooltip(c_text.as_ptr()); + } + } } impl RaylibDrawGui for D {} @@ -127,6 +124,13 @@ pub trait RaylibDrawGui { fn gui_unlock(&mut self) { unsafe { ffi::GuiUnlock() } } + + /// Check if gui is locked (global state) + #[inline] + fn gui_is_locked(&mut self) -> bool { + unsafe { ffi::GuiIsLocked() } + } + // Set gui controls alpha (global state), alpha goes from 0.0f to 1.0f #[inline] fn gui_fade(&mut self, color: Color, alpha: f32) -> Color { @@ -159,6 +163,13 @@ pub trait RaylibDrawGui { unsafe { ffi::GuiSetStyle(control as i32, property as i32, value) } } + /// Set gui controls alpha (global state), alpha goes from 0.0f to 1.0f + fn gui_set_alpha(&mut self, alpha: f32) { + unsafe { + ffi::GuiSetAlpha(alpha); + } + } + /// Get one style property /// SHOULD use one of the Gui*Property enums #[inline] @@ -167,8 +178,9 @@ pub trait RaylibDrawGui { } /// Load style file (.rgs) #[inline] - fn gui_load_style(&mut self, filename: impl IntoCStr) { - unsafe { ffi::GuiLoadStyle(filename.as_cstr_ptr()) } + fn gui_load_style(&mut self, filename: impl Into) { + let c_filename = CString::new(filename.into()).unwrap(); + unsafe { ffi::GuiLoadStyle(c_filename.as_ptr()) } } /// Load style default over global style #[inline] @@ -177,40 +189,53 @@ pub trait RaylibDrawGui { } /// Window Box control, shows a window that can be closed #[inline] - fn gui_window_box(&mut self, bounds: impl Into, title: impl IntoCStr) -> bool { - unsafe { ffi::GuiWindowBox(bounds.into(), title.as_cstr_ptr()) > 0 } + fn gui_window_box( + &mut self, + bounds: impl Into, + title: impl Into, + ) -> bool { + let c_filename = CString::new(title.into()).unwrap(); + unsafe { ffi::GuiWindowBox(bounds.into(), c_filename.as_ptr()) > 0 } } /// Group Box control with text name #[inline] - fn gui_group_box(&mut self, bounds: impl Into, text: impl IntoCStr) -> bool { - unsafe { ffi::GuiGroupBox(bounds.into(), text.as_cstr_ptr()) > 0 } + fn gui_group_box( + &mut self, + bounds: impl Into, + text: impl Into, + ) -> bool { + let c_filename = CString::new(text.into()).unwrap(); + unsafe { ffi::GuiGroupBox(bounds.into(), c_filename.as_ptr()) > 0 } } /// Line separator control, could contain text #[inline] - fn gui_line(&mut self, bounds: impl Into, text: impl IntoCStr) -> bool { - unsafe { ffi::GuiLine(bounds.into(), text.as_cstr_ptr()) > 0 } + fn gui_line(&mut self, bounds: impl Into, text: impl Into) -> bool { + let c_filename = CString::new(text.into()).unwrap(); + unsafe { ffi::GuiLine(bounds.into(), c_filename.as_ptr()) > 0 } } /// Panel control, useful to group controls #[inline] - fn gui_panel(&mut self, bounds: impl Into, text: impl IntoCStr) -> bool { - unsafe { ffi::GuiPanel(bounds.into(), text.as_cstr_ptr()) > 0 } + fn gui_panel(&mut self, bounds: impl Into, text: impl Into) -> bool { + let c_filename = CString::new(text.into()).unwrap(); + unsafe { ffi::GuiPanel(bounds.into(), c_filename.as_ptr()) > 0 } } /// Scroll Panel control #[inline] fn gui_scroll_panel( &mut self, bounds: impl Into, - text: impl IntoCStr, + text: impl Into, content: impl Into, scroll: impl Into, view: impl Into, ) -> (bool, Rectangle, Vector2) { let mut scroll = scroll.into(); let mut view = view.into(); + let c_filename = CString::new(text.into()).unwrap(); let result = unsafe { ffi::GuiScrollPanel( bounds.into(), - text.as_cstr_ptr(), + c_filename.as_ptr(), content.into(), &mut scroll, &mut view, @@ -220,86 +245,99 @@ pub trait RaylibDrawGui { } /// Label control, shows text #[inline] - fn gui_label(&mut self, bounds: impl Into, text: impl IntoCStr) -> bool { - unsafe { ffi::GuiLabel(bounds.into(), text.as_cstr_ptr()) > 0 } + fn gui_label(&mut self, bounds: impl Into, text: impl Into) -> bool { + let c_text = CString::new(text.into()).unwrap(); + unsafe { ffi::GuiLabel(bounds.into(), c_text.as_ptr()) > 0 } } /// Button control, returns true when clicked #[inline] - fn gui_button(&mut self, bounds: impl Into, text: impl IntoCStr) -> bool { - unsafe { ffi::GuiButton(bounds.into(), text.as_cstr_ptr()) > 0 } + fn gui_button(&mut self, bounds: impl Into, text: impl Into) -> bool { + let c_text = CString::new(text.into()).unwrap(); + unsafe { ffi::GuiButton(bounds.into(), c_text.as_ptr()) > 0 } } /// Label button control, show true when clicked #[inline] - fn gui_label_button(&mut self, bounds: impl Into, text: impl IntoCStr) -> bool { - unsafe { ffi::GuiLabelButton(bounds.into(), text.as_cstr_ptr()) > 0 } + fn gui_label_button( + &mut self, + bounds: impl Into, + text: impl Into, + ) -> bool { + let c_text = CString::new(text.into()).unwrap(); + unsafe { ffi::GuiLabelButton(bounds.into(), c_text.as_ptr()) > 0 } } /// Toggle Button control, returns true when active #[inline] fn gui_toggle( &mut self, bounds: impl Into, - text: impl IntoCStr, + text: impl Into, active: &mut bool, ) -> bool { - unsafe { ffi::GuiToggle(bounds.into(), text.as_cstr_ptr(), active) > 0 } + let c_text = CString::new(text.into()).unwrap(); + unsafe { ffi::GuiToggle(bounds.into(), c_text.as_ptr(), active) > 0 } } /// Toggle Group control, returns active toggle index #[inline] fn gui_toggle_group( &mut self, bounds: impl Into, - text: impl IntoCStr, + text: impl Into, active: &mut i32, ) -> i32 { - unsafe { ffi::GuiToggleGroup(bounds.into(), text.as_cstr_ptr(), active) } + let c_text = CString::new(text.into()).unwrap(); + unsafe { ffi::GuiToggleGroup(bounds.into(), c_text.as_ptr(), active) } } /// Check Box control, returns true when active #[inline] fn gui_check_box( &mut self, bounds: impl Into, - text: impl IntoCStr, + text: impl Into, checked: &mut bool, ) -> bool { - unsafe { ffi::GuiCheckBox(bounds.into(), text.as_cstr_ptr(), checked) > 0 } + let c_text = CString::new(text.into()).unwrap(); + unsafe { ffi::GuiCheckBox(bounds.into(), c_text.as_ptr(), checked) > 0 } } /// Combo Box control, returns selected item index #[inline] fn gui_combo_box( &mut self, bounds: impl Into, - text: impl IntoCStr, + text: impl Into, active: &mut i32, ) -> i32 { - unsafe { ffi::GuiComboBox(bounds.into(), text.as_cstr_ptr(), active) } + let c_text = CString::new(text.into()).unwrap(); + unsafe { ffi::GuiComboBox(bounds.into(), c_text.as_ptr(), active) } } /// Dropdown Box control, returns selected item #[inline] fn gui_dropdown_box( &mut self, bounds: impl Into, - text: impl IntoCStr, + text: impl Into, active: &mut i32, edit_mode: bool, ) -> bool { - unsafe { ffi::GuiDropdownBox(bounds.into(), text.as_cstr_ptr(), active, edit_mode) > 0 } + let c_text = CString::new(text.into()).unwrap(); + unsafe { ffi::GuiDropdownBox(bounds.into(), c_text.as_ptr(), active, edit_mode) > 0 } } /// Spinner control, returns selected value #[inline] fn gui_spinner( &mut self, bounds: impl Into, - text: impl IntoCStr, + text: impl Into, value: &mut i32, min_value: i32, max_value: i32, edit_mode: bool, ) -> bool { + let c_text = CString::new(text.into()).unwrap(); unsafe { ffi::GuiSpinner( bounds.into(), // text.map(CStr::as_ptr).unwrap_or(crate::rstr!("").as_ptr()), - text.as_cstr_ptr(), + c_text.as_ptr(), value, min_value, max_value, @@ -312,16 +350,17 @@ pub trait RaylibDrawGui { fn gui_value_box( &mut self, bounds: impl Into, - text: impl IntoCStr, + text: impl Into, value: &mut i32, min_value: i32, max_value: i32, edit_mode: bool, ) -> bool { + let c_text = CString::new(text.into()).unwrap(); unsafe { ffi::GuiValueBox( bounds.into(), - text.as_cstr_ptr(), + c_text.as_ptr(), value, min_value, max_value, @@ -355,17 +394,19 @@ pub trait RaylibDrawGui { fn gui_slider( &mut self, bounds: impl Into, - text_left: impl IntoCStr, - text_right: impl IntoCStr, + text_left: impl Into, + text_right: impl Into, value: &mut f32, min_value: f32, max_value: f32, ) -> bool { + let c_text_left = CString::new(text_left.into()).unwrap(); + let c_text_right = CString::new(text_right.into()).unwrap(); unsafe { ffi::GuiSlider( bounds.into(), - text_left.as_cstr_ptr(), - text_right.as_cstr_ptr(), + c_text_left.as_ptr(), + c_text_right.as_ptr(), value, min_value, max_value, @@ -377,17 +418,19 @@ pub trait RaylibDrawGui { fn gui_slider_bar( &mut self, bounds: impl Into, - text_left: impl IntoCStr, - text_right: impl IntoCStr, + text_left: impl Into, + text_right: impl Into, value: &mut f32, min_value: f32, max_value: f32, ) -> bool { + let c_text_left = CString::new(text_left.into()).unwrap(); + let c_text_right = CString::new(text_right.into()).unwrap(); unsafe { ffi::GuiSliderBar( bounds.into(), - text_left.as_cstr_ptr(), - text_right.as_cstr_ptr(), + c_text_left.as_ptr(), + c_text_right.as_ptr(), value, min_value, max_value, @@ -399,17 +442,19 @@ pub trait RaylibDrawGui { fn gui_progress_bar( &mut self, bounds: impl Into, - text_left: impl IntoCStr, - text_right: impl IntoCStr, + text_left: impl Into, + text_right: impl Into, value: &mut f32, min_value: f32, max_value: f32, ) -> bool { + let c_text_left = CString::new(text_left.into()).unwrap(); + let c_text_right = CString::new(text_right.into()).unwrap(); unsafe { ffi::GuiProgressBar( bounds.into(), - text_left.as_cstr_ptr(), - text_right.as_cstr_ptr(), + c_text_left.as_ptr(), + c_text_right.as_ptr(), value, min_value, max_value, @@ -418,29 +463,31 @@ pub trait RaylibDrawGui { } /// Status Bar control, shows info text #[inline] - fn gui_status_bar(&mut self, bounds: impl Into, text: impl IntoCStr) -> bool { - unsafe { ffi::GuiStatusBar(bounds.into(), text.as_cstr_ptr()) > 0 } - } - /// Dummy control for placeholders - #[inline] - fn gui_dummy_rec(&mut self, bounds: impl Into, text: impl IntoCStr) -> bool { - unsafe { ffi::GuiStatusBar(bounds.into(), text.as_cstr_ptr()) > 0 } + fn gui_status_bar( + &mut self, + bounds: impl Into, + text: impl Into, + ) -> bool { + let c_text = CString::new(text.into()).unwrap(); + unsafe { ffi::GuiStatusBar(bounds.into(), c_text.as_ptr()) > 0 } } + /// Grid control #[inline] fn gui_grid( &mut self, bounds: impl Into, - text: impl IntoCStr, + text: impl Into, spacing: f32, subdivs: i32, ) -> (bool, Vector2) { + let c_text = CString::new(text.into()).unwrap(); let mut mouseCell = ffi::Vector2 { x: 0.0, y: 0.0 }; ( unsafe { ffi::GuiGrid( bounds.into(), - text.as_cstr_ptr(), + c_text.as_ptr(), spacing, subdivs, &mut mouseCell, @@ -454,11 +501,12 @@ pub trait RaylibDrawGui { fn gui_list_view( &mut self, bounds: impl Into, - text: impl IntoCStr, + text: impl Into, scroll_index: &mut i32, active: &mut i32, ) -> i32 { - unsafe { ffi::GuiListView(bounds.into(), text.as_cstr_ptr(), scroll_index, active) } + let c_text = CString::new(text.into()).unwrap(); + unsafe { ffi::GuiListView(bounds.into(), c_text.as_ptr(), scroll_index, active) } } /// List View with extended parameters #[inline] @@ -490,16 +538,19 @@ pub trait RaylibDrawGui { fn gui_message_box( &mut self, bounds: impl Into, - text: impl IntoCStr, - message: impl IntoCStr, - buttons: impl IntoCStr, + text: impl Into, + message: impl Into, + buttons: impl Into, ) -> i32 { + let c_text = CString::new(text.into()).unwrap(); + let c_message = CString::new(message.into()).unwrap(); + let c_buttons = CString::new(buttons.into()).unwrap(); unsafe { ffi::GuiMessageBox( bounds.into(), - text.as_cstr_ptr(), - message.as_cstr_ptr(), - buttons.as_cstr_ptr(), + c_text.as_ptr(), + c_message.as_ptr(), + c_buttons.as_ptr(), ) } } @@ -508,21 +559,24 @@ pub trait RaylibDrawGui { fn gui_text_input_box( &mut self, bounds: impl Into, - title: impl IntoCStr, - message: impl IntoCStr, - buttons: impl IntoCStr, + title: impl Into, + message: impl Into, + buttons: impl Into, text: &mut Vec, text_max_size: i32, secret_view_active: &mut bool, ) -> i32 { // rgui.h: line 3699 MAX_FILENAME_LEN text.reserve((256 - text.len()).max(0) as usize); + let c_title = CString::new(title.into()).unwrap(); + let c_message = CString::new(message.into()).unwrap(); + let c_buttons = CString::new(buttons.into()).unwrap(); let btn_index = unsafe { ffi::GuiTextInputBox( bounds.into(), - title.as_cstr_ptr(), - message.as_cstr_ptr(), - buttons.as_cstr_ptr(), + c_title.as_ptr(), + c_message.as_ptr(), + c_buttons.as_ptr(), text.as_mut_ptr() as *mut _, text_max_size, secret_view_active, @@ -537,11 +591,13 @@ pub trait RaylibDrawGui { fn gui_color_picker( &mut self, bounds: impl Into, - text: impl IntoCStr, + text: impl Into, color: impl Into, ) -> Color { let mut out = color.into(); - let result = unsafe { ffi::GuiColorPicker(bounds.into(), text.as_cstr_ptr(), &mut out) }; + let c_text = CString::new(text.into()).unwrap(); + + let result = unsafe { ffi::GuiColorPicker(bounds.into(), c_text.as_ptr(), &mut out) }; return out.into(); } // Get text with icon id prepended @@ -551,11 +607,12 @@ pub trait RaylibDrawGui { fn gui_icon_text( &mut self, icon_id: crate::consts::GuiIconName, - text: impl IntoCStr, + text: impl Into, ) -> String { - let buffer = unsafe { ffi::GuiIconText(icon_id as i32, text.as_cstr_ptr()) }; + let c_text = CString::new(text.into()).unwrap(); + let buffer = unsafe { ffi::GuiIconText(icon_id as i32, c_text.as_ptr()) }; if buffer.is_null() { - let ptr = text.as_cstr_ptr(); + let ptr = c_text.as_ptr(); if ptr.is_null() { return String::default(); } @@ -574,9 +631,36 @@ pub trait RaylibDrawGui { fn gui_color_bar_alpha( &mut self, bounds: impl Into, - text: impl IntoCStr, + text: impl Into, alpha: &mut f32, ) -> bool { - unsafe { ffi::GuiColorBarAlpha(bounds.into(), text.as_cstr_ptr(), alpha) > 0 } + let c_text = CString::new(text.into()).unwrap(); + + unsafe { ffi::GuiColorBarAlpha(bounds.into(), c_text.as_ptr(), alpha) > 0 } + } + + /// Toggle Slider control + #[inline] + fn gui_toggle_slider( + &mut self, + bounds: impl Into, + text: impl Into, + active: &mut i32, + ) -> bool { + let c_text = CString::new(text.into()).unwrap(); + + unsafe { ffi::GuiToggleSlider(bounds.into(), c_text.as_ptr(), active) > 0 } + } + + /// Dummy control for placeholders + #[inline] + fn gui_dummy_rec( + &mut self, + bounds: impl Into, + text: impl Into, + ) -> bool { + let c_text = CString::new(text.into()).unwrap(); + + unsafe { ffi::GuiDummyRec(bounds.into(), c_text.as_ptr()) > 0 } } } From 9446281c2babfcf64e4fe126f2d08f805e1f7c70 Mon Sep 17 00:00:00 2001 From: IoIxD Date: Tue, 3 Dec 2024 12:30:07 -0700 Subject: [PATCH 53/93] [raygui] we can bind GuiColorBarHue safely as it's a pointer to a float --- raylib/src/rgui/safe.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/raylib/src/rgui/safe.rs b/raylib/src/rgui/safe.rs index bdfa685c..e68b6394 100644 --- a/raylib/src/rgui/safe.rs +++ b/raylib/src/rgui/safe.rs @@ -663,4 +663,17 @@ pub trait RaylibDrawGui { unsafe { ffi::GuiDummyRec(bounds.into(), c_text.as_ptr()) > 0 } } + + /// Color Bar Hue control + #[inline] + fn gui_color_bar_hue( + &mut self, + bounds: impl Into, + text: impl Into, + value: &mut f32, + ) -> bool { + let c_text = CString::new(text.into()).unwrap(); + + unsafe { ffi::GuiColorBarHue(bounds.into(), c_text.as_ptr(), value) > 0 } + } } From 7d70bc6bf77b5ab8ece3ece6308d489be70a7aa5 Mon Sep 17 00:00:00 2001 From: IoIxD <30945097+IoIxD@users.noreply.github.com> Date: Fri, 6 Dec 2024 09:50:59 -0700 Subject: [PATCH 54/93] Decouple the callback functions from RaylibHandle, allowing them to used before Raylib is initialized. (#104) * [callbacks] Decouple the callback functions from RaylibHandle, allowing them to used before Raylib is initialized. Fixes #66. * [raylib] accidentally reverted the repo back. * [callbacks] lifetimes --- raylib/src/core/callbacks.rs | 104 ++++++++++++++++++++++++----------- 1 file changed, 73 insertions(+), 31 deletions(-) diff --git a/raylib/src/core/callbacks.rs b/raylib/src/core/callbacks.rs index 88a06ffa..02f509b9 100644 --- a/raylib/src/core/callbacks.rs +++ b/raylib/src/core/callbacks.rs @@ -150,74 +150,116 @@ macro_rules! safe_callback_set_func { }; } +/// Set custom trace log +pub fn set_trace_log_callback<'a>(cb: fn(TraceLogLevel, &str)) -> Result<(), SetLogError<'a>> { + TRACE_LOG_CALLBACK.store(cb as usize, Ordering::Relaxed); + unsafe { ffi::setLogCallbackWrapper() }; + Ok(()) +} +/// Set custom file binary data saver +pub fn set_save_file_data_callback<'a>(cb: fn(&str, &[u8]) -> bool) -> Result<(), SetLogError<'a>> { + safe_callback_set_func!( + cb, + SAVE_FILE_DATA_CALLBACK, + ffi::SetSaveFileDataCallback, + custom_save_file_data_callback, + "save file data" + ) +} +/// Set custom file binary data loader +/// +/// Whatever you return from your callback will be intentionally leaked as Raylib is relied on to free it. +pub fn set_load_file_data_callback<'b>(cb: fn(&str) -> Vec) -> Result<(), SetLogError<'b>> { + safe_callback_set_func!( + cb, + LOAD_FILE_DATA_CALLBACK, + ffi::SetLoadFileDataCallback, + custom_load_file_data_callback, + "load file data" + ) +} +/// Set custom file text data saver +pub fn set_save_file_text_callback<'a>(cb: fn(&str, &str) -> bool) -> Result<(), SetLogError<'a>> { + safe_callback_set_func!( + cb, + SAVE_FILE_TEXT_CALLBACK, + ffi::SetSaveFileTextCallback, + custom_save_file_text_callback, + "load file data" + ) +} +/// Set custom file text data loader +/// +/// Whatever you return from your callback will be intentionally leaked as Raylib is relied on to free it. +pub fn set_load_file_text_callback<'a>(cb: fn(&str) -> String) -> Result<(), SetLogError<'a>> { + safe_callback_set_func!( + cb, + LOAD_FILE_TEXT_CALLBACK, + ffi::SetLoadFileTextCallback, + custom_load_file_text_callback, + "load file text" + ) +} + +/// Audio thread callback to request new data +pub fn set_audio_stream_callback(stream: AudioStream, cb: fn(&[u8])) -> Result<(), SetLogError> { + if AUDIO_STREAM_CALLBACK.load(Ordering::Acquire) == 0 { + AUDIO_STREAM_CALLBACK.store(cb as _, Ordering::Release); + unsafe { ffi::SetAudioStreamCallback(stream.0, Some(custom_audio_stream_callback)) } + Ok(()) + } else { + Err(SetLogError("audio stream")) + } +} + impl RaylibHandle { /// Set custom trace log + #[deprecated = "Decoupled from RaylibHandle. Use [set_trace_log_callback](core::callbacks::set_trace_log_callback) instead."] pub fn set_trace_log_callback( &mut self, cb: fn(TraceLogLevel, &str), ) -> Result<(), SetLogError> { - TRACE_LOG_CALLBACK.store(cb as usize, Ordering::Relaxed); - unsafe { ffi::setLogCallbackWrapper() }; - Ok(()) + set_trace_log_callback(cb) } /// Set custom file binary data saver + #[deprecated = "Decoupled from RaylibHandle. Use [set_save_file_data_callback](core::callbacks::set_save_file_data_callback) instead."] pub fn set_save_file_data_callback( &mut self, cb: fn(&str, &[u8]) -> bool, ) -> Result<(), SetLogError> { - safe_callback_set_func!( - cb, - SAVE_FILE_DATA_CALLBACK, - ffi::SetSaveFileDataCallback, - custom_save_file_data_callback, - "save file data" - ) + set_save_file_data_callback(cb) } /// Set custom file binary data loader /// /// Whatever you return from your callback will be intentionally leaked as Raylib is relied on to free it. + #[deprecated = "Decoupled from RaylibHandle. Use [set_load_file_data_callback](core::callbacks::set_load_file_data_callback) instead."] pub fn set_load_file_data_callback<'b>( &mut self, cb: fn(&str) -> Vec, ) -> Result<(), SetLogError> { - safe_callback_set_func!( - cb, - LOAD_FILE_DATA_CALLBACK, - ffi::SetLoadFileDataCallback, - custom_load_file_data_callback, - "load file data" - ) + set_load_file_data_callback(cb) } /// Set custom file text data saver + #[deprecated = "Decoupled from RaylibHandle. Use [set_save_file_text_callback](core::callbacks::set_save_file_text_callback) instead."] pub fn set_save_file_text_callback( &mut self, cb: fn(&str, &str) -> bool, ) -> Result<(), SetLogError> { - safe_callback_set_func!( - cb, - SAVE_FILE_TEXT_CALLBACK, - ffi::SetSaveFileTextCallback, - custom_save_file_text_callback, - "load file data" - ) + set_save_file_text_callback(cb) } /// Set custom file text data loader /// /// Whatever you return from your callback will be intentionally leaked as Raylib is relied on to free it. + #[deprecated = "Decoupled from RaylibHandle. Use [set_load_file_text_callback](core::callbacks::set_load_file_text_callback) instead."] pub fn set_load_file_text_callback( &mut self, cb: fn(&str) -> String, ) -> Result<(), SetLogError> { - safe_callback_set_func!( - cb, - LOAD_FILE_TEXT_CALLBACK, - ffi::SetLoadFileTextCallback, - custom_load_file_text_callback, - "load file text" - ) + set_load_file_text_callback(cb) } /// Audio thread callback to request new data + #[deprecated = "Decoupled from RaylibHandle. Use [set_audio_stream_callback](core::callbacks::set_audio_stream_callback) instead."] pub fn set_audio_stream_callback( &mut self, stream: AudioStream, From 943b819f8b512c733101a01830d89034c51d27a6 Mon Sep 17 00:00:00 2001 From: sockentrocken Date: Wed, 18 Dec 2024 17:02:54 -0300 Subject: [PATCH 55/93] add new constructor function for Ray (#109) --- raylib/src/core/math.rs | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/raylib/src/core/math.rs b/raylib/src/core/math.rs index 7d90c317..64970ec0 100644 --- a/raylib/src/core/math.rs +++ b/raylib/src/core/math.rs @@ -82,10 +82,7 @@ impl From for ffi::Vector2 { impl From<&Vector2> for ffi::Vector2 { fn from(v: &Vector2) -> ffi::Vector2 { - ffi::Vector2 { - x: v.x, - y: v.y, - } + ffi::Vector2 { x: v.x, y: v.y } } } @@ -424,7 +421,7 @@ impl From for mint::Vector3 { Self { x: v.x, y: v.y, - z: v.z + z: v.z, } } } @@ -1242,7 +1239,11 @@ impl From> for Quaternion { impl From for mint::Quaternion { fn from(q: Quaternion) -> Self { Self { - v: mint::Vector3 { x: q.x, y: q.y, z: q.z }, + v: mint::Vector3 { + x: q.x, + y: q.y, + z: q.z, + }, s: q.w, } } @@ -1900,6 +1901,15 @@ impl From<&Ray> for ffi::Ray { } } +impl Ray { + pub const fn new(position: Vector3, direction: Vector3) -> Self { + Self { + position, + direction, + } + } +} + optional_serde_struct! { pub struct Rectangle { pub x: f32, From b0d1f9a500c027452cb6320aaf0fba69f63d4e33 Mon Sep 17 00:00:00 2001 From: IoIxD <30945097+IoIxD@users.noreply.github.com> Date: Wed, 25 Dec 2024 13:11:57 -0700 Subject: [PATCH 56/93] rlImGui bindings (#107) * [imgui] added imgui * [gitmodules] fix gitmodules * [binding/gitattributes] vendor imgui and raygui * [binding/gitattributes] folders need wildcards when vendored * [binding/gitattributes] got wildcard wrong * [build] include raylib when generating rlImGui bindings to fix ci. * [build] add raylib/src as an include when building rlImGui too. * [raylib/cargo] imgui should not be a default feature * [imgui] remove rlImGuiShutdown, which segfaults. see comment put in its place. * [imgui] work around the deltatime assertion error * [imgui] we do not need the freetype feature enabled for our own code * [imgui] split imgui into a new folder where it is also a blanket trait --- .gitmodules | 4 + raylib-sys/Cargo.toml | 7 + raylib-sys/binding/.gitattributes | 3 + raylib-sys/binding/binding.h | 1 + raylib-sys/binding/imgui/decoy/imgui.h | 11 + raylib-sys/binding/imgui/imconfig.h | 139 ++ raylib-sys/binding/imgui/imgui.h | 3077 ++++++++++++++++++++++++ raylib-sys/binding/rlImGui | 1 + raylib-sys/build.rs | 23 + raylib/Cargo.toml | 3 + raylib/src/core/drawing.rs | 1 + raylib/src/core/mod.rs | 23 +- raylib/src/imgui/mod.rs | 130 + raylib/src/lib.rs | 3 + raylib/src/prelude.rs | 4 +- samples/Cargo.toml | 12 +- samples/imgui.rs | 27 + 17 files changed, 3466 insertions(+), 3 deletions(-) create mode 100644 raylib-sys/binding/.gitattributes create mode 100644 raylib-sys/binding/imgui/decoy/imgui.h create mode 100644 raylib-sys/binding/imgui/imconfig.h create mode 100644 raylib-sys/binding/imgui/imgui.h create mode 160000 raylib-sys/binding/rlImGui create mode 100644 raylib/src/imgui/mod.rs create mode 100644 samples/imgui.rs diff --git a/.gitmodules b/.gitmodules index fa0b22c7..87017aa9 100644 --- a/.gitmodules +++ b/.gitmodules @@ -3,3 +3,7 @@ url = https://github.com/raysan5/raylib commit = "5.5" shallow = true +[submodule "raylib-sys/binding/rlImGui"] + path = raylib-sys/binding/rlImGui + url = https://github.com/raylib-extras/rlImGui/ + commit = "7864355" diff --git a/raylib-sys/Cargo.toml b/raylib-sys/Cargo.toml index c2790608..3b5f5b91 100644 --- a/raylib-sys/Cargo.toml +++ b/raylib-sys/Cargo.toml @@ -11,6 +11,10 @@ categories = ["external-ffi-bindings"] edition = "2018" exclude = ["raylib/examples/*", "raylib/projects/*", "raylib/templates/*"] +[dependencies] +imgui = { version = "0.12.0", optional = true, features = [] } +imgui-sys = { version = "0.12.0", optional = true } + [build-dependencies] cmake = "0.1.51" cc = "1.0" @@ -38,3 +42,6 @@ nogif = [] # config.h's SUPPORT_CUSTOM_FRAME_CONTROL custom_frame_control = [] + +# ImGui support +imgui = ["dep:imgui", "dep:imgui-sys"] diff --git a/raylib-sys/binding/.gitattributes b/raylib-sys/binding/.gitattributes new file mode 100644 index 00000000..d06cd24d --- /dev/null +++ b/raylib-sys/binding/.gitattributes @@ -0,0 +1,3 @@ +rlImGui/** linguist-vendored +imgui/** linguist-vendored +raygui.h linguist-vendored diff --git a/raylib-sys/binding/binding.h b/raylib-sys/binding/binding.h index 265c5e08..37866acf 100644 --- a/raylib-sys/binding/binding.h +++ b/raylib-sys/binding/binding.h @@ -2,6 +2,7 @@ #include "../raylib/src/rlgl.h" #include "utils_log.h" + typedef enum { RAYGUI_ICON_NONE = 0, diff --git a/raylib-sys/binding/imgui/decoy/imgui.h b/raylib-sys/binding/imgui/decoy/imgui.h new file mode 100644 index 00000000..33b243a9 --- /dev/null +++ b/raylib-sys/binding/imgui/decoy/imgui.h @@ -0,0 +1,11 @@ +/* Decoy imgui.h because bindgen can't actually (and shouldn't actually) bind a + * C++ file*/ + +#ifndef IMGUI_DECOY +#define IMGUI_DECOY + +#define IMGUI_IMPL_API +typedef struct ImVec2 ImVec2; +typedef struct ImGuiContext ImGuiContext; + +#endif \ No newline at end of file diff --git a/raylib-sys/binding/imgui/imconfig.h b/raylib-sys/binding/imgui/imconfig.h new file mode 100644 index 00000000..8d13da42 --- /dev/null +++ b/raylib-sys/binding/imgui/imconfig.h @@ -0,0 +1,139 @@ +//----------------------------------------------------------------------------- +// DEAR IMGUI COMPILE-TIME OPTIONS +// Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure. +// You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions. +//----------------------------------------------------------------------------- +// A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/rebased branch with your modifications to it) +// B) or '#define IMGUI_USER_CONFIG "my_imgui_config.h"' in your project and then add directives in your own file without touching this template. +//----------------------------------------------------------------------------- +// You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp +// files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures. +// Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts. +// Call IMGUI_CHECKVERSION() from your .cpp file to verify that the data structures your files are using are matching the ones imgui.cpp is using. +//----------------------------------------------------------------------------- + +#pragma once + +//---- Define assertion handler. Defaults to calling assert(). +// If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement. +//#define IM_ASSERT(_EXPR) MyAssert(_EXPR) +//#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts + +//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows +// Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility. +// - Windows DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() +// for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details. +//#define IMGUI_API __declspec(dllexport) // MSVC Windows: DLL export +//#define IMGUI_API __declspec(dllimport) // MSVC Windows: DLL import +//#define IMGUI_API __attribute__((visibility("default"))) // GCC/Clang: override visibility when set is hidden + +//---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to clean your code of obsolete function/names. +//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +//---- Disable all of Dear ImGui or don't implement standard windows/tools. +// It is very strongly recommended to NOT disable the demo windows and debug tool during development. They are extremely useful in day to day work. Please read comments in imgui_demo.cpp. +//#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty. +//#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty. +//#define IMGUI_DISABLE_DEBUG_TOOLS // Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowIDStackToolWindow() will be empty. + +//---- Don't implement some functions to reduce linkage requirements. +//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a) +//#define IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with Visual Studio] Implement default IME handler (require imm32.lib/.a, auto-link for Visual Studio, -limm32 on command-line for MinGW) +//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't implement default IME handler (won't require imm32.lib/.a) +//#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, IME). +//#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default). +//#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS // Don't implement default platform_io.Platform_OpenInShellFn() handler (Win32: ShellExecute(), require shell32.lib/.a, Mac/Linux: use system("")). +//#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf) +//#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself. +//#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies) +//#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function. +//#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions(). +//#define IMGUI_DISABLE_DEFAULT_FONT // Disable default embedded font (ProggyClean.ttf), remove ~9.5 KB from output binary. AddFontDefault() will assert. +//#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available + +//---- Enable Test Engine / Automation features. +//#define IMGUI_ENABLE_TEST_ENGINE // Enable imgui_test_engine hooks. Generally set automatically by include "imgui_te_config.h", see Test Engine for details. + +//---- Include imgui_user.h at the end of imgui.h as a convenience +// May be convenient for some users to only explicitly include vanilla imgui.h and have extra stuff included. +//#define IMGUI_INCLUDE_IMGUI_USER_H +//#define IMGUI_USER_H_FILENAME "my_folder/my_imgui_user.h" + +//---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another) +//#define IMGUI_USE_BGRA_PACKED_COLOR + +//---- Use 32-bit for ImWchar (default is 16-bit) to support Unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...) +//#define IMGUI_USE_WCHAR32 + +//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version +// By default the embedded implementations are declared static and not available outside of Dear ImGui sources files. +//#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h" +//#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h" +//#define IMGUI_STB_SPRINTF_FILENAME "my_folder/stb_sprintf.h" // only used if IMGUI_USE_STB_SPRINTF is defined. +//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION +//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION +//#define IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION // only disabled if IMGUI_USE_STB_SPRINTF is defined. + +//---- Use stb_sprintf.h for a faster implementation of vsnprintf instead of the one from libc (unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined) +// Compatibility checks of arguments and formats done by clang and GCC will be disabled in order to support the extra formats provided by stb_sprintf.h. +//#define IMGUI_USE_STB_SPRINTF + +//---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui) +// Requires FreeType headers to be available in the include path. Requires program to be compiled with 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided). +// On Windows you may use vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'. +//#define IMGUI_ENABLE_FREETYPE + +//---- Use FreeType + plutosvg or lunasvg to render OpenType SVG fonts (SVGinOT) +// Only works in combination with IMGUI_ENABLE_FREETYPE. +// - lunasvg is currently easier to acquire/install, as e.g. it is part of vcpkg. +// - plutosvg will support more fonts and may load them faster. It currently requires to be built manually but it is fairly easy. See misc/freetype/README for instructions. +// - Both require headers to be available in the include path + program to be linked with the library code (not provided). +// - (note: lunasvg implementation is based on Freetype's rsvg-port.c which is licensed under CeCILL-C Free Software License Agreement) +//#define IMGUI_ENABLE_FREETYPE_PLUTOSVG +//#define IMGUI_ENABLE_FREETYPE_LUNASVG + +//---- Use stb_truetype to build and rasterize the font atlas (default) +// The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend. +//#define IMGUI_ENABLE_STB_TRUETYPE + +//---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4. +// This will be inlined as part of ImVec2 and ImVec4 class declarations. +/* +#define IM_VEC2_CLASS_EXTRA \ + constexpr ImVec2(const MyVec2& f) : x(f.x), y(f.y) {} \ + operator MyVec2() const { return MyVec2(x,y); } + +#define IM_VEC4_CLASS_EXTRA \ + constexpr ImVec4(const MyVec4& f) : x(f.x), y(f.y), z(f.z), w(f.w) {} \ + operator MyVec4() const { return MyVec4(x,y,z,w); } +*/ +//---- ...Or use Dear ImGui's own very basic math operators. +//#define IMGUI_DEFINE_MATH_OPERATORS + +//---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices. +// Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices). +// Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer. +// Read about ImGuiBackendFlags_RendererHasVtxOffset for details. +//#define ImDrawIdx unsigned int + +//---- Override ImDrawCallback signature (will need to modify renderer backends accordingly) +//struct ImDrawList; +//struct ImDrawCmd; +//typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data); +//#define ImDrawCallback MyImDrawCallback + +//---- Debug Tools: Macro to break in Debugger (we provide a default implementation of this in the codebase) +// (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.) +//#define IM_DEBUG_BREAK IM_ASSERT(0) +//#define IM_DEBUG_BREAK __debugbreak() + +//---- Debug Tools: Enable slower asserts +//#define IMGUI_DEBUG_PARANOID + +//---- Tip: You can add extra functions within the ImGui:: namespace from anywhere (e.g. your own sources/header files) +/* +namespace ImGui +{ + void MyFunction(const char* name, MyMatrix44* mtx); +} +*/ \ No newline at end of file diff --git a/raylib-sys/binding/imgui/imgui.h b/raylib-sys/binding/imgui/imgui.h new file mode 100644 index 00000000..1eb4fd49 --- /dev/null +++ b/raylib-sys/binding/imgui/imgui.h @@ -0,0 +1,3077 @@ +// dear imgui, v1.89.2 +// (headers) + +// Help: +// - Read FAQ at http://dearimgui.org/faq +// - Newcomers, read 'Programmer guide' in imgui.cpp for notes on how to setup Dear ImGui in your codebase. +// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that. +// Read imgui.cpp for details, links and comments. + +// Resources: +// - FAQ http://dearimgui.org/faq +// - Homepage & latest https://github.com/ocornut/imgui +// - Releases & changelog https://github.com/ocornut/imgui/releases +// - Gallery https://github.com/ocornut/imgui/issues/5243 (please post your screenshots/video there!) +// - Wiki https://github.com/ocornut/imgui/wiki (lots of good stuff there) +// - Glossary https://github.com/ocornut/imgui/wiki/Glossary +// - Issues & support https://github.com/ocornut/imgui/issues + +// Getting Started? +// - For first-time users having issues compiling/linking/running or issues loading fonts: +// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above. + +// Library Version +// (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM > 12345') +#define IMGUI_VERSION "1.89.2" +#define IMGUI_VERSION_NUM 18920 +#define IMGUI_HAS_TABLE + +/* + +Index of this file: +// [SECTION] Header mess +// [SECTION] Forward declarations and basic types +// [SECTION] Dear ImGui end-user API functions +// [SECTION] Flags & Enumerations +// [SECTION] Helpers: Memory allocations macros, ImVector<> +// [SECTION] ImGuiStyle +// [SECTION] ImGuiIO +// [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) +// [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, ImColor) +// [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData) +// [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont) +// [SECTION] Viewports (ImGuiViewportFlags, ImGuiViewport) +// [SECTION] Platform Dependent Interfaces (ImGuiPlatformImeData) +// [SECTION] Obsolete functions and types + +*/ + +#pragma once + +// Configuration file with compile-time options +// (edit imconfig.h or '#define IMGUI_USER_CONFIG "myfilename.h" from your build system') +#ifdef IMGUI_USER_CONFIG +#include IMGUI_USER_CONFIG +#endif +#include "imconfig.h" + +#ifndef IMGUI_DISABLE + +//----------------------------------------------------------------------------- +// [SECTION] Header mess +//----------------------------------------------------------------------------- + +// Includes +#include // FLT_MIN, FLT_MAX +#include // va_list, va_start, va_end +#include // ptrdiff_t, NULL +#include // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp + +// Define attributes of all API symbols declarations (e.g. for DLL under Windows) +// IMGUI_API is used for core imgui functions, IMGUI_IMPL_API is used for the default backends files (imgui_impl_xxx.h) +// Using dear imgui via a shared library is not recommended, because we don't guarantee backward nor forward ABI compatibility (also function call overhead, as dear imgui is a call-heavy API) +#ifndef IMGUI_API +#define IMGUI_API +#endif +#ifndef IMGUI_IMPL_API +#define IMGUI_IMPL_API IMGUI_API +#endif + +// Helper Macros +#ifndef IM_ASSERT +#include +#define IM_ASSERT(_EXPR) assert(_EXPR) // You can override the default assert handler by editing imconfig.h +#endif +#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR) / sizeof(*(_ARR)))) // Size of a static C-style array. Don't use on pointers! +#define IM_UNUSED(_VAR) ((void)(_VAR)) // Used to silence "unused variable warnings". Often useful as asserts may be stripped out from final builds. +#define IM_OFFSETOF(_TYPE,_MEMBER) offsetof(_TYPE, _MEMBER) // Offset of _MEMBER within _TYPE. Standardized as offsetof() in C++11 +#define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) + +// Helper Macros - IM_FMTARGS, IM_FMTLIST: Apply printf-style warnings to our formatting functions. +#if !defined(IMGUI_USE_STB_SPRINTF) && defined(__MINGW32__) && !defined(__clang__) +#define IM_FMTARGS(FMT) __attribute__((format(gnu_printf, FMT, FMT+1))) +#define IM_FMTLIST(FMT) __attribute__((format(gnu_printf, FMT, 0))) +#elif !defined(IMGUI_USE_STB_SPRINTF) && (defined(__clang__) || defined(__GNUC__)) +#define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1))) +#define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0))) +#else +#define IM_FMTARGS(FMT) +#define IM_FMTLIST(FMT) +#endif + +// Disable some of MSVC most aggressive Debug runtime checks in function header/footer (used in some simple/low-level functions) +#if defined(_MSC_VER) && !defined(__clang__) && !defined(__INTEL_COMPILER) && !defined(IMGUI_DEBUG_PARANOID) +#define IM_MSVC_RUNTIME_CHECKS_OFF __pragma(runtime_checks("",off)) __pragma(check_stack(off)) __pragma(strict_gs_check(push,off)) +#define IM_MSVC_RUNTIME_CHECKS_RESTORE __pragma(runtime_checks("",restore)) __pragma(check_stack()) __pragma(strict_gs_check(pop)) +#else +#define IM_MSVC_RUNTIME_CHECKS_OFF +#define IM_MSVC_RUNTIME_CHECKS_RESTORE +#endif + +// Warnings +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6). +#endif +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" +#if __has_warning("-Wzero-as-null-pointer-constant") +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" +#endif +#elif defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead +#endif + +//----------------------------------------------------------------------------- +// [SECTION] Forward declarations and basic types +//----------------------------------------------------------------------------- + +// Forward declarations +struct ImDrawChannel; // Temporary storage to output draw commands out of order, used by ImDrawListSplitter and ImDrawList::ChannelsSplit() +struct ImDrawCmd; // A single draw command within a parent ImDrawList (generally maps to 1 GPU draw call, unless it is a callback) +struct ImDrawData; // All draw command lists required to render the frame + pos/size coordinates to use for the projection matrix. +struct ImDrawList; // A single draw command list (generally one per window, conceptually you may see this as a dynamic "mesh" builder) +struct ImDrawListSharedData; // Data shared among multiple draw lists (typically owned by parent ImGui context, but you may create one yourself) +struct ImDrawListSplitter; // Helper to split a draw list into different layers which can be drawn into out of order, then flattened back. +struct ImDrawVert; // A single vertex (pos + uv + col = 20 bytes by default. Override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT) +struct ImFont; // Runtime data for a single font within a parent ImFontAtlas +struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader +struct ImFontBuilderIO; // Opaque interface to a font builder (stb_truetype or FreeType). +struct ImFontConfig; // Configuration data when adding a font or merging fonts +struct ImFontGlyph; // A single font glyph (code point + coordinates within in ImFontAtlas + offset) +struct ImFontGlyphRangesBuilder; // Helper to build glyph ranges from text/string data +struct ImColor; // Helper functions to create a color that can be converted to either u32 or float4 (*OBSOLETE* please avoid using) +struct ImGuiContext; // Dear ImGui context (opaque structure, unless including imgui_internal.h) +struct ImGuiIO; // Main configuration and I/O between your application and ImGui +struct ImGuiInputTextCallbackData; // Shared state of InputText() when using custom ImGuiInputTextCallback (rare/advanced use) +struct ImGuiKeyData; // Storage for ImGuiIO and IsKeyDown(), IsKeyPressed() etc functions. +struct ImGuiListClipper; // Helper to manually clip large list of items +struct ImGuiOnceUponAFrame; // Helper for running a block of code not more than once a frame +struct ImGuiPayload; // User data payload for drag and drop operations +struct ImGuiPlatformImeData; // Platform IME data for io.SetPlatformImeDataFn() function. +struct ImGuiSizeCallbackData; // Callback data when using SetNextWindowSizeConstraints() (rare/advanced use) +struct ImGuiStorage; // Helper for key->value storage +struct ImGuiStyle; // Runtime data for styling/colors +struct ImGuiTableSortSpecs; // Sorting specifications for a table (often handling sort specs for a single column, occasionally more) +struct ImGuiTableColumnSortSpecs; // Sorting specification for one column of a table +struct ImGuiTextBuffer; // Helper to hold and append into a text buffer (~string builder) +struct ImGuiTextFilter; // Helper to parse and apply text filters (e.g. "aaaaa[,bbbbb][,ccccc]") +struct ImGuiViewport; // A Platform Window (always only one in 'master' branch), in the future may represent Platform Monitor + +// Enumerations +// - We don't use strongly typed enums much because they add constraints (can't extend in private code, can't store typed in bit fields, extra casting on iteration) +// - Tip: Use your programming IDE navigation facilities on the names in the _central column_ below to find the actual flags/enum lists! +// In Visual Studio IDE: CTRL+comma ("Edit.GoToAll") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. +// With Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols in comments. +enum ImGuiKey : int; // -> enum ImGuiKey // Enum: A key identifier (ImGuiKey_XXX or ImGuiMod_XXX value) +typedef int ImGuiCol; // -> enum ImGuiCol_ // Enum: A color identifier for styling +typedef int ImGuiCond; // -> enum ImGuiCond_ // Enum: A condition for many Set*() functions +typedef int ImGuiDataType; // -> enum ImGuiDataType_ // Enum: A primary data type +typedef int ImGuiDir; // -> enum ImGuiDir_ // Enum: A cardinal direction +typedef int ImGuiMouseButton; // -> enum ImGuiMouseButton_ // Enum: A mouse button identifier (0=left, 1=right, 2=middle) +typedef int ImGuiMouseCursor; // -> enum ImGuiMouseCursor_ // Enum: A mouse cursor shape +typedef int ImGuiSortDirection; // -> enum ImGuiSortDirection_ // Enum: A sorting direction (ascending or descending) +typedef int ImGuiStyleVar; // -> enum ImGuiStyleVar_ // Enum: A variable identifier for styling +typedef int ImGuiTableBgTarget; // -> enum ImGuiTableBgTarget_ // Enum: A color target for TableSetBgColor() + +// Flags (declared as int for compatibility with old C++, to allow using as flags without overhead, and to not pollute the top of this file) +// - Tip: Use your programming IDE navigation facilities on the names in the _central column_ below to find the actual flags/enum lists! +// In Visual Studio IDE: CTRL+comma ("Edit.GoToAll") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. +// With Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols in comments. +typedef int ImDrawFlags; // -> enum ImDrawFlags_ // Flags: for ImDrawList functions +typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList instance +typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas build +typedef int ImGuiBackendFlags; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags +typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for InvisibleButton() +typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit4(), ColorPicker4() etc. +typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags +typedef int ImGuiComboFlags; // -> enum ImGuiComboFlags_ // Flags: for BeginCombo() +typedef int ImGuiDragDropFlags; // -> enum ImGuiDragDropFlags_ // Flags: for BeginDragDropSource(), AcceptDragDropPayload() +typedef int ImGuiFocusedFlags; // -> enum ImGuiFocusedFlags_ // Flags: for IsWindowFocused() +typedef int ImGuiHoveredFlags; // -> enum ImGuiHoveredFlags_ // Flags: for IsItemHovered(), IsWindowHovered() etc. +typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: for InputText(), InputTextMultiline() +typedef int ImGuiKeyChord; // -> ImGuiKey | ImGuiMod_XXX // Flags: for storage only for now: an ImGuiKey optionally OR-ed with one or more ImGuiMod_XXX values. +typedef int ImGuiPopupFlags; // -> enum ImGuiPopupFlags_ // Flags: for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() +typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable() +typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. +typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: for BeginTabBar() +typedef int ImGuiTabItemFlags; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem() +typedef int ImGuiTableFlags; // -> enum ImGuiTableFlags_ // Flags: For BeginTable() +typedef int ImGuiTableColumnFlags; // -> enum ImGuiTableColumnFlags_// Flags: For TableSetupColumn() +typedef int ImGuiTableRowFlags; // -> enum ImGuiTableRowFlags_ // Flags: For TableNextRow() +typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode(), TreeNodeEx(), CollapsingHeader() +typedef int ImGuiViewportFlags; // -> enum ImGuiViewportFlags_ // Flags: for ImGuiViewport +typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: for Begin(), BeginChild() + +// ImTexture: user data for renderer backend to identify a texture [Compile-time configurable type] +// - To use something else than an opaque void* pointer: override with e.g. '#define ImTextureID MyTextureType*' in your imconfig.h file. +// - This can be whatever to you want it to be! read the FAQ about ImTextureID for details. +#ifndef ImTextureID +typedef void* ImTextureID; // Default: store a pointer or an integer fitting in a pointer (most renderer backends are ok with that) +#endif + +// ImDrawIdx: vertex index. [Compile-time configurable type] +// - To use 16-bit indices + allow large meshes: backend need to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset (recommended). +// - To use 32-bit indices: override with '#define ImDrawIdx unsigned int' in your imconfig.h file. +#ifndef ImDrawIdx +typedef unsigned short ImDrawIdx; // Default: 16-bit (for maximum compatibility with renderer backends) +#endif + +// Scalar data types +typedef unsigned int ImGuiID;// A unique ID used by widgets (typically the result of hashing a stack of string) +typedef signed char ImS8; // 8-bit signed integer +typedef unsigned char ImU8; // 8-bit unsigned integer +typedef signed short ImS16; // 16-bit signed integer +typedef unsigned short ImU16; // 16-bit unsigned integer +typedef signed int ImS32; // 32-bit signed integer == int +typedef unsigned int ImU32; // 32-bit unsigned integer (often used to store packed colors) +typedef signed long long ImS64; // 64-bit signed integer +typedef unsigned long long ImU64; // 64-bit unsigned integer + +// Character types +// (we generally use UTF-8 encoded string in the API. This is storage specifically for a decoded character used for keyboard input and display) +typedef unsigned short ImWchar16; // A single decoded U16 character/code point. We encode them as multi bytes UTF-8 when used in strings. +typedef unsigned int ImWchar32; // A single decoded U32 character/code point. We encode them as multi bytes UTF-8 when used in strings. +#ifdef IMGUI_USE_WCHAR32 // ImWchar [configurable type: override in imconfig.h with '#define IMGUI_USE_WCHAR32' to support Unicode planes 1-16] +typedef ImWchar32 ImWchar; +#else +typedef ImWchar16 ImWchar; +#endif + +// Callback and functions types +typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData* data); // Callback function for ImGui::InputText() +typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data); // Callback function for ImGui::SetNextWindowSizeConstraints() +typedef void* (*ImGuiMemAllocFunc)(size_t sz, void* user_data); // Function signature for ImGui::SetAllocatorFunctions() +typedef void (*ImGuiMemFreeFunc)(void* ptr, void* user_data); // Function signature for ImGui::SetAllocatorFunctions() + +// ImVec2: 2D vector used to store positions, sizes etc. [Compile-time configurable type] +// This is a frequently used type in the API. Consider using IM_VEC2_CLASS_EXTRA to create implicit cast from/to our preferred type. +IM_MSVC_RUNTIME_CHECKS_OFF +struct ImVec2 +{ + float x, y; + constexpr ImVec2() : x(0.0f), y(0.0f) { } + constexpr ImVec2(float _x, float _y) : x(_x), y(_y) { } + float operator[] (size_t idx) const { IM_ASSERT(idx == 0 || idx == 1); return (&x)[idx]; } // We very rarely use this [] operator, the assert overhead is fine. + float& operator[] (size_t idx) { IM_ASSERT(idx == 0 || idx == 1); return (&x)[idx]; } // We very rarely use this [] operator, the assert overhead is fine. +#ifdef IM_VEC2_CLASS_EXTRA + IM_VEC2_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec2. +#endif +}; + +// ImVec4: 4D vector used to store clipping rectangles, colors etc. [Compile-time configurable type] +struct ImVec4 +{ + float x, y, z, w; + constexpr ImVec4() : x(0.0f), y(0.0f), z(0.0f), w(0.0f) { } + constexpr ImVec4(float _x, float _y, float _z, float _w) : x(_x), y(_y), z(_z), w(_w) { } +#ifdef IM_VEC4_CLASS_EXTRA + IM_VEC4_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec4. +#endif +}; +IM_MSVC_RUNTIME_CHECKS_RESTORE + +//----------------------------------------------------------------------------- +// [SECTION] Dear ImGui end-user API functions +// (Note that ImGui:: being a namespace, you can add extra ImGui:: functions in your own separate file. Please don't modify imgui source files!) +//----------------------------------------------------------------------------- + +namespace ImGui +{ + // Context creation and access + // - Each context create its own ImFontAtlas by default. You may instance one yourself and pass it to CreateContext() to share a font atlas between contexts. + // - DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() + // for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for details. + IMGUI_API ImGuiContext* CreateContext(ImFontAtlas* shared_font_atlas = NULL); + IMGUI_API void DestroyContext(ImGuiContext* ctx = NULL); // NULL = destroy current context + IMGUI_API ImGuiContext* GetCurrentContext(); + IMGUI_API void SetCurrentContext(ImGuiContext* ctx); + + // Main + IMGUI_API ImGuiIO& GetIO(); // access the IO structure (mouse/keyboard/gamepad inputs, time, various configuration options/flags) + IMGUI_API ImGuiStyle& GetStyle(); // access the Style structure (colors, sizes). Always use PushStyleCol(), PushStyleVar() to modify style mid-frame! + IMGUI_API void NewFrame(); // start a new Dear ImGui frame, you can submit any command from this point until Render()/EndFrame(). + IMGUI_API void EndFrame(); // ends the Dear ImGui frame. automatically called by Render(). If you don't need to render data (skipping rendering) you may call EndFrame() without Render()... but you'll have wasted CPU already! If you don't need to render, better to not create any windows and not call NewFrame() at all! + IMGUI_API void Render(); // ends the Dear ImGui frame, finalize the draw data. You can then get call GetDrawData(). + IMGUI_API ImDrawData* GetDrawData(); // valid after Render() and until the next call to NewFrame(). this is what you have to render. + + // Demo, Debug, Information + IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create Demo window. demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application! + IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create Metrics/Debugger window. display Dear ImGui internals: windows, draw commands, various internal state, etc. + IMGUI_API void ShowDebugLogWindow(bool* p_open = NULL); // create Debug Log window. display a simplified log of important dear imgui events. + IMGUI_API void ShowStackToolWindow(bool* p_open = NULL); // create Stack Tool window. hover items with mouse to query information about the source of their unique ID. + IMGUI_API void ShowAboutWindow(bool* p_open = NULL); // create About window. display Dear ImGui version, credits and build/system information. + IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // add style editor block (not a window). you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style) + IMGUI_API bool ShowStyleSelector(const char* label); // add style selector block (not a window), essentially a combo listing the default styles. + IMGUI_API void ShowFontSelector(const char* label); // add font selector block (not a window), essentially a combo listing the loaded fonts. + IMGUI_API void ShowUserGuide(); // add basic help/info block (not a window): how to manipulate ImGui as an end-user (mouse/keyboard controls). + IMGUI_API const char* GetVersion(); // get the compiled version string e.g. "1.80 WIP" (essentially the value for IMGUI_VERSION from the compiled version of imgui.cpp) + + // Styles + IMGUI_API void StyleColorsDark(ImGuiStyle* dst = NULL); // new, recommended style (default) + IMGUI_API void StyleColorsLight(ImGuiStyle* dst = NULL); // best used with borders and a custom, thicker font + IMGUI_API void StyleColorsClassic(ImGuiStyle* dst = NULL); // classic imgui style + + // Windows + // - Begin() = push window to the stack and start appending to it. End() = pop window from the stack. + // - Passing 'bool* p_open != NULL' shows a window-closing widget in the upper-right corner of the window, + // which clicking will set the boolean to false when clicked. + // - You may append multiple times to the same window during the same frame by calling Begin()/End() pairs multiple times. + // Some information such as 'flags' or 'p_open' will only be considered by the first call to Begin(). + // - Begin() return false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting + // anything to the window. Always call a matching End() for each Begin() call, regardless of its return value! + // [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu, + // BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function + // returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.] + // - Note that the bottom of window stack always contains a window called "Debug". + IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); + IMGUI_API void End(); + + // Child Windows + // - Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window. Child windows can embed their own child. + // - For each independent axis of 'size': ==0.0f: use remaining host window size / >0.0f: fixed size / <0.0f: use remaining window size minus abs(size) / Each axis can use a different mode, e.g. ImVec2(0,400). + // - BeginChild() returns false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting anything to the window. + // Always call a matching EndChild() for each BeginChild() call, regardless of its return value. + // [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu, + // BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function + // returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.] + IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags flags = 0); + IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags flags = 0); + IMGUI_API void EndChild(); + + // Windows Utilities + // - 'current window' = the window we are appending into while inside a Begin()/End() block. 'next window' = next window we will Begin() into. + IMGUI_API bool IsWindowAppearing(); + IMGUI_API bool IsWindowCollapsed(); + IMGUI_API bool IsWindowFocused(ImGuiFocusedFlags flags=0); // is current window focused? or its root/child, depending on flags. see flags for options. + IMGUI_API bool IsWindowHovered(ImGuiHoveredFlags flags=0); // is current window hovered (and typically: not blocked by a popup/modal)? see flags for options. NB: If you are trying to check whether your mouse should be dispatched to imgui or to your app, you should use the 'io.WantCaptureMouse' boolean for that! Please read the FAQ! + IMGUI_API ImDrawList* GetWindowDrawList(); // get draw list associated to the current window, to append your own drawing primitives + IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (useful if you want to do your own drawing via the DrawList API) + IMGUI_API ImVec2 GetWindowSize(); // get current window size + IMGUI_API float GetWindowWidth(); // get current window width (shortcut for GetWindowSize().x) + IMGUI_API float GetWindowHeight(); // get current window height (shortcut for GetWindowSize().y) + + // Window manipulation + // - Prefer using SetNextXXX functions (before Begin) rather that SetXXX functions (after Begin). + IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiCond cond = 0, const ImVec2& pivot = ImVec2(0, 0)); // set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc. + IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin() + IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Sizes will be rounded down. Use callback to apply non-trivial programmatic constraints. + IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (~ scrollable client area, which enforce the range of scrollbars). Not including window decorations (title bar, menu bar, etc.) nor WindowPadding. set an axis to 0.0f to leave it automatic. call before Begin() + IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // set next window collapsed state. call before Begin() + IMGUI_API void SetNextWindowFocus(); // set next window to be focused / top-most. call before Begin() + IMGUI_API void SetNextWindowScroll(const ImVec2& scroll); // set next window scrolling value (use < 0.0f to not affect a given axis). + IMGUI_API void SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily override the Alpha component of ImGuiCol_WindowBg/ChildBg/PopupBg. you may also use ImGuiWindowFlags_NoBackground. + IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects. + IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0, 0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects. + IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed(). + IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / top-most. prefer using SetNextWindowFocus(). + IMGUI_API void SetWindowFontScale(float scale); // [OBSOLETE] set font scale. Adjust IO.FontGlobalScale if you want to scale all windows. This is an old API! For correct scaling, prefer to reload font + rebuild ImFontAtlas + call style.ScaleAllSizes(). + IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond = 0); // set named window position. + IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis. + IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond = 0); // set named window collapsed state + IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / top-most. use NULL to remove focus. + + // Content region + // - Retrieve available space from a given point. GetContentRegionAvail() is frequently useful. + // - Those functions are bound to be redesigned (they are confusing, incomplete and the Min/Max return values are in local window coordinates which increases confusion) + IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos() + IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates + IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min for the full window (roughly (0,0)-Scroll), in window coordinates + IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max for the full window (roughly (0,0)+Size-Scroll) where Size can be overridden with SetNextWindowContentSize(), in window coordinates + + // Windows Scrolling + // - Any change of Scroll will be applied at the beginning of next frame in the first call to Begin(). + // - You may instead use SetNextWindowScroll() prior to calling Begin() to avoid this delay, as an alternative to using SetScrollX()/SetScrollY(). + IMGUI_API float GetScrollX(); // get scrolling amount [0 .. GetScrollMaxX()] + IMGUI_API float GetScrollY(); // get scrolling amount [0 .. GetScrollMaxY()] + IMGUI_API void SetScrollX(float scroll_x); // set scrolling amount [0 .. GetScrollMaxX()] + IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0 .. GetScrollMaxY()] + IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.x - WindowSize.x - DecorationsSize.x + IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.y - WindowSize.y - DecorationsSize.y + IMGUI_API void SetScrollHereX(float center_x_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_x_ratio=0.0: left, 0.5: center, 1.0: right. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead. + IMGUI_API void SetScrollHereY(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead. + IMGUI_API void SetScrollFromPosX(float local_x, float center_x_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position. + IMGUI_API void SetScrollFromPosY(float local_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position. + + // Parameters stacks (shared) + IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font + IMGUI_API void PopFont(); + IMGUI_API void PushStyleColor(ImGuiCol idx, ImU32 col); // modify a style color. always use this if you modify the style after NewFrame(). + IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col); + IMGUI_API void PopStyleColor(int count = 1); + IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); // modify a style float variable. always use this if you modify the style after NewFrame(). + IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); // modify a style ImVec2 variable. always use this if you modify the style after NewFrame(). + IMGUI_API void PopStyleVar(int count = 1); + IMGUI_API void PushAllowKeyboardFocus(bool allow_keyboard_focus); // == tab stop enable. Allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets + IMGUI_API void PopAllowKeyboardFocus(); + IMGUI_API void PushButtonRepeat(bool repeat); // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (using io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame. + IMGUI_API void PopButtonRepeat(); + + // Parameters stacks (current window) + IMGUI_API void PushItemWidth(float item_width); // push width of items for common large "item+label" widgets. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side). + IMGUI_API void PopItemWidth(); + IMGUI_API void SetNextItemWidth(float item_width); // set width of the _next_ common large "item+label" widget. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side) + IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position. NOT necessarily the width of last item unlike most 'Item' functions. + IMGUI_API void PushTextWrapPos(float wrap_local_pos_x = 0.0f); // push word-wrapping position for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space + IMGUI_API void PopTextWrapPos(); + + // Style read access + // - Use the ShowStyleEditor() function to interactively see/edit the colors. + IMGUI_API ImFont* GetFont(); // get current font + IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied + IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API + IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier, packed as a 32-bit value suitable for ImDrawList + IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList + IMGUI_API ImU32 GetColorU32(ImU32 col); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList + IMGUI_API const ImVec4& GetStyleColorVec4(ImGuiCol idx); // retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwise use GetColorU32() to get style color with style alpha baked in. + + // Cursor / Layout + // - By "cursor" we mean the current output position. + // - The typical widget behavior is to output themselves at the current cursor position, then move the cursor one line down. + // - You can call SameLine() between widgets to undo the last carriage return and output at the right of the preceding widget. + // - Attention! We currently have inconsistencies between window-local and absolute positions we will aim to fix with future API: + // Window-local coordinates: SameLine(), GetCursorPos(), SetCursorPos(), GetCursorStartPos(), GetContentRegionMax(), GetWindowContentRegion*(), PushTextWrapPos() + // Absolute coordinate: GetCursorScreenPos(), SetCursorScreenPos(), all ImDrawList:: functions. + IMGUI_API void Separator(); // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator. + IMGUI_API void SameLine(float offset_from_start_x=0.0f, float spacing=-1.0f); // call between widgets or groups to layout them horizontally. X position given in window coordinates. + IMGUI_API void NewLine(); // undo a SameLine() or force a new line when in a horizontal-layout context. + IMGUI_API void Spacing(); // add vertical spacing. + IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size. unlike InvisibleButton(), Dummy() won't take the mouse click or be navigable into. + IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by indent_w, or style.IndentSpacing if indent_w <= 0 + IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by indent_w, or style.IndentSpacing if indent_w <= 0 + IMGUI_API void BeginGroup(); // lock horizontal starting position + IMGUI_API void EndGroup(); // unlock horizontal starting position + capture the whole group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) + IMGUI_API ImVec2 GetCursorPos(); // cursor position in window coordinates (relative to window position) + IMGUI_API float GetCursorPosX(); // (some functions are using window-relative coordinates, such as: GetCursorPos, GetCursorStartPos, GetContentRegionMax, GetWindowContentRegion* etc. + IMGUI_API float GetCursorPosY(); // other functions such as GetCursorScreenPos or everything in ImDrawList:: + IMGUI_API void SetCursorPos(const ImVec2& local_pos); // are using the main, absolute coordinate system. + IMGUI_API void SetCursorPosX(float local_x); // GetWindowPos() + GetCursorPos() == GetCursorScreenPos() etc.) + IMGUI_API void SetCursorPosY(float local_y); // + IMGUI_API ImVec2 GetCursorStartPos(); // initial cursor position in window coordinates + IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute coordinates (useful to work with ImDrawList API). generally top-left == GetMainViewport()->Pos == (0,0) in single viewport mode, and bottom-right == GetMainViewport()->Pos+Size == io.DisplaySize in single-viewport mode. + IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position in absolute coordinates + IMGUI_API void AlignTextToFramePadding(); // vertically align upcoming text baseline to FramePadding.y so that it will align properly to regularly framed items (call if you have text on a line before a framed item) + IMGUI_API float GetTextLineHeight(); // ~ FontSize + IMGUI_API float GetTextLineHeightWithSpacing(); // ~ FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text) + IMGUI_API float GetFrameHeight(); // ~ FontSize + style.FramePadding.y * 2 + IMGUI_API float GetFrameHeightWithSpacing(); // ~ FontSize + style.FramePadding.y * 2 + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of framed widgets) + + // ID stack/scopes + // Read the FAQ (docs/FAQ.md or http://dearimgui.org/faq) for more details about how ID are handled in dear imgui. + // - Those questions are answered and impacted by understanding of the ID stack system: + // - "Q: Why is my widget not reacting when I click on it?" + // - "Q: How can I have widgets with an empty label?" + // - "Q: How can I have multiple widgets with the same label?" + // - Short version: ID are hashes of the entire ID stack. If you are creating widgets in a loop you most likely + // want to push a unique identifier (e.g. object pointer, loop index) to uniquely differentiate them. + // - You can also use the "Label##foobar" syntax within widget label to distinguish them from each others. + // - In this header file we use the "label"/"name" terminology to denote a string that will be displayed + used as an ID, + // whereas "str_id" denote a string that is only used as an ID and not normally displayed. + IMGUI_API void PushID(const char* str_id); // push string into the ID stack (will hash string). + IMGUI_API void PushID(const char* str_id_begin, const char* str_id_end); // push string into the ID stack (will hash string). + IMGUI_API void PushID(const void* ptr_id); // push pointer into the ID stack (will hash pointer). + IMGUI_API void PushID(int int_id); // push integer into the ID stack (will hash integer). + IMGUI_API void PopID(); // pop from the ID stack. + IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage yourself + IMGUI_API ImGuiID GetID(const char* str_id_begin, const char* str_id_end); + IMGUI_API ImGuiID GetID(const void* ptr_id); + + // Widgets: Text + IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // raw text without formatting. Roughly equivalent to Text("%s", text) but: A) doesn't require null terminated string if 'text_end' is specified, B) it's faster, no memory copy is done, no buffer size limits, recommended for long chunks of text. + IMGUI_API void Text(const char* fmt, ...) IM_FMTARGS(1); // formatted text + IMGUI_API void TextV(const char* fmt, va_list args) IM_FMTLIST(1); + IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_FMTARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor(); + IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API void TextDisabled(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor(); + IMGUI_API void TextDisabledV(const char* fmt, va_list args) IM_FMTLIST(1); + IMGUI_API void TextWrapped(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize(). + IMGUI_API void TextWrappedV(const char* fmt, va_list args) IM_FMTLIST(1); + IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_FMTARGS(2); // display text+label aligned the same way as value+label widgets + IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API void BulletText(const char* fmt, ...) IM_FMTARGS(1); // shortcut for Bullet()+Text() + IMGUI_API void BulletTextV(const char* fmt, va_list args) IM_FMTLIST(1); + + // Widgets: Main + // - Most widgets return true when the value has been changed or when pressed/selected + // - You may also use one of the many IsItemXXX functions (e.g. IsItemActive, IsItemHovered, etc.) to query widget state. + IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0, 0)); // button + IMGUI_API bool SmallButton(const char* label); // button with FramePadding=(0,0) to easily embed within text + IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size, ImGuiButtonFlags flags = 0); // flexible button behavior without the visuals, frequently useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.) + IMGUI_API bool ArrowButton(const char* str_id, ImGuiDir dir); // square button with an arrow shape + IMGUI_API bool Checkbox(const char* label, bool* v); + IMGUI_API bool CheckboxFlags(const char* label, int* flags, int flags_value); + IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value); + IMGUI_API bool RadioButton(const char* label, bool active); // use with e.g. if (RadioButton("one", my_value==1)) { my_value = 1; } + IMGUI_API bool RadioButton(const char* label, int* v, int v_button); // shortcut to handle the above pattern when value is an integer + IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-FLT_MIN, 0), const char* overlay = NULL); + IMGUI_API void Bullet(); // draw a small circle + keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses + + // Widgets: Images + // - Read about ImTextureID here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples + IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& tint_col = ImVec4(1, 1, 1, 1), const ImVec4& border_col = ImVec4(0, 0, 0, 0)); + IMGUI_API bool ImageButton(const char* str_id, ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); + + // Widgets: Combo Box (Dropdown) + // - The BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items. + // - The old Combo() api are helpers over BeginCombo()/EndCombo() which are kept available for convenience purpose. This is analogous to how ListBox are created. + IMGUI_API bool BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags = 0); + IMGUI_API void EndCombo(); // only call EndCombo() if BeginCombo() returns true! + IMGUI_API bool Combo(const char* label, int* current_item, const char* const items[], int items_count, int popup_max_height_in_items = -1); + IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items = -1); // Separate items with \0 within a string, end item-list with \0\0. e.g. "One\0Two\0Three\0" + IMGUI_API bool Combo(const char* label, int* current_item, bool(*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int popup_max_height_in_items = -1); + + // Widgets: Drag Sliders + // - CTRL+Click on any drag box to turn them into an input box. Manually input values aren't clamped by default and can go off-bounds. Use ImGuiSliderFlags_AlwaysClamp to always clamp. + // - For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every function, note that a 'float v[X]' function argument is the same as 'float* v', + // the array syntax is just a way to document the number of elements that are expected to be accessible. You can pass address of your first element out of a contiguous set, e.g. &myvector.x + // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. + // - Format string may also be set to NULL or use the default format ("%f" or "%d"). + // - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision). + // - Use v_min < v_max to clamp edits to given limits. Note that CTRL+Click manual input can override those limits if ImGuiSliderFlags_AlwaysClamp is not used. + // - Use v_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum. + // - We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them. + // - Legacy: Pre-1.78 there are DragXXX() function signatures that take a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument. + // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361 + IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound + IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound + IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed = 1.0f, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed = 1.0f, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0); + + // Widgets: Regular Sliders + // - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped by default and can go off-bounds. Use ImGuiSliderFlags_AlwaysClamp to always clamp. + // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. + // - Format string may also be set to NULL or use the default format ("%f" or "%d"). + // - Legacy: Pre-1.78 there are SliderXXX() function signatures that take a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument. + // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361 + IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. + IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); + + // Widgets: Input with Keyboard + // - If you want to use InputText() with std::string or any custom dynamic string type, see misc/cpp/imgui_stdlib.h and comments in imgui_demo.cpp. + // - Most of the ImGuiInputTextFlags flags are only useful for InputText() and not for InputFloatX, InputIntX, InputDouble etc. + IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, const char* format = "%.3f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputFloat2(const char* label, float v[2], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputFloat3(const char* label, float v[3], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputFloat4(const char* label, float v[4], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputInt(const char* label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputDouble(const char* label, double* v, double step = 0.0, double step_fast = 0.0, const char* format = "%.6f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0); + + // Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little color square that can be left-clicked to open a picker, and right-clicked to open an option menu.) + // - Note that in C++ a 'float v[X]' function argument is the _same_ as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. + // - You can pass the address of a first float element out of a contiguous structure, e.g. &myvector.x + IMGUI_API bool ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); + IMGUI_API bool ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0); + IMGUI_API bool ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); + IMGUI_API bool ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags = 0, const float* ref_col = NULL); + IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // display a color square/button, hover for details, return true when pressed. + IMGUI_API void SetColorEditOptions(ImGuiColorEditFlags flags); // initialize current options (generally on application startup) if you want to select a default format, picker type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls. + + // Widgets: Trees + // - TreeNode functions return true when the node is open, in which case you need to also call TreePop() when you are finished displaying the tree node contents. + IMGUI_API bool TreeNode(const char* label); + IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_FMTARGS(2); // helper variation to easily decorelate the id from the displayed string. Read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet(). + IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_FMTARGS(2); // " + IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0); + IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); + IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); + IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); + IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); + IMGUI_API void TreePush(const char* str_id); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call TreePush/TreePop yourself if desired. + IMGUI_API void TreePush(const void* ptr_id); // " + IMGUI_API void TreePop(); // ~ Unindent()+PopId() + IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode + IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop(). + IMGUI_API bool CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags = 0); // when 'p_visible != NULL': if '*p_visible==true' display an additional small close button on upper right of the header which will set the bool to false when clicked, if '*p_visible==false' don't display the header. + IMGUI_API void SetNextItemOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state. + + // Widgets: Selectables + // - A selectable highlights when hovered, and can display another color when selected. + // - Neighbors selectable extend their highlight bounds in order to leave no gap between them. This is so a series of selected Selectable appear contiguous. + IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height + IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool* p_selected" point to the selection state (read-write), as a convenient helper. + + // Widgets: List Boxes + // - This is essentially a thin wrapper to using BeginChild/EndChild with some stylistic changes. + // - The BeginListBox()/EndListBox() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() or any items. + // - The simplified/old ListBox() api are helpers over BeginListBox()/EndListBox() which are kept available for convenience purpose. This is analoguous to how Combos are created. + // - Choose frame width: size.x > 0.0f: custom / size.x < 0.0f or -FLT_MIN: right-align / size.x = 0.0f (default): use current ItemWidth + // - Choose frame height: size.y > 0.0f: custom / size.y < 0.0f or -FLT_MIN: bottom-align / size.y = 0.0f (default): arbitrary default height which can fit ~7 items + IMGUI_API bool BeginListBox(const char* label, const ImVec2& size = ImVec2(0, 0)); // open a framed scrolling region + IMGUI_API void EndListBox(); // only call EndListBox() if BeginListBox() returned true! + IMGUI_API bool ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items = -1); + IMGUI_API bool ListBox(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1); + + // Widgets: Data Plotting + // - Consider using ImPlot (https://github.com/epezent/implot) which is much better! + IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float)); + IMGUI_API void PlotLines(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0)); + IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float)); + IMGUI_API void PlotHistogram(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0)); + + // Widgets: Value() Helpers. + // - Those are merely shortcut to calling Text() with a format string. Output single value in "name: value" format (tip: freely declare more in your code to handle your types. you can add functions to the ImGui namespace) + IMGUI_API void Value(const char* prefix, bool b); + IMGUI_API void Value(const char* prefix, int v); + IMGUI_API void Value(const char* prefix, unsigned int v); + IMGUI_API void Value(const char* prefix, float v, const char* float_format = NULL); + + // Widgets: Menus + // - Use BeginMenuBar() on a window ImGuiWindowFlags_MenuBar to append to its menu bar. + // - Use BeginMainMenuBar() to create a menu bar at the top of the screen and append to it. + // - Use BeginMenu() to create a menu. You can call BeginMenu() multiple time with the same identifier to append more items to it. + // - Not that MenuItem() keyboardshortcuts are displayed as a convenience but _not processed_ by Dear ImGui at the moment. + IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set on parent window). + IMGUI_API void EndMenuBar(); // only call EndMenuBar() if BeginMenuBar() returns true! + IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar. + IMGUI_API void EndMainMenuBar(); // only call EndMainMenuBar() if BeginMainMenuBar() returns true! + IMGUI_API bool BeginMenu(const char* label, bool enabled = true); // create a sub-menu entry. only call EndMenu() if this returns true! + IMGUI_API void EndMenu(); // only call EndMenu() if BeginMenu() returns true! + IMGUI_API bool MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true); // return true when activated. + IMGUI_API bool MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true); // return true when activated + toggle (*p_selected) if p_selected != NULL + + // Tooltips + // - Tooltip are windows following the mouse. They do not take focus away. + IMGUI_API void BeginTooltip(); // begin/append a tooltip window. to create full-featured tooltip (with any kind of items). + IMGUI_API void EndTooltip(); + IMGUI_API void SetTooltip(const char* fmt, ...) IM_FMTARGS(1); // set a text-only tooltip, typically use with ImGui::IsItemHovered(). override any previous call to SetTooltip(). + IMGUI_API void SetTooltipV(const char* fmt, va_list args) IM_FMTLIST(1); + + // Popups, Modals + // - They block normal mouse hovering detection (and therefore most mouse interactions) behind them. + // - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE. + // - Their visibility state (~bool) is held internally instead of being held by the programmer as we are used to with regular Begin*() calls. + // - The 3 properties above are related: we need to retain popup visibility state in the library because popups may be closed as any time. + // - You can bypass the hovering restriction by using ImGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered(). + // - IMPORTANT: Popup identifiers are relative to the current ID stack, so OpenPopup and BeginPopup generally needs to be at the same level of the stack. + // This is sometimes leading to confusing mistakes. May rework this in the future. + + // Popups: begin/end functions + // - BeginPopup(): query popup state, if open start appending into the window. Call EndPopup() afterwards. ImGuiWindowFlags are forwarded to the window. + // - BeginPopupModal(): block every interaction behind the window, cannot be closed by user, add a dimming background, has a title bar. + IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. + IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // return true if the modal is open, and you can start outputting to it. + IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true! + + // Popups: open/close functions + // - OpenPopup(): set popup state to open. ImGuiPopupFlags are available for opening options. + // - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE. + // - CloseCurrentPopup(): use inside the BeginPopup()/EndPopup() scope to close manually. + // - CloseCurrentPopup() is called by default by Selectable()/MenuItem() when activated (FIXME: need some options). + // - Use ImGuiPopupFlags_NoOpenOverExistingPopup to avoid opening a popup if there's already one at the same level. This is equivalent to e.g. testing for !IsAnyPopupOpen() prior to OpenPopup(). + // - Use IsWindowAppearing() after BeginPopup() to tell if a window just opened. + // - IMPORTANT: Notice that for OpenPopupOnItemClick() we exceptionally default flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter + IMGUI_API void OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags = 0); // call to mark popup as open (don't call every frame!). + IMGUI_API void OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags = 0); // id overload to facilitate calling from nested stacks + IMGUI_API void OpenPopupOnItemClick(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // helper to open popup when clicked on last item. Default to ImGuiPopupFlags_MouseButtonRight == 1. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) + IMGUI_API void CloseCurrentPopup(); // manually close the popup we have begin-ed into. + + // Popups: open+begin combined functions helpers + // - Helpers to do OpenPopup+BeginPopup where the Open action is triggered by e.g. hovering an item and right-clicking. + // - They are convenient to easily create context menus, hence the name. + // - IMPORTANT: Notice that BeginPopupContextXXX takes ImGuiPopupFlags just like OpenPopup() and unlike BeginPopup(). For full consistency, we may add ImGuiWindowFlags to the BeginPopupContextXXX functions in the future. + // - IMPORTANT: Notice that we exceptionally default their flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter, so if you add other flags remember to re-add the ImGuiPopupFlags_MouseButtonRight. + IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // open+begin popup when clicked on last item. Use str_id==NULL to associate the popup to previous item. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! + IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1);// open+begin popup when clicked on current window. + IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // open+begin popup when clicked in void (where there are no windows). + + // Popups: query functions + // - IsPopupOpen(): return true if the popup is open at the current BeginPopup() level of the popup stack. + // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId: return true if any popup is open at the current BeginPopup() level of the popup stack. + // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId + ImGuiPopupFlags_AnyPopupLevel: return true if any popup is open. + IMGUI_API bool IsPopupOpen(const char* str_id, ImGuiPopupFlags flags = 0); // return true if the popup is open. + + // Tables + // - Full-featured replacement for old Columns API. + // - See Demo->Tables for demo code. See top of imgui_tables.cpp for general commentary. + // - See ImGuiTableFlags_ and ImGuiTableColumnFlags_ enums for a description of available flags. + // The typical call flow is: + // - 1. Call BeginTable(), early out if returning false. + // - 2. Optionally call TableSetupColumn() to submit column name/flags/defaults. + // - 3. Optionally call TableSetupScrollFreeze() to request scroll freezing of columns/rows. + // - 4. Optionally call TableHeadersRow() to submit a header row. Names are pulled from TableSetupColumn() data. + // - 5. Populate contents: + // - In most situations you can use TableNextRow() + TableSetColumnIndex(N) to start appending into a column. + // - If you are using tables as a sort of grid, where every column is holding the same type of contents, + // you may prefer using TableNextColumn() instead of TableNextRow() + TableSetColumnIndex(). + // TableNextColumn() will automatically wrap-around into the next row if needed. + // - IMPORTANT: Comparatively to the old Columns() API, we need to call TableNextColumn() for the first column! + // - Summary of possible call flow: + // -------------------------------------------------------------------------------------------------------- + // TableNextRow() -> TableSetColumnIndex(0) -> Text("Hello 0") -> TableSetColumnIndex(1) -> Text("Hello 1") // OK + // TableNextRow() -> TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK + // TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK: TableNextColumn() automatically gets to next row! + // TableNextRow() -> Text("Hello 0") // Not OK! Missing TableSetColumnIndex() or TableNextColumn()! Text will not appear! + // -------------------------------------------------------------------------------------------------------- + // - 5. Call EndTable() + IMGUI_API bool BeginTable(const char* str_id, int column, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0.0f, 0.0f), float inner_width = 0.0f); + IMGUI_API void EndTable(); // only call EndTable() if BeginTable() returns true! + IMGUI_API void TableNextRow(ImGuiTableRowFlags row_flags = 0, float min_row_height = 0.0f); // append into the first cell of a new row. + IMGUI_API bool TableNextColumn(); // append into the next column (or first column of next row if currently in last column). Return true when column is visible. + IMGUI_API bool TableSetColumnIndex(int column_n); // append into the specified column. Return true when column is visible. + + // Tables: Headers & Columns declaration + // - Use TableSetupColumn() to specify label, resizing policy, default width/weight, id, various other flags etc. + // - Use TableHeadersRow() to create a header row and automatically submit a TableHeader() for each column. + // Headers are required to perform: reordering, sorting, and opening the context menu. + // The context menu can also be made available in columns body using ImGuiTableFlags_ContextMenuInBody. + // - You may manually submit headers using TableNextRow() + TableHeader() calls, but this is only useful in + // some advanced use cases (e.g. adding custom widgets in header row). + // - Use TableSetupScrollFreeze() to lock columns/rows so they stay visible when scrolled. + IMGUI_API void TableSetupColumn(const char* label, ImGuiTableColumnFlags flags = 0, float init_width_or_weight = 0.0f, ImGuiID user_id = 0); + IMGUI_API void TableSetupScrollFreeze(int cols, int rows); // lock columns/rows so they stay visible when scrolled. + IMGUI_API void TableHeadersRow(); // submit all headers cells based on data provided to TableSetupColumn() + submit context menu + IMGUI_API void TableHeader(const char* label); // submit one header cell manually (rarely used) + + // Tables: Sorting & Miscellaneous functions + // - Sorting: call TableGetSortSpecs() to retrieve latest sort specs for the table. NULL when not sorting. + // When 'sort_specs->SpecsDirty == true' you should sort your data. It will be true when sorting specs have + // changed since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting, + // else you may wastefully sort your data every frame! + // - Functions args 'int column_n' treat the default value of -1 as the same as passing the current column index. + IMGUI_API ImGuiTableSortSpecs* TableGetSortSpecs(); // get latest sort specs for the table (NULL if not sorting). Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable(). + IMGUI_API int TableGetColumnCount(); // return number of columns (value passed to BeginTable) + IMGUI_API int TableGetColumnIndex(); // return current column index. + IMGUI_API int TableGetRowIndex(); // return current row index. + IMGUI_API const char* TableGetColumnName(int column_n = -1); // return "" if column didn't have a name declared by TableSetupColumn(). Pass -1 to use current column. + IMGUI_API ImGuiTableColumnFlags TableGetColumnFlags(int column_n = -1); // return column flags so you can query their Enabled/Visible/Sorted/Hovered status flags. Pass -1 to use current column. + IMGUI_API void TableSetColumnEnabled(int column_n, bool v);// change user accessible enabled/disabled state of a column. Set to false to hide the column. User can use the context menu to change this themselves (right-click in headers, or right-click in columns body with ImGuiTableFlags_ContextMenuInBody) + IMGUI_API void TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n = -1); // change the color of a cell, row, or column. See ImGuiTableBgTarget_ flags for details. + + // Legacy Columns API (prefer using Tables!) + // - You can also use SameLine(pos_x) to mimic simplified columns. + IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true); + IMGUI_API void NextColumn(); // next column, defaults to current row or next row if the current row is finished + IMGUI_API int GetColumnIndex(); // get current column index + IMGUI_API float GetColumnWidth(int column_index = -1); // get column width (in pixels). pass -1 to use current column + IMGUI_API void SetColumnWidth(int column_index, float width); // set column width (in pixels). pass -1 to use current column + IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f + IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column + IMGUI_API int GetColumnsCount(); + + // Tab Bars, Tabs + // - Note: Tabs are automatically created by the docking system (when in 'docking' branch). Use this to create tab bars/tabs yourself. + IMGUI_API bool BeginTabBar(const char* str_id, ImGuiTabBarFlags flags = 0); // create and append into a TabBar + IMGUI_API void EndTabBar(); // only call EndTabBar() if BeginTabBar() returns true! + IMGUI_API bool BeginTabItem(const char* label, bool* p_open = NULL, ImGuiTabItemFlags flags = 0); // create a Tab. Returns true if the Tab is selected. + IMGUI_API void EndTabItem(); // only call EndTabItem() if BeginTabItem() returns true! + IMGUI_API bool TabItemButton(const char* label, ImGuiTabItemFlags flags = 0); // create a Tab behaving like a button. return true when clicked. cannot be selected in the tab bar. + IMGUI_API void SetTabItemClosed(const char* tab_or_docked_window_label); // notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable tab bars). For tab-bar: call after BeginTabBar() and before Tab submissions. Otherwise call with a window name. + + // Logging/Capture + // - All text output from the interface can be captured into tty/file/clipboard. By default, tree nodes are automatically opened during logging. + IMGUI_API void LogToTTY(int auto_open_depth = -1); // start logging to tty (stdout) + IMGUI_API void LogToFile(int auto_open_depth = -1, const char* filename = NULL); // start logging to file + IMGUI_API void LogToClipboard(int auto_open_depth = -1); // start logging to OS clipboard + IMGUI_API void LogFinish(); // stop logging (close file, etc.) + IMGUI_API void LogButtons(); // helper to display buttons for logging to tty/file/clipboard + IMGUI_API void LogText(const char* fmt, ...) IM_FMTARGS(1); // pass text data straight to log (without being displayed) + IMGUI_API void LogTextV(const char* fmt, va_list args) IM_FMTLIST(1); + + // Drag and Drop + // - On source items, call BeginDragDropSource(), if it returns true also call SetDragDropPayload() + EndDragDropSource(). + // - On target candidates, call BeginDragDropTarget(), if it returns true also call AcceptDragDropPayload() + EndDragDropTarget(). + // - If you stop calling BeginDragDropSource() the payload is preserved however it won't have a preview tooltip (we currently display a fallback "..." tooltip, see #1725) + // - An item can be both drag source and drop target. + IMGUI_API bool BeginDragDropSource(ImGuiDragDropFlags flags = 0); // call after submitting an item which may be dragged. when this return true, you can call SetDragDropPayload() + EndDragDropSource() + IMGUI_API bool SetDragDropPayload(const char* type, const void* data, size_t sz, ImGuiCond cond = 0); // type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for dear imgui internal types. Data is copied and held by imgui. Return true when payload has been accepted. + IMGUI_API void EndDragDropSource(); // only call EndDragDropSource() if BeginDragDropSource() returns true! + IMGUI_API bool BeginDragDropTarget(); // call after submitting an item that may receive a payload. If this returns true, you can call AcceptDragDropPayload() + EndDragDropTarget() + IMGUI_API const ImGuiPayload* AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags = 0); // accept contents of a given type. If ImGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload before the mouse button is released. + IMGUI_API void EndDragDropTarget(); // only call EndDragDropTarget() if BeginDragDropTarget() returns true! + IMGUI_API const ImGuiPayload* GetDragDropPayload(); // peek directly into the current payload from anywhere. may return NULL. use ImGuiPayload::IsDataType() to test for the payload type. + + // Disabling [BETA API] + // - Disable all user interactions and dim items visuals (applying style.DisabledAlpha over current colors) + // - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled) + // - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it. + IMGUI_API void BeginDisabled(bool disabled = true); + IMGUI_API void EndDisabled(); + + // Clipping + // - Mouse hovering is affected by ImGui::PushClipRect() calls, unlike direct calls to ImDrawList::PushClipRect() which are render only. + IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect); + IMGUI_API void PopClipRect(); + + // Focus, Activation + // - Prefer using "SetItemDefaultFocus()" over "if (IsWindowAppearing()) SetScrollHereY()" when applicable to signify "this is the default item" + IMGUI_API void SetItemDefaultFocus(); // make last item the default focused item of a window. + IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use -1 to access previous widget. + + // Item/Widgets Utilities and Query Functions + // - Most of the functions are referring to the previous Item that has been submitted. + // - See Demo Window under "Widgets->Querying Status" for an interactive visualization of most of those functions. + IMGUI_API bool IsItemHovered(ImGuiHoveredFlags flags = 0); // is the last item hovered? (and usable, aka not blocked by a popup, etc.). See ImGuiHoveredFlags for more options. + IMGUI_API bool IsItemActive(); // is the last item active? (e.g. button being held, text field being edited. This will continuously return true while holding mouse button on an item. Items that don't interact will always return false) + IMGUI_API bool IsItemFocused(); // is the last item focused for keyboard/gamepad navigation? + IMGUI_API bool IsItemClicked(ImGuiMouseButton mouse_button = 0); // is the last item hovered and mouse clicked on? (**) == IsMouseClicked(mouse_button) && IsItemHovered()Important. (**) this is NOT equivalent to the behavior of e.g. Button(). Read comments in function definition. + IMGUI_API bool IsItemVisible(); // is the last item visible? (items may be out of sight because of clipping/scrolling) + IMGUI_API bool IsItemEdited(); // did the last item modify its underlying value this frame? or was pressed? This is generally the same as the "bool" return value of many widgets. + IMGUI_API bool IsItemActivated(); // was the last item just made active (item was previously inactive). + IMGUI_API bool IsItemDeactivated(); // was the last item just made inactive (item was previously active). Useful for Undo/Redo patterns with widgets that require continuous editing. + IMGUI_API bool IsItemDeactivatedAfterEdit(); // was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). Useful for Undo/Redo patterns with widgets that require continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item). + IMGUI_API bool IsItemToggledOpen(); // was the last item open state toggled? set by TreeNode(). + IMGUI_API bool IsAnyItemHovered(); // is any item hovered? + IMGUI_API bool IsAnyItemActive(); // is any item active? + IMGUI_API bool IsAnyItemFocused(); // is any item focused? + IMGUI_API ImGuiID GetItemID(); // get ID of last item (~~ often same ImGui::GetID(label) beforehand) + IMGUI_API ImVec2 GetItemRectMin(); // get upper-left bounding rectangle of the last item (screen space) + IMGUI_API ImVec2 GetItemRectMax(); // get lower-right bounding rectangle of the last item (screen space) + IMGUI_API ImVec2 GetItemRectSize(); // get size of last item + IMGUI_API void SetItemAllowOverlap(); // allow last item to be overlapped by a subsequent item. sometimes useful with invisible buttons, selectables, etc. to catch unused area. + + // Viewports + // - Currently represents the Platform Window created by the application which is hosting our Dear ImGui windows. + // - In 'docking' branch with multi-viewport enabled, we extend this concept to have multiple active viewports. + // - In the future we will extend this concept further to also represent Platform Monitor and support a "no main platform window" operation mode. + IMGUI_API ImGuiViewport* GetMainViewport(); // return primary/default viewport. This can never be NULL. + + // Background/Foreground Draw Lists + IMGUI_API ImDrawList* GetBackgroundDrawList(); // this draw list will be the first rendered one. Useful to quickly draw shapes/text behind dear imgui contents. + IMGUI_API ImDrawList* GetForegroundDrawList(); // this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents. + + // Miscellaneous Utilities + IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle (of given size, starting from cursor position) is visible / not clipped. + IMGUI_API bool IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max); // test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side. + IMGUI_API double GetTime(); // get global imgui time. incremented by io.DeltaTime every frame. + IMGUI_API int GetFrameCount(); // get global imgui frame count. incremented by 1 every frame. + IMGUI_API ImDrawListSharedData* GetDrawListSharedData(); // you may use this when creating your own ImDrawList instances. + IMGUI_API const char* GetStyleColorName(ImGuiCol idx); // get a string corresponding to the enum value (for display, saving, etc.). + IMGUI_API void SetStateStorage(ImGuiStorage* storage); // replace current window storage with our own (if you want to manipulate it yourself, typically clear subsection of it) + IMGUI_API ImGuiStorage* GetStateStorage(); + IMGUI_API bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags flags = 0); // helper to create a child window / scrolling region that looks like a normal widget frame + IMGUI_API void EndChildFrame(); // always call EndChildFrame() regardless of BeginChildFrame() return values (which indicates a collapsed/clipped window) + + // Text Utilities + IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f); + + // Color Utilities + IMGUI_API ImVec4 ColorConvertU32ToFloat4(ImU32 in); + IMGUI_API ImU32 ColorConvertFloat4ToU32(const ImVec4& in); + IMGUI_API void ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v); + IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b); + + // Inputs Utilities: Keyboard/Mouse/Gamepad + // - the ImGuiKey enum contains all possible keyboard, mouse and gamepad inputs (e.g. ImGuiKey_A, ImGuiKey_MouseLeft, ImGuiKey_GamepadDpadUp...). + // - before v1.87, we used ImGuiKey to carry native/user indices as defined by each backends. About use of those legacy ImGuiKey values: + // - without IMGUI_DISABLE_OBSOLETE_KEYIO (legacy support): you can still use your legacy native/user indices (< 512) according to how your backend/engine stored them in io.KeysDown[], but need to cast them to ImGuiKey. + // - with IMGUI_DISABLE_OBSOLETE_KEYIO (this is the way forward): any use of ImGuiKey will assert with key < 512. GetKeyIndex() is pass-through and therefore deprecated (gone if IMGUI_DISABLE_OBSOLETE_KEYIO is defined). + IMGUI_API bool IsKeyDown(ImGuiKey key); // is key being held. + IMGUI_API bool IsKeyPressed(ImGuiKey key, bool repeat = true); // was key pressed (went from !Down to Down)? if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate + IMGUI_API bool IsKeyReleased(ImGuiKey key); // was key released (went from Down to !Down)? + IMGUI_API int GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float rate); // uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough that DeltaTime > RepeatRate + IMGUI_API const char* GetKeyName(ImGuiKey key); // [DEBUG] returns English name of the key. Those names a provided for debugging purpose and are not meant to be saved persistently not compared. + IMGUI_API void SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard); // Override io.WantCaptureKeyboard flag next frame (said flag is left for your application to handle, typically when true it instructs your app to ignore inputs). e.g. force capture keyboard when your widget is being hovered. This is equivalent to setting "io.WantCaptureKeyboard = want_capture_keyboard"; after the next NewFrame() call. + + // Inputs Utilities: Mouse specific + // - To refer to a mouse button, you may use named enums in your code e.g. ImGuiMouseButton_Left, ImGuiMouseButton_Right. + // - You can also use regular integer: it is forever guaranteed that 0=Left, 1=Right, 2=Middle. + // - Dragging operations are only reported after mouse has moved a certain distance away from the initial clicking position (see 'lock_threshold' and 'io.MouseDraggingThreshold') + IMGUI_API bool IsMouseDown(ImGuiMouseButton button); // is mouse button held? + IMGUI_API bool IsMouseClicked(ImGuiMouseButton button, bool repeat = false); // did mouse button clicked? (went from !Down to Down). Same as GetMouseClickedCount() == 1. + IMGUI_API bool IsMouseReleased(ImGuiMouseButton button); // did mouse button released? (went from Down to !Down) + IMGUI_API bool IsMouseDoubleClicked(ImGuiMouseButton button); // did mouse button double-clicked? Same as GetMouseClickedCount() == 2. (note that a double-click will also report IsMouseClicked() == true) + IMGUI_API int GetMouseClickedCount(ImGuiMouseButton button); // return the number of successive mouse-clicks at the time where a click happen (otherwise 0). + IMGUI_API bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true);// is mouse hovering given bounding rect (in screen space). clipped by current clipping settings, but disregarding of other consideration of focus/window ordering/popup-block. + IMGUI_API bool IsMousePosValid(const ImVec2* mouse_pos = NULL); // by convention we use (-FLT_MAX,-FLT_MAX) to denote that there is no mouse available + IMGUI_API bool IsAnyMouseDown(); // [WILL OBSOLETE] is any mouse button held? This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid. + IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls + IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve mouse position at the time of opening popup we have BeginPopup() into (helper to avoid user backing that value themselves) + IMGUI_API bool IsMouseDragging(ImGuiMouseButton button, float lock_threshold = -1.0f); // is mouse dragging? (if lock_threshold < -1.0f, uses io.MouseDraggingThreshold) + IMGUI_API ImVec2 GetMouseDragDelta(ImGuiMouseButton button = 0, float lock_threshold = -1.0f); // return the delta from the initial clicking position while the mouse button is pressed or was just released. This is locked and return 0.0f until the mouse moves past a distance threshold at least once (if lock_threshold < -1.0f, uses io.MouseDraggingThreshold) + IMGUI_API void ResetMouseDragDelta(ImGuiMouseButton button = 0); // + IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired mouse cursor shape. Important: reset in ImGui::NewFrame(), this is updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you + IMGUI_API void SetMouseCursor(ImGuiMouseCursor cursor_type); // set desired mouse cursor shape + IMGUI_API void SetNextFrameWantCaptureMouse(bool want_capture_mouse); // Override io.WantCaptureMouse flag next frame (said flag is left for your application to handle, typical when true it instucts your app to ignore inputs). This is equivalent to setting "io.WantCaptureMouse = want_capture_mouse;" after the next NewFrame() call. + + // Clipboard Utilities + // - Also see the LogToClipboard() function to capture GUI into clipboard, or easily output text data to the clipboard. + IMGUI_API const char* GetClipboardText(); + IMGUI_API void SetClipboardText(const char* text); + + // Settings/.Ini Utilities + // - The disk functions are automatically called if io.IniFilename != NULL (default is "imgui.ini"). + // - Set io.IniFilename to NULL to load/save manually. Read io.WantSaveIniSettings description about handling .ini saving manually. + // - Important: default value "imgui.ini" is relative to current working dir! Most apps will want to lock this to an absolute path (e.g. same path as executables). + IMGUI_API void LoadIniSettingsFromDisk(const char* ini_filename); // call after CreateContext() and before the first call to NewFrame(). NewFrame() automatically calls LoadIniSettingsFromDisk(io.IniFilename). + IMGUI_API void LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size=0); // call after CreateContext() and before the first call to NewFrame() to provide .ini data from your own data source. + IMGUI_API void SaveIniSettingsToDisk(const char* ini_filename); // this is automatically called (if io.IniFilename is not empty) a few seconds after any modification that should be reflected in the .ini file (and also by DestroyContext). + IMGUI_API const char* SaveIniSettingsToMemory(size_t* out_ini_size = NULL); // return a zero-terminated string with the .ini data which you can save by your own mean. call when io.WantSaveIniSettings is set, then save data by your own mean and clear io.WantSaveIniSettings. + + // Debug Utilities + IMGUI_API void DebugTextEncoding(const char* text); + IMGUI_API bool DebugCheckVersionAndDataLayout(const char* version_str, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_drawvert, size_t sz_drawidx); // This is called by IMGUI_CHECKVERSION() macro. + + // Memory Allocators + // - Those functions are not reliant on the current context. + // - DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() + // for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details. + IMGUI_API void SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data = NULL); + IMGUI_API void GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data); + IMGUI_API void* MemAlloc(size_t size); + IMGUI_API void MemFree(void* ptr); + +} // namespace ImGui + +//----------------------------------------------------------------------------- +// [SECTION] Flags & Enumerations +//----------------------------------------------------------------------------- + +// Flags for ImGui::Begin() +// (Those are per-window flags. There are shared flags in ImGuiIO: io.ConfigWindowsResizeFromEdges and io.ConfigWindowsMoveFromTitleBarOnly) +enum ImGuiWindowFlags_ +{ + ImGuiWindowFlags_None = 0, + ImGuiWindowFlags_NoTitleBar = 1 << 0, // Disable title-bar + ImGuiWindowFlags_NoResize = 1 << 1, // Disable user resizing with the lower-right grip + ImGuiWindowFlags_NoMove = 1 << 2, // Disable user moving the window + ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbars (window can still scroll with mouse or programmatically) + ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set. + ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it. Also referred to as Window Menu Button (e.g. within a docking node). + ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame + ImGuiWindowFlags_NoBackground = 1 << 7, // Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f). + ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file + ImGuiWindowFlags_NoMouseInputs = 1 << 9, // Disable catching mouse, hovering test with pass through. + ImGuiWindowFlags_MenuBar = 1 << 10, // Has a menu-bar + ImGuiWindowFlags_HorizontalScrollbar = 1 << 11, // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. + ImGuiWindowFlags_NoFocusOnAppearing = 1 << 12, // Disable taking focus when transitioning from hidden to visible state + ImGuiWindowFlags_NoBringToFrontOnFocus = 1 << 13, // Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus) + ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14, // Always show vertical scrollbar (even if ContentSize.y < Size.y) + ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15, // Always show horizontal scrollbar (even if ContentSize.x < Size.x) + ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 16, // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient) + ImGuiWindowFlags_NoNavInputs = 1 << 18, // No gamepad/keyboard navigation within the window + ImGuiWindowFlags_NoNavFocus = 1 << 19, // No focusing toward this window with gamepad/keyboard navigation (e.g. skipped by CTRL+TAB) + ImGuiWindowFlags_UnsavedDocument = 1 << 20, // Display a dot next to the title. When used in a tab/docking context, tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. + ImGuiWindowFlags_NoNav = ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, + ImGuiWindowFlags_NoDecoration = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse, + ImGuiWindowFlags_NoInputs = ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, + + // [Internal] + ImGuiWindowFlags_NavFlattened = 1 << 23, // [BETA] On child window: allow gamepad/keyboard navigation to cross over parent border to this child or between sibling child windows. + ImGuiWindowFlags_ChildWindow = 1 << 24, // Don't use! For internal use by BeginChild() + ImGuiWindowFlags_Tooltip = 1 << 25, // Don't use! For internal use by BeginTooltip() + ImGuiWindowFlags_Popup = 1 << 26, // Don't use! For internal use by BeginPopup() + ImGuiWindowFlags_Modal = 1 << 27, // Don't use! For internal use by BeginPopupModal() + ImGuiWindowFlags_ChildMenu = 1 << 28, // Don't use! For internal use by BeginMenu() +}; + +// Flags for ImGui::InputText() +// (Those are per-item flags. There are shared flags in ImGuiIO: io.ConfigInputTextCursorBlink and io.ConfigInputTextEnterKeepActive) +enum ImGuiInputTextFlags_ +{ + ImGuiInputTextFlags_None = 0, + ImGuiInputTextFlags_CharsDecimal = 1 << 0, // Allow 0123456789.+-*/ + ImGuiInputTextFlags_CharsHexadecimal = 1 << 1, // Allow 0123456789ABCDEFabcdef + ImGuiInputTextFlags_CharsUppercase = 1 << 2, // Turn a..z into A..Z + ImGuiInputTextFlags_CharsNoBlank = 1 << 3, // Filter out spaces, tabs + ImGuiInputTextFlags_AutoSelectAll = 1 << 4, // Select entire text when first taking mouse focus + ImGuiInputTextFlags_EnterReturnsTrue = 1 << 5, // Return 'true' when Enter is pressed (as opposed to every time the value was modified). Consider looking at the IsItemDeactivatedAfterEdit() function. + ImGuiInputTextFlags_CallbackCompletion = 1 << 6, // Callback on pressing TAB (for completion handling) + ImGuiInputTextFlags_CallbackHistory = 1 << 7, // Callback on pressing Up/Down arrows (for history handling) + ImGuiInputTextFlags_CallbackAlways = 1 << 8, // Callback on each iteration. User code may query cursor position, modify text buffer. + ImGuiInputTextFlags_CallbackCharFilter = 1 << 9, // Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. + ImGuiInputTextFlags_AllowTabInput = 1 << 10, // Pressing TAB input a '\t' character into the text field + ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 11, // In multi-line mode, unfocus with Enter, add new line with Ctrl+Enter (default is opposite: unfocus with Ctrl+Enter, add line with Enter). + ImGuiInputTextFlags_NoHorizontalScroll = 1 << 12, // Disable following the cursor horizontally + ImGuiInputTextFlags_AlwaysOverwrite = 1 << 13, // Overwrite mode + ImGuiInputTextFlags_ReadOnly = 1 << 14, // Read-only mode + ImGuiInputTextFlags_Password = 1 << 15, // Password mode, display all characters as '*' + ImGuiInputTextFlags_NoUndoRedo = 1 << 16, // Disable undo/redo. Note that input text owns the text data while active, if you want to provide your own undo/redo stack you need e.g. to call ClearActiveID(). + ImGuiInputTextFlags_CharsScientific = 1 << 17, // Allow 0123456789.+-*/eE (Scientific notation input) + ImGuiInputTextFlags_CallbackResize = 1 << 18, // Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/imgui_stdlib.h for an example of using this) + ImGuiInputTextFlags_CallbackEdit = 1 << 19, // Callback on any edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active) + ImGuiInputTextFlags_EscapeClearsAll = 1 << 20, // Escape key clears content if not empty, and deactivate otherwise (contrast to default behavior of Escape to revert) + + // Obsolete names (will be removed soon) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiInputTextFlags_AlwaysInsertMode = ImGuiInputTextFlags_AlwaysOverwrite // [renamed in 1.82] name was not matching behavior +#endif +}; + +// Flags for ImGui::TreeNodeEx(), ImGui::CollapsingHeader*() +enum ImGuiTreeNodeFlags_ +{ + ImGuiTreeNodeFlags_None = 0, + ImGuiTreeNodeFlags_Selected = 1 << 0, // Draw as selected + ImGuiTreeNodeFlags_Framed = 1 << 1, // Draw frame with background (e.g. for CollapsingHeader) + ImGuiTreeNodeFlags_AllowItemOverlap = 1 << 2, // Hit testing to allow subsequent widgets to overlap this one + ImGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3, // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack + ImGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4, // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes) + ImGuiTreeNodeFlags_DefaultOpen = 1 << 5, // Default node to be open + ImGuiTreeNodeFlags_OpenOnDoubleClick = 1 << 6, // Need double-click to open node + ImGuiTreeNodeFlags_OpenOnArrow = 1 << 7, // Only open when clicking on the arrow part. If ImGuiTreeNodeFlags_OpenOnDoubleClick is also set, single-click arrow or double-click all box to open. + ImGuiTreeNodeFlags_Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes). + ImGuiTreeNodeFlags_Bullet = 1 << 9, // Display a bullet instead of arrow + ImGuiTreeNodeFlags_FramePadding = 1 << 10, // Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding(). + ImGuiTreeNodeFlags_SpanAvailWidth = 1 << 11, // Extend hit box to the right-most edge, even if not framed. This is not the default in order to allow adding other items on the same line. In the future we may refactor the hit system to be front-to-back, allowing natural overlaps and then this can become the default. + ImGuiTreeNodeFlags_SpanFullWidth = 1 << 12, // Extend hit box to the left-most and right-most edges (bypass the indented area). + ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 1 << 13, // (WIP) Nav: left direction may move to this TreeNode() from any of its child (items submitted between TreeNode and TreePop) + //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 14, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible + ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog, +}; + +// Flags for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() functions. +// - To be backward compatible with older API which took an 'int mouse_button = 1' argument, we need to treat +// small flags values as a mouse button index, so we encode the mouse button in the first few bits of the flags. +// It is therefore guaranteed to be legal to pass a mouse button index in ImGuiPopupFlags. +// - For the same reason, we exceptionally default the ImGuiPopupFlags argument of BeginPopupContextXXX functions to 1 instead of 0. +// IMPORTANT: because the default parameter is 1 (==ImGuiPopupFlags_MouseButtonRight), if you rely on the default parameter +// and want to use another flag, you need to pass in the ImGuiPopupFlags_MouseButtonRight flag explicitly. +// - Multiple buttons currently cannot be combined/or-ed in those functions (we could allow it later). +enum ImGuiPopupFlags_ +{ + ImGuiPopupFlags_None = 0, + ImGuiPopupFlags_MouseButtonLeft = 0, // For BeginPopupContext*(): open on Left Mouse release. Guaranteed to always be == 0 (same as ImGuiMouseButton_Left) + ImGuiPopupFlags_MouseButtonRight = 1, // For BeginPopupContext*(): open on Right Mouse release. Guaranteed to always be == 1 (same as ImGuiMouseButton_Right) + ImGuiPopupFlags_MouseButtonMiddle = 2, // For BeginPopupContext*(): open on Middle Mouse release. Guaranteed to always be == 2 (same as ImGuiMouseButton_Middle) + ImGuiPopupFlags_MouseButtonMask_ = 0x1F, + ImGuiPopupFlags_MouseButtonDefault_ = 1, + ImGuiPopupFlags_NoOpenOverExistingPopup = 1 << 5, // For OpenPopup*(), BeginPopupContext*(): don't open if there's already a popup at the same level of the popup stack + ImGuiPopupFlags_NoOpenOverItems = 1 << 6, // For BeginPopupContextWindow(): don't return true when hovering items, only when hovering empty space + ImGuiPopupFlags_AnyPopupId = 1 << 7, // For IsPopupOpen(): ignore the ImGuiID parameter and test for any popup. + ImGuiPopupFlags_AnyPopupLevel = 1 << 8, // For IsPopupOpen(): search/test at any level of the popup stack (default test in the current level) + ImGuiPopupFlags_AnyPopup = ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel, +}; + +// Flags for ImGui::Selectable() +enum ImGuiSelectableFlags_ +{ + ImGuiSelectableFlags_None = 0, + ImGuiSelectableFlags_DontClosePopups = 1 << 0, // Clicking this doesn't close parent popup window + ImGuiSelectableFlags_SpanAllColumns = 1 << 1, // Selectable frame can span all columns (text will still fit in current column) + ImGuiSelectableFlags_AllowDoubleClick = 1 << 2, // Generate press events on double clicks too + ImGuiSelectableFlags_Disabled = 1 << 3, // Cannot be selected, display grayed out text + ImGuiSelectableFlags_AllowItemOverlap = 1 << 4, // (WIP) Hit testing to allow subsequent widgets to overlap this one +}; + +// Flags for ImGui::BeginCombo() +enum ImGuiComboFlags_ +{ + ImGuiComboFlags_None = 0, + ImGuiComboFlags_PopupAlignLeft = 1 << 0, // Align the popup toward the left by default + ImGuiComboFlags_HeightSmall = 1 << 1, // Max ~4 items visible. Tip: If you want your combo popup to be a specific size you can use SetNextWindowSizeConstraints() prior to calling BeginCombo() + ImGuiComboFlags_HeightRegular = 1 << 2, // Max ~8 items visible (default) + ImGuiComboFlags_HeightLarge = 1 << 3, // Max ~20 items visible + ImGuiComboFlags_HeightLargest = 1 << 4, // As many fitting items as possible + ImGuiComboFlags_NoArrowButton = 1 << 5, // Display on the preview box without the square arrow button + ImGuiComboFlags_NoPreview = 1 << 6, // Display only a square arrow button + ImGuiComboFlags_HeightMask_ = ImGuiComboFlags_HeightSmall | ImGuiComboFlags_HeightRegular | ImGuiComboFlags_HeightLarge | ImGuiComboFlags_HeightLargest, +}; + +// Flags for ImGui::BeginTabBar() +enum ImGuiTabBarFlags_ +{ + ImGuiTabBarFlags_None = 0, + ImGuiTabBarFlags_Reorderable = 1 << 0, // Allow manually dragging tabs to re-order them + New tabs are appended at the end of list + ImGuiTabBarFlags_AutoSelectNewTabs = 1 << 1, // Automatically select new tabs when they appear + ImGuiTabBarFlags_TabListPopupButton = 1 << 2, // Disable buttons to open the tab list popup + ImGuiTabBarFlags_NoCloseWithMiddleMouseButton = 1 << 3, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. + ImGuiTabBarFlags_NoTabListScrollingButtons = 1 << 4, // Disable scrolling buttons (apply when fitting policy is ImGuiTabBarFlags_FittingPolicyScroll) + ImGuiTabBarFlags_NoTooltip = 1 << 5, // Disable tooltips when hovering a tab + ImGuiTabBarFlags_FittingPolicyResizeDown = 1 << 6, // Resize tabs when they don't fit + ImGuiTabBarFlags_FittingPolicyScroll = 1 << 7, // Add scroll buttons when tabs don't fit + ImGuiTabBarFlags_FittingPolicyMask_ = ImGuiTabBarFlags_FittingPolicyResizeDown | ImGuiTabBarFlags_FittingPolicyScroll, + ImGuiTabBarFlags_FittingPolicyDefault_ = ImGuiTabBarFlags_FittingPolicyResizeDown, +}; + +// Flags for ImGui::BeginTabItem() +enum ImGuiTabItemFlags_ +{ + ImGuiTabItemFlags_None = 0, + ImGuiTabItemFlags_UnsavedDocument = 1 << 0, // Display a dot next to the title + tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. + ImGuiTabItemFlags_SetSelected = 1 << 1, // Trigger flag to programmatically make the tab selected when calling BeginTabItem() + ImGuiTabItemFlags_NoCloseWithMiddleMouseButton = 1 << 2, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. + ImGuiTabItemFlags_NoPushId = 1 << 3, // Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem() + ImGuiTabItemFlags_NoTooltip = 1 << 4, // Disable tooltip for the given tab + ImGuiTabItemFlags_NoReorder = 1 << 5, // Disable reordering this tab or having another tab cross over this tab + ImGuiTabItemFlags_Leading = 1 << 6, // Enforce the tab position to the left of the tab bar (after the tab list popup button) + ImGuiTabItemFlags_Trailing = 1 << 7, // Enforce the tab position to the right of the tab bar (before the scrolling buttons) +}; + +// Flags for ImGui::BeginTable() +// - Important! Sizing policies have complex and subtle side effects, much more so than you would expect. +// Read comments/demos carefully + experiment with live demos to get acquainted with them. +// - The DEFAULT sizing policies are: +// - Default to ImGuiTableFlags_SizingFixedFit if ScrollX is on, or if host window has ImGuiWindowFlags_AlwaysAutoResize. +// - Default to ImGuiTableFlags_SizingStretchSame if ScrollX is off. +// - When ScrollX is off: +// - Table defaults to ImGuiTableFlags_SizingStretchSame -> all Columns defaults to ImGuiTableColumnFlags_WidthStretch with same weight. +// - Columns sizing policy allowed: Stretch (default), Fixed/Auto. +// - Fixed Columns (if any) will generally obtain their requested width (unless the table cannot fit them all). +// - Stretch Columns will share the remaining width according to their respective weight. +// - Mixed Fixed/Stretch columns is possible but has various side-effects on resizing behaviors. +// The typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns. +// (this is because the visible order of columns have subtle but necessary effects on how they react to manual resizing). +// - When ScrollX is on: +// - Table defaults to ImGuiTableFlags_SizingFixedFit -> all Columns defaults to ImGuiTableColumnFlags_WidthFixed +// - Columns sizing policy allowed: Fixed/Auto mostly. +// - Fixed Columns can be enlarged as needed. Table will show a horizontal scrollbar if needed. +// - When using auto-resizing (non-resizable) fixed columns, querying the content width to use item right-alignment e.g. SetNextItemWidth(-FLT_MIN) doesn't make sense, would create a feedback loop. +// - Using Stretch columns OFTEN DOES NOT MAKE SENSE if ScrollX is on, UNLESS you have specified a value for 'inner_width' in BeginTable(). +// If you specify a value for 'inner_width' then effectively the scrolling space is known and Stretch or mixed Fixed/Stretch columns become meaningful again. +// - Read on documentation at the top of imgui_tables.cpp for details. +enum ImGuiTableFlags_ +{ + // Features + ImGuiTableFlags_None = 0, + ImGuiTableFlags_Resizable = 1 << 0, // Enable resizing columns. + ImGuiTableFlags_Reorderable = 1 << 1, // Enable reordering columns in header row (need calling TableSetupColumn() + TableHeadersRow() to display headers) + ImGuiTableFlags_Hideable = 1 << 2, // Enable hiding/disabling columns in context menu. + ImGuiTableFlags_Sortable = 1 << 3, // Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags_SortMulti and ImGuiTableFlags_SortTristate. + ImGuiTableFlags_NoSavedSettings = 1 << 4, // Disable persisting columns order, width and sort settings in the .ini file. + ImGuiTableFlags_ContextMenuInBody = 1 << 5, // Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow(). + // Decorations + ImGuiTableFlags_RowBg = 1 << 6, // Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually) + ImGuiTableFlags_BordersInnerH = 1 << 7, // Draw horizontal borders between rows. + ImGuiTableFlags_BordersOuterH = 1 << 8, // Draw horizontal borders at the top and bottom. + ImGuiTableFlags_BordersInnerV = 1 << 9, // Draw vertical borders between columns. + ImGuiTableFlags_BordersOuterV = 1 << 10, // Draw vertical borders on the left and right sides. + ImGuiTableFlags_BordersH = ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_BordersOuterH, // Draw horizontal borders. + ImGuiTableFlags_BordersV = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersOuterV, // Draw vertical borders. + ImGuiTableFlags_BordersInner = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersInnerH, // Draw inner borders. + ImGuiTableFlags_BordersOuter = ImGuiTableFlags_BordersOuterV | ImGuiTableFlags_BordersOuterH, // Draw outer borders. + ImGuiTableFlags_Borders = ImGuiTableFlags_BordersInner | ImGuiTableFlags_BordersOuter, // Draw all borders. + ImGuiTableFlags_NoBordersInBody = 1 << 11, // [ALPHA] Disable vertical borders in columns Body (borders will always appear in Headers). -> May move to style + ImGuiTableFlags_NoBordersInBodyUntilResize = 1 << 12, // [ALPHA] Disable vertical borders in columns Body until hovered for resize (borders will always appear in Headers). -> May move to style + // Sizing Policy (read above for defaults) + ImGuiTableFlags_SizingFixedFit = 1 << 13, // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching contents width. + ImGuiTableFlags_SizingFixedSame = 2 << 13, // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching the maximum contents width of all columns. Implicitly enable ImGuiTableFlags_NoKeepColumnsVisible. + ImGuiTableFlags_SizingStretchProp = 3 << 13, // Columns default to _WidthStretch with default weights proportional to each columns contents widths. + ImGuiTableFlags_SizingStretchSame = 4 << 13, // Columns default to _WidthStretch with default weights all equal, unless overridden by TableSetupColumn(). + // Sizing Extra Options + ImGuiTableFlags_NoHostExtendX = 1 << 16, // Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. + ImGuiTableFlags_NoHostExtendY = 1 << 17, // Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible. + ImGuiTableFlags_NoKeepColumnsVisible = 1 << 18, // Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable. + ImGuiTableFlags_PreciseWidths = 1 << 19, // Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth. + // Clipping + ImGuiTableFlags_NoClip = 1 << 20, // Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with TableSetupScrollFreeze(). + // Padding + ImGuiTableFlags_PadOuterX = 1 << 21, // Default if BordersOuterV is on. Enable outermost padding. Generally desirable if you have headers. + ImGuiTableFlags_NoPadOuterX = 1 << 22, // Default if BordersOuterV is off. Disable outermost padding. + ImGuiTableFlags_NoPadInnerX = 1 << 23, // Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off). + // Scrolling + ImGuiTableFlags_ScrollX = 1 << 24, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this creates a child window, ScrollY is currently generally recommended when using ScrollX. + ImGuiTableFlags_ScrollY = 1 << 25, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. + // Sorting + ImGuiTableFlags_SortMulti = 1 << 26, // Hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1). + ImGuiTableFlags_SortTristate = 1 << 27, // Allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0). + + // [Internal] Combinations and masks + ImGuiTableFlags_SizingMask_ = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_SizingFixedSame | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_SizingStretchSame, +}; + +// Flags for ImGui::TableSetupColumn() +enum ImGuiTableColumnFlags_ +{ + // Input configuration flags + ImGuiTableColumnFlags_None = 0, + ImGuiTableColumnFlags_Disabled = 1 << 0, // Overriding/master disable flag: hide column, won't show in context menu (unlike calling TableSetColumnEnabled() which manipulates the user accessible state) + ImGuiTableColumnFlags_DefaultHide = 1 << 1, // Default as a hidden/disabled column. + ImGuiTableColumnFlags_DefaultSort = 1 << 2, // Default as a sorting column. + ImGuiTableColumnFlags_WidthStretch = 1 << 3, // Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp). + ImGuiTableColumnFlags_WidthFixed = 1 << 4, // Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable). + ImGuiTableColumnFlags_NoResize = 1 << 5, // Disable manual resizing. + ImGuiTableColumnFlags_NoReorder = 1 << 6, // Disable manual reordering this column, this will also prevent other columns from crossing over this column. + ImGuiTableColumnFlags_NoHide = 1 << 7, // Disable ability to hide/disable this column. + ImGuiTableColumnFlags_NoClip = 1 << 8, // Disable clipping for this column (all NoClip columns will render in a same draw command). + ImGuiTableColumnFlags_NoSort = 1 << 9, // Disable ability to sort on this field (even if ImGuiTableFlags_Sortable is set on the table). + ImGuiTableColumnFlags_NoSortAscending = 1 << 10, // Disable ability to sort in the ascending direction. + ImGuiTableColumnFlags_NoSortDescending = 1 << 11, // Disable ability to sort in the descending direction. + ImGuiTableColumnFlags_NoHeaderLabel = 1 << 12, // TableHeadersRow() will not submit label for this column. Convenient for some small columns. Name will still appear in context menu. + ImGuiTableColumnFlags_NoHeaderWidth = 1 << 13, // Disable header text width contribution to automatic column width. + ImGuiTableColumnFlags_PreferSortAscending = 1 << 14, // Make the initial sort direction Ascending when first sorting on this column (default). + ImGuiTableColumnFlags_PreferSortDescending = 1 << 15, // Make the initial sort direction Descending when first sorting on this column. + ImGuiTableColumnFlags_IndentEnable = 1 << 16, // Use current Indent value when entering cell (default for column 0). + ImGuiTableColumnFlags_IndentDisable = 1 << 17, // Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored. + + // Output status flags, read-only via TableGetColumnFlags() + ImGuiTableColumnFlags_IsEnabled = 1 << 24, // Status: is enabled == not hidden by user/api (referred to as "Hide" in _DefaultHide and _NoHide) flags. + ImGuiTableColumnFlags_IsVisible = 1 << 25, // Status: is visible == is enabled AND not clipped by scrolling. + ImGuiTableColumnFlags_IsSorted = 1 << 26, // Status: is currently part of the sort specs + ImGuiTableColumnFlags_IsHovered = 1 << 27, // Status: is hovered by mouse + + // [Internal] Combinations and masks + ImGuiTableColumnFlags_WidthMask_ = ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_WidthFixed, + ImGuiTableColumnFlags_IndentMask_ = ImGuiTableColumnFlags_IndentEnable | ImGuiTableColumnFlags_IndentDisable, + ImGuiTableColumnFlags_StatusMask_ = ImGuiTableColumnFlags_IsEnabled | ImGuiTableColumnFlags_IsVisible | ImGuiTableColumnFlags_IsSorted | ImGuiTableColumnFlags_IsHovered, + ImGuiTableColumnFlags_NoDirectResize_ = 1 << 30, // [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge) +}; + +// Flags for ImGui::TableNextRow() +enum ImGuiTableRowFlags_ +{ + ImGuiTableRowFlags_None = 0, + ImGuiTableRowFlags_Headers = 1 << 0, // Identify header row (set default background color + width of its contents accounted differently for auto column width) +}; + +// Enum for ImGui::TableSetBgColor() +// Background colors are rendering in 3 layers: +// - Layer 0: draw with RowBg0 color if set, otherwise draw with ColumnBg0 if set. +// - Layer 1: draw with RowBg1 color if set, otherwise draw with ColumnBg1 if set. +// - Layer 2: draw with CellBg color if set. +// The purpose of the two row/columns layers is to let you decide if a background color change should override or blend with the existing color. +// When using ImGuiTableFlags_RowBg on the table, each row has the RowBg0 color automatically set for odd/even rows. +// If you set the color of RowBg0 target, your color will override the existing RowBg0 color. +// If you set the color of RowBg1 or ColumnBg1 target, your color will blend over the RowBg0 color. +enum ImGuiTableBgTarget_ +{ + ImGuiTableBgTarget_None = 0, + ImGuiTableBgTarget_RowBg0 = 1, // Set row background color 0 (generally used for background, automatically set when ImGuiTableFlags_RowBg is used) + ImGuiTableBgTarget_RowBg1 = 2, // Set row background color 1 (generally used for selection marking) + ImGuiTableBgTarget_CellBg = 3, // Set cell background color (top-most color) +}; + +// Flags for ImGui::IsWindowFocused() +enum ImGuiFocusedFlags_ +{ + ImGuiFocusedFlags_None = 0, + ImGuiFocusedFlags_ChildWindows = 1 << 0, // Return true if any children of the window is focused + ImGuiFocusedFlags_RootWindow = 1 << 1, // Test from root window (top most parent of the current hierarchy) + ImGuiFocusedFlags_AnyWindow = 1 << 2, // Return true if any window is focused. Important: If you are trying to tell how to dispatch your low-level inputs, do NOT use this. Use 'io.WantCaptureMouse' instead! Please read the FAQ! + ImGuiFocusedFlags_NoPopupHierarchy = 1 << 3, // Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) + //ImGuiFocusedFlags_DockHierarchy = 1 << 4, // Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) + ImGuiFocusedFlags_RootAndChildWindows = ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows, +}; + +// Flags for ImGui::IsItemHovered(), ImGui::IsWindowHovered() +// Note: if you are trying to check whether your mouse should be dispatched to Dear ImGui or to your app, you should use 'io.WantCaptureMouse' instead! Please read the FAQ! +// Note: windows with the ImGuiWindowFlags_NoInputs flag are ignored by IsWindowHovered() calls. +enum ImGuiHoveredFlags_ +{ + ImGuiHoveredFlags_None = 0, // Return true if directly over the item/window, not obstructed by another window, not obstructed by an active popup or modal blocking inputs under them. + ImGuiHoveredFlags_ChildWindows = 1 << 0, // IsWindowHovered() only: Return true if any children of the window is hovered + ImGuiHoveredFlags_RootWindow = 1 << 1, // IsWindowHovered() only: Test from root window (top most parent of the current hierarchy) + ImGuiHoveredFlags_AnyWindow = 1 << 2, // IsWindowHovered() only: Return true if any window is hovered + ImGuiHoveredFlags_NoPopupHierarchy = 1 << 3, // IsWindowHovered() only: Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) + //ImGuiHoveredFlags_DockHierarchy = 1 << 4, // IsWindowHovered() only: Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) + ImGuiHoveredFlags_AllowWhenBlockedByPopup = 1 << 5, // Return true even if a popup window is normally blocking access to this item/window + //ImGuiHoveredFlags_AllowWhenBlockedByModal = 1 << 6, // Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet. + ImGuiHoveredFlags_AllowWhenBlockedByActiveItem = 1 << 7, // Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns. + ImGuiHoveredFlags_AllowWhenOverlapped = 1 << 8, // IsItemHovered() only: Return true even if the position is obstructed or overlapped by another window + ImGuiHoveredFlags_AllowWhenDisabled = 1 << 9, // IsItemHovered() only: Return true even if the item is disabled + ImGuiHoveredFlags_NoNavOverride = 1 << 10, // Disable using gamepad/keyboard navigation state when active, always query mouse. + ImGuiHoveredFlags_RectOnly = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped, + ImGuiHoveredFlags_RootAndChildWindows = ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows, + + // Hovering delays (for tooltips) + ImGuiHoveredFlags_DelayNormal = 1 << 11, // Return true after io.HoverDelayNormal elapsed (~0.30 sec) + ImGuiHoveredFlags_DelayShort = 1 << 12, // Return true after io.HoverDelayShort elapsed (~0.10 sec) + ImGuiHoveredFlags_NoSharedDelay = 1 << 13, // Disable shared delay system where moving from one item to the next keeps the previous timer for a short time (standard for tooltips with long delays) +}; + +// Flags for ImGui::BeginDragDropSource(), ImGui::AcceptDragDropPayload() +enum ImGuiDragDropFlags_ +{ + ImGuiDragDropFlags_None = 0, + // BeginDragDropSource() flags + ImGuiDragDropFlags_SourceNoPreviewTooltip = 1 << 0, // Disable preview tooltip. By default, a successful call to BeginDragDropSource opens a tooltip so you can display a preview or description of the source contents. This flag disables this behavior. + ImGuiDragDropFlags_SourceNoDisableHover = 1 << 1, // By default, when dragging we clear data so that IsItemHovered() will return false, to avoid subsequent user code submitting tooltips. This flag disables this behavior so you can still call IsItemHovered() on the source item. + ImGuiDragDropFlags_SourceNoHoldToOpenOthers = 1 << 2, // Disable the behavior that allows to open tree nodes and collapsing header by holding over them while dragging a source item. + ImGuiDragDropFlags_SourceAllowNullID = 1 << 3, // Allow items such as Text(), Image() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the dear imgui ecosystem and so we made it explicit. + ImGuiDragDropFlags_SourceExtern = 1 << 4, // External source (from outside of dear imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously. + ImGuiDragDropFlags_SourceAutoExpirePayload = 1 << 5, // Automatically expire the payload if the source cease to be submitted (otherwise payloads are persisting while being dragged) + // AcceptDragDropPayload() flags + ImGuiDragDropFlags_AcceptBeforeDelivery = 1 << 10, // AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered. + ImGuiDragDropFlags_AcceptNoDrawDefaultRect = 1 << 11, // Do not draw the default highlight rectangle when hovering over target. + ImGuiDragDropFlags_AcceptNoPreviewTooltip = 1 << 12, // Request hiding the BeginDragDropSource tooltip from the BeginDragDropTarget site. + ImGuiDragDropFlags_AcceptPeekOnly = ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect, // For peeking ahead and inspecting the payload before delivery. +}; + +// Standard Drag and Drop payload types. You can define you own payload types using short strings. Types starting with '_' are defined by Dear ImGui. +#define IMGUI_PAYLOAD_TYPE_COLOR_3F "_COL3F" // float[3]: Standard type for colors, without alpha. User code may use this type. +#define IMGUI_PAYLOAD_TYPE_COLOR_4F "_COL4F" // float[4]: Standard type for colors. User code may use this type. + +// A primary data type +enum ImGuiDataType_ +{ + ImGuiDataType_S8, // signed char / char (with sensible compilers) + ImGuiDataType_U8, // unsigned char + ImGuiDataType_S16, // short + ImGuiDataType_U16, // unsigned short + ImGuiDataType_S32, // int + ImGuiDataType_U32, // unsigned int + ImGuiDataType_S64, // long long / __int64 + ImGuiDataType_U64, // unsigned long long / unsigned __int64 + ImGuiDataType_Float, // float + ImGuiDataType_Double, // double + ImGuiDataType_COUNT +}; + +// A cardinal direction +enum ImGuiDir_ +{ + ImGuiDir_None = -1, + ImGuiDir_Left = 0, + ImGuiDir_Right = 1, + ImGuiDir_Up = 2, + ImGuiDir_Down = 3, + ImGuiDir_COUNT +}; + +// A sorting direction +enum ImGuiSortDirection_ +{ + ImGuiSortDirection_None = 0, + ImGuiSortDirection_Ascending = 1, // Ascending = 0->9, A->Z etc. + ImGuiSortDirection_Descending = 2 // Descending = 9->0, Z->A etc. +}; + +// A key identifier (ImGuiKey_XXX or ImGuiMod_XXX value): can represent Keyboard, Mouse and Gamepad values. +// All our named keys are >= 512. Keys value 0 to 511 are left unused as legacy native/opaque key values (< 1.87). +// Since >= 1.89 we increased typing (went from int to enum), some legacy code may need a cast to ImGuiKey. +// Read details about the 1.87 and 1.89 transition : https://github.com/ocornut/imgui/issues/4921 +enum ImGuiKey : int +{ + // Keyboard + ImGuiKey_None = 0, + ImGuiKey_Tab = 512, // == ImGuiKey_NamedKey_BEGIN + ImGuiKey_LeftArrow, + ImGuiKey_RightArrow, + ImGuiKey_UpArrow, + ImGuiKey_DownArrow, + ImGuiKey_PageUp, + ImGuiKey_PageDown, + ImGuiKey_Home, + ImGuiKey_End, + ImGuiKey_Insert, + ImGuiKey_Delete, + ImGuiKey_Backspace, + ImGuiKey_Space, + ImGuiKey_Enter, + ImGuiKey_Escape, + ImGuiKey_LeftCtrl, ImGuiKey_LeftShift, ImGuiKey_LeftAlt, ImGuiKey_LeftSuper, + ImGuiKey_RightCtrl, ImGuiKey_RightShift, ImGuiKey_RightAlt, ImGuiKey_RightSuper, + ImGuiKey_Menu, + ImGuiKey_0, ImGuiKey_1, ImGuiKey_2, ImGuiKey_3, ImGuiKey_4, ImGuiKey_5, ImGuiKey_6, ImGuiKey_7, ImGuiKey_8, ImGuiKey_9, + ImGuiKey_A, ImGuiKey_B, ImGuiKey_C, ImGuiKey_D, ImGuiKey_E, ImGuiKey_F, ImGuiKey_G, ImGuiKey_H, ImGuiKey_I, ImGuiKey_J, + ImGuiKey_K, ImGuiKey_L, ImGuiKey_M, ImGuiKey_N, ImGuiKey_O, ImGuiKey_P, ImGuiKey_Q, ImGuiKey_R, ImGuiKey_S, ImGuiKey_T, + ImGuiKey_U, ImGuiKey_V, ImGuiKey_W, ImGuiKey_X, ImGuiKey_Y, ImGuiKey_Z, + ImGuiKey_F1, ImGuiKey_F2, ImGuiKey_F3, ImGuiKey_F4, ImGuiKey_F5, ImGuiKey_F6, + ImGuiKey_F7, ImGuiKey_F8, ImGuiKey_F9, ImGuiKey_F10, ImGuiKey_F11, ImGuiKey_F12, + ImGuiKey_Apostrophe, // ' + ImGuiKey_Comma, // , + ImGuiKey_Minus, // - + ImGuiKey_Period, // . + ImGuiKey_Slash, // / + ImGuiKey_Semicolon, // ; + ImGuiKey_Equal, // = + ImGuiKey_LeftBracket, // [ + ImGuiKey_Backslash, // \ (this text inhibit multiline comment caused by backslash) + ImGuiKey_RightBracket, // ] + ImGuiKey_GraveAccent, // ` + ImGuiKey_CapsLock, + ImGuiKey_ScrollLock, + ImGuiKey_NumLock, + ImGuiKey_PrintScreen, + ImGuiKey_Pause, + ImGuiKey_Keypad0, ImGuiKey_Keypad1, ImGuiKey_Keypad2, ImGuiKey_Keypad3, ImGuiKey_Keypad4, + ImGuiKey_Keypad5, ImGuiKey_Keypad6, ImGuiKey_Keypad7, ImGuiKey_Keypad8, ImGuiKey_Keypad9, + ImGuiKey_KeypadDecimal, + ImGuiKey_KeypadDivide, + ImGuiKey_KeypadMultiply, + ImGuiKey_KeypadSubtract, + ImGuiKey_KeypadAdd, + ImGuiKey_KeypadEnter, + ImGuiKey_KeypadEqual, + + // Gamepad (some of those are analog values, 0.0f to 1.0f) // NAVIGATION ACTION + // (download controller mapping PNG/PSD at http://dearimgui.org/controls_sheets) + ImGuiKey_GamepadStart, // Menu (Xbox) + (Switch) Start/Options (PS) + ImGuiKey_GamepadBack, // View (Xbox) - (Switch) Share (PS) + ImGuiKey_GamepadFaceLeft, // X (Xbox) Y (Switch) Square (PS) // Tap: Toggle Menu. Hold: Windowing mode (Focus/Move/Resize windows) + ImGuiKey_GamepadFaceRight, // B (Xbox) A (Switch) Circle (PS) // Cancel / Close / Exit + ImGuiKey_GamepadFaceUp, // Y (Xbox) X (Switch) Triangle (PS) // Text Input / On-screen Keyboard + ImGuiKey_GamepadFaceDown, // A (Xbox) B (Switch) Cross (PS) // Activate / Open / Toggle / Tweak + ImGuiKey_GamepadDpadLeft, // D-pad Left // Move / Tweak / Resize Window (in Windowing mode) + ImGuiKey_GamepadDpadRight, // D-pad Right // Move / Tweak / Resize Window (in Windowing mode) + ImGuiKey_GamepadDpadUp, // D-pad Up // Move / Tweak / Resize Window (in Windowing mode) + ImGuiKey_GamepadDpadDown, // D-pad Down // Move / Tweak / Resize Window (in Windowing mode) + ImGuiKey_GamepadL1, // L Bumper (Xbox) L (Switch) L1 (PS) // Tweak Slower / Focus Previous (in Windowing mode) + ImGuiKey_GamepadR1, // R Bumper (Xbox) R (Switch) R1 (PS) // Tweak Faster / Focus Next (in Windowing mode) + ImGuiKey_GamepadL2, // L Trig. (Xbox) ZL (Switch) L2 (PS) [Analog] + ImGuiKey_GamepadR2, // R Trig. (Xbox) ZR (Switch) R2 (PS) [Analog] + ImGuiKey_GamepadL3, // L Stick (Xbox) L3 (Switch) L3 (PS) + ImGuiKey_GamepadR3, // R Stick (Xbox) R3 (Switch) R3 (PS) + ImGuiKey_GamepadLStickLeft, // [Analog] // Move Window (in Windowing mode) + ImGuiKey_GamepadLStickRight, // [Analog] // Move Window (in Windowing mode) + ImGuiKey_GamepadLStickUp, // [Analog] // Move Window (in Windowing mode) + ImGuiKey_GamepadLStickDown, // [Analog] // Move Window (in Windowing mode) + ImGuiKey_GamepadRStickLeft, // [Analog] + ImGuiKey_GamepadRStickRight, // [Analog] + ImGuiKey_GamepadRStickUp, // [Analog] + ImGuiKey_GamepadRStickDown, // [Analog] + + // Aliases: Mouse Buttons (auto-submitted from AddMouseButtonEvent() calls) + // - This is mirroring the data also written to io.MouseDown[], io.MouseWheel, in a format allowing them to be accessed via standard key API. + ImGuiKey_MouseLeft, ImGuiKey_MouseRight, ImGuiKey_MouseMiddle, ImGuiKey_MouseX1, ImGuiKey_MouseX2, ImGuiKey_MouseWheelX, ImGuiKey_MouseWheelY, + + // [Internal] Reserved for mod storage + ImGuiKey_ReservedForModCtrl, ImGuiKey_ReservedForModShift, ImGuiKey_ReservedForModAlt, ImGuiKey_ReservedForModSuper, + ImGuiKey_COUNT, + + // Keyboard Modifiers (explicitly submitted by backend via AddKeyEvent() calls) + // - This is mirroring the data also written to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper, in a format allowing + // them to be accessed via standard key API, allowing calls such as IsKeyPressed(), IsKeyReleased(), querying duration etc. + // - Code polling every key (e.g. an interface to detect a key press for input mapping) might want to ignore those + // and prefer using the real keys (e.g. ImGuiKey_LeftCtrl, ImGuiKey_RightCtrl instead of ImGuiMod_Ctrl). + // - In theory the value of keyboard modifiers should be roughly equivalent to a logical or of the equivalent left/right keys. + // In practice: it's complicated; mods are often provided from different sources. Keyboard layout, IME, sticky keys and + // backends tend to interfere and break that equivalence. The safer decision is to relay that ambiguity down to the end-user... + ImGuiMod_None = 0, + ImGuiMod_Ctrl = 1 << 12, // Ctrl + ImGuiMod_Shift = 1 << 13, // Shift + ImGuiMod_Alt = 1 << 14, // Option/Menu + ImGuiMod_Super = 1 << 15, // Cmd/Super/Windows + ImGuiMod_Shortcut = 1 << 11, // Alias for Ctrl (non-macOS) _or_ Super (macOS). + ImGuiMod_Mask_ = 0xF800, // 5-bits + + // [Internal] Prior to 1.87 we required user to fill io.KeysDown[512] using their own native index + the io.KeyMap[] array. + // We are ditching this method but keeping a legacy path for user code doing e.g. IsKeyPressed(MY_NATIVE_KEY_CODE) + ImGuiKey_NamedKey_BEGIN = 512, + ImGuiKey_NamedKey_END = ImGuiKey_COUNT, + ImGuiKey_NamedKey_COUNT = ImGuiKey_NamedKey_END - ImGuiKey_NamedKey_BEGIN, +#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO + ImGuiKey_KeysData_SIZE = ImGuiKey_NamedKey_COUNT, // Size of KeysData[]: only hold named keys + ImGuiKey_KeysData_OFFSET = ImGuiKey_NamedKey_BEGIN, // First key stored in io.KeysData[0]. Accesses to io.KeysData[] must use (key - ImGuiKey_KeysData_OFFSET). +#else + ImGuiKey_KeysData_SIZE = ImGuiKey_COUNT, // Size of KeysData[]: hold legacy 0..512 keycodes + named keys + ImGuiKey_KeysData_OFFSET = 0, // First key stored in io.KeysData[0]. Accesses to io.KeysData[] must use (key - ImGuiKey_KeysData_OFFSET). +#endif + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiKey_ModCtrl = ImGuiMod_Ctrl, ImGuiKey_ModShift = ImGuiMod_Shift, ImGuiKey_ModAlt = ImGuiMod_Alt, ImGuiKey_ModSuper = ImGuiMod_Super, // Renamed in 1.89 + ImGuiKey_KeyPadEnter = ImGuiKey_KeypadEnter, // Renamed in 1.87 +#endif +}; + +#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO +// OBSOLETED in 1.88 (from July 2022): ImGuiNavInput and io.NavInputs[]. +// Official backends between 1.60 and 1.86: will keep working and feed gamepad inputs as long as IMGUI_DISABLE_OBSOLETE_KEYIO is not set. +// Custom backends: feed gamepad inputs via io.AddKeyEvent() and ImGuiKey_GamepadXXX enums. +enum ImGuiNavInput +{ + ImGuiNavInput_Activate, ImGuiNavInput_Cancel, ImGuiNavInput_Input, ImGuiNavInput_Menu, ImGuiNavInput_DpadLeft, ImGuiNavInput_DpadRight, ImGuiNavInput_DpadUp, ImGuiNavInput_DpadDown, + ImGuiNavInput_LStickLeft, ImGuiNavInput_LStickRight, ImGuiNavInput_LStickUp, ImGuiNavInput_LStickDown, ImGuiNavInput_FocusPrev, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakSlow, ImGuiNavInput_TweakFast, + ImGuiNavInput_COUNT, +}; +#endif + +// Configuration flags stored in io.ConfigFlags. Set by user/application. +enum ImGuiConfigFlags_ +{ + ImGuiConfigFlags_None = 0, + ImGuiConfigFlags_NavEnableKeyboard = 1 << 0, // Master keyboard navigation enable flag. + ImGuiConfigFlags_NavEnableGamepad = 1 << 1, // Master gamepad navigation enable flag. Backend also needs to set ImGuiBackendFlags_HasGamepad. + ImGuiConfigFlags_NavEnableSetMousePos = 1 << 2, // Instruct navigation to move the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is awkward. Will update io.MousePos and set io.WantSetMousePos=true. If enabled you MUST honor io.WantSetMousePos requests in your backend, otherwise ImGui will react as if the mouse is jumping around back and forth. + ImGuiConfigFlags_NavNoCaptureKeyboard = 1 << 3, // Instruct navigation to not set the io.WantCaptureKeyboard flag when io.NavActive is set. + ImGuiConfigFlags_NoMouse = 1 << 4, // Instruct imgui to clear mouse position/buttons in NewFrame(). This allows ignoring the mouse information set by the backend. + ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, // Instruct backend to not alter mouse cursor shape and visibility. Use if the backend cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead. + + // User storage (to allow your backend/engine to communicate to code that may be shared between multiple projects. Those flags are NOT used by core Dear ImGui) + ImGuiConfigFlags_IsSRGB = 1 << 20, // Application is SRGB-aware. + ImGuiConfigFlags_IsTouchScreen = 1 << 21, // Application is using a touch screen instead of a mouse. +}; + +// Backend capabilities flags stored in io.BackendFlags. Set by imgui_impl_xxx or custom backend. +enum ImGuiBackendFlags_ +{ + ImGuiBackendFlags_None = 0, + ImGuiBackendFlags_HasGamepad = 1 << 0, // Backend Platform supports gamepad and currently has one connected. + ImGuiBackendFlags_HasMouseCursors = 1 << 1, // Backend Platform supports honoring GetMouseCursor() value to change the OS cursor shape. + ImGuiBackendFlags_HasSetMousePos = 1 << 2, // Backend Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if ImGuiConfigFlags_NavEnableSetMousePos is set). + ImGuiBackendFlags_RendererHasVtxOffset = 1 << 3, // Backend Renderer supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bit indices. +}; + +// Enumeration for PushStyleColor() / PopStyleColor() +enum ImGuiCol_ +{ + ImGuiCol_Text, + ImGuiCol_TextDisabled, + ImGuiCol_WindowBg, // Background of normal windows + ImGuiCol_ChildBg, // Background of child windows + ImGuiCol_PopupBg, // Background of popups, menus, tooltips windows + ImGuiCol_Border, + ImGuiCol_BorderShadow, + ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input + ImGuiCol_FrameBgHovered, + ImGuiCol_FrameBgActive, + ImGuiCol_TitleBg, + ImGuiCol_TitleBgActive, + ImGuiCol_TitleBgCollapsed, + ImGuiCol_MenuBarBg, + ImGuiCol_ScrollbarBg, + ImGuiCol_ScrollbarGrab, + ImGuiCol_ScrollbarGrabHovered, + ImGuiCol_ScrollbarGrabActive, + ImGuiCol_CheckMark, + ImGuiCol_SliderGrab, + ImGuiCol_SliderGrabActive, + ImGuiCol_Button, + ImGuiCol_ButtonHovered, + ImGuiCol_ButtonActive, + ImGuiCol_Header, // Header* colors are used for CollapsingHeader, TreeNode, Selectable, MenuItem + ImGuiCol_HeaderHovered, + ImGuiCol_HeaderActive, + ImGuiCol_Separator, + ImGuiCol_SeparatorHovered, + ImGuiCol_SeparatorActive, + ImGuiCol_ResizeGrip, // Resize grip in lower-right and lower-left corners of windows. + ImGuiCol_ResizeGripHovered, + ImGuiCol_ResizeGripActive, + ImGuiCol_Tab, // TabItem in a TabBar + ImGuiCol_TabHovered, + ImGuiCol_TabActive, + ImGuiCol_TabUnfocused, + ImGuiCol_TabUnfocusedActive, + ImGuiCol_PlotLines, + ImGuiCol_PlotLinesHovered, + ImGuiCol_PlotHistogram, + ImGuiCol_PlotHistogramHovered, + ImGuiCol_TableHeaderBg, // Table header background + ImGuiCol_TableBorderStrong, // Table outer and header borders (prefer using Alpha=1.0 here) + ImGuiCol_TableBorderLight, // Table inner borders (prefer using Alpha=1.0 here) + ImGuiCol_TableRowBg, // Table row background (even rows) + ImGuiCol_TableRowBgAlt, // Table row background (odd rows) + ImGuiCol_TextSelectedBg, + ImGuiCol_DragDropTarget, // Rectangle highlighting a drop target + ImGuiCol_NavHighlight, // Gamepad/keyboard: current highlighted item + ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB + ImGuiCol_NavWindowingDimBg, // Darken/colorize entire screen behind the CTRL+TAB window list, when active + ImGuiCol_ModalWindowDimBg, // Darken/colorize entire screen behind a modal window, when one is active + ImGuiCol_COUNT +}; + +// Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the ImGuiStyle structure. +// - The enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code. +// During initialization or between frames, feel free to just poke into ImGuiStyle directly. +// - Tip: Use your programming IDE navigation facilities on the names in the _second column_ below to find the actual members and their description. +// In Visual Studio IDE: CTRL+comma ("Edit.GoToAll") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. +// With Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols in comments. +// - When changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type. +enum ImGuiStyleVar_ +{ + // Enum name --------------------- // Member in ImGuiStyle structure (see ImGuiStyle for descriptions) + ImGuiStyleVar_Alpha, // float Alpha + ImGuiStyleVar_DisabledAlpha, // float DisabledAlpha + ImGuiStyleVar_WindowPadding, // ImVec2 WindowPadding + ImGuiStyleVar_WindowRounding, // float WindowRounding + ImGuiStyleVar_WindowBorderSize, // float WindowBorderSize + ImGuiStyleVar_WindowMinSize, // ImVec2 WindowMinSize + ImGuiStyleVar_WindowTitleAlign, // ImVec2 WindowTitleAlign + ImGuiStyleVar_ChildRounding, // float ChildRounding + ImGuiStyleVar_ChildBorderSize, // float ChildBorderSize + ImGuiStyleVar_PopupRounding, // float PopupRounding + ImGuiStyleVar_PopupBorderSize, // float PopupBorderSize + ImGuiStyleVar_FramePadding, // ImVec2 FramePadding + ImGuiStyleVar_FrameRounding, // float FrameRounding + ImGuiStyleVar_FrameBorderSize, // float FrameBorderSize + ImGuiStyleVar_ItemSpacing, // ImVec2 ItemSpacing + ImGuiStyleVar_ItemInnerSpacing, // ImVec2 ItemInnerSpacing + ImGuiStyleVar_IndentSpacing, // float IndentSpacing + ImGuiStyleVar_CellPadding, // ImVec2 CellPadding + ImGuiStyleVar_ScrollbarSize, // float ScrollbarSize + ImGuiStyleVar_ScrollbarRounding, // float ScrollbarRounding + ImGuiStyleVar_GrabMinSize, // float GrabMinSize + ImGuiStyleVar_GrabRounding, // float GrabRounding + ImGuiStyleVar_TabRounding, // float TabRounding + ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign + ImGuiStyleVar_SelectableTextAlign, // ImVec2 SelectableTextAlign + ImGuiStyleVar_COUNT +}; + +// Flags for InvisibleButton() [extended in imgui_internal.h] +enum ImGuiButtonFlags_ +{ + ImGuiButtonFlags_None = 0, + ImGuiButtonFlags_MouseButtonLeft = 1 << 0, // React on left mouse button (default) + ImGuiButtonFlags_MouseButtonRight = 1 << 1, // React on right mouse button + ImGuiButtonFlags_MouseButtonMiddle = 1 << 2, // React on center mouse button + + // [Internal] + ImGuiButtonFlags_MouseButtonMask_ = ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight | ImGuiButtonFlags_MouseButtonMiddle, + ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft, +}; + +// Flags for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton() +enum ImGuiColorEditFlags_ +{ + ImGuiColorEditFlags_None = 0, + ImGuiColorEditFlags_NoAlpha = 1 << 1, // // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (will only read 3 components from the input pointer). + ImGuiColorEditFlags_NoPicker = 1 << 2, // // ColorEdit: disable picker when clicking on color square. + ImGuiColorEditFlags_NoOptions = 1 << 3, // // ColorEdit: disable toggling options menu when right-clicking on inputs/small preview. + ImGuiColorEditFlags_NoSmallPreview = 1 << 4, // // ColorEdit, ColorPicker: disable color square preview next to the inputs. (e.g. to show only the inputs) + ImGuiColorEditFlags_NoInputs = 1 << 5, // // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview color square). + ImGuiColorEditFlags_NoTooltip = 1 << 6, // // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview. + ImGuiColorEditFlags_NoLabel = 1 << 7, // // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker). + ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small color square preview instead. + ImGuiColorEditFlags_NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target. ColorButton: disable drag and drop source. + ImGuiColorEditFlags_NoBorder = 1 << 10, // // ColorButton: disable border (which is enforced by default) + + // User Options (right-click on widget to change some of them). + ImGuiColorEditFlags_AlphaBar = 1 << 16, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. + ImGuiColorEditFlags_AlphaPreview = 1 << 17, // // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque. + ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 18, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque. + ImGuiColorEditFlags_HDR = 1 << 19, // // (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA edition (note: you probably want to use ImGuiColorEditFlags_Float flag as well). + ImGuiColorEditFlags_DisplayRGB = 1 << 20, // [Display] // ColorEdit: override _display_ type among RGB/HSV/Hex. ColorPicker: select any combination using one or more of RGB/HSV/Hex. + ImGuiColorEditFlags_DisplayHSV = 1 << 21, // [Display] // " + ImGuiColorEditFlags_DisplayHex = 1 << 22, // [Display] // " + ImGuiColorEditFlags_Uint8 = 1 << 23, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255. + ImGuiColorEditFlags_Float = 1 << 24, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers. + ImGuiColorEditFlags_PickerHueBar = 1 << 25, // [Picker] // ColorPicker: bar for Hue, rectangle for Sat/Value. + ImGuiColorEditFlags_PickerHueWheel = 1 << 26, // [Picker] // ColorPicker: wheel for Hue, triangle for Sat/Value. + ImGuiColorEditFlags_InputRGB = 1 << 27, // [Input] // ColorEdit, ColorPicker: input and output data in RGB format. + ImGuiColorEditFlags_InputHSV = 1 << 28, // [Input] // ColorEdit, ColorPicker: input and output data in HSV format. + + // Defaults Options. You can set application defaults using SetColorEditOptions(). The intent is that you probably don't want to + // override them in most of your calls. Let the user choose via the option menu and/or call SetColorEditOptions() once during startup. + ImGuiColorEditFlags_DefaultOptions_ = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_PickerHueBar, + + // [Internal] Masks + ImGuiColorEditFlags_DisplayMask_ = ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_DisplayHex, + ImGuiColorEditFlags_DataTypeMask_ = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_Float, + ImGuiColorEditFlags_PickerMask_ = ImGuiColorEditFlags_PickerHueWheel | ImGuiColorEditFlags_PickerHueBar, + ImGuiColorEditFlags_InputMask_ = ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_InputHSV, + + // Obsolete names (will be removed) + // ImGuiColorEditFlags_RGB = ImGuiColorEditFlags_DisplayRGB, ImGuiColorEditFlags_HSV = ImGuiColorEditFlags_DisplayHSV, ImGuiColorEditFlags_HEX = ImGuiColorEditFlags_DisplayHex // [renamed in 1.69] +}; + +// Flags for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. +// We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them. +// (Those are per-item flags. There are shared flags in ImGuiIO: io.ConfigDragClickToInputText) +enum ImGuiSliderFlags_ +{ + ImGuiSliderFlags_None = 0, + ImGuiSliderFlags_AlwaysClamp = 1 << 4, // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. + ImGuiSliderFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits. + ImGuiSliderFlags_NoRoundToFormat = 1 << 6, // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits) + ImGuiSliderFlags_NoInput = 1 << 7, // Disable CTRL+Click or Enter key allowing to input text directly into the widget + ImGuiSliderFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. + + // Obsolete names (will be removed) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiSliderFlags_ClampOnInput = ImGuiSliderFlags_AlwaysClamp, // [renamed in 1.79] +#endif +}; + +// Identify a mouse button. +// Those values are guaranteed to be stable and we frequently use 0/1 directly. Named enums provided for convenience. +enum ImGuiMouseButton_ +{ + ImGuiMouseButton_Left = 0, + ImGuiMouseButton_Right = 1, + ImGuiMouseButton_Middle = 2, + ImGuiMouseButton_COUNT = 5 +}; + +// Enumeration for GetMouseCursor() +// User code may request backend to display given cursor by calling SetMouseCursor(), which is why we have some cursors that are marked unused here +enum ImGuiMouseCursor_ +{ + ImGuiMouseCursor_None = -1, + ImGuiMouseCursor_Arrow = 0, + ImGuiMouseCursor_TextInput, // When hovering over InputText, etc. + ImGuiMouseCursor_ResizeAll, // (Unused by Dear ImGui functions) + ImGuiMouseCursor_ResizeNS, // When hovering over a horizontal border + ImGuiMouseCursor_ResizeEW, // When hovering over a vertical border or a column + ImGuiMouseCursor_ResizeNESW, // When hovering over the bottom-left corner of a window + ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window + ImGuiMouseCursor_Hand, // (Unused by Dear ImGui functions. Use for e.g. hyperlinks) + ImGuiMouseCursor_NotAllowed, // When hovering something with disallowed interaction. Usually a crossed circle. + ImGuiMouseCursor_COUNT +}; + +// Enumeration for ImGui::SetWindow***(), SetNextWindow***(), SetNextItem***() functions +// Represent a condition. +// Important: Treat as a regular enum! Do NOT combine multiple values using binary operators! All the functions above treat 0 as a shortcut to ImGuiCond_Always. +enum ImGuiCond_ +{ + ImGuiCond_None = 0, // No condition (always set the variable), same as _Always + ImGuiCond_Always = 1 << 0, // No condition (always set the variable), same as _None + ImGuiCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call will succeed) + ImGuiCond_FirstUseEver = 1 << 2, // Set the variable if the object/window has no persistently saved data (no entry in .ini file) + ImGuiCond_Appearing = 1 << 3, // Set the variable if the object/window is appearing after being hidden/inactive (or the first time) +}; + +//----------------------------------------------------------------------------- +// [SECTION] Helpers: Memory allocations macros, ImVector<> +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// IM_MALLOC(), IM_FREE(), IM_NEW(), IM_PLACEMENT_NEW(), IM_DELETE() +// We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax. +// Defining a custom placement new() with a custom parameter allows us to bypass including which on some platforms complains when user has disabled exceptions. +//----------------------------------------------------------------------------- + +struct ImNewWrapper {}; +inline void* operator new(size_t, ImNewWrapper, void* ptr) { return ptr; } +inline void operator delete(void*, ImNewWrapper, void*) {} // This is only required so we can use the symmetrical new() +#define IM_ALLOC(_SIZE) ImGui::MemAlloc(_SIZE) +#define IM_FREE(_PTR) ImGui::MemFree(_PTR) +#define IM_PLACEMENT_NEW(_PTR) new(ImNewWrapper(), _PTR) +#define IM_NEW(_TYPE) new(ImNewWrapper(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE +template void IM_DELETE(T* p) { if (p) { p->~T(); ImGui::MemFree(p); } } + +//----------------------------------------------------------------------------- +// ImVector<> +// Lightweight std::vector<>-like class to avoid dragging dependencies (also, some implementations of STL with debug enabled are absurdly slow, we bypass it so our code runs fast in debug). +//----------------------------------------------------------------------------- +// - You generally do NOT need to care or use this ever. But we need to make it available in imgui.h because some of our public structures are relying on it. +// - We use std-like naming convention here, which is a little unusual for this codebase. +// - Important: clear() frees memory, resize(0) keep the allocated buffer. We use resize(0) a lot to intentionally recycle allocated buffers across frames and amortize our costs. +// - Important: our implementation does NOT call C++ constructors/destructors, we treat everything as raw data! This is intentional but be extra mindful of that, +// Do NOT use this class as a std::vector replacement in your own code! Many of the structures used by dear imgui can be safely initialized by a zero-memset. +//----------------------------------------------------------------------------- + +IM_MSVC_RUNTIME_CHECKS_OFF +template +struct ImVector +{ + int Size; + int Capacity; + T* Data; + + // Provide standard typedefs but we don't use them ourselves. + typedef T value_type; + typedef value_type* iterator; + typedef const value_type* const_iterator; + + // Constructors, destructor + inline ImVector() { Size = Capacity = 0; Data = NULL; } + inline ImVector(const ImVector& src) { Size = Capacity = 0; Data = NULL; operator=(src); } + inline ImVector& operator=(const ImVector& src) { clear(); resize(src.Size); if (src.Data) memcpy(Data, src.Data, (size_t)Size * sizeof(T)); return *this; } + inline ~ImVector() { if (Data) IM_FREE(Data); } // Important: does not destruct anything + + inline void clear() { if (Data) { Size = Capacity = 0; IM_FREE(Data); Data = NULL; } } // Important: does not destruct anything + inline void clear_delete() { for (int n = 0; n < Size; n++) IM_DELETE(Data[n]); clear(); } // Important: never called automatically! always explicit. + inline void clear_destruct() { for (int n = 0; n < Size; n++) Data[n].~T(); clear(); } // Important: never called automatically! always explicit. + + inline bool empty() const { return Size == 0; } + inline int size() const { return Size; } + inline int size_in_bytes() const { return Size * (int)sizeof(T); } + inline int max_size() const { return 0x7FFFFFFF / (int)sizeof(T); } + inline int capacity() const { return Capacity; } + inline T& operator[](int i) { IM_ASSERT(i >= 0 && i < Size); return Data[i]; } + inline const T& operator[](int i) const { IM_ASSERT(i >= 0 && i < Size); return Data[i]; } + + inline T* begin() { return Data; } + inline const T* begin() const { return Data; } + inline T* end() { return Data + Size; } + inline const T* end() const { return Data + Size; } + inline T& front() { IM_ASSERT(Size > 0); return Data[0]; } + inline const T& front() const { IM_ASSERT(Size > 0); return Data[0]; } + inline T& back() { IM_ASSERT(Size > 0); return Data[Size - 1]; } + inline const T& back() const { IM_ASSERT(Size > 0); return Data[Size - 1]; } + inline void swap(ImVector& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; T* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; } + + inline int _grow_capacity(int sz) const { int new_capacity = Capacity ? (Capacity + Capacity / 2) : 8; return new_capacity > sz ? new_capacity : sz; } + inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; } + inline void resize(int new_size, const T& v) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); if (new_size > Size) for (int n = Size; n < new_size; n++) memcpy(&Data[n], &v, sizeof(v)); Size = new_size; } + inline void shrink(int new_size) { IM_ASSERT(new_size <= Size); Size = new_size; } // Resize a vector to a smaller size, guaranteed not to cause a reallocation + inline void reserve(int new_capacity) { if (new_capacity <= Capacity) return; T* new_data = (T*)IM_ALLOC((size_t)new_capacity * sizeof(T)); if (Data) { memcpy(new_data, Data, (size_t)Size * sizeof(T)); IM_FREE(Data); } Data = new_data; Capacity = new_capacity; } + inline void reserve_discard(int new_capacity) { if (new_capacity <= Capacity) return; if (Data) IM_FREE(Data); Data = (T*)IM_ALLOC((size_t)new_capacity * sizeof(T)); Capacity = new_capacity; } + + // NB: It is illegal to call push_back/push_front/insert with a reference pointing inside the ImVector data itself! e.g. v.push_back(v[10]) is forbidden. + inline void push_back(const T& v) { if (Size == Capacity) reserve(_grow_capacity(Size + 1)); memcpy(&Data[Size], &v, sizeof(v)); Size++; } + inline void pop_back() { IM_ASSERT(Size > 0); Size--; } + inline void push_front(const T& v) { if (Size == 0) push_back(v); else insert(Data, v); } + inline T* erase(const T* it) { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(T)); Size--; return Data + off; } + inline T* erase(const T* it, const T* it_last){ IM_ASSERT(it >= Data && it < Data + Size && it_last >= it && it_last <= Data + Size); const ptrdiff_t count = it_last - it; const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + count, ((size_t)Size - (size_t)off - (size_t)count) * sizeof(T)); Size -= (int)count; return Data + off; } + inline T* erase_unsorted(const T* it) { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; if (it < Data + Size - 1) memcpy(Data + off, Data + Size - 1, sizeof(T)); Size--; return Data + off; } + inline T* insert(const T* it, const T& v) { IM_ASSERT(it >= Data && it <= Data + Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(_grow_capacity(Size + 1)); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(T)); memcpy(&Data[off], &v, sizeof(v)); Size++; return Data + off; } + inline bool contains(const T& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data++ == v) return true; return false; } + inline T* find(const T& v) { T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; } + inline const T* find(const T& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; } + inline bool find_erase(const T& v) { const T* it = find(v); if (it < Data + Size) { erase(it); return true; } return false; } + inline bool find_erase_unsorted(const T& v) { const T* it = find(v); if (it < Data + Size) { erase_unsorted(it); return true; } return false; } + inline int index_from_ptr(const T* it) const { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; return (int)off; } +}; +IM_MSVC_RUNTIME_CHECKS_RESTORE + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiStyle +//----------------------------------------------------------------------------- +// You may modify the ImGui::GetStyle() main instance during initialization and before NewFrame(). +// During the frame, use ImGui::PushStyleVar(ImGuiStyleVar_XXXX)/PopStyleVar() to alter the main style values, +// and ImGui::PushStyleColor(ImGuiCol_XXX)/PopStyleColor() for colors. +//----------------------------------------------------------------------------- + +struct ImGuiStyle +{ + float Alpha; // Global alpha applies to everything in Dear ImGui. + float DisabledAlpha; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. + ImVec2 WindowPadding; // Padding within a window. + float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended. + float WindowBorderSize; // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). + ImVec2 WindowMinSize; // Minimum window size. This is a global setting. If you want to constrain individual windows, use SetNextWindowSizeConstraints(). + ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered. + ImGuiDir WindowMenuButtonPosition; // Side of the collapsing/docking button in the title bar (None/Left/Right). Defaults to ImGuiDir_Left. + float ChildRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows. + float ChildBorderSize; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). + float PopupRounding; // Radius of popup window corners rounding. (Note that tooltip windows use WindowRounding) + float PopupBorderSize; // Thickness of border around popup/tooltip windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). + ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets). + float FrameRounding; // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets). + float FrameBorderSize; // Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). + ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines. + ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label). + ImVec2 CellPadding; // Padding within a table cell + ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! + float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). + float ColumnsMinSpacing; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). + float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar. + float ScrollbarRounding; // Radius of grab corners for scrollbar. + float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar. + float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. + float LogSliderDeadzone; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. + float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. + float TabBorderSize; // Thickness of border around tabs. + float TabMinWidthForCloseButton; // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. + ImGuiDir ColorButtonPosition; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. + ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered). + ImVec2 SelectableTextAlign; // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. + ImVec2 DisplayWindowPadding; // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows. + ImVec2 DisplaySafeAreaPadding; // If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly! + float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. + bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). + bool AntiAliasedLinesUseTex; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). Latched at the beginning of the frame (copied to ImDrawList). + bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). + float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. + float CircleTessellationMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. + ImVec4 Colors[ImGuiCol_COUNT]; + + IMGUI_API ImGuiStyle(); + IMGUI_API void ScaleAllSizes(float scale_factor); +}; + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiIO +//----------------------------------------------------------------------------- +// Communicate most settings and inputs/outputs to Dear ImGui using this structure. +// Access via ImGui::GetIO(). Read 'Programmer guide' section in .cpp file for general usage. +//----------------------------------------------------------------------------- + +// [Internal] Storage used by IsKeyDown(), IsKeyPressed() etc functions. +// If prior to 1.87 you used io.KeysDownDuration[] (which was marked as internal), you should use GetKeyData(key)->DownDuration and *NOT* io.KeysData[key]->DownDuration. +struct ImGuiKeyData +{ + bool Down; // True for if key is down + float DownDuration; // Duration the key has been down (<0.0f: not pressed, 0.0f: just pressed, >0.0f: time held) + float DownDurationPrev; // Last frame duration the key has been down + float AnalogValue; // 0.0f..1.0f for gamepad values +}; + +struct ImGuiIO +{ + //------------------------------------------------------------------ + // Configuration // Default value + //------------------------------------------------------------------ + + ImGuiConfigFlags ConfigFlags; // = 0 // See ImGuiConfigFlags_ enum. Set by user/application. Gamepad/keyboard navigation options, etc. + ImGuiBackendFlags BackendFlags; // = 0 // See ImGuiBackendFlags_ enum. Set by backend (imgui_impl_xxx files or custom backend) to communicate features supported by the backend. + ImVec2 DisplaySize; // // Main display size, in pixels (generally == GetMainViewport()->Size). May change every frame. + float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds. May change every frame. + float IniSavingRate; // = 5.0f // Minimum time between saving positions/sizes to .ini file, in seconds. + const char* IniFilename; // = "imgui.ini" // Path to .ini file (important: default "imgui.ini" is relative to current working dir!). Set NULL to disable automatic .ini loading/saving or if you want to manually call LoadIniSettingsXXX() / SaveIniSettingsXXX() functions. + const char* LogFilename; // = "imgui_log.txt"// Path to .log file (default parameter to ImGui::LogToFile when no file is specified). + float MouseDoubleClickTime; // = 0.30f // Time for a double-click, in seconds. + float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels. + float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging. + float KeyRepeatDelay; // = 0.275f // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.). + float KeyRepeatRate; // = 0.050f // When holding a key/button, rate at which it repeats, in seconds. + float HoverDelayNormal; // = 0.30 sec // Delay on hovering before IsItemHovered(ImGuiHoveredFlags_DelayNormal) returns true. + float HoverDelayShort; // = 0.10 sec // Delay on hovering before IsItemHovered(ImGuiHoveredFlags_DelayShort) returns true. + void* UserData; // = NULL // Store your own data. + + ImFontAtlas*Fonts; // // Font atlas: load, rasterize and pack one or more fonts into a single texture. + float FontGlobalScale; // = 1.0f // Global scale all fonts + bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel. + ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. + ImVec2 DisplayFramebufferScale; // = (1, 1) // For retina display or other situations where window coordinates are different from framebuffer coordinates. This generally ends up in ImDrawData::FramebufferScale. + + // Miscellaneous options + bool MouseDrawCursor; // = false // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations. + bool ConfigMacOSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl. + bool ConfigInputTrickleEventQueue; // = true // Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates. + bool ConfigInputTextCursorBlink; // = true // Enable blinking cursor (optional as some users consider it to be distracting). + bool ConfigInputTextEnterKeepActive; // = false // [BETA] Pressing Enter will keep item active and select contents (single-line only). + bool ConfigDragClickToInputText; // = false // [BETA] Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving). Not desirable on devices without a keyboard. + bool ConfigWindowsResizeFromEdges; // = true // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag) + bool ConfigWindowsMoveFromTitleBarOnly; // = false // Enable allowing to move windows only when clicking on their title bar. Does not apply to windows without a title bar. + float ConfigMemoryCompactTimer; // = 60.0f // Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable. + + //------------------------------------------------------------------ + // Platform Functions + // (the imgui_impl_xxxx backend files are setting those up for you) + //------------------------------------------------------------------ + + // Optional: Platform/Renderer backend name (informational only! will be displayed in About Window) + User data for backend/wrappers to store their own stuff. + const char* BackendPlatformName; // = NULL + const char* BackendRendererName; // = NULL + void* BackendPlatformUserData; // = NULL // User data for platform backend + void* BackendRendererUserData; // = NULL // User data for renderer backend + void* BackendLanguageUserData; // = NULL // User data for non C++ programming language backend + + // Optional: Access OS clipboard + // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) + const char* (*GetClipboardTextFn)(void* user_data); + void (*SetClipboardTextFn)(void* user_data, const char* text); + void* ClipboardUserData; + + // Optional: Notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME on Windows) + // (default to use native imm32 api on Windows) + void (*SetPlatformImeDataFn)(ImGuiViewport* viewport, ImGuiPlatformImeData* data); +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + void* ImeWindowHandle; // = NULL // [Obsolete] Set ImGuiViewport::PlatformHandleRaw instead. Set this to your HWND to get automatic IME cursor positioning. +#else + void* _UnusedPadding; // Unused field to keep data structure the same size. +#endif + + //------------------------------------------------------------------ + // Input - Call before calling NewFrame() + //------------------------------------------------------------------ + + // Input Functions + IMGUI_API void AddKeyEvent(ImGuiKey key, bool down); // Queue a new key down/up event. Key should be "translated" (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character) + IMGUI_API void AddKeyAnalogEvent(ImGuiKey key, bool down, float v); // Queue a new key down/up event for analog values (e.g. ImGuiKey_Gamepad_ values). Dead-zones should be handled by the backend. + IMGUI_API void AddMousePosEvent(float x, float y); // Queue a mouse position update. Use -FLT_MAX,-FLT_MAX to signify no mouse (e.g. app not focused and not hovered) + IMGUI_API void AddMouseButtonEvent(int button, bool down); // Queue a mouse button change + IMGUI_API void AddMouseWheelEvent(float wh_x, float wh_y); // Queue a mouse wheel update + IMGUI_API void AddFocusEvent(bool focused); // Queue a gain/loss of focus for the application (generally based on OS/platform focus of your window) + IMGUI_API void AddInputCharacter(unsigned int c); // Queue a new character input + IMGUI_API void AddInputCharacterUTF16(ImWchar16 c); // Queue a new character input from a UTF-16 character, it can be a surrogate + IMGUI_API void AddInputCharactersUTF8(const char* str); // Queue a new characters input from a UTF-8 string + + IMGUI_API void SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index = -1); // [Optional] Specify index for legacy <1.87 IsKeyXXX() functions with native indices + specify native keycode, scancode. + IMGUI_API void SetAppAcceptingEvents(bool accepting_events); // Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen. + IMGUI_API void ClearInputCharacters(); // [Internal] Clear the text input buffer manually + IMGUI_API void ClearInputKeys(); // [Internal] Release all keys + + //------------------------------------------------------------------ + // Output - Updated by NewFrame() or EndFrame()/Render() + // (when reading from the io.WantCaptureMouse, io.WantCaptureKeyboard flags to dispatch your inputs, it is + // generally easier and more correct to use their state BEFORE calling NewFrame(). See FAQ for details!) + //------------------------------------------------------------------ + + bool WantCaptureMouse; // Set when Dear ImGui will use mouse inputs, in this case do not dispatch them to your main game/application (either way, always pass on mouse inputs to imgui). (e.g. unclicked mouse is hovering over an imgui window, widget is active, mouse was clicked over an imgui window, etc.). + bool WantCaptureKeyboard; // Set when Dear ImGui will use keyboard inputs, in this case do not dispatch them to your main game/application (either way, always pass keyboard inputs to imgui). (e.g. InputText active, or an imgui window is focused and navigation is enabled, etc.). + bool WantTextInput; // Mobile/console: when set, you may display an on-screen keyboard. This is set by Dear ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active). + bool WantSetMousePos; // MousePos has been altered, backend should reposition mouse on next frame. Rarely used! Set only when ImGuiConfigFlags_NavEnableSetMousePos flag is enabled. + bool WantSaveIniSettings; // When manual .ini load/save is active (io.IniFilename == NULL), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. Important: clear io.WantSaveIniSettings yourself after saving! + bool NavActive; // Keyboard/Gamepad navigation is currently allowed (will handle ImGuiKey_NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags_NoNavInputs flag. + bool NavVisible; // Keyboard/Gamepad navigation is visible and allowed (will handle ImGuiKey_NavXXX events). + float Framerate; // Estimate of application framerate (rolling average over 60 frames, based on io.DeltaTime), in frame per second. Solely for convenience. Slow applications may not want to use a moving average or may want to reset underlying buffers occasionally. + int MetricsRenderVertices; // Vertices output during last call to Render() + int MetricsRenderIndices; // Indices output during last call to Render() = number of triangles * 3 + int MetricsRenderWindows; // Number of visible windows + int MetricsActiveWindows; // Number of active windows + int MetricsActiveAllocations; // Number of active allocations, updated by MemAlloc/MemFree based on current context. May be off if you have multiple imgui contexts. + ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are invalid (-FLT_MAX,-FLT_MAX), so a disappearing/reappearing mouse won't have a huge delta. + + // Legacy: before 1.87, we required backend to fill io.KeyMap[] (imgui->native map) during initialization and io.KeysDown[] (native indices) every frame. + // This is still temporarily supported as a legacy feature. However the new preferred scheme is for backend to call io.AddKeyEvent(). + // Old (<1.87): ImGui::IsKeyPressed(ImGui::GetIO().KeyMap[ImGuiKey_Space]) --> New (1.87+) ImGui::IsKeyPressed(ImGuiKey_Space) +#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO + int KeyMap[ImGuiKey_COUNT]; // [LEGACY] Input: map of indices into the KeysDown[512] entries array which represent your "native" keyboard state. The first 512 are now unused and should be kept zero. Legacy backend will write into KeyMap[] using ImGuiKey_ indices which are always >512. + bool KeysDown[ImGuiKey_COUNT]; // [LEGACY] Input: Keyboard keys that are pressed (ideally left in the "native" order your engine has access to keyboard keys, so you can use your own defines/enums for keys). This used to be [512] sized. It is now ImGuiKey_COUNT to allow legacy io.KeysDown[GetKeyIndex(...)] to work without an overflow. + float NavInputs[ImGuiNavInput_COUNT]; // [LEGACY] Since 1.88, NavInputs[] was removed. Backends from 1.60 to 1.86 won't build. Feed gamepad inputs via io.AddKeyEvent() and ImGuiKey_GamepadXXX enums. +#endif + + //------------------------------------------------------------------ + // [Internal] Dear ImGui will maintain those fields. Forward compatibility not guaranteed! + //------------------------------------------------------------------ + + // Main Input State + // (this block used to be written by backend, since 1.87 it is best to NOT write to those directly, call the AddXXX functions above instead) + // (reading from those variables is fair game, as they are extremely unlikely to be moving anywhere) + ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX, -FLT_MAX) if mouse is unavailable (on another screen, etc.) + bool MouseDown[5]; // Mouse buttons: 0=left, 1=right, 2=middle + extras (ImGuiMouseButton_COUNT == 5). Dear ImGui mostly uses left and right buttons. Other buttons allow us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. + float MouseWheel; // Mouse wheel Vertical: 1 unit scrolls about 5 lines text. + float MouseWheelH; // Mouse wheel Horizontal. Most users don't have a mouse with a horizontal wheel, may not be filled by all backends. + bool KeyCtrl; // Keyboard modifier down: Control + bool KeyShift; // Keyboard modifier down: Shift + bool KeyAlt; // Keyboard modifier down: Alt + bool KeySuper; // Keyboard modifier down: Cmd/Super/Windows + + // Other state maintained from data above + IO function calls + ImGuiKeyChord KeyMods; // Key mods flags (any of ImGuiMod_Ctrl/ImGuiMod_Shift/ImGuiMod_Alt/ImGuiMod_Super flags, same as io.KeyCtrl/KeyShift/KeyAlt/KeySuper but merged into flags. DOES NOT CONTAINS ImGuiMod_Shortcut which is pretranslated). Read-only, updated by NewFrame() + ImGuiKeyData KeysData[ImGuiKey_KeysData_SIZE]; // Key state for all known keys. Use IsKeyXXX() functions to access this. + bool WantCaptureMouseUnlessPopupClose; // Alternative to WantCaptureMouse: (WantCaptureMouse == true && WantCaptureMouseUnlessPopupClose == false) when a click over void is expected to close a popup. + ImVec2 MousePosPrev; // Previous mouse position (note that MouseDelta is not necessary == MousePos-MousePosPrev, in case either position is invalid) + ImVec2 MouseClickedPos[5]; // Position at time of clicking + double MouseClickedTime[5]; // Time of last click (used to figure out double-click) + bool MouseClicked[5]; // Mouse button went from !Down to Down (same as MouseClickedCount[x] != 0) + bool MouseDoubleClicked[5]; // Has mouse button been double-clicked? (same as MouseClickedCount[x] == 2) + ImU16 MouseClickedCount[5]; // == 0 (not clicked), == 1 (same as MouseClicked[]), == 2 (double-clicked), == 3 (triple-clicked) etc. when going from !Down to Down + ImU16 MouseClickedLastCount[5]; // Count successive number of clicks. Stays valid after mouse release. Reset after another click is done. + bool MouseReleased[5]; // Mouse button went from Down to !Down + bool MouseDownOwned[5]; // Track if button was clicked inside a dear imgui window or over void blocked by a popup. We don't request mouse capture from the application if click started outside ImGui bounds. + bool MouseDownOwnedUnlessPopupClose[5]; // Track if button was clicked inside a dear imgui window. + float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked) + float MouseDownDurationPrev[5]; // Previous time the mouse button has been down + float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the clicking point (used for moving thresholds) + float PenPressure; // Touch/Pen pressure (0.0f to 1.0f, should be >0.0f only when MouseDown[0] == true). Helper storage currently unused by Dear ImGui. + bool AppFocusLost; // Only modify via AddFocusEvent() + bool AppAcceptingEvents; // Only modify via SetAppAcceptingEvents() + ImS8 BackendUsingLegacyKeyArrays; // -1: unknown, 0: using AddKeyEvent(), 1: using legacy io.KeysDown[] + bool BackendUsingLegacyNavInputArray; // 0: using AddKeyAnalogEvent(), 1: writing to legacy io.NavInputs[] directly + ImWchar16 InputQueueSurrogate; // For AddInputCharacterUTF16() + ImVector InputQueueCharacters; // Queue of _characters_ input (obtained by platform backend). Fill using AddInputCharacter() helper. + + IMGUI_API ImGuiIO(); +}; + +//----------------------------------------------------------------------------- +// [SECTION] Misc data structures +//----------------------------------------------------------------------------- + +// Shared state of InputText(), passed as an argument to your callback when a ImGuiInputTextFlags_Callback* flag is used. +// The callback function should return 0 by default. +// Callbacks (follow a flag name and see comments in ImGuiInputTextFlags_ declarations for more details) +// - ImGuiInputTextFlags_CallbackEdit: Callback on buffer edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active) +// - ImGuiInputTextFlags_CallbackAlways: Callback on each iteration +// - ImGuiInputTextFlags_CallbackCompletion: Callback on pressing TAB +// - ImGuiInputTextFlags_CallbackHistory: Callback on pressing Up/Down arrows +// - ImGuiInputTextFlags_CallbackCharFilter: Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. +// - ImGuiInputTextFlags_CallbackResize: Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. +struct ImGuiInputTextCallbackData +{ + ImGuiInputTextFlags EventFlag; // One ImGuiInputTextFlags_Callback* // Read-only + ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only + void* UserData; // What user passed to InputText() // Read-only + + // Arguments for the different callback events + // - To modify the text buffer in a callback, prefer using the InsertChars() / DeleteChars() function. InsertChars() will take care of calling the resize callback if necessary. + // - If you know your edits are not going to resize the underlying buffer allocation, you may modify the contents of 'Buf[]' directly. You need to update 'BufTextLen' accordingly (0 <= BufTextLen < BufSize) and set 'BufDirty'' to true so InputText can update its internal state. + ImWchar EventChar; // Character input // Read-write // [CharFilter] Replace character with another one, or set to zero to drop. return 1 is equivalent to setting EventChar=0; + ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only // [Completion,History] + char* Buf; // Text buffer // Read-write // [Resize] Can replace pointer / [Completion,History,Always] Only write to pointed data, don't replace the actual pointer! + int BufTextLen; // Text length (in bytes) // Read-write // [Resize,Completion,History,Always] Exclude zero-terminator storage. In C land: == strlen(some_text), in C++ land: string.length() + int BufSize; // Buffer size (in bytes) = capacity+1 // Read-only // [Resize,Completion,History,Always] Include zero-terminator storage. In C land == ARRAYSIZE(my_char_array), in C++ land: string.capacity()+1 + bool BufDirty; // Set if you modify Buf/BufTextLen! // Write // [Completion,History,Always] + int CursorPos; // // Read-write // [Completion,History,Always] + int SelectionStart; // // Read-write // [Completion,History,Always] == to SelectionEnd when no selection) + int SelectionEnd; // // Read-write // [Completion,History,Always] + + // Helper functions for text manipulation. + // Use those function to benefit from the CallbackResize behaviors. Calling those function reset the selection. + IMGUI_API ImGuiInputTextCallbackData(); + IMGUI_API void DeleteChars(int pos, int bytes_count); + IMGUI_API void InsertChars(int pos, const char* text, const char* text_end = NULL); + void SelectAll() { SelectionStart = 0; SelectionEnd = BufTextLen; } + void ClearSelection() { SelectionStart = SelectionEnd = BufTextLen; } + bool HasSelection() const { return SelectionStart != SelectionEnd; } +}; + +// Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin(). +// NB: For basic min/max size constraint on each axis you don't need to use the callback! The SetNextWindowSizeConstraints() parameters are enough. +struct ImGuiSizeCallbackData +{ + void* UserData; // Read-only. What user passed to SetNextWindowSizeConstraints(). Generally store an integer or float in here (need reinterpret_cast<>). + ImVec2 Pos; // Read-only. Window position, for reference. + ImVec2 CurrentSize; // Read-only. Current window size. + ImVec2 DesiredSize; // Read-write. Desired size, based on user's mouse position. Write to this field to restrain resizing. +}; + +// Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload() +struct ImGuiPayload +{ + // Members + void* Data; // Data (copied and owned by dear imgui) + int DataSize; // Data size + + // [Internal] + ImGuiID SourceId; // Source item id + ImGuiID SourceParentId; // Source parent id (if available) + int DataFrameCount; // Data timestamp + char DataType[32 + 1]; // Data type tag (short user-supplied string, 32 characters max) + bool Preview; // Set when AcceptDragDropPayload() was called and mouse has been hovering the target item (nb: handle overlapping drag targets) + bool Delivery; // Set when AcceptDragDropPayload() was called and mouse button is released over the target item. + + ImGuiPayload() { Clear(); } + void Clear() { SourceId = SourceParentId = 0; Data = NULL; DataSize = 0; memset(DataType, 0, sizeof(DataType)); DataFrameCount = -1; Preview = Delivery = false; } + bool IsDataType(const char* type) const { return DataFrameCount != -1 && strcmp(type, DataType) == 0; } + bool IsPreview() const { return Preview; } + bool IsDelivery() const { return Delivery; } +}; + +// Sorting specification for one column of a table (sizeof == 12 bytes) +struct ImGuiTableColumnSortSpecs +{ + ImGuiID ColumnUserID; // User id of the column (if specified by a TableSetupColumn() call) + ImS16 ColumnIndex; // Index of the column + ImS16 SortOrder; // Index within parent ImGuiTableSortSpecs (always stored in order starting from 0, tables sorted on a single criteria will always have a 0 here) + ImGuiSortDirection SortDirection : 8; // ImGuiSortDirection_Ascending or ImGuiSortDirection_Descending (you can use this or SortSign, whichever is more convenient for your sort function) + + ImGuiTableColumnSortSpecs() { memset(this, 0, sizeof(*this)); } +}; + +// Sorting specifications for a table (often handling sort specs for a single column, occasionally more) +// Obtained by calling TableGetSortSpecs(). +// When 'SpecsDirty == true' you can sort your data. It will be true with sorting specs have changed since last call, or the first time. +// Make sure to set 'SpecsDirty = false' after sorting, else you may wastefully sort your data every frame! +struct ImGuiTableSortSpecs +{ + const ImGuiTableColumnSortSpecs* Specs; // Pointer to sort spec array. + int SpecsCount; // Sort spec count. Most often 1. May be > 1 when ImGuiTableFlags_SortMulti is enabled. May be == 0 when ImGuiTableFlags_SortTristate is enabled. + bool SpecsDirty; // Set to true when specs have changed since last time! Use this to sort again, then clear the flag. + + ImGuiTableSortSpecs() { memset(this, 0, sizeof(*this)); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, ImColor) +//----------------------------------------------------------------------------- + +// Helper: Unicode defines +#define IM_UNICODE_CODEPOINT_INVALID 0xFFFD // Invalid Unicode code point (standard value). +#ifdef IMGUI_USE_WCHAR32 +#define IM_UNICODE_CODEPOINT_MAX 0x10FFFF // Maximum Unicode code point supported by this build. +#else +#define IM_UNICODE_CODEPOINT_MAX 0xFFFF // Maximum Unicode code point supported by this build. +#endif + +// Helper: Execute a block of code at maximum once a frame. Convenient if you want to quickly create a UI within deep-nested code that runs multiple times every frame. +// Usage: static ImGuiOnceUponAFrame oaf; if (oaf) ImGui::Text("This will be called only once per frame"); +struct ImGuiOnceUponAFrame +{ + ImGuiOnceUponAFrame() { RefFrame = -1; } + mutable int RefFrame; + operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; } +}; + +// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" +struct ImGuiTextFilter +{ + IMGUI_API ImGuiTextFilter(const char* default_filter = ""); + IMGUI_API bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build + IMGUI_API bool PassFilter(const char* text, const char* text_end = NULL) const; + IMGUI_API void Build(); + void Clear() { InputBuf[0] = 0; Build(); } + bool IsActive() const { return !Filters.empty(); } + + // [Internal] + struct ImGuiTextRange + { + const char* b; + const char* e; + + ImGuiTextRange() { b = e = NULL; } + ImGuiTextRange(const char* _b, const char* _e) { b = _b; e = _e; } + bool empty() const { return b == e; } + IMGUI_API void split(char separator, ImVector* out) const; + }; + char InputBuf[256]; + ImVectorFilters; + int CountGrep; +}; + +// Helper: Growable text buffer for logging/accumulating text +// (this could be called 'ImGuiTextBuilder' / 'ImGuiStringBuilder') +struct ImGuiTextBuffer +{ + ImVector Buf; + IMGUI_API static char EmptyString[1]; + + ImGuiTextBuffer() { } + inline char operator[](int i) const { IM_ASSERT(Buf.Data != NULL); return Buf.Data[i]; } + const char* begin() const { return Buf.Data ? &Buf.front() : EmptyString; } + const char* end() const { return Buf.Data ? &Buf.back() : EmptyString; } // Buf is zero-terminated, so end() will point on the zero-terminator + int size() const { return Buf.Size ? Buf.Size - 1 : 0; } + bool empty() const { return Buf.Size <= 1; } + void clear() { Buf.clear(); } + void reserve(int capacity) { Buf.reserve(capacity); } + const char* c_str() const { return Buf.Data ? Buf.Data : EmptyString; } + IMGUI_API void append(const char* str, const char* str_end = NULL); + IMGUI_API void appendf(const char* fmt, ...) IM_FMTARGS(2); + IMGUI_API void appendfv(const char* fmt, va_list args) IM_FMTLIST(2); +}; + +// Helper: Key->Value storage +// Typically you don't have to worry about this since a storage is held within each Window. +// We use it to e.g. store collapse state for a tree (Int 0/1) +// This is optimized for efficient lookup (dichotomy into a contiguous buffer) and rare insertion (typically tied to user interactions aka max once a frame) +// You can use it as custom user storage for temporary values. Declare your own storage if, for example: +// - You want to manipulate the open/close state of a particular sub-tree in your interface (tree node uses Int 0/1 to store their state). +// - You want to store custom debug data easily without adding or editing structures in your code (probably not efficient, but convenient) +// Types are NOT stored, so it is up to you to make sure your Key don't collide with different types. +struct ImGuiStorage +{ + // [Internal] + struct ImGuiStoragePair + { + ImGuiID key; + union { int val_i; float val_f; void* val_p; }; + ImGuiStoragePair(ImGuiID _key, int _val_i) { key = _key; val_i = _val_i; } + ImGuiStoragePair(ImGuiID _key, float _val_f) { key = _key; val_f = _val_f; } + ImGuiStoragePair(ImGuiID _key, void* _val_p) { key = _key; val_p = _val_p; } + }; + + ImVector Data; + + // - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N) + // - Set***() functions find pair, insertion on demand if missing. + // - Sorted insertion is costly, paid once. A typical frame shouldn't need to insert any new pair. + void Clear() { Data.clear(); } + IMGUI_API int GetInt(ImGuiID key, int default_val = 0) const; + IMGUI_API void SetInt(ImGuiID key, int val); + IMGUI_API bool GetBool(ImGuiID key, bool default_val = false) const; + IMGUI_API void SetBool(ImGuiID key, bool val); + IMGUI_API float GetFloat(ImGuiID key, float default_val = 0.0f) const; + IMGUI_API void SetFloat(ImGuiID key, float val); + IMGUI_API void* GetVoidPtr(ImGuiID key) const; // default_val is NULL + IMGUI_API void SetVoidPtr(ImGuiID key, void* val); + + // - Get***Ref() functions finds pair, insert on demand if missing, return pointer. Useful if you intend to do Get+Set. + // - References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. + // - A typical use case where this is convenient for quick hacking (e.g. add storage during a live Edit&Continue session if you can't modify existing struct) + // float* pvar = ImGui::GetFloatRef(key); ImGui::SliderFloat("var", pvar, 0, 100.0f); some_var += *pvar; + IMGUI_API int* GetIntRef(ImGuiID key, int default_val = 0); + IMGUI_API bool* GetBoolRef(ImGuiID key, bool default_val = false); + IMGUI_API float* GetFloatRef(ImGuiID key, float default_val = 0.0f); + IMGUI_API void** GetVoidPtrRef(ImGuiID key, void* default_val = NULL); + + // Use on your own storage if you know only integer are being stored (open/close all tree nodes) + IMGUI_API void SetAllInt(int val); + + // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once. + IMGUI_API void BuildSortByKey(); +}; + +// Helper: Manually clip large list of items. +// If you have lots evenly spaced items and you have random access to the list, you can perform coarse +// clipping based on visibility to only submit items that are in view. +// The clipper calculates the range of visible items and advance the cursor to compensate for the non-visible items we have skipped. +// (Dear ImGui already clip items based on their bounds but: it needs to first layout the item to do so, and generally +// fetching/submitting your own data incurs additional cost. Coarse clipping using ImGuiListClipper allows you to easily +// scale using lists with tens of thousands of items without a problem) +// Usage: +// ImGuiListClipper clipper; +// clipper.Begin(1000); // We have 1000 elements, evenly spaced. +// while (clipper.Step()) +// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) +// ImGui::Text("line number %d", i); +// Generally what happens is: +// - Clipper lets you process the first element (DisplayStart = 0, DisplayEnd = 1) regardless of it being visible or not. +// - User code submit that one element. +// - Clipper can measure the height of the first element +// - Clipper calculate the actual range of elements to display based on the current clipping rectangle, position the cursor before the first visible element. +// - User code submit visible elements. +// - The clipper also handles various subtleties related to keyboard/gamepad navigation, wrapping etc. +struct ImGuiListClipper +{ + int DisplayStart; // First item to display, updated by each call to Step() + int DisplayEnd; // End of items to display (exclusive) + int ItemsCount; // [Internal] Number of items + float ItemsHeight; // [Internal] Height of item after a first step and item submission can calculate it + float StartPosY; // [Internal] Cursor position at the time of Begin() or after table frozen rows are all processed + void* TempData; // [Internal] Internal data + + // items_count: Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step) + // items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetFrameHeightWithSpacing(). + IMGUI_API ImGuiListClipper(); + IMGUI_API ~ImGuiListClipper(); + IMGUI_API void Begin(int items_count, float items_height = -1.0f); + IMGUI_API void End(); // Automatically called on the last call of Step() that returns false. + IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items. + + // Call ForceDisplayRangeByIndices() before first call to Step() if you need a range of items to be displayed regardless of visibility. + IMGUI_API void ForceDisplayRangeByIndices(int item_min, int item_max); // item_max is exclusive e.g. use (42, 42+1) to make item 42 always visible BUT due to alignment/padding of certain items it is likely that an extra item may be included on either end of the display range. + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + inline ImGuiListClipper(int items_count, float items_height = -1.0f) { memset(this, 0, sizeof(*this)); ItemsCount = -1; Begin(items_count, items_height); } // [removed in 1.79] +#endif +}; + +// Helpers macros to generate 32-bit encoded colors +// User can declare their own format by #defining the 5 _SHIFT/_MASK macros in their imconfig file. +#ifndef IM_COL32_R_SHIFT +#ifdef IMGUI_USE_BGRA_PACKED_COLOR +#define IM_COL32_R_SHIFT 16 +#define IM_COL32_G_SHIFT 8 +#define IM_COL32_B_SHIFT 0 +#define IM_COL32_A_SHIFT 24 +#define IM_COL32_A_MASK 0xFF000000 +#else +#define IM_COL32_R_SHIFT 0 +#define IM_COL32_G_SHIFT 8 +#define IM_COL32_B_SHIFT 16 +#define IM_COL32_A_SHIFT 24 +#define IM_COL32_A_MASK 0xFF000000 +#endif +#endif +#define IM_COL32(R,G,B,A) (((ImU32)(A)<> IM_COL32_R_SHIFT) & 0xFF) * sc; Value.y = (float)((rgba >> IM_COL32_G_SHIFT) & 0xFF) * sc; Value.z = (float)((rgba >> IM_COL32_B_SHIFT) & 0xFF) * sc; Value.w = (float)((rgba >> IM_COL32_A_SHIFT) & 0xFF) * sc; } + inline operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); } + inline operator ImVec4() const { return Value; } + + // FIXME-OBSOLETE: May need to obsolete/cleanup those helpers. + inline void SetHSV(float h, float s, float v, float a = 1.0f){ ImGui::ColorConvertHSVtoRGB(h, s, v, Value.x, Value.y, Value.z); Value.w = a; } + static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r, g, b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r, g, b, a); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData) +// Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. +//----------------------------------------------------------------------------- + +// The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoBakedLines to disable baking. +#ifndef IM_DRAWLIST_TEX_LINES_WIDTH_MAX +#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (63) +#endif + +// ImDrawCallback: Draw callbacks for advanced uses [configurable type: override in imconfig.h] +// NB: You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering, +// you can poke into the draw list for that! Draw callback may be useful for example to: +// A) Change your GPU render state, +// B) render a complex 3D scene inside a UI element without an intermediate texture/render target, etc. +// The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) { cmd.UserCallback(parent_list, cmd); } else { RenderTriangles() }' +// If you want to override the signature of ImDrawCallback, you can simply use e.g. '#define ImDrawCallback MyDrawCallback' (in imconfig.h) + update rendering backend accordingly. +#ifndef ImDrawCallback +typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd); +#endif + +// Special Draw callback value to request renderer backend to reset the graphics/render state. +// The renderer backend needs to handle this special value, otherwise it will crash trying to call a function at this address. +// This is useful for example if you submitted callbacks which you know have altered the render state and you want it to be restored. +// It is not done by default because they are many perfectly useful way of altering render state for imgui contents (e.g. changing shader/blending settings before an Image call). +#define ImDrawCallback_ResetRenderState (ImDrawCallback)(-1) + +// Typically, 1 command = 1 GPU draw call (unless command is a callback) +// - VtxOffset: When 'io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset' is enabled, +// this fields allow us to render meshes larger than 64K vertices while keeping 16-bit indices. +// Backends made for <1.71. will typically ignore the VtxOffset fields. +// - The ClipRect/TextureId/VtxOffset fields must be contiguous as we memcmp() them together (this is asserted for). +struct ImDrawCmd +{ + ImVec4 ClipRect; // 4*4 // Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates + ImTextureID TextureId; // 4-8 // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas. + unsigned int VtxOffset; // 4 // Start offset in vertex buffer. ImGuiBackendFlags_RendererHasVtxOffset: always 0, otherwise may be >0 to support meshes larger than 64K vertices with 16-bit indices. + unsigned int IdxOffset; // 4 // Start offset in index buffer. + unsigned int ElemCount; // 4 // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[]. + ImDrawCallback UserCallback; // 4-8 // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. + void* UserCallbackData; // 4-8 // The draw callback code can access this. + + ImDrawCmd() { memset(this, 0, sizeof(*this)); } // Also ensure our padding fields are zeroed + + // Since 1.83: returns ImTextureID associated with this draw call. Warning: DO NOT assume this is always same as 'TextureId' (we will change this function for an upcoming feature) + inline ImTextureID GetTexID() const { return TextureId; } +}; + +// Vertex layout +#ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT +struct ImDrawVert +{ + ImVec2 pos; + ImVec2 uv; + ImU32 col; +}; +#else +// You can override the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h +// The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine. +// The type has to be described within the macro (you can either declare the struct or use a typedef). This is because ImVec2/ImU32 are likely not declared at the time you'd want to set your type up. +// NOTE: IMGUI DOESN'T CLEAR THE STRUCTURE AND DOESN'T CALL A CONSTRUCTOR SO ANY CUSTOM FIELD WILL BE UNINITIALIZED. IF YOU ADD EXTRA FIELDS (SUCH AS A 'Z' COORDINATES) YOU WILL NEED TO CLEAR THEM DURING RENDER OR TO IGNORE THEM. +IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; +#endif + +// [Internal] For use by ImDrawList +struct ImDrawCmdHeader +{ + ImVec4 ClipRect; + ImTextureID TextureId; + unsigned int VtxOffset; +}; + +// [Internal] For use by ImDrawListSplitter +struct ImDrawChannel +{ + ImVector _CmdBuffer; + ImVector _IdxBuffer; +}; + + +// Split/Merge functions are used to split the draw list into different layers which can be drawn into out of order. +// This is used by the Columns/Tables API, so items of each column can be batched together in a same draw call. +struct ImDrawListSplitter +{ + int _Current; // Current channel number (0) + int _Count; // Number of active channels (1+) + ImVector _Channels; // Draw channels (not resized down so _Count might be < Channels.Size) + + inline ImDrawListSplitter() { memset(this, 0, sizeof(*this)); } + inline ~ImDrawListSplitter() { ClearFreeMemory(); } + inline void Clear() { _Current = 0; _Count = 1; } // Do not clear Channels[] so our allocations are reused next frame + IMGUI_API void ClearFreeMemory(); + IMGUI_API void Split(ImDrawList* draw_list, int count); + IMGUI_API void Merge(ImDrawList* draw_list); + IMGUI_API void SetCurrentChannel(ImDrawList* draw_list, int channel_idx); +}; + +// Flags for ImDrawList functions +// (Legacy: bit 0 must always correspond to ImDrawFlags_Closed to be backward compatible with old API using a bool. Bits 1..3 must be unused) +enum ImDrawFlags_ +{ + ImDrawFlags_None = 0, + ImDrawFlags_Closed = 1 << 0, // PathStroke(), AddPolyline(): specify that shape should be closed (Important: this is always == 1 for legacy reason) + ImDrawFlags_RoundCornersTopLeft = 1 << 4, // AddRect(), AddRectFilled(), PathRect(): enable rounding top-left corner only (when rounding > 0.0f, we default to all corners). Was 0x01. + ImDrawFlags_RoundCornersTopRight = 1 << 5, // AddRect(), AddRectFilled(), PathRect(): enable rounding top-right corner only (when rounding > 0.0f, we default to all corners). Was 0x02. + ImDrawFlags_RoundCornersBottomLeft = 1 << 6, // AddRect(), AddRectFilled(), PathRect(): enable rounding bottom-left corner only (when rounding > 0.0f, we default to all corners). Was 0x04. + ImDrawFlags_RoundCornersBottomRight = 1 << 7, // AddRect(), AddRectFilled(), PathRect(): enable rounding bottom-right corner only (when rounding > 0.0f, we default to all corners). Wax 0x08. + ImDrawFlags_RoundCornersNone = 1 << 8, // AddRect(), AddRectFilled(), PathRect(): disable rounding on all corners (when rounding > 0.0f). This is NOT zero, NOT an implicit flag! + ImDrawFlags_RoundCornersTop = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight, + ImDrawFlags_RoundCornersBottom = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, + ImDrawFlags_RoundCornersLeft = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersTopLeft, + ImDrawFlags_RoundCornersRight = ImDrawFlags_RoundCornersBottomRight | ImDrawFlags_RoundCornersTopRight, + ImDrawFlags_RoundCornersAll = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight | ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, + ImDrawFlags_RoundCornersDefault_ = ImDrawFlags_RoundCornersAll, // Default to ALL corners if none of the _RoundCornersXX flags are specified. + ImDrawFlags_RoundCornersMask_ = ImDrawFlags_RoundCornersAll | ImDrawFlags_RoundCornersNone, +}; + +// Flags for ImDrawList instance. Those are set automatically by ImGui:: functions from ImGuiIO settings, and generally not manipulated directly. +// It is however possible to temporarily alter flags between calls to ImDrawList:: functions. +enum ImDrawListFlags_ +{ + ImDrawListFlags_None = 0, + ImDrawListFlags_AntiAliasedLines = 1 << 0, // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles) + ImDrawListFlags_AntiAliasedLinesUseTex = 1 << 1, // Enable anti-aliased lines/borders using textures when possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). + ImDrawListFlags_AntiAliasedFill = 1 << 2, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). + ImDrawListFlags_AllowVtxOffset = 1 << 3, // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. +}; + +// Draw command list +// This is the low-level list of polygons that ImGui:: functions are filling. At the end of the frame, +// all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering. +// Each dear imgui window contains its own ImDrawList. You can use ImGui::GetWindowDrawList() to +// access the current window draw list and draw custom primitives. +// You can interleave normal ImGui:: calls and adding primitives to the current draw list. +// In single viewport mode, top-left is == GetMainViewport()->Pos (generally 0,0), bottom-right is == GetMainViewport()->Pos+Size (generally io.DisplaySize). +// You are totally free to apply whatever transformation matrix to want to the data (depending on the use of the transformation you may want to apply it to ClipRect as well!) +// Important: Primitives are always added to the list and not culled (culling is done at higher-level by ImGui:: functions), if you use this API a lot consider coarse culling your drawn objects. +struct ImDrawList +{ + // This is what you have to render + ImVector CmdBuffer; // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback. + ImVector IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those + ImVector VtxBuffer; // Vertex buffer. + ImDrawListFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive. + + // [Internal, used while building lists] + unsigned int _VtxCurrentIdx; // [Internal] generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0. + ImDrawListSharedData* _Data; // Pointer to shared draw data (you can use ImGui::GetDrawListSharedData() to get the one from current ImGui context) + const char* _OwnerName; // Pointer to owner window's name for debugging + ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + ImVector _ClipRectStack; // [Internal] + ImVector _TextureIdStack; // [Internal] + ImVector _Path; // [Internal] current path building + ImDrawCmdHeader _CmdHeader; // [Internal] template of active commands. Fields should match those of CmdBuffer.back(). + ImDrawListSplitter _Splitter; // [Internal] for channels api (note: prefer using your own persistent instance of ImDrawListSplitter!) + float _FringeScale; // [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content + + // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData() or create and use your own ImDrawListSharedData (so you can use ImDrawList without ImGui) + ImDrawList(ImDrawListSharedData* shared_data) { memset(this, 0, sizeof(*this)); _Data = shared_data; } + + ~ImDrawList() { _ClearFreeMemory(); } + IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) + IMGUI_API void PushClipRectFullScreen(); + IMGUI_API void PopClipRect(); + IMGUI_API void PushTextureID(ImTextureID texture_id); + IMGUI_API void PopTextureID(); + inline ImVec2 GetClipRectMin() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.x, cr.y); } + inline ImVec2 GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); } + + // Primitives + // - Filled shapes must always use clockwise winding order. The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. + // - For rectangular primitives, "p_min" and "p_max" represent the upper-left and lower-right corners. + // - For circle primitives, use "num_segments == 0" to automatically calculate tessellation (preferred). + // In older versions (until Dear ImGui 1.77) the AddCircle functions defaulted to num_segments == 12. + // In future versions we will use textures to provide cheaper and higher-quality circles. + // Use AddNgon() and AddNgonFilled() functions if you need to guarantee a specific number of sides. + IMGUI_API void AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawFlags flags = 0, float thickness = 1.0f); // a: upper-left, b: lower-right (== upper-left + size) + IMGUI_API void AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawFlags flags = 0); // a: upper-left, b: lower-right (== upper-left + size) + IMGUI_API void AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_max, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); + IMGUI_API void AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col); + IMGUI_API void AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col); + IMGUI_API void AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments = 0, float thickness = 1.0f); + IMGUI_API void AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments = 0); + IMGUI_API void AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness = 1.0f); + IMGUI_API void AddNgonFilled(const ImVec2& center, float radius, ImU32 col, int num_segments); + IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL); + IMGUI_API void AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL); + IMGUI_API void AddPolyline(const ImVec2* points, int num_points, ImU32 col, ImDrawFlags flags, float thickness); + IMGUI_API void AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col); + IMGUI_API void AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0); // Cubic Bezier (4 control points) + IMGUI_API void AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments = 0); // Quadratic Bezier (3 control points) + + // Image primitives + // - Read FAQ to understand what ImTextureID is. + // - "p_min" and "p_max" represent the upper-left and lower-right corners of the rectangle. + // - "uv_min" and "uv_max" represent the normalized texture coordinates to use for those corners. Using (0,0)->(1,1) texture coordinates will generally display the entire texture. + IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min = ImVec2(0, 0), const ImVec2& uv_max = ImVec2(1, 1), ImU32 col = IM_COL32_WHITE); + IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1 = ImVec2(0, 0), const ImVec2& uv2 = ImVec2(1, 0), const ImVec2& uv3 = ImVec2(1, 1), const ImVec2& uv4 = ImVec2(0, 1), ImU32 col = IM_COL32_WHITE); + IMGUI_API void AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags = 0); + + // Stateful path API, add points then finish with PathFillConvex() or PathStroke() + // - Filled shapes must always use clockwise winding order. The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. + inline void PathClear() { _Path.Size = 0; } + inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); } + inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path.Data[_Path.Size - 1], &pos, 8) != 0) _Path.push_back(pos); } + inline void PathFillConvex(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col); _Path.Size = 0; } + inline void PathStroke(ImU32 col, ImDrawFlags flags = 0, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, flags, thickness); _Path.Size = 0; } + IMGUI_API void PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments = 0); + IMGUI_API void PathArcToFast(const ImVec2& center, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle + IMGUI_API void PathBezierCubicCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0); // Cubic Bezier (4 control points) + IMGUI_API void PathBezierQuadraticCurveTo(const ImVec2& p2, const ImVec2& p3, int num_segments = 0); // Quadratic Bezier (3 control points) + IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, ImDrawFlags flags = 0); + + // Advanced + IMGUI_API void AddCallback(ImDrawCallback callback, void* callback_data); // Your rendering function must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles. + IMGUI_API void AddDrawCmd(); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible + IMGUI_API ImDrawList* CloneOutput() const; // Create a clone of the CmdBuffer/IdxBuffer/VtxBuffer. + + // Advanced: Channels + // - Use to split render into layers. By switching channels to can render out-of-order (e.g. submit FG primitives before BG primitives) + // - Use to minimize draw calls (e.g. if going back-and-forth between multiple clipping rectangles, prefer to append into separate channels then merge at the end) + // - FIXME-OBSOLETE: This API shouldn't have been in ImDrawList in the first place! + // Prefer using your own persistent instance of ImDrawListSplitter as you can stack them. + // Using the ImDrawList::ChannelsXXXX you cannot stack a split over another. + inline void ChannelsSplit(int count) { _Splitter.Split(this, count); } + inline void ChannelsMerge() { _Splitter.Merge(this); } + inline void ChannelsSetCurrent(int n) { _Splitter.SetCurrentChannel(this, n); } + + // Advanced: Primitives allocations + // - We render triangles (three vertices) + // - All primitives needs to be reserved via PrimReserve() beforehand. + IMGUI_API void PrimReserve(int idx_count, int vtx_count); + IMGUI_API void PrimUnreserve(int idx_count, int vtx_count); + IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles) + IMGUI_API void PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col); + IMGUI_API void PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col); + inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; } + inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; } + inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } // Write vertex with unique index + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + inline void AddBezierCurve(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0) { AddBezierCubic(p1, p2, p3, p4, col, thickness, num_segments); } // OBSOLETED in 1.80 (Jan 2021) + inline void PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0) { PathBezierCubicCurveTo(p2, p3, p4, num_segments); } // OBSOLETED in 1.80 (Jan 2021) +#endif + + // [Internal helpers] + IMGUI_API void _ResetForNewFrame(); + IMGUI_API void _ClearFreeMemory(); + IMGUI_API void _PopUnusedDrawCmd(); + IMGUI_API void _TryMergeDrawCmds(); + IMGUI_API void _OnChangedClipRect(); + IMGUI_API void _OnChangedTextureID(); + IMGUI_API void _OnChangedVtxOffset(); + IMGUI_API int _CalcCircleAutoSegmentCount(float radius) const; + IMGUI_API void _PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step); + IMGUI_API void _PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments); +}; + +// All draw data to render a Dear ImGui frame +// (NB: the style and the naming convention here is a little inconsistent, we currently preserve them for backward compatibility purpose, +// as this is one of the oldest structure exposed by the library! Basically, ImDrawList == CmdList) +struct ImDrawData +{ + bool Valid; // Only valid after Render() is called and before the next NewFrame() is called. + int CmdListsCount; // Number of ImDrawList* to render + int TotalIdxCount; // For convenience, sum of all ImDrawList's IdxBuffer.Size + int TotalVtxCount; // For convenience, sum of all ImDrawList's VtxBuffer.Size + ImDrawList** CmdLists; // Array of ImDrawList* to render. The ImDrawList are owned by ImGuiContext and only pointed to from here. + ImVec2 DisplayPos; // Top-left position of the viewport to render (== top-left of the orthogonal projection matrix to use) (== GetMainViewport()->Pos for the main viewport, == (0.0) in most single-viewport applications) + ImVec2 DisplaySize; // Size of the viewport to render (== GetMainViewport()->Size for the main viewport, == io.DisplaySize in most single-viewport applications) + ImVec2 FramebufferScale; // Amount of pixels for each unit of DisplaySize. Based on io.DisplayFramebufferScale. Generally (1,1) on normal display, (2,2) on OSX with Retina display. + + // Functions + ImDrawData() { Clear(); } + void Clear() { memset(this, 0, sizeof(*this)); } // The ImDrawList are owned by ImGuiContext! + IMGUI_API void DeIndexAllBuffers(); // Helper to convert all buffers from indexed to non-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! + IMGUI_API void ScaleClipRects(const ImVec2& fb_scale); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than Dear ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. +}; + +//----------------------------------------------------------------------------- +// [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFontGlyphRangesBuilder, ImFont) +//----------------------------------------------------------------------------- + +struct ImFontConfig +{ + void* FontData; // // TTF/OTF data + int FontDataSize; // // TTF/OTF data size + bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself). + int FontNo; // 0 // Index of font within TTF/OTF file + float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height). + int OversampleH; // 3 // Rasterize at higher quality for sub-pixel positioning. Note the difference between 2 and 3 is minimal so you can reduce this to 2 to save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. + int OversampleV; // 1 // Rasterize at higher quality for sub-pixel positioning. This is not really useful as we don't use sub-pixel positions on the Y axis. + bool PixelSnapH; // false // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. + ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs. Only X axis is supported for now. + ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input. + const ImWchar* GlyphRanges; // NULL // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. + float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font + float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs + bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. + unsigned int FontBuilderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. + float RasterizerMultiply; // 1.0f // Brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. + ImWchar EllipsisChar; // -1 // Explicitly specify unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. + + // [Internal] + char Name[40]; // Name (strictly to ease debugging) + ImFont* DstFont; + + IMGUI_API ImFontConfig(); +}; + +// Hold rendering data for one glyph. +// (Note: some language parsers may fail to convert the 31+1 bitfield members, in this case maybe drop store a single u32 or we can rework this) +struct ImFontGlyph +{ + unsigned int Colored : 1; // Flag to indicate glyph is colored and should generally ignore tinting (make it usable with no shift on little-endian as this is used in loops) + unsigned int Visible : 1; // Flag to indicate glyph has no visible pixels (e.g. space). Allow early out when rendering. + unsigned int Codepoint : 30; // 0x0000..0x10FFFF + float AdvanceX; // Distance to next character (= data from font + ImFontConfig::GlyphExtraSpacing.x baked in) + float X0, Y0, X1, Y1; // Glyph corners + float U0, V0, U1, V1; // Texture coordinates +}; + +// Helper to build glyph ranges from text/string data. Feed your application strings/characters to it then call BuildRanges(). +// This is essentially a tightly packed of vector of 64k booleans = 8KB storage. +struct ImFontGlyphRangesBuilder +{ + ImVector UsedChars; // Store 1-bit per Unicode code point (0=unused, 1=used) + + ImFontGlyphRangesBuilder() { Clear(); } + inline void Clear() { int size_in_bytes = (IM_UNICODE_CODEPOINT_MAX + 1) / 8; UsedChars.resize(size_in_bytes / (int)sizeof(ImU32)); memset(UsedChars.Data, 0, (size_t)size_in_bytes); } + inline bool GetBit(size_t n) const { int off = (int)(n >> 5); ImU32 mask = 1u << (n & 31); return (UsedChars[off] & mask) != 0; } // Get bit n in the array + inline void SetBit(size_t n) { int off = (int)(n >> 5); ImU32 mask = 1u << (n & 31); UsedChars[off] |= mask; } // Set bit n in the array + inline void AddChar(ImWchar c) { SetBit(c); } // Add character + IMGUI_API void AddText(const char* text, const char* text_end = NULL); // Add string (each character of the UTF-8 string are added) + IMGUI_API void AddRanges(const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault()) to force add all of ASCII/Latin+Ext + IMGUI_API void BuildRanges(ImVector* out_ranges); // Output new ranges +}; + +// See ImFontAtlas::AddCustomRectXXX functions. +struct ImFontAtlasCustomRect +{ + unsigned short Width, Height; // Input // Desired rectangle dimension + unsigned short X, Y; // Output // Packed position in Atlas + unsigned int GlyphID; // Input // For custom font glyphs only (ID < 0x110000) + float GlyphAdvanceX; // Input // For custom font glyphs only: glyph xadvance + ImVec2 GlyphOffset; // Input // For custom font glyphs only: glyph display offset + ImFont* Font; // Input // For custom font glyphs only: target font + ImFontAtlasCustomRect() { Width = Height = 0; X = Y = 0xFFFF; GlyphID = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0, 0); Font = NULL; } + bool IsPacked() const { return X != 0xFFFF; } +}; + +// Flags for ImFontAtlas build +enum ImFontAtlasFlags_ +{ + ImFontAtlasFlags_None = 0, + ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two + ImFontAtlasFlags_NoMouseCursors = 1 << 1, // Don't build software mouse cursors into the atlas (save a little texture memory) + ImFontAtlasFlags_NoBakedLines = 1 << 2, // Don't build thick line textures into the atlas (save a little texture memory, allow support for point/nearest filtering). The AntiAliasedLinesUseTex features uses them, otherwise they will be rendered using polygons (more expensive for CPU/GPU). +}; + +// Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding: +// - One or more fonts. +// - Custom graphics data needed to render the shapes needed by Dear ImGui. +// - Mouse cursor shapes for software cursor rendering (unless setting 'Flags |= ImFontAtlasFlags_NoMouseCursors' in the font atlas). +// It is the user-code responsibility to setup/build the atlas, then upload the pixel data into a texture accessible by your graphics api. +// - Optionally, call any of the AddFont*** functions. If you don't call any, the default font embedded in the code will be loaded for you. +// - Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data. +// - Upload the pixels data into a texture within your graphics system (see imgui_impl_xxxx.cpp examples) +// - Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture in a format natural to your graphics API. +// This value will be passed back to you during rendering to identify the texture. Read FAQ entry about ImTextureID for more details. +// Common pitfalls: +// - If you pass a 'glyph_ranges' array to AddFont*** functions, you need to make sure that your array persist up until the +// atlas is build (when calling GetTexData*** or Build()). We only copy the pointer, not the data. +// - Important: By default, AddFontFromMemoryTTF() takes ownership of the data. Even though we are not writing to it, we will free the pointer on destruction. +// You can set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed, +// - Even though many functions are suffixed with "TTF", OTF data is supported just as well. +// - This is an old API and it is currently awkward for those and various other reasons! We will address them in the future! +struct ImFontAtlas +{ + IMGUI_API ImFontAtlas(); + IMGUI_API ~ImFontAtlas(); + IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg); + IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL); + IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); + IMGUI_API ImFont* AddFontFromMemoryTTF(void* font_data, int font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after destruction of the atlas. Set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed. + IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp. + IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter. + IMGUI_API void ClearInputData(); // Clear input data (all ImFontConfig structures including sizes, TTF data, glyph ranges, etc.) = all the data used to build the texture and fonts. + IMGUI_API void ClearTexData(); // Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory. + IMGUI_API void ClearFonts(); // Clear output font data (glyphs storage, UV coordinates). + IMGUI_API void Clear(); // Clear all input and output. + + // Build atlas, retrieve pixel data. + // User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID(). + // The pitch is always = Width * BytesPerPixels (1 or 4) + // Building in RGBA32 format is provided for convenience and compatibility, but note that unless you manually manipulate or copy color data into + // the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste. + IMGUI_API bool Build(); // Build pixels data. This is called automatically for you by the GetTexData*** functions. + IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel + IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel + bool IsBuilt() const { return Fonts.Size > 0 && TexReady; } // Bit ambiguous: used to detect when user didn't build texture but effectively we should check TexID != 0 except that would be backend dependent... + void SetTexID(ImTextureID id) { TexID = id; } + + //------------------------------------------- + // Glyph Ranges + //------------------------------------------- + + // Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list) + // NB: Make sure that your string are UTF-8 and NOT in your local code page. In C++11, you can create UTF-8 string literal using the u8"Hello world" syntax. See FAQ for details. + // NB: Consider using ImFontGlyphRangesBuilder to build glyph ranges from textual data. + IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin + IMGUI_API const ImWchar* GetGlyphRangesGreek(); // Default + Greek and Coptic + IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters + IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 2999 Ideographs + IMGUI_API const ImWchar* GetGlyphRangesChineseFull(); // Default + Half-Width + Japanese Hiragana/Katakana + full set of about 21000 CJK Unified Ideographs + IMGUI_API const ImWchar* GetGlyphRangesChineseSimplifiedCommon();// Default + Half-Width + Japanese Hiragana/Katakana + set of 2500 CJK Unified Ideographs for common simplified Chinese + IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters + IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters + IMGUI_API const ImWchar* GetGlyphRangesVietnamese(); // Default + Vietnamese characters + + //------------------------------------------- + // [BETA] Custom Rectangles/Glyphs API + //------------------------------------------- + + // You can request arbitrary rectangles to be packed into the atlas, for your own purposes. + // - After calling Build(), you can query the rectangle position and render your pixels. + // - If you render colored output, set 'atlas->TexPixelsUseColors = true' as this may help some backends decide of prefered texture format. + // - You can also request your rectangles to be mapped as font glyph (given a font + Unicode point), + // so you can render e.g. custom colorful icons and use them as regular glyphs. + // - Read docs/FONTS.md for more details about using colorful icons. + // - Note: this API may be redesigned later in order to support multi-monitor varying DPI settings. + IMGUI_API int AddCustomRectRegular(int width, int height); + IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); + ImFontAtlasCustomRect* GetCustomRectByIndex(int index) { IM_ASSERT(index >= 0); return &CustomRects[index]; } + + // [Internal] + IMGUI_API void CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const; + IMGUI_API bool GetMouseCursorTexData(ImGuiMouseCursor cursor, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]); + + //------------------------------------------- + // Members + //------------------------------------------- + + ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_) + ImTextureID TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. + int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. + int TexGlyphPadding; // Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0 (will also need to set AntiAliasedLinesUseTex = false). + bool Locked; // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert. + void* UserData; // Store your own atlas related user-data (if e.g. you have multiple font atlas). + + // [Internal] + // NB: Access texture data via GetTexData*() calls! Which will setup a default font for you. + bool TexReady; // Set when texture was built matching current font input + bool TexPixelsUseColors; // Tell whether our texture data is known to use colors (rather than just alpha channel), in order to help backend select a format. + unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight + unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 + int TexWidth; // Texture width calculated during Build(). + int TexHeight; // Texture height calculated during Build(). + ImVec2 TexUvScale; // = (1.0f/TexWidth, 1.0f/TexHeight) + ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel + ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. + ImVector CustomRects; // Rectangles for packing custom texture data into the atlas. + ImVector ConfigData; // Configuration data + ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines + + // [Internal] Font builder + const ImFontBuilderIO* FontBuilderIO; // Opaque interface to a font builder (default to stb_truetype, can be changed to use FreeType by defining IMGUI_ENABLE_FREETYPE). + unsigned int FontBuilderFlags; // Shared flags (for all fonts) for custom font builder. THIS IS BUILD IMPLEMENTATION DEPENDENT. Per-font override is also available in ImFontConfig. + + // [Internal] Packing data + int PackIdMouseCursors; // Custom texture rectangle ID for white pixel and mouse cursors + int PackIdLines; // Custom texture rectangle ID for baked anti-aliased lines + + // [Obsolete] + //typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ + //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+ +}; + +// Font runtime data and rendering +// ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32(). +struct ImFont +{ + // Members: Hot ~20/24 bytes (for CalcTextSize) + ImVector IndexAdvanceX; // 12-16 // out // // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this this info, and are often bottleneck in large UI). + float FallbackAdvanceX; // 4 // out // = FallbackGlyph->AdvanceX + float FontSize; // 4 // in // // Height of characters/line, set during loading (don't change after loading) + + // Members: Hot ~28/40 bytes (for CalcTextSize + render loop) + ImVector IndexLookup; // 12-16 // out // // Sparse. Index glyphs by Unicode code-point. + ImVector Glyphs; // 12-16 // out // // All glyphs. + const ImFontGlyph* FallbackGlyph; // 4-8 // out // = FindGlyph(FontFallbackChar) + + // Members: Cold ~32/40 bytes + ImFontAtlas* ContainerAtlas; // 4-8 // out // // What we has been loaded into + const ImFontConfig* ConfigData; // 4-8 // in // // Pointer within ContainerAtlas->ConfigData + short ConfigDataCount; // 2 // in // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont. + ImWchar FallbackChar; // 2 // out // = FFFD/'?' // Character used if a glyph isn't found. + ImWchar EllipsisChar; // 2 // out // = '...' // Character used for ellipsis rendering. + ImWchar DotChar; // 2 // out // = '.' // Character used for ellipsis rendering (if a single '...' character isn't found) + bool DirtyLookupTables; // 1 // out // + float Scale; // 4 // in // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetWindowFontScale() + float Ascent, Descent; // 4+4 // out // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] + int MetricsTotalSurface;// 4 // out // // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) + ImU8 Used4kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/4096/8]; // 2 bytes if ImWchar=ImWchar16, 34 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. + + // Methods + IMGUI_API ImFont(); + IMGUI_API ~ImFont(); + IMGUI_API const ImFontGlyph*FindGlyph(ImWchar c) const; + IMGUI_API const ImFontGlyph*FindGlyphNoFallback(ImWchar c) const; + float GetCharAdvance(ImWchar c) const { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; } + bool IsLoaded() const { return ContainerAtlas != NULL; } + const char* GetDebugName() const { return ConfigData ? ConfigData->Name : ""; } + + // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable. + // 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable. + IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL) const; // utf8 + IMGUI_API const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const; + IMGUI_API void RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c) const; + IMGUI_API void RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false) const; + + // [Internal] Don't use! + IMGUI_API void BuildLookupTable(); + IMGUI_API void ClearOutputData(); + IMGUI_API void GrowIndex(int new_size); + IMGUI_API void AddGlyph(const ImFontConfig* src_cfg, ImWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x); + IMGUI_API void AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built. + IMGUI_API void SetGlyphVisible(ImWchar c, bool visible); + IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last); +}; + +//----------------------------------------------------------------------------- +// [SECTION] Viewports +//----------------------------------------------------------------------------- + +// Flags stored in ImGuiViewport::Flags, giving indications to the platform backends. +enum ImGuiViewportFlags_ +{ + ImGuiViewportFlags_None = 0, + ImGuiViewportFlags_IsPlatformWindow = 1 << 0, // Represent a Platform Window + ImGuiViewportFlags_IsPlatformMonitor = 1 << 1, // Represent a Platform Monitor (unused yet) + ImGuiViewportFlags_OwnedByApp = 1 << 2, // Platform Window: is created/managed by the application (rather than a dear imgui backend) +}; + +// - Currently represents the Platform Window created by the application which is hosting our Dear ImGui windows. +// - In 'docking' branch with multi-viewport enabled, we extend this concept to have multiple active viewports. +// - In the future we will extend this concept further to also represent Platform Monitor and support a "no main platform window" operation mode. +// - About Main Area vs Work Area: +// - Main Area = entire viewport. +// - Work Area = entire viewport minus sections used by main menu bars (for platform windows), or by task bar (for platform monitor). +// - Windows are generally trying to stay within the Work Area of their host viewport. +struct ImGuiViewport +{ + ImGuiViewportFlags Flags; // See ImGuiViewportFlags_ + ImVec2 Pos; // Main Area: Position of the viewport (Dear ImGui coordinates are the same as OS desktop/native coordinates) + ImVec2 Size; // Main Area: Size of the viewport. + ImVec2 WorkPos; // Work Area: Position of the viewport minus task bars, menus bars, status bars (>= Pos) + ImVec2 WorkSize; // Work Area: Size of the viewport minus task bars, menu bars, status bars (<= Size) + + // Platform/Backend Dependent Data + void* PlatformHandleRaw; // void* to hold lower-level, platform-native window handle (under Win32 this is expected to be a HWND, unused for other platforms) + + ImGuiViewport() { memset(this, 0, sizeof(*this)); } + + // Helpers + ImVec2 GetCenter() const { return ImVec2(Pos.x + Size.x * 0.5f, Pos.y + Size.y * 0.5f); } + ImVec2 GetWorkCenter() const { return ImVec2(WorkPos.x + WorkSize.x * 0.5f, WorkPos.y + WorkSize.y * 0.5f); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Platform Dependent Interfaces +//----------------------------------------------------------------------------- + +// (Optional) Support for IME (Input Method Editor) via the io.SetPlatformImeDataFn() function. +struct ImGuiPlatformImeData +{ + bool WantVisible; // A widget wants the IME to be visible + ImVec2 InputPos; // Position of the input cursor + float InputLineHeight; // Line height + + ImGuiPlatformImeData() { memset(this, 0, sizeof(*this)); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Obsolete functions and types +// (Will be removed! Read 'API BREAKING CHANGES' section in imgui.cpp for details) +// Please keep your copy of dear imgui up to date! Occasionally set '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in imconfig.h to stay ahead. +//----------------------------------------------------------------------------- + +namespace ImGui +{ +#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO + IMGUI_API ImGuiKey GetKeyIndex(ImGuiKey key); // map ImGuiKey_* values into legacy native key index. == io.KeyMap[key] +#else + static inline ImGuiKey GetKeyIndex(ImGuiKey key) { IM_ASSERT(key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END && "ImGuiKey and native_index was merged together and native_index is disabled by IMGUI_DISABLE_OBSOLETE_KEYIO. Please switch to ImGuiKey."); return key; } +#endif +} + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +namespace ImGui +{ + // OBSOLETED in 1.89 (from August 2022) + IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); // Use new ImageButton() signature (explicit item id, regular FramePadding) + // OBSOLETED in 1.88 (from May 2022) + static inline void CaptureKeyboardFromApp(bool want_capture_keyboard = true) { SetNextFrameWantCaptureKeyboard(want_capture_keyboard); } // Renamed as name was misleading + removed default value. + static inline void CaptureMouseFromApp(bool want_capture_mouse = true) { SetNextFrameWantCaptureMouse(want_capture_mouse); } // Renamed as name was misleading + removed default value. + // OBSOLETED in 1.86 (from November 2021) + IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // Calculate coarse clipping for large list of evenly sized items. Prefer using ImGuiListClipper. + // OBSOLETED in 1.85 (from August 2021) + static inline float GetWindowContentRegionWidth() { return GetWindowContentRegionMax().x - GetWindowContentRegionMin().x; } + // OBSOLETED in 1.81 (from February 2021) + IMGUI_API bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1); // Helper to calculate size from items_count and height_in_items + static inline bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0, 0)) { return BeginListBox(label, size); } + static inline void ListBoxFooter() { EndListBox(); } + + // Some of the older obsolete names along with their replacement (commented out so they are not reported in IDE) + //-- OBSOLETED in 1.79 (from August 2020) + //static inline void OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mb = 1) { OpenPopupOnItemClick(str_id, mb); } // Bool return value removed. Use IsWindowAppearing() in BeginPopup() instead. Renamed in 1.77, renamed back in 1.79. Sorry! + //-- OBSOLETED in 1.78 (from June 2020): Old drag/sliders functions that took a 'float power > 1.0f' argument instead of ImGuiSliderFlags_Logarithmic. See github.com/ocornut/imgui/issues/3361 for details. + //IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power = 1.0f) // OBSOLETED in 1.78 (from June 2020) + //IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power = 1.0f); // OBSOLETED in 1.78 (from June 2020) + //IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power = 1.0f); // OBSOLETED in 1.78 (from June 2020) + //IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format, float power = 1.0f); // OBSOLETED in 1.78 (from June 2020) + //static inline bool DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power = 1.0f) { return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //static inline bool DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power = 1.0f) { return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //static inline bool DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power = 1.0f) { return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //static inline bool DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power = 1.0f) { return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //static inline bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power = 1.0f) { return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //static inline bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power = 1.0f) { return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //static inline bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power = 1.0f) { return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //static inline bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power = 1.0f) { return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) + //-- OBSOLETED in 1.77 and before + //static inline bool BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mb, bool over_items) { return BeginPopupContextWindow(str_id, mb | (over_items ? 0 : ImGuiPopupFlags_NoOpenOverItems)); } // OBSOLETED in 1.77 (from June 2020) + //static inline void TreeAdvanceToLabelPos() { SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()); } // OBSOLETED in 1.72 (from July 2019) + //static inline void SetNextTreeNodeOpen(bool open, ImGuiCond cond = 0) { SetNextItemOpen(open, cond); } // OBSOLETED in 1.71 (from June 2019) + //static inline float GetContentRegionAvailWidth() { return GetContentRegionAvail().x; } // OBSOLETED in 1.70 (from May 2019) + //static inline ImDrawList* GetOverlayDrawList() { return GetForegroundDrawList(); } // OBSOLETED in 1.69 (from Mar 2019) + //static inline void SetScrollHere(float ratio = 0.5f) { SetScrollHereY(ratio); } // OBSOLETED in 1.66 (from Nov 2018) + //static inline bool IsItemDeactivatedAfterChange() { return IsItemDeactivatedAfterEdit(); } // OBSOLETED in 1.63 (from Aug 2018) + //-- OBSOLETED in 1.60 and before + //static inline bool IsAnyWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_AnyWindow); } // OBSOLETED in 1.60 (from Apr 2018) + //static inline bool IsAnyWindowHovered() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } // OBSOLETED in 1.60 (between Dec 2017 and Apr 2018) + //static inline void ShowTestWindow() { return ShowDemoWindow(); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) + //static inline bool IsRootWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootWindow); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) + //static inline bool IsRootWindowOrAnyChildFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) + //static inline void SetNextWindowContentWidth(float w) { SetNextWindowContentSize(ImVec2(w, 0.0f)); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) + //static inline float GetItemsLineHeightWithSpacing() { return GetFrameHeightWithSpacing(); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) + //IMGUI_API bool Begin(char* name, bool* p_open, ImVec2 size_first_use, float bg_alpha = -1.0f, ImGuiWindowFlags flags=0); // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017): Equivalent of using SetNextWindowSize(size, ImGuiCond_FirstUseEver) and SetNextWindowBgAlpha(). + //static inline bool IsRootWindowOrAnyChildHovered() { return IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows); } // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017) + //static inline void AlignFirstTextHeightToWidgets() { AlignTextToFramePadding(); } // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017) + //static inline void SetNextWindowPosCenter(ImGuiCond c=0) { SetNextWindowPos(GetMainViewport()->GetCenter(), c, ImVec2(0.5f,0.5f)); } // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017) + //static inline bool IsItemHoveredRect() { return IsItemHovered(ImGuiHoveredFlags_RectOnly); } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017) + //static inline bool IsPosHoveringAnyWindow(const ImVec2&) { IM_ASSERT(0); return false; } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017): This was misleading and partly broken. You probably want to use the io.WantCaptureMouse flag instead. + //static inline bool IsMouseHoveringAnyWindow() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017) + //static inline bool IsMouseHoveringWindow() { return IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017) + //-- OBSOLETED in 1.50 and before + //static inline bool CollapsingHeader(char* label, const char* str_id, bool framed = true, bool default_open = false) { return CollapsingHeader(label, (default_open ? (1 << 5) : 0)); } // OBSOLETED in 1.49 + //static inline ImFont*GetWindowFont() { return GetFont(); } // OBSOLETED in 1.48 + //static inline float GetWindowFontSize() { return GetFontSize(); } // OBSOLETED in 1.48 + //static inline void SetScrollPosHere() { SetScrollHere(); } // OBSOLETED in 1.42 +} + +// OBSOLETED in 1.82 (from Mars 2021): flags for AddRect(), AddRectFilled(), AddImageRounded(), PathRect() +typedef ImDrawFlags ImDrawCornerFlags; +enum ImDrawCornerFlags_ +{ + ImDrawCornerFlags_None = ImDrawFlags_RoundCornersNone, // Was == 0 prior to 1.82, this is now == ImDrawFlags_RoundCornersNone which is != 0 and not implicit + ImDrawCornerFlags_TopLeft = ImDrawFlags_RoundCornersTopLeft, // Was == 0x01 (1 << 0) prior to 1.82. Order matches ImDrawFlags_NoRoundCorner* flag (we exploit this internally). + ImDrawCornerFlags_TopRight = ImDrawFlags_RoundCornersTopRight, // Was == 0x02 (1 << 1) prior to 1.82. + ImDrawCornerFlags_BotLeft = ImDrawFlags_RoundCornersBottomLeft, // Was == 0x04 (1 << 2) prior to 1.82. + ImDrawCornerFlags_BotRight = ImDrawFlags_RoundCornersBottomRight, // Was == 0x08 (1 << 3) prior to 1.82. + ImDrawCornerFlags_All = ImDrawFlags_RoundCornersAll, // Was == 0x0F prior to 1.82 + ImDrawCornerFlags_Top = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_TopRight, + ImDrawCornerFlags_Bot = ImDrawCornerFlags_BotLeft | ImDrawCornerFlags_BotRight, + ImDrawCornerFlags_Left = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotLeft, + ImDrawCornerFlags_Right = ImDrawCornerFlags_TopRight | ImDrawCornerFlags_BotRight, +}; + +// RENAMED and MERGED both ImGuiKey_ModXXX and ImGuiModFlags_XXX into ImGuiMod_XXX (from September 2022) +// RENAMED ImGuiKeyModFlags -> ImGuiModFlags in 1.88 (from April 2022). Exceptionally commented out ahead of obscolescence schedule to reduce confusion and because they were not meant to be used in the first place. +typedef ImGuiKeyChord ImGuiModFlags; // == int. We generally use ImGuiKeyChord to mean "a ImGuiKey or-ed with any number of ImGuiMod_XXX value", but you may store only mods in there. +enum ImGuiModFlags_ { ImGuiModFlags_None = 0, ImGuiModFlags_Ctrl = ImGuiMod_Ctrl, ImGuiModFlags_Shift = ImGuiMod_Shift, ImGuiModFlags_Alt = ImGuiMod_Alt, ImGuiModFlags_Super = ImGuiMod_Super }; +//typedef ImGuiKeyChord ImGuiKeyModFlags; // == int +//enum ImGuiKeyModFlags_ { ImGuiKeyModFlags_None = 0, ImGuiKeyModFlags_Ctrl = ImGuiMod_Ctrl, ImGuiKeyModFlags_Shift = ImGuiMod_Shift, ImGuiKeyModFlags_Alt = ImGuiMod_Alt, ImGuiKeyModFlags_Super = ImGuiMod_Super }; + +#endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +// RENAMED IMGUI_DISABLE_METRICS_WINDOW > IMGUI_DISABLE_DEBUG_TOOLS in 1.88 (from June 2022) +#if defined(IMGUI_DISABLE_METRICS_WINDOW) && !defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) && !defined(IMGUI_DISABLE_DEBUG_TOOLS) +#define IMGUI_DISABLE_DEBUG_TOOLS +#endif +#if defined(IMGUI_DISABLE_METRICS_WINDOW) && defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) +#error IMGUI_DISABLE_METRICS_WINDOW was renamed to IMGUI_DISABLE_DEBUG_TOOLS, please use new name. +#endif + +//----------------------------------------------------------------------------- + +#if defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + +#ifdef _MSC_VER +#pragma warning (pop) +#endif + +// Include imgui_user.h at the end of imgui.h (convenient for user to only explicitly include vanilla imgui.h) +#ifdef IMGUI_INCLUDE_IMGUI_USER_H +#include "imgui_user.h" +#endif + +#endif // #ifndef IMGUI_DISABLE \ No newline at end of file diff --git a/raylib-sys/binding/rlImGui b/raylib-sys/binding/rlImGui new file mode 160000 index 00000000..7864355e --- /dev/null +++ b/raylib-sys/binding/rlImGui @@ -0,0 +1 @@ +Subproject commit 7864355e232dbe4dd48ae3532957ea1d78b91a8c diff --git a/raylib-sys/build.rs b/raylib-sys/build.rs index 32e7672d..cfd0d239 100644 --- a/raylib-sys/build.rs +++ b/raylib-sys/build.rs @@ -280,6 +280,14 @@ fn gen_bindings() { .clang_arg(plat) .parse_callbacks(Box::new(ignored_macros)); + #[cfg(feature = "imgui")] + { + builder = builder + .clang_arg("-I./binding/imgui/decoy") + .clang_arg("-I./raylib/src") + .header("binding/rlImGui/rlImGui.h"); + } + if platform == Platform::Desktop && os == PlatformOS::Windows { // odd workaround for booleans being broken builder = builder.clang_arg("-D__STDC__"); @@ -324,6 +332,19 @@ fn gen_rgui() { } } +fn gen_imgui() { + println!("cargo:rustc-link-lib=dylib=stdc++"); + + cc::Build::new() + .define("NO_FONT_AWESOME", "1") + .files(vec!["binding/rlImGui/rlImGui.cpp"]) + .include("binding/imgui") + .include("raylib/src") + .warnings(false) + .extra_warnings(false) + .compile("rlImGui"); +} + #[cfg(feature = "nobuild")] fn link(_platform: Platform, _platform_os: PlatformOS) {} @@ -408,6 +429,8 @@ fn main() { link(platform, platform_os); gen_rgui(); + + gen_imgui(); } #[must_use] diff --git a/raylib/Cargo.toml b/raylib/Cargo.toml index 42463edc..ed62bcef 100644 --- a/raylib/Cargo.toml +++ b/raylib/Cargo.toml @@ -17,6 +17,8 @@ raylib-sys = { version = "5.5.0", path = "../raylib-sys" } cfg-if = "1.0.0" serde = { version = "1.0.125", features = ["derive"], optional = true } serde_json = { version = "1.0.64", optional = true } +imgui = { version = "0.12.0", optional = true, features = [] } +imgui-sys = { version = "0.12.0", optional = true } mint = { version = "0.5.9", optional = true } @@ -41,6 +43,7 @@ opengl_es_30 = ["raylib-sys/opengl_es_30"] sdl = ["raylib-sys/sdl"] noscreenshot = ["raylib-sys/noscreenshot"] nogif = ["raylib-sys/nogif"] +imgui = ["raylib-sys/imgui", "dep:imgui", "dep:imgui-sys"] [[example]] name = "specs" diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index b32ec556..f76ded6b 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -28,6 +28,7 @@ impl RaylibHandle { unsafe { ffi::BeginDrawing(); }; + let d = RaylibDrawHandle(self); d } diff --git a/raylib/src/core/mod.rs b/raylib/src/core/mod.rs index f3e988b4..67136609 100644 --- a/raylib/src/core/mod.rs +++ b/raylib/src/core/mod.rs @@ -10,6 +10,8 @@ pub mod color; pub mod data; pub mod drawing; pub mod error; +pub mod file; + pub mod input; pub mod logging; pub mod math; @@ -20,11 +22,11 @@ pub mod text; pub mod texture; pub mod vr; pub mod window; -pub mod file; use raylib_sys::TraceLogLevel; use crate::ffi; +use crate::imgui::init_imgui_context; use std::ffi::CString; use std::marker::PhantomData; @@ -66,6 +68,8 @@ impl Drop for RaylibHandle { unsafe { if ffi::IsWindowReady() { ffi::CloseWindow(); + // NOTE(IOI_XD): If imgui is enabled, we don't call the destructor here because we're using a context that Rust expects to free, and the only other thing in that function is the free'ing of FontTexture...an action which causes a segfault. + // It then gets successfully replaced if rlImGuiReloadFonts is called, so we'll take it. } } } @@ -84,6 +88,8 @@ pub struct RaylibBuilder { width: i32, height: i32, title: String, + #[cfg(feature = "imgui")] + imgui_theme: crate::imgui::ImGuiTheme, } /// Creates a `RaylibBuilder` for choosing window options before initialization. @@ -163,6 +169,13 @@ impl RaylibBuilder { self } + #[cfg(feature = "imgui")] + /// Set the theme to be used for imgui. + pub fn imgui_theme(&mut self, theme: crate::imgui::ImGuiTheme) -> &mut Self { + self.imgui_theme = theme; + self + } + /// Builds and initializes a Raylib window. /// /// # Panics @@ -197,7 +210,14 @@ impl RaylibBuilder { unsafe { ffi::SetTraceLogLevel(self.log_level as i32); } + let rl = init_window(self.width, self.height, &self.title); + + #[cfg(feature = "imgui")] + unsafe { + init_imgui_context(self.imgui_theme == crate::imgui::ImGuiTheme::Dark); + } + (rl, RaylibThread(PhantomData)) } } @@ -218,6 +238,7 @@ fn init_window(width: i32, height: i32, title: &str) -> RaylibHandle { if !unsafe { ffi::IsWindowReady() } { panic!("Attempting to create window failed!"); } + RaylibHandle(()) } } diff --git a/raylib/src/imgui/mod.rs b/raylib/src/imgui/mod.rs new file mode 100644 index 00000000..2574bde3 --- /dev/null +++ b/raylib/src/imgui/mod.rs @@ -0,0 +1,130 @@ +use std::{ + cell::UnsafeCell, + ops::{Deref, DerefMut}, + ptr::{null, null_mut}, + sync::OnceLock, +}; + +use imgui::{Context, Ui, UiBuffer}; +use imgui_sys::{ + igGetCurrentContext, igGetIO, igStyleColorsDark, igStyleColorsLight, + ImFontAtlas_AddFontDefault, ImGuiStyle, +}; + +use super::drawing::RaylibDrawHandle; + +static mut CONTEXT: OnceLock = OnceLock::new(); + +fn context() -> &'static Context { + unsafe { CONTEXT.get_or_init(|| imgui::Context::create()) } +} + +/** + Recreation of rlImGuiSetup because imgui-rs **really** wants you to use it's own function for the imgui context. + + We currently use a version of rlImGui where this is actually possible, and hopefully you aren't reading this in a point of time where it's not. +*/ +pub(crate) unsafe fn init_imgui_context(dark: bool) { + context(); + if dark { + igStyleColorsDark(null_mut() as *mut ImGuiStyle); + } else { + igStyleColorsLight(null_mut() as *mut ImGuiStyle); + } + + let io = igGetIO().as_ref().unwrap(); + ImFontAtlas_AddFontDefault(io.Fonts, null()); + + raylib_sys::rlImGuiEndInitImGui(); +} + +/// The interface for rlImGui. +/// +/// This can be constructed via [RaylibDrawHandle::start_imgui] or [RaylibDrawHandle::begin_imgui] +pub struct RayImGUIHandle(Ui); + +impl RayImGUIHandle { + fn new() -> Option { + unsafe { + // Correct an assertion error that sometimes happens with DeltaTime. + // We have to step into unsafe code to set the actual values that ImGui looks at + // and not imgui-rs's custom stuff. + if let Some(_ctx) = igGetCurrentContext().as_mut() { + if let Some(io) = igGetIO().as_mut() { + if io.DeltaTime <= 0.0 { + io.DeltaTime = 0.01; + // Yes we have to return None at this point, setting DeltaTime did not actually + // work. Yes this sucks. + return None; + } + } + } + raylib_sys::rlImGuiBegin(); + }; + + // We don't actually have a ui buffer from imgui-rs to store here, but what we do have + // is the fact that we can just make our own ui buffer with unsafe code, and it works + // because the struct only has one value and is most likely going to work unless they add + // something else. + Some(Self(unsafe { + std::mem::transmute(UnsafeCell::new(UiBuffer::new(1024))) + })) + } +} + +impl Drop for RayImGUIHandle { + fn drop(&mut self) { + unsafe { + raylib_sys::rlImGuiEnd(); + } + } +} + +impl Deref for RayImGUIHandle { + type Target = Ui; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for RayImGUIHandle { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +pub trait RayImGUITrait { + /// Setup ImGUI to start drawing. Prefer using the closure version, [RaylibHandle::start_imgui]. This version returns a handle that calls [raylib_sys::rlImGuiEnd] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) + /// + /// Returns None in the specific but also common case that the delta time is negative on any frame other then 0. + fn begin_imgui(&self) -> Option { + return RayImGUIHandle::new(); + } + + /// Setup ImGUI then call the closure with the appropriate handle. + /// + /// Fails silently if the delta time is negative on any frame other then 0. + fn start_imgui(&self, f: impl Fn(&mut Ui)) { + if let Some(mut new_frame) = RayImGUIHandle::new() { + f(&mut new_frame); + } + } +} + +impl RayImGUITrait for RaylibDrawHandle<'_> {} + +/// The theme chosen for imgui integeration. +#[cfg(feature = "imgui")] +#[derive(Debug, PartialEq)] +pub enum ImGuiTheme { + Light, + Dark, +} + +#[cfg(feature = "imgui")] +impl Default for ImGuiTheme { + fn default() -> Self { + Self::Dark + } +} diff --git a/raylib/src/lib.rs b/raylib/src/lib.rs index e88eabad..60122b23 100644 --- a/raylib/src/lib.rs +++ b/raylib/src/lib.rs @@ -78,3 +78,6 @@ pub use crate::core::*; pub use nalgebra as na; #[cfg(feature = "with_serde")] pub use serde; + +#[cfg(feature = "imgui")] +pub mod imgui; diff --git a/raylib/src/prelude.rs b/raylib/src/prelude.rs index 9b359d0b..b59da045 100644 --- a/raylib/src/prelude.rs +++ b/raylib/src/prelude.rs @@ -33,6 +33,7 @@ pub use crate::core::collision::*; pub use crate::core::color::*; pub use crate::core::data::*; pub use crate::core::drawing::*; +pub use crate::core::file::*; pub use crate::core::input::*; pub use crate::core::logging::*; pub use crate::core::math::*; @@ -44,6 +45,7 @@ pub use crate::core::texture::*; pub use crate::core::vr::*; pub use crate::core::window::*; pub use crate::core::*; -pub use crate::core::file::*; +#[cfg(feature = "imgui")] +pub use crate::imgui::*; pub use crate::rgui::*; pub use crate::*; diff --git a/samples/Cargo.toml b/samples/Cargo.toml index 190dc8c2..ed1f986e 100644 --- a/samples/Cargo.toml +++ b/samples/Cargo.toml @@ -16,6 +16,11 @@ rand = "0.7" #tcod = "0.14" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" +imgui = {version = "0.12.0", optional = true} +imgui-sys = {version = "0.12.0", optional = true} + +[features] +imgui = ["raylib/imgui","dep:imgui","dep:imgui-sys"] [dependencies.specs] version = "0.16.1" @@ -89,4 +94,9 @@ path = "./floppy.rs" [[bin]] name = "shader_multisample" -path = "./shader_multisample.rs" \ No newline at end of file +path = "./shader_multisample.rs" + +[[bin]] +name = "imgui" +path = "imgui.rs" +required-features = ["imgui"] \ No newline at end of file diff --git a/samples/imgui.rs b/samples/imgui.rs new file mode 100644 index 00000000..de7dbf51 --- /dev/null +++ b/samples/imgui.rs @@ -0,0 +1,27 @@ +use raylib::prelude::*; + +macro_rules! add_menu_color { + ($ui:tt, $name:tt, $src:tt, $dst:tt) => { + if $ui.menu_item($name) { + *$dst.lock().unwrap() = Color::$src; + } + }; +} + +use std::sync::Mutex; + +fn main() -> Result<(), Box> { + let (mut rl, thread) = raylib::init().width(640).height(480).build(); + + while (!rl.window_should_close()) { + let mut d = rl.begin_drawing(&thread); + + d.start_imgui(|ui| { + ui.window("A Window").build(|| { + // imgui functions + }); + }); + } + + Ok(()) +} From 2860541712972e003a8e3dd2b45e48e01dedd939 Mon Sep 17 00:00:00 2001 From: IoIxD Date: Sat, 28 Dec 2024 15:23:02 -0700 Subject: [PATCH 57/93] [samples] working rgui example --- samples/Cargo.toml | 6 +- samples/rgui.rs | 785 +++++++++++++++++++++++---------------------- 2 files changed, 410 insertions(+), 381 deletions(-) diff --git a/samples/Cargo.toml b/samples/Cargo.toml index 190dc8c2..0fba9835 100644 --- a/samples/Cargo.toml +++ b/samples/Cargo.toml @@ -2,14 +2,14 @@ name = "raylib-examples" version = "5.5.0" authors = ["David Ayeke"] -edition = "2018" +edition = "2021" license = "Zlib" readme = "../README.md" repository = "https://github.com/raylib-rs/raylib-rs" [dependencies] -raylib = { version = "5.5.0", path = "../raylib" } +raylib = { path = "../raylib", version = "5.5.0" } structopt = "0.2" specs-derive = "0.4.1" rand = "0.7" @@ -89,4 +89,4 @@ path = "./floppy.rs" [[bin]] name = "shader_multisample" -path = "./shader_multisample.rs" \ No newline at end of file +path = "./shader_multisample.rs" diff --git a/samples/rgui.rs b/samples/rgui.rs index 837847d0..06af2fc2 100644 --- a/samples/rgui.rs +++ b/samples/rgui.rs @@ -1,5 +1,13 @@ -#![allow(non_snake_case)] -use raylib::ffi; +use raylib::prelude::GuiControl::*; +use raylib::prelude::GuiControlProperty::*; +use raylib::prelude::GuiDefaultProperty::*; +use raylib::prelude::GuiIconName::*; +use raylib::prelude::GuiSliderProperty::*; +use raylib::prelude::GuiState::*; +use raylib::prelude::GuiTextAlignment::*; +use raylib::prelude::GuiTextAlignmentVertical::*; +use raylib::prelude::GuiTextWrapMode::*; +use raylib::prelude::KeyboardKey::*; use raylib::prelude::*; //------------------------------------------------------------------------------------ @@ -8,433 +16,454 @@ use raylib::prelude::*; pub fn main() { // Initialization //--------------------------------------------------------------------------------------- - let screenWidth = 690; + let screenWidth = 960; let screenHeight = 560; - // let (mut rl, thread) = raylib::init() - // .size(screenWidth, screenHeight) - // .title("rgui") - // .build(); - // let logo = raylib::prelude::Image::load_image("static/logo.png").unwrap(); - // rl.set_window_icon(&logo); - // rl.set_target_fps(60); - - unsafe { - ffi::InitWindow( - screenWidth, - screenHeight, - b"raygui - controls test suite\0".as_ptr() as *const _, - ); - ffi::SetTargetFPS(60); - } + let (mut rl, thread) = raylib::init() + .width(screenWidth) + .height(screenHeight) + .title("raygui - controls test suite") + .build(); + + rl.set_exit_key(None); // GUI controls initialization //---------------------------------------------------------------------------------- - // let mut dropdownBox000Active = 0; - // let mut dropDown000EditMode = false; + let mut dropdownBox000Active = 0; + let mut dropDown000EditMode = false; - // let mut dropdownBox001Active = 0; - // let mut dropDown001EditMode = false; + let mut dropdownBox001Active = 0; + let mut dropDown001EditMode = false; let mut spinner001Value = 0; let mut spinnerEditMode = false; - // let mut valueBox002Value = 0; - // let mut valueBoxEditMode = false; + let mut valueBox002Value = 0; + let mut valueBoxEditMode = false; + + let mut textBoxText = String::from("Text box"); + let mut textBoxEditMode = false; - // let mut textBoxText = [0u8; 64]; - // textBoxText[..8].clone_from_slice(b"Text box"); - // let mut textBoxEditMode = false; + let mut textBoxMultiText = String::from("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n\nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat Nonea pariatur.\n\nThisisastringlongerthanexpectedwithoutspacestotestcharbreaksforthosecases,checkingifworkingasexpected.\n\nExcepteur slet occaecatcupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."); + let mut textBoxMultiEditMode = false; - // let mut listViewScrollIndex = 0; - // let mut listViewActive = -1; + let mut listViewScrollIndex = 0; + let mut listViewActive = -1; - // let mut listViewExScrollIndex = 0; - // let mut listViewExActive = 2; - // let mut listViewExFocus = -1; - // let listViewExList = vec![ - // rstr!("This"), - // rstr!("is"), - // rstr!("a"), - // rstr!("list view"), - // rstr!("with"), - // rstr!("disable"), - // rstr!("elements"), - // rstr!("amazing!"), - // ]; + let mut listViewExScrollIndex = 0; + let mut listViewExActive = 2; + let mut listViewExFocus = -1; + let mut listViewExList = [ + c"This", + c"is", + c"a", + c"list view", + c"with", + c"disable", + c"elements", + c"amazing!", + ]; - // let mut multiTextBoxText = [0u8; 256]; - // multiTextBoxText[..14].clone_from_slice(b"Multi text box"); - // let mut multiTextBoxEditMode = false; - // let mut colorPickerValue = Color::RED; + let colorPickerValue = Color::RED; - // let mut sliderValue = 50f32; - // let mut sliderBarValue = 60f32; - // let mut progressValue = 0.4; + let mut sliderValue = 50.0; + let mut sliderBarValue = 60.0; + let mut progressValue = 0.1; - // let mut forceSquaredChecked = false; + let mut forceSquaredChecked = false; - // let mut alphaValue = 0.5; + let mut alphaValue = 0.5; - // let mut comboBoxActive = 1; + //let comboBoxActive= 1; + let mut visualStyleActive = 0; + let mut prevVisualStyleActive = 0; - // let mut toggleGroupActive = 0; + let mut toggleGroupActive = 0; + let mut toggleSliderActive = 0; - // let mut viewScroll = rvec2(0, 0); - // //---------------------------------------------------------------------------------- + let viewScroll = Vector2::new(0.0, 0.0); + //---------------------------------------------------------------------------------- - // // Custom GUI font loading - // //Font font = LoadFontEx("fonts/rainyhearts16.ttf", 12, 0, 0); - // //GuiSetFont(font); + // Custom GUI font loading + //Font font = LoadFontEx("fonts/rainyhearts16.ttf", 12, 0, 0); + //GuiSetFont(font); let mut exitWindow = false; - // let mut showMessageBox = false; + let mut showMessageBox = false; + + let mut textInput = String::new(); + let mut textInputFileName = String::new(); + let mut showTextInputBox = false; - // let mut textInput = vec![0u8; 256]; - // let mut showTextInputBox = false; + let mut alpha = 1.0; - // let mut textInputFileName = [0u8; 256]; + // DEBUG: Testing how those two properties affect all controls! + //rl.gui_set_style(DEFAULT, TEXT_PADDING, 0); + //rl.gui_set_style(DEFAULT, TEXT_ALIGNMENT, TEXT_ALIGN_CENTER); + rl.set_target_fps(60); //-------------------------------------------------------------------------------------- // Main game loop while !exitWindow // Detect window close button or ESC key { - use raylib::consts::GuiControl::*; - use raylib::consts::GuiControlProperty::*; - - use raylib::consts::GuiTextAlignment::*; - // Update //---------------------------------------------------------------------------------- + exitWindow = rl.window_should_close(); - // exitWindow = rl.window_should_close(); - exitWindow = unsafe { ffi::WindowShouldClose() }; + if rl.is_key_pressed(KEY_ESCAPE) { + showMessageBox = !showMessageBox + }; - // if rl.is_key_pressed(KEY_ESCAPE) { - // showMessageBox = !showMessageBox; - // } + if rl.is_key_down(KEY_LEFT_CONTROL) && rl.is_key_pressed(KEY_S) { + showTextInputBox = true + }; - // if rl.is_key_down(KEY_LEFT_CONTROL) && rl.is_key_pressed(KEY_S) { - // showTextInputBox = true; - // } + if rl.is_file_dropped() { + let droppedFiles = rl.load_dropped_files(); - // if rl.is_file_dropped() { - // let droppedFiles = rl.load_dropped_files(); + let paths = droppedFiles.paths(); + if droppedFiles.count > 0 && paths[0].ends_with(".rgs") { + rl.gui_load_style(paths[0]) + }; + } + + //alpha -= 0.002; + if alpha < 0.0 { + alpha = 0.0; + } + if rl.is_key_pressed(KEY_SPACE) { + { + alpha = 1.0 + }; + } + + //progressValue += 0.002; + if rl.is_key_pressed(KEY_LEFT) { + { + progressValue -= 0.1 + }; + } else if rl.is_key_pressed(KEY_RIGHT) { + { + progressValue += 0.1 + }; + } + if progressValue > 1.0 { + progressValue = 1.0; + } else if progressValue < 0.0 { + { + progressValue = 0.0 + }; + } - // if (droppedFiles.len() > 0) && droppedFiles[0].ends_with(".rgs") { - // rl.gui_load_style(Some(&CString::new(droppedFiles[0].clone()).unwrap())); - // } + if visualStyleActive != prevVisualStyleActive { + rl.gui_load_style_default(); + + // switch (visualStyleActive) + // { + // 0 => break; // Default style + // 1 => rl.gui_load_styleJungle(); + // 2 => rl.gui_load_styleLavanda(); + // 3 => rl.gui_load_styleDark(); + // 4 => rl.gui_load_styleBluish(); + // 5 => rl.gui_load_styleCyber(); + // 6 => rl.gui_load_styleTerminal(); + // _: break; + // } - // rl.unload_dropped_files(); - // } + rl.gui_set_style(LABEL, TEXT_ALIGNMENT, TEXT_ALIGN_LEFT as i32); + prevVisualStyleActive = visualStyleActive; + } //---------------------------------------------------------------------------------- // Draw //---------------------------------------------------------------------------------- - // let mut d = rl.begin_drawing(&thread); - // let hex = d.gui_get_style(DEFAULT, BACKGROUND_COLOR as i32); - // d.clear_background(Color::get_color(hex)); - unsafe { - ffi::BeginDrawing(); - ffi::ClearBackground(Color::WHITE.into()); - } + let mut d = rl.begin_drawing(&thread); + + d.clear_background(Color::get_color( + d.gui_get_style(DEFAULT, BACKGROUND_COLOR) as u32 + )); + d.gui_set_alpha(alpha); + + // raygui: controls drawing + //---------------------------------------------------------------------------------- + // Check all possible events that require d.gui_lock + if dropDown000EditMode || dropDown001EditMode { + d.gui_lock() + }; + + // First GUI column + //rl.gui_set_style(CHECKBOX, TEXT_ALIGNMENT, TEXT_ALIGN_LEFT); + d.gui_check_box( + Rectangle::new(25.0, 108.0, 15.0, 15.0), + "FORCE CHECK!", + &mut forceSquaredChecked, + ); + + d.gui_set_style(TEXTBOX, TEXT_ALIGNMENT, TEXT_ALIGN_CENTER as i32); + //d.gui_set_style(VALUEBOX, TEXT_ALIGNMENT, TEXT_ALIGN_LEFT); + if d.gui_spinner( + Rectangle::new(25.0, 135.0, 125.0, 30.0), + "", + &mut spinner001Value, + 0, + 100, + spinnerEditMode, + ) { + spinnerEditMode = !spinnerEditMode + }; + if d.gui_value_box( + Rectangle::new(25.0, 175.0, 125.0, 30.0), + "", + &mut valueBox002Value, + 0, + 100, + valueBoxEditMode, + ) { + valueBoxEditMode = !valueBoxEditMode + }; + d.gui_set_style(TEXTBOX, TEXT_ALIGNMENT, TEXT_ALIGN_LEFT as i32); + if d.gui_text_box( + Rectangle::new(25.0, 215.0, 125.0, 30.0), + &mut textBoxText, + textBoxEditMode, + ) { + textBoxEditMode = !textBoxEditMode + }; + + d.gui_set_style(BUTTON, TEXT_ALIGNMENT, TEXT_ALIGN_CENTER as i32); + + let gui_icon_text = d.gui_icon_text(ICON_FILE_SAVE, "Save File"); + if d.gui_button( + Rectangle::new(25.0, 255.0, 125.0, 30.0), + gui_icon_text.as_str(), + ) { + showTextInputBox = true + }; + + d.gui_group_box(Rectangle::new(25.0, 310.0, 125.0, 150.0), "STATES"); + //d.gui_lock(); + d.gui_set_state(STATE_NORMAL); + if d.gui_button(Rectangle::new(30.0, 320.0, 115.0, 30.0), "NORMAL") {} + d.gui_set_state(STATE_FOCUSED); + if d.gui_button(Rectangle::new(30.0, 355.0, 115.0, 30.0), "FOCUSED") {} + d.gui_set_state(STATE_PRESSED); + if d.gui_button(Rectangle::new(30.0, 390.0, 115.0, 30.0), "#15#PRESSED") {} + d.gui_set_state(STATE_DISABLED); + if d.gui_button(Rectangle::new(30.0, 425.0, 115.0, 30.0), "DISABLED") {} + d.gui_set_state(STATE_NORMAL); + //d.gui_unlock(); + + d.gui_combo_box( + Rectangle::new(25.0, 480.0, 125.0, 30.0), + "default;Jungle;Lavanda;Dark;Bluish;Cyber;Terminal", + &mut visualStyleActive, + ); - // // raygui: controls drawing - // //---------------------------------------------------------------------------------- - // if dropDown000EditMode || dropDown001EditMode { - // d.gui_lock(); - // } - // //GuiDisable(); - - // // First GUI column - // //GuiSetStyle(CHECKBOX, TEXT_ALIGNMENT, TEXT_ALIGN_LEFT); - // forceSquaredChecked = d.gui_check_box( - // rrect(25, 108, 15, 15), - // Some(rstr!("FORCE CHECK!")), - // forceSquaredChecked, - // ); - - unsafe { - ffi::GuiSetStyle( - TEXTBOX as i32, - TEXT_ALIGNMENT as i32, - TEXT_ALIGN_CENTER as i32, + // NOTE: d.gui_dropdown_box must draw after any other control that can be covered on unfolding + d.gui_unlock(); + d.gui_set_style(DROPDOWNBOX, TEXT_PADDING, 4); + d.gui_set_style(DROPDOWNBOX, TEXT_ALIGNMENT, TEXT_ALIGN_LEFT as i32); + if d.gui_dropdown_box( + Rectangle::new(25.0, 65.0, 125.0, 30.0), + "#01#ONE;#02#TWO;#03#THREE;#04#FOUR", + &mut dropdownBox001Active, + dropDown001EditMode, + ) { + dropDown001EditMode = !dropDown001EditMode + }; + d.gui_set_style(DROPDOWNBOX, TEXT_ALIGNMENT, TEXT_ALIGN_CENTER as i32); + d.gui_set_style(DROPDOWNBOX, TEXT_PADDING, 0); + + if d.gui_dropdown_box( + Rectangle::new(25.0, 25.0, 125.0, 30.0), + "ONE;TWO;THREE", + &mut dropdownBox000Active, + dropDown000EditMode, + ) { + dropDown000EditMode = !dropDown000EditMode + }; + + // Second GUI column + d.gui_list_view( + Rectangle::new(165.0, 25.0, 140.0, 124.0), + "Charmander;Bulbasaur;#18#Squirtel;Pikachu;Eevee;Pidgey", + &mut listViewScrollIndex, + &mut listViewActive, + ); + d.gui_list_view_ex( + Rectangle::new(165.0, 162.0, 140.0, 184.0), + &listViewExList, + &mut listViewExScrollIndex, + &mut listViewExActive, + &mut listViewExFocus, + ); + + //GuiToggle(Rectangle::new( 165, 400, 140, 25 ), "#1#ONE", &toggleGroupActive); + d.gui_toggle_group( + Rectangle::new(165.0, 360.0, 140.0, 24.0), + "#1#ONE\n#3#TWO\n#8#THREE\n#23#", + &mut toggleGroupActive, + ); + //d.gui_disable(); + d.gui_set_style(SLIDER, SLIDER_PADDING, 2); + d.gui_toggle_slider( + Rectangle::new(165.0, 480.0, 140.0, 30.0), + "ON;OFF", + &mut toggleSliderActive, + ); + d.gui_set_style(SLIDER, SLIDER_PADDING, 0); + + // Third GUI column + d.gui_panel(Rectangle::new(320.0, 25.0, 225.0, 140.0), "Panel Info"); + d.gui_color_picker( + Rectangle::new(320.0, 185.0, 196.0, 192.0), + "", + &colorPickerValue, + ); + + //d.gui_disable(); + d.gui_slider( + Rectangle::new(355.0, 400.0, 165.0, 20.0), + "TEST", + format!("{}", sliderValue).as_str(), + &mut sliderValue, + -50.0, + 100.0, + ); + d.gui_slider_bar( + Rectangle::new(320.0, 430.0, 200.0, 20.0), + "", + format!("{}", sliderBarValue).as_str(), + &mut sliderBarValue, + 0.0, + 100.0, + ); + + d.gui_progress_bar( + Rectangle::new(320.0, 460.0, 200.0, 20.0), + "", + format!("{}", (progressValue * 100.0)).as_str(), + &mut progressValue, + 0.0, + 1.0, + ); + d.gui_enable(); + + // NOTE: View rectangle could be used to perform some scissor test + let view = Rectangle::new(0.0, 0.0, 0.0, 0.0); + d.gui_scroll_panel( + Rectangle::new(560.0, 25.0, 102.0, 354.0), + "", + Rectangle::new(560.0, 25.0, 300.0, 1200.0), + &viewScroll, + &view, + ); + + let mouseCell = Vector2::new(0.0, 0.0); + d.gui_grid( + Rectangle::new(560.0, 25.0 + 180.0 + 195.0, 100.0, 120.0), + "", + 20.0, + 3, + ); + + d.gui_color_bar_alpha( + Rectangle::new(320.0, 490.0, 200.0, 30.0), + "", + &mut alphaValue, + ); + + d.gui_set_style(DEFAULT, TEXT_ALIGNMENT_VERTICAL, TEXT_ALIGN_TOP as i32); // WARNING: Word-wrap does not work as expected in case of no-top alignment + d.gui_set_style(DEFAULT, TEXT_WRAP_MODE, TEXT_WRAP_WORD as i32); // WARNING: If wrap mode enabled, text editing is not supported + if d.gui_text_box( + Rectangle::new(678.0, 25.0, 258.0, 492.0), + &mut textBoxMultiText, + textBoxMultiEditMode, + ) { + textBoxMultiEditMode = !textBoxMultiEditMode + }; + d.gui_set_style(DEFAULT, TEXT_WRAP_MODE, TEXT_WRAP_NONE as i32); + d.gui_set_style(DEFAULT, TEXT_ALIGNMENT_VERTICAL, TEXT_ALIGN_MIDDLE as i32); + + d.gui_set_style(DEFAULT, TEXT_ALIGNMENT, TEXT_ALIGN_LEFT as i32); + d.gui_status_bar( + Rectangle::new( + 0.0, + d.get_screen_height() as f32 - 20.0, + d.get_screen_width() as f32, + 20.0, + ), + "This is a status bar", + ); + d.gui_set_style(DEFAULT, TEXT_ALIGNMENT, TEXT_ALIGN_CENTER as i32); + //d.gui_set_style(STATUSBAR, TEXT_INDENTATION, 20); + + if showMessageBox { + d.draw_rectangle( + 0, + 0, + d.get_screen_width(), + d.get_screen_height(), + Color::RAYWHITE.fade(0.8), ); - } - // dbg!(spinnerEditMode); - // let pos = d.get_mouse_position(); - // let coll = rrect(25, 135, 125, 30).check_collision_point_rec(pos); - // let down = d.is_mouse_button_down(raylib::consts::MouseButton::MOUSE_LEFT_BUTTON); - - // if d.gui_spinner( - // rrect(25, 135, 125, 30), - // None, - // &mut spinner001Value, - // 0, - // 100, - // spinnerEditMode, - // ) { - // spinnerEditMode = dbg!(!spinnerEditMode); - // } - unsafe { - ffi::DrawCircle( - 50, - 50, - 5.0, - if spinnerEditMode { - Color::BLUE.into() - } else { - Color::RED.into() - }, + let gui_icon_text = d.gui_icon_text(ICON_EXIT, "Close Window"); + let result = d.gui_message_box( + Rectangle::new( + (d.get_screen_width() / 2 - 125) as f32, + (d.get_screen_height() / 2 - 50) as f32, + 250.0, + 100.0, + ), + gui_icon_text.as_str(), + "Do you really want to exit?", + "Yes;No", ); - if ffi::GuiSpinner( - rrect(25, 135, 125, 30).into(), - std::ptr::null(), - &mut spinner001Value, + + if result == 0 || (result == 2) { + showMessageBox = false + } else if result == 1 { + exitWindow = true + }; + } + + if showTextInputBox { + d.draw_rectangle( 0, - 100, - spinnerEditMode, - ) > 0 - { - spinnerEditMode = dbg!(!spinnerEditMode); + 0, + d.get_screen_width(), + d.get_screen_height(), + Color::RAYWHITE.fade(0.8), + ); + let mut _act = true; + let gui_icon_text = d.gui_icon_text(ICON_FILE_SAVE, "Save file as..."); + let result = d.gui_text_input_box( + Rectangle::new( + (d.get_screen_width() / 2 - 120) as f32, + (d.get_screen_height() / 2 - 60) as f32, + 240.0, + 140.0, + ), + gui_icon_text.as_str(), + "Introduce output file name:", + "Ok;Cancel", + &mut textInput, + 255, + &mut _act, + ); + + if result == 1 { + // TODO: Validate textInput value and save + textInputFileName = textInput.clone(); + } + + if result == 0 || (result == 1 || (result == 2)) { + showTextInputBox = false; + textInput.truncate(0); } - // if ffi::GuiSpinner( - // rrect(25, 185, 125, 30).into(), - // std::ptr::null(), - // &mut spinner001Value, - // 0, - // 100, - // false, - // ) { - // // spinnerEditMode = dbg!(!spinnerEditMode); - // } - // if ffi::GuiSpinner( - // rrect(25, 225, 125, 30).into(), - // std::ptr::null(), - // &mut spinner001Value, - // 0, - // 100, - // false, - // ) { - // // spinnerEditMode = dbg!(!spinnerEditMode); - // } - } - // if d.gui_value_box( - // rrect(25, 175, 125, 30), - // None, - // &mut valueBox002Value, - // 0, - // 100, - // valueBoxEditMode, - // ) { - // valueBoxEditMode = !valueBoxEditMode; - // } - // d.gui_set_style(TEXTBOX, TEXT_ALIGNMENT as i32, TEXT_ALIGN_LEFT as i32); - // if d.gui_text_box(rrect(25, 215, 125, 30), &mut textBoxText, textBoxEditMode) { - // textBoxEditMode = !textBoxEditMode; - // } - - // d.gui_set_style(BUTTON, TEXT_ALIGNMENT as i32, TEXT_ALIGN_CENTER as i32); - - // let itext = d.gui_icon_text(RICON_FILE_SAVE, Some(rstr!("Save File"))); - // let itext = CString::new(itext).unwrap(); - // if d.gui_button(rrect(25, 255, 125, 30), Some(&itext)) { - // showTextInputBox = true; - // } - - // d.gui_group_box(rrect(25, 310, 125, 150), Some(rstr!("STATES"))); - - // d.gui_lock(); - // d.gui_set_state(_NORMAL); - // if d.gui_button(rrect(30, 320, 115, 30), Some(rstr!("NORMAL"))) {} - // d.gui_set_state(_FOCUSED); - // if d.gui_button(rrect(30, 355, 115, 30), Some(rstr!("FOCUSED"))) {} - // d.gui_set_state(_PRESSED); - // if d.gui_button(rrect(30, 390, 115, 30), Some(rstr!("#15#PRESSED"))) {} - // d.gui_set_state(_DISABLED); - // if d.gui_button(rrect(30, 425, 115, 30), Some(rstr!("DISABLED"))) {} - // d.gui_set_state(_NORMAL); - // d.gui_unlock(); - - // comboBoxActive = d.gui_combo_box( - // rrect(25, 470, 125, 30), - // Some(rstr!("ONE;TWO;THREE;FOUR")), - // comboBoxActive, - // ); - - // // NOTE: GuiDropdownBox must draw after any other control that can be covered on unfolding - // d.gui_set_style( - // DROPDOWNBOX, - // TEXT_ALIGNMENT as i32, - // TEXT_ALIGN_LEFT as i32, - // ); - // if d.gui_dropdown_box( - // rrect(25, 65, 125, 30), - // Some(rstr!("#01#ONE;#02#TWO;#03#THREE;#04#FOUR")), - // &mut dropdownBox001Active, - // dropDown001EditMode, - // ) { - // dropDown001EditMode = !dropDown001EditMode; - // } - - // d.gui_set_style( - // DROPDOWNBOX, - // TEXT_ALIGNMENT as i32, - // TEXT_ALIGN_CENTER as i32, - // ); - // if d.gui_dropdown_box( - // rrect(25, 25, 125, 30), - // Some(rstr!("ONE;TWO;THREE")), - // &mut dropdownBox000Active, - // dropDown000EditMode, - // ) { - // dropDown000EditMode = !dropDown000EditMode; - // } - - // // Second GUI column - // listViewActive = d.gui_list_view( - // rrect(165, 25, 140, 140), - // Some(rstr!( - // "Charmander;Bulbasaur;#18#Squirtel;Pikachu;Eevee;Pidgey" - // )), - // &mut listViewScrollIndex, - // listViewActive, - // ); - // listViewExActive = d.gui_list_view_ex( - // rrect(165, 180, 140, 200), - // &listViewExList, - // 8, - // &mut listViewExFocus, - // &mut listViewExScrollIndex, - // listViewExActive, - // ); - - // toggleGroupActive = d.gui_toggle_group( - // rrect(165, 400, 140, 25), - // Some(rstr!("#1#ONE\n#3#TWO\n#8#THREE\n#23#")), - // toggleGroupActive, - // ); - - // // Third GUI column - // if d.gui_text_box_multi( - // rrect(320, 25, 225, 140), - // &mut multiTextBoxText, - // multiTextBoxEditMode, - // ) { - // multiTextBoxEditMode = !multiTextBoxEditMode; - // } - // colorPickerValue = d.gui_color_picker(rrect(320, 185, 196, 192), colorPickerValue); - - // sliderValue = d.gui_slider( - // rrect(355, 400, 165, 20), - // Some(rstr!("TEST")), - // Some(&rstr!("{:.2}", sliderValue as f32).unwrap()), - // sliderValue, - // -50.0, - // 100.0, - // ); - // sliderBarValue = d.gui_slider_bar( - // rrect(320, 430, 200, 20), - // None, - // Some(&rstr!("{}", sliderBarValue).unwrap()), - // sliderBarValue, - // 0.0, - // 100.0, - // ); - // progressValue = d.gui_progress_bar( - // rrect(320, 460, 200, 20), - // None, - // None, - // progressValue, - // 0.0, - // 1.0, - // ); - - // // NOTE: View rectangle could be used to perform some scissor test - // let (_view, nextScroll) = d.gui_scroll_panel( - // rrect(560, 25, 100, 160), - // rrect(560, 25, 200, 400), - // viewScroll, - // ); - // viewScroll = nextScroll.into(); - - // d.gui_status_bar( - // rrect(0, d.get_screen_height() - 20, d.get_screen_width(), 20), - // Some(rstr!("This is a status bar")), - // ); - - // alphaValue = d.gui_color_bar_alpha(rrect(320, 490, 200, 30), alphaValue); - - // if showMessageBox { - // d.draw_rectangle( - // 0, - // 0, - // d.get_screen_width(), - // d.get_screen_height(), - // Color::RAYWHITE.fade(0.8), - // ); - // let itext = d.gui_icon_text(RICON_EXIT, Some(rstr!("Close Window"))); - // let itext = CString::new(itext).unwrap(); - // let result = d.gui_message_box( - // rrect( - // d.get_screen_width() / 2 - 125, - // d.get_screen_height() / 2 - 50, - // 250, - // 100, - // ), - // Some(&itext), - // Some(rstr!("Do you really want to exit?")), - // Some(rstr!("Yes;No")), - // ); - - // if ((result == 0) || (result == 2)) { - // showMessageBox = false; - // } else if (result == 1) { - // exitWindow = true; - // } - // } - - // if showTextInputBox { - // d.draw_rectangle( - // 0, - // 0, - // d.get_screen_width(), - // d.get_screen_height(), - // Color::RAYWHITE.fade(0.8), - // ); - // let itext = unsafe { d.gui_icon_text(RICON_FILE_SAVE, Some(rstr!("Save file as..."))) }; - // let itext = CString::new(itext).unwrap(); - // let result = d.gui_text_input_box( - // rrect( - // d.get_screen_width() / 2 - 120, - // d.get_screen_height() / 2 - 60, - // 240, - // 140, - // ), - // Some(&itext), - // Some(rstr!("Introduce a save file name")), - // Some(rstr!("Ok;Cancel")), - // &mut textInput, - // ); - - // if (result == 1) { - // // TODO: Validate textInput value and save - // textInputFileName[..textInput.len()].clone_from_slice(&textInput); - // } - - // if ((result == 0) || (result == 1) || (result == 2)) { - // showTextInputBox = false; - // textInput[0] = b'\0'; - // } - // } - - // d.gui_unlock(); - unsafe { - ffi::EndDrawing(); } } } From 25e817a8187d86f21985a8f50865c83f3a37bf4a Mon Sep 17 00:00:00 2001 From: IoIxD Date: Sat, 28 Dec 2024 15:34:58 -0700 Subject: [PATCH 58/93] [rgui] enforce usage of GuiProperty enums --- raylib/src/consts.rs | 2 + raylib/src/rgui/safe.rs | 112 ++++++++++++++++++++++++++++++++++------ 2 files changed, 98 insertions(+), 16 deletions(-) diff --git a/raylib/src/consts.rs b/raylib/src/consts.rs index 797de7af..9a055ddd 100644 --- a/raylib/src/consts.rs +++ b/raylib/src/consts.rs @@ -38,7 +38,9 @@ pub use ffi::GuiSliderProperty; pub use ffi::GuiSpinnerProperty; pub use ffi::GuiState; pub use ffi::GuiTextAlignment; +pub use ffi::GuiTextAlignmentVertical; pub use ffi::GuiTextBoxProperty; +pub use ffi::GuiTextWrapMode; pub use ffi::GuiToggleProperty; pub use ffi::MouseCursor; pub use ffi::PI; diff --git a/raylib/src/rgui/safe.rs b/raylib/src/rgui/safe.rs index e68b6394..85f2988a 100644 --- a/raylib/src/rgui/safe.rs +++ b/raylib/src/rgui/safe.rs @@ -55,17 +55,24 @@ impl RaylibHandle { unsafe { WeakFont(ffi::GuiGetFont()) } } /// Set one style property - /// SHOULD use one of the Gui*Property enums #[inline] - pub fn gui_set_style(&mut self, control: crate::consts::GuiControl, property: i32, value: i32) { - unsafe { ffi::GuiSetStyle(control as i32, property as i32, value) } + pub fn gui_set_style( + &mut self, + control: crate::consts::GuiControl, + property: impl GuiProperty, + value: i32, + ) { + unsafe { ffi::GuiSetStyle(control as i32, property.as_i32(), value) } } /// Get one style property - /// SHOULD use one of the Gui*Property enums #[inline] - pub fn gui_get_style(&mut self, control: crate::consts::GuiControl, property: i32) -> i32 { - unsafe { ffi::GuiGetStyle(control as i32, property as i32) } + pub fn gui_get_style( + &mut self, + control: crate::consts::GuiControl, + property: impl GuiProperty, + ) -> i32 { + unsafe { ffi::GuiGetStyle(control as i32, property.as_i32()) } } /// Load style file (.rgs) #[inline] @@ -157,10 +164,14 @@ pub trait RaylibDrawGui { unsafe { WeakFont(ffi::GuiGetFont()) } } /// Set one style property - /// SHOULD use one of the Gui*Property enums #[inline] - fn gui_set_style(&mut self, control: crate::consts::GuiControl, property: i32, value: i32) { - unsafe { ffi::GuiSetStyle(control as i32, property as i32, value) } + fn gui_set_style( + &mut self, + control: crate::consts::GuiControl, + property: impl GuiProperty, + value: i32, + ) { + unsafe { ffi::GuiSetStyle(control as i32, property.as_i32(), value) } } /// Set gui controls alpha (global state), alpha goes from 0.0f to 1.0f @@ -171,10 +182,9 @@ pub trait RaylibDrawGui { } /// Get one style property - /// SHOULD use one of the Gui*Property enums #[inline] - fn gui_get_style(&self, control: crate::consts::GuiControl, property: i32) -> i32 { - unsafe { ffi::GuiGetStyle(control as i32, property as i32) } + fn gui_get_style(&self, control: crate::consts::GuiControl, property: impl GuiProperty) -> i32 { + unsafe { ffi::GuiGetStyle(control as i32, property.as_i32()) } } /// Load style file (.rgs) #[inline] @@ -374,15 +384,14 @@ pub trait RaylibDrawGui { fn gui_text_box( &mut self, bounds: impl Into, - buffer: &mut [u8], + buffer: &mut String, edit_mode: bool, ) -> bool { let len = buffer.len(); - let c_text = unsafe { CStr::from_bytes_with_nul_unchecked(buffer) }; unsafe { ffi::GuiTextBox( bounds.into(), - c_text.as_ptr() as *mut _, + buffer.as_mut_ptr() as *mut _, len as i32, edit_mode, ) > 0 @@ -562,7 +571,7 @@ pub trait RaylibDrawGui { title: impl Into, message: impl Into, buttons: impl Into, - text: &mut Vec, + text: &mut String, text_max_size: i32, secret_view_active: &mut bool, ) -> i32 { @@ -677,3 +686,74 @@ pub trait RaylibDrawGui { unsafe { ffi::GuiColorBarHue(bounds.into(), c_text.as_ptr(), value) > 0 } } } + +pub trait GuiProperty { + fn as_i32(self) -> i32; +} + +impl GuiProperty for crate::consts::GuiControlProperty { + fn as_i32(self) -> i32 { + self as i32 + } +} +impl GuiProperty for crate::consts::GuiDefaultProperty { + fn as_i32(self) -> i32 { + self as i32 + } +} +impl GuiProperty for crate::consts::GuiCheckBoxProperty { + fn as_i32(self) -> i32 { + self as i32 + } +} +impl GuiProperty for crate::consts::GuiColorPickerProperty { + fn as_i32(self) -> i32 { + self as i32 + } +} +impl GuiProperty for crate::consts::GuiComboBoxProperty { + fn as_i32(self) -> i32 { + self as i32 + } +} +impl GuiProperty for crate::consts::GuiDropdownBoxProperty { + fn as_i32(self) -> i32 { + self as i32 + } +} +impl GuiProperty for crate::consts::GuiListViewProperty { + fn as_i32(self) -> i32 { + self as i32 + } +} +impl GuiProperty for crate::consts::GuiProgressBarProperty { + fn as_i32(self) -> i32 { + self as i32 + } +} +impl GuiProperty for crate::consts::GuiScrollBarProperty { + fn as_i32(self) -> i32 { + self as i32 + } +} +impl GuiProperty for crate::consts::GuiSliderProperty { + fn as_i32(self) -> i32 { + self as i32 + } +} +impl GuiProperty for crate::consts::GuiSpinnerProperty { + fn as_i32(self) -> i32 { + self as i32 + } +} +impl GuiProperty for crate::consts::GuiToggleProperty { + fn as_i32(self) -> i32 { + self as i32 + } +} + +impl GuiProperty for i32 { + fn as_i32(self) -> i32 { + self + } +} From ded9b798dd96f415ce5774e8105ca726c401b5cc Mon Sep 17 00:00:00 2001 From: IoIxD Date: Sat, 28 Dec 2024 15:39:45 -0700 Subject: [PATCH 59/93] [rgui] impl Into -> &str --- raylib/src/rgui/safe.rs | 190 +++++++++++++++++----------------------- 1 file changed, 82 insertions(+), 108 deletions(-) diff --git a/raylib/src/rgui/safe.rs b/raylib/src/rgui/safe.rs index 85f2988a..810b34ea 100644 --- a/raylib/src/rgui/safe.rs +++ b/raylib/src/rgui/safe.rs @@ -76,8 +76,8 @@ impl RaylibHandle { } /// Load style file (.rgs) #[inline] - pub fn gui_load_style(&mut self, filename: impl Into) { - let c_filename = CString::new(filename.into()).unwrap(); + pub fn gui_load_style(&mut self, filename: &str) { + let c_filename = CString::new(filename).unwrap(); unsafe { ffi::GuiLoadStyle(c_filename.as_ptr()) } } /// Load style default over global style @@ -100,8 +100,8 @@ impl RaylibHandle { /// Set tooltip string #[inline] - pub fn gui_set_tooltip(&mut self, tooltip: impl Into) { - let c_text = CString::new(tooltip.into()).unwrap(); + pub fn gui_set_tooltip(&mut self, tooltip: &str) { + let c_text = CString::new(tooltip).unwrap(); unsafe { ffi::GuiSetTooltip(c_text.as_ptr()); } @@ -188,8 +188,8 @@ pub trait RaylibDrawGui { } /// Load style file (.rgs) #[inline] - fn gui_load_style(&mut self, filename: impl Into) { - let c_filename = CString::new(filename.into()).unwrap(); + fn gui_load_style(&mut self, filename: &str) { + let c_filename = CString::new(filename).unwrap(); unsafe { ffi::GuiLoadStyle(c_filename.as_ptr()) } } /// Load style default over global style @@ -199,34 +199,26 @@ pub trait RaylibDrawGui { } /// Window Box control, shows a window that can be closed #[inline] - fn gui_window_box( - &mut self, - bounds: impl Into, - title: impl Into, - ) -> bool { - let c_filename = CString::new(title.into()).unwrap(); + fn gui_window_box(&mut self, bounds: impl Into, title: &str) -> bool { + let c_filename = CString::new(title).unwrap(); unsafe { ffi::GuiWindowBox(bounds.into(), c_filename.as_ptr()) > 0 } } /// Group Box control with text name #[inline] - fn gui_group_box( - &mut self, - bounds: impl Into, - text: impl Into, - ) -> bool { - let c_filename = CString::new(text.into()).unwrap(); + fn gui_group_box(&mut self, bounds: impl Into, text: &str) -> bool { + let c_filename = CString::new(text).unwrap(); unsafe { ffi::GuiGroupBox(bounds.into(), c_filename.as_ptr()) > 0 } } /// Line separator control, could contain text #[inline] - fn gui_line(&mut self, bounds: impl Into, text: impl Into) -> bool { - let c_filename = CString::new(text.into()).unwrap(); + fn gui_line(&mut self, bounds: impl Into, text: &str) -> bool { + let c_filename = CString::new(text).unwrap(); unsafe { ffi::GuiLine(bounds.into(), c_filename.as_ptr()) > 0 } } /// Panel control, useful to group controls #[inline] - fn gui_panel(&mut self, bounds: impl Into, text: impl Into) -> bool { - let c_filename = CString::new(text.into()).unwrap(); + fn gui_panel(&mut self, bounds: impl Into, text: &str) -> bool { + let c_filename = CString::new(text).unwrap(); unsafe { ffi::GuiPanel(bounds.into(), c_filename.as_ptr()) > 0 } } /// Scroll Panel control @@ -234,14 +226,14 @@ pub trait RaylibDrawGui { fn gui_scroll_panel( &mut self, bounds: impl Into, - text: impl Into, + text: &str, content: impl Into, scroll: impl Into, view: impl Into, ) -> (bool, Rectangle, Vector2) { let mut scroll = scroll.into(); let mut view = view.into(); - let c_filename = CString::new(text.into()).unwrap(); + let c_filename = CString::new(text).unwrap(); let result = unsafe { ffi::GuiScrollPanel( bounds.into(), @@ -255,24 +247,20 @@ pub trait RaylibDrawGui { } /// Label control, shows text #[inline] - fn gui_label(&mut self, bounds: impl Into, text: impl Into) -> bool { - let c_text = CString::new(text.into()).unwrap(); + fn gui_label(&mut self, bounds: impl Into, text: &str) -> bool { + let c_text = CString::new(text).unwrap(); unsafe { ffi::GuiLabel(bounds.into(), c_text.as_ptr()) > 0 } } /// Button control, returns true when clicked #[inline] - fn gui_button(&mut self, bounds: impl Into, text: impl Into) -> bool { - let c_text = CString::new(text.into()).unwrap(); + fn gui_button(&mut self, bounds: impl Into, text: &str) -> bool { + let c_text = CString::new(text).unwrap(); unsafe { ffi::GuiButton(bounds.into(), c_text.as_ptr()) > 0 } } /// Label button control, show true when clicked #[inline] - fn gui_label_button( - &mut self, - bounds: impl Into, - text: impl Into, - ) -> bool { - let c_text = CString::new(text.into()).unwrap(); + fn gui_label_button(&mut self, bounds: impl Into, text: &str) -> bool { + let c_text = CString::new(text).unwrap(); unsafe { ffi::GuiLabelButton(bounds.into(), c_text.as_ptr()) > 0 } } /// Toggle Button control, returns true when active @@ -280,10 +268,10 @@ pub trait RaylibDrawGui { fn gui_toggle( &mut self, bounds: impl Into, - text: impl Into, + text: &str, active: &mut bool, ) -> bool { - let c_text = CString::new(text.into()).unwrap(); + let c_text = CString::new(text).unwrap(); unsafe { ffi::GuiToggle(bounds.into(), c_text.as_ptr(), active) > 0 } } /// Toggle Group control, returns active toggle index @@ -291,10 +279,10 @@ pub trait RaylibDrawGui { fn gui_toggle_group( &mut self, bounds: impl Into, - text: impl Into, + text: &str, active: &mut i32, ) -> i32 { - let c_text = CString::new(text.into()).unwrap(); + let c_text = CString::new(text).unwrap(); unsafe { ffi::GuiToggleGroup(bounds.into(), c_text.as_ptr(), active) } } /// Check Box control, returns true when active @@ -302,10 +290,10 @@ pub trait RaylibDrawGui { fn gui_check_box( &mut self, bounds: impl Into, - text: impl Into, + text: &str, checked: &mut bool, ) -> bool { - let c_text = CString::new(text.into()).unwrap(); + let c_text = CString::new(text).unwrap(); unsafe { ffi::GuiCheckBox(bounds.into(), c_text.as_ptr(), checked) > 0 } } /// Combo Box control, returns selected item index @@ -313,10 +301,10 @@ pub trait RaylibDrawGui { fn gui_combo_box( &mut self, bounds: impl Into, - text: impl Into, + text: &str, active: &mut i32, ) -> i32 { - let c_text = CString::new(text.into()).unwrap(); + let c_text = CString::new(text).unwrap(); unsafe { ffi::GuiComboBox(bounds.into(), c_text.as_ptr(), active) } } /// Dropdown Box control, returns selected item @@ -324,11 +312,11 @@ pub trait RaylibDrawGui { fn gui_dropdown_box( &mut self, bounds: impl Into, - text: impl Into, + text: &str, active: &mut i32, edit_mode: bool, ) -> bool { - let c_text = CString::new(text.into()).unwrap(); + let c_text = CString::new(text).unwrap(); unsafe { ffi::GuiDropdownBox(bounds.into(), c_text.as_ptr(), active, edit_mode) > 0 } } /// Spinner control, returns selected value @@ -336,13 +324,13 @@ pub trait RaylibDrawGui { fn gui_spinner( &mut self, bounds: impl Into, - text: impl Into, + text: &str, value: &mut i32, min_value: i32, max_value: i32, edit_mode: bool, ) -> bool { - let c_text = CString::new(text.into()).unwrap(); + let c_text = CString::new(text).unwrap(); unsafe { ffi::GuiSpinner( bounds.into(), @@ -360,13 +348,13 @@ pub trait RaylibDrawGui { fn gui_value_box( &mut self, bounds: impl Into, - text: impl Into, + text: &str, value: &mut i32, min_value: i32, max_value: i32, edit_mode: bool, ) -> bool { - let c_text = CString::new(text.into()).unwrap(); + let c_text = CString::new(text).unwrap(); unsafe { ffi::GuiValueBox( bounds.into(), @@ -403,14 +391,14 @@ pub trait RaylibDrawGui { fn gui_slider( &mut self, bounds: impl Into, - text_left: impl Into, - text_right: impl Into, + text_left: &str, + text_right: &str, value: &mut f32, min_value: f32, max_value: f32, ) -> bool { - let c_text_left = CString::new(text_left.into()).unwrap(); - let c_text_right = CString::new(text_right.into()).unwrap(); + let c_text_left = CString::new(text_left).unwrap(); + let c_text_right = CString::new(text_right).unwrap(); unsafe { ffi::GuiSlider( bounds.into(), @@ -427,14 +415,14 @@ pub trait RaylibDrawGui { fn gui_slider_bar( &mut self, bounds: impl Into, - text_left: impl Into, - text_right: impl Into, + text_left: &str, + text_right: &str, value: &mut f32, min_value: f32, max_value: f32, ) -> bool { - let c_text_left = CString::new(text_left.into()).unwrap(); - let c_text_right = CString::new(text_right.into()).unwrap(); + let c_text_left = CString::new(text_left).unwrap(); + let c_text_right = CString::new(text_right).unwrap(); unsafe { ffi::GuiSliderBar( bounds.into(), @@ -451,14 +439,14 @@ pub trait RaylibDrawGui { fn gui_progress_bar( &mut self, bounds: impl Into, - text_left: impl Into, - text_right: impl Into, + text_left: &str, + text_right: &str, value: &mut f32, min_value: f32, max_value: f32, ) -> bool { - let c_text_left = CString::new(text_left.into()).unwrap(); - let c_text_right = CString::new(text_right.into()).unwrap(); + let c_text_left = CString::new(text_left).unwrap(); + let c_text_right = CString::new(text_right).unwrap(); unsafe { ffi::GuiProgressBar( bounds.into(), @@ -472,12 +460,8 @@ pub trait RaylibDrawGui { } /// Status Bar control, shows info text #[inline] - fn gui_status_bar( - &mut self, - bounds: impl Into, - text: impl Into, - ) -> bool { - let c_text = CString::new(text.into()).unwrap(); + fn gui_status_bar(&mut self, bounds: impl Into, text: &str) -> bool { + let c_text = CString::new(text).unwrap(); unsafe { ffi::GuiStatusBar(bounds.into(), c_text.as_ptr()) > 0 } } @@ -486,11 +470,11 @@ pub trait RaylibDrawGui { fn gui_grid( &mut self, bounds: impl Into, - text: impl Into, + text: &str, spacing: f32, subdivs: i32, ) -> (bool, Vector2) { - let c_text = CString::new(text.into()).unwrap(); + let c_text = CString::new(text).unwrap(); let mut mouseCell = ffi::Vector2 { x: 0.0, y: 0.0 }; ( unsafe { @@ -510,11 +494,11 @@ pub trait RaylibDrawGui { fn gui_list_view( &mut self, bounds: impl Into, - text: impl Into, + text: &str, scroll_index: &mut i32, active: &mut i32, ) -> i32 { - let c_text = CString::new(text.into()).unwrap(); + let c_text = CString::new(text).unwrap(); unsafe { ffi::GuiListView(bounds.into(), c_text.as_ptr(), scroll_index, active) } } /// List View with extended parameters @@ -547,13 +531,13 @@ pub trait RaylibDrawGui { fn gui_message_box( &mut self, bounds: impl Into, - text: impl Into, - message: impl Into, - buttons: impl Into, + text: &str, + message: &str, + buttons: &str, ) -> i32 { - let c_text = CString::new(text.into()).unwrap(); - let c_message = CString::new(message.into()).unwrap(); - let c_buttons = CString::new(buttons.into()).unwrap(); + let c_text = CString::new(text).unwrap(); + let c_message = CString::new(message).unwrap(); + let c_buttons = CString::new(buttons).unwrap(); unsafe { ffi::GuiMessageBox( bounds.into(), @@ -568,18 +552,18 @@ pub trait RaylibDrawGui { fn gui_text_input_box( &mut self, bounds: impl Into, - title: impl Into, - message: impl Into, - buttons: impl Into, + title: &str, + message: &str, + buttons: &str, text: &mut String, text_max_size: i32, secret_view_active: &mut bool, ) -> i32 { // rgui.h: line 3699 MAX_FILENAME_LEN text.reserve((256 - text.len()).max(0) as usize); - let c_title = CString::new(title.into()).unwrap(); - let c_message = CString::new(message.into()).unwrap(); - let c_buttons = CString::new(buttons.into()).unwrap(); + let c_title = CString::new(title).unwrap(); + let c_message = CString::new(message).unwrap(); + let c_buttons = CString::new(buttons).unwrap(); let btn_index = unsafe { ffi::GuiTextInputBox( bounds.into(), @@ -600,11 +584,11 @@ pub trait RaylibDrawGui { fn gui_color_picker( &mut self, bounds: impl Into, - text: impl Into, + text: &str, color: impl Into, ) -> Color { let mut out = color.into(); - let c_text = CString::new(text.into()).unwrap(); + let c_text = CString::new(text).unwrap(); let result = unsafe { ffi::GuiColorPicker(bounds.into(), c_text.as_ptr(), &mut out) }; return out.into(); @@ -613,12 +597,8 @@ pub trait RaylibDrawGui { // NOTE: Useful to add icons by name id (enum) instead of // a number that can change between ricon versions #[inline] - fn gui_icon_text( - &mut self, - icon_id: crate::consts::GuiIconName, - text: impl Into, - ) -> String { - let c_text = CString::new(text.into()).unwrap(); + fn gui_icon_text(&mut self, icon_id: crate::consts::GuiIconName, text: &str) -> String { + let c_text = CString::new(text).unwrap(); let buffer = unsafe { ffi::GuiIconText(icon_id as i32, c_text.as_ptr()) }; if buffer.is_null() { let ptr = c_text.as_ptr(); @@ -640,10 +620,10 @@ pub trait RaylibDrawGui { fn gui_color_bar_alpha( &mut self, bounds: impl Into, - text: impl Into, + text: &str, alpha: &mut f32, ) -> bool { - let c_text = CString::new(text.into()).unwrap(); + let c_text = CString::new(text).unwrap(); unsafe { ffi::GuiColorBarAlpha(bounds.into(), c_text.as_ptr(), alpha) > 0 } } @@ -653,22 +633,18 @@ pub trait RaylibDrawGui { fn gui_toggle_slider( &mut self, bounds: impl Into, - text: impl Into, + text: &str, active: &mut i32, ) -> bool { - let c_text = CString::new(text.into()).unwrap(); + let c_text = CString::new(text).unwrap(); unsafe { ffi::GuiToggleSlider(bounds.into(), c_text.as_ptr(), active) > 0 } } /// Dummy control for placeholders #[inline] - fn gui_dummy_rec( - &mut self, - bounds: impl Into, - text: impl Into, - ) -> bool { - let c_text = CString::new(text.into()).unwrap(); + fn gui_dummy_rec(&mut self, bounds: impl Into, text: &str) -> bool { + let c_text = CString::new(text).unwrap(); unsafe { ffi::GuiDummyRec(bounds.into(), c_text.as_ptr()) > 0 } } @@ -678,15 +654,19 @@ pub trait RaylibDrawGui { fn gui_color_bar_hue( &mut self, bounds: impl Into, - text: impl Into, + text: &str, value: &mut f32, ) -> bool { - let c_text = CString::new(text.into()).unwrap(); + let c_text = CString::new(text).unwrap(); unsafe { ffi::GuiColorBarHue(bounds.into(), c_text.as_ptr(), value) > 0 } } } +#[diagnostic::on_unimplemented( + message = "{Self} is not a gui property, or does not implement the GuiProperty trait.", + note = "As of Raylib 5.5, raygui functions that once took \"property enum as i32\" now just take the enum." +)] pub trait GuiProperty { fn as_i32(self) -> i32; } @@ -751,9 +731,3 @@ impl GuiProperty for crate::consts::GuiToggleProperty { self as i32 } } - -impl GuiProperty for i32 { - fn as_i32(self) -> i32 { - self - } -} From aae1d32908809725c4255f79ef9634dc19b0a7f3 Mon Sep 17 00:00:00 2001 From: IoIxD <30945097+IoIxD@users.noreply.github.com> Date: Sat, 28 Dec 2024 18:40:23 -0700 Subject: [PATCH 60/93] [imgui] accidentally left an import in mod.rs that errors if imgui feature isn't on (#113) --- raylib/src/core/mod.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/raylib/src/core/mod.rs b/raylib/src/core/mod.rs index 67136609..6c6e1b8f 100644 --- a/raylib/src/core/mod.rs +++ b/raylib/src/core/mod.rs @@ -26,7 +26,6 @@ pub mod window; use raylib_sys::TraceLogLevel; use crate::ffi; -use crate::imgui::init_imgui_context; use std::ffi::CString; use std::marker::PhantomData; @@ -215,7 +214,7 @@ impl RaylibBuilder { #[cfg(feature = "imgui")] unsafe { - init_imgui_context(self.imgui_theme == crate::imgui::ImGuiTheme::Dark); + crate::imgui::init_imgui_context(self.imgui_theme == crate::imgui::ImGuiTheme::Dark); } (rl, RaylibThread(PhantomData)) From ba1f5d9ebc88e04057a379ca2500b71072483975 Mon Sep 17 00:00:00 2001 From: Teddy Astie Date: Mon, 30 Dec 2024 20:23:27 +0100 Subject: [PATCH 61/93] Rework gui_list_view_ex. Working with CStr is not practical, and expecting the user to have to manipulate them is even less. Users are very likely to need to make a wrapper in order use this interface, so rework it to make it better to use. Expect a iterator of String for the text, this is more flexible than using a array and doesn't complicate the implementation as we will have to convert it to a list of CStr anyway. --- raylib/src/rgui/safe.rs | 20 ++++++++++++-------- samples/rgui.rs | 18 +++++++++--------- 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/raylib/src/rgui/safe.rs b/raylib/src/rgui/safe.rs index 810b34ea..9d1c86f7 100644 --- a/raylib/src/rgui/safe.rs +++ b/raylib/src/rgui/safe.rs @@ -5,7 +5,7 @@ use crate::core::text::WeakFont; use crate::core::RaylibHandle; use crate::ffi; -use std::ffi::{CStr, CString}; +use std::ffi::{c_char, CStr, CString}; /// Global gui modification functions impl RaylibHandle { @@ -506,20 +506,24 @@ pub trait RaylibDrawGui { fn gui_list_view_ex( &mut self, bounds: impl Into, - text: &[&CStr], + text: impl Iterator>, focus: &mut i32, scroll_index: &mut i32, active: &mut i32, ) -> i32 { - let mut buffer = Vec::with_capacity(text.len()); - for t in text { - buffer.push(t.as_ptr()); - } + // We need to keep track of all CStr buffers. + let buffer: Box<[Box]> = text + .map(|s| CString::new(s.as_ref()).unwrap().into_boxed_c_str()) + .collect(); + + let mut text_params: Box<[*const c_char]> = + buffer.iter().map(|cstr| cstr.as_ptr()).collect(); + unsafe { ffi::GuiListViewEx( bounds.into(), - buffer.as_mut_ptr(), - text.len() as i32, + text_params.as_mut_ptr(), + text_params.len() as i32, focus, scroll_index, active, diff --git a/samples/rgui.rs b/samples/rgui.rs index 06af2fc2..dcbedf62 100644 --- a/samples/rgui.rs +++ b/samples/rgui.rs @@ -54,14 +54,14 @@ pub fn main() { let mut listViewExActive = 2; let mut listViewExFocus = -1; let mut listViewExList = [ - c"This", - c"is", - c"a", - c"list view", - c"with", - c"disable", - c"elements", - c"amazing!", + "This", + "is", + "a", + "list view", + "with", + "disable", + "elements", + "amazing!", ]; let colorPickerValue = Color::RED; @@ -296,7 +296,7 @@ pub fn main() { ); d.gui_list_view_ex( Rectangle::new(165.0, 162.0, 140.0, 184.0), - &listViewExList, + listViewExList.iter(), &mut listViewExScrollIndex, &mut listViewExActive, &mut listViewExFocus, From 6d0d128baf1d5700b82ef2ae2af55623cb65dc9b Mon Sep 17 00:00:00 2001 From: Teddy Astie Date: Tue, 31 Dec 2024 00:24:13 +0100 Subject: [PATCH 62/93] Various examples fixes (#115) * Remove [[example]] entries of raylib/Cargo.toml Those entries actually point nowhere and makes cargo build --examples fail confusingly. As they are actually replaced with what we have in samples, we can remove them. * Remove examples scrapping As we don't have a raylib/examples directory, this feature doesn't do anything anymore. * Bump rand dependency in samples. 3d_camera_first_person uses gen_range expecting a range, which is only the case for rand 0.8. * Remove excessive parents in shader multisample example Fixes a cargo check warning. --- raylib/Cargo.toml | 90 ----------------------------------- samples/Cargo.toml | 2 +- samples/shader_multisample.rs | 4 +- 3 files changed, 3 insertions(+), 93 deletions(-) diff --git a/raylib/Cargo.toml b/raylib/Cargo.toml index ed62bcef..1fad2aaf 100644 --- a/raylib/Cargo.toml +++ b/raylib/Cargo.toml @@ -44,93 +44,3 @@ sdl = ["raylib-sys/sdl"] noscreenshot = ["raylib-sys/noscreenshot"] nogif = ["raylib-sys/nogif"] imgui = ["raylib-sys/imgui", "dep:imgui", "dep:imgui-sys"] - -[[example]] -name = "specs" -path = "examples/samples/specs.rs" -doc-scrape-examples = true - -[[example]] -name = "rgui" -path = "examples/samples/rgui.rs" -doc-scrape-examples = true - -[[example]] -name = "arkanoid" -path = "examples/samples/arkanoid.rs" -doc-scrape-examples = true - -[[example]] -name = "logo" -path = "examples/samples/logo.rs" -doc-scrape-examples = true - - -[[example]] -name = "camera2D" -path = "examples/samples/camera2D.rs" -doc-scrape-examples = true - -[[example]] -name = "raymarch" -path = "examples/samples/raymarch.rs" -doc-scrape-examples = true - -[[example]] -name = "font" -path = "examples/samples/font.rs" -doc-scrape-examples = true - -[[example]] -name = "drop" -path = "examples/samples/drop.rs" -doc-scrape-examples = true - -[[example]] -name = "texture" -path = "examples/samples/texture.rs" -doc-scrape-examples = true - -[[example]] -name = "yaw_pitch_roll" -path = "examples/samples/yaw_pitch_roll.rs" -doc-scrape-examples = true - -[[example]] -name = "roguelike" -path = "examples/samples/roguelike.rs" -required-features = ["with_serde"] -doc-scrape-examples = true - -[[example]] -name = "input" -path = "examples/samples/input.rs" -doc-scrape-examples = true - -[[example]] -name = "3d_camera_first_person" -path = "examples/samples/3d_camera_first_person.rs" -doc-scrape-examples = true - -[[example]] -name = "model_shader" -path = "examples/samples/model_shader.rs" -doc-scrape-examples = true - -[[example]] -name = "extensions" -path = "examples/samples/extensions.rs" -doc-scrape-examples = true - -[[example]] -name = "asteroids" -path = "examples/samples/asteroids.rs" -doc-scrape-examples = true - -[[example]] -name = "floppy" -path = "examples/samples/floppy.rs" -doc-scrape-examples = true - -[package.metadata.docs.rs] -cargo-args = ["-Zunstable-options", "-Zrustdoc-scrape-examples"] diff --git a/samples/Cargo.toml b/samples/Cargo.toml index ed1f986e..82f942b5 100644 --- a/samples/Cargo.toml +++ b/samples/Cargo.toml @@ -12,7 +12,7 @@ repository = "https://github.com/raylib-rs/raylib-rs" raylib = { version = "5.5.0", path = "../raylib" } structopt = "0.2" specs-derive = "0.4.1" -rand = "0.7" +rand = "0.8" #tcod = "0.14" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" diff --git a/samples/shader_multisample.rs b/samples/shader_multisample.rs index 5f658310..3792f581 100644 --- a/samples/shader_multisample.rs +++ b/samples/shader_multisample.rs @@ -26,9 +26,9 @@ pub fn main() { divider_value -= 0.01; } - if (divider_value < 0.0) { + if divider_value < 0.0 { divider_value = 0.0; - } else if (divider_value > 1.0) { + } else if divider_value > 1.0 { divider_value = 1.0; }; rl.start_drawing(&thread, |mut d| { From 765475261de8eca2c47773d984fa9381e9f549c0 Mon Sep 17 00:00:00 2001 From: Teddy Astie Date: Wed, 22 Jan 2025 20:00:38 +0100 Subject: [PATCH 63/93] Audio improvements (#116) * Make audio.rs more concise and consistent. Add some missing inlines and remove some superfluous syntax. * Rework WaveSamples structure. WaveSamples can be made a lot more simpler and less bug-prone. --- raylib/src/core/audio.rs | 163 +++++++++++++++------------------------ 1 file changed, 63 insertions(+), 100 deletions(-) diff --git a/raylib/src/core/audio.rs b/raylib/src/core/audio.rs index e801fb07..c95a60f9 100644 --- a/raylib/src/core/audio.rs +++ b/raylib/src/core/audio.rs @@ -4,8 +4,6 @@ use crate::error::{error, Error}; use crate::ffi; use std::ffi::CString; use std::marker::PhantomData; -use std::mem::ManuallyDrop; -use std::ops::{Deref, DerefMut}; use std::path::Path; make_thin_wrapper_lifetime!(Wave, ffi::Wave, RaylibAudio, ffi::UnloadWave); @@ -19,7 +17,19 @@ make_thin_wrapper_lifetime!( ffi::UnloadAudioStream ); -make_rslice!(WaveSamples, f32, ffi::UnloadWaveSamples); +pub struct WaveSamples(*mut f32, usize); + +impl AsRef<[f32]> for WaveSamples { + fn as_ref(&self) -> &[f32] { + unsafe { std::slice::from_raw_parts(self.0, self.1) } + } +} + +impl Drop for WaveSamples { + fn drop(&mut self) { + unsafe { ffi::UnloadWaveSamples(self.0) } + } +} /// A marker trait specifying an audio sample (`u8`, `i16`, or `f32`). pub trait AudioSample {} @@ -52,8 +62,7 @@ impl RaylibAudio { #[inline] pub fn init_audio_device() -> Result { unsafe { - let t = ffi::IsAudioDeviceReady(); - if t { + if ffi::IsAudioDeviceReady() { return Err(RaylibAudioInitError); } ffi::InitAudioDevice(); @@ -68,6 +77,7 @@ impl RaylibAudio { } /// Get master volume (listener) + #[inline] pub fn get_master_volume(&self) -> f32 { unsafe { ffi::GetMasterVolume() } } @@ -75,12 +85,11 @@ impl RaylibAudio { /// Sets master volume (listener). #[inline] pub fn set_master_volume(&self, volume: f32) { - unsafe { - ffi::SetMasterVolume(volume); - } + unsafe { ffi::SetMasterVolume(volume) } } /// Loads a new sound from file. + #[inline] pub fn new_sound<'aud>(&'aud self, filename: &str) -> Result, Error> { let c_filename = CString::new(filename).unwrap(); let s = unsafe { ffi::LoadSound(c_filename.as_ptr()) }; @@ -92,6 +101,7 @@ impl RaylibAudio { } /// Loads sound from wave data. + #[inline] pub fn new_sound_from_wave<'aud>(&'aud self, wave: &Wave) -> Result, Error> { let s = unsafe { ffi::LoadSoundFromWave(wave.0) }; if s.stream.buffer.is_null() { @@ -111,15 +121,16 @@ impl RaylibAudio { } /// Load wave from memory buffer, fileType refers to extension: i.e. '.wav' + #[inline] pub fn new_wave_from_memory<'aud>( &'aud self, filetype: &str, bytes: &[u8], ) -> Result, Error> { let c_filetype = CString::new(filetype).unwrap(); - let c_bytes = bytes.as_ptr(); - let w = - unsafe { ffi::LoadWaveFromMemory(c_filetype.as_ptr(), c_bytes, bytes.len() as i32) }; + let w = unsafe { + ffi::LoadWaveFromMemory(c_filetype.as_ptr(), bytes.as_ptr(), bytes.len() as i32) + }; if w.data.is_null() { return Err(error!("Wave data is null. Check provided buffer data")); }; @@ -127,7 +138,7 @@ impl RaylibAudio { } /// Loads music stream from file. - // #[inline] + #[inline] pub fn new_music<'aud>(&'aud self, filename: &str) -> Result, Error> { let c_filename = CString::new(filename).unwrap(); let m = unsafe { ffi::LoadMusicStream(c_filename.as_ptr()) }; @@ -138,15 +149,15 @@ impl RaylibAudio { } /// Load music stream from data + #[inline] pub fn new_music_from_memory<'aud>( &'aud self, filetype: &str, bytes: &Vec, ) -> Result, Error> { let c_filetype = CString::new(filetype).unwrap(); - let c_bytes = bytes.as_ptr(); let w = unsafe { - ffi::LoadMusicStreamFromMemory(c_filetype.as_ptr(), c_bytes, bytes.len() as i32) + ffi::LoadMusicStreamFromMemory(c_filetype.as_ptr(), bytes.as_ptr(), bytes.len() as i32) }; if w.stream.buffer.is_null() { return Err(error!( @@ -175,9 +186,7 @@ impl RaylibAudio { impl<'aud> Drop for RaylibAudio { fn drop(&mut self) { - unsafe { - ffi::CloseAudioDevice(); - } + unsafe { ffi::CloseAudioDevice() } } } @@ -200,6 +209,7 @@ impl<'aud> Wave<'aud> { inner } + #[inline] pub fn is_wave_valid(&self) -> bool { unsafe { ffi::IsWaveValid(self.0) } } @@ -227,17 +237,13 @@ impl<'aud> Wave<'aud> { /// Converts wave data to desired format. #[inline] pub fn format(&mut self, sample_rate: i32, sample_size: i32, channels: i32) { - unsafe { - ffi::WaveFormat(&mut self.0, sample_rate, sample_size, channels); - } + unsafe { ffi::WaveFormat(&mut self.0, sample_rate, sample_size, channels) } } /// Crops a wave to defined sample range. #[inline] pub fn crop(&mut self, init_sample: i32, final_sample: i32) { - unsafe { - ffi::WaveCrop(&mut self.0, init_sample, final_sample); - } + unsafe { ffi::WaveCrop(&mut self.0, init_sample, final_sample) } } /// Load samples data from wave as a floats array @@ -245,14 +251,10 @@ impl<'aud> Wave<'aud> { /// NOTE 2: Sample data allocated should be freed with UnloadWaveSamples() #[inline] pub fn load_samples(&self) -> WaveSamples { - let as_slice = unsafe { - let data = ffi::LoadWaveSamples(self.0); - Box::from_raw(std::slice::from_raw_parts_mut( - data, - self.frame_count() as usize, - )) - }; - WaveSamples(ManuallyDrop::new(as_slice)) + WaveSamples( + unsafe { ffi::LoadWaveSamples(self.0) }, + self.frameCount as usize, + ) } } @@ -285,33 +287,25 @@ impl<'aud> Sound<'aud> { /// Plays a sound. #[inline] pub fn play(&self) { - unsafe { - ffi::PlaySound(self.0); - } + unsafe { ffi::PlaySound(self.0) } } /// Pauses a sound. #[inline] pub fn pause(&self) { - unsafe { - ffi::PauseSound(self.0); - } + unsafe { ffi::PauseSound(self.0) } } /// Resumes a paused sound. #[inline] pub fn resume(&self) { - unsafe { - ffi::ResumeSound(self.0); - } + unsafe { ffi::ResumeSound(self.0) } } /// Stops playing a sound. #[inline] pub fn stop(&self) { - unsafe { - ffi::StopSound(self.0); - } + unsafe { ffi::StopSound(self.0) } } /// Checks if a sound is currently playing. @@ -323,22 +317,18 @@ impl<'aud> Sound<'aud> { /// Sets volume for a sound (`1.0` is max level). #[inline] pub fn set_volume(&self, volume: f32) { - unsafe { - ffi::SetSoundVolume(self.0, volume); - } + unsafe { ffi::SetSoundVolume(self.0, volume) } } /// Sets pitch for a sound (`1.0` is base level). #[inline] pub fn set_pitch(&self, pitch: f32) { - unsafe { - ffi::SetSoundPitch(self.0, pitch); - } + unsafe { ffi::SetSoundPitch(self.0, pitch) } } + + #[inline] pub fn set_pan(&self, pan: f32) { - unsafe { - ffi::SetSoundPan(self.0, pan); - } + unsafe { ffi::SetSoundPan(self.0, pan) } } // Uncomment this when Raylib fulfills the todo comment within the original function to make the function safe. @@ -372,33 +362,25 @@ impl<'aud, 'bind> SoundAlias<'aud, 'bind> { /// Plays a sound. #[inline] pub fn play(&self) { - unsafe { - ffi::PlaySound(self.0); - } + unsafe { ffi::PlaySound(self.0) } } /// Pauses a sound. #[inline] pub fn pause(&self) { - unsafe { - ffi::PauseSound(self.0); - } + unsafe { ffi::PauseSound(self.0) } } /// Resumes a paused sound. #[inline] pub fn resume(&self) { - unsafe { - ffi::ResumeSound(self.0); - } + unsafe { ffi::ResumeSound(self.0) } } /// Stops playing a sound. #[inline] pub fn stop(&self) { - unsafe { - ffi::StopSound(self.0); - } + unsafe { ffi::StopSound(self.0) } } /// Checks if a sound is currently playing. @@ -410,22 +392,18 @@ impl<'aud, 'bind> SoundAlias<'aud, 'bind> { /// Sets volume for a sound (`1.0` is max level). #[inline] pub fn set_volume(&self, volume: f32) { - unsafe { - ffi::SetSoundVolume(self.0, volume); - } + unsafe { ffi::SetSoundVolume(self.0, volume) } } /// Sets pitch for a sound (`1.0` is base level). #[inline] pub fn set_pitch(&self, pitch: f32) { - unsafe { - ffi::SetSoundPitch(self.0, pitch); - } + unsafe { ffi::SetSoundPitch(self.0, pitch) } } + + #[inline] pub fn set_pan(&self, pan: f32) { - unsafe { - ffi::SetSoundPan(self.0, pan); - } + unsafe { ffi::SetSoundPan(self.0, pan) } } } @@ -439,41 +417,31 @@ impl<'aud> Music<'aud> { /// Starts music playing. #[inline] pub fn play_stream(&self) { - unsafe { - ffi::PlayMusicStream(self.0); - } + unsafe { ffi::PlayMusicStream(self.0) } } /// Updates buffers for music streaming. #[inline] pub fn update_stream(&self) { - unsafe { - ffi::UpdateMusicStream(self.0); - } + unsafe { ffi::UpdateMusicStream(self.0) } } /// Stops music playing. #[inline] pub fn stop_stream(&self) { - unsafe { - ffi::StopMusicStream(self.0); - } + unsafe { ffi::StopMusicStream(self.0) } } /// Pauses music playing. #[inline] pub fn pause_stream(&self) { - unsafe { - ffi::PauseMusicStream(self.0); - } + unsafe { ffi::PauseMusicStream(self.0) } } /// Resumes playing paused music. #[inline] pub fn resume_stream(&self) { - unsafe { - ffi::ResumeMusicStream(self.0); - } + unsafe { ffi::ResumeMusicStream(self.0) } } /// Checks if music is playing. @@ -485,17 +453,13 @@ impl<'aud> Music<'aud> { /// Sets volume for music (`1.0` is max level). #[inline] pub fn set_volume(&self, volume: f32) { - unsafe { - ffi::SetMusicVolume(self.0, volume); - } + unsafe { ffi::SetMusicVolume(self.0, volume) } } /// Sets pitch for music (`1.0` is base level). #[inline] pub fn set_pitch(&self, pitch: f32) { - unsafe { - ffi::SetMusicPitch(self.0, pitch); - } + unsafe { ffi::SetMusicPitch(self.0, pitch) } } /// Gets music time length in seconds. @@ -510,18 +474,17 @@ impl<'aud> Music<'aud> { unsafe { ffi::GetMusicTimePlayed(self.0) } } + #[inline] pub fn seek_stream(&self, position: f32) { - unsafe { - ffi::SeekMusicStream(self.0, position); - } + unsafe { ffi::SeekMusicStream(self.0, position) } } + #[inline] pub fn set_pan(&self, pan: f32) { - unsafe { - ffi::SetMusicPan(self.0, pan); - } + unsafe { ffi::SetMusicPan(self.0, pan) } } + #[inline] pub fn is_music_valid(&self) -> bool { unsafe { ffi::IsMusicValid(self.0) } } From 9ac3acff7774a937dec6e2f8b6d835cbfae049cf Mon Sep 17 00:00:00 2001 From: James Ebert Date: Thu, 6 Feb 2025 15:19:50 -0800 Subject: [PATCH 64/93] feat: add nixos shell.nix and docs for it (#123) Signed-off-by: James Ebert --- README.md | 12 ++++++++++++ shell.nix | 21 +++++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 shell.nix diff --git a/README.md b/README.md index 41056f94..ecb82692 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,18 @@ fn main() { } ``` +### NixOS + +To use raylib-rs on NixOS there's a provided nix-shell file `shell.nix` at the root of the repo that should get you up and running, which can be used like so: + +`nix-shell ./shell.nix` + +You'll also need to enable the Wayland feature on the raylib crate: + +`cargo add raylib -F wayland` + +Contributions are welcome to improve or fix the shell.nix! + # Tech Notes - Structs holding resources have RAII/move semantics, including: `Image`, `Texture2D`, `RenderTexture2D`, `Font`, `Mesh`, `Shader`, `Material`, and `Model`. diff --git a/shell.nix b/shell.nix new file mode 100644 index 00000000..3a1d5098 --- /dev/null +++ b/shell.nix @@ -0,0 +1,21 @@ +{ pkgs ? import {} }: +pkgs.mkShell { + packages = with pkgs; [ + rustup + glfw + cmake + clang + wayland + # Web support (uncomment to enable) -- Untested - @JamesKEbert + # emscripten + ]; + + LD_LIBRARY_PATH = with pkgs; lib.makeLibraryPath [ + libGL + xorg.libXrandr + xorg.libXinerama + xorg.libXcursor + xorg.libXi + ]; + LIBCLANG_PATH = "${pkgs.libclang.lib}/lib"; +} \ No newline at end of file From fbe882a754d308f6d10f733ffb4d5b186a1aa674 Mon Sep 17 00:00:00 2001 From: IoIxD <30945097+IoIxD@users.noreply.github.com> Date: Thu, 13 Feb 2025 21:31:55 -0700 Subject: [PATCH 65/93] added back nobuild because removing it was stupid why did i do that what (#126) * [imgui] accidentally left an import in mod.rs that errors if imgui feature isn't on * [cargo] Added back nobuild because removing it was stupid --- raylib-sys/Cargo.toml | 2 +- raylib/Cargo.toml | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/raylib-sys/Cargo.toml b/raylib-sys/Cargo.toml index 3b5f5b91..778e8ad7 100644 --- a/raylib-sys/Cargo.toml +++ b/raylib-sys/Cargo.toml @@ -23,7 +23,7 @@ bindgen = "0.70" [features] default = [] # Build Raylib headless for docs. Up to you to link -#nobuild = [] +nobuild = [] # Build for wayland on linux. Should fix #119 wayland = [] diff --git a/raylib/Cargo.toml b/raylib/Cargo.toml index 1fad2aaf..65b42dd2 100644 --- a/raylib/Cargo.toml +++ b/raylib/Cargo.toml @@ -44,3 +44,4 @@ sdl = ["raylib-sys/sdl"] noscreenshot = ["raylib-sys/noscreenshot"] nogif = ["raylib-sys/nogif"] imgui = ["raylib-sys/imgui", "dep:imgui", "dep:imgui-sys"] +nobuild = ["raylib-sys/nobuild"] \ No newline at end of file From 34f21f692977b8be435a6a234ab6466a4226f866 Mon Sep 17 00:00:00 2001 From: Izzy <30461139+izzymg@users.noreply.github.com> Date: Fri, 14 Feb 2025 17:41:29 +1300 Subject: [PATCH 66/93] Put specs behind feature (#125) Specs was marked as optional, but could not be removed from the dependency chain. Co-authored-by: IoIxD <30945097+IoIxD@users.noreply.github.com> --- raylib/Cargo.toml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/raylib/Cargo.toml b/raylib/Cargo.toml index 65b42dd2..a48a41bb 100644 --- a/raylib/Cargo.toml +++ b/raylib/Cargo.toml @@ -44,4 +44,5 @@ sdl = ["raylib-sys/sdl"] noscreenshot = ["raylib-sys/noscreenshot"] nogif = ["raylib-sys/nogif"] imgui = ["raylib-sys/imgui", "dep:imgui", "dep:imgui-sys"] -nobuild = ["raylib-sys/nobuild"] \ No newline at end of file +specs = ["dep:specs", "dep:specs-derive"] +nobuild = ["raylib-sys/nobuild"] From 2fd6fcd3fbe2bf5313a2ac5b98fb7e489ca983ae Mon Sep 17 00:00:00 2001 From: IoIxD <30945097+IoIxD@users.noreply.github.com> Date: Fri, 14 Feb 2025 17:58:48 -0700 Subject: [PATCH 67/93] Expanded nobuild flag (#127) * [build] expanded nobuild * [file] accidentally removed get_file_length although to be fair it should be removed anyways --- raylib-sys/Cargo.toml | 8 +++++--- raylib-sys/build.rs | 30 ++++++++++++++++++++++++++++++ raylib-sys/src/lib.rs | 4 ++++ raylib/Cargo.toml | 2 ++ 4 files changed, 41 insertions(+), 3 deletions(-) diff --git a/raylib-sys/Cargo.toml b/raylib-sys/Cargo.toml index 778e8ad7..11d6eae2 100644 --- a/raylib-sys/Cargo.toml +++ b/raylib-sys/Cargo.toml @@ -21,10 +21,12 @@ cc = "1.0" bindgen = "0.70" [features] -default = [] -# Build Raylib headless for docs. Up to you to link +# Build Raylib headless for docs/esoteric platforms. Up to you to link. nobuild = [] - +# Generate bindings automatically. +# You can turn this off if you wanna go into the source and put in your own bindings.rs, which is +# useful since bindgen doesn't work on esoteric platforms. +bindgen = [] # Build for wayland on linux. Should fix #119 wayland = [] diff --git a/raylib-sys/build.rs b/raylib-sys/build.rs index cfd0d239..f34d0b90 100644 --- a/raylib-sys/build.rs +++ b/raylib-sys/build.rs @@ -396,6 +396,7 @@ fn link(platform: Platform, platform_os: PlatformOS) { println!("cargo:rustc-link-lib=static=raylib"); } +#[cfg(not(feature = "nobuild"))] fn main() { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=./binding/binding.h"); @@ -433,6 +434,35 @@ fn main() { gen_imgui(); } +#[cfg(feature = "nobuild")] +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-changed=./binding/binding.h"); + let target = env::var("TARGET").expect("Cargo build scripts always have TARGET"); + + if target.contains("wasm32-unknown-emscripten") { + if let Err(e) = env::var("EMCC_CFLAGS") { + if e == std::env::VarError::NotPresent { + panic!("\nYou must have to set EMCC_CFLAGS yourself to compile for WASM.\n{}{}\"\n",{ + #[cfg(target_family = "windows")] + {"set EMCC_CFLAGS="} + #[cfg(not(target_family = "windows"))] + {"export EMCC_CFLAGS="} + },"\"-O3 -sUSE_GLFW=3 -sASSERTIONS=1 -sWASM=1 -sASYNCIFY -sGL_ENABLE_GET_PROC_ADDRESS=1\""); + } else { + panic!("\nError regarding EMCC_CFLAGS: {:?}\n", e); + } + } + } + + #[cfg(feature = "bindgen")] + gen_bindings(); + + gen_rgui(); + + gen_imgui(); +} + #[must_use] /// returns false if the directory does not exist fn is_directory_empty(path: &str) -> bool { diff --git a/raylib-sys/src/lib.rs b/raylib-sys/src/lib.rs index 585bae64..f1643497 100644 --- a/raylib-sys/src/lib.rs +++ b/raylib-sys/src/lib.rs @@ -3,8 +3,12 @@ #![allow(non_snake_case)] #![allow(clippy::approx_constant)] +#[cfg(feature = "bindgen")] include!(concat!(env!("OUT_DIR"), "/bindings.rs")); +#[cfg(not(feature = "bindgen"))] +include!(env!("RAYLIB_BINDGEN_LOCATION")); + #[cfg(target_os = "macos")] pub const MAX_MATERIAL_MAPS: u32 = 12; diff --git a/raylib/Cargo.toml b/raylib/Cargo.toml index a48a41bb..300b21a6 100644 --- a/raylib/Cargo.toml +++ b/raylib/Cargo.toml @@ -46,3 +46,5 @@ nogif = ["raylib-sys/nogif"] imgui = ["raylib-sys/imgui", "dep:imgui", "dep:imgui-sys"] specs = ["dep:specs", "dep:specs-derive"] nobuild = ["raylib-sys/nobuild"] +bindgen = ["raylib-sys/bindgen"] +default = ["bindgen"] \ No newline at end of file From eca46e2c558d2f491c8b8b5af71a59410ed3caf4 Mon Sep 17 00:00:00 2001 From: Barys <128910676+Barysk@users.noreply.github.com> Date: Tue, 18 Mar 2025 00:13:24 +0100 Subject: [PATCH 68/93] Added binding for SetAudioStreamBufferSizeDefault(int) (#128) --- raylib/src/core/audio.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/raylib/src/core/audio.rs b/raylib/src/core/audio.rs index c95a60f9..f99bbe9e 100644 --- a/raylib/src/core/audio.rs +++ b/raylib/src/core/audio.rs @@ -87,6 +87,14 @@ impl RaylibAudio { pub fn set_master_volume(&self, volume: f32) { unsafe { ffi::SetMasterVolume(volume) } } + + /// Sets default audio buffer size for new audio streams. + #[inline] + pub fn set_audio_stream_buffer_size_default(&self, size: i32) { + unsafe { + ffi::SetAudioStreamBufferSizeDefault(size); + } + } /// Loads a new sound from file. #[inline] From 317a0b5abf3d22b3dcc779a5a9404f1b539ab355 Mon Sep 17 00:00:00 2001 From: goto40 Date: Tue, 18 Mar 2025 00:14:07 +0100 Subject: [PATCH 69/93] attach_audio_stream_processor_to_music: attach one or more closures as audio processors (#124) * impl: constructed a wrapper to provide some user data to the callbacks (limited to N callbacks) * impl: constructed a wrapper to provide some user data to the callbacks (limited to N callbacks) * doc * doc and send trait * doc * wip * chore: automated number of indices/callbacks; fixed clear function * doc * chore: get rid of lazy static * chore: fix panic format string * chore: added music player demo with effects * chore: review, fixed dependency to be optional and only used by the example. --- raylib/Cargo.toml | 3 + raylib/src/core/callbacks.rs | 97 +++++++++++ ...stream_processor_with_user_data_wrapper.rs | 153 ++++++++++++++++++ samples/Cargo.toml | 7 + samples/music_effects.rs | 123 ++++++++++++++ 5 files changed, 383 insertions(+) create mode 100644 raylib/src/core/callbacks/stream_processor_with_user_data_wrapper.rs create mode 100644 samples/music_effects.rs diff --git a/raylib/Cargo.toml b/raylib/Cargo.toml index 300b21a6..8305fde7 100644 --- a/raylib/Cargo.toml +++ b/raylib/Cargo.toml @@ -26,6 +26,9 @@ specs = { version = "0.16.1", default = false, optional = true } specs-derive = { version = "0.4.1", optional = true } thiserror = "1.0.61" +paste = "1.0" +seq-macro = "0.3.5" + [dev-dependencies] structopt = "0.3" rand = "0.8.5" diff --git a/raylib/src/core/callbacks.rs b/raylib/src/core/callbacks.rs index 02f509b9..63adb965 100644 --- a/raylib/src/core/callbacks.rs +++ b/raylib/src/core/callbacks.rs @@ -7,10 +7,14 @@ use std::{ convert::TryInto, ffi::{c_char, c_int, c_void, CStr, CString}, mem::{size_of, transmute}, + pin::Pin, ptr::null_mut, slice::from_raw_parts_mut, sync::atomic::{AtomicUsize, Ordering}, }; +mod stream_processor_with_user_data_wrapper; +use super::audio::Music; +use stream_processor_with_user_data_wrapper::*; type TraceLogCallback = unsafe extern "C" fn(*mut i8, *const i8, ...); extern "C" { @@ -201,6 +205,99 @@ pub fn set_load_file_text_callback<'a>(cb: fn(&str) -> String) -> Result<(), Set ) } +// region: -- AudioStreamProcessorCallback -- + +/// This struct encapsulates a rust callback +/// and guarantees the lifetime to be long enough ('a) +/// (once `get_as_user_data` is called, it the struct +/// should not be moved again! -> use Pin<..>) +pub struct AudioStreamProcessorCallback<'a, F> +where + F: FnMut(&mut [f32], u32) -> (), +{ + rust_callback: &'a mut F, + nb_channels: u32, + callback_index: Option, +} + +impl<'a, F> AudioStreamProcessorCallback<'a, F> +where + F: FnMut(&mut [f32], u32) -> (), +{ + fn new(closure: &'a mut F, nb_channels_from_music: u32) -> Self { + Self { + rust_callback: closure, + nb_channels: nb_channels_from_music, + callback_index: None, + } + } + + fn get_as_user_data(&mut self) -> *mut ::std::os::raw::c_void { + return self as *mut Self as *mut ::std::os::raw::c_void; + } + + fn get_c_callback( + &mut self, + ) -> extern "C" fn( + *mut ::std::os::raw::c_void, + *mut ::std::os::raw::c_void, + ::std::os::raw::c_uint, + ) -> () { + Self::c_callback + } + + extern "C" fn c_callback( + user_data: *mut ::std::os::raw::c_void, + data_ptr: *mut ::std::os::raw::c_void, + frame_count: ::std::os::raw::c_uint, + ) -> () { + unsafe { + let stream_processor_callback: &mut Self = user_data.cast::().as_mut().unwrap(); + let f32_ptr = data_ptr as *mut f32; + let data = unsafe { + std::slice::from_raw_parts_mut( + f32_ptr, + frame_count as usize * stream_processor_callback.nb_channels as usize, + ) + }; + (stream_processor_callback.rust_callback)(data, stream_processor_callback.nb_channels); + } + } +} + +impl<'a, F> Drop for AudioStreamProcessorCallback<'a, F> +where + F: FnMut(&mut [f32], u32) -> (), +{ + fn drop(&mut self) { + if let Some(index) = self.callback_index { + detach_audio_stream_processor_with_user_data(index); + } + } +} + +// endregion: -- AudioStreamProcessorCallback -- + +pub fn attach_audio_stream_processor_to_music<'a, F>( + music: &'a Music<'a>, + processor: &'a mut F, +) -> Pin>> +where + F: FnMut(&mut [f32], u32) -> () + Send + 'static, // static because the function is executed in another thread +{ + let mut stream_processor_callback = + Box::new(AudioStreamProcessorCallback::<'a, F>::new(processor, 2)); + stream_processor_callback.callback_index = Some(attach_audio_stream_processor_with_user_data( + music.stream, + AudioCallbackWithUserData::new( + stream_processor_callback.get_as_user_data(), // pass the address of the stream_processor_callback as void* + stream_processor_callback.get_c_callback(), + ), + )); + assert!(stream_processor_callback.callback_index.is_some()); + Box::into_pin(stream_processor_callback) +} + /// Audio thread callback to request new data pub fn set_audio_stream_callback(stream: AudioStream, cb: fn(&[u8])) -> Result<(), SetLogError> { if AUDIO_STREAM_CALLBACK.load(Ordering::Acquire) == 0 { diff --git a/raylib/src/core/callbacks/stream_processor_with_user_data_wrapper.rs b/raylib/src/core/callbacks/stream_processor_with_user_data_wrapper.rs new file mode 100644 index 00000000..0d4f9197 --- /dev/null +++ b/raylib/src/core/callbacks/stream_processor_with_user_data_wrapper.rs @@ -0,0 +1,153 @@ +use paste::paste; +use raylib_sys::{AttachAudioStreamProcessor, AudioStream}; +use seq_macro::seq; +use std::sync::{LazyLock, Mutex}; + +// region: -- AudioCallbackWithUserData -- + +/// This is the callback we wish to get from raylib: +/// It contains `user_data` in order to plug in our +/// context (e.g. our closure). +type RawAudioCallbackWithUserData = extern "C" fn( + user_data: *mut ::std::os::raw::c_void, + data_ptr: *mut ::std::os::raw::c_void, + frames: u32, +) -> (); + +/// This is a tuple of `user_data` which represents +/// our context (see RawAudioCallbackWithUserData) +/// and the callback we wish to pass to our raylib +/// abstraction layer (wrapping the real raylib +/// callback to plug in our context). +pub struct AudioCallbackWithUserData { + user_data: *mut ::std::os::raw::c_void, + callback: Option, +} + +unsafe impl Send for AudioCallbackWithUserData {} //?? + +impl AudioCallbackWithUserData { + pub fn new( + user_data: *mut ::std::os::raw::c_void, + raw_callback: RawAudioCallbackWithUserData, + ) -> Self { + AudioCallbackWithUserData { + user_data: user_data, + callback: Some(raw_callback), + } + } +} + +impl Default for AudioCallbackWithUserData { + fn default() -> Self { + AudioCallbackWithUserData { + user_data: std::ptr::null_mut(), + callback: None, + } + } +} + +// endregion: -- AudioCallbackWithUserData -- + +// region: -- raw callbacks and linkage +// raw callback and linkage to AudioCallbackWithUserData +// we only support a limited amount of callbacks - since +// we need a dedicated callback function for each +// callback or closure we plug in. This is caused by the +// absence of a `user_data` context in the callbacks +// supported by raylib. + +macro_rules! generate_functions { + ( $( $n:literal ),* ) => { + paste! { + $( + /// For each supported callback the data for our context. + /// (here we have N "slots" with context data) + static [< CLOSURE_ $n >]: LazyLock> = LazyLock::new(|| Mutex::new(AudioCallbackWithUserData::default())); + )* + + /// Function to set our context + /// and returns the slot used to store the context. + fn set_context(audio_callback: AudioCallbackWithUserData) -> usize { + $( + { + let mut guard = [< CLOSURE_ $n >].lock().unwrap(); + if (*guard).callback == None { + *guard = audio_callback; + return $n; + } + } + )* + panic!("index out of bounds"); + } + + /// Function to clear our context given the slot of the context. + fn clear_context(index: usize) { + $( + if index == $n { + let mut guard = [< CLOSURE_ $n >].lock().unwrap(); + if (*guard).callback == None { + panic!( + "No callbacks registered under this number ({}).", + index + ); + } + *guard = AudioCallbackWithUserData::default(); + return; + } + )* + panic!("clear_context: index {} out of bounds", index); + } + + $( + /// The real callback passed to raylib. + /// Each callback has a fixed association with + /// a given context "slot". + #[no_mangle] + pub extern "C" fn [< callback_ $n >](data_ptr: *mut ::std::os::raw::c_void, frames: u32) -> () { + let guard = [< CLOSURE_ $n >].lock().unwrap(); + let audio_callback = &(*guard); + if let Some(callback) = audio_callback.callback { + (callback)(audio_callback.user_data, data_ptr, frames); + } else { + panic!("unexpected: no callback $n set") + } + } + )* + + /// Function to get the callback for a given context + /// given the slot of the context. + fn get_callback(index: usize) -> extern "C" fn(data_ptr: *mut ::std::os::raw::c_void, frames: u32) { + $( + if index == $n { + return [< callback_ $n >]; + } + )* + panic!("get_callback: index out of bounds"); + } + } + } +} + +// here, you can control how many callbacks are supported +seq!(I in 1..30 { + generate_functions!( 0#(,I)* ); +}); + +// endregion: -- raw callbacks and linkage + +/// Here, we c +pub fn attach_audio_stream_processor_with_user_data( + stream: AudioStream, + callback: AudioCallbackWithUserData, +) -> usize { + let idx = set_context(callback); + unsafe { + AttachAudioStreamProcessor(stream, Some(get_callback(idx))); + } + idx +} + +pub fn detach_audio_stream_processor_with_user_data(index: usize) { + clear_context(index); +} diff --git a/samples/Cargo.toml b/samples/Cargo.toml index cfdeaad9..5606176b 100644 --- a/samples/Cargo.toml +++ b/samples/Cargo.toml @@ -18,9 +18,11 @@ serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" imgui = {version = "0.12.0", optional = true} imgui-sys = {version = "0.12.0", optional = true} +ringbuf = {version = "0.4.7", optional = true} [features] imgui = ["raylib/imgui","dep:imgui","dep:imgui-sys"] +ringbuf = ["dep:ringbuf"] [dependencies.specs] version = "0.16.1" @@ -100,3 +102,8 @@ path = "./shader_multisample.rs" name = "imgui" path = "imgui.rs" required-features = ["imgui"] + +[[bin]] +name = "music_effects" +path = "music_effects.rs" +required-features = ["ringbuf"] diff --git a/samples/music_effects.rs b/samples/music_effects.rs new file mode 100644 index 00000000..ea6a4566 --- /dev/null +++ b/samples/music_effects.rs @@ -0,0 +1,123 @@ +use raylib::prelude::*; +use ringbuf::{ + traits::{Consumer, Observer, RingBuffer}, + HeapRb, +}; +use std::{ + cell::RefCell, + env, f32, + sync::{Arc, Mutex}, +}; + +fn main() { + // get file name + let args: Vec = env::args().collect(); + if args.len() != 2 { + panic!("usage {} ", args[0]); + } + let filename = args[1].as_str(); + + // open window + let (mut rl, thread) = raylib::init() + .size(640, 480) + .title("Music Player") + .resizable() + .vsync() + .build(); + + // open audio file + let audio = raylib::core::audio::RaylibAudio::init_audio_device().unwrap(); + let music = audio.new_music(filename).unwrap(); + music.play_stream(); + + let mut effects = vec![]; + let mut effects_control = vec![]; + + // create effects + for (k, key) in [ + (1, KeyboardKey::KEY_ONE), + (2, KeyboardKey::KEY_TWO), + (3, KeyboardKey::KEY_THREE), + ] { + let hall_switch = Arc::new(Mutex::new(RefCell::new(false))); + let hall_switch_for_callback = Arc::clone(&hall_switch); + let dist = k * 10000; + let mut hall_buffer = HeapRb::::new(dist); + let hall_callback = move |data: &mut [f32], _nb_channels: u32| { + let hall_buffer = &mut hall_buffer; + let hall_switch = hall_switch_for_callback.lock().unwrap(); + let delta = dist; + let delta_alpha: f32 = 0.5; + if *hall_switch.borrow_mut() { + (0..data.len()).for_each(|idx| { + hall_buffer.push_overwrite(data[idx]); + while hall_buffer.occupied_len() > delta { + hall_buffer.try_pop().unwrap(); + } + if hall_buffer.occupied_len() == delta { + data[idx] = data[idx] + delta_alpha * hall_buffer.try_pop().unwrap(); + } + }); + } + }; + effects.push(hall_callback); + effects_control.push((hall_switch, key)); + } + + let mut _keep_alive = vec![]; + for callback in effects.iter_mut() { + _keep_alive.push(attach_audio_stream_processor_to_music(&music, callback)); + } + + // run main loop (use key to control music and effects) + while !rl.window_should_close() { + if rl.is_key_pressed(KeyboardKey::KEY_RIGHT) { + let new_pos = f32::min(music.get_time_played() + 10.0, music.get_time_length()); + music.seek_stream(new_pos); + } + if rl.is_key_pressed(KeyboardKey::KEY_LEFT) { + let new_pos = f32::max(music.get_time_played() - 10.0, 0.0); + music.seek_stream(new_pos); + } + for (switch, key) in effects_control.iter_mut() { + if rl.is_key_pressed(*key) { + let switch = switch.lock().unwrap(); + let mut b = switch.borrow_mut(); + *b = !(*b); + } + } + + music.update_stream(); + + let mut d = rl.begin_drawing(&thread); + let info_color = Color::get_color(0xffff00ff); + let light_info_color = Color::get_color(0xa0a000ff); + d.clear_background(Color::get_color(0x006040ff)); + d.draw_text(filename, 12, 42, 20, info_color); + d.draw_fps(d.get_render_width() - 90, 12); + let time_y = 80; + let time_x = ((d.get_render_width() - 20) as f32 + * (music.get_time_played() / music.get_time_length())) as i32; + d.draw_line( + 10, + time_y, + d.get_render_width() - 10, + time_y, + light_info_color, + ); + d.draw_circle(time_x, time_y, 5.0, light_info_color); + { + let switch_states = effects_control + .iter() + .map(|(switch, _)| *RefCell::borrow(&switch.lock().unwrap())) + .collect::>(); + d.draw_text( + &format!("Press <-, ->, 1,2,3...: {:?}", switch_states), + 12, + 90, + 20, + light_info_color, + ); + } + } +} From d95234304137ae697a02a1dfce8d17a1a9a19341 Mon Sep 17 00:00:00 2001 From: IoIxD <30945097+IoIxD@users.noreply.github.com> Date: Thu, 20 Mar 2025 19:06:09 -0700 Subject: [PATCH 70/93] Assorted 5.5 fixes (#132) * [...] assorted fixes that got lost because i forgot to update the branch * [...] assorted fixes that got lost because i forgot to update the branch * [raylib-test] remove reference to a feature that isn't even in raylib * [samples] undo cargo.toml changes other then authors --- raylib-sys/Cargo.toml | 2 +- raylib-test/Cargo.toml | 4 +- raylib/Cargo.toml | 7 +- raylib/src/core/automation.rs | 8 +- raylib/src/core/drawing.rs | 66 ++++++----- raylib/src/imgui/mod.rs | 2 +- samples/Cargo.toml | 4 +- samples/specs.rs | 215 ---------------------------------- showcase/Cargo.toml | 2 +- 9 files changed, 44 insertions(+), 266 deletions(-) delete mode 100644 samples/specs.rs diff --git a/raylib-sys/Cargo.toml b/raylib-sys/Cargo.toml index 11d6eae2..822c799b 100644 --- a/raylib-sys/Cargo.toml +++ b/raylib-sys/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "raylib-sys" version = "5.5.0" -authors = ["DeltaPHC "] +authors = ["raylib-rs team "] license = "Zlib" description = "Raw FFI bindings for Raylib" documentation = "https://docs.rs/raylib-sys" diff --git a/raylib-test/Cargo.toml b/raylib-test/Cargo.toml index 29b0e992..d24a2675 100644 --- a/raylib-test/Cargo.toml +++ b/raylib-test/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "raylib-test" version = "5.5.0" -authors = ["David Ayeke"] +authors = ["raylib-rs team "] edition = "2018" license = "Zlib" readme = "../README.md" @@ -9,7 +9,7 @@ repository = "https://github.com/raylib-rs/raylib-rs" [dependencies] -raylib = { version = "5.5.0", path = "../raylib", features=["use_begin_functions"] } +raylib = { version = "5.5.0", path = "../raylib" } lazy_static = "1.2.0" colored = "2.1.0" diff --git a/raylib/Cargo.toml b/raylib/Cargo.toml index 8305fde7..f83f8dd0 100644 --- a/raylib/Cargo.toml +++ b/raylib/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "raylib" version = "5.5.0" -authors = ["DeltaPHC "] +authors = ["raylib-rs team "] license = "Zlib" readme = "../README.md" description = "Safe Rust bindings for Raylib." @@ -22,8 +22,6 @@ imgui-sys = { version = "0.12.0", optional = true } mint = { version = "0.5.9", optional = true } -specs = { version = "0.16.1", default = false, optional = true } -specs-derive = { version = "0.4.1", optional = true } thiserror = "1.0.61" paste = "1.0" @@ -47,7 +45,6 @@ sdl = ["raylib-sys/sdl"] noscreenshot = ["raylib-sys/noscreenshot"] nogif = ["raylib-sys/nogif"] imgui = ["raylib-sys/imgui", "dep:imgui", "dep:imgui-sys"] -specs = ["dep:specs", "dep:specs-derive"] nobuild = ["raylib-sys/nobuild"] bindgen = ["raylib-sys/bindgen"] -default = ["bindgen"] \ No newline at end of file +default = ["bindgen"] diff --git a/raylib/src/core/automation.rs b/raylib/src/core/automation.rs index 8b5f51ba..cd9e4bb1 100644 --- a/raylib/src/core/automation.rs +++ b/raylib/src/core/automation.rs @@ -6,16 +6,10 @@ use std::{ use crate::{ffi, RaylibHandle}; -fn unload_automation_event_list(mut s: ffi::AutomationEventList) { - unsafe { - ffi::UnloadAutomationEventList(s); - } -} - make_thin_wrapper!( AutomationEventList, ffi::AutomationEventList, - unload_automation_event_list, + ffi::UnloadAutomationEventList, false ); diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index f76ded6b..8d4ac127 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -23,7 +23,7 @@ use super::shaders::{Shader, ShaderV}; impl RaylibHandle { #[must_use] /// Setup canvas (framebuffer) to start drawing. - /// Prefer using the closure version, [RaylibHandle::begin_drawing]. This version returns a handle that calls [raylib_sys::EndDrawing] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) + /// Prefer using the closure version, [RaylibHandle::draw]. This version returns a handle that calls [raylib_sys::EndDrawing] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) pub fn begin_drawing(&mut self, _: &RaylibThread) -> RaylibDrawHandle { unsafe { ffi::BeginDrawing(); @@ -32,7 +32,7 @@ impl RaylibHandle { let d = RaylibDrawHandle(self); d } - pub fn start_drawing(&mut self, _: &RaylibThread, mut func: impl FnMut(RaylibDrawHandle)) { + pub fn draw(&mut self, _: &RaylibThread, mut func: impl FnMut(RaylibDrawHandle)) { unsafe { ffi::BeginDrawing(); }; @@ -46,13 +46,15 @@ impl RaylibHandle { pub struct RaylibDrawHandle<'a>(&'a mut RaylibHandle); impl<'a> RaylibDrawHandle<'a> { - #[deprecated = "Calling begin_drawing within itself will result in a runtime error."] + #[deprecated = "Calling begin_drawing within RaylibDrawHandle will result in a runtime error."] + #[doc(hidden)] pub fn begin_drawing(&mut self, _: &RaylibThread) -> RaylibDrawHandle { panic!("Nested begin_drawing call") } - #[deprecated = "Calling start_drawing within itself will result in a runtime error."] - pub fn start_drawing(&mut self, _: &RaylibThread, mut _func: impl FnMut(RaylibDrawHandle)) { - panic!("Nested start_drawing call") + #[deprecated = "Calling draw within RaylibDrawHandle will result in a runtime error."] + #[doc(hidden)] + pub fn draw(&mut self, _: &RaylibThread, mut _func: impl FnMut(RaylibDrawHandle)) { + panic!("Nested draw call") } } @@ -81,7 +83,7 @@ impl<'a> RaylibDraw for RaylibDrawHandle<'a> {} // Texture2D Stuff -pub struct RaylibTextureMode<'a, T>(&'a mut T, Option<&'a mut ffi::RenderTexture2D>); +pub struct RaylibTextureMode<'a, T>(&'a mut T, &'a mut ffi::RenderTexture2D); impl<'a, T> Drop for RaylibTextureMode<'a, T> { fn drop(&mut self) { @@ -107,7 +109,7 @@ where Self: Sized, { /// Begin drawing to render texture. - /// Prefer using the closure version, [RaylibTextureModeExt::start_texture_mode] . This version returns a handle that calls [raylib_sys::EndTextureMode] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) + /// Prefer using the closure version, [RaylibTextureModeExt::draw_texture_mode] . This version returns a handle that calls [raylib_sys::EndTextureMode] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) #[must_use] fn begin_texture_mode<'a>( &'a mut self, @@ -115,17 +117,17 @@ where framebuffer: &'a mut ffi::RenderTexture2D, ) -> RaylibTextureMode { unsafe { ffi::BeginTextureMode(*framebuffer) } - RaylibTextureMode(self, Some(framebuffer)) + RaylibTextureMode(self, framebuffer) } - fn start_texture_mode<'a>( + fn draw_texture_mode<'a>( &'a mut self, _: &RaylibThread, framebuffer: &'a mut ffi::RenderTexture2D, - mut func: impl FnMut(RaylibTextureMode, &'a mut ffi::RenderTexture2D), + mut func: impl FnMut(RaylibTextureMode), ) { unsafe { ffi::BeginTextureMode(*framebuffer) } - func(RaylibTextureMode(self, None), framebuffer); + func(RaylibTextureMode(self, framebuffer)); } } @@ -136,7 +138,7 @@ impl<'a, T> RaylibDraw for RaylibTextureMode<'a, T> {} // VR Stuff -pub struct RaylibVRMode<'a, T>(&'a T, Option<&'a mut VrStereoConfig>); +pub struct RaylibVRMode<'a, T>(&'a T, &'a mut VrStereoConfig); impl<'a, T> Drop for RaylibVRMode<'a, T> { fn drop(&mut self) { unsafe { ffi::EndVrStereoMode() } @@ -155,7 +157,7 @@ where Self: Sized, { /// Begin stereo rendering (requires VR simulator). - /// Prefer using the closure version, [RaylibVRModeExt::start_vr_stereo_mode] . This version returns a handle that calls [raylib_sys::EndVrStereoMode] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) + /// Prefer using the closure version, [RaylibVRModeExt::draw_vr_stereo_mode] . This version returns a handle that calls [raylib_sys::EndVrStereoMode] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) #[must_use] fn begin_vr_stereo_mode<'a>( &'a mut self, @@ -163,16 +165,16 @@ where vr_config: &'a mut VrStereoConfig, ) -> RaylibVRMode { unsafe { ffi::BeginVrStereoMode(*vr_config.as_ref()) } - RaylibVRMode(self, Some(vr_config)) + RaylibVRMode(self, vr_config) } - fn start_vr_stereo_mode<'a>( + fn draw_vr_stereo_mode<'a>( &'a mut self, vr_config: &'a mut VrStereoConfig, - mut func: impl FnMut(RaylibVRMode, &'a mut VrStereoConfig), + mut func: impl FnMut(RaylibVRMode), ) { unsafe { ffi::BeginVrStereoMode(*vr_config.as_ref()) } - func(RaylibVRMode(&self, None), vr_config); + func(RaylibVRMode(&self, vr_config)); } } @@ -205,7 +207,7 @@ where Self: Sized, { /// Begin 2D mode with custom camera (2D). - /// Prefer using the closure version, [RaylibMode2DExt::begin_mode2D]. This version returns a handle that calls [raylib_sys::EndMode2D] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) + /// Prefer using the closure version, [RaylibMode2DExt::draw_mode2D]. This version returns a handle that calls [raylib_sys::EndMode2D] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) #[allow(non_snake_case)] #[must_use] fn begin_mode2D(&mut self, camera: impl Into) -> RaylibMode2D { @@ -216,7 +218,7 @@ where } #[allow(non_snake_case)] - fn start_mode2D( + fn draw_mode2D( &mut self, camera: Camera2D, mut func: impl FnMut(RaylibMode2D, Camera2D), @@ -260,7 +262,7 @@ where Self: Sized, { /// Begin 3D mode with custom camera (3D). - /// Prefer using the closure version, [RaylibMode3DExt::begin_mode3D]. This version returns a handle that calls [raylib_sys::EndMode3D] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) + /// Prefer using the closure version, [RaylibMode3DExt::draw_mode3D]. This version returns a handle that calls [raylib_sys::EndMode3D] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) #[allow(non_snake_case)] #[must_use] fn begin_mode3D(&mut self, camera: impl Into) -> RaylibMode3D { @@ -271,7 +273,7 @@ where } #[allow(non_snake_case)] - fn start_mode3D( + fn draw_mode3D( &mut self, camera: Camera3D, mut func: impl FnMut(RaylibMode3D, Camera3D), @@ -292,7 +294,7 @@ impl<'a, T> RaylibDraw3D for RaylibMode3D<'a, T> {} // shader Mode -pub struct RaylibShaderMode<'a, T>(&'a mut T, Option<&'a mut Shader>); +pub struct RaylibShaderMode<'a, T>(&'a mut T, &'a mut Shader); impl<'a, T> Drop for RaylibShaderMode<'a, T> { fn drop(&mut self) { @@ -317,20 +319,20 @@ where Self: Sized, { /// Begin custom shader drawing. - /// Prefer using the closure version, [RaylibShaderModeExt::begin_shader_mode]. This version returns a handle that calls [raylib_sys::EndShaderMode] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) + /// Prefer using the closure version, [RaylibShaderModeExt::draw_shader_mode]. This version returns a handle that calls [raylib_sys::EndShaderMode] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) #[must_use] fn begin_shader_mode<'a>(&'a mut self, shader: &'a mut Shader) -> RaylibShaderMode { unsafe { ffi::BeginShaderMode(*shader.as_ref()) } - RaylibShaderMode(self, Some(shader)) + RaylibShaderMode(self, shader) } - fn start_shader_mode<'a>( + fn draw_shader_mode<'a>( &'a mut self, shader: &'a mut Shader, - mut func: impl FnMut(RaylibShaderMode, &'a mut Shader), + mut func: impl FnMut(RaylibShaderMode), ) { unsafe { ffi::BeginShaderMode(*shader.as_ref()) } - func(RaylibShaderMode(self, None), shader); + func(RaylibShaderMode(self, shader)); } } @@ -364,14 +366,14 @@ where Self: Sized, { /// Begin blending mode (alpha, additive, multiplied, subtract, custom). - /// Prefer using the closure version, [RaylibBlendModeExt::begin_blend_mode]. This version returns a handle that calls [raylib_sys::EndBlendMode] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) + /// Prefer using the closure version, [RaylibBlendModeExt::draw_blend_mode]. This version returns a handle that calls [raylib_sys::EndBlendMode] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) #[must_use] fn begin_blend_mode(&mut self, blend_mode: crate::consts::BlendMode) -> RaylibBlendMode { unsafe { ffi::BeginBlendMode((blend_mode as u32) as i32) } RaylibBlendMode(self) } - fn start_blend_mode( + fn draw_blend_mode( &mut self, blend_mode: crate::consts::BlendMode, mut func: impl FnMut(RaylibBlendMode), @@ -411,7 +413,7 @@ where Self: Sized, { /// Begin scissor mode (define screen area for following drawing). - /// Prefer using the closure version, [RaylibScissorModeExt::begin_scissor_mode]. This version returns a handle that calls [raylib_sys::EndScissorMode] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) + /// Prefer using the closure version, [RaylibScissorModeExt::draw_scissor_mode]. This version returns a handle that calls [raylib_sys::EndScissorMode] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) #[must_use] fn begin_scissor_mode( &mut self, @@ -424,7 +426,7 @@ where RaylibScissorMode(self) } - fn start_scissor_mode( + fn draw_scissor_mode( &mut self, x: i32, y: i32, diff --git a/raylib/src/imgui/mod.rs b/raylib/src/imgui/mod.rs index 2574bde3..b3eb055c 100644 --- a/raylib/src/imgui/mod.rs +++ b/raylib/src/imgui/mod.rs @@ -105,7 +105,7 @@ pub trait RayImGUITrait { /// Setup ImGUI then call the closure with the appropriate handle. /// /// Fails silently if the delta time is negative on any frame other then 0. - fn start_imgui(&self, f: impl Fn(&mut Ui)) { + fn draw_imgui(&self, f: impl Fn(&mut Ui)) { if let Some(mut new_frame) = RayImGUIHandle::new() { f(&mut new_frame); } diff --git a/samples/Cargo.toml b/samples/Cargo.toml index 5606176b..ab4afd64 100644 --- a/samples/Cargo.toml +++ b/samples/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "raylib-examples" version = "5.5.0" -authors = ["David Ayeke"] +authors = ["raylib-rs team "] edition = "2021" license = "Zlib" readme = "../README.md" @@ -106,4 +106,4 @@ required-features = ["imgui"] [[bin]] name = "music_effects" path = "music_effects.rs" -required-features = ["ringbuf"] +required-features = ["ringbuf"] \ No newline at end of file diff --git a/samples/specs.rs b/samples/specs.rs deleted file mode 100644 index 67ccc1af..00000000 --- a/samples/specs.rs +++ /dev/null @@ -1,215 +0,0 @@ -//! Die if you touch fire -#[macro_use] -extern crate specs_derive; -use raylib::prelude::*; -use specs::prelude::*; -use std::collections::HashMap; - -use structopt::StructOpt; - -mod options; - -/// Assume square grid -const TILE_COUNT: i32 = 20; -const MARGIN: i32 = 2; - -#[derive(Clone, Component)] -struct Pos(i32, i32); - -impl From<&Pos> for Vector2 { - fn from(pos: &Pos) -> Vector2 { - Vector2::new(pos.0 as f32, pos.1 as f32) - } -} - -impl From for (i32, i32) { - fn from(val: Pos) -> Self { - (val.0, val.1) - } -} - -#[derive(Component)] -struct Fire; - -#[derive(Component)] -struct Tile; - -#[derive(Component)] -struct Player; - -type EntityMap = HashMap<(i32, i32), Entity>; - -#[derive(PartialEq, Clone, Copy)] -enum GameState { - PLAYING, - LOST, -} - -struct DeathSys; - -impl<'a> System<'a> for DeathSys { - type SystemData = ( - WriteExpect<'a, GameState>, - ReadStorage<'a, Player>, - ReadStorage<'a, Fire>, - ); - - fn run(&mut self, (mut gs, players, fire): Self::SystemData) { - // Touch fire then die - if (&players, &fire).join().nth(0).is_some() { - *gs = GameState::LOST; - println!("Lost"); - } - } -} - -struct PlayerSys; - -impl<'a> System<'a> for PlayerSys { - type SystemData = ( - Entities<'a>, - ReadExpect<'a, RaylibHandle>, - ReadExpect<'a, EntityMap>, - WriteStorage<'a, Player>, - ReadStorage<'a, Pos>, - ); - - fn run(&mut self, (ents, rl, emap, mut players, pos): Self::SystemData) { - use raylib::consts::KeyboardKey::*; - - let player = (&*ents, &pos, &players).join().nth(0).unwrap(); - - let mut new_pos = player.1.clone(); - if rl.is_key_pressed(KEY_D) { - new_pos.0 += 1; - } else if rl.is_key_pressed(KEY_A) { - new_pos.0 -= 1; - } else if rl.is_key_pressed(KEY_W) { - new_pos.1 -= 1; - } else if rl.is_key_pressed(KEY_S) { - new_pos.1 += 1; - } else { - return; - } - - let p_ent = player.0; - - match emap.get(&new_pos.into()) { - Some(e) => { - players.insert(*e, Player).unwrap(); - players.remove(p_ent); - } - _ => println!("Nothing"), - } - } -} - -// System is not thread safe -struct DrawSys { - thread: RaylibThread, -} -impl<'a> System<'a> for DrawSys { - type SystemData = ( - WriteExpect<'a, RaylibHandle>, - ReadStorage<'a, Player>, - ReadStorage<'a, Tile>, - ReadStorage<'a, Pos>, - ReadStorage<'a, Fire>, - ); - - fn run(&mut self, (mut rl, player, tiles, pos, fire): Self::SystemData) { - let (_, sh) = (rl.get_screen_width(), rl.get_screen_height()); - let tw = sh / TILE_COUNT - 2 * MARGIN; - - let margin = Vector2::new(MARGIN as f32, MARGIN as f32); - let size = Vector2::new(tw as f32, tw as f32) + margin; - let tile_size = Vector2::new(tw as f32, tw as f32); - - rl.start_drawing(&mut self.thread, |mut d| { - d.clear_background(Color::BLACK); - // draw the tiles - for (pos, _) in (&pos, &tiles).join() { - let p: Vector2 = pos.into(); - d.draw_rectangle_v(p * size + margin, tile_size, Color::RAYWHITE); - } - // draw the fire tiles - for (pos, _, _) in (&pos, &tiles, &fire).join() { - let p: Vector2 = pos.into(); - d.draw_rectangle_v(p * size + margin, tile_size, Color::RED); - } - // draw the player tiles - for (pos, _, _) in (&pos, &tiles, &player).join() { - let p: Vector2 = pos.into(); - d.draw_rectangle_v(p * size + margin, tile_size, Color::GREEN); - } - }); - } -} - -fn main() { - let opt = options::Opt::from_args(); - let (rl, thread) = opt.open_window("Specs Example"); - let (_w, _h) = (opt.width, opt.height); - - let mut world = World::new(); - register_components(&mut world); - let emap = init_world(&rl, &mut world); - - world.insert(rl); - // Raylib Thread is not safe to send between threads, but we can force it with an ARC - // It's up to the user to ensure the only systems that use it are - // thread local otherwise you will segfault - world.insert(emap); - world.insert(GameState::PLAYING); - let mut dispatcher = DispatcherBuilder::new() - .with(DeathSys, "death_sys", &[]) - .with(PlayerSys, "player_sys", &[]) - // Drawing must be done on the same thread - .with_thread_local(DrawSys { thread }) - .build(); - dispatcher.setup(&mut world); - while !window_should_close(&world) && !player_lost(&world) { - dispatcher.dispatch(&mut world); - } -} - -fn window_should_close(world: &World) -> bool { - let rl = world.read_resource::(); - rl.window_should_close() -} - -fn player_lost(world: &World) -> bool { - let gs = world.read_resource::(); - *gs == GameState::LOST -} - -fn register_components(world: &mut World) { - world.register::(); - world.register::(); - world.register::(); - world.register::(); -} - -fn init_world(rl: &RaylibHandle, world: &mut World) -> EntityMap { - let (_, sh) = (rl.get_screen_width(), rl.get_screen_height()); - let _tw = sh / TILE_COUNT; - - let mut placed_player = false; - let mut emap = EntityMap::new(); - - for x in 0..TILE_COUNT { - for y in 0..TILE_COUNT { - let mut eb = world.create_entity().with(Tile).with(Pos(x, y)); - if !placed_player && rl.get_random_value::(0..100) < 10 { - placed_player = true; - eb = eb.with(Player); - } else if rl.get_random_value::(0..100) < 10 { - eb = eb.with(Fire); - } - - let e = eb.build(); - emap.insert((x, y), e); - } - } - emap -} diff --git a/showcase/Cargo.toml b/showcase/Cargo.toml index 1b972a16..61a7244b 100644 --- a/showcase/Cargo.toml +++ b/showcase/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "raylib-showcase" version = "5.5.0" -authors = ["David Ayeke"] +authors = ["raylib-rs team "] edition = "2018" license = "Zlib" readme = "../README.md" From a725c30361aef17dd508f44cbaad61da7ee805fc Mon Sep 17 00:00:00 2001 From: IoIxD <30945097+IoIxD@users.noreply.github.com> Date: Thu, 20 Mar 2025 19:25:17 -0700 Subject: [PATCH 71/93] [raylib-test] remove set_file_text_loader (#134) * [raylib-test] remove set_file_text_loader * [raylib-test] ci test * [ci] raylib-test doesn't need all features --- .github/workflows/ci.yml | 4 ++-- raylib-test/Cargo.toml | 2 +- raylib-test/src/callbacks.rs | 2 -- raylib-test/src/tests.rs | 1 - 4 files changed, 3 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4716166b..694023de 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,5 +28,5 @@ jobs: run: sudo apt-get update; sudo apt-get install --no-install-recommends libasound2-dev libudev-dev libglfw3-dev libwayland-dev libsdl2-dev - name: Clone latest GLFW3 run: git clone https://github.com/glfw/glfw; cd glfw; mkdir build; cd build; cmake ..; make -j$(nproc); sudo make install; cd ../..; - - name: Run doc tests with all features (this also compiles README examples) - run: cargo test --doc --all-features + - name: Run doc tests (this also compiles README examples) + run: cargo test --doc diff --git a/raylib-test/Cargo.toml b/raylib-test/Cargo.toml index d24a2675..ed69f002 100644 --- a/raylib-test/Cargo.toml +++ b/raylib-test/Cargo.toml @@ -7,9 +7,9 @@ license = "Zlib" readme = "../README.md" repository = "https://github.com/raylib-rs/raylib-rs" - [dependencies] raylib = { version = "5.5.0", path = "../raylib" } +raylib_sys = { version = "5.5.0", path = "../raylib-sys" } lazy_static = "1.2.0" colored = "2.1.0" diff --git a/raylib-test/src/callbacks.rs b/raylib-test/src/callbacks.rs index 3187f041..e796214d 100644 --- a/raylib-test/src/callbacks.rs +++ b/raylib-test/src/callbacks.rs @@ -148,6 +148,4 @@ pub mod callback_tests { .unwrap(); } } - - pub fn set_file_text_loader(_: &RaylibThread) {} } diff --git a/raylib-test/src/tests.rs b/raylib-test/src/tests.rs index 496a2990..4de3e2fb 100644 --- a/raylib-test/src/tests.rs +++ b/raylib-test/src/tests.rs @@ -91,7 +91,6 @@ pub fn test_runner(tests: &[&dyn Testable]) { callbacks::callback_tests::set_file_data_saver(&thread); callbacks::callback_tests::set_file_text_saver(&thread); callbacks::callback_tests::set_file_data_loader(&thread); - callbacks::callback_tests::set_file_text_loader(&thread); let args = std::env::args().collect::>(); let opts = match parse_opts(&args) { From 789ede0bdf739db6e365c1d7bcacd7b6c3226074 Mon Sep 17 00:00:00 2001 From: IoIxD <30945097+IoIxD@users.noreply.github.com> Date: Thu, 20 Mar 2025 20:28:47 -0700 Subject: [PATCH 72/93] [raylib-sys] bindgen feature should be default oops (#136) Co-authored-by: Dacode45 --- raylib-sys/Cargo.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/raylib-sys/Cargo.toml b/raylib-sys/Cargo.toml index 822c799b..a1f98989 100644 --- a/raylib-sys/Cargo.toml +++ b/raylib-sys/Cargo.toml @@ -29,6 +29,8 @@ nobuild = [] bindgen = [] # Build for wayland on linux. Should fix #119 wayland = [] +# Bindgen is default +default = ["bindgen"] # OpenGL stuff, intended for fixing #122 opengl_33 = [] From fba491e4394c83a4d27ea31f3763804fdb3ec3d1 Mon Sep 17 00:00:00 2001 From: Austin Oliver Haskell Date: Tue, 25 Mar 2025 18:04:07 -0500 Subject: [PATCH 73/93] Imgui bindings are only called when imgui feature is enabled (#142) --- raylib-sys/build.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/raylib-sys/build.rs b/raylib-sys/build.rs index f34d0b90..126d7938 100644 --- a/raylib-sys/build.rs +++ b/raylib-sys/build.rs @@ -431,6 +431,7 @@ fn main() { gen_rgui(); + #[cfg(feature = "imgui")] gen_imgui(); } @@ -460,6 +461,7 @@ fn main() { gen_rgui(); + #[cfg(feature = "imgui")] gen_imgui(); } From 91bcb492c61dc067945d59357ca6def0d83fcb2c Mon Sep 17 00:00:00 2001 From: IoIxD <30945097+IoIxD@users.noreply.github.com> Date: Sat, 29 Mar 2025 21:59:19 -0700 Subject: [PATCH 74/93] Version bump to 5.5.1 so that I can publish the MacOS fix (#145) * [raylib-test] remove set_file_text_loader * [meta] version bump --- raylib-sys/Cargo.toml | 2 +- raylib-test/Cargo.toml | 6 +++--- raylib/Cargo.toml | 4 ++-- samples/Cargo.toml | 6 +++--- showcase/Cargo.toml | 4 ++-- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/raylib-sys/Cargo.toml b/raylib-sys/Cargo.toml index a1f98989..473559ce 100644 --- a/raylib-sys/Cargo.toml +++ b/raylib-sys/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "raylib-sys" -version = "5.5.0" +version = "5.5.1" authors = ["raylib-rs team "] license = "Zlib" description = "Raw FFI bindings for Raylib" diff --git a/raylib-test/Cargo.toml b/raylib-test/Cargo.toml index ed69f002..c2b460ac 100644 --- a/raylib-test/Cargo.toml +++ b/raylib-test/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "raylib-test" -version = "5.5.0" +version = "5.5.1" authors = ["raylib-rs team "] edition = "2018" license = "Zlib" @@ -8,8 +8,8 @@ readme = "../README.md" repository = "https://github.com/raylib-rs/raylib-rs" [dependencies] -raylib = { version = "5.5.0", path = "../raylib" } -raylib_sys = { version = "5.5.0", path = "../raylib-sys" } +raylib = { version = "5.5.1", path = "../raylib" } +raylib_sys = { version = "5.5.1", path = "../raylib-sys" } lazy_static = "1.2.0" colored = "2.1.0" diff --git a/raylib/Cargo.toml b/raylib/Cargo.toml index f83f8dd0..5d3c0566 100644 --- a/raylib/Cargo.toml +++ b/raylib/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "raylib" -version = "5.5.0" +version = "5.5.1" authors = ["raylib-rs team "] license = "Zlib" readme = "../README.md" @@ -13,7 +13,7 @@ edition = "2018" autoexamples = false [dependencies] -raylib-sys = { version = "5.5.0", path = "../raylib-sys" } +raylib-sys = { version = "5.5.1", path = "../raylib-sys" } cfg-if = "1.0.0" serde = { version = "1.0.125", features = ["derive"], optional = true } serde_json = { version = "1.0.64", optional = true } diff --git a/samples/Cargo.toml b/samples/Cargo.toml index ab4afd64..bfe21c6f 100644 --- a/samples/Cargo.toml +++ b/samples/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "raylib-examples" -version = "5.5.0" +version = "5.5.1" authors = ["raylib-rs team "] edition = "2021" license = "Zlib" @@ -9,7 +9,7 @@ repository = "https://github.com/raylib-rs/raylib-rs" [dependencies] -raylib = { path = "../raylib", version = "5.5.0" } +raylib = { path = "../raylib", version = "5.5.1" } structopt = "0.2" specs-derive = "0.4.1" rand = "0.8" @@ -106,4 +106,4 @@ required-features = ["imgui"] [[bin]] name = "music_effects" path = "music_effects.rs" -required-features = ["ringbuf"] \ No newline at end of file +required-features = ["ringbuf"] diff --git a/showcase/Cargo.toml b/showcase/Cargo.toml index 61a7244b..420646b9 100644 --- a/showcase/Cargo.toml +++ b/showcase/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "raylib-showcase" -version = "5.5.0" +version = "5.5.1" authors = ["raylib-rs team "] edition = "2018" license = "Zlib" @@ -10,4 +10,4 @@ repository = "https://github.com/raylib-rs/raylib-rs" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -raylib = { version = "5.5.0", path = "../raylib" } +raylib = { version = "5.5.1", path = "../raylib" } From bdc64b254224633a40a772258a40603074855f2e Mon Sep 17 00:00:00 2001 From: Amy Wilder <74995093+AmityWilder@users.noreply.github.com> Date: Sun, 30 Mar 2025 01:03:57 -0400 Subject: [PATCH 75/93] Change get_mouse_wheel_move_v return type (#139) --- raylib/src/core/input.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/raylib/src/core/input.rs b/raylib/src/core/input.rs index e607f427..73fa04bd 100644 --- a/raylib/src/core/input.rs +++ b/raylib/src/core/input.rs @@ -248,8 +248,8 @@ impl RaylibHandle { /// Get mouse wheel movement for both X and Y #[inline] - pub fn get_mouse_wheel_move_v(&self) -> raylib_sys::Vector2 { - unsafe { ffi::GetMouseWheelMoveV() } + pub fn get_mouse_wheel_move_v(&self) -> Vector2 { + unsafe { ffi::GetMouseWheelMoveV().into() } } /// Returns touch position X for touch point 0 (relative to screen size). From 0a9e8b235a41b9764383b983c1acd2fbaf5c5c08 Mon Sep 17 00:00:00 2001 From: Amy Wilder <74995093+AmityWilder@users.noreply.github.com> Date: Tue, 1 Apr 2025 20:03:52 -0400 Subject: [PATCH 76/93] Move check_collision_circle_line out of Rectangle impl (#149) --- raylib/src/core/collision.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/raylib/src/core/collision.rs b/raylib/src/core/collision.rs index a19cfc55..40a223a8 100644 --- a/raylib/src/core/collision.rs +++ b/raylib/src/core/collision.rs @@ -41,17 +41,16 @@ impl Rectangle { pub fn check_collision_point_rec(&self, point: impl Into) -> bool { unsafe { ffi::CheckCollisionPointRec(point.into(), self.into()) } } +} - /// Check if circle collides with a line created betweeen two points [p1] and [p2] - pub fn check_collision_circle_line( - &self, - center: impl Into, - radius: f32, - p1: impl Into, - p2: impl Into, - ) -> bool { - unsafe { ffi::CheckCollisionCircleLine(center.into(), radius, p1.into(), p2.into()) } - } +/// Check if circle collides with a line created betweeen two points [p1] and [p2] +pub fn check_collision_circle_line( + center: impl Into, + radius: f32, + p1: impl Into, + p2: impl Into, +) -> bool { + unsafe { ffi::CheckCollisionCircleLine(center.into(), radius, p1.into(), p2.into()) } } // Collision Handling From 95234d17a1943e00b06e30f8323a63b78323880c Mon Sep 17 00:00:00 2001 From: jgabaut <109908086+jgabaut@users.noreply.github.com> Date: Wed, 2 Apr 2025 02:23:27 +0200 Subject: [PATCH 77/93] [rgui] gui_panel handles empty str (#150) Restores the 5.0 usage for gui_panel(), which allowed None. Previously, passing None would cause a NULL pointer to be get to GuiPanel(), effectively avoiding the rendering of the panel label. --- raylib/src/rgui/safe.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/raylib/src/rgui/safe.rs b/raylib/src/rgui/safe.rs index 9d1c86f7..31b49179 100644 --- a/raylib/src/rgui/safe.rs +++ b/raylib/src/rgui/safe.rs @@ -218,8 +218,14 @@ pub trait RaylibDrawGui { /// Panel control, useful to group controls #[inline] fn gui_panel(&mut self, bounds: impl Into, text: &str) -> bool { - let c_filename = CString::new(text).unwrap(); - unsafe { ffi::GuiPanel(bounds.into(), c_filename.as_ptr()) > 0 } + let cstr: CString; + let c_text = if text.is_empty() { + std::ptr::null() + } else { + cstr = CString::new(text).unwrap(); + cstr.as_ptr() + }; + unsafe { ffi::GuiPanel(bounds.into(), c_text) > 0 } } /// Scroll Panel control #[inline] From aadf1a76be022f197460d061c17570803010df58 Mon Sep 17 00:00:00 2001 From: Amy Wilder <74995093+AmityWilder@users.noreply.github.com> Date: Tue, 1 Apr 2025 21:52:28 -0400 Subject: [PATCH 78/93] Fix double-end-draw bug (#152) --- raylib/src/core/drawing.rs | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index 8d4ac127..1f1d0cf4 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -37,9 +37,10 @@ impl RaylibHandle { ffi::BeginDrawing(); }; func(RaylibDrawHandle(self)); - unsafe { - ffi::EndDrawing(); - }; + // Uncomment the following if RaylibDrawHandle has been changed to no longer call EndDrawing() in its drop implementation: + // unsafe { + // ffi::EndDrawing(); + // } } } @@ -128,6 +129,8 @@ where ) { unsafe { ffi::BeginTextureMode(*framebuffer) } func(RaylibTextureMode(self, framebuffer)); + // Uncomment the following if RaylibTextureMode has been changed to no longer call EndTextureMode() in its drop implementation: + // unsafe { ffi::EndTextureMode(); } } } @@ -175,6 +178,8 @@ where ) { unsafe { ffi::BeginVrStereoMode(*vr_config.as_ref()) } func(RaylibVRMode(&self, vr_config)); + // Uncomment the following if RaylibVRMode has been changed to no longer call EndTextureMode() in its drop implementation: + // unsafe { ffi::EndVrStereoMode(); } } } @@ -227,9 +232,10 @@ where ffi::BeginMode2D(camera.into()); } func(RaylibMode2D(self), camera); - unsafe { - ffi::EndMode2D(); - } + // Uncomment the following if RaylibMode2D has been changed to no longer call EndMode2D() in its drop implementation: + // unsafe { + // ffi::EndMode2D(); + // } } } @@ -282,9 +288,10 @@ where ffi::BeginMode3D(camera.into()); } func(RaylibMode3D(self), camera); - unsafe { - ffi::EndMode3D(); - } + // Uncomment the following if RaylibMode3D has been changed to no longer call EndMode3D() in its drop implementation: + // unsafe { + // ffi::EndMode3D(); + // } } } @@ -333,6 +340,8 @@ where ) { unsafe { ffi::BeginShaderMode(*shader.as_ref()) } func(RaylibShaderMode(self, shader)); + // Uncomment the following if RaylibShaderMode has been changed to no longer call EndShaderMode() in its drop implementation: + // unsafe { ffi::EndShaderMode(); } } } @@ -380,6 +389,8 @@ where ) { unsafe { ffi::BeginBlendMode((blend_mode as u32) as i32) } func(RaylibBlendMode(self)); + // Uncomment the following if RaylibBlendMode has been changed to no longer call EndBlendMode() in its drop implementation: + // unsafe { ffi::EndBlendMode(); } } } @@ -436,6 +447,8 @@ where ) { unsafe { ffi::BeginScissorMode(x, y, width, height) } func(RaylibScissorMode(self)); + // Uncomment the following if RaylibScissorMode has been changed to no longer call EndScissorMode() in its drop implementation: + // unsafe { ffi::EndScissorMode(); } } } From cb0c0048b6c80ec8e487fafad2b07da1886007c8 Mon Sep 17 00:00:00 2001 From: Amy Wilder <74995093+AmityWilder@users.noreply.github.com> Date: Tue, 1 Apr 2025 22:03:50 -0400 Subject: [PATCH 79/93] Fix update_texture_rec precondition (#153) --- raylib/src/core/texture.rs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/raylib/src/core/texture.rs b/raylib/src/core/texture.rs index d3edd5e2..1b1885e1 100644 --- a/raylib/src/core/texture.rs +++ b/raylib/src/core/texture.rs @@ -1084,10 +1084,23 @@ pub trait RaylibTexture2D: AsRef + AsMut { rec: impl Into, pixels: &[u8], ) -> Result<(), Error> { + let rec = rec.into(); + + if (rec.x < 0.0) || (rec.y < 0.0) || ((rec.x as i32 + rec.width as i32) > (self.as_ref().width)) || ((rec.y as i32 + rec.height as i32) > (self.as_ref().height)) { + return Err(error!( + "update_texture: Destination rectangle cannot exceed texture bounds." + )); + } + if (rec.width < 0.0) || (rec.height < 0.0) { + return Err(error!( + "update_texture: Destination rectangle cannot have negative extents." + )); + } + let expected_len = unsafe { get_pixel_data_size( - self.as_ref().width, - self.as_ref().height, + rec.width as i32, + rec.height as i32, std::mem::transmute::(self.as_ref().format), ) as usize }; @@ -1101,7 +1114,7 @@ pub trait RaylibTexture2D: AsRef + AsMut { unsafe { ffi::UpdateTextureRec( *self.as_ref(), - rec.into(), + rec, pixels.as_ptr() as *const std::os::raw::c_void, ) } From ac948ceb44fd46cbf506db9738654deade12c9e3 Mon Sep 17 00:00:00 2001 From: Amy Wilder <74995093+AmityWilder@users.noreply.github.com> Date: Tue, 1 Apr 2025 22:18:33 -0400 Subject: [PATCH 80/93] Fix documentation mistake (#154) --- raylib/src/core/input.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/raylib/src/core/input.rs b/raylib/src/core/input.rs index 73fa04bd..ebe99d53 100644 --- a/raylib/src/core/input.rs +++ b/raylib/src/core/input.rs @@ -318,7 +318,7 @@ impl RaylibHandle { unsafe { ffi::GetTouchPointCount() as u32 } } - /// Gets gesture hold time in milliseconds. + /// Gets gesture hold time in seconds. #[inline] pub fn get_gesture_hold_duration(&self) -> f32 { unsafe { ffi::GetGestureHoldDuration() } From 4ef48378a6a4ef83784644ce91f48d33df969816 Mon Sep 17 00:00:00 2001 From: Amy Wilder <74995093+AmityWilder@users.noreply.github.com> Date: Thu, 3 Apr 2025 12:36:20 -0400 Subject: [PATCH 81/93] Implement `DataBuf` structure (#155) * Implement `DataBuf` structure * Make requested changes * Generalize DataBuf * Add alignment assertion * Fix doctest mistake * Update DataBuf documentation * Remember that NonNull doesn't care whether T implements Debug * Update DataBuf documentation * Add DataBuf::leak and extra safety notes --- raylib/src/core/data.rs | 185 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 169 insertions(+), 16 deletions(-) diff --git a/raylib/src/core/data.rs b/raylib/src/core/data.rs index edc96535..18c68c7c 100644 --- a/raylib/src/core/data.rs +++ b/raylib/src/core/data.rs @@ -1,7 +1,6 @@ //! Data manipulation functions. Compress and Decompress with DEFLATE use std::{ - ffi::{c_char, CString}, - path::Path, + alloc::Layout, ffi::{c_char, CString}, ops::{Deref, DerefMut}, path::Path, ptr::NonNull }; use crate::{ @@ -9,24 +8,180 @@ use crate::{ ffi, }; +/// A wrapper acting as an owned buffer for Raylib-allocated memory. +/// Automatically releases the memory with [`ffi::MemFree()`] when dropped. +/// +/// Dereference or call `.as_ref()`/`.as_mut()` to access the memory as a `&[T]` or `&mut [T]` respectively. +/// +/// # Example +/// ``` +/// use raylib::prelude::*; +/// let buf: DataBuf = compress_data(b"11111").unwrap(); +/// // Use this how you used to use the return of `compress_data()`. +/// // It will live until `buf` goes out of scope or gets dropped. +/// let data: &[u8] = buf.as_ref(); +/// let expected: &[u8] = &[1, 5, 0, 250, 255, 49, 49, 49, 49, 49]; +/// assert_eq!(data, expected); +/// ``` +#[derive(Debug)] +pub struct DataBuf { + buf: NonNull, + len: usize, +} +impl Drop for DataBuf { + fn drop(&mut self) { + unsafe { + ffi::MemFree(self.buf.as_ptr().cast()); + } + } +} +impl Deref for DataBuf { + type Target = [T]; + fn deref(&self) -> &Self::Target { + // This is safe because DataBuf contents are checked everywhere `buf` can be set. + unsafe { &*std::ptr::slice_from_raw_parts(self.buf.as_ptr(), self.len) } + } +} +impl DerefMut for DataBuf { + fn deref_mut(&mut self) -> &mut Self::Target { + // This is safe because DataBuf contents are checked everywhere `buf` can be set. + unsafe { &mut *std::ptr::slice_from_raw_parts_mut(self.buf.as_ptr(), self.len) } + } +} +impl AsRef<[T]> for DataBuf { + #[inline] + fn as_ref(&self) -> &[T] { + self.deref() + } +} +impl AsMut<[T]> for DataBuf { + #[inline] + fn as_mut(&mut self) -> &mut [T] { + self.deref_mut() + } +} +impl DataBuf { + /// Wrap an already allocated pointer in a `DataBuf`. + /// + /// **Note:** This method is only intended for use with pointers given by Raylib + /// with the expectation that they will be manually deallocated with [`ffi::MemFree`]. + /// DO NOT use this function to wrap arbitrary pointers or pointers that Raylib will + /// deallocate itself. + /// + /// If the pointer is expected to be conditionally deallocated by Raylib, + /// (i.e. conditionally passing the buffer to a Raylib function that will certainly deallocatate it) + /// use [`DataBuf::leak`] to unwrap the memory so that `drop` does not automatically free it. + /// + /// # Returns + /// + /// This method returns [`None`] if `buf` is null. + /// + /// # Panics + /// + /// This method may panic if any of the following are true while `buf` is non-null: + /// - `count` is less than 1 + /// - `buf` is unaligned + /// - total bytes exceed [`isize::MAX`] + pub(crate) fn new(buf: *mut T, count: i32) -> Option { + NonNull::new(buf).map(|buf| { + // Ensure DataBuf can always be dereferenced as a slice. + assert!(count >= 1, "non-null data should be at least 1 byte"); + assert!(buf.is_aligned(), "DataBuf should be aligned"); + assert!(std::mem::size_of::() + .checked_mul(count as usize) + .is_some_and(|total_size| total_size <= (isize::MAX as usize)), + "total size of DataBuf should not exceed `isize::MAX`"); + + Self { buf, len: count as usize } + }) + } + + /// Extract the pointer without freeing it, for the purpose of passing it to a function that will deallocate it manually. + pub(crate) fn leak(self) -> (NonNull, usize) { + let buf = self.buf; + let len = self.len; + std::mem::forget(self); + (buf, len) + } + + /// Allocate new memory managed by Raylib + /// + /// # Errors + /// + /// - "cannot allocate less than 1 element": `count` is less than 1. + /// - "memory request exceeds unsigned integer maximum": The size of `[T; count]` is greater than [`u32::MAX`]. + /// - "memory request exceeds capacity": [`ffi::MemAlloc`] returned null. + /// + /// # Panics + /// + /// This method may panic if the pointer returned by [`ffi::MemAlloc`] is unaligned. + pub fn alloc(count: i32) -> Result { + if count >= 1 { + let count = count as usize; + match Layout::array::(count) { + Err(_e) => Err(error!("memory request does not produce a valid layout")), // I would like to display `e` if possible + Ok(layout) => { + let size = layout.size(); + if size <= u32::MAX as usize { + if let Some(buf) = NonNull::new(unsafe { ffi::MemAlloc(size as u32) }.cast()) { + assert!(buf.is_aligned(), "allocated buffer should always be aligned"); + Ok(Self { buf, len: count }) + } else { Err(error!("memory request exceeds capacity")) } + } else { Err(error!("memory request exceeds unsigned integer maximum")) } + } + } + } else { Err(error!("cannot allocate less than 1 element")) } + } + + /// Reallocate memory already managed by Raylib + /// + /// # Errors + /// + /// - "cannot allocate less than 1 element": `count` is less than 1. + /// - "memory request exceeds unsigned integer maximum": The size of `[T; count]` is greater than [`u32::MAX`]. + /// - "memory request exceeds capacity": [`ffi::MemRealloc`] returned null. \ + /// **Warning:** This represents a risk of double-free if `RL_REALLOC` deallocates regardless of reallocation success, + /// because `self` will retain the old pointer and `DataBuf`'s drop implementation will still free it. + /// + /// # Panics + /// + /// This method may panic if the pointer returned by [`ffi::MemRealloc`] is unaligned. + pub fn realloc(&mut self, new_count: i32) -> Result<(), Error> { + if new_count >= 1 { + let new_count = new_count as usize; + match Layout::array::(new_count) { + Err(_e) => Err(error!("memory request does not produce a valid layout")), // I would like to display `e` if possible + Ok(layout) => { + let size = layout.size(); + if size <= u32::MAX as usize { + if let Some(buf) = NonNull::new(unsafe { ffi::MemRealloc(self.buf.as_ptr().cast(), size as u32) }.cast()) { + assert!(buf.is_aligned(), "allocated buffer should always be aligned"); + self.buf = buf; + self.len = new_count; + Ok(()) + } else { Err(error!("memory request exceeds capacity")) } + } else { Err(error!("memory request exceeds unsigned integer maximum")) } + } + } + } else { Err(error!("cannot allocate less than 1 element")) } + } +} + /// Compress data (DEFLATE algorythm) /// ```rust /// use raylib::prelude::*; /// let data = compress_data(b"11111").unwrap(); /// let expected: &[u8] = &[1, 5, 0, 250, 255, 49, 49, 49, 49, 49]; -/// assert_eq!(data, expected); +/// assert_eq!(data.as_ref(), expected); /// ``` -pub fn compress_data(data: &[u8]) -> Result<&'static [u8], Error> { +pub fn compress_data(data: &[u8]) -> Result, Error> { let mut out_length: i32 = 0; // CompressData doesn't actually modify the data, but the header is wrong let buffer = { unsafe { ffi::CompressData(data.as_ptr() as *mut _, data.len() as i32, &mut out_length) } }; - if buffer.is_null() { - return Err(error!("could not compress data")); - } - let buffer = unsafe { std::slice::from_raw_parts(buffer, out_length as usize) }; - return Ok(buffer); + DataBuf::new(buffer, out_length) + .ok_or_else(|| error!("could not compress data")) } /// Decompress data (DEFLATE algorythm) @@ -35,9 +190,10 @@ pub fn compress_data(data: &[u8]) -> Result<&'static [u8], Error> { /// let input: &[u8] = &[1, 5, 0, 250, 255, 49, 49, 49, 49, 49]; /// let expected: &[u8] = b"11111"; /// let data = decompress_data(input).unwrap(); -/// assert_eq!(data, expected); +/// assert_eq!(data.as_ref(), expected); /// ``` -pub fn decompress_data(data: &[u8]) -> Result<&'static [u8], Error> { +pub fn decompress_data(data: &[u8]) -> Result, Error> { + #[cfg(debug_assertions)] println!("{:?}", data.len()); let mut out_length: i32 = 0; @@ -45,11 +201,8 @@ pub fn decompress_data(data: &[u8]) -> Result<&'static [u8], Error> { let buffer = { unsafe { ffi::DecompressData(data.as_ptr() as *mut _, data.len() as i32, &mut out_length) } }; - if buffer.is_null() { - return Err(error!("could not compress data")); - } - let buffer = unsafe { std::slice::from_raw_parts(buffer, out_length as usize) }; - return Ok(buffer); + DataBuf::new(buffer, out_length) + .ok_or_else(|| error!("could not compress data")) } #[cfg(unix)] From bd8b94d523c29602478985b40e72c1c7d6ab5b96 Mon Sep 17 00:00:00 2001 From: Edvin Sternvik <39171004+edvinsternvik@users.noreply.github.com> Date: Sun, 6 Apr 2025 05:14:42 +0200 Subject: [PATCH 82/93] fix: Image::get_color should not require mut (#157) --- raylib/src/core/texture.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/raylib/src/core/texture.rs b/raylib/src/core/texture.rs index 1b1885e1..cc2496fd 100644 --- a/raylib/src/core/texture.rs +++ b/raylib/src/core/texture.rs @@ -159,7 +159,7 @@ impl Image { unsafe { ffi::ImageRotate(&mut self.0, degrees) } } /// Get image pixel color at (x, y) position - pub fn get_color(&mut self, x: i32, y: i32) -> Color { + pub fn get_color(&self, x: i32, y: i32) -> Color { Color::from(unsafe { ffi::GetImageColor(self.0, x, y) }) } /// Draw circle outline within an image From d830925f093ae036edbed5fe7c4393d78eafa5f9 Mon Sep 17 00:00:00 2001 From: IoIxD <30945097+IoIxD@users.noreply.github.com> Date: Sat, 5 Apr 2025 20:16:01 -0700 Subject: [PATCH 83/93] [readme] remove mention of physac (#151) --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index ecb82692..0f7b4793 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,6 @@ Most development happens over at: https://github.com/raylib-rs/raylib-rs | ------ | ------------------ | ------------------ | ------------------ | -------------- | ------- | | core | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :x: | | rgui | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | ❔ | :x: | -| physac | :construction: | :construction: | :construction: | ❔ | :x: | | rlgl | :heavy_check_mark: | :x: | :x: | ❔ | :x: | ## Build Dependencies From 0bb54956d4a61ed604dfceaa05cbc103554953b0 Mon Sep 17 00:00:00 2001 From: Amy Wilder <74995093+AmityWilder@users.noreply.github.com> Date: Wed, 9 Apr 2025 16:13:46 -0400 Subject: [PATCH 84/93] Move `.as_ptr()` so its return doesn't dangle (#163) --- raylib/src/core/drawing.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index 1f1d0cf4..18aedd54 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -1677,9 +1677,8 @@ pub trait RaylibDraw3D { let tr = transforms .iter() .map(|f| f.into()) - .collect::>() - .as_ptr(); - unsafe { ffi::DrawMeshInstanced(*mesh.as_ref(), material.0, tr, transforms.len() as i32) } + .collect::>(); + unsafe { ffi::DrawMeshInstanced(*mesh.as_ref(), material.0, tr.as_ptr(), transforms.len() as i32) } } /// Draws a sphere. From 86dfff733f38c22ddbfa0786bb0230d093a6ea89 Mon Sep 17 00:00:00 2001 From: Amy Wilder <74995093+AmityWilder@users.noreply.github.com> Date: Wed, 9 Apr 2025 16:14:07 -0400 Subject: [PATCH 85/93] Remove dependency on cfg-if (#159) * Remove cfg-if from Cargo.toml * Remove cfg_if from optional_serde_struct --- raylib/Cargo.toml | 1 - raylib/src/core/math.rs | 15 ++++----------- 2 files changed, 4 insertions(+), 12 deletions(-) diff --git a/raylib/Cargo.toml b/raylib/Cargo.toml index 5d3c0566..e74fa254 100644 --- a/raylib/Cargo.toml +++ b/raylib/Cargo.toml @@ -14,7 +14,6 @@ autoexamples = false [dependencies] raylib-sys = { version = "5.5.1", path = "../raylib-sys" } -cfg-if = "1.0.0" serde = { version = "1.0.125", features = ["derive"], optional = true } serde_json = { version = "1.0.64", optional = true } imgui = { version = "0.12.0", optional = true, features = [] } diff --git a/raylib/src/core/math.rs b/raylib/src/core/math.rs index 64970ec0..f90a3f71 100644 --- a/raylib/src/core/math.rs +++ b/raylib/src/core/math.rs @@ -26,17 +26,10 @@ make_rslice!(RSliceVec4, Vector4, ffi::MemFree); macro_rules! optional_serde_struct { ($def:item) => { - cfg_if::cfg_if! { - if #[cfg(feature = "with_serde")] { - #[repr(C)] - #[derive(Default, Debug, Copy, Clone, PartialEq, Serialize, Deserialize)] - $def - } else { - #[repr(C)] - #[derive(Default, Debug, Copy, Clone, PartialEq)] - $def - } - } + #[repr(C)] + #[derive(Default, Debug, Copy, Clone, PartialEq)] + #[cfg_attr(feature = "with_serde", derive(Serialize, Deserialize))] + $def }; } From 25f6790d3b36721daeb7c02cdfd5a1cef9c7b9d1 Mon Sep 17 00:00:00 2001 From: Amy Wilder <74995093+AmityWilder@users.noreply.github.com> Date: Wed, 9 Apr 2025 16:14:38 -0400 Subject: [PATCH 86/93] Simplify Serde `use` statements in `color.rs` and `window.rs` (#161) * Simplify serde use statement * Simplify serde use statement --- raylib/src/core/color.rs | 9 --------- raylib/src/core/window.rs | 9 --------- 2 files changed, 18 deletions(-) diff --git a/raylib/src/core/color.rs b/raylib/src/core/color.rs index fd97d5aa..e6c5b774 100644 --- a/raylib/src/core/color.rs +++ b/raylib/src/core/color.rs @@ -5,15 +5,6 @@ use crate::core::math::{Vector3, Vector4}; use crate::ffi; use raylib_sys::{ColorIsEqual, GetPixelColor, PixelFormat}; -#[cfg(not(feature = "with_serde"))] -#[cfg(feature = "serde")] -use serde::{Deserialize, Serialize}; - -#[cfg(not(feature = "serde"))] -#[cfg(feature = "with_serde")] -use serde::{Deserialize, Serialize}; - -#[cfg(feature = "with_serde")] #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; diff --git a/raylib/src/core/window.rs b/raylib/src/core/window.rs index d38f0bde..7f4fb27a 100644 --- a/raylib/src/core/window.rs +++ b/raylib/src/core/window.rs @@ -5,15 +5,6 @@ use crate::ffi; use std::ffi::{CStr, CString, IntoStringError, NulError}; use std::os::raw::c_char; -#[cfg(not(feature = "with_serde"))] -#[cfg(feature = "serde")] -use serde::{Deserialize, Serialize}; - -#[cfg(feature = "with_serde")] -#[cfg(not(feature = "serde"))] -use serde::{Deserialize, Serialize}; - -#[cfg(feature = "with_serde")] #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; From a3d13c146130dfe2bf015dae0570dfaf01736ec1 Mon Sep 17 00:00:00 2001 From: Amy Wilder <74995093+AmityWilder@users.noreply.github.com> Date: Wed, 9 Apr 2025 16:16:42 -0400 Subject: [PATCH 87/93] Make draw modes slightly more versatile (#165) * Improve lifetime versatility of drawing.rs * Undo breaking change, to be addressed in a separate issue --- raylib/src/core/drawing.rs | 167 +++++++++++++++++++------------------ 1 file changed, 88 insertions(+), 79 deletions(-) diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index 18aedd54..b4637e23 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -13,7 +13,7 @@ use crate::ffi; use crate::math::Matrix; use crate::models::{Mesh, WeakMaterial}; use crate::text::Codepoints; -use std::convert::AsRef; +use std::{convert::AsRef, marker::PhantomData}; use std::ffi::CString; use super::camera::Camera2D; @@ -24,7 +24,7 @@ impl RaylibHandle { #[must_use] /// Setup canvas (framebuffer) to start drawing. /// Prefer using the closure version, [RaylibHandle::draw]. This version returns a handle that calls [raylib_sys::EndDrawing] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) - pub fn begin_drawing(&mut self, _: &RaylibThread) -> RaylibDrawHandle { + pub fn begin_drawing<'a>(&'a mut self, _: &RaylibThread) -> RaylibDrawHandle<'a> { unsafe { ffi::BeginDrawing(); }; @@ -32,7 +32,9 @@ impl RaylibHandle { let d = RaylibDrawHandle(self); d } - pub fn draw(&mut self, _: &RaylibThread, mut func: impl FnMut(RaylibDrawHandle)) { + // Every FnMut is a FnOnce, but not every FnOnce is a FnMut. The closure may possibly execute multiple times throughout the program, but not multiple times in a single call to this method. + // Taking a FnOnce instead of a FnMut when the function only needs to be called once in this method makes the method slightly more versatile/less needlessly restrictive for no actual cost. + pub fn draw<'a>(&'a mut self, _: &RaylibThread, func: impl FnOnce(RaylibDrawHandle<'a>)) { unsafe { ffi::BeginDrawing(); }; @@ -84,21 +86,27 @@ impl<'a> RaylibDraw for RaylibDrawHandle<'a> {} // Texture2D Stuff -pub struct RaylibTextureMode<'a, T>(&'a mut T, &'a mut ffi::RenderTexture2D); +// The texture does not need to be held exclusively for the duration of the *previous* draw mode, nor does the *previous* draw mode need to outlive the texture reference. +// The texture exclusivity and previous draw mode only need to outlive the *current* draw mode. So they can (and should) have separate lifetimes. +// +// Additionally: the texture is not actually *used* by this wrapper after construction, only the previous draw mode. +// Some space can be saved by using a phantom instead of copying the actual reference. +// The PhantomData will ensure that the borrow checker still analyzes as though the mutable texture reference was held, without physically storing it in the runtime memory. +pub struct RaylibTextureMode<'a, 'b, T: 'a>(&'a mut T, PhantomData<&'b mut ffi::RenderTexture2D>); -impl<'a, T> Drop for RaylibTextureMode<'a, T> { +impl<'a, 'b, T: 'a> Drop for RaylibTextureMode<'a, 'b, T> { fn drop(&mut self) { unsafe { ffi::EndTextureMode() } } } -impl<'a, T> std::ops::Deref for RaylibTextureMode<'a, T> { +impl<'a, 'b, T: 'a> std::ops::Deref for RaylibTextureMode<'a, 'b, T> { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } -impl<'a, T> std::ops::DerefMut for RaylibTextureMode<'a, T> { +impl<'a, 'b, T: 'a> std::ops::DerefMut for RaylibTextureMode<'a, 'b, T> { fn deref_mut(&mut self) -> &mut T { self.0 } @@ -112,23 +120,23 @@ where /// Begin drawing to render texture. /// Prefer using the closure version, [RaylibTextureModeExt::draw_texture_mode] . This version returns a handle that calls [raylib_sys::EndTextureMode] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) #[must_use] - fn begin_texture_mode<'a>( + fn begin_texture_mode<'a, 'b>( &'a mut self, _: &RaylibThread, - framebuffer: &'a mut ffi::RenderTexture2D, - ) -> RaylibTextureMode { + framebuffer: &'b mut ffi::RenderTexture2D, + ) -> RaylibTextureMode<'a, 'b, Self> { unsafe { ffi::BeginTextureMode(*framebuffer) } - RaylibTextureMode(self, framebuffer) + RaylibTextureMode(self, PhantomData) } - fn draw_texture_mode<'a>( + fn draw_texture_mode<'a, 'b>( &'a mut self, _: &RaylibThread, - framebuffer: &'a mut ffi::RenderTexture2D, - mut func: impl FnMut(RaylibTextureMode), + framebuffer: &'b mut ffi::RenderTexture2D, + func: impl FnOnce(RaylibTextureMode<'a, 'b, Self>), ) { unsafe { ffi::BeginTextureMode(*framebuffer) } - func(RaylibTextureMode(self, framebuffer)); + func(RaylibTextureMode(self, PhantomData)); // Uncomment the following if RaylibTextureMode has been changed to no longer call EndTextureMode() in its drop implementation: // unsafe { ffi::EndTextureMode(); } } @@ -137,17 +145,18 @@ where // Only the DrawHandle and the RaylibHandle can start a texture impl<'a> RaylibTextureModeExt for RaylibDrawHandle<'a> {} impl RaylibTextureModeExt for RaylibHandle {} -impl<'a, T> RaylibDraw for RaylibTextureMode<'a, T> {} +impl<'a, 'b, T: 'a> RaylibDraw for RaylibTextureMode<'a, 'b, T> {} // VR Stuff -pub struct RaylibVRMode<'a, T>(&'a T, &'a mut VrStereoConfig); -impl<'a, T> Drop for RaylibVRMode<'a, T> { +// Lifetime 'a is duplicatively stored in a PhantomData so that the borrow checker knows T is being held *exclusively* for the lifetime of the mode, without giving the false impression that it can actually be mutated by the library. +pub struct RaylibVRMode<'a, 'b, T: 'a>(&'a T, PhantomData<&'a mut T>, PhantomData<&'b mut VrStereoConfig>); +impl<'a, 'b, T: 'a> Drop for RaylibVRMode<'a, 'b, T> { fn drop(&mut self) { unsafe { ffi::EndVrStereoMode() } } } -impl<'a, T> std::ops::Deref for RaylibVRMode<'a, T> { +impl<'a, 'b, T: 'a> std::ops::Deref for RaylibVRMode<'a, 'b, T> { type Target = T; fn deref(&self) -> &Self::Target { @@ -162,46 +171,46 @@ where /// Begin stereo rendering (requires VR simulator). /// Prefer using the closure version, [RaylibVRModeExt::draw_vr_stereo_mode] . This version returns a handle that calls [raylib_sys::EndVrStereoMode] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) #[must_use] - fn begin_vr_stereo_mode<'a>( + fn begin_vr_stereo_mode<'a, 'b>( &'a mut self, _: &RaylibThread, - vr_config: &'a mut VrStereoConfig, - ) -> RaylibVRMode { + vr_config: &'b mut VrStereoConfig, + ) -> RaylibVRMode<'a, 'b, Self> { unsafe { ffi::BeginVrStereoMode(*vr_config.as_ref()) } - RaylibVRMode(self, vr_config) + RaylibVRMode(self, PhantomData, PhantomData) } - fn draw_vr_stereo_mode<'a>( + fn draw_vr_stereo_mode<'a, 'b>( &'a mut self, - vr_config: &'a mut VrStereoConfig, - mut func: impl FnMut(RaylibVRMode), + vr_config: &'b mut VrStereoConfig, + func: impl FnOnce(RaylibVRMode<'a, 'b, Self>), ) { unsafe { ffi::BeginVrStereoMode(*vr_config.as_ref()) } - func(RaylibVRMode(&self, vr_config)); + func(RaylibVRMode(self, PhantomData, PhantomData)); // Uncomment the following if RaylibVRMode has been changed to no longer call EndTextureMode() in its drop implementation: // unsafe { ffi::EndVrStereoMode(); } } } impl RaylibVRModeExt for D {} -impl<'a, T> RaylibDraw for RaylibVRMode<'a, T> {} +impl<'a, 'b, T: 'a> RaylibDraw for RaylibVRMode<'a, 'b, T> {} // 2D Mode -pub struct RaylibMode2D<'a, T>(&'a mut T); -impl<'a, T> Drop for RaylibMode2D<'a, T> { +pub struct RaylibMode2D<'a, T: 'a>(&'a mut T); +impl<'a, T: 'a> Drop for RaylibMode2D<'a, T> { fn drop(&mut self) { unsafe { ffi::EndMode2D() } } } -impl<'a, T> std::ops::Deref for RaylibMode2D<'a, T> { +impl<'a, T: 'a> std::ops::Deref for RaylibMode2D<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } -impl<'a, T> std::ops::DerefMut for RaylibMode2D<'a, T> { +impl<'a, T: 'a> std::ops::DerefMut for RaylibMode2D<'a, T> { fn deref_mut(&mut self) -> &mut T { self.0 } @@ -215,7 +224,7 @@ where /// Prefer using the closure version, [RaylibMode2DExt::draw_mode2D]. This version returns a handle that calls [raylib_sys::EndMode2D] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) #[allow(non_snake_case)] #[must_use] - fn begin_mode2D(&mut self, camera: impl Into) -> RaylibMode2D { + fn begin_mode2D(&mut self, camera: impl Into) -> RaylibMode2D<'_, Self> { unsafe { ffi::BeginMode2D(camera.into()); } @@ -223,10 +232,10 @@ where } #[allow(non_snake_case)] - fn draw_mode2D( - &mut self, + fn draw_mode2D<'a>( + &'a mut self, camera: Camera2D, - mut func: impl FnMut(RaylibMode2D, Camera2D), + func: impl FnOnce(RaylibMode2D<'a, Self>, Camera2D), ) { unsafe { ffi::BeginMode2D(camera.into()); @@ -240,24 +249,24 @@ where } impl RaylibMode2DExt for D {} -impl<'a, T> RaylibDraw for RaylibMode2D<'a, T> {} +impl<'a, T: 'a> RaylibDraw for RaylibMode2D<'a, T> {} // 3D Mode -pub struct RaylibMode3D<'a, T>(&'a mut T); -impl<'a, T> Drop for RaylibMode3D<'a, T> { +pub struct RaylibMode3D<'a, T: 'a>(&'a mut T); +impl<'a, T: 'a> Drop for RaylibMode3D<'a, T> { fn drop(&mut self) { unsafe { ffi::EndMode3D() } } } -impl<'a, T> std::ops::Deref for RaylibMode3D<'a, T> { +impl<'a, T: 'a> std::ops::Deref for RaylibMode3D<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } -impl<'a, T> std::ops::DerefMut for RaylibMode3D<'a, T> { +impl<'a, T: 'a> std::ops::DerefMut for RaylibMode3D<'a, T> { fn deref_mut(&mut self) -> &mut T { self.0 } @@ -271,7 +280,7 @@ where /// Prefer using the closure version, [RaylibMode3DExt::draw_mode3D]. This version returns a handle that calls [raylib_sys::EndMode3D] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) #[allow(non_snake_case)] #[must_use] - fn begin_mode3D(&mut self, camera: impl Into) -> RaylibMode3D { + fn begin_mode3D(&mut self, camera: impl Into) -> RaylibMode3D<'_, Self> { unsafe { ffi::BeginMode3D(camera.into()); } @@ -279,10 +288,10 @@ where } #[allow(non_snake_case)] - fn draw_mode3D( - &mut self, + fn draw_mode3D<'a>( + &'a mut self, camera: Camera3D, - mut func: impl FnMut(RaylibMode3D, Camera3D), + func: impl FnOnce(RaylibMode3D<'a, Self>, Camera3D), ) { unsafe { ffi::BeginMode3D(camera.into()); @@ -296,26 +305,26 @@ where } impl RaylibMode3DExt for D {} -impl<'a, T> RaylibDraw for RaylibMode3D<'a, T> {} -impl<'a, T> RaylibDraw3D for RaylibMode3D<'a, T> {} +impl<'a, T: 'a> RaylibDraw for RaylibMode3D<'a, T> {} +impl<'a, T: 'a> RaylibDraw3D for RaylibMode3D<'a, T> {} // shader Mode -pub struct RaylibShaderMode<'a, T>(&'a mut T, &'a mut Shader); +pub struct RaylibShaderMode<'a, 'b, T: 'a>(&'a mut T, PhantomData<&'b mut Shader>); -impl<'a, T> Drop for RaylibShaderMode<'a, T> { +impl<'a, 'b, T: 'a> Drop for RaylibShaderMode<'a, 'b, T> { fn drop(&mut self) { unsafe { ffi::EndShaderMode() } } } -impl<'a, T> std::ops::Deref for RaylibShaderMode<'a, T> { +impl<'a, 'b, T: 'a> std::ops::Deref for RaylibShaderMode<'a, 'b, T> { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } -impl<'a, T> std::ops::DerefMut for RaylibShaderMode<'a, T> { +impl<'a, 'b, T: 'a> std::ops::DerefMut for RaylibShaderMode<'a, 'b, T> { fn deref_mut(&mut self) -> &mut T { self.0 } @@ -328,43 +337,43 @@ where /// Begin custom shader drawing. /// Prefer using the closure version, [RaylibShaderModeExt::draw_shader_mode]. This version returns a handle that calls [raylib_sys::EndShaderMode] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) #[must_use] - fn begin_shader_mode<'a>(&'a mut self, shader: &'a mut Shader) -> RaylibShaderMode { + fn begin_shader_mode<'a, 'b>(&'a mut self, shader: &'b mut Shader) -> RaylibShaderMode<'a, 'b, Self> { unsafe { ffi::BeginShaderMode(*shader.as_ref()) } - RaylibShaderMode(self, shader) + RaylibShaderMode(self, PhantomData) } - fn draw_shader_mode<'a>( + fn draw_shader_mode<'a, 'b>( &'a mut self, - shader: &'a mut Shader, - mut func: impl FnMut(RaylibShaderMode), + shader: &'b mut Shader, + func: impl FnOnce(RaylibShaderMode<'a, 'b, Self>), ) { unsafe { ffi::BeginShaderMode(*shader.as_ref()) } - func(RaylibShaderMode(self, shader)); + func(RaylibShaderMode(self, PhantomData)); // Uncomment the following if RaylibShaderMode has been changed to no longer call EndShaderMode() in its drop implementation: // unsafe { ffi::EndShaderMode(); } } } impl RaylibShaderModeExt for D {} -impl<'a, T> RaylibDraw for RaylibShaderMode<'a, T> {} -impl<'a, T> RaylibDraw3D for RaylibShaderMode<'a, T> {} +impl<'a, 'b, T: 'a> RaylibDraw for RaylibShaderMode<'a, 'b, T> {} +impl<'a, 'b, T: 'a> RaylibDraw3D for RaylibShaderMode<'a, 'b, T> {} // Blend Mode -pub struct RaylibBlendMode<'a, T>(&'a mut T); -impl<'a, T> Drop for RaylibBlendMode<'a, T> { +pub struct RaylibBlendMode<'a, T: 'a>(&'a mut T); +impl<'a, T: 'a> Drop for RaylibBlendMode<'a, T> { fn drop(&mut self) { unsafe { ffi::EndBlendMode() } } } -impl<'a, T> std::ops::Deref for RaylibBlendMode<'a, T> { +impl<'a, T: 'a> std::ops::Deref for RaylibBlendMode<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } -impl<'a, T> std::ops::DerefMut for RaylibBlendMode<'a, T> { +impl<'a, T: 'a> std::ops::DerefMut for RaylibBlendMode<'a, T> { fn deref_mut(&mut self) -> &mut T { self.0 } @@ -377,15 +386,15 @@ where /// Begin blending mode (alpha, additive, multiplied, subtract, custom). /// Prefer using the closure version, [RaylibBlendModeExt::draw_blend_mode]. This version returns a handle that calls [raylib_sys::EndBlendMode] at the end of the scope and is provided as a fallback incase you run into issues with closures(such as lifetime or performance reasons) #[must_use] - fn begin_blend_mode(&mut self, blend_mode: crate::consts::BlendMode) -> RaylibBlendMode { + fn begin_blend_mode(&mut self, blend_mode: crate::consts::BlendMode) -> RaylibBlendMode<'_, Self> { unsafe { ffi::BeginBlendMode((blend_mode as u32) as i32) } RaylibBlendMode(self) } - fn draw_blend_mode( - &mut self, + fn draw_blend_mode<'a>( + &'a mut self, blend_mode: crate::consts::BlendMode, - mut func: impl FnMut(RaylibBlendMode), + func: impl FnOnce(RaylibBlendMode<'a, Self>), ) { unsafe { ffi::BeginBlendMode((blend_mode as u32) as i32) } func(RaylibBlendMode(self)); @@ -395,25 +404,25 @@ where } impl RaylibBlendModeExt for D {} -impl<'a, T> RaylibDraw for RaylibBlendMode<'a, T> {} -impl<'a, T> RaylibDraw3D for RaylibBlendMode<'a, T> {} +impl<'a, T: 'a> RaylibDraw for RaylibBlendMode<'a, T> {} +impl<'a, T: 'a> RaylibDraw3D for RaylibBlendMode<'a, T> {} // Scissor Mode stuff -pub struct RaylibScissorMode<'a, T>(&'a mut T); -impl<'a, T> Drop for RaylibScissorMode<'a, T> { +pub struct RaylibScissorMode<'a, T: 'a>(&'a mut T); +impl<'a, T: 'a> Drop for RaylibScissorMode<'a, T> { fn drop(&mut self) { unsafe { ffi::EndScissorMode() } } } -impl<'a, T> std::ops::Deref for RaylibScissorMode<'a, T> { +impl<'a, T: 'a> std::ops::Deref for RaylibScissorMode<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } -impl<'a, T> std::ops::DerefMut for RaylibScissorMode<'a, T> { +impl<'a, T: 'a> std::ops::DerefMut for RaylibScissorMode<'a, T> { fn deref_mut(&mut self) -> &mut T { self.0 } @@ -432,18 +441,18 @@ where y: i32, width: i32, height: i32, - ) -> RaylibScissorMode { + ) -> RaylibScissorMode<'_, Self> { unsafe { ffi::BeginScissorMode(x, y, width, height) } RaylibScissorMode(self) } - fn draw_scissor_mode( - &mut self, + fn draw_scissor_mode<'a>( + &'a mut self, x: i32, y: i32, width: i32, height: i32, - mut func: impl FnMut(RaylibScissorMode), + func: impl FnOnce(RaylibScissorMode<'a, Self>), ) { unsafe { ffi::BeginScissorMode(x, y, width, height) } func(RaylibScissorMode(self)); @@ -453,8 +462,8 @@ where } impl RaylibScissorModeExt for D {} -impl<'a, T> RaylibDraw for RaylibScissorMode<'a, T> {} -impl<'a, T: RaylibDraw3D> RaylibDraw3D for RaylibScissorMode<'a, T> {} +impl<'a, T: 'a> RaylibDraw for RaylibScissorMode<'a, T> {} +impl<'a, T: 'a + RaylibDraw3D> RaylibDraw3D for RaylibScissorMode<'a, T> {} // Actual drawing functions From 85d67ce3fd1ca295495731f588476f8f04633ef6 Mon Sep 17 00:00:00 2001 From: Amy Wilder <74995093+AmityWilder@users.noreply.github.com> Date: Wed, 9 Apr 2025 19:34:45 -0400 Subject: [PATCH 88/93] Remove redundant camera argument (#167) --- raylib/src/core/drawing.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index b4637e23..d0b377c4 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -235,12 +235,12 @@ where fn draw_mode2D<'a>( &'a mut self, camera: Camera2D, - func: impl FnOnce(RaylibMode2D<'a, Self>, Camera2D), + func: impl FnOnce(RaylibMode2D<'a, Self>), ) { unsafe { ffi::BeginMode2D(camera.into()); } - func(RaylibMode2D(self), camera); + func(RaylibMode2D(self)); // Uncomment the following if RaylibMode2D has been changed to no longer call EndMode2D() in its drop implementation: // unsafe { // ffi::EndMode2D(); @@ -291,12 +291,12 @@ where fn draw_mode3D<'a>( &'a mut self, camera: Camera3D, - func: impl FnOnce(RaylibMode3D<'a, Self>, Camera3D), + func: impl FnOnce(RaylibMode3D<'a, Self>), ) { unsafe { ffi::BeginMode3D(camera.into()); } - func(RaylibMode3D(self), camera); + func(RaylibMode3D(self)); // Uncomment the following if RaylibMode3D has been changed to no longer call EndMode3D() in its drop implementation: // unsafe { // ffi::EndMode3D(); From e6f7a599f305cdc9dec9b1a42e75d1b7561b3170 Mon Sep 17 00:00:00 2001 From: Amy Wilder <74995093+AmityWilder@users.noreply.github.com> Date: Thu, 10 Apr 2025 12:09:38 -0400 Subject: [PATCH 89/93] Get `load_shader` and `load_shader_from_memory` working with Option ergonomics (#169) * Replace match statement with map_or_else * Remove resolved comments --- raylib/src/core/shaders.rs | 44 +++++++------------------------------- 1 file changed, 8 insertions(+), 36 deletions(-) diff --git a/raylib/src/core/shaders.rs b/raylib/src/core/shaders.rs index b841a875..6aa96ce3 100644 --- a/raylib/src/core/shaders.rs +++ b/raylib/src/core/shaders.rs @@ -29,17 +29,10 @@ impl RaylibHandle { let c_vs_filename = vs_filename.map(|f| CString::new(f).unwrap()); let c_fs_filename = fs_filename.map(|f| CString::new(f).unwrap()); - // Trust me, I have tried ALL the RUST option ergonamics. This is the only way - // to get this to work without raylib breaking for whatever reason - // UPDATE FOR 2024 FROM ANOTHER PERSON: Yes this is still true, doing although "for some reason" is likely due to the pointer getting freed too early if you don't do it this way. - let shader = match (c_vs_filename, c_fs_filename) { - (Some(vs), Some(fs)) => unsafe { Shader(ffi::LoadShader(vs.as_ptr(), fs.as_ptr())) }, - (None, Some(fs)) => unsafe { Shader(ffi::LoadShader(std::ptr::null(), fs.as_ptr())) }, - (Some(vs), None) => unsafe { Shader(ffi::LoadShader(vs.as_ptr(), std::ptr::null())) }, - (None, None) => unsafe { Shader(ffi::LoadShader(std::ptr::null(), std::ptr::null())) }, - }; + let vs = c_vs_filename.as_ref().map_or_else(std::ptr::null, |s| s.as_ptr()); + let fs = c_fs_filename.as_ref().map_or_else(std::ptr::null, |s| s.as_ptr()); - return shader; + Shader(unsafe { ffi::LoadShader(vs, fs) }) } /// Loads shader from code strings and binds default locations. @@ -51,32 +44,11 @@ impl RaylibHandle { ) -> Shader { let c_vs_code = vs_code.map(|f| CString::new(f).unwrap()); let c_fs_code = fs_code.map(|f| CString::new(f).unwrap()); - return match (c_vs_code, c_fs_code) { - (Some(vs), Some(fs)) => unsafe { - Shader(ffi::LoadShaderFromMemory( - vs.as_ptr() as *mut c_char, - fs.as_ptr() as *mut c_char, - )) - }, - (None, Some(fs)) => unsafe { - Shader(ffi::LoadShaderFromMemory( - std::ptr::null_mut(), - fs.as_ptr() as *mut c_char, - )) - }, - (Some(vs), None) => unsafe { - Shader(ffi::LoadShaderFromMemory( - vs.as_ptr() as *mut c_char, - std::ptr::null_mut(), - )) - }, - (None, None) => unsafe { - Shader(ffi::LoadShaderFromMemory( - std::ptr::null_mut(), - std::ptr::null_mut(), - )) - }, - }; + + let vs = c_vs_code.as_ref().map_or_else(std::ptr::null, |s| s.as_ptr()); + let fs = c_fs_code.as_ref().map_or_else(std::ptr::null, |s| s.as_ptr()); + + Shader(unsafe { ffi::LoadShaderFromMemory(vs, fs) }) } /// Get default shader. Modifying it modifies everthing that uses that shader From 927dccdceb5ae5d51c93f8c5fdfd4a42ca56998d Mon Sep 17 00:00:00 2001 From: Amy Wilder <74995093+AmityWilder@users.noreply.github.com> Date: Fri, 11 Apr 2025 20:17:30 -0400 Subject: [PATCH 90/93] Implement lazy iterators (#171) * Create FilePathIter and create initial tests * Add file path iter tests * Improve FilePathIter doctests * Make iterators for automation.rs and model.rs * Add extra iterator methods for optimization --------- Co-authored-by: Henry Wilder <74995093+HenryWilder@users.noreply.github.com> --- raylib/src/core/automation.rs | 62 ++++++++++ raylib/src/core/file.rs | 227 +++++++++++++++++++++++++++++++++- raylib/src/core/models.rs | 135 ++++++++++++++++++++ 3 files changed, 423 insertions(+), 1 deletion(-) diff --git a/raylib/src/core/automation.rs b/raylib/src/core/automation.rs index cd9e4bb1..b9cc4a5c 100644 --- a/raylib/src/core/automation.rs +++ b/raylib/src/core/automation.rs @@ -6,6 +6,64 @@ use std::{ use crate::{ffi, RaylibHandle}; +#[derive(Debug, Clone)] +pub struct AutomationEventIter<'a> { + iter: std::slice::Iter<'a, ffi::AutomationEvent> +} +impl<'a> AutomationEventIter<'a> { + unsafe fn new(events: *mut ffi::AutomationEvent, count: u32) -> Self { + // No new items are being created that get dropped here, these are just changes in perspective of how to borrow-check the pointers. + assert!(!events.is_null(), "automation event array cannot be null"); + assert!(events.is_aligned(), "automation event array must be aligned"); + let iter = unsafe { std::slice::from_raw_parts(events, count as usize) }.iter(); + Self { iter } + } + fn func(e: &ffi::AutomationEvent) -> AutomationEvent { + // This relies on the fact that `ffi::AutomationEvent` is Copy `unload_automation_event` doesn't actually do anything. + AutomationEvent(*e) + } +} +impl<'a> Iterator for AutomationEventIter<'a> { + type Item = AutomationEvent; + + fn next(&mut self) -> Option { + self.iter.next().map(Self::func) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } + + #[inline] + fn count(self) -> usize { + self.len() + } + + fn last(self) -> Option { + self.iter.last().map(Self::func) + } + + fn nth(&mut self, n: usize) -> Option { + self.iter.nth(n).map(Self::func) + } +} +impl<'a> DoubleEndedIterator for AutomationEventIter<'a> { + fn next_back(&mut self) -> Option { + self.iter.next_back().map(Self::func) + } + + fn nth_back(&mut self, n: usize) -> Option { + self.iter.nth_back(n).map(Self::func) + } +} +impl<'a> ExactSizeIterator for AutomationEventIter<'a> { + #[inline] + fn len(&self) -> usize { + self.iter.len() + } +} + make_thin_wrapper!( AutomationEventList, ffi::AutomationEventList, @@ -30,6 +88,10 @@ impl AutomationEventList { .map(|f| AutomationEvent(*f)) .collect() } + /// An iterator over the events held in this list. + pub fn iter<'a>(&'a self) -> AutomationEventIter<'a> { + unsafe { AutomationEventIter::new(self.0.events, self.count()) } + } /// Export automation events list as text file pub fn export(&self, file_name: impl AsRef) -> bool { diff --git a/raylib/src/core/file.rs b/raylib/src/core/file.rs index abe3dfaa..f7c1d8cf 100644 --- a/raylib/src/core/file.rs +++ b/raylib/src/core/file.rs @@ -2,7 +2,120 @@ use crate::ffi; use crate::core::RaylibHandle; -use std::ffi::{CStr, CString, OsString}; +use std::ffi::{c_char, CStr, CString, OsString}; + +#[derive(Debug, Clone)] +pub struct FilePathIter<'a> { + iter: std::slice::Iter<'a, Option<&'a c_char>>, +} +impl<'a> FilePathIter<'a> { + /// # Safety + /// The memory pointed to by `list` must not be mutated for `'a`. + /// Every `*mut c_char` in `list` must outlive `'a`. + /// + /// ## Examples + /// + /// The following is invalid, because `list` is dropped while `it` is still borrowing it. + /// ```compile_fail + /// # use raylib::{ffi, file::*}; + /// # use std::{mem::ManuallyDrop, ffi::CStr}; + /// let mut it; + /// let s; + /// { + /// let mut paths = [ + /// CStr::from_bytes_with_nul(b"apple\0").unwrap().as_ptr().cast_mut(), + /// ]; + /// let mut list = ManuallyDrop::new(unsafe { + /// FilePathList::from_raw(ffi::FilePathList { + /// capacity: 1, + /// count: 1, + /// paths: paths.as_mut_ptr(), + /// }) + /// }); + /// it = list.iter(); // expect error[E0597] + /// // ^^^^ borrowed value does not live long enough + /// s = it.next(); + /// assert_eq!(s, Some("apple")); + /// } // `list` dropped here while still borrowed + /// assert_eq!(s, Some("apple")); // borrow later used here + /// ``` + /// + /// The following is invalid, because `list` is mutated while `it` is still borrowing it. + /// ```compile_fail + /// # use raylib::{ffi, file::*}; + /// # use std::{mem::ManuallyDrop, ffi::CStr}; + /// let mut paths = [ + /// CStr::from_bytes_with_nul(b"apple\0").unwrap().as_ptr().cast_mut(), + /// ]; + /// let mut list = ManuallyDrop::new(unsafe { + /// FilePathList::from_raw(ffi::FilePathList { + /// capacity: 1, + /// count: 1, + /// paths: paths.as_mut_ptr(), + /// }) + /// }); + /// let mut it = list.iter(); + /// // ---- immutable borrow occurs here + /// let s = it.next(); + /// assert_eq!(s, Some("apple")); + /// unsafe { *(*list.paths) = b'@' as std::ffi::c_char; } // expect error[E0502] + /// // ^^^^ mutable borrow occurs here + /// assert_eq!(s, Some("apple")); // immutable borrow later used here + /// ``` + unsafe fn new(list: *mut *mut c_char, count: u32) -> Self { + // No new items are being created that get dropped here, these are just changes in perspective of how to borrow-check the pointers. + assert!(!list.is_null(), "file path array cannot be null"); + assert!(list.is_aligned(), "file path array must be aligned"); + let list = list.cast::>(); + let iter = unsafe { std::slice::from_raw_parts(list, count as usize) }.iter(); + Self { iter } + } + fn func(f: &Option<&'a c_char>) -> &'a str { + // CStr isn't being "constructed", it's essentially an adapter on &[c_char] + let s = std::slice::from_ref(f.expect("file path string cannot be null")); + unsafe { CStr::from_ptr(s.as_ptr()) }.to_str().unwrap() + } +} +impl<'a> Iterator for FilePathIter<'a> { + type Item = &'a str; + + fn next(&mut self) -> Option { + self.iter.next().map(Self::func) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } + + #[inline] + fn count(self) -> usize { + self.len() + } + + fn last(self) -> Option { + self.iter.last().map(Self::func) + } + + fn nth(&mut self, n: usize) -> Option { + self.iter.nth(n).map(Self::func) + } +} +impl<'a> DoubleEndedIterator for FilePathIter<'a> { + fn next_back(&mut self) -> Option { + self.iter.next_back().map(Self::func) + } + + fn nth_back(&mut self, n: usize) -> Option { + self.iter.nth_back(n).map(Self::func) + } +} +impl<'a> ExactSizeIterator for FilePathIter<'a> { + #[inline] + fn len(&self) -> usize { + self.iter.len() + } +} make_thin_wrapper!(FilePathList, ffi::FilePathList, ffi::UnloadDirectoryFiles); make_thin_wrapper!( @@ -28,6 +141,10 @@ impl FilePathList { .map(|f| unsafe { CStr::from_ptr(*f) }.to_str().unwrap()) .collect() } + /// An iterator over the paths held in this list. + pub fn iter<'a>(&'a self) -> FilePathIter<'a> { + unsafe { FilePathIter::new(self.0.paths, self.count()) } + } } impl DroppedFilePathList { @@ -47,6 +164,10 @@ impl DroppedFilePathList { .map(|f| unsafe { CStr::from_ptr(*f) }.to_str().unwrap()) .collect() } + /// An iterator over the paths held in this list. + pub fn iter<'a>(&'a self) -> FilePathIter<'a> { + unsafe { FilePathIter::new(self.0.paths, self.count()) } + } } impl RaylibHandle { @@ -137,3 +258,107 @@ impl RaylibHandle { unsafe { DroppedFilePathList(ffi::LoadDroppedFiles()) } } } + +#[cfg(test)] +mod tests { + use std::mem::ManuallyDrop; + use super::*; + + #[test] + #[should_panic(expected = "file path array cannot be null")] + fn test_null_list() { + let list = ManuallyDrop::new(FilePathList(ffi::FilePathList { + capacity: 0, + count: 0, + paths: std::ptr::null_mut(), + })); + let _it = list.iter(); + // should have panicked while calling .iter() + } + + #[test] + #[should_panic(expected = "file path string cannot be null")] + fn test_null_item() { + let mut paths = [std::ptr::null_mut()]; + let list = ManuallyDrop::new(FilePathList(ffi::FilePathList { + capacity: 1, + count: 1, + paths: paths.as_mut_ptr(), + })); + let mut it = list.iter(); + let _f = it.next(); + // should have panicked while calling .next() + } + + #[test] + #[should_panic(expected = "file path string cannot be null")] + fn test_null_item_double_ended() { + let mut paths = [std::ptr::null_mut()]; + let list = ManuallyDrop::new(FilePathList(ffi::FilePathList { + capacity: 1, + count: 1, + paths: paths.as_mut_ptr(), + })); + let mut it = list.iter(); + let _f = it.next_back(); + // should have panicked while calling .next_back() + } + + #[test] + fn test_len() { + let mut paths = [ + CStr::from_bytes_with_nul(b"apple\0").unwrap().as_ptr().cast_mut(), + CStr::from_bytes_with_nul(b"orange\0").unwrap().as_ptr().cast_mut(), + CStr::from_bytes_with_nul(b"banana\0").unwrap().as_ptr().cast_mut(), + CStr::from_bytes_with_nul(b"mango\0").unwrap().as_ptr().cast_mut(), + CStr::from_bytes_with_nul(b"pineapple\0").unwrap().as_ptr().cast_mut(), + ]; + let list = ManuallyDrop::new(FilePathList(ffi::FilePathList { + capacity: 5, + count: 5, + paths: paths.as_mut_ptr(), + })); + let mut it = list.iter(); + assert_eq!(it.len(), 5); + assert_eq!(it.next(), Some("apple")); + assert_eq!(it.len(), 4); + assert_eq!(it.next(), Some("orange")); + assert_eq!(it.len(), 3); + assert_eq!(it.next(), Some("banana")); + assert_eq!(it.len(), 2); + assert_eq!(it.next(), Some("mango")); + assert_eq!(it.len(), 1); + assert_eq!(it.next(), Some("pineapple")); + assert_eq!(it.len(), 0); + assert_eq!(it.next(), None); + } + + #[test] + fn test_len_double_ended() { + let mut paths = [ + CStr::from_bytes_with_nul(b"apple\0").unwrap().as_ptr().cast_mut(), + CStr::from_bytes_with_nul(b"orange\0").unwrap().as_ptr().cast_mut(), + CStr::from_bytes_with_nul(b"banana\0").unwrap().as_ptr().cast_mut(), + CStr::from_bytes_with_nul(b"mango\0").unwrap().as_ptr().cast_mut(), + CStr::from_bytes_with_nul(b"pineapple\0").unwrap().as_ptr().cast_mut(), + ]; + let list = ManuallyDrop::new(FilePathList(ffi::FilePathList { + capacity: 5, + count: 5, + paths: paths.as_mut_ptr(), + })); + let mut it = list.iter(); + assert_eq!(it.len(), 5); + assert_eq!(it.next_back(), Some("pineapple")); + assert_eq!(it.len(), 4); + assert_eq!(it.next_back(), Some("mango")); + assert_eq!(it.len(), 3); + assert_eq!(it.next_back(), Some("banana")); + assert_eq!(it.len(), 2); + assert_eq!(it.next_back(), Some("orange")); + assert_eq!(it.len(), 1); + assert_eq!(it.next_back(), Some("apple")); + assert_eq!(it.len(), 0); + assert_eq!(it.next_back(), None); + } +} diff --git a/raylib/src/core/models.rs b/raylib/src/core/models.rs index f8555d1b..a93fb6e2 100644 --- a/raylib/src/core/models.rs +++ b/raylib/src/core/models.rs @@ -532,6 +532,133 @@ pub trait RaylibMaterial: AsRef + AsMut { } } +#[derive(Debug, Clone)] +pub struct FramePoseIter<'a> { + iter: std::slice::Iter<'a, Option<&'a [crate::math::Transform]>>, + bone_count: usize, +} +impl<'a> FramePoseIter<'a> { + unsafe fn new(frame_poses: *mut *mut ffi::Transform, frame_count: usize, bone_count: usize) -> Self { + // No new items are being created that get dropped here, these are just changes in perspective of how to borrow-check the pointers. + assert!(!frame_poses.is_null(), "frame pose array cannot be null"); + assert!(frame_poses.is_aligned(), "frame pose array must be aligned"); + let frame_poses = frame_poses.cast::>(); + let iter = unsafe { std::slice::from_raw_parts(frame_poses, frame_count) }.iter(); + Self { iter, bone_count } + } + fn func(tf: &Option<&'a [crate::math::Transform]>, bone_count: usize) -> &'a [crate::math::Transform] { + unsafe { std::slice::from_raw_parts(tf.expect("frame pose transform cannot be null").as_ptr(), bone_count) } + } +} +impl<'a> Iterator for FramePoseIter<'a> { + type Item = &'a [crate::math::Transform]; + + fn next(&mut self) -> Option { + let bone_count = self.bone_count; + self.iter.next().map(move |tf| Self::func(tf, bone_count)) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } + + #[inline] + fn count(self) -> usize { + self.len() + } + + fn last(self) -> Option { + let bone_count = self.bone_count; + self.iter.last().map(move |tf| Self::func(tf, bone_count)) + } + + fn nth(&mut self, n: usize) -> Option { + let bone_count = self.bone_count; + self.iter.nth(n).map(move |tf| Self::func(tf, bone_count)) + } +} +impl<'a> DoubleEndedIterator for FramePoseIter<'a> { + fn next_back(&mut self) -> Option { + let bone_count = self.bone_count; + self.iter.next_back().map(move |tf| Self::func(tf, bone_count)) + } + + fn nth_back(&mut self, n: usize) -> Option { + let bone_count = self.bone_count; + self.iter.nth_back(n).map(move |tf| Self::func(tf, bone_count)) + } +} +impl<'a> ExactSizeIterator for FramePoseIter<'a> { + #[inline] + fn len(&self) -> usize { + self.iter.len() + } +} +#[derive(Debug)] +pub struct FramePoseIterMut<'a> { + iter: std::slice::IterMut<'a, Option<&'a mut [crate::math::Transform]>>, + bone_count: usize, +} +impl<'a> FramePoseIterMut<'a> { + unsafe fn new(frame_poses: *mut *mut ffi::Transform, frame_count: usize, bone_count: usize) -> Self { + // No new items are being created that get dropped here, these are just changes in perspective of how to borrow-check the pointers. + assert!(!frame_poses.is_null(), "frame pose array cannot be null"); + assert!(frame_poses.is_aligned(), "frame pose array must be aligned"); + let frame_poses = frame_poses.cast::>(); + let iter = unsafe { std::slice::from_raw_parts_mut(frame_poses, frame_count) }.iter_mut(); + Self { iter, bone_count } + } + fn func(tf: &mut Option<&'a mut [crate::math::Transform]>, bone_count: usize) -> &'a mut [crate::math::Transform] { + unsafe { std::slice::from_raw_parts_mut(tf.as_mut().expect("frame pose transform cannot be null").as_mut_ptr(), bone_count) } + } +} +impl<'a> Iterator for FramePoseIterMut<'a> { + type Item = &'a mut [crate::math::Transform]; + + fn next(&mut self) -> Option { + let bone_count = self.bone_count; + self.iter.next().map(move |tf| Self::func(tf, bone_count)) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } + + #[inline] + fn count(self) -> usize { + self.len() + } + + fn last(self) -> Option { + let bone_count = self.bone_count; + self.iter.last().map(move |tf| Self::func(tf, bone_count)) + } + + fn nth(&mut self, n: usize) -> Option { + let bone_count = self.bone_count; + self.iter.nth(n).map(move |tf| Self::func(tf, bone_count)) + } +} +impl<'a> DoubleEndedIterator for FramePoseIterMut<'a> { + fn next_back(&mut self) -> Option { + let bone_count = self.bone_count; + self.iter.next_back().map(move |tf| Self::func(tf, bone_count)) + } + + fn nth_back(&mut self, n: usize) -> Option { + let bone_count = self.bone_count; + self.iter.nth_back(n).map(move |tf| Self::func(tf, bone_count)) + } +} +impl<'a> ExactSizeIterator for FramePoseIterMut<'a> { + #[inline] + fn len(&self) -> usize { + self.iter.len() + } +} + impl RaylibModelAnimation for ModelAnimation {} impl RaylibModelAnimation for WeakModelAnimation {} @@ -577,6 +704,10 @@ pub trait RaylibModelAnimation: AsRef + AsMut(&'a self) -> FramePoseIter<'a> { + let anim = self.as_ref(); + unsafe { FramePoseIter::new(anim.framePoses, anim.frameCount as usize, anim.boneCount as usize) } + } fn frame_poses_mut(&mut self) -> Vec<&mut [crate::math::Transform]> { let anim = self.as_ref(); @@ -593,6 +724,10 @@ pub trait RaylibModelAnimation: AsRef + AsMut(&'a mut self) -> FramePoseIterMut<'a> { + let anim = self.as_ref(); + unsafe { FramePoseIterMut::new(anim.framePoses, anim.frameCount as usize, anim.boneCount as usize) } + } } impl MaterialMap { From 7ed5adbb72f4532a234414c88decbaf569a875b0 Mon Sep 17 00:00:00 2001 From: Amy Wilder <74995093+AmityWilder@users.noreply.github.com> Date: Fri, 11 Apr 2025 20:17:56 -0400 Subject: [PATCH 91/93] Fix inconsistencies in documentation/attributes/function inclusion (#177) * Apply documentation to audio methods * Make getter methods const * Apply documentation to automation methods * Apply documentation to `camera.rs` * Apply documentation to `color.rs` * Add color palette impls * Fix documentation comment * Apply documentation to `drawing.rs * Fix inconsistent name pattern * Fix documentation and inline inconsistencies in `file.rs` * Add missing inlines in `input.rs` * Improve consistency within `math.rs` * Add missing documentation to `models.rs` * Improve API consistency in `shaders.rs` * Add missing documentation to `text.rs` * Add optional attributes to `make_thin_wrapper!` * Add documentation to `texture.rs` * Add missing docs to `vr.rs` * Add missing documentation to `window.rs` * Confirm all public functions from Raylib API are documented * Add documentation comments to thin wrappers in `audio.rs` --- raylib/src/core/audio.rs | 86 +++++++++++--- raylib/src/core/automation.rs | 19 ++++ raylib/src/core/camera.rs | 20 +++- raylib/src/core/color.rs | 207 +++++++++++++++++++++++++++++++++- raylib/src/core/data.rs | 2 +- raylib/src/core/drawing.rs | 55 +++++++-- raylib/src/core/file.rs | 7 ++ raylib/src/core/input.rs | 2 + raylib/src/core/macros.rs | 19 ++-- raylib/src/core/math.rs | 170 +++++++++++++++++++++------- raylib/src/core/models.rs | 116 ++++++++++++++++++- raylib/src/core/shaders.rs | 16 ++- raylib/src/core/text.rs | 32 +++++- raylib/src/core/texture.rs | 77 ++++++++++++- raylib/src/core/vr.rs | 35 ++++-- raylib/src/core/window.rs | 106 +++++++++++------ 16 files changed, 825 insertions(+), 144 deletions(-) diff --git a/raylib/src/core/audio.rs b/raylib/src/core/audio.rs index f99bbe9e..8fc00186 100644 --- a/raylib/src/core/audio.rs +++ b/raylib/src/core/audio.rs @@ -6,11 +6,31 @@ use std::ffi::CString; use std::marker::PhantomData; use std::path::Path; -make_thin_wrapper_lifetime!(Wave, ffi::Wave, RaylibAudio, ffi::UnloadWave); +make_thin_wrapper_lifetime!( + /// Wave, audio wave data + Wave, + ffi::Wave, + RaylibAudio, + ffi::UnloadWave +); -make_thin_wrapper_lifetime!(Sound, ffi::Sound, RaylibAudio, (ffi::UnloadSound), true); -make_thin_wrapper_lifetime!(Music, ffi::Music, RaylibAudio, ffi::UnloadMusicStream); make_thin_wrapper_lifetime!( + /// Sound + Sound, + ffi::Sound, + RaylibAudio, + (ffi::UnloadSound), + true +); +make_thin_wrapper_lifetime!( + /// Music, audio stream, anything longer than ~10 seconds should be streamed + Music, + ffi::Music, + RaylibAudio, + ffi::UnloadMusicStream +); +make_thin_wrapper_lifetime!( + /// AudioStream, custom audio stream AudioStream, ffi::AudioStream, RaylibAudio, @@ -87,14 +107,14 @@ impl RaylibAudio { pub fn set_master_volume(&self, volume: f32) { unsafe { ffi::SetMasterVolume(volume) } } - + /// Sets default audio buffer size for new audio streams. #[inline] pub fn set_audio_stream_buffer_size_default(&self, size: i32) { unsafe { ffi::SetAudioStreamBufferSizeDefault(size); } - } + } /// Loads a new sound from file. #[inline] @@ -199,16 +219,24 @@ impl<'aud> Drop for RaylibAudio { } impl<'aud> Wave<'aud> { - pub fn frame_count(&self) -> u32 { + /// Total number of frames (considering channels) + #[inline] + pub const fn frame_count(&self) -> u32 { self.0.frameCount } - pub fn sample_rate(&self) -> u32 { + /// Frequency (samples per second) + #[inline] + pub const fn sample_rate(&self) -> u32 { self.0.sampleRate } - pub fn sample_size(&self) -> u32 { + /// Bit depth (bits per sample): 8, 16, 32 (24 not supported) + #[inline] + pub const fn sample_size(&self) -> u32 { self.0.sampleSize } - pub fn channels(&self) -> u32 { + /// Number of channels (1-mono, 2-stereo, ...) + #[inline] + pub const fn channels(&self) -> u32 { self.0.channels } pub unsafe fn inner(self) -> ffi::Wave { @@ -217,6 +245,7 @@ impl<'aud> Wave<'aud> { inner } + /// Checks if wave data is valid (data loaded and parameters) #[inline] pub fn is_wave_valid(&self) -> bool { unsafe { ffi::IsWaveValid(self.0) } @@ -229,8 +258,8 @@ impl<'aud> Wave<'aud> { unsafe { ffi::ExportWave(self.0, c_filename.as_ptr()) } } - /// Export wave sample data to code (.h) - /*#[inline] + /*/// Export wave sample data to code (.h) + #[inline] pub fn export_wave_as_code(&self, filename: &str) -> bool { let c_filename = CString::new(filename).unwrap(); unsafe { ffi::ExportWaveAsCode(self.0, c_filename.as_ptr()) } @@ -279,11 +308,15 @@ impl<'aud> AsMut for Sound<'aud> { } impl<'aud> Sound<'aud> { + /// Checks if a sound is valid (data loaded and buffers initialized) + #[inline] pub fn is_sound_valid(&self) -> bool { unsafe { ffi::IsSoundValid(self.0) } } - pub fn frame_count(&self) -> u32 { + /// Total number of frames (considering channels) + #[inline] + pub const fn frame_count(&self) -> u32 { self.0.frameCount } pub unsafe fn inner(self) -> ffi::Sound { @@ -334,6 +367,7 @@ impl<'aud> Sound<'aud> { unsafe { ffi::SetSoundPitch(self.0, pitch) } } + /// Set pan for a sound (0.5 is center) #[inline] pub fn set_pan(&self, pan: f32) { unsafe { ffi::SetSoundPan(self.0, pan) } @@ -354,11 +388,15 @@ impl<'aud> Sound<'aud> { } impl<'aud, 'bind> SoundAlias<'aud, 'bind> { + /// Checks if a sound is valid (data loaded and buffers initialized) + #[inline] pub fn is_sound_valid(&self) -> bool { unsafe { ffi::IsSoundValid(self.0) } } - pub fn frame_count(&self) -> u32 { + /// Total number of frames (considering channels) + #[inline] + pub const fn frame_count(&self) -> u32 { self.0.frameCount } pub unsafe fn inner(self) -> ffi::Sound { @@ -409,6 +447,7 @@ impl<'aud, 'bind> SoundAlias<'aud, 'bind> { unsafe { ffi::SetSoundPitch(self.0, pitch) } } + /// Set pan for a sound (0.5 is center) #[inline] pub fn set_pan(&self, pan: f32) { unsafe { ffi::SetSoundPan(self.0, pan) } @@ -482,16 +521,19 @@ impl<'aud> Music<'aud> { unsafe { ffi::GetMusicTimePlayed(self.0) } } + /// Seek music to a position (in seconds) #[inline] pub fn seek_stream(&self, position: f32) { unsafe { ffi::SeekMusicStream(self.0, position) } } + /// Set pan for a music (0.5 is center) #[inline] pub fn set_pan(&self, pan: f32) { unsafe { ffi::SetMusicPan(self.0, pan) } } + /// Checks if a music stream is valid (context and buffers initialized) #[inline] pub fn is_music_valid(&self) -> bool { unsafe { ffi::IsMusicValid(self.0) } @@ -499,16 +541,24 @@ impl<'aud> Music<'aud> { } impl<'aud> AudioStream<'aud> { + /// Checks if an audio stream is valid (buffers initialized) + #[inline] pub fn is_audio_stream_valid(&self) -> bool { unsafe { ffi::IsAudioStreamValid(self.0) } } - pub fn sample_rate(&self) -> u32 { + /// Frequency (samples per second) + #[inline] + pub const fn sample_rate(&self) -> u32 { self.0.sampleRate } - pub fn sample_size(&self) -> u32 { + /// Bit depth (bits per sample): 8, 16, 32 (24 not supported) + #[inline] + pub const fn sample_size(&self) -> u32 { self.0.sampleSize } - pub fn channels(&self) -> u32 { + /// Number of channels (1-mono, 2-stereo, ...) + #[inline] + pub const fn channels(&self) -> u32 { self.0.channels } @@ -590,6 +640,8 @@ impl<'aud> AudioStream<'aud> { unsafe { ffi::IsAudioStreamProcessed(self.0) } } + /// Set pan for audio stream (0.5 is centered) + #[inline] pub fn set_pan(&self, pan: f32) { unsafe { ffi::SetAudioStreamPan(self.0, pan); @@ -598,6 +650,8 @@ impl<'aud> AudioStream<'aud> { } impl<'bind> Sound<'_> { + /// Clone sound from existing sound data, clone does not own wave data + // NOTE: Wave data must be unallocated manually and will be shared across all clones pub fn alias<'snd>(&'snd self) -> Result, Error> { let s = unsafe { ffi::LoadSoundAlias(self.0) }; if s.stream.buffer.is_null() { diff --git a/raylib/src/core/automation.rs b/raylib/src/core/automation.rs index b9cc4a5c..8b0377c8 100644 --- a/raylib/src/core/automation.rs +++ b/raylib/src/core/automation.rs @@ -73,10 +73,12 @@ make_thin_wrapper!( impl AutomationEventList { /// Length of the automation event list + #[inline] pub const fn count(&self) -> u32 { self.0.count } /// The amount of automation events that can be held in this list. + #[inline] pub const fn capacity(&self) -> u32 { self.0.capacity } @@ -108,18 +110,26 @@ make_thin_wrapper!( ); impl AutomationEvent { + /// Event frame + #[inline] pub const fn frame(&self) -> u32 { self.0.frame } + /// Event type (AutomationEventType) + #[inline] pub const fn get_type(&self) -> u32 { self.0.type_ } + /// Event parameters (if required) + #[inline] pub const fn params(&self) -> [i32; 4] { self.0.params } } impl AutomationEvent { + /// Play a recorded automation event + #[inline] pub fn play(&self) { unsafe { ffi::PlayAutomationEvent(self.0) } } @@ -130,6 +140,7 @@ fn unload_automation_event(_s: ffi::AutomationEvent) { } impl RaylibHandle { + /// Load automation events list from file, NULL for empty list, capacity = MAX_AUTOMATION_EVENTS pub fn load_automation_event_list(&self, file_name: Option) -> AutomationEventList { match file_name { Some(a) => { @@ -139,17 +150,25 @@ impl RaylibHandle { None => AutomationEventList(unsafe { ffi::LoadAutomationEventList(null()) }), } } + /// Set automation event list to record to + #[inline] pub fn set_automation_event_list(&self, l: &mut AutomationEventList) { unsafe { ffi::SetAutomationEventList(&mut l.0 as *mut ffi::AutomationEventList); } } + /// Set automation event internal base frame to start recording + #[inline] pub fn set_automation_event_base_frame(&self, b: i32) { unsafe { ffi::SetAutomationEventBaseFrame(b) }; } + /// Start recording automation events (AutomationEventList must be set) + #[inline] pub fn start_automation_event_recording(&self) { unsafe { ffi::StartAutomationEventRecording() }; } + /// Stop recording automation events + #[inline] pub fn stop_automation_event_recording(&self) { unsafe { ffi::StopAutomationEventRecording() }; } diff --git a/raylib/src/core/camera.rs b/raylib/src/core/camera.rs index 23528b21..d3e2d576 100644 --- a/raylib/src/core/camera.rs +++ b/raylib/src/core/camera.rs @@ -5,15 +5,22 @@ use crate::core::math::{Vector2, Vector3}; use crate::core::RaylibHandle; use crate::ffi; +/// Camera, defines position/orientation in 3d space #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Camera3D { + /// Camera position pub position: Vector3, + /// Camera target it looks-at pub target: Vector3, + /// Camera up vector (rotation over its axis) pub up: Vector3, + /// Camera field-of-view aperture in Y (degrees) in perspective, used as near plane width in orthographic pub fovy: f32, + /// Camera projection: CAMERA_PERSPECTIVE or CAMERA_ORTHOGRAPHIC projection_: ffi::CameraProjection, } +/// Camera type fallback, defaults to Camera3D pub type Camera = Camera3D; impl From for Camera3D { @@ -40,12 +47,17 @@ impl Into for &Camera3D { } } +/// Camera2D, defines position/orientation in 2d space #[repr(C)] #[derive(Debug, Copy, Clone, Default)] pub struct Camera2D { + /// Camera offset (displacement from target) pub offset: Vector2, + /// Camera target (rotation and zoom origin) pub target: Vector2, + /// Camera rotation in degrees pub rotation: f32, + /// Camera zoom (scaling), should be 1.0 by default pub zoom: f32, } @@ -73,8 +85,9 @@ impl Into for &Camera2D { } impl Camera3D { - pub fn camera_type(&self) -> crate::consts::CameraProjection { - unsafe { std::mem::transmute(self.projection_.clone()) } + /// Camera projection: CAMERA_PERSPECTIVE or CAMERA_ORTHOGRAPHIC + pub const fn camera_type(&self) -> crate::consts::CameraProjection { + unsafe { std::mem::transmute_copy(&self.projection_) } } /// Create a perspective camera. /// fovy is in degrees @@ -106,7 +119,8 @@ impl RaylibHandle { *camera = fficam.into(); } } - + + /// Update camera movement/rotation pub fn update_camera_pro(&self, camera: &mut Camera3D, movement: Vector3, rotation: Vector3, zoom: f32) { unsafe { let mut fficam: ffi::Camera3D = (*camera).into(); diff --git a/raylib/src/core/color.rs b/raylib/src/core/color.rs index e6c5b774..afa0d2fd 100644 --- a/raylib/src/core/color.rs +++ b/raylib/src/core/color.rs @@ -10,18 +10,24 @@ use serde::{Deserialize, Serialize}; use super::RaylibHandle; +/// Color, 4 components, R8G8B8A8 (32bit) #[repr(C)] #[derive(Debug, Copy, Clone, Default)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct Color { + /// Color red value pub r: u8, + /// Color green value pub g: u8, + /// Color blue value pub b: u8, + /// Color alpha value pub a: u8, } -// A convenience function for making a new `Color`. -pub fn rcolor(r: u8, g: u8, b: u8, a: u8) -> Color { +/// A convenience function for making a new `Color`. +#[inline] +pub const fn rcolor(r: u8, g: u8, b: u8, a: u8) -> Color { Color::new(r, g, b, a) } @@ -74,7 +80,7 @@ impl Color { /// use raylib::prelude::*; /// let color_white = Color::from_hex("FFFFFF").unwrap(); /// let color_black = Color::from_hex("000000").unwrap(); - /// + /// /// assert_eq!(color_black, Color::BLACK); /// assert_eq!(color_white, Color::WHITE); /// ``` @@ -124,7 +130,7 @@ impl Color { /// Returns color from normalized values [0..1] /// ```rust /// use raylib::prelude::*; - /// fn main() { + /// fn main() { /// assert_eq!(Color::color_from_normalized(Vector4::new(1.0, 1.0, 1.0, 1.0)), Color::new(255, 255, 255, 255)); /// } /// ``` @@ -140,18 +146,22 @@ impl Color { } /// Get color multiplied with another color + #[inline] pub fn tint(&self, color: Self) -> Self { unsafe { ffi::ColorTint(self.into(), color.into()).into() } } /// Get color with brightness correction, brightness factor goes from -1.0f to 1.0f + #[inline] pub fn brightness(&self, factor: f32) -> Self { unsafe { ffi::ColorBrightness(self.into(), factor).into() } } /// Get color with contrast correction, contrast values between -1.0f and 1.0f + #[inline] pub fn contrast(&self, factor: f32) -> Self { unsafe { ffi::ColorContrast(self.into(), factor).into() } } /// Get color with alpha applied, alpha goes from 0.0f to 1.0f + #[inline] pub fn alpha(&self, alpha: f32) -> Self { unsafe { ffi::ColorAlpha(self.into(), alpha).into() } } @@ -168,11 +178,13 @@ impl Color { unsafe { ffi::ColorAlphaBlend(dst.into(), src.into(), tint.into()).into() } } /// Check if color is equal to another. + #[inline] pub fn is_equal(&self, rhs: impl Into) -> bool { unsafe { ffi::ColorIsEqual(self.into(), rhs.into()) } } /// Get color lerp interpolation between two colors, factor [0.0f..1.0f] + #[inline] pub fn lerp(&self, rhs: Color, factor: f32) -> Color { unsafe { ffi::ColorLerp(self.into(), rhs.into(), factor).into() } } @@ -187,6 +199,193 @@ impl PartialEq for Color { } impl Eq for Color {} +/// Some Basic Colors +/// NOTE: Custom raylib color palette for amazing visuals on WHITE background +pub trait RaylibPalette { + /** Light Gray */ const LIGHTGRAY: Color = Color::new(200, 200, 200, 255); + /** Gray */ const GRAY: Color = Color::new(130, 130, 130, 255); + /** Dark Gray */ const DARKGRAY: Color = Color::new( 80, 80, 80, 255); + /** Yellow */ const YELLOW: Color = Color::new(253, 249, 0, 255); + /** Gold */ const GOLD: Color = Color::new(255, 203, 0, 255); + /** Orange */ const ORANGE: Color = Color::new(255, 161, 0, 255); + /** Pink */ const PINK: Color = Color::new(255, 109, 194, 255); + /** Red */ const RED: Color = Color::new(230, 41, 55, 255); + /** Maroon */ const MAROON: Color = Color::new(190, 33, 55, 255); + /** Green */ const GREEN: Color = Color::new( 0, 228, 48, 255); + /** Lime */ const LIME: Color = Color::new( 0, 158, 47, 255); + /** Dark Green */ const DARKGREEN: Color = Color::new( 0, 117, 44, 255); + /** Sky Blue */ const SKYBLUE: Color = Color::new(102, 191, 255, 255); + /** Blue */ const BLUE: Color = Color::new( 0, 121, 241, 255); + /** Dark Blue */ const DARKBLUE: Color = Color::new( 0, 82, 172, 255); + /** Purple */ const PURPLE: Color = Color::new(200, 122, 255, 255); + /** Violet */ const VIOLET: Color = Color::new(135, 60, 190, 255); + /** Dark Purple */ const DARKPURPLE: Color = Color::new(112, 31, 126, 255); + /** Beige */ const BEIGE: Color = Color::new(211, 176, 131, 255); + /** Brown */ const BROWN: Color = Color::new(127, 106, 79, 255); + /** Dark Brown */ const DARKBROWN: Color = Color::new( 76, 63, 47, 255); + + /** White */ const WHITE: Color = Color::new(255, 255, 255, 255); + /** Black */ const BLACK: Color = Color::new( 0, 0, 0, 255); + /** Blank (Transparent) */ const BLANK: Color = Color::new( 0, 0, 0, 0); + /** Magenta */ const MAGENTA: Color = Color::new(255, 0, 255, 255); + /** My own White (raylib logo) */ const RAYWHITE: Color = Color::new(245, 245, 245, 255); +} +impl RaylibPalette for Color {} + +/// CSS Color constants +pub trait CSSPalette { + /** #f0f8ffff */ const ALICEBLUE: Color = Color::new(0xf0, 0xf8, 0xff, 0xff); + /** #faebd7ff */ const ANTIQUEWHITE: Color = Color::new(0xfa, 0xeb, 0xd7, 0xff); + /** #00ffffff */ const AQUA: Color = Color::new(0x00, 0xff, 0xff, 0xff); + /** #7fffd4ff */ const AQUAMARINE: Color = Color::new(0x7f, 0xff, 0xd4, 0xff); + /** #f0ffffff */ const AZURE: Color = Color::new(0xf0, 0xff, 0xff, 0xff); + /** #f5f5dcff */ const BEIGE: Color = Color::new(0xf5, 0xf5, 0xdc, 0xff); + /** #ffe4c4ff */ const BISQUE: Color = Color::new(0xff, 0xe4, 0xc4, 0xff); + /** #000000ff */ const BLACK: Color = Color::new(0x00, 0x00, 0x00, 0xff); + /** #ffebcdff */ const BLANCHEDALMOND: Color = Color::new(0xff, 0xeb, 0xcd, 0xff); + /** #0000ffff */ const BLUE: Color = Color::new(0x00, 0x00, 0xff, 0xff); + /** #8a2be2ff */ const BLUEVIOLET: Color = Color::new(0x8a, 0x2b, 0xe2, 0xff); + /** #a52a2aff */ const BROWN: Color = Color::new(0xa5, 0x2a, 0x2a, 0xff); + /** #deb887ff */ const BURLYWOOD: Color = Color::new(0xde, 0xb8, 0x87, 0xff); + /** #5f9ea0ff */ const CADETBLUE: Color = Color::new(0x5f, 0x9e, 0xa0, 0xff); + /** #7fff00ff */ const CHARTREUSE: Color = Color::new(0x7f, 0xff, 0x00, 0xff); + /** #d2691eff */ const CHOCOLATE: Color = Color::new(0xd2, 0x69, 0x1e, 0xff); + /** #ff7f50ff */ const CORAL: Color = Color::new(0xff, 0x7f, 0x50, 0xff); + /** #6495edff */ const CORNFLOWERBLUE: Color = Color::new(0x64, 0x95, 0xed, 0xff); + /** #fff8dcff */ const CORNSILK: Color = Color::new(0xff, 0xf8, 0xdc, 0xff); + /** #dc143cff */ const CRIMSON: Color = Color::new(0xdc, 0x14, 0x3c, 0xff); + /** #00ffffff */ const CYAN: Color = Self::AQUA; + /** #00008bff */ const DARKBLUE: Color = Color::new(0x00, 0x00, 0x8b, 0xff); + /** #008b8bff */ const DARKCYAN: Color = Color::new(0x00, 0x8b, 0x8b, 0xff); + /** #b8860bff */ const DARKGOLDENROD: Color = Color::new(0xb8, 0x86, 0x0b, 0xff); + /** #a9a9a9ff */ const DARKGRAY: Color = Color::new(0xa9, 0xa9, 0xa9, 0xff); + /** #006400ff */ const DARKGREEN: Color = Color::new(0x00, 0x64, 0x00, 0xff); + /** #a9a9a9ff */ const DARKGREY: Color = Color::new(0xa9, 0xa9, 0xa9, 0xff); + /** #bdb76bff */ const DARKKHAKI: Color = Color::new(0xbd, 0xb7, 0x6b, 0xff); + /** #8b008bff */ const DARKMAGENTA: Color = Color::new(0x8b, 0x00, 0x8b, 0xff); + /** #556b2fff */ const DARKOLIVEGREEN: Color = Color::new(0x55, 0x6b, 0x2f, 0xff); + /** #ff8c00ff */ const DARKORANGE: Color = Color::new(0xff, 0x8c, 0x00, 0xff); + /** #9932ccff */ const DARKORCHID: Color = Color::new(0x99, 0x32, 0xcc, 0xff); + /** #8b0000ff */ const DARKRED: Color = Color::new(0x8b, 0x00, 0x00, 0xff); + /** #e9967aff */ const DARKSALMON: Color = Color::new(0xe9, 0x96, 0x7a, 0xff); + /** #8fbc8fff */ const DARKSEAGREEN: Color = Color::new(0x8f, 0xbc, 0x8f, 0xff); + /** #483d8bff */ const DARKSLATEBLUE: Color = Color::new(0x48, 0x3d, 0x8b, 0xff); + /** #2f4f4fff */ const DARKSLATEGRAY: Color = Color::new(0x2f, 0x4f, 0x4f, 0xff); + /** #2f4f4fff */ const DARKSLATEGREY: Color = Color::new(0x2f, 0x4f, 0x4f, 0xff); + /** #00ced1ff */ const DARKTURQUOISE: Color = Color::new(0x00, 0xce, 0xd1, 0xff); + /** #9400d3ff */ const DARKVIOLET: Color = Color::new(0x94, 0x00, 0xd3, 0xff); + /** #ff1493ff */ const DEEPPINK: Color = Color::new(0xff, 0x14, 0x93, 0xff); + /** #00bfffff */ const DEEPSKYBLUE: Color = Color::new(0x00, 0xbf, 0xff, 0xff); + /** #696969ff */ const DIMGRAY: Color = Color::new(0x69, 0x69, 0x69, 0xff); + /** #696969ff */ const DIMGREY: Color = Color::new(0x69, 0x69, 0x69, 0xff); + /** #1e90ffff */ const DODGERBLUE: Color = Color::new(0x1e, 0x90, 0xff, 0xff); + /** #b22222ff */ const FIREBRICK: Color = Color::new(0xb2, 0x22, 0x22, 0xff); + /** #fffaf0ff */ const FLORALWHITE: Color = Color::new(0xff, 0xfa, 0xf0, 0xff); + /** #228b22ff */ const FORESTGREEN: Color = Color::new(0x22, 0x8b, 0x22, 0xff); + /** #ff00ffff */ const FUCHSIA: Color = Color::new(0xff, 0x00, 0xff, 0xff); + /** #dcdcdcff */ const GAINSBORO: Color = Color::new(0xdc, 0xdc, 0xdc, 0xff); + /** #f8f8ffff */ const GHOSTWHITE: Color = Color::new(0xf8, 0xf8, 0xff, 0xff); + /** #ffd700ff */ const GOLD: Color = Color::new(0xff, 0xd7, 0x00, 0xff); + /** #daa520ff */ const GOLDENROD: Color = Color::new(0xda, 0xa5, 0x20, 0xff); + /** #808080ff */ const GRAY: Color = Color::new(0x80, 0x80, 0x80, 0xff); + /** #008000ff */ const GREEN: Color = Color::new(0x00, 0x80, 0x00, 0xff); + /** #adff2fff */ const GREENYELLOW: Color = Color::new(0xad, 0xff, 0x2f, 0xff); + /** #808080ff */ const GREY: Color = Self::GRAY; + /** #f0fff0ff */ const HONEYDEW: Color = Color::new(0xf0, 0xff, 0xf0, 0xff); + /** #ff69b4ff */ const HOTPINK: Color = Color::new(0xff, 0x69, 0xb4, 0xff); + /** #cd5c5cff */ const INDIANRED: Color = Color::new(0xcd, 0x5c, 0x5c, 0xff); + /** #4b0082ff */ const INDIGO: Color = Color::new(0x4b, 0x00, 0x82, 0xff); + /** #fffff0ff */ const IVORY: Color = Color::new(0xff, 0xff, 0xf0, 0xff); + /** #f0e68cff */ const KHAKI: Color = Color::new(0xf0, 0xe6, 0x8c, 0xff); + /** #e6e6faff */ const LAVENDER: Color = Color::new(0xe6, 0xe6, 0xfa, 0xff); + /** #fff0f5ff */ const LAVENDERBLUSH: Color = Color::new(0xff, 0xf0, 0xf5, 0xff); + /** #7cfc00ff */ const LAWNGREEN: Color = Color::new(0x7c, 0xfc, 0x00, 0xff); + /** #fffacdff */ const LEMONCHIFFON: Color = Color::new(0xff, 0xfa, 0xcd, 0xff); + /** #add8e6ff */ const LIGHTBLUE: Color = Color::new(0xad, 0xd8, 0xe6, 0xff); + /** #f08080ff */ const LIGHTCORAL: Color = Color::new(0xf0, 0x80, 0x80, 0xff); + /** #e0ffffff */ const LIGHTCYAN: Color = Color::new(0xe0, 0xff, 0xff, 0xff); + /** #fafad2ff */ const LIGHTGOLDENRODYELLOW: Color = Color::new(0xfa, 0xfa, 0xd2, 0xff); + /** #d3d3d3ff */ const LIGHTGRAY: Color = Color::new(0xd3, 0xd3, 0xd3, 0xff); + /** #90ee90ff */ const LIGHTGREEN: Color = Color::new(0x90, 0xee, 0x90, 0xff); + /** #d3d3d3ff */ const LIGHTGREY: Color = Color::new(0xd3, 0xd3, 0xd3, 0xff); + /** #ffb6c1ff */ const LIGHTPINK: Color = Color::new(0xff, 0xb6, 0xc1, 0xff); + /** #ffa07aff */ const LIGHTSALMON: Color = Color::new(0xff, 0xa0, 0x7a, 0xff); + /** #20b2aaff */ const LIGHTSEAGREEN: Color = Color::new(0x20, 0xb2, 0xaa, 0xff); + /** #87cefaff */ const LIGHTSKYBLUE: Color = Color::new(0x87, 0xce, 0xfa, 0xff); + /** #778899ff */ const LIGHTSLATEGRAY: Color = Color::new(0x77, 0x88, 0x99, 0xff); + /** #778899ff */ const LIGHTSLATEGREY: Color = Color::new(0x77, 0x88, 0x99, 0xff); + /** #b0c4deff */ const LIGHTSTEELBLUE: Color = Color::new(0xb0, 0xc4, 0xde, 0xff); + /** #ffffe0ff */ const LIGHTYELLOW: Color = Color::new(0xff, 0xff, 0xe0, 0xff); + /** #00ff00ff */ const LIME: Color = Color::new(0x00, 0xff, 0x00, 0xff); + /** #32cd32ff */ const LIMEGREEN: Color = Color::new(0x32, 0xcd, 0x32, 0xff); + /** #faf0e6ff */ const LINEN: Color = Color::new(0xfa, 0xf0, 0xe6, 0xff); + /** #ff00ffff */ const MAGENTA: Color = Self::FUCHSIA; + /** #800000ff */ const MAROON: Color = Color::new(0x80, 0x00, 0x00, 0xff); + /** #66cdaaff */ const MEDIUMAQUAMARINE: Color = Color::new(0x66, 0xcd, 0xaa, 0xff); + /** #0000cdff */ const MEDIUMBLUE: Color = Color::new(0x00, 0x00, 0xcd, 0xff); + /** #ba55d3ff */ const MEDIUMORCHID: Color = Color::new(0xba, 0x55, 0xd3, 0xff); + /** #9370dbff */ const MEDIUMPURPLE: Color = Color::new(0x93, 0x70, 0xdb, 0xff); + /** #3cb371ff */ const MEDIUMSEAGREEN: Color = Color::new(0x3c, 0xb3, 0x71, 0xff); + /** #7b68eeff */ const MEDIUMSLATEBLUE: Color = Color::new(0x7b, 0x68, 0xee, 0xff); + /** #00fa9aff */ const MEDIUMSPRINGGREEN: Color = Color::new(0x00, 0xfa, 0x9a, 0xff); + /** #48d1ccff */ const MEDIUMTURQUOISE: Color = Color::new(0x48, 0xd1, 0xcc, 0xff); + /** #c71585ff */ const MEDIUMVIOLETRED: Color = Color::new(0xc7, 0x15, 0x85, 0xff); + /** #191970ff */ const MIDNIGHTBLUE: Color = Color::new(0x19, 0x19, 0x70, 0xff); + /** #f5fffaff */ const MINTCREAM: Color = Color::new(0xf5, 0xff, 0xfa, 0xff); + /** #ffe4e1ff */ const MISTYROSE: Color = Color::new(0xff, 0xe4, 0xe1, 0xff); + /** #ffe4b5ff */ const MOCCASIN: Color = Color::new(0xff, 0xe4, 0xb5, 0xff); + /** #ffdeadff */ const NAVAJOWHITE: Color = Color::new(0xff, 0xde, 0xad, 0xff); + /** #000080ff */ const NAVY: Color = Color::new(0x00, 0x00, 0x80, 0xff); + /** #fdf5e6ff */ const OLDLACE: Color = Color::new(0xfd, 0xf5, 0xe6, 0xff); + /** #808000ff */ const OLIVE: Color = Color::new(0x80, 0x80, 0x00, 0xff); + /** #6b8e23ff */ const OLIVEDRAB: Color = Color::new(0x6b, 0x8e, 0x23, 0xff); + /** #ffa500ff */ const ORANGE: Color = Color::new(0xff, 0xa5, 0x00, 0xff); + /** #ff4500ff */ const ORANGERED: Color = Color::new(0xff, 0x45, 0x00, 0xff); + /** #da70d6ff */ const ORCHID: Color = Color::new(0xda, 0x70, 0xd6, 0xff); + /** #eee8aaff */ const PALEGOLDENROD: Color = Color::new(0xee, 0xe8, 0xaa, 0xff); + /** #98fb98ff */ const PALEGREEN: Color = Color::new(0x98, 0xfb, 0x98, 0xff); + /** #afeeeeff */ const PALETURQUOISE: Color = Color::new(0xaf, 0xee, 0xee, 0xff); + /** #db7093ff */ const PALEVIOLETRED: Color = Color::new(0xdb, 0x70, 0x93, 0xff); + /** #ffefd5ff */ const PAPAYAWHIP: Color = Color::new(0xff, 0xef, 0xd5, 0xff); + /** #ffdab9ff */ const PEACHPUFF: Color = Color::new(0xff, 0xda, 0xb9, 0xff); + /** #cd853fff */ const PERU: Color = Color::new(0xcd, 0x85, 0x3f, 0xff); + /** #ffc0cbff */ const PINK: Color = Color::new(0xff, 0xc0, 0xcb, 0xff); + /** #dda0ddff */ const PLUM: Color = Color::new(0xdd, 0xa0, 0xdd, 0xff); + /** #b0e0e6ff */ const POWDERBLUE: Color = Color::new(0xb0, 0xe0, 0xe6, 0xff); + /** #800080ff */ const PURPLE: Color = Color::new(0x80, 0x00, 0x80, 0xff); + /** #663399ff */ const REBECCAPURPLE: Color = Color::new(0x66, 0x33, 0x99, 0xff); + /** #ff0000ff */ const RED: Color = Color::new(0xff, 0x00, 0x00, 0xff); + /** #bc8f8fff */ const ROSYBROWN: Color = Color::new(0xbc, 0x8f, 0x8f, 0xff); + /** #4169e1ff */ const ROYALBLUE: Color = Color::new(0x41, 0x69, 0xe1, 0xff); + /** #8b4513ff */ const SADDLEBROWN: Color = Color::new(0x8b, 0x45, 0x13, 0xff); + /** #fa8072ff */ const SALMON: Color = Color::new(0xfa, 0x80, 0x72, 0xff); + /** #f4a460ff */ const SANDYBROWN: Color = Color::new(0xf4, 0xa4, 0x60, 0xff); + /** #2e8b57ff */ const SEAGREEN: Color = Color::new(0x2e, 0x8b, 0x57, 0xff); + /** #fff5eeff */ const SEASHELL: Color = Color::new(0xff, 0xf5, 0xee, 0xff); + /** #a0522dff */ const SIENNA: Color = Color::new(0xa0, 0x52, 0x2d, 0xff); + /** #c0c0c0ff */ const SILVER: Color = Color::new(0xc0, 0xc0, 0xc0, 0xff); + /** #87ceebff */ const SKYBLUE: Color = Color::new(0x87, 0xce, 0xeb, 0xff); + /** #6a5acdff */ const SLATEBLUE: Color = Color::new(0x6a, 0x5a, 0xcd, 0xff); + /** #708090ff */ const SLATEGRAY: Color = Color::new(0x70, 0x80, 0x90, 0xff); + /** #708090ff */ const SLATEGREY: Color = Color::new(0x70, 0x80, 0x90, 0xff); + /** #fffafaff */ const SNOW: Color = Color::new(0xff, 0xfa, 0xfa, 0xff); + /** #00ff7fff */ const SPRINGGREEN: Color = Color::new(0x00, 0xff, 0x7f, 0xff); + /** #4682b4ff */ const STEELBLUE: Color = Color::new(0x46, 0x82, 0xb4, 0xff); + /** #d2b48cff */ const TAN: Color = Color::new(0xd2, 0xb4, 0x8c, 0xff); + /** #008080ff */ const TEAL: Color = Color::new(0x00, 0x80, 0x80, 0xff); + /** #d8bfd8ff */ const THISTLE: Color = Color::new(0xd8, 0xbf, 0xd8, 0xff); + /** #00000000 */ const TRANSPARENT: Color = Color::new(0x00, 0x00, 0x00, 0x00); + /** #ff6347ff */ const TOMATO: Color = Color::new(0xff, 0x63, 0x47, 0xff); + /** #40e0d0ff */ const TURQUOISE: Color = Color::new(0x40, 0xe0, 0xd0, 0xff); + /** #ee82eeff */ const VIOLET: Color = Color::new(0xee, 0x82, 0xee, 0xff); + /** #f5deb3ff */ const WHEAT: Color = Color::new(0xf5, 0xde, 0xb3, 0xff); + /** #ffffffff */ const WHITE: Color = Color::new(0xff, 0xff, 0xff, 0xff); + /** #f5f5f5ff */ const WHITESMOKE: Color = Color::new(0xf5, 0xf5, 0xf5, 0xff); + /** #ffff00ff */ const YELLOW: Color = Color::new(0xff, 0xff, 0x00, 0xff); + /** #9acd32ff */ const YELLOWGREEN: Color = Color::new(0x9a, 0xcd, 0x32, 0xff); +} +impl CSSPalette for Color {} + /// Color constants impl Color { pub const INDIANRED: Color = Color::new(205, 92, 92, 255); diff --git a/raylib/src/core/data.rs b/raylib/src/core/data.rs index 18c68c7c..720ee119 100644 --- a/raylib/src/core/data.rs +++ b/raylib/src/core/data.rs @@ -249,7 +249,7 @@ pub fn encode_data_base64(data: &[u8]) -> Vec { } } -// Decode Base64 data +/// Decode Base64 data pub fn decode_data_base64(data: &[u8]) -> Vec { let mut output_size = 0; diff --git a/raylib/src/core/drawing.rs b/raylib/src/core/drawing.rs index d0b377c4..12dd187f 100644 --- a/raylib/src/core/drawing.rs +++ b/raylib/src/core/drawing.rs @@ -32,6 +32,7 @@ impl RaylibHandle { let d = RaylibDrawHandle(self); d } + /// Setup canvas (framebuffer) to start drawing. // Every FnMut is a FnOnce, but not every FnOnce is a FnMut. The closure may possibly execute multiple times throughout the program, but not multiple times in a single call to this method. // Taking a FnOnce instead of a FnMut when the function only needs to be called once in this method makes the method slightly more versatile/less needlessly restrictive for no actual cost. pub fn draw<'a>(&'a mut self, _: &RaylibThread, func: impl FnOnce(RaylibDrawHandle<'a>)) { @@ -129,6 +130,7 @@ where RaylibTextureMode(self, PhantomData) } + /// Begin drawing to render texture. fn draw_texture_mode<'a, 'b>( &'a mut self, _: &RaylibThread, @@ -180,6 +182,7 @@ where RaylibVRMode(self, PhantomData, PhantomData) } + /// Begin stereo rendering (requires VR simulator). fn draw_vr_stereo_mode<'a, 'b>( &'a mut self, vr_config: &'b mut VrStereoConfig, @@ -231,6 +234,7 @@ where RaylibMode2D(self) } + /// Begin 2D mode with custom camera (2D). #[allow(non_snake_case)] fn draw_mode2D<'a>( &'a mut self, @@ -287,6 +291,7 @@ where RaylibMode3D(self) } + /// Begin 3D mode with custom camera (3D). #[allow(non_snake_case)] fn draw_mode3D<'a>( &'a mut self, @@ -342,6 +347,7 @@ where RaylibShaderMode(self, PhantomData) } + /// Begin custom shader drawing. fn draw_shader_mode<'a, 'b>( &'a mut self, shader: &'b mut Shader, @@ -391,6 +397,7 @@ where RaylibBlendMode(self) } + /// Begin blending mode (alpha, additive, multiplied, subtract, custom). fn draw_blend_mode<'a>( &'a mut self, blend_mode: crate::consts::BlendMode, @@ -446,6 +453,7 @@ where RaylibScissorMode(self) } + /// Begin scissor mode (define screen area for following drawing). fn draw_scissor_mode<'a>( &'a mut self, x: i32, @@ -477,16 +485,19 @@ pub trait RaylibDraw { } /// Get texture that is used for shapes drawing + #[inline] fn get_shapes_texture(&self) -> Texture2D { Texture2D(unsafe { ffi::GetShapesTexture() }) } /// Get texture source rectangle that is used for shapes drawing + #[inline] fn get_shapes_texture_rectangle(&self) -> Rectangle { unsafe { ffi::GetShapesTextureRectangle() } } /// Define default texture used to draw shapes + #[inline] fn set_shapes_texture( &mut self, texture: impl AsRef, @@ -573,7 +584,8 @@ pub trait RaylibDraw { } } - /// Draw lines sequence #[inline] + /// Draw lines sequence + #[inline] fn draw_line_strip(&mut self, points: &[Vector2], color: impl Into) { unsafe { ffi::DrawLineStrip( @@ -943,6 +955,7 @@ pub trait RaylibDraw { } /// Draw rectangle with rounded edges outline + #[inline] fn draw_rectangle_rounded_lines_ex( &mut self, rec: impl Into, @@ -1133,7 +1146,7 @@ pub trait RaylibDraw { } } - ///Draws a texture (or part of it) that stretches or shrinks nicely + /// Draws a texture (or part of it) that stretches or shrinks nicely #[inline] fn draw_texture_n_patch( &mut self, @@ -1234,6 +1247,8 @@ pub trait RaylibDraw { } } + /// Draw text using Font and pro parameters (rotation) + #[inline] fn draw_text_pro( &mut self, font: impl AsRef, @@ -1282,16 +1297,19 @@ pub trait RaylibDraw { } /// Enable waiting for events when the handle is dropped, no automatic event polling + #[inline] fn enable_event_waiting(&self) { unsafe { ffi::EnableEventWaiting() } } /// Disable waiting for events when the handle is dropped, no automatic event polling + #[inline] fn disable_event_waiting(&self) { unsafe { ffi::DisableEventWaiting() } } /// Draw a polygon outline of n sides with extended parameters + #[inline] fn draw_poly_lines_ex( &mut self, center: Vector2, @@ -1313,6 +1331,7 @@ pub trait RaylibDraw { } } /// Draw spline: Linear, minimum 2 points + #[inline] fn draw_spline_linear(&mut self, points: &[Vector2], thick: f32, color: impl Into) { unsafe { ffi::DrawSplineLinear( @@ -1324,6 +1343,7 @@ pub trait RaylibDraw { } } /// Draw spline: B-Spline, minimum 4 points + #[inline] fn draw_spline_basis(&mut self, points: &[Vector2], thick: f32, color: impl Into) { unsafe { ffi::DrawSplineBasis( @@ -1335,6 +1355,7 @@ pub trait RaylibDraw { } } /// Draw spline: Catmull-Rom, minimum 4 points + #[inline] fn draw_spline_catmull_rom( &mut self, points: &[Vector2], @@ -1352,6 +1373,7 @@ pub trait RaylibDraw { } /// Draw spline: Quadratic Bezier, minimum 3 points (1 control point): [p1, c2, p3, c4...] + #[inline] fn draw_spline_bezier_quadratic( &mut self, points: &[Vector2], @@ -1369,6 +1391,7 @@ pub trait RaylibDraw { } /// Draw spline: Cubic Bezier, minimum 4 points (2 control points): [p1, c2, c3, p4, c5, c6...] + #[inline] fn draw_spline_bezier_cubic( &mut self, points: &[Vector2], @@ -1386,6 +1409,7 @@ pub trait RaylibDraw { } /// Draw spline segment: Linear, 2 points + #[inline] fn draw_spline_segment_linear( &mut self, p1: Vector2, @@ -1397,6 +1421,7 @@ pub trait RaylibDraw { } /// Draw spline segment: B-Spline, 4 points + #[inline] fn draw_spline_segment_basis( &mut self, p1: Vector2, @@ -1419,6 +1444,7 @@ pub trait RaylibDraw { } /// Draw spline segment: Catmull-Rom, 4 points + #[inline] fn draw_spline_segment_catmull_rom( &mut self, p1: Vector2, @@ -1441,6 +1467,7 @@ pub trait RaylibDraw { } /// Draw spline segment: Quadratic Bezier, 2 points, 1 control point + #[inline] fn draw_spline_segment_bezier_quadratic( &mut self, p1: Vector2, @@ -1461,6 +1488,7 @@ pub trait RaylibDraw { } /// Draw spline segment: Cubic Bezier, 2 points, 2 control points + #[inline] fn draw_spline_segment_bezier_cubic( &mut self, p1: Vector2, @@ -1483,11 +1511,13 @@ pub trait RaylibDraw { } /// Get (evaluate) spline point: Linear + #[inline] fn get_spline_point_linear(&mut self, start_pos: Vector2, end_pos: Vector2, t: f32) -> Vector2 { unsafe { ffi::GetSplinePointLinear(start_pos.into(), end_pos.into(), t).into() } } /// Get (evaluate) spline point: B-Spline + #[inline] fn get_spline_point_basis( &mut self, p1: Vector2, @@ -1500,6 +1530,7 @@ pub trait RaylibDraw { } /// Get (evaluate) spline point: Catmull-Rom + #[inline] fn get_spline_point_catmull_rom( &mut self, p1: Vector2, @@ -1514,6 +1545,7 @@ pub trait RaylibDraw { } /// Get (evaluate) spline point: Quadratic Bezier + #[inline] fn get_spline_point_bezier_quad( &mut self, p1: Vector2, @@ -1524,6 +1556,8 @@ pub trait RaylibDraw { unsafe { ffi::GetSplinePointBezierQuad(p1.into(), c2.into(), p3.into(), t).into() } } + /// Get (evaluate) spline point: Cubic Bezier + #[inline] fn get_spline_point_bezier_cubic( &mut self, p1: Vector2, @@ -1548,7 +1582,7 @@ pub trait RaylibDraw3D { } } - ///// Draw a color-filled triangle (vertex in counter-clockwise order!) + /// Draw a color-filled triangle (vertex in counter-clockwise order!) #[allow(non_snake_case)] #[inline] fn draw_triangle3D( @@ -1563,7 +1597,7 @@ pub trait RaylibDraw3D { } } - /// // Draw a triangle strip defined by points + /// Draw a triangle strip defined by points #[allow(non_snake_case)] #[inline] fn draw_triangle_strip3D(&mut self, points: &[Vector3], color: impl Into) { @@ -1573,9 +1607,9 @@ pub trait RaylibDraw3D { } /// Draws a line in 3D world space. - #[inline] #[allow(non_snake_case)] - fn draw_line_3D( + #[inline] + fn draw_line3D( &mut self, start_pos: impl Into, end_pos: impl Into, @@ -1587,9 +1621,9 @@ pub trait RaylibDraw3D { } /// Draws a circle in 3D world space. - #[inline] #[allow(non_snake_case)] - fn draw_circle_3D( + #[inline] + fn draw_circle3D( &mut self, center: impl Into, radius: f32, @@ -1826,6 +1860,7 @@ pub trait RaylibDraw3D { } /// Draw capsule with the center of its sphere caps at startPos and endPos + #[inline] fn draw_capsule( &mut self, start_pos: impl Into, @@ -1848,6 +1883,7 @@ pub trait RaylibDraw3D { } ///Draw capsule wireframe with the center of its sphere caps at startPos and endPos + #[inline] fn draw_capsule_wires( &mut self, start_pos: impl Into, @@ -2023,6 +2059,7 @@ pub trait RaylibDraw3D { } /// Draw a billboard texture defined by source and rotation + #[inline] fn draw_billboard_pro( &mut self, camera: impl Into, @@ -2051,6 +2088,7 @@ pub trait RaylibDraw3D { } /// Draw a model as points + #[inline] fn draw_model_points( &mut self, model: impl Into, @@ -2064,6 +2102,7 @@ pub trait RaylibDraw3D { } /// Draw a model as points with extended parameters + #[inline] fn draw_model_points_ex( &mut self, model: impl Into, diff --git a/raylib/src/core/file.rs b/raylib/src/core/file.rs index f7c1d8cf..4669c8b5 100644 --- a/raylib/src/core/file.rs +++ b/raylib/src/core/file.rs @@ -126,10 +126,12 @@ make_thin_wrapper!( impl FilePathList { /// Length of the file path list + #[inline] pub const fn count(&self) -> u32 { self.0.count } /// The amount of files that can be held in this list. + #[inline] pub const fn capacity(&self) -> u32 { self.0.capacity } @@ -149,10 +151,12 @@ impl FilePathList { impl DroppedFilePathList { /// Length of the file path list + #[inline] pub const fn count(&self) -> u32 { self.0.count } /// The amount of files that can be held in this list. + #[inline] pub const fn capacity(&self) -> u32 { self.0.capacity } @@ -211,8 +215,10 @@ impl RaylibHandle { } /// Check if a given path is a file or a directory + /// /// # Errors /// This function will return an error if the supplied bytes contain an internal 0 byte. The NulError returned will contain the bytes as well as the position of the nul byte. + #[must_use] pub fn is_path_file(&self, filename: A) -> bool where A: Into, @@ -254,6 +260,7 @@ impl RaylibHandle { } /// Check if a file has been dropped into window + #[inline] pub fn load_dropped_files(&self) -> DroppedFilePathList { unsafe { DroppedFilePathList(ffi::LoadDroppedFiles()) } } diff --git a/raylib/src/core/input.rs b/raylib/src/core/input.rs index ebe99d53..bbb4fc78 100644 --- a/raylib/src/core/input.rs +++ b/raylib/src/core/input.rs @@ -279,11 +279,13 @@ impl RaylibHandle { } /// Set internal gamepad mappings (SDL_GameControllerDB) + #[inline] pub fn set_gamepad_mappings(&self, bind: &[c_char]) -> i32 { unsafe { ffi::SetGamepadMappings(bind.as_ptr()) } } /// Set gamepad vibration for both motors + #[inline] pub fn set_gamepad_vibration( &mut self, gamepad: i32, diff --git a/raylib/src/core/macros.rs b/raylib/src/core/macros.rs index a775e060..4ab63f9b 100644 --- a/raylib/src/core/macros.rs +++ b/raylib/src/core/macros.rs @@ -1,8 +1,9 @@ macro_rules! make_thin_wrapper { - ($name:ident, $t:ty, $dropfunc:expr) => { - make_thin_wrapper!($name, $t, $dropfunc, true); + ($(#[$attrs:meta])* $name:ident, $t:ty, $dropfunc:expr) => { + make_thin_wrapper!($(#[$attrs])* $name, $t, $dropfunc, true); }; - ($name:ident, $t:ty, $dropfunc:expr, false) => { + ($(#[$attrs:meta])* $name:ident, $t:ty, $dropfunc:expr, false) => { + $(#[$attrs])* #[repr(transparent)] #[derive(Debug)] pub struct $name(pub(crate) $t); @@ -10,7 +11,8 @@ macro_rules! make_thin_wrapper { impl_wrapper!($name, $t, $dropfunc, 0); gen_from_raw_wrapper!($name, $t, $dropfunc, 0); }; - ($name:ident, $t:ty, $dropfunc:expr, true) => { + ($(#[$attrs:meta])* $name:ident, $t:ty, $dropfunc:expr, true) => { + $(#[$attrs])* #[repr(transparent)] #[derive(Debug)] pub struct $name(pub(crate) $t); @@ -22,16 +24,16 @@ macro_rules! make_thin_wrapper { } macro_rules! make_thin_wrapper_lifetime { - ($name:ident, $t1:ty, $t2:ty, $dropfunc:expr) => { + ($(#[$attrs:meta])* $name:ident, $t1:ty, $t2:ty, $dropfunc:expr) => { make_thin_wrapper_lifetime!($name, $t1, $t2, $dropfunc, true); }; - ($name:ident, $t1:ty, $t2:ty,$dropfunc:expr, false) => { + ($(#[$attrs:meta])* $name:ident, $t1:ty, $t2:ty,$dropfunc:expr, false) => { #[derive(Debug)] pub struct $name<'a>(pub(crate) $t1, &'a $t2); impl_wrapper!($name, $t1, $dropfunc, 0); }; - ($name:ident, $t1:ty, $t2:ty, $dropfunc:expr, true) => { + ($(#[$attrs:meta])* $name:ident, $t1:ty, $t2:ty, $dropfunc:expr, true) => { #[derive(Debug)] pub struct $name<'a>(pub(crate) $t1, &'a $t2); @@ -115,7 +117,8 @@ macro_rules! deref_impl_wrapper { }; } macro_rules! make_rslice { - ($name:ident, $t:ty, $dropfunc:expr) => { + ($(#[$attrs:meta])* $name:ident, $t:ty, $dropfunc:expr) => { + $(#[$attrs])* #[repr(transparent)] #[derive(Debug)] pub struct $name(pub(crate) std::mem::ManuallyDrop>); diff --git a/raylib/src/core/math.rs b/raylib/src/core/math.rs index f90a3f71..11ffbad3 100644 --- a/raylib/src/core/math.rs +++ b/raylib/src/core/math.rs @@ -34,8 +34,11 @@ macro_rules! optional_serde_struct { } optional_serde_struct! { + /// Vector2, 2 components pub struct Vector2 { + /// Vector x component pub x: f32, + /// Vector y component pub y: f32, } } @@ -81,7 +84,7 @@ impl From<&Vector2> for ffi::Vector2 { /// A convenience function for linearly interpolating an `f32`. #[inline] -pub fn lerp(v0: f32, v1: f32, amount: f32) -> f32 { +pub const fn lerp(v0: f32, v1: f32, amount: f32) -> f32 { v0 + amount * (v1 - v0) } @@ -139,21 +142,25 @@ impl Vector2 { } /// Calculates the vector length. + #[inline] pub fn length(&self) -> f32 { ((self.x * self.x) + (self.y * self.y)).sqrt() } /// Calculates the vector length square (**2); - pub fn length_sqr(&self) -> f32 { + #[inline] + pub const fn length_sqr(&self) -> f32 { (self.x * self.x) + (self.y * self.y) } /// Calculates the dot product with vector `v`. - pub fn dot(&self, v: Vector2) -> f32 { + #[inline] + pub const fn dot(&self, v: Vector2) -> f32 { self.x * v.x + self.y * v.y } /// Calculates the distance towards vector `v`. + #[inline] pub fn distance_to(&self, v: Vector2) -> f32 { ((self.x - v.x) * (self.x - v.x) + (self.y - v.y) * (self.y - v.y)).sqrt() } @@ -168,16 +175,19 @@ impl Vector2 { } /// Scales the vector by multiplying both components by `scale`. + #[inline] pub fn scale(&mut self, scale: f32) { *self *= scale; } /// Returns a new `Vector2` with components scaled by `scale`. + #[inline] pub fn scale_by(&self, scale: f32) -> Vector2 { *self * scale } /// Normalizes the vector. + #[inline] pub fn normalize(&mut self) { *self = self.normalized(); } @@ -217,7 +227,8 @@ impl Vector2 { } /// Returns a new `Vector2` with componenets linearly interpolated by `amount` towards vector `v`. - pub fn lerp(&self, v: Vector2, amount: f32) -> Vector2 { + #[inline] + pub const fn lerp(&self, v: Vector2, amount: f32) -> Vector2 { Vector2 { x: self.x + amount * (v.x - self.x), y: self.y + amount * (v.y - self.y), @@ -225,7 +236,8 @@ impl Vector2 { } /// Returns a new `Vector2` with componenets clamp to a certain interval. - pub fn clamp(&self, num: Range) -> Vector2 { + #[inline] + pub const fn clamp(&self, num: Range) -> Vector2 { Vector2 { x: self.x.clamp(num.start, num.end), y: self.y.clamp(num.start, num.end), @@ -379,9 +391,13 @@ impl Neg for Vector2 { } optional_serde_struct! { + /// Vector3, 3 components pub struct Vector3 { + /// Vector x component pub x: f32, + /// Vector y component pub y: f32, + /// Vector z component pub z: f32, } } @@ -447,24 +463,33 @@ impl Vector3 { Vector3 { x, y, z } } - pub fn up() -> Vector3 { + /// Returns a new `Vector3` one positive unit in the Y axis. + #[inline] + pub const fn up() -> Vector3 { Vector3::new(0.0, 1.0, 0.0) } - pub fn forward() -> Vector3 { + /// Returns a new `Vector3` one positive unit in the Z axis. + #[inline] + pub const fn forward() -> Vector3 { Vector3::new(0.0, 0.0, 1.0) } - pub fn right() -> Vector3 { + /// Returns a new `Vector3` one positive unit in the X axis. + #[inline] + pub const fn right() -> Vector3 { Vector3::new(1.0, 0.0, 0.0) } - pub fn left() -> Vector3 { + /// Returns a new `Vector3` one negative unit in the X axis. + #[inline] + pub const fn left() -> Vector3 { Vector3::new(-1.0, 0.0, 0.0) } /// Returns a new `Vector3` with all components set to zero. - pub fn zero() -> Vector3 { + #[inline] + pub const fn zero() -> Vector3 { Vector3 { x: 0.0, y: 0.0, @@ -473,7 +498,8 @@ impl Vector3 { } /// Returns a new `Vector3` with all components set to one. - pub fn one() -> Vector3 { + #[inline] + pub const fn one() -> Vector3 { Vector3 { x: 1.0, y: 1.0, @@ -482,7 +508,7 @@ impl Vector3 { } /// Returns a new `Vector3` containing the cross product between `self` and vector `v`. - pub fn cross(&self, v: Vector3) -> Vector3 { + pub const fn cross(&self, v: Vector3) -> Vector3 { Vector3 { x: self.y * v.z - self.z * v.y, y: self.z * v.x - self.x * v.z, @@ -491,7 +517,7 @@ impl Vector3 { } /// Returns a new `Vector3` perpendicular to `self`. - pub fn perpendicular(&self) -> Vector3 { + pub const fn perpendicular(&self) -> Vector3 { let mut min = self.x.abs(); let mut cardinal_axis = Vector3 { x: 1.0, @@ -520,16 +546,19 @@ impl Vector3 { } /// Calculates the vector length. + #[inline] pub fn length(&self) -> f32 { (self.x * self.x + self.y * self.y + self.z * self.z).sqrt() } /// Calculates the dot product with vector `v`. - pub fn dot(&self, v: Vector3) -> f32 { + #[inline] + pub const fn dot(&self, v: Vector3) -> f32 { self.x * v.x + self.y * v.y + self.z * v.z } /// Calculates the distance towards vector `v`. + #[inline] pub fn distance_to(&self, v: Vector3) -> f32 { let dx = v.x - self.x; let dy = v.y - self.y; @@ -538,16 +567,19 @@ impl Vector3 { } /// Scales the vector by multiplying both components by `scale`. + #[inline] pub fn scale(&mut self, scale: f32) { *self *= scale; } /// Returns a new `Vector3` with components scaled by `scale`. + #[inline] pub fn scale_by(&self, scale: f32) -> Vector3 { *self * scale } /// Normalizes the current vector. + #[inline] pub fn normalize(&mut self) { *self = self.normalized(); } @@ -575,12 +607,13 @@ impl Vector3 { } /// Transforms the current vector using Matrix `mat`. - pub fn transform(&mut self, mat: Matrix) { + #[inline] + pub const fn transform(&mut self, mat: Matrix) { *self = self.transform_with(mat); } /// Returns a new `Vector3` containing components transformed by Matrix `mat`. - pub fn transform_with(&self, mat: Matrix) -> Vector3 { + pub const fn transform_with(&self, mat: Matrix) -> Vector3 { Vector3 { x: mat.m0 * self.x + mat.m4 * self.y + mat.m8 * self.z + mat.m12, y: mat.m1 * self.x + mat.m5 * self.y + mat.m9 * self.z + mat.m13, @@ -589,12 +622,13 @@ impl Vector3 { } /// Rotates the current vector using Quaternion `q`. - pub fn rotate(&mut self, q: Quaternion) { + #[inline] + pub const fn rotate(&mut self, q: Quaternion) { *self = self.rotate_by(q); } /// Returns a new `Vector3` with components rotated by Quaternion `q`. - pub fn rotate_by(&self, q: Quaternion) -> Vector3 { + pub const fn rotate_by(&self, q: Quaternion) -> Vector3 { Vector3 { x: self.x * (q.x * q.x + q.w * q.w - q.y * q.y - q.z * q.z) + self.y * (2.0 * q.x * q.y - 2.0 * q.w * q.z) @@ -609,7 +643,8 @@ impl Vector3 { } /// Returns a new `Vector3` with componenets linearly interpolated by `amount` towards vector `v`. - pub fn lerp(&self, v: Vector3, amount: f32) -> Vector3 { + #[inline] + pub const fn lerp(&self, v: Vector3, amount: f32) -> Vector3 { Vector3 { x: self.x + amount * (v.x - self.x), y: self.y + amount * (v.y - self.y), @@ -618,12 +653,13 @@ impl Vector3 { } /// Reflects the current vector from `normal`. - pub fn reflect(&mut self, normal: Vector3) { + #[inline] + pub const fn reflect(&mut self, normal: Vector3) { *self = self.reflect_from(normal); } /// Returns a new `Vector3` reflected from the current vector using `normal`. - pub fn reflect_from(&self, normal: Vector3) -> Vector3 { + pub const fn reflect_from(&self, normal: Vector3) -> Vector3 { let dot_product = self.dot(normal); Vector3 { x: self.x - (2.0 * normal.x) * dot_product, @@ -633,7 +669,8 @@ impl Vector3 { } /// Returns a new `Vector3` containing the minimum of each corresponding component. - pub fn min(&self, v: Vector3) -> Vector3 { + #[inline] + pub const fn min(&self, v: Vector3) -> Vector3 { Vector3 { x: self.x.min(v.x), y: self.y.min(v.y), @@ -642,7 +679,8 @@ impl Vector3 { } /// Returns a new `Vector3` containing the maximum of each corresponding component. - pub fn max(&self, v: Vector3) -> Vector3 { + #[inline] + pub const fn max(&self, v: Vector3) -> Vector3 { Vector3 { x: self.x.max(v.x), y: self.y.max(v.y), @@ -651,10 +689,10 @@ impl Vector3 { } /// Returns barycenter coordinates (u, v, w) from point p (current vector) with respect to triangle (`a`, `b`, `c`). - pub fn barycenter(&self, a: Vector3, b: Vector3, c: Vector3) -> Vector3 { - let v0 = b - a; - let v1 = c - a; - let v2 = *self - a; + pub const fn barycenter(&self, a: Vector3, b: Vector3, c: Vector3) -> Vector3 { + let v0 = Vector3::new(b.x - a.x, b.y - a.y, b.z - a.z); + let v1 = Vector3::new(c.x - a.x, c.y - a.y, c.z - a.z); + let v2 = Vector3::new(self.x - a.x, self.y - a.y, self.z - a.z); let d00 = v0.dot(v0); let d01 = v0.dot(v1); let d11 = v1.dot(v1); @@ -672,12 +710,14 @@ impl Vector3 { } /// Returns a 3-length `f32` array containing components `[x, y, z]` of the current vector. - pub fn to_array(&self) -> [f32; 3] { + #[inline] + pub const fn to_array(&self) -> [f32; 3] { [self.x, self.y, self.z] } /// Returns a new `Vector3` with componenets clamp to a certain interval. - pub fn clamp(&self, num: Range) -> Vector3 { + #[inline] + pub const fn clamp(&self, num: Range) -> Vector3 { Vector3 { x: self.x.clamp(num.start, num.end), y: self.y.clamp(num.start, num.end), @@ -841,14 +881,20 @@ impl Neg for Vector3 { } optional_serde_struct! { + /// Vector4, 4 components pub struct Vector4 { + /// Vector x component pub x: f32, + /// Vector y component pub y: f32, + /// Vector z component pub z: f32, + /// Vector w component pub w: f32, } } +/// Quaternion, 4 components (Vector4 alias) pub type Quaternion = Vector4; #[cfg(feature = "convert_mint")] @@ -905,7 +951,8 @@ impl Quaternion { } /// Returns the identity quaternion. - pub fn identity() -> Quaternion { + #[inline] + pub const fn identity() -> Quaternion { Quaternion { x: 0.0, y: 0.0, @@ -1111,6 +1158,7 @@ impl Quaternion { } /// Computes the length of the current quaternion. + #[inline] pub fn length(&self) -> f32 { (self.x * self.x + self.y * self.y + self.z * self.z + self.w * self.w).sqrt() } @@ -1148,7 +1196,8 @@ impl Quaternion { } /// Calculates linear interpolation between current and `q` quaternions. - pub fn lerp(&self, q: Quaternion, amount: f32) -> Quaternion { + #[inline] + pub const fn lerp(&self, q: Quaternion, amount: f32) -> Quaternion { Quaternion { x: self.x + amount * (q.x - self.x), y: self.y + amount * (q.y - self.y), @@ -1158,6 +1207,7 @@ impl Quaternion { } /// Calculates slerp-optimized interpolation between current and `q` quaternions. + #[inline] pub fn nlerp(&self, q: Quaternion, amount: f32) -> Quaternion { self.lerp(q, amount).normalized() } @@ -1196,7 +1246,7 @@ impl Quaternion { } /// Returns a transformed version of the current quaternion given a transformation matrix. - pub fn transform(&self, mat: Matrix) -> Quaternion { + pub const fn transform(&self, mat: Matrix) -> Quaternion { Quaternion { x: mat.m0 * self.x + mat.m4 * self.y + mat.m8 * self.z + mat.m12 * self.w, y: mat.m1 * self.x + mat.m5 * self.y + mat.m9 * self.z + mat.m13 * self.w, @@ -1206,7 +1256,8 @@ impl Quaternion { } /// Returns a new `Quaternion` with componenets clamp to a certain interval. - pub fn clamp(&self, num: Range) -> Quaternion { + #[inline] + pub const fn clamp(&self, num: Range) -> Quaternion { Quaternion { x: self.x.clamp(num.start, num.end), y: self.y.clamp(num.start, num.end), @@ -1277,19 +1328,24 @@ impl MulAssign for Quaternion { } optional_serde_struct! { + /// Matrix, 4x4 components, column major, OpenGL style, right-handed pub struct Matrix { + // Matrix first row (4 components) pub m0: f32, pub m4: f32, pub m8: f32, pub m12: f32, + // Matrix second row (4 components) pub m1: f32, pub m5: f32, pub m9: f32, pub m13: f32, + // Matrix third row (4 components) pub m2: f32, pub m6: f32, pub m10: f32, pub m14: f32, + // Matrix fourth row (4 components) pub m3: f32, pub m7: f32, pub m11: f32, @@ -1334,7 +1390,8 @@ impl From<&Matrix> for ffi::Matrix { impl Matrix { /// Returns the identity matrix. - pub fn identity() -> Matrix { + #[inline] + pub const fn identity() -> Matrix { Matrix { m0: 1.0, m4: 0.0, @@ -1356,7 +1413,8 @@ impl Matrix { } /// Returns the zero matriz. - pub fn zero() -> Matrix { + #[inline] + pub const fn zero() -> Matrix { Matrix { m0: 0.0, m4: 0.0, @@ -1378,7 +1436,8 @@ impl Matrix { } /// Returns a translation matrix. - pub fn translate(x: f32, y: f32, z: f32) -> Matrix { + #[inline] + pub const fn translate(x: f32, y: f32, z: f32) -> Matrix { Matrix { m0: 1.0, m4: 0.0, @@ -1509,7 +1568,8 @@ impl Matrix { } /// Returns a scaling matrix. - pub fn scale(x: f32, y: f32, z: f32) -> Matrix { + #[inline] + pub const fn scale(x: f32, y: f32, z: f32) -> Matrix { Matrix { m0: x, m4: 0.0, @@ -1620,7 +1680,7 @@ impl Matrix { } /// Calculates the determinant of the current matrix. - pub fn determinant(&self) -> f32 { + pub const fn determinant(&self) -> f32 { let a00 = self.m0; let a01 = self.m1; let a02 = self.m2; @@ -1663,12 +1723,14 @@ impl Matrix { } /// Calculates the trace of the matrix (sum of the values along the diagonal). - pub fn trace(&self) -> f32 { + #[inline] + pub const fn trace(&self) -> f32 { self.m0 + self.m5 + self.m10 + self.m15 } /// Returns a new `Matrix` transposed from the current one. - pub fn transposed(&self) -> Matrix { + #[inline] + pub const fn transposed(&self) -> Matrix { Matrix { m0: self.m0, m1: self.m4, @@ -1690,7 +1752,7 @@ impl Matrix { } /// Returns a new `Matrix` inverted from the current one. - pub fn inverted(&self) -> Matrix { + pub const fn inverted(&self) -> Matrix { let a00 = self.m0; let a01 = self.m1; let a02 = self.m2; @@ -1745,7 +1807,8 @@ impl Matrix { } /// Returns a new `Matrix` normalized from the current one. - pub fn normalized(&self) -> Matrix { + #[inline] + pub const fn normalized(&self) -> Matrix { let det = self.determinant(); Matrix { m0: self.m0 / det, @@ -1768,7 +1831,8 @@ impl Matrix { } /// Returns a 16-length `f32` array containing the current matrix data. - pub fn to_array(&self) -> [f32; 16] { + #[inline] + pub const fn to_array(&self) -> [f32; 16] { [ self.m0, self.m1, self.m2, self.m3, self.m4, self.m5, self.m6, self.m7, self.m8, self.m9, self.m10, self.m11, self.m12, self.m13, self.m14, self.m15, @@ -1867,8 +1931,11 @@ impl MulAssign for Matrix { } optional_serde_struct! { + /// Ray, ray for raycasting pub struct Ray { + /// Ray position (origin) pub position: Vector3, + /// Ray direction (normalized) pub direction: Vector3, } } @@ -1904,10 +1971,15 @@ impl Ray { } optional_serde_struct! { + /// Rectangle, 4 components pub struct Rectangle { + /// Rectangle top-left corner position x pub x: f32, + /// Rectangle top-left corner position y pub y: f32, + /// Rectangle width pub width: f32, + /// Rectangle height pub height: f32, } } @@ -1948,8 +2020,11 @@ impl Rectangle { } optional_serde_struct! { + /// BoundingBox pub struct BoundingBox { + /// Minimum vertex box-corner pub min: Vector3, + /// Maximum vertex box-corner pub max: Vector3, } } @@ -1982,10 +2057,15 @@ impl From<&BoundingBox> for ffi::BoundingBox { } optional_serde_struct! { + /// RayCollision, ray hit information pub struct RayCollision { + /// Did the ray hit something? pub hit: bool, + /// Distance to the nearest hit pub distance: f32, + /// Point of the nearest hit pub point: Vector3, + /// Surface normal of hit pub normal: Vector3, } } @@ -2014,9 +2094,13 @@ impl From<&RayCollision> for ffi::RayCollision { } optional_serde_struct! { + /// Transform, vertex transformation data pub struct Transform { + /// Translation pub translation: Vector3, + /// Rotation pub rotation: Quaternion, + /// Scale pub scale: Vector3, } } diff --git a/raylib/src/core/models.rs b/raylib/src/core/models.rs index a93fb6e2..bbc77dcb 100644 --- a/raylib/src/core/models.rs +++ b/raylib/src/core/models.rs @@ -9,20 +9,46 @@ use std::ffi::CString; use std::os::raw::c_void; fn no_drop(_thing: T) {} -make_thin_wrapper!(Model, ffi::Model, ffi::UnloadModel); +make_thin_wrapper!( + /// Model, meshes, materials and animation data + 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!( + /// Mesh, vertex data and vao/vbo + 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!( + /// Material, includes shader and maps + Material, + ffi::Material, + ffi::UnloadMaterial +); make_thin_wrapper!(WeakMaterial, ffi::Material, no_drop); -make_thin_wrapper!(BoneInfo, ffi::BoneInfo, no_drop); make_thin_wrapper!( + /// Bone, skeletal animation bone + BoneInfo, + ffi::BoneInfo, + no_drop +); +make_thin_wrapper!( + /// ModelAnimation ModelAnimation, ffi::ModelAnimation, ffi::UnloadModelAnimation ); make_thin_wrapper!(WeakModelAnimation, ffi::ModelAnimation, no_drop); -make_thin_wrapper!(MaterialMap, ffi::MaterialMap, no_drop); +make_thin_wrapper!( + /// MaterialMap + MaterialMap, + ffi::MaterialMap, + no_drop +); // Weak things can be clone impl Clone for WeakModel { @@ -66,7 +92,7 @@ impl RaylibHandle { Ok(Model(m)) } - // Loads model from a generated mesh + /// Loads model from a generated mesh pub fn load_model_from_mesh( &mut self, _: &RaylibThread, @@ -81,6 +107,7 @@ impl RaylibHandle { Ok(Model(m)) } + /// Load model animations from file pub fn load_model_animations( &mut self, _: &RaylibThread, @@ -104,6 +131,8 @@ impl RaylibHandle { Ok(m_vec) } + /// Update model animation pose (CPU) + #[inline] pub fn update_model_animation( &mut self, _: &RaylibThread, @@ -116,6 +145,8 @@ impl RaylibHandle { } } + /// Update model animation mesh bone matrices (GPU skinning) + #[inline] pub fn update_model_animation_bones( &mut self, _: &RaylibThread, @@ -141,6 +172,7 @@ impl Model { } pub trait RaylibModel: AsRef + AsMut { + /// Local transform matrix fn transform(&self) -> &crate::math::Matrix { unsafe { std::mem::transmute(&self.as_ref().transform) } } @@ -149,6 +181,8 @@ pub trait RaylibModel: AsRef + AsMut { self.as_mut().transform = mat.into(); } + /// Meshes array + #[inline] fn meshes(&self) -> &[WeakMesh] { unsafe { std::slice::from_raw_parts( @@ -157,6 +191,8 @@ pub trait RaylibModel: AsRef + AsMut { ) } } + // Meshes array + #[inline] fn meshes_mut(&mut self) -> &mut [WeakMesh] { unsafe { std::slice::from_raw_parts_mut( @@ -165,6 +201,8 @@ pub trait RaylibModel: AsRef + AsMut { ) } } + /// Materials array + #[inline] fn materials(&self) -> &[WeakMaterial] { unsafe { std::slice::from_raw_parts( @@ -173,6 +211,8 @@ pub trait RaylibModel: AsRef + AsMut { ) } } + /// Materials array + #[inline] fn materials_mut(&mut self) -> &mut [WeakMaterial] { unsafe { std::slice::from_raw_parts_mut( @@ -182,6 +222,7 @@ pub trait RaylibModel: AsRef + AsMut { } } + /// Bones information (skeleton) fn bones(&self) -> Option<&[BoneInfo]> { if self.as_ref().bones.is_null() { return None; @@ -194,6 +235,7 @@ pub trait RaylibModel: AsRef + AsMut { ) }) } + /// Bones information (skeleton) fn bones_mut(&mut self) -> Option<&mut [BoneInfo]> { if self.as_ref().bones.is_null() { return None; @@ -206,6 +248,7 @@ pub trait RaylibModel: AsRef + AsMut { ) }) } + /// Bones base transformation (pose) fn bind_pose(&self) -> Option<&crate::math::Transform> { if self.as_ref().bindPose.is_null() { return None; @@ -213,6 +256,7 @@ pub trait RaylibModel: AsRef + AsMut { Some(unsafe { std::mem::transmute(self.as_ref().bindPose) }) } + /// Bones base transformation (pose) fn bind_pose_mut(&mut self) -> Option<&mut crate::math::Transform> { if self.as_ref().bindPose.is_null() { return None; @@ -227,11 +271,13 @@ pub trait RaylibModel: AsRef + AsMut { } /// Check if a model is ready + #[inline] fn is_model_valid(&self) -> bool { unsafe { ffi::IsModelValid(*self.as_ref()) } } /// Compute model bounding box limits (considers all meshes) + #[inline] fn get_model_bounding_box(&self) -> BoundingBox { unsafe { BoundingBox::from(ffi::GetModelBoundingBox(*self.as_ref())) } } @@ -260,9 +306,13 @@ impl Mesh { } } pub trait RaylibMesh: AsRef + AsMut { + /// Upload mesh vertex data in GPU and provide VAO/VBO ids + #[inline] unsafe fn upload(&mut self, dynamic: bool) { ffi::UploadMesh(self.as_mut(), dynamic); } + /// Update mesh vertex data in GPU for a specific buffer index + #[inline] unsafe fn update_buffer(&mut self, index: i32, data: &[u8], offset: i32) { ffi::UpdateMeshBuffer( *self.as_ref(), @@ -272,6 +322,8 @@ pub trait RaylibMesh: AsRef + AsMut { offset, ); } + /// Vertex position (XYZ - 3 components per vertex) (shader-location = 0) + #[inline] fn vertices(&self) -> &[Vector3] { unsafe { std::slice::from_raw_parts( @@ -280,6 +332,8 @@ pub trait RaylibMesh: AsRef + AsMut { ) } } + /// Vertex position (XYZ - 3 components per vertex) (shader-location = 0) + #[inline] fn vertices_mut(&mut self) -> &mut [Vector3] { unsafe { std::slice::from_raw_parts_mut( @@ -288,6 +342,8 @@ pub trait RaylibMesh: AsRef + AsMut { ) } } + /// Vertex normals (XYZ - 3 components per vertex) (shader-location = 2) + #[inline] fn normals(&self) -> &[Vector3] { unsafe { std::slice::from_raw_parts( @@ -296,6 +352,8 @@ pub trait RaylibMesh: AsRef + AsMut { ) } } + /// Vertex normals (XYZ - 3 components per vertex) (shader-location = 2) + #[inline] fn normals_mut(&mut self) -> &mut [Vector3] { unsafe { std::slice::from_raw_parts_mut( @@ -304,6 +362,8 @@ pub trait RaylibMesh: AsRef + AsMut { ) } } + /// Vertex tangents (XYZW - 4 components per vertex) (shader-location = 4) + #[inline] fn tangents(&self) -> &[Vector3] { unsafe { std::slice::from_raw_parts( @@ -312,6 +372,8 @@ pub trait RaylibMesh: AsRef + AsMut { ) } } + /// Vertex tangents (XYZW - 4 components per vertex) (shader-location = 4) + #[inline] fn tangents_mut(&mut self) -> &mut [Vector3] { unsafe { std::slice::from_raw_parts_mut( @@ -320,6 +382,8 @@ pub trait RaylibMesh: AsRef + AsMut { ) } } + /// Vertex colors (RGBA - 4 components per vertex) (shader-location = 3) + #[inline] fn colors(&self) -> &[crate::color::Color] { unsafe { std::slice::from_raw_parts( @@ -328,6 +392,8 @@ pub trait RaylibMesh: AsRef + AsMut { ) } } + /// Vertex colors (RGBA - 4 components per vertex) (shader-location = 3) + #[inline] fn colors_mut(&mut self) -> &mut [crate::color::Color] { unsafe { std::slice::from_raw_parts_mut( @@ -336,6 +402,8 @@ pub trait RaylibMesh: AsRef + AsMut { ) } } + /// Vertex indices (in case vertex data comes indexed) + #[inline] fn indicies(&self) -> &[u16] { unsafe { std::slice::from_raw_parts( @@ -344,6 +412,8 @@ pub trait RaylibMesh: AsRef + AsMut { ) } } + /// Vertex indices (in case vertex data comes indexed) + #[inline] fn indicies_mut(&mut self) -> &mut [u16] { unsafe { std::slice::from_raw_parts_mut( @@ -422,6 +492,7 @@ pub trait RaylibMesh: AsRef + AsMut { } /// Generate cone/pyramid mesh + #[inline] fn gen_mesh_cone(_: &RaylibThread, radius: f32, height: f32, slices: i32) -> Mesh { unsafe { Mesh(ffi::GenMeshCone(radius, height, slices)) } } @@ -467,6 +538,7 @@ impl Material { m } + /// Load materials from model file pub fn load_materials(filename: &str) -> Result, Error> { let c_filename = CString::new(filename).unwrap(); let mut m_size = 0; @@ -491,14 +563,17 @@ impl RaylibMaterial for WeakMaterial {} impl RaylibMaterial for Material {} pub trait RaylibMaterial: AsRef + AsMut { + /// Material shader fn shader(&self) -> &crate::shaders::WeakShader { unsafe { std::mem::transmute(&self.as_ref().shader) } } + /// Material shader fn shader_mut(&mut self) -> &mut crate::shaders::WeakShader { unsafe { std::mem::transmute(&mut self.as_mut().shader) } } + /// Material maps array (MAX_MATERIAL_MAPS) fn maps(&self) -> &[MaterialMap] { unsafe { std::slice::from_raw_parts( @@ -508,6 +583,7 @@ pub trait RaylibMaterial: AsRef + AsMut { } } + /// Material maps array (MAX_MATERIAL_MAPS) fn maps_mut(&mut self) -> &mut [MaterialMap] { unsafe { std::slice::from_raw_parts_mut( @@ -517,6 +593,8 @@ pub trait RaylibMaterial: AsRef + AsMut { } } + /// Set texture for a material map type (MATERIAL_MAP_DIFFUSE, MATERIAL_MAP_SPECULAR...) + #[inline] fn set_material_texture( &mut self, map_type: crate::consts::MaterialMapIndex, @@ -527,6 +605,8 @@ pub trait RaylibMaterial: AsRef + AsMut { } } + /// Check if a material is valid (shader assigned, map textures loaded in GPU) + #[inline] fn is_material_valid(&mut self) -> bool { unsafe { ffi::IsMaterialValid(*self.as_ref()) } } @@ -671,6 +751,8 @@ impl ModelAnimation { } pub trait RaylibModelAnimation: AsRef + AsMut { + /// Bones information (skeleton) + #[inline] fn bones(&self) -> &[BoneInfo] { unsafe { std::slice::from_raw_parts( @@ -680,6 +762,8 @@ pub trait RaylibModelAnimation: AsRef + AsMut &mut [BoneInfo] { unsafe { std::slice::from_raw_parts_mut( @@ -689,6 +773,7 @@ pub trait RaylibModelAnimation: AsRef + AsMut Vec<&[crate::math::Transform]> { let anim = self.as_ref(); let mut top = Vec::with_capacity(anim.frameCount as usize); @@ -709,6 +794,7 @@ pub trait RaylibModelAnimation: AsRef + AsMut Vec<&mut [crate::math::Transform]> { let anim = self.as_ref(); let mut top = Vec::with_capacity(anim.frameCount as usize); @@ -731,35 +817,50 @@ pub trait RaylibModelAnimation: AsRef + AsMut &crate::texture::WeakTexture2D { unsafe { std::mem::transmute(&self.0.texture) } } + /// Material map texture + #[inline] pub fn texture_mut(&mut self) -> &mut crate::texture::WeakTexture2D { unsafe { std::mem::transmute(&mut self.0.texture) } } + /// Material map color + #[inline] pub fn color(&self) -> &crate::color::Color { unsafe { std::mem::transmute(&self.0.color) } } + /// Material map color + #[inline] pub fn color_mut(&mut self) -> &mut crate::color::Color { unsafe { std::mem::transmute(&mut self.0.color) } } + /// Material map value + #[inline] pub fn value(&self) -> &f32 { unsafe { std::mem::transmute(&self.0.value) } } + /// Material map value + #[inline] pub fn value_mut(&mut self) -> &mut f32 { unsafe { std::mem::transmute(&mut self.0.value) } } } impl RaylibHandle { + /// Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps) + #[inline] 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) + #[inline] pub unsafe fn unload_material(&mut self, _: &RaylibThread, material: WeakMaterial) { { ffi::UnloadMaterial(*material.as_ref()) @@ -768,6 +869,7 @@ impl RaylibHandle { /// Weak models will leak memeory if they are not unlaoded /// Unload model from GPU memory (VRAM) + #[inline] pub unsafe fn unload_model(&mut self, _: &RaylibThread, model: WeakModel) { { ffi::UnloadModel(*model.as_ref()) @@ -776,6 +878,7 @@ impl RaylibHandle { /// Weak model_animations will leak memeory if they are not unlaoded /// Unload model_animation from GPU memory (VRAM) + #[inline] pub unsafe fn unload_model_animation( &mut self, _: &RaylibThread, @@ -788,6 +891,7 @@ impl RaylibHandle { /// Weak meshs will leak memeory if they are not unlaoded /// Unload mesh from GPU memory (VRAM) + #[inline] pub unsafe fn unload_mesh(&mut self, _: &RaylibThread, mesh: WeakMesh) { { ffi::UnloadMesh(*mesh.as_ref()) diff --git a/raylib/src/core/shaders.rs b/raylib/src/core/shaders.rs index 6aa96ce3..17a763d5 100644 --- a/raylib/src/core/shaders.rs +++ b/raylib/src/core/shaders.rs @@ -70,6 +70,7 @@ pub trait ShaderV { impl ShaderV for f32 { const UNIFORM_TYPE: ShaderUniformDataType = ShaderUniformDataType::SHADER_UNIFORM_FLOAT; + #[inline] unsafe fn value(&self) -> *const c_void { self as *const f32 as *const c_void } @@ -77,6 +78,7 @@ impl ShaderV for f32 { impl ShaderV for Vector2 { const UNIFORM_TYPE: ShaderUniformDataType = ShaderUniformDataType::SHADER_UNIFORM_VEC2; + #[inline] unsafe fn value(&self) -> *const c_void { self as *const Vector2 as *const c_void } @@ -84,6 +86,7 @@ impl ShaderV for Vector2 { impl ShaderV for Vector3 { const UNIFORM_TYPE: ShaderUniformDataType = ShaderUniformDataType::SHADER_UNIFORM_VEC3; + #[inline] unsafe fn value(&self) -> *const c_void { self as *const Vector3 as *const c_void } @@ -91,6 +94,7 @@ impl ShaderV for Vector3 { impl ShaderV for Vector4 { const UNIFORM_TYPE: ShaderUniformDataType = ShaderUniformDataType::SHADER_UNIFORM_VEC4; + #[inline] unsafe fn value(&self) -> *const c_void { self as *const Vector4 as *const c_void } @@ -98,6 +102,7 @@ impl ShaderV for Vector4 { impl ShaderV for i32 { const UNIFORM_TYPE: ShaderUniformDataType = ShaderUniformDataType::SHADER_UNIFORM_INT; + #[inline] unsafe fn value(&self) -> *const c_void { self as *const i32 as *const c_void } @@ -105,6 +110,7 @@ impl ShaderV for i32 { impl ShaderV for [i32; 2] { const UNIFORM_TYPE: ShaderUniformDataType = ShaderUniformDataType::SHADER_UNIFORM_IVEC2; + #[inline] unsafe fn value(&self) -> *const c_void { self.as_ptr() as *const c_void } @@ -112,6 +118,7 @@ impl ShaderV for [i32; 2] { impl ShaderV for [i32; 3] { const UNIFORM_TYPE: ShaderUniformDataType = ShaderUniformDataType::SHADER_UNIFORM_IVEC3; + #[inline] unsafe fn value(&self) -> *const c_void { self.as_ptr() as *const c_void } @@ -119,6 +126,7 @@ impl ShaderV for [i32; 3] { impl ShaderV for [i32; 4] { const UNIFORM_TYPE: ShaderUniformDataType = ShaderUniformDataType::SHADER_UNIFORM_IVEC4; + #[inline] unsafe fn value(&self) -> *const c_void { self.as_ptr() as *const c_void } @@ -126,6 +134,7 @@ impl ShaderV for [i32; 4] { impl ShaderV for [f32; 2] { const UNIFORM_TYPE: ShaderUniformDataType = ShaderUniformDataType::SHADER_UNIFORM_VEC2; + #[inline] unsafe fn value(&self) -> *const c_void { self.as_ptr() as *const c_void } @@ -133,6 +142,7 @@ impl ShaderV for [f32; 2] { impl ShaderV for [f32; 3] { const UNIFORM_TYPE: ShaderUniformDataType = ShaderUniformDataType::SHADER_UNIFORM_VEC3; + #[inline] unsafe fn value(&self) -> *const c_void { self.as_ptr() as *const c_void } @@ -140,6 +150,7 @@ impl ShaderV for [f32; 3] { impl ShaderV for [f32; 4] { const UNIFORM_TYPE: ShaderUniformDataType = ShaderUniformDataType::SHADER_UNIFORM_VEC4; + #[inline] unsafe fn value(&self) -> *const c_void { self.as_ptr() as *const c_void } @@ -147,6 +158,7 @@ impl ShaderV for [f32; 4] { impl ShaderV for &[i32] { const UNIFORM_TYPE: ShaderUniformDataType = ShaderUniformDataType::SHADER_UNIFORM_SAMPLER2D; + #[inline] unsafe fn value(&self) -> *const c_void { self.as_ptr() as *const c_void } @@ -217,11 +229,13 @@ impl RaylibShader for WeakShader {} impl RaylibShader for Shader {} pub trait RaylibShader: AsRef + AsMut { + /// Shader locations array (RL_MAX_SHADER_LOCATIONS) #[inline] fn locs(&self) -> &[i32] { unsafe { std::slice::from_raw_parts(self.as_ref().locs, 32) } } + /// Shader locations array (RL_MAX_SHADER_LOCATIONS) #[inline] fn locs_mut(&mut self) -> &mut [i32] { unsafe { std::slice::from_raw_parts_mut(self.as_mut().locs, 32) } @@ -254,7 +268,7 @@ pub trait RaylibShader: AsRef + AsMut { } } - /// et shader uniform value vector + /// Set shader uniform value vector #[inline] fn set_shader_value_v(&mut self, uniform_loc: i32, value: &[S]) { unsafe { diff --git a/raylib/src/core/text.rs b/raylib/src/core/text.rs index 9d2e77a1..36411a6d 100644 --- a/raylib/src/core/text.rs +++ b/raylib/src/core/text.rs @@ -15,9 +15,19 @@ use std::mem::ManuallyDrop; use std::ops::Deref; fn no_drop(_thing: T) {} -make_thin_wrapper!(Font, ffi::Font, ffi::UnloadFont); +make_thin_wrapper!( + /// Font, font texture and GlyphInfo array data + Font, + ffi::Font, + ffi::UnloadFont +); make_thin_wrapper!(WeakFont, ffi::Font, no_drop); -make_thin_wrapper!(GlyphInfo, ffi::GlyphInfo, no_drop); +make_thin_wrapper!( + /// GlyphInfo, font characters glyphs info + GlyphInfo, + ffi::GlyphInfo, + no_drop +); #[repr(transparent)] #[derive(Debug)] @@ -96,6 +106,7 @@ impl Drop for Codepoints { } impl RaylibHandle { + /// Load all codepoints from a UTF-8 text string, codepoints count returned by parameter pub(crate) fn load_codepoints(&mut self, text: &str) -> Codepoints { let ptr = CString::new(text).unwrap(); let mut len = 0; @@ -108,11 +119,14 @@ impl RaylibHandle { } } + /// Get total number of codepoints in a UTF-8 encoded string pub fn get_codepoint_count(text: &str) -> i32 { let ptr = CString::new(text).unwrap(); unsafe { ffi::GetCodepointCount(ptr.as_ptr()) } } + /// Unload font from GPU memory (VRAM) + #[inline] pub fn unload_font(&mut self, font: WeakFont) { unsafe { ffi::UnloadFont(font.0) }; } @@ -271,12 +285,18 @@ impl RaylibFont for WeakFont {} impl RaylibFont for Font {} pub trait RaylibFont: AsRef + AsMut { + /// Base size (default chars height) + #[inline] fn base_size(&self) -> i32 { self.as_ref().baseSize } + /// Texture atlas containing the glyphs + #[inline] fn texture(&self) -> &Texture2D { unsafe { std::mem::transmute(&self.as_ref().texture) } } + /// Glyphs info data + #[inline] fn chars(&self) -> &[GlyphInfo] { unsafe { std::slice::from_raw_parts( @@ -285,6 +305,8 @@ pub trait RaylibFont: AsRef + AsMut { ) } } + /// Glyphs info data + #[inline] fn chars_mut(&mut self) -> &mut [GlyphInfo] { unsafe { std::slice::from_raw_parts_mut( @@ -295,6 +317,7 @@ pub trait RaylibFont: AsRef + AsMut { } /// Check if a font is valid + #[inline] fn is_font_valid(&self) -> bool { unsafe { ffi::IsFontValid(*self.as_ref()) } } @@ -309,16 +332,19 @@ pub trait RaylibFont: AsRef + AsMut { } /// Get glyph font info data for a codepoint (unicode character), fallback to '?' if not found + #[inline] fn get_glyph_info(&self, codepoint: char) -> GlyphInfo { unsafe { GlyphInfo(ffi::GetGlyphInfo(*self.as_ref(), codepoint as i32)) } } /// Gets index position for a unicode character on `font`. + #[inline] fn get_glyph_index(&self, codepoint: char) -> i32 { unsafe { ffi::GetGlyphIndex(*self.as_ref(), codepoint as i32) } } /// Get glyph rectangle in font atlas for a codepoint (unicode character), fallback to '?' if not found + #[inline] fn get_glyph_atlas_rec(&self, codepoint: char) -> Rectangle { unsafe { ffi::GetGlyphAtlasRec(*self.as_ref(), codepoint as i32).into() } } @@ -433,6 +459,8 @@ impl RaylibHandle { unsafe { ffi::MeasureText(c_text.as_ptr(), font_size) } } + /// Set vertical line spacing when drawing with line-breaks + #[inline] pub fn set_text_line_spacing(&self, spacing: i32) { unsafe { ffi::SetTextLineSpacing(spacing) } } diff --git a/raylib/src/core/texture.rs b/raylib/src/core/texture.rs index cc2496fd..364b95f3 100644 --- a/raylib/src/core/texture.rs +++ b/raylib/src/core/texture.rs @@ -16,14 +16,21 @@ use super::math::Vector2; make_rslice!(ImagePalette, Color, ffi::UnloadImagePalette); make_rslice!(ImageColors, Color, ffi::UnloadImageColors); +/// NPatchInfo, n-patch layout info #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct NPatchInfo { + /// Texture source rectangle pub source: Rectangle, + /// Left border offset pub left: i32, + /// Top border offset pub top: i32, + /// Right border offset pub right: i32, + /// Bottom border offset pub bottom: i32, + /// Layout of the n-patch: 3x3, 1x3 or 3x1 pub layout: crate::consts::NPatchLayout, } @@ -53,10 +60,21 @@ impl Into for &NPatchInfo { } fn no_drop(_thing: T) {} -make_thin_wrapper!(Image, ffi::Image, ffi::UnloadImage); -make_thin_wrapper!(Texture2D, ffi::Texture2D, ffi::UnloadTexture); +make_thin_wrapper!( + /// Image, pixel data stored in CPU memory (RAM) + Image, + ffi::Image, + ffi::UnloadImage +); +make_thin_wrapper!( + /// Texture, tex data stored in GPU memory (VRAM) + Texture2D, + ffi::Texture2D, + ffi::UnloadTexture +); make_thin_wrapper!(WeakTexture2D, ffi::Texture2D, no_drop); make_thin_wrapper!( + /// RenderTexture, fbo for texture rendering RenderTexture2D, ffi::RenderTexture2D, ffi::UnloadRenderTexture @@ -81,24 +99,28 @@ impl RaylibRenderTexture2D for WeakRenderTexture2D {} impl RaylibRenderTexture2D for RenderTexture2D {} impl AsRef for RenderTexture2D { + #[inline] fn as_ref(&self) -> &ffi::Texture2D { self.texture() } } impl AsMut for RenderTexture2D { + #[inline] fn as_mut(&mut self) -> &mut ffi::Texture2D { self.texture_mut() } } impl AsRef for WeakRenderTexture2D { + #[inline] fn as_ref(&self) -> &ffi::Texture2D { self.texture() } } impl AsMut for WeakRenderTexture2D { + #[inline] fn as_mut(&mut self) -> &mut ffi::Texture2D { self.texture_mut() } @@ -111,58 +133,79 @@ impl RenderTexture2D { m } + /// Check if a render texture is valid (loaded in GPU) + #[inline] pub fn is_render_texture_valid(&self) -> bool { unsafe { ffi::IsRenderTextureValid(self.0) } } } pub trait RaylibRenderTexture2D: AsRef + AsMut { + /// OpenGL framebuffer object id + #[inline] fn id(&self) -> u32 { self.as_ref().id } + /// Color buffer attachment texture + #[inline] fn texture(&self) -> &WeakTexture2D { unsafe { std::mem::transmute(&self.as_ref().texture) } } + /// Color buffer attachment texture + #[inline] fn texture_mut(&mut self) -> &mut WeakTexture2D { unsafe { std::mem::transmute(&mut self.as_mut().texture) } } } impl Clone for Image { + /// Create an image duplicate (useful for transformations) fn clone(&self) -> Image { unsafe { Image(ffi::ImageCopy(self.0)) } } } impl Image { + /// Image base width + #[inline] pub fn width(&self) -> i32 { self.0.width } + /// Image base height + #[inline] pub fn height(&self) -> i32 { self.0.height } + /// Mipmap levels, 1 by default + #[inline] pub fn mipmaps(&self) -> i32 { self.0.mipmaps } + /// Image raw data + #[inline] pub unsafe fn data(&self) -> *mut ::std::os::raw::c_void { self.0.data } /// Apply Gaussian blur using a box blur approximation + #[inline] pub fn blur_gaussian(&mut self, blur_size: i32) { unsafe { ffi::ImageBlurGaussian(&mut self.0, blur_size) } } /// Rotate image by input angle in degrees (-359 to 359) + #[inline] pub fn rotate(&mut self, degrees: i32) { unsafe { ffi::ImageRotate(&mut self.0, degrees) } } /// Get image pixel color at (x, y) position + #[inline] pub fn get_color(&self, x: i32, y: i32) -> Color { Color::from(unsafe { ffi::GetImageColor(self.0, x, y) }) } /// Draw circle outline within an image + #[inline] pub fn draw_circle_lines( &mut self, center_x: i32, @@ -173,6 +216,7 @@ impl Image { unsafe { ffi::ImageDrawCircleLines(&mut self.0, center_x, center_y, radius, color.into()) } } /// Draw circle outline within an image (Vector version) + #[inline] pub fn draw_circle_lines_v( &mut self, center: crate::prelude::Vector2, @@ -182,17 +226,21 @@ impl Image { unsafe { ffi::ImageDrawCircleLinesV(&mut self.0, center.into(), center_y, color.into()) } } + /// Data format (PixelFormat type) #[inline] pub fn format(&self) -> crate::consts::PixelFormat { let i: u32 = self.format as u32; unsafe { std::mem::transmute(i) } } + /// Create an image from another image piece #[inline] pub fn from_image(&self, rec: impl Into) -> Image { unsafe { Image(ffi::ImageFromImage(self.0, rec.into())) } } + /// Create an image from a selected channel of another image (GRAYSCALE) + #[inline] pub fn from_channel(&self, selected_channel: i32) -> Image { unsafe { Image(ffi::ImageFromChannel(self.0, selected_channel)) } } @@ -215,6 +263,7 @@ impl Image { } /// Get pixel data size in bytes (image or texture) + #[inline] pub fn get_pixel_data_size(&self) -> usize { unsafe { ffi::GetPixelDataSize(self.width(), self.height(), self.format() as i32) as usize } } @@ -426,6 +475,7 @@ impl Image { } /// Draw a line (using triangles/quads) + #[inline] pub fn draw_line_ex( &mut self, start_pos: impl Into, @@ -456,6 +506,7 @@ impl Image { } /// Draw triangle within an image + #[inline] pub fn draw_triangle( &mut self, v1: impl Into, @@ -469,6 +520,7 @@ impl Image { } /// Draw triangle with interpolated colors within an image + #[inline] pub fn draw_triangle_ex( &mut self, v1: impl Into, @@ -492,6 +544,7 @@ impl Image { } /// Draw triangle outline within an image + #[inline] pub fn draw_triangle_lines( &mut self, v1: impl Into, @@ -575,6 +628,7 @@ impl Image { } /// Draw rectangle within an image (Vector version) + #[inline] pub fn draw_rectangle_v( &mut self, position: impl Into, @@ -587,6 +641,7 @@ impl Image { } /// Draw rectangle within an image (Rectangle version) + #[inline] pub fn draw_rectangle_rec( &mut self, rectangle: impl Into, @@ -1016,6 +1071,8 @@ impl Image { } } + /// Check if an image is valid (data and parameters) + #[inline] pub fn is_image_valid(&self) -> bool { unsafe { ffi::IsImageValid(self.0) } } @@ -1035,18 +1092,26 @@ impl Texture2D { } pub trait RaylibTexture2D: AsRef + AsMut { + /// Texture base width + #[inline] fn width(&self) -> i32 { self.as_ref().width } + /// Texture base height + #[inline] fn height(&self) -> i32 { self.as_ref().height } + /// Mipmap levels, 1 by default + #[inline] fn mipmaps(&self) -> i32 { self.as_ref().width } + /// Data format (PixelFormat type) + #[inline] fn format(&self) -> i32 { self.as_ref().format } @@ -1085,7 +1150,7 @@ pub trait RaylibTexture2D: AsRef + AsMut { pixels: &[u8], ) -> Result<(), Error> { let rec = rec.into(); - + if (rec.x < 0.0) || (rec.y < 0.0) || ((rec.x as i32 + rec.width as i32) > (self.as_ref().width)) || ((rec.y as i32 + rec.height as i32) > (self.as_ref().height)) { return Err(error!( "update_texture: Destination rectangle cannot exceed texture bounds." @@ -1096,7 +1161,7 @@ pub trait RaylibTexture2D: AsRef + AsMut { "update_texture: Destination rectangle cannot have negative extents." )); } - + let expected_len = unsafe { get_pixel_data_size( rec.width as i32, @@ -1157,6 +1222,8 @@ pub trait RaylibTexture2D: AsRef + AsMut { } } + /// Check if a texture is valid (loaded in GPU) + #[inline] fn is_texture_valid(&self) -> bool { unsafe { ffi::IsTextureValid(*self.as_ref()) } } @@ -1225,6 +1292,7 @@ impl RaylibHandle { impl RaylibHandle { /// Weak Textures will leak memeory if they are not unlaoded /// Unload textures from GPU memory (VRAM) + #[inline] pub unsafe fn unload_texture(&mut self, _: &RaylibThread, texture: WeakTexture2D) { { ffi::UnloadTexture(*texture.as_ref()) @@ -1232,6 +1300,7 @@ impl RaylibHandle { } /// Weak RenderTextures will leak memeory if they are not unlaoded /// Unload RenderTextures from GPU memory (VRAM) + #[inline] pub unsafe fn unload_render_texture(&mut self, _: &RaylibThread, texture: WeakRenderTexture2D) { { ffi::UnloadRenderTexture(*texture.as_ref()) diff --git a/raylib/src/core/vr.rs b/raylib/src/core/vr.rs index 8dac85c3..42844d12 100644 --- a/raylib/src/core/vr.rs +++ b/raylib/src/core/vr.rs @@ -1,25 +1,36 @@ -//! Vr related functions +//! VR related functions use crate::core::{RaylibHandle, RaylibThread}; use crate::ffi; make_thin_wrapper!( + /// VrStereoConfig, VR stereo rendering configuration for simulator VrStereoConfig, ffi::VrStereoConfig, ffi::UnloadVrStereoConfig ); +/// VrDeviceInfo, Head-Mounted-Display device parameters #[repr(C)] #[derive(Debug, Copy, Clone, PartialEq)] pub struct VrDeviceInfo { - pub h_resolution: i32, // Horizontal resolution in pixels - pub v_esolution: i32, // Vertical resolution in pixels - pub h_screen_size: f32, // Horizontal size in meters - pub v_screen_size: f32, // Vertical size in meters - pub eye_to_screen_distance: f32, // Distance between eye and display in meters - pub lens_separation_distance: f32, // Lens separation distance in meters - pub interpupillary_distance: f32, // IPD (distance between pupils) in meters - pub lens_distortion_values: [f32; 4], // Lens distortion constant parameters - pub chroma_ab_correction: [f32; 4], // Chromatic aberration correction parameters + /// Horizontal resolution in pixels + pub h_resolution: i32, + /// Vertical resolution in pixels + pub v_esolution: i32, + /// Horizontal size in meters + pub h_screen_size: f32, + /// Vertical size in meters + pub v_screen_size: f32, + /// Distance between eye and display in meters + pub eye_to_screen_distance: f32, + /// Lens separation distance in meters + pub lens_separation_distance: f32, + /// IPD (distance between pupils) in meters + pub interpupillary_distance: f32, + /// Lens distortion constant parameters + pub lens_distortion_values: [f32; 4], + /// Chromatic aberration correction parameters + pub chroma_ab_correction: [f32; 4], } impl From for VrDeviceInfo { @@ -45,12 +56,14 @@ impl Into for &VrDeviceInfo { lensSeparationDistance: self.lens_separation_distance, // Lens separation distance in meters interpupillaryDistance: self.interpupillary_distance, // IPD (distance between pupils) in meters lensDistortionValues: self.lens_distortion_values, // Lens distortion constant parameters - chromaAbCorrection: self.chroma_ab_correction, + chromaAbCorrection: self.chroma_ab_correction, // Chromatic aberration correction parameters } } } impl RaylibHandle { + /// Load VR stereo config for VR simulator device parameters + #[inline] pub fn load_vr_stereo_config( &mut self, _: &RaylibThread, diff --git a/raylib/src/core/window.rs b/raylib/src/core/window.rs index 7f4fb27a..d02d4ba4 100644 --- a/raylib/src/core/window.rs +++ b/raylib/src/core/window.rs @@ -8,7 +8,7 @@ use std::os::raw::c_char; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; -// MonitorInfo grabs the sizes (virtual and physical) of your monitor +/// MonitorInfo grabs the sizes (virtual and physical) of your monitor #[derive(Clone, Debug)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct MonitorInfo { @@ -25,11 +25,12 @@ pub struct MonitorInfo { pub struct WindowState(i32); impl WindowState { - pub fn vsync_hint(&self) -> bool { + /// Whether to try enabling V-Sync on GPU + pub const fn vsync_hint(&self) -> bool { self.0 & (ffi::ConfigFlags::FLAG_VSYNC_HINT as i32) != 0 } /// Set to try enabling V-Sync on GPU - pub fn set_vsync_hint(mut self, enabled: bool) -> Self { + pub const fn set_vsync_hint(mut self, enabled: bool) -> Self { if enabled { // set the bit self.0 |= ffi::ConfigFlags::FLAG_VSYNC_HINT as i32; @@ -40,11 +41,12 @@ impl WindowState { self } - pub fn fullscreen_mode(&self) -> bool { + /// Whether to run program in fullscreen + pub const fn fullscreen_mode(&self) -> bool { self.0 & (ffi::ConfigFlags::FLAG_FULLSCREEN_MODE as i32) != 0 } /// Set to run program in fullscreen - pub fn set_fullscreen_mode(mut self, enabled: bool) -> Self { + pub const fn set_fullscreen_mode(mut self, enabled: bool) -> Self { if enabled { // set the bit self.0 |= ffi::ConfigFlags::FLAG_FULLSCREEN_MODE as i32; @@ -55,11 +57,12 @@ impl WindowState { self } - pub fn window_resizable(&self) -> bool { + /// Whether to allow resizable window + pub const fn window_resizable(&self) -> bool { self.0 & (ffi::ConfigFlags::FLAG_WINDOW_RESIZABLE as i32) != 0 } /// Set to allow resizable window - pub fn set_window_resizable(mut self, enabled: bool) -> Self { + pub const fn set_window_resizable(mut self, enabled: bool) -> Self { if enabled { // set the bit self.0 |= ffi::ConfigFlags::FLAG_WINDOW_RESIZABLE as i32; @@ -70,11 +73,12 @@ impl WindowState { self } - pub fn window_undecorated(&self) -> bool { + /// Whether to disable window decoration (frame and buttons) + pub const fn window_undecorated(&self) -> bool { self.0 & (ffi::ConfigFlags::FLAG_WINDOW_UNDECORATED as i32) != 0 } /// Set to disable window decoration (frame and buttons) - pub fn set_window_undecorated(mut self, enabled: bool) -> Self { + pub const fn set_window_undecorated(mut self, enabled: bool) -> Self { if enabled { // set the bit self.0 |= ffi::ConfigFlags::FLAG_WINDOW_UNDECORATED as i32; @@ -85,11 +89,12 @@ impl WindowState { self } - pub fn window_hidden(&self) -> bool { + /// Whether to hide window + pub const fn window_hidden(&self) -> bool { self.0 & (ffi::ConfigFlags::FLAG_WINDOW_HIDDEN as i32) != 0 } /// Set to hide window - pub fn set_window_hidden(mut self, enabled: bool) -> Self { + pub const fn set_window_hidden(mut self, enabled: bool) -> Self { if enabled { // set the bit self.0 |= ffi::ConfigFlags::FLAG_WINDOW_HIDDEN as i32; @@ -100,11 +105,12 @@ impl WindowState { self } - pub fn window_minimized(&self) -> bool { + /// Whether to minimize window (iconify) + pub const fn window_minimized(&self) -> bool { self.0 & (ffi::ConfigFlags::FLAG_WINDOW_MINIMIZED as i32) != 0 } /// Set to minimize window (iconify) - pub fn set_window_minimized(mut self, enabled: bool) -> Self { + pub const fn set_window_minimized(mut self, enabled: bool) -> Self { if enabled { // set the bit self.0 |= ffi::ConfigFlags::FLAG_WINDOW_MINIMIZED as i32; @@ -115,11 +121,12 @@ impl WindowState { self } - pub fn window_maximized(&self) -> bool { + /// Whether to maximize window (expanded to monitor) + pub const fn window_maximized(&self) -> bool { self.0 & (ffi::ConfigFlags::FLAG_WINDOW_MAXIMIZED as i32) != 0 } /// Set to maximize window (expanded to monitor) - pub fn set_window_maximized(mut self, enabled: bool) -> Self { + pub const fn set_window_maximized(mut self, enabled: bool) -> Self { if enabled { // set the bit self.0 |= ffi::ConfigFlags::FLAG_WINDOW_MAXIMIZED as i32; @@ -130,11 +137,12 @@ impl WindowState { self } - pub fn window_unfocused(&self) -> bool { + /// Whether to window non focused + pub const fn window_unfocused(&self) -> bool { self.0 & (ffi::ConfigFlags::FLAG_WINDOW_UNFOCUSED as i32) != 0 } /// Set to window non focused - pub fn set_window_unfocused(mut self, enabled: bool) -> Self { + pub const fn set_window_unfocused(mut self, enabled: bool) -> Self { if enabled { // set the bit self.0 |= ffi::ConfigFlags::FLAG_WINDOW_UNFOCUSED as i32; @@ -145,11 +153,12 @@ impl WindowState { self } - pub fn window_topmost(&self) -> bool { + /// Whether to window always on top + pub const fn window_topmost(&self) -> bool { self.0 & (ffi::ConfigFlags::FLAG_WINDOW_TOPMOST as i32) != 0 } /// Set to window always on top - pub fn set_window_topmost(mut self, enabled: bool) -> Self { + pub const fn set_window_topmost(mut self, enabled: bool) -> Self { if enabled { // set the bit self.0 |= ffi::ConfigFlags::FLAG_WINDOW_TOPMOST as i32; @@ -160,11 +169,12 @@ impl WindowState { self } - pub fn window_always_run(&self) -> bool { + /// Whether to allow windows running while minimized + pub const fn window_always_run(&self) -> bool { self.0 & (ffi::ConfigFlags::FLAG_WINDOW_ALWAYS_RUN as i32) != 0 } /// Set to allow windows running while minimized - pub fn set_window_always_run(mut self, enabled: bool) -> Self { + pub const fn set_window_always_run(mut self, enabled: bool) -> Self { if enabled { // set the bit self.0 |= ffi::ConfigFlags::FLAG_WINDOW_ALWAYS_RUN as i32; @@ -175,11 +185,12 @@ impl WindowState { self } - pub fn window_transparent(&self) -> bool { + /// Whether to allow transparent framebuffer + pub const fn window_transparent(&self) -> bool { self.0 & (ffi::ConfigFlags::FLAG_WINDOW_TRANSPARENT as i32) != 0 } /// Set to allow transparent framebuffer - pub fn set_window_transparent(mut self, enabled: bool) -> Self { + pub const fn set_window_transparent(mut self, enabled: bool) -> Self { if enabled { // set the bit self.0 |= ffi::ConfigFlags::FLAG_WINDOW_TRANSPARENT as i32; @@ -190,11 +201,12 @@ impl WindowState { self } - pub fn window_highdpi(&self) -> bool { + /// Whether to support HighDPI + pub const fn window_highdpi(&self) -> bool { self.0 & (ffi::ConfigFlags::FLAG_WINDOW_HIGHDPI as i32) != 0 } /// Set to support HighDPI - pub fn set_window_highdpi(mut self, enabled: bool) -> Self { + pub const fn set_window_highdpi(mut self, enabled: bool) -> Self { if enabled { // set the bit self.0 |= ffi::ConfigFlags::FLAG_WINDOW_HIGHDPI as i32; @@ -205,11 +217,12 @@ impl WindowState { self } - pub fn msaa(&self) -> bool { + /// Whether to try enabling MSAA 4X + pub const fn msaa(&self) -> bool { self.0 & (ffi::ConfigFlags::FLAG_MSAA_4X_HINT as i32) != 0 } /// Set to try enabling MSAA 4X - pub fn set_msaa(mut self, enabled: bool) -> Self { + pub const fn set_msaa(mut self, enabled: bool) -> Self { if enabled { // set the bit self.0 |= ffi::ConfigFlags::FLAG_MSAA_4X_HINT as i32; @@ -220,11 +233,12 @@ impl WindowState { self } - pub fn interlaced_hint(&self) -> bool { + /// Whether to try enabling interlaced video format (for V3D) + pub const fn interlaced_hint(&self) -> bool { self.0 & (ffi::ConfigFlags::FLAG_INTERLACED_HINT as i32) != 0 } /// Set to try enabling interlaced video format (for V3D) - pub fn set_interlaced_hint(mut self, enabled: bool) -> Self { + pub const fn set_interlaced_hint(mut self, enabled: bool) -> Self { if enabled { // set the bit self.0 |= ffi::ConfigFlags::FLAG_INTERLACED_HINT as i32; @@ -242,13 +256,13 @@ pub fn get_monitor_count() -> i32 { unsafe { ffi::GetMonitorCount() } } -// Get current connected monitor +/// Get current connected monitor #[inline] pub fn get_current_monitor() -> i32 { unsafe { ffi::GetCurrentMonitor() } } -// Get current connected monitor +/// Get current connected monitor #[inline] pub fn get_current_monitor_index() -> i32 { unsafe { ffi::GetCurrentMonitor() } @@ -413,6 +427,7 @@ impl RaylibHandle { // Screen-space-related functions impl RaylibHandle { /// Get a ray trace from screen position (i.e mouse) + #[inline] pub fn get_screen_to_world_ray( &self, mouse_position: impl Into, @@ -422,6 +437,7 @@ impl RaylibHandle { } /// Get a ray trace from screen position (i.e mouse) in a viewport + #[inline] pub fn get_screen_to_world_ray_ex( &self, mouse_position: impl Into, @@ -435,6 +451,7 @@ impl RaylibHandle { } /// Returns the screen space position for a 3d world space position + #[inline] pub fn get_world_to_screen( &self, position: impl Into, @@ -445,6 +462,7 @@ impl RaylibHandle { /// Returns the screen space position for a 2d camera world space position #[allow(non_snake_case)] + #[inline] pub fn get_world_to_screen2D( &self, position: impl Into, @@ -454,6 +472,7 @@ impl RaylibHandle { } /// Returns size position for a 3d world space position + #[inline] pub fn get_world_to_screen_ex( &self, position: impl Into, @@ -466,6 +485,7 @@ impl RaylibHandle { /// Returns the world space position for a 2d camera screen space position #[allow(non_snake_case)] + #[inline] pub fn get_screen_to_world2D( &self, position: impl Into, @@ -478,6 +498,7 @@ impl RaylibHandle { // Timing related functions impl RaylibHandle { /// Set target FPS (maximum) + #[inline] pub fn set_target_fps(&mut self, fps: u32) { unsafe { ffi::SetTargetFPS(fps as i32); @@ -485,16 +506,19 @@ impl RaylibHandle { } /// Returns current FPS + #[inline] pub fn get_fps(&self) -> u32 { unsafe { ffi::GetFPS() as u32 } } /// Returns time in seconds for last frame drawn + #[inline] pub fn get_frame_time(&self) -> f32 { unsafe { ffi::GetFrameTime() } } /// Returns elapsed time in seconds since InitWindow() + #[inline] pub fn get_time(&self) -> f64 { unsafe { ffi::GetTime() } } @@ -563,7 +587,7 @@ impl RaylibHandle { unsafe { ffi::IsWindowFullscreen() } } - // Check if window is currently focused (only PLATFORM_DESKTOP) + /// Check if window is currently focused (only PLATFORM_DESKTOP) #[inline] pub fn is_window_focused(&self) -> bool { unsafe { ffi::IsWindowFocused() } @@ -596,11 +620,13 @@ impl RaylibHandle { } /// Set window configuration state using flags + #[inline] pub fn set_window_state(&mut self, state: WindowState) { unsafe { ffi::SetWindowState(state.0 as u32) } } /// Clear window configuration state flags + #[inline] pub fn clear_window_state(&mut self, state: WindowState) { unsafe { ffi::ClearWindowState(state.0 as u32) } } @@ -664,6 +690,7 @@ impl RaylibHandle { } } + /// Set icon for window (multiple images, RGBA 32bit) #[inline] pub fn set_window_icons(&mut self, images: &mut [raylib_sys::Image]) { use std::convert::TryInto; @@ -757,12 +784,14 @@ impl RaylibHandle { unsafe { ffi::GetWindowPosition().into() } } - // Toggle window state: borderless windowed (only on desktop platforms). + /// Toggle window state: borderless windowed (only on desktop platforms). + #[inline] pub fn toggle_borderless_windowed(&self) { unsafe { ffi::ToggleBorderlessWindowed() } } - // Focus the window (only on desktop platforms) + /// Focus the window (only on desktop platforms) + #[inline] pub fn set_window_focused(&self) { unsafe { ffi::SetWindowFocused() } } @@ -816,20 +845,23 @@ impl RaylibHandle { } // Advanced "frame control" functions. +// NOTE: Those functions are intended for advanced users that want full control over the frame processing +// By default EndDrawing() does this job: draws everything + SwapScreenBuffer() + manage frame timing + PollInputEvents() +// To avoid that behaviour and control frame processes manually, enable in config.h: SUPPORT_CUSTOM_FRAME_CONTROL +#[cfg(feature = "custom_frame_control")] impl RaylibHandle { - #[cfg(feature = "custom_frame_control")] /// Swap back buffer with front buffer (screen drawing) /// This function, by default, is already done when the handle is dropped. pub fn swap_screen_buffer(&self) { unsafe { ffi::SwapScreenBuffer() } } - #[cfg(feature = "custom_frame_control")] + /// Register all input events pub fn poll_input_events(&self) { unsafe { ffi::PollInputEvents() } } - #[cfg(feature = "custom_frame_control")] + /// Wait for some time (halt program execution) pub fn wait_time(&self, seconds: f64) { unsafe { ffi::WaitTime(seconds) } } From 4d53bd49af9a437433b7dff92b38cb06831351df Mon Sep 17 00:00:00 2001 From: Amy Wilder <74995093+AmityWilder@users.noreply.github.com> Date: Fri, 11 Apr 2025 20:20:46 -0400 Subject: [PATCH 92/93] Fix lifetime mistake (#176) Co-authored-by: IoIxD <30945097+IoIxD@users.noreply.github.com> --- raylib/src/core/audio.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/raylib/src/core/audio.rs b/raylib/src/core/audio.rs index 8fc00186..fddc0185 100644 --- a/raylib/src/core/audio.rs +++ b/raylib/src/core/audio.rs @@ -649,10 +649,8 @@ impl<'aud> AudioStream<'aud> { } } -impl<'bind> Sound<'_> { - /// Clone sound from existing sound data, clone does not own wave data - // NOTE: Wave data must be unallocated manually and will be shared across all clones - pub fn alias<'snd>(&'snd self) -> Result, Error> { +impl<'bind> Sound<'bind> { + pub fn alias<'snd>(&'snd self) -> Result, Error> { let s = unsafe { ffi::LoadSoundAlias(self.0) }; if s.stream.buffer.is_null() { return Err(error!("failed to load sound from wave")); From 93dde6b90bb75f937229f59203317e270eda4b7c Mon Sep 17 00:00:00 2001 From: Amy Wilder <74995093+AmityWilder@users.noreply.github.com> Date: Sat, 12 Apr 2025 01:22:27 -0400 Subject: [PATCH 93/93] Better errors (#173) * Make errors more helpful in audio.rs * Finish audio errors * Add errors for data.rs * Add font and model errors * Add errors for texture.rs * Move error types into error.rs * Import texture error types * Add RaylibError type * Improve context of some errors --- raylib/src/core/audio.rs | 80 ++++++++------- raylib/src/core/data.rs | 33 +++--- raylib/src/core/error.rs | 204 +++++++++++++++++++++++++++++-------- raylib/src/core/models.rs | 30 +++--- raylib/src/core/text.rs | 30 ++---- raylib/src/core/texture.rs | 102 +++++++++---------- 6 files changed, 291 insertions(+), 188 deletions(-) diff --git a/raylib/src/core/audio.rs b/raylib/src/core/audio.rs index fddc0185..fe7f8352 100644 --- a/raylib/src/core/audio.rs +++ b/raylib/src/core/audio.rs @@ -1,11 +1,12 @@ //! Contains code related to audio. [`RaylibAudio`] plays sounds and music. -use crate::error::{error, Error}; -use crate::ffi; -use std::ffi::CString; +use crate::{ffi, error::{AudioInitError, LoadSoundError}}; +use std::ffi::{CStr, CString}; use std::marker::PhantomData; use std::path::Path; +use super::error::ExportWaveError; + make_thin_wrapper_lifetime!( /// Wave, audio wave data Wave, @@ -57,21 +58,6 @@ impl AudioSample for u8 {} impl AudioSample for i16 {} impl AudioSample for f32 {} -pub struct RaylibAudioInitError; - -impl std::fmt::Debug for RaylibAudioInitError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("RaylibAudio cannot be instantiated more then once at a time.") - } -} -impl std::fmt::Display for RaylibAudioInitError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("RaylibAudio cannot be instantiated more then once at a time.") - } -} - -impl std::error::Error for RaylibAudioInitError {} - /// This token is used to indicate audio is initialized. It's also used to create [`Wave`], [`Sound`], [`Music`], [`AudioStream`], and [`SoundAlias`]. /// All of those have a lifetime that is bound to RaylibAudio. The compiler will disallow you from using them without ensuring that the [`RaylibAudio`] is present while doing so. #[derive(Debug, Clone)] @@ -80,12 +66,15 @@ pub struct RaylibAudio(PhantomData<()>); impl RaylibAudio { /// Initializes audio device and context. #[inline] - pub fn init_audio_device() -> Result { + pub fn init_audio_device() -> Result { unsafe { if ffi::IsAudioDeviceReady() { - return Err(RaylibAudioInitError); + return Err(AudioInitError::DoubleInit); } ffi::InitAudioDevice(); + if !ffi::IsAudioDeviceReady() { + return Err(AudioInitError::InitFailed); + } } Ok(RaylibAudio(PhantomData)) } @@ -118,11 +107,11 @@ impl RaylibAudio { /// Loads a new sound from file. #[inline] - pub fn new_sound<'aud>(&'aud self, filename: &str) -> Result, Error> { + pub fn new_sound<'aud>(&'aud self, filename: &str) -> Result, LoadSoundError> { let c_filename = CString::new(filename).unwrap(); let s = unsafe { ffi::LoadSound(c_filename.as_ptr()) }; if s.stream.buffer.is_null() { - return Err(error!("failed to load sound", filename)); + return Err(LoadSoundError::LoadFailed { path: filename.into() }); } Ok(Sound(s, self)) @@ -130,20 +119,20 @@ impl RaylibAudio { /// Loads sound from wave data. #[inline] - pub fn new_sound_from_wave<'aud>(&'aud self, wave: &Wave) -> Result, Error> { + pub fn new_sound_from_wave<'aud>(&'aud self, wave: &Wave) -> Result, LoadSoundError> { let s = unsafe { ffi::LoadSoundFromWave(wave.0) }; if s.stream.buffer.is_null() { - return Err(error!("failed to load sound from wave")); + return Err(LoadSoundError::LoadFromWaveFailed); } Ok(Sound(s, self)) } /// Loads wave data from file into RAM. #[inline] - pub fn new_wave<'aud>(&'aud self, filename: &str) -> Result, Error> { + pub fn new_wave<'aud>(&'aud self, filename: &str) -> Result, LoadSoundError> { let c_filename = CString::new(filename).unwrap(); let w = unsafe { ffi::LoadWave(c_filename.as_ptr()) }; if w.data.is_null() { - return Err(error!("Cannot load wave {}", filename)); + return Err(LoadSoundError::LoadWaveFromFileFailed { path: filename.into() }); } Ok(Wave(w, self)) } @@ -154,24 +143,24 @@ impl RaylibAudio { &'aud self, filetype: &str, bytes: &[u8], - ) -> Result, Error> { + ) -> Result, LoadSoundError> { let c_filetype = CString::new(filetype).unwrap(); let w = unsafe { ffi::LoadWaveFromMemory(c_filetype.as_ptr(), bytes.as_ptr(), bytes.len() as i32) }; if w.data.is_null() { - return Err(error!("Wave data is null. Check provided buffer data")); + return Err(LoadSoundError::Null); }; Ok(Wave(w, self)) } /// Loads music stream from file. #[inline] - pub fn new_music<'aud>(&'aud self, filename: &str) -> Result, Error> { + pub fn new_music<'aud>(&'aud self, filename: &str) -> Result, LoadSoundError> { let c_filename = CString::new(filename).unwrap(); let m = unsafe { ffi::LoadMusicStream(c_filename.as_ptr()) }; if m.stream.buffer.is_null() { - return Err(error!("music could not be loaded from file", filename)); + return Err(LoadSoundError::LoadMusicFromFileFailed { path: filename.into() }); } Ok(Music(m, self)) } @@ -182,15 +171,13 @@ impl RaylibAudio { &'aud self, filetype: &str, bytes: &Vec, - ) -> Result, Error> { + ) -> Result, LoadSoundError> { let c_filetype = CString::new(filetype).unwrap(); let w = unsafe { ffi::LoadMusicStreamFromMemory(c_filetype.as_ptr(), bytes.as_ptr(), bytes.len() as i32) }; if w.stream.buffer.is_null() { - return Err(error!( - "Music's buffer data data is null. Check provided buffer data" - )); + return Err(LoadSoundError::MusicNull); }; Ok(Music(w, self)) } @@ -253,9 +240,24 @@ impl<'aud> Wave<'aud> { /// Export wave file. Extension must be .wav or .raw #[inline] - pub fn export(&self, filename: impl AsRef) -> bool { + pub fn export(&self, filename: impl AsRef) -> Result<(), ExportWaveError> { let c_filename = CString::new(filename.as_ref().to_string_lossy().as_bytes()).unwrap(); - unsafe { ffi::ExportWave(self.0, c_filename.as_ptr()) } + let success = unsafe { ffi::ExportWave(self.0, c_filename.as_ptr()) }; + if success { + Ok(()) + } else { + // const WAV: &CStr = unsafe { CStr::from_bytes_with_nul_unchecked(b".wav\0") }; + const QOA: &CStr = unsafe { CStr::from_bytes_with_nul_unchecked(b".qoa\0") }; + // const RAW: &CStr = unsafe { CStr::from_bytes_with_nul_unchecked(b".raw\0") }; + let is_qoa = unsafe { ffi::IsFileExtension(c_filename.as_ptr(), QOA.as_ptr()) }; + if is_qoa { + let samples = self.0.sampleSize as i32; + if samples != 16 { + return Err(ExportWaveError::QoaBadSamples(self.0.sampleSize as i32)); + } + } + Err(ExportWaveError::ExportFailed) + } } /*/// Export wave sample data to code (.h) @@ -650,10 +652,12 @@ impl<'aud> AudioStream<'aud> { } impl<'bind> Sound<'bind> { - pub fn alias<'snd>(&'snd self) -> Result, Error> { + /// Clone sound from existing sound data, clone does not own wave data + // NOTE: Wave data must be unallocated manually and will be shared across all clones + pub fn alias<'snd>(&'snd self) -> Result, LoadSoundError> { let s = unsafe { ffi::LoadSoundAlias(self.0) }; if s.stream.buffer.is_null() { - return Err(error!("failed to load sound from wave")); + return Err(LoadSoundError::LoadFromWaveFailed); } Ok(SoundAlias(s, PhantomData)) } diff --git a/raylib/src/core/data.rs b/raylib/src/core/data.rs index 720ee119..c4efdd86 100644 --- a/raylib/src/core/data.rs +++ b/raylib/src/core/data.rs @@ -3,10 +3,7 @@ use std::{ alloc::Layout, ffi::{c_char, CString}, ops::{Deref, DerefMut}, path::Path, ptr::NonNull }; -use crate::{ - error::{error, Error}, - ffi, -}; +use crate::{ffi, error::{AllocationError, CompressionError}}; /// A wrapper acting as an owned buffer for Raylib-allocated memory. /// Automatically releases the memory with [`ffi::MemFree()`] when dropped. @@ -115,22 +112,22 @@ impl DataBuf { /// # Panics /// /// This method may panic if the pointer returned by [`ffi::MemAlloc`] is unaligned. - pub fn alloc(count: i32) -> Result { + pub fn alloc(count: i32) -> Result { if count >= 1 { let count = count as usize; match Layout::array::(count) { - Err(_e) => Err(error!("memory request does not produce a valid layout")), // I would like to display `e` if possible + Err(_e) => Err(AllocationError::InvalidLayout), // I would like to display `e` if possible Ok(layout) => { let size = layout.size(); if size <= u32::MAX as usize { if let Some(buf) = NonNull::new(unsafe { ffi::MemAlloc(size as u32) }.cast()) { assert!(buf.is_aligned(), "allocated buffer should always be aligned"); Ok(Self { buf, len: count }) - } else { Err(error!("memory request exceeds capacity")) } - } else { Err(error!("memory request exceeds unsigned integer maximum")) } + } else { Err(AllocationError::ExceedsCapacity) } + } else { Err(AllocationError::ExceedsUIntMax) } } } - } else { Err(error!("cannot allocate less than 1 element")) } + } else { Err(AllocationError::SubMinSize) } } /// Reallocate memory already managed by Raylib @@ -146,11 +143,11 @@ impl DataBuf { /// # Panics /// /// This method may panic if the pointer returned by [`ffi::MemRealloc`] is unaligned. - pub fn realloc(&mut self, new_count: i32) -> Result<(), Error> { + pub fn realloc(&mut self, new_count: i32) -> Result<(), AllocationError> { if new_count >= 1 { let new_count = new_count as usize; match Layout::array::(new_count) { - Err(_e) => Err(error!("memory request does not produce a valid layout")), // I would like to display `e` if possible + Err(_e) => Err(AllocationError::InvalidLayout), // I would like to display `e` if possible Ok(layout) => { let size = layout.size(); if size <= u32::MAX as usize { @@ -159,11 +156,11 @@ impl DataBuf { self.buf = buf; self.len = new_count; Ok(()) - } else { Err(error!("memory request exceeds capacity")) } - } else { Err(error!("memory request exceeds unsigned integer maximum")) } + } else { Err(AllocationError::ExceedsCapacity) } + } else { Err(AllocationError::ExceedsUIntMax) } } } - } else { Err(error!("cannot allocate less than 1 element")) } + } else { Err(AllocationError::SubMinSize) } } } @@ -174,14 +171,14 @@ impl DataBuf { /// let expected: &[u8] = &[1, 5, 0, 250, 255, 49, 49, 49, 49, 49]; /// assert_eq!(data.as_ref(), expected); /// ``` -pub fn compress_data(data: &[u8]) -> Result, Error> { +pub fn compress_data(data: &[u8]) -> Result, CompressionError> { let mut out_length: i32 = 0; // CompressData doesn't actually modify the data, but the header is wrong let buffer = { unsafe { ffi::CompressData(data.as_ptr() as *mut _, data.len() as i32, &mut out_length) } }; DataBuf::new(buffer, out_length) - .ok_or_else(|| error!("could not compress data")) + .ok_or_else(|| CompressionError::CompressionFailed) } /// Decompress data (DEFLATE algorythm) @@ -192,7 +189,7 @@ pub fn compress_data(data: &[u8]) -> Result, Error> { /// let data = decompress_data(input).unwrap(); /// assert_eq!(data.as_ref(), expected); /// ``` -pub fn decompress_data(data: &[u8]) -> Result, Error> { +pub fn decompress_data(data: &[u8]) -> Result, CompressionError> { #[cfg(debug_assertions)] println!("{:?}", data.len()); @@ -202,7 +199,7 @@ pub fn decompress_data(data: &[u8]) -> Result, Error> { unsafe { ffi::DecompressData(data.as_ptr() as *mut _, data.len() as i32, &mut out_length) } }; DataBuf::new(buffer, out_length) - .ok_or_else(|| error!("could not compress data")) + .ok_or_else(|| CompressionError::CompressionFailed) } #[cfg(unix)] diff --git a/raylib/src/core/error.rs b/raylib/src/core/error.rs index 2cdd68a1..053d1b82 100644 --- a/raylib/src/core/error.rs +++ b/raylib/src/core/error.rs @@ -1,47 +1,167 @@ //! Definitions for error types used throught the crate -use std::{borrow::Cow, path::PathBuf}; - use thiserror::Error; #[derive(Error, Debug)] -#[error( - "{message}{path}", - path = path.as_ref().map(|p| format!("\npath: {}", p.display())).unwrap_or("".to_owned()), -)] -pub struct Error { - pub(crate) message: Cow<'static, str>, - pub(crate) path: Option, -} - -impl Error { - pub(crate) const fn new(message: Cow<'static, str>, path: Option) -> Self { - Self { message, path } - } -} - -macro_rules! error { - ($message:literal) => {{ - $crate::core::error::Error::new( - std::borrow::Cow::Borrowed($message), - ::core::option::Option::None, - ) - }}; - ($message:expr $(,)?) => {{ - $crate::core::error::Error::new($message, ::core::option::Option::None) - }}; - ($message:literal, $path:expr $(,)?) => {{ - $crate::core::error::Error::new( - std::borrow::Cow::Borrowed($message), - ::core::option::Option::Some(::std::path::PathBuf::from($path)), - ) - }}; - ($message:expr, $path:expr $(,)?) => {{ - $crate::core::error::Error::new( - $message, - ::core::option::Option::Some(::std::path::PathBuf::from($path)), - ) - }}; -} - -pub(crate) use error; +pub enum AudioInitError { + #[error("RaylibAudio cannot be instantiated more then once at a time")] + DoubleInit, + #[error("failed to initialize audio device")] + InitFailed, +} + +#[derive(Error, Debug)] +pub enum ExportWaveError { + #[error("wave data must be 16 bit per sample for QOA format export (actual: {0})")] + QoaBadSamples(i32), + #[error("failed to export wave data")] + ExportFailed, +} + +#[derive(Error, Debug)] +pub enum LoadSoundError { + #[error("failed to load sound\npath: {path:?}")] + LoadFailed { path: String }, + #[error("failed to load sound from wave")] + LoadFromWaveFailed, + #[error("cannot load wave\npath: {path:?}")] + LoadWaveFromFileFailed { path: String }, + #[error("wave data is null, check provided buffer data")] + Null, + #[error("music could not be loaded from file\npath: {path:?}")] + LoadMusicFromFileFailed { path: String }, + #[error("music's buffer data data is null, check provided buffer data")] + MusicNull, +} + +#[derive(Error, Debug)] +pub enum AllocationError { + #[error("memory request does not produce a valid layout")] + InvalidLayout, + #[error("memory request exceeds capacity")] + ExceedsCapacity, + #[error("memory request exceeds unsigned integer maximum")] + ExceedsUIntMax, + #[error("cannot allocate less than 1 element")] + SubMinSize, +} + +#[derive(Error, Debug)] +pub enum CompressionError { + #[error("could not compress data")] + CompressionFailed, +} + +#[derive(Error, Debug)] +pub enum LoadModelError { + #[error("could not load model\npath: {path:?}")] + LoadFromFileFailed { path: String }, + #[error("could not load model from mesh")] + LoadFromMeshFailed, +} + +#[derive(Error, Debug)] +pub enum LoadModelAnimError { + #[error("no model animations loaded\npath: {path:?}")] + NoAnimationsLoaded { path: String }, +} + +#[derive(Error, Debug)] +pub enum SetMaterialError { + #[error("mesh_id greater than mesh count")] + MeshIdOutOfBounds, + #[error("material_id greater than material count")] + MaterialIdOutOfBounds, +} + +#[derive(Error, Debug)] +pub enum LoadMaterialError { + #[error("no materials loaded\npath: {path:?}")] + NoneLoaded { path: String }, +} + +#[derive(Error, Debug)] +pub enum LoadFontError { + #[error("error loading font; check if the file exists and if it's the right type\npath: {path:?}")] + LoadFromFileFailed { path: String }, + #[error("error loading font from image")] + LoadFromImageFailed, + #[error("error loading font from memory; check if the file's type is correct")] + LoadFromMemoryFailed, +} + +#[derive(Error, Debug)] +pub enum InvalidImageError { + #[error("invalid image: width is 0")] + ZeroWidth, + #[error("invalid image: height is 0")] + ZeroHeight, + #[error("invalid image: data is null")] + NullData, + #[error("image data is null, either the file doesnt exist or the image type is unsupported")] + NullDataFromFile, + #[error("invalid file data")] + InvalidFile, + #[error("image data is null, check provided buffer data")] + NullDataFromMemory, + #[error("failed to retrieve pixel data")] + NullDataFromTexture, + #[error("unsupported format")] + UnsupportedFormat, + #[error("convolution kernel must be square to be applied")] + NonSquareKernel, +} + +#[derive(Error, Debug)] +pub enum UpdateTextureError { + #[error("data is wrong size (expected {expect} bytes, got {actual})")] + WrongDataSize { expect: usize, actual: usize }, + #[error("destination rectangle cannot exceed texture bounds")] + OutOfBounds, + #[error("destination rectangle cannot have negative extents")] + NegativeSize, +} + +#[derive(Error, Debug)] +pub enum LoadTextureError { + #[error("failed to load the texture\npath: {path:?}")] + TextureFromFileFailed { path: String }, + #[error("failed to load image as a texture cubemap")] + CubemapFromImageFailed, + #[error("failed to load image as a texture")] + TextureFromImageFailed, + #[error("failed to create render texture")] + CreateRenderTextureFailed, + #[error("data is not valid to load texture")] + InvalidData, +} + +#[derive(Error, Debug)] +pub enum RaylibError { + #[error("audio initialization error")] + AudioInit(#[from] AudioInitError), + #[error("wave export error")] + ExportWave(#[from] ExportWaveError), + #[error("sound loading error")] + LoadSound(#[from] LoadSoundError), + #[error("allocation error")] + Allocation(#[from] AllocationError), + #[error("compression error")] + Compression(#[from] CompressionError), + #[error("model loading error")] + LoadModel(#[from] LoadModelError), + #[error("model animation loading error")] + LoadModelAnim(#[from] LoadModelAnimError), + #[error("material update error")] + SetMaterial(#[from] SetMaterialError), + #[error("material loading error")] + LoadMaterial(#[from] LoadMaterialError), + #[error("font loading error")] + LoadFont(#[from] LoadFontError), + #[error("image error")] + InvalidImage(#[from] InvalidImageError), + #[error("texture update error")] + UpdateTexture(#[from] UpdateTextureError), + #[error("texture loading error")] + LoadTexture(#[from] LoadTextureError), +} diff --git a/raylib/src/core/models.rs b/raylib/src/core/models.rs index bbc77dcb..ba859a19 100644 --- a/raylib/src/core/models.rs +++ b/raylib/src/core/models.rs @@ -3,8 +3,7 @@ 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 crate::{consts, ffi, error::{LoadMaterialError, LoadModelAnimError, LoadModelError, SetMaterialError}}; use std::ffi::CString; use std::os::raw::c_void; @@ -81,12 +80,12 @@ impl Clone for WeakModelAnimation { impl RaylibHandle { /// Loads model from files (mesh and material). // #[inline] - pub fn load_model(&mut self, _: &RaylibThread, filename: &str) -> Result { + pub fn load_model(&mut self, _: &RaylibThread, filename: &str) -> Result { 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.bones.is_null() && m.bindPose.is_null() { - return Err(error!("could not load model", filename)); + return Err(LoadModelError::LoadFromFileFailed { path: filename.into() }); } // TODO check if null pointer checks are necessary. Ok(Model(m)) @@ -97,11 +96,11 @@ impl RaylibHandle { &mut self, _: &RaylibThread, mesh: WeakMesh, - ) -> Result { + ) -> Result { 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")); + return Err(LoadModelError::LoadFromMeshFailed); } Ok(Model(m)) @@ -112,12 +111,12 @@ impl RaylibHandle { &mut self, _: &RaylibThread, filename: &str, - ) -> Result, Error> { + ) -> Result, LoadModelAnimError> { 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)); + return Err(LoadModelAnimError::NoAnimationsLoaded { path: filename.into() }); } let mut m_vec = Vec::with_capacity(m_size as usize); for i in 0..m_size { @@ -283,15 +282,16 @@ pub trait RaylibModel: AsRef + AsMut { } /// Set material for a mesh - fn set_model_mesh_material(&mut self, mesh_id: i32, material_id: i32) -> Result<(), Error> { + fn set_model_mesh_material(&mut self, mesh_id: i32, material_id: i32) -> Result<(), SetMaterialError> { + // should this be an assertion? if mesh_id >= self.as_ref().meshCount { - return Err(error!("mesh_id greater than mesh count")); + Err(SetMaterialError::MeshIdOutOfBounds) } else if material_id >= self.as_ref().materialCount { - return Err(error!("material_id greater than material count")); + Err(SetMaterialError::MaterialIdOutOfBounds) } else { unsafe { ffi::SetModelMeshMaterial(self.as_mut(), mesh_id, material_id) }; - return Ok(()); - }; + Ok(()) + } } } @@ -539,12 +539,12 @@ impl Material { } /// Load materials from model file - pub fn load_materials(filename: &str) -> Result, Error> { + pub fn load_materials(filename: &str) -> Result, LoadMaterialError> { 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)); + return Err(LoadMaterialError::NoneLoaded { path: filename.into() }); } let mut m_vec = Vec::with_capacity(m_size as usize); for i in 0..m_size { diff --git a/raylib/src/core/text.rs b/raylib/src/core/text.rs index 36411a6d..e42b85b5 100644 --- a/raylib/src/core/text.rs +++ b/raylib/src/core/text.rs @@ -5,9 +5,9 @@ use raylib_sys::LoadUTF8; use crate::core::math::Vector2; use crate::core::texture::{Image, Texture2D}; use crate::core::{RaylibHandle, RaylibThread}; -use crate::error::{error, Error}; use crate::ffi; use crate::math::Rectangle; +use crate::error::LoadFontError; use std::convert::{AsMut, AsRef, TryInto}; use std::ffi::{CString, OsString}; @@ -133,14 +133,11 @@ impl RaylibHandle { /// Loads font from file into GPU memory (VRAM). #[inline] - pub fn load_font(&mut self, _: &RaylibThread, filename: &str) -> Result { + pub fn load_font(&mut self, _: &RaylibThread, filename: &str) -> Result { let c_filename = CString::new(filename).unwrap(); let f = unsafe { ffi::LoadFont(c_filename.as_ptr()) }; if f.glyphs.is_null() || f.texture.id == 0 { - return Err(error!( - "Error loading font. Check if the file exists and if it's the right type", - filename, - )); + return Err(LoadFontError::LoadFromFileFailed { path: filename.into() }); } Ok(Font(f)) } @@ -154,7 +151,7 @@ impl RaylibHandle { filename: &str, font_size: i32, chars: Option<&str>, - ) -> Result { + ) -> Result { let c_filename = CString::new(filename).unwrap(); let f = unsafe { match chars { @@ -171,10 +168,7 @@ impl RaylibHandle { } }; if f.glyphs.is_null() || f.texture.id == 0 { - return Err(error!( - "Error loading font. Check if the file exists and if it's the right type", - filename, - )); + return Err(LoadFontError::LoadFromFileFailed { path: filename.into() }); } Ok(Font(f)) } @@ -187,10 +181,10 @@ impl RaylibHandle { image: &Image, key: impl Into, first_char: i32, - ) -> Result { + ) -> Result { let f = unsafe { ffi::LoadFontFromImage(image.0, key.into(), first_char) }; if f.glyphs.is_null() { - return Err(error!("Error loading font from image.")); + return Err(LoadFontError::LoadFromImageFailed); } Ok(Font(f)) } @@ -205,7 +199,7 @@ impl RaylibHandle { file_data: &[u8], font_size: i32, chars: Option<&str>, - ) -> Result { + ) -> Result { let c_file_type = CString::new(file_type).unwrap(); let f = unsafe { match chars { @@ -231,9 +225,7 @@ impl RaylibHandle { } }; if f.glyphs.is_null() || f.texture.id == 0 { - return Err(error!( - "Error loading font from memory. Check if the file's type is correct" - )); + return Err(LoadFontError::LoadFromMemoryFailed); } Ok(Font(f)) } @@ -368,7 +360,7 @@ impl Font { base_size: i32, padding: i32, pack_method: i32, - ) -> Result { + ) -> Result { let f = unsafe { let mut f = std::mem::zeroed::(); f.baseSize = base_size; @@ -387,7 +379,7 @@ impl Font { f }; if f.0.glyphs.is_null() || f.0.texture.id == 0 { - return Err(error!("Error loading font from image.")); + return Err(LoadFontError::LoadFromImageFailed); } Ok(f) } diff --git a/raylib/src/core/texture.rs b/raylib/src/core/texture.rs index 364b95f3..5f585a5e 100644 --- a/raylib/src/core/texture.rs +++ b/raylib/src/core/texture.rs @@ -3,7 +3,6 @@ use crate::core::color::Color; use crate::core::math::Rectangle; use crate::core::{RaylibHandle, RaylibThread}; -use crate::error::{error, Error}; use crate::ffi; use std::convert::TryInto; use std::ffi::CString; @@ -11,7 +10,7 @@ use std::mem::ManuallyDrop; use std::os::raw::c_void; use std::ptr::{null, null_mut}; -use super::math::Vector2; +use super::{error::{InvalidImageError, LoadTextureError, UpdateTextureError}, math::Vector2}; make_rslice!(ImagePalette, Color, ffi::UnloadImagePalette); make_rslice!(ImageColors, Color, ffi::UnloadImageColors); @@ -794,15 +793,15 @@ impl Image { } /// Export image to memory buffer. - pub fn export_image_to_memory(&self, file_type: &str) -> Result<&[u8], Error> { + pub fn export_image_to_memory(&self, file_type: &str) -> Result<&[u8], InvalidImageError> { if self.width == 0 { - return Err(error!("Invalid image; width == 0")); + return Err(InvalidImageError::ZeroWidth); } if self.height == 0 { - return Err(error!("Invalid image; height == 0")); + return Err(InvalidImageError::ZeroHeight); } if self.data == null_mut() { - return Err(error!("Invalid image; data == null")); + return Err(InvalidImageError::NullData); } let c_filetype = CString::new(file_type).unwrap(); @@ -811,29 +810,29 @@ impl Image { // The actual function returns null if the code for converting to a file type never goes off. if data == null_mut() { - return Err(error!("Unsupported format.")); + return Err(InvalidImageError::UnsupportedFormat); } - return Ok(unsafe { std::slice::from_raw_parts(data as *const u8, *data_size as usize) }); + Ok(unsafe { std::slice::from_raw_parts(data as *const u8, *data_size as usize) }) } /// Apply custom square convolution kernel to image /// NOTE: The convolution kernel matrix is expected to be square - pub fn kernel_convolution(&mut self, kernel: &[f32]) -> Result<(), Error> { + pub fn kernel_convolution(&mut self, kernel: &[f32]) -> Result<(), InvalidImageError> { if self.width == 0 { - return Err(error!("Invalid image; width == 0")); + return Err(InvalidImageError::ZeroWidth); } if self.height == 0 { - return Err(error!("Invalid image; height == 0")); + return Err(InvalidImageError::ZeroHeight); } if self.data == null_mut() { - return Err(error!("Invalid image; data == null")); + return Err(InvalidImageError::NullData); } let kernel_width = (kernel.len() as f32).sqrt() as i32; if (kernel_width * kernel_width) as usize != kernel.len() { - return Err(error!("Convolution kernel must be square to be applied")); + return Err(InvalidImageError::NonSquareKernel); } unsafe { ffi::ImageKernelConvolution(&mut self.0, kernel.as_ptr(), kernel.len() as i32) } @@ -961,22 +960,20 @@ impl Image { /// /// NOTE: Only avaliable on Windows. Do not use if you plan to compile to other platforms. #[cfg(target_os = "windows")] - pub fn get_clipboard_image(&mut self) -> Result { + pub fn get_clipboard_image(&mut self) -> Result { let i = unsafe { ffi::GetClipboardImage() }; if i.data.is_null() { - return Err(error!("Image data is null.")); + return Err(InvalidImageError::NullData); } Ok(Image(i)) } /// Loads image from file into CPU memory (RAM). - pub fn load_image(filename: &str) -> Result { + pub fn load_image(filename: &str) -> Result { let c_filename = CString::new(filename).unwrap(); let i = unsafe { ffi::LoadImage(c_filename.as_ptr()) }; if i.data.is_null() { - return Err(error!( - "Image data is null. Either the file doesnt exist or the image type is unsupported." - )); + return Err(InvalidImageError::NullDataFromFile); } Ok(Image(i)) } @@ -984,17 +981,21 @@ impl Image { /// Loads image from a given memory buffer /// The input data is expected to be in a supported file format such as png. Which formats are /// supported depend on the build flags used for the raylib (C) library. - pub fn load_image_from_mem(filetype: &str, bytes: &[u8]) -> Result { + pub fn load_image_from_mem(filetype: &str, bytes: &[u8]) -> Result { let c_filetype = CString::new(filetype).unwrap(); + let data_size = bytes.len().try_into().unwrap(); + if data_size == 0 { + return Err(InvalidImageError::InvalidFile) + } let i = unsafe { ffi::LoadImageFromMemory( c_filetype.as_ptr(), bytes.as_ptr(), - bytes.len().try_into().unwrap(), + data_size, ) }; if i.data.is_null() { - return Err(error!("Image data is null. Check provided buffer data")); + return Err(InvalidImageError::NullDataFromMemory); }; Ok(Image(i)) } @@ -1031,14 +1032,12 @@ impl Image { height: i32, format: i32, header_size: i32, - ) -> Result { + ) -> Result { let c_filename = CString::new(filename).unwrap(); let i = unsafe { ffi::LoadImageRaw(c_filename.as_ptr(), width, height, format, header_size) }; if i.data.is_null() { - return Err(error!( - "Image data is null. Either the file doesnt exist or the image type is unsupported." - )); + return Err(InvalidImageError::NullDataFromFile); } Ok(Image(i)) } @@ -1118,7 +1117,7 @@ pub trait RaylibTexture2D: AsRef + AsMut { /// Updates GPU texture with new data. #[inline] - fn update_texture(&mut self, pixels: &[u8]) -> Result<(), Error> { + fn update_texture(&mut self, pixels: &[u8]) -> Result<(), UpdateTextureError> { let expected_len = unsafe { get_pixel_data_size( self.as_ref().width, @@ -1127,11 +1126,7 @@ pub trait RaylibTexture2D: AsRef + AsMut { ) as usize }; if pixels.len() != expected_len { - return Err(error!(std::borrow::Cow::Owned(format!( - "update_texture: Data is wrong size. Expected {}, got {}", - expected_len, - pixels.len() - )))); + return Err(UpdateTextureError::WrongDataSize { expect: expected_len, actual: pixels.len() }); } unsafe { ffi::UpdateTexture( @@ -1148,18 +1143,14 @@ pub trait RaylibTexture2D: AsRef + AsMut { &mut self, rec: impl Into, pixels: &[u8], - ) -> Result<(), Error> { + ) -> Result<(), UpdateTextureError> { let rec = rec.into(); if (rec.x < 0.0) || (rec.y < 0.0) || ((rec.x as i32 + rec.width as i32) > (self.as_ref().width)) || ((rec.y as i32 + rec.height as i32) > (self.as_ref().height)) { - return Err(error!( - "update_texture: Destination rectangle cannot exceed texture bounds." - )); + return Err(UpdateTextureError::OutOfBounds); } if (rec.width < 0.0) || (rec.height < 0.0) { - return Err(error!( - "update_texture: Destination rectangle cannot have negative extents." - )); + return Err(UpdateTextureError::NegativeSize); } let expected_len = unsafe { @@ -1170,11 +1161,7 @@ pub trait RaylibTexture2D: AsRef + AsMut { ) as usize }; if pixels.len() != expected_len { - return Err(error!(std::borrow::Cow::Owned(format!( - "update_texture: Data is wrong size. Expected {}, got {}", - expected_len, - pixels.len() - )))); + return Err(UpdateTextureError::WrongDataSize { expect: expected_len, actual: pixels.len() }); } unsafe { ffi::UpdateTextureRec( @@ -1190,10 +1177,10 @@ pub trait RaylibTexture2D: AsRef + AsMut { /// Gets pixel data from GPU texture and returns an `Image`. /// Fairly sure this would never fail. If it does wrap in result. #[inline] - fn load_image(&self) -> Result { + fn load_image(&self) -> Result { let i = unsafe { ffi::LoadImageFromTexture(*self.as_ref()) }; if i.data.is_null() { - return Err(error!("Texture cannot be rendered to an image")); + return Err(InvalidImageError::NullDataFromTexture); } Ok(Image(i)) } @@ -1237,11 +1224,11 @@ pub fn get_pixel_data_size(width: i32, height: i32, format: ffi::PixelFormat) -> impl RaylibHandle { /// Loads texture from file into GPU memory (VRAM). - pub fn load_texture(&mut self, _: &RaylibThread, filename: &str) -> Result { + pub fn load_texture(&mut self, _: &RaylibThread, filename: &str) -> Result { let c_filename = CString::new(filename).unwrap(); let t = unsafe { ffi::LoadTexture(c_filename.as_ptr()) }; if t.id == 0 { - return Err(error!("failed to load the texture.", filename)); + return Err(LoadTextureError::TextureFromFileFailed { path: filename.into() }); } Ok(Texture2D(t)) } @@ -1252,10 +1239,10 @@ impl RaylibHandle { _: &RaylibThread, image: &Image, layout: crate::consts::CubemapLayout, - ) -> Result { + ) -> Result { let t = unsafe { ffi::LoadTextureCubemap(image.0, layout as i32) }; if t.id == 0 { - return Err(error!("failed to load image as a texture cubemap.")); + return Err(LoadTextureError::CubemapFromImageFailed); } Ok(Texture2D(t)) } @@ -1266,10 +1253,13 @@ impl RaylibHandle { &mut self, _: &RaylibThread, image: &Image, - ) -> Result { + ) -> Result { + if image.width == 0 || image.height == 0 { + return Err(LoadTextureError::InvalidData); + } let t = unsafe { ffi::LoadTextureFromImage(image.0) }; if t.id == 0 { - return Err(error!("failed to load image as a texture.")); + return Err(LoadTextureError::TextureFromImageFailed); } Ok(Texture2D(t)) } @@ -1280,17 +1270,17 @@ impl RaylibHandle { _: &RaylibThread, width: u32, height: u32, - ) -> Result { + ) -> Result { let t = unsafe { ffi::LoadRenderTexture(width as i32, height as i32) }; if t.id == 0 { - return Err(error!("failed to create render texture.")); + return Err(LoadTextureError::CreateRenderTextureFailed); } Ok(RenderTexture2D(t)) } } impl RaylibHandle { - /// Weak Textures will leak memeory if they are not unlaoded + /// Weak Textures will leak memeory if they are not unloaded /// Unload textures from GPU memory (VRAM) #[inline] pub unsafe fn unload_texture(&mut self, _: &RaylibThread, texture: WeakTexture2D) { @@ -1298,7 +1288,7 @@ impl RaylibHandle { ffi::UnloadTexture(*texture.as_ref()) } } - /// Weak RenderTextures will leak memeory if they are not unlaoded + /// Weak RenderTextures will leak memeory if they are not unloaded /// Unload RenderTextures from GPU memory (VRAM) #[inline] pub unsafe fn unload_render_texture(&mut self, _: &RaylibThread, texture: WeakRenderTexture2D) {