diff --git a/.cargo/config.toml b/.cargo/config.toml index 94420f58..b423dd3e 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,2 +1,2 @@ [env] -TARGET_DIR={ value = "target", relative = true } \ No newline at end of file +TARGET_DIR = { value = "target", relative = true } diff --git a/.gitattributes b/.gitattributes index 843d7031..bb1448cf 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,5 +1,2 @@ -bevy_script_api/src/generated.rs linguist-generated -bevy_script_api/src/generated.rs -diff -merge - -**/*generated*.rs linguist-generated -**/*generated*.rs -diff -merge +crates/bevy_script_api/providers/*.rs linguist-generated +crates/bevy_script_api/providers/*.rs -diff -merge \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4a7e389c..29630863 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,7 +16,7 @@ jobs: run_args: [ {os: windows-latest, lua: lua54, cross: null}, {os: macOS-latest, lua: lua54, cross: null}, - {os: ubuntu-latest, lua: lua54, cross: aarch64-unknown-linux-gnu}, + # {os: ubuntu-latest, lua: lua54, cross: aarch64-unknown-linux-gnu}, see https://github.com/houseabsolute/actions-rust-cross/issues/15 {os: ubuntu-latest, lua: lua51, cross: null}, {os: ubuntu-latest, lua: lua52, cross: null}, {os: ubuntu-latest, lua: lua53, cross: null}, diff --git a/.rustfmt.toml b/.rustfmt.toml index e69de29b..6e65172c 100644 --- a/.rustfmt.toml +++ b/.rustfmt.toml @@ -0,0 +1,3 @@ +# max_width = 60 +# use_small_heuristics = "Max" +# format_generated_files = false diff --git a/.vscode/launch.json b/.vscode/launch.json index 07adf353..a6483eca 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,30 +1,20 @@ { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "type": "lldb", "request": "launch", - "name": "Debug unit tests in library 'bevy_mod_scripting'", - "cargo": { - "args": [ - "test", - "--no-run", - "--lib", - "--package=bevy_mod_scripting" - ], - "filter": { - "name": "bevy_mod_scripting", - "kind": "lib" - } - }, - "args": [], + "name": "Debug specific unit test", + "preLaunchTask": "Build specific package's unit tests", + "program": "${workspaceFolder}/target/debug/test_binary", "env": { - "CARGO_MANIFEST_DIR": "${workspaceFolder}/bevy_mod_scripting" + "CARGO_MANIFEST_DIR": "${workspaceFolder}/bevy_mod_scripting", + "LD_LIBRARY_PATH": "${workspaceFolder}/target/debug/deps:${env:HOME}/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib" }, - "cwd": "${workspaceFolder}" + "cwd": "${workspaceFolder}", }, { "name": "Debug example 'game_of_life_lua'", @@ -45,7 +35,8 @@ "args": [], "cwd": "${workspaceFolder}", "env": { - "CARGO_MANIFEST_DIR": "${workspaceFolder}" + "CARGO_MANIFEST_DIR": "${workspaceFolder}", + "LD_LIBRARY_PATH": "${workspaceFolder}/target/debug/deps:${env:HOME}/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib" } }, { diff --git a/.vscode/settings.json b/.vscode/settings.json index 7012d83a..5a25c446 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -3,15 +3,21 @@ "lldb.showDisassembly": "never", "lldb.dereferencePointers": true, "lldb.consoleMode": "commands", - "rust-analyzer.cargo.features": [ - "lua54", - "lua_script_api", - "rhai", - "rhai_script_api", - "teal", - "rune" + "[rust]": { + "editor.formatOnSave": true, + "editor.formatOnSaveMode": "file", + "editor.defaultFormatter": "rust-lang.rust-analyzer" + }, + "rust-analyzer.rustc.source": "discover", + "rust-analyzer.linkedProjects": [ + "./crates/bevy_api_gen/Cargo.toml", + "Cargo.toml", ], - "rust-analyzer.server.extraEnv": { - "RUSTUP_TOOLCHAIN": "stable" - } + "rust-analyzer.check.invocationStrategy": "per_workspace", + "rust-analyzer.check.invocationLocation": "workspace", + "rust-analyzer.check.overrideCommand": [ + "/home/makspll/git/bevy_mod_scripting/check.sh" + ], + "rust-analyzer.showUnlinkedFileNotification": false, + // "rust-analyzer.semanticHighlighting.operator.enable": false } \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 00000000..14262c18 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,29 @@ +{ + "version": "2.0.0", + "inputs": [ + { + "id": "test_name", + "type": "promptString", + "description": "Run only tests including this string in their name", + "default": "" + }, + { + "id": "package", + "type": "promptString", + "description": "The crate location of this unit test", + "default": "bevy_mod_scripting" + } + ], + "tasks": [ + { + "label": "Build specific package's unit tests", + "type": "process", + "command": "make", + "args": [ + "build_test_in_package", + "PACKAGE=${input:package}", + "TEST_NAME=${input:test_name}" + ] + } + ] +} \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml index 7bea21d1..37bd285c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,41 +61,47 @@ rhai_script_api = ["bevy_script_api/rhai"] rune = ["bevy_mod_scripting_rune"] [dependencies] -bevy = { version = "0.13", default-features = false } -bevy_mod_scripting_core = { path = "bevy_mod_scripting_core", version = "0.5.0" } -bevy_mod_scripting_lua = { path = "languages/bevy_mod_scripting_lua", version = "0.5.0", optional = true } -bevy_mod_scripting_rhai = { path = "languages/bevy_mod_scripting_rhai", version = "0.5.0", optional = true } -bevy_mod_scripting_rune = { path = "languages/bevy_mod_scripting_rune", version = "0.5.0", optional = true } -bevy_script_api = { path = "bevy_script_api", version = "0.5.0", optional = true } +bevy = { workspace = true } +bevy_mod_scripting_core = { workspace = true } +bevy_mod_scripting_lua = { path = "crates/languages/bevy_mod_scripting_lua", version = "0.5.0", optional = true } +bevy_mod_scripting_rhai = { path = "crates/languages/bevy_mod_scripting_rhai", version = "0.5.0", optional = true } +bevy_mod_scripting_rune = { path = "crates/languages/bevy_mod_scripting_rune", version = "0.5.0", optional = true } +bevy_script_api = { path = "crates/bevy_script_api", version = "0.5.0", optional = true } +[workspace.dependencies] +bevy = { version = "=0.13.1", default-features = false } +bevy_mod_scripting_core = { path = "crates/bevy_mod_scripting_core", version = "0.5.0" } +bevy_mod_scripting_common = { path = "crates/bevy_mod_scripting_common", version = "0.5.0" } + [dev-dependencies] -bevy = { version = "0.13" } +bevy = { workspace = true, default-features = true } clap = { version = "4.1", features = ["derive"] } rand = "0.8.5" bevy_console = "0.11.1" rhai-rand = "0.1" [workspace] -resolver = "2" members = [ - "bevy_mod_scripting_core", - "bevy_event_priority", - "bevy_mod_scripting_derive", - "bevy_api_gen", - "bevy_script_api", - "languages/bevy_mod_scripting_lua", - "languages/bevy_mod_scripting_lua_derive", - "languages/bevy_mod_scripting_rhai", - "languages/bevy_mod_scripting_rhai_derive", - "languages/bevy_mod_scripting_rune", - "bevy_mod_scripting_common", + "crates/bevy_mod_scripting_core", + "crates/bevy_event_priority", + "crates/bevy_script_api", + "crates/languages/bevy_mod_scripting_lua", + "crates/languages/bevy_mod_scripting_lua_derive", + "crates/languages/bevy_mod_scripting_rhai", + "crates/languages/bevy_mod_scripting_rhai_derive", + "crates/languages/bevy_mod_scripting_rune", + "crates/bevy_mod_scripting_common", ] +resolver = "2" +exclude = ["bevy_api_gen"] [profile.dev] +debug = 1 opt-level = 1 [profile.dev.package."*"] +debug = 0 opt-level = 3 [profile.ephemeral-build] @@ -105,16 +111,25 @@ codegen-units = 8 incremental = false debug = false - [[example]] name = "console_integration_lua" path = "examples/lua/console_integration.rs" -required-features = ["lua54", "lua_script_api", "bevy/file_watcher"] +required-features = [ + "lua54", + "lua_script_api", + "bevy/file_watcher", + "bevy/multi-threaded", +] [[example]] name = "console_integration_rhai" path = "examples/rhai/console_integration.rs" -required-features = ["rhai", "rhai_script_api", "bevy/file_watcher"] +required-features = [ + "rhai", + "rhai_script_api", + "bevy/file_watcher", + "bevy/multi-threaded", +] [[example]] name = "complex_game_loop_lua" @@ -124,12 +139,22 @@ required-features = ["lua54"] [[example]] name = "game_of_life_lua" path = "examples/lua/game_of_life.rs" -required-features = ["lua54", "teal", "lua_script_api", "bevy/file_watcher"] +required-features = [ + "lua54", + "lua_script_api", + "bevy/file_watcher", + "bevy/multi-threaded", +] [[example]] name = "game_of_life_rhai" path = "examples/rhai/game_of_life.rs" -required-features = ["rhai", "rhai_script_api", "bevy/file_watcher"] +required-features = [ + "rhai", + "rhai_script_api", + "bevy/file_watcher", + "bevy/multi-threaded", +] [[example]] name = "event_recipients_lua" @@ -156,11 +181,6 @@ name = "bevy_api_rhai" path = "examples/rhai/bevy_api.rs" required-features = ["rhai", "rhai_script_api"] -[[example]] -name = "multiple_events_rhai" -path = "examples/rhai/multiple_events_rhai.rs" -required-features = ["rhai", "rhai_script_api"] - [[example]] name = "wrappers" path = "examples/wrappers.rs" diff --git a/api_gen_config.toml b/api_gen_config.toml deleted file mode 100644 index 54439127..00000000 --- a/api_gen_config.toml +++ /dev/null @@ -1,908 +0,0 @@ -imports = """ -#[cfg(feature="lua")] -use { - bevy_mod_scripting_lua_derive::impl_lua_newtype, - bevy_mod_scripting_lua::{ - tealr::mlu::mlua::MetaMethod, - docs::LuaDocFragment - }, - crate::{common::bevy::GetWorld, lua::{RegisterForeignLuaType, util::LuaIndex}}, -}; -use std::ops::*; -use crate::{script_ref::{ReflectedValue,ValueIndex}, - sub_reflect::ReflectPathElem, - error::ReflectionError, -}; -use std::sync::Mutex; -use bevy_mod_scripting_core::prelude::*; -use bevy::prelude::App; -use bevy::reflect::Enum; -""" - -other = """ -#[cfg(feature="lua")] -crate::impl_tealr_generic!(pub(crate) struct T); -""" - -lua_api_defaults = """ -fn setup_script( - &mut self, - script_data: &ScriptData, - ctx: &mut Self::ScriptContext, -) -> Result<(), ScriptError> { - let ctx = ctx.get_mut().expect("Could not get context"); - let globals = ctx.globals(); - globals - .set( - "entity", - crate::lua::bevy::LuaEntity::new(script_data.entity), - ) - .map_err(ScriptError::new_other)?; - globals - .set::<_, crate::lua::bevy::LuaScriptData>("script", script_data.into()) - .map_err(ScriptError::new_other)?; - - Ok(()) -} - -fn setup_script_runtime( - &mut self, - world_ptr: bevy_mod_scripting_core::world::WorldPointer, - _script_data: &ScriptData, - ctx: &mut Self::ScriptContext, -) -> Result<(), ScriptError> { - let ctx = ctx.get_mut().expect("Could not get context"); - let globals = ctx.globals(); - globals - .set("world", crate::lua::bevy::LuaWorld::new(world_ptr)) - .map_err(ScriptError::new_other) -} -""" - -primitives = [ - "usize", - "isize", - "f32", - "f64", - "u128", - "u64", - "u32", - "u16", - "u8", - "i128", - "i64", - "i32", - "i16", - "i8", - "String", - "bool", -] - - -[[manual_lua_types]] -name = "ReflectedValue" - -[[manual_lua_types]] -name = "crate::lua::bevy::LuaWorld" -proxy_name = "world" -include_global_proxy = true -use_dummy_proxy = true - -[[manual_lua_types]] -name = "crate::lua::bevy::LuaScriptData" -proxy_name = "script" -include_global_proxy = true -use_dummy_proxy = true - -[[manual_lua_types]] -name = "crate::lua::bevy::LuaEntity" -proxy_name = "entity" -include_global_proxy = true -use_dummy_proxy = true -dont_process = true - -[[manual_lua_types]] -name = "crate::lua::bevy::LuaTypeRegistration" - -[[manual_lua_types]] -name = "crate::lua::std::LuaVec" - - -## BEVY_UI - -[[types]] -type = "AlignContent" -source = "bevy_ui" - -[[types]] -type = "AlignItems" -source = "bevy_ui" - -[[types]] -type = "AlignSelf" -source = "bevy_ui" - -[[types]] -type = "Direction" -source = "bevy_ui" - -[[types]] -type = "FlexDirection" -source = "bevy_ui" - -[[types]] -type = "FlexWrap" -source = "bevy_ui" - -[[types]] -type = "FocusPolicy" -source = "bevy_ui" - -[[types]] -type = "Interaction" -source = "bevy_ui" - -[[types]] -type = "JustifyContent" -source = "bevy_ui" - -[[types]] -type = "Overflow" -source = "bevy_ui" - -[[types]] -type = "PositionType" -source = "bevy_ui" - -[[types]] -type = "Val" -source = "bevy_ui" - -[[types]] -type = "CalculatedClip" -source = "bevy_ui" - -[[types]] -type = "Node" -source = "bevy_ui" - -[[types]] -type = "Style" -source = "bevy_ui" - -[[types]] -type = "UiImage" -source = "bevy_ui" - -[[types]] -type = "Button" -source = "bevy_ui" - -[[types]] -type = "Display" -source = "bevy_ui" - - -## BEVY_ANIMATION - -[[types]] -type = "AnimationPlayer" -source = "bevy_animation" - - -## BEVY_CORE - -[[types]] -type = "Name" -source = "bevy_core" - - -# ## BEVY_GLTF - -[[types]] -type = "GltfExtras" -source = "bevy_gltf" - - -## BEVY_HIERARCHY - -[[types]] -type = "Children" -source = "bevy_hierarchy" - -[[types]] -type = "Parent" -source = "bevy_hierarchy" - -## BEVY_TEXT - -[[types]] -type = "Text2dBounds" -source = "bevy_text" - -[[types]] -type = "Text" -source = "bevy_text" - -[[types]] -type = "JustifyText" -source = "bevy_text" - -[[types]] -type = "TextSection" -source = "bevy_text" - -[[types]] -type = "TextStyle" -source = "bevy_text" - -## BEVY_TIME - -[[types]] -type = "Stopwatch" -source = "bevy_time" - -[[types]] -type = "Timer" -source = "bevy_time" - - -## BEVY_UTILS - -# [[types]] -# type="Duration" -# source="bevy_utils" - - -# ## BEVY_REFLECT - -# [[types]] -# type="DynamicArray" -# source="bevy_reflect" - -# [[types]] -# type="DynamicList" -# source="bevy_reflect" - -# [[types]] -# type="DynamicMap" -# source="bevy_reflect" - -# [[types]] -# type="DynamicStruct" -# source="bevy_reflect" - -# [[types]] -# type="DynamicTuple" -# source="bevy_reflect" - -# [[types]] -# type="DynamicTupleStruct" -# source="bevy_reflect" - - -## BEVY_ECS -[[types]] -type = "Entity" -source = "bevy_ecs" - -## BEVY_TRANSFORM - -[[types]] -type = "Transform" -source = "bevy_transform" - -[[types]] -type = "GlobalTransform" -source = "bevy_transform" - -## BEVY_PBR - -[[types]] -type = "AmbientLight" -source = "bevy_pbr" - -[[types]] -type = "CubemapVisibleEntities" -source = "bevy_pbr" - -[[types]] -type = "DirectionalLight" -source = "bevy_pbr" - -[[types]] -type = "DirectionalLightShadowMap" -source = "bevy_pbr" - -[[types]] -type = "NotShadowCaster" -source = "bevy_pbr" - -[[types]] -type = "NotShadowReceiver" -source = "bevy_pbr" - -[[types]] -type = "PointLight" -source = "bevy_pbr" - -[[types]] -type = "PointLightShadowMap" -source = "bevy_pbr" - - -[[types]] -type = "AlphaMode" -source = "bevy_pbr" - -[[types]] -type = "Wireframe" -source = "bevy_pbr" - -[[types]] -type = "WireframeConfig" -source = "bevy_pbr" - -## BEVY_CORE_PIPELINE - -[[types]] -type = "Camera3dDepthLoadOp" -source = "bevy_core_pipeline" - - -[[types]] -type = "ClearColor" -source = "bevy_render" - -[[types]] -type = "ClearColorConfig" -source = "bevy_render" - -[[types]] -type = "Camera2d" -source = "bevy_core_pipeline" - -[[types]] -type = "Camera3d" -source = "bevy_core_pipeline" - -## BEVY_SPRITE - -[[types]] -type = "Anchor" -source = "bevy_sprite" - -[[types]] -type = "Mesh2dHandle" -source = "bevy_sprite" - -[[types]] -type = "TextureAtlas" -source = "bevy_sprite" - - -[[types]] -type = "Sprite" -source = "bevy_sprite" - - -## BEVY_RENDER - -[[types]] -type = "RenderLayers" -source = "bevy_render" - -[[types]] -type = "Visibility" -source = "bevy_render" - -[[types]] -type = "VisibleEntities" -source = "bevy_render" - -[[types]] -type = "InheritedVisibility" -source = "bevy_render" - -[[types]] -type = "ViewVisibility" -source = "bevy_render" - -[[types]] -type = "SkinnedMesh" -source = "bevy_render" - -[[types]] -type = "ScalingMode" -source = "bevy_render" - -[[types]] -type = "Color" -source = "bevy_render" - -[[types]] -type = "Aabb" -source = "bevy_render" - -[[types]] -type = "CubemapFrusta" -source = "bevy_render" - -[[types]] -type = "Frustum" -source = "bevy_render" - -[[types]] -type = "Msaa" -source = "bevy_render" - -[[types]] -type = "Camera" -source = "bevy_render" - -[[types]] -type = "RenderTarget" -source = "bevy_render" - -[[types]] -type = "Viewport" -source = "bevy_render" - - -[[types]] -type = "Projection" -source = "bevy_render" -traits = [ - { name = "CameraProjection", import_path = "bevy::render::camera::CameraProjection" }, -] - -[[types]] -type = "OrthographicProjection" -source = "bevy_render" -traits = [ - { name = "CameraProjection", import_path = "bevy::render::camera::CameraProjection" }, -] - -[[types]] -type = "PerspectiveProjection" -source = "bevy_render" -traits = [ - { name = "CameraProjection", import_path = "bevy::render::camera::CameraProjection" }, -] - -[[types]] -type = "CameraRenderGraph" -source = "bevy_render" - - -## BEVY_UTILS -# needs a reflect impl -# [[types]] -# type="Uuid" -# source="uuid" - -## BEVY_ASSET - -[[types]] -type = "AssetIndex" -source = "bevy_asset" - -#Needs manual implementation? it's generic. -#[[types]] -#type="AssetId" -#source="bevy_asset" - -#Not handled by reflection -#[[types]] -#type="StrongHandle" -#source="bevy_asset" - -#[[types]] -#type="Label" -#source="bevy_asset" - -#[[types]] -#type="Handle" -#source="bevy_asset" - -## BEVY_MATH -[[types]] -type = "Vec2" -source = "bevy_math" -lua_methods = [ - "(MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}", - "mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,f32)| {s.val_mut(|s| Ok(s[*idx] = val))?}", -] -import_path = "glam::f32::Vec2" - -[[types]] -type = "Vec3" -source = "bevy_math" -lua_methods = [ - "(MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}", - "mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,f32)| {s.val_mut(|s| Ok(s[*idx] = val))?}", -] -import_path = "glam::f32::Vec3" - -[[types]] -type = "Vec3A" -source = "bevy_math" -lua_methods = [ - "(MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}", - "mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,f32)| {s.val_mut(|s| Ok(s[*idx] = val))?}", -] -import_path = "glam::f32::Vec3A" - - -[[types]] -type = "Vec4" -source = "bevy_math" -lua_methods = [ - "(MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}", - "mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,f32)| {s.val_mut(|s| Ok(s[*idx] = val))?}", -] -import_path = "glam::f32::Vec4" - -[[types]] -type = "BVec2" -source = "bevy_math" -import_path = "glam::bool::BVec2" - -[[types]] -type = "BVec3" -source = "bevy_math" -import_path = "glam::bool::BVec3" - -[[types]] -type = "BVec4" -source = "bevy_math" -import_path = "glam::bool::BVec4" - -[[types]] -type = "BVec3A" -source = "bevy_math" -import_path = "glam::bool::BVec3A" - -[[types]] -type = "BVec4A" -source = "bevy_math" -import_path = "glam::bool::BVec4A" - -[[types]] -type = "DVec2" -source = "bevy_math" -lua_methods = [ - "(MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}", - "mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,f64)| {s.val_mut(|s| Ok(s[*idx] = val))?}", -] -import_path = "glam::f64::DVec2" - -[[types]] -type = "DVec3" -source = "bevy_math" -lua_methods = [ - "(MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}", - "mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,f64)| {s.val_mut(|s| Ok(s[*idx] = val))?}", -] -import_path = "glam::f64::DVec3" - -[[types]] -type = "DVec4" -source = "bevy_math" -lua_methods = [ - "(MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}", - "mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,f64)| {s.val_mut(|s| Ok(s[*idx] = val))?}", -] -import_path = "glam::f64::DVec4" - -[[types]] -type = "IVec2" -source = "bevy_math" -lua_methods = [ - "(MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}", - "mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,i32)| {s.val_mut(|s| Ok(s[*idx] = val))?}", -] -import_path = "glam::i32::IVec2" - -[[types]] -type = "IVec3" -source = "bevy_math" -lua_methods = [ - "(MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}", - "mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,i32)| {s.val_mut(|s| Ok(s[*idx] = val))?}", -] -import_path = "glam::i32::IVec3" - -[[types]] -type = "IVec4" -source = "bevy_math" -lua_methods = [ - "(MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}", - "mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,i32)| {s.val_mut(|s| Ok(s[*idx] = val))?}", -] -import_path = "glam::i32::IVec4" - -[[types]] -type = "UVec2" -source = "bevy_math" -lua_methods = [ - "(MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}", - "mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,u32)| {s.val_mut(|s| Ok(s[*idx] = val))?}", -] -import_path = "glam::u32::UVec2" - -[[types]] -type = "UVec3" -source = "bevy_math" -lua_methods = [ - "(MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}", - "mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,u32)| {s.val_mut(|s| Ok(s[*idx] = val))?}", -] -import_path = "glam::u32::UVec3" - -[[types]] -type = "UVec4" -source = "bevy_math" -lua_methods = [ - "(MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}", - "mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,u32)| {s.val_mut(|s| Ok(s[*idx] = val))?}", -] -import_path = "glam::u32::UVec4" - -[[types]] -type = "Mat3" -source = "bevy_math" -lua_methods = [ - """ - mut (MetaMethod::Index) => |ctx,s,idx : LuaIndex| { - Ok(LuaVec3::new_ref( - s.script_ref(ctx.get_world()?).sub_ref(ReflectPathElem::SubReflectionIndexed{ - label:"col", - index: *idx, - get: |idx,ref_| Err(ReflectionError::InsufficientProvenance{ - path: "".to_owned(), - msg: "Cannot get column of matrix with immutable reference".to_owned() - }), - get_mut: |idx, ref_| { - if ref_.is::(){ - Ok(ref_.downcast_mut::() - .unwrap() - .col_mut(idx)) - } else { - Err(ReflectionError::CannotDowncast{from: ref_.get_represented_type_info().unwrap().type_path().into(), to:"Mat3".into()}) - } - } - }) - ) - ) - } -""", -] -import_path = "glam::f32::Mat3" - -[[types]] -type = "Mat2" -source = "bevy_math" -lua_methods = [ - """ - mut (MetaMethod::Index) => |ctx,s,idx : LuaIndex| { - Ok(LuaVec2::new_ref( - s.script_ref(ctx.get_world()?).sub_ref(ReflectPathElem::SubReflectionIndexed{ - label:"col", - index: *idx, - get: |idx,ref_| Err(ReflectionError::InsufficientProvenance{ - path: "".to_owned(), - msg: "Cannot get column of matrix with immutable reference".to_owned() - }), - get_mut: |idx, ref_| { - if ref_.is::(){ - Ok(ref_.downcast_mut::() - .unwrap() - .col_mut(idx)) - } else { - Err(ReflectionError::CannotDowncast{from: ref_.get_represented_type_info().unwrap().type_path().into(), to:"Mat2".into()}) - } - } - }) - ) - ) - } -""", -] -import_path = "glam::f32::Mat2" - - -[[types]] -type = "Mat3A" -source = "bevy_math" -lua_methods = [ - """ - mut (MetaMethod::Index) => |ctx,s,idx : LuaIndex| { - Ok(LuaVec3A::new_ref( - s.script_ref(ctx.get_world()?).sub_ref(ReflectPathElem::SubReflectionIndexed{ - label:"col", - index: *idx, - get: |idx,ref_| Err(ReflectionError::InsufficientProvenance{ - path: "".to_owned(), - msg: "Cannot get column of matrix with immutable reference".to_owned() - }), - get_mut: |idx, ref_| { - if ref_.is::(){ - Ok(ref_.downcast_mut::() - .unwrap() - .col_mut(idx)) - } else { - Err(ReflectionError::CannotDowncast{from: ref_.get_represented_type_info().unwrap().type_path().into(), to:"Mat3A".into()}) - } - } - }) - ) - ) - } -""", -] -import_path = "glam::f32::Mat3A" - -[[types]] -type = "Mat4" -source = "bevy_math" -lua_methods = [ - """ - mut (MetaMethod::Index) => |ctx,s,idx : LuaIndex| { - Ok(LuaVec4::new_ref( - s.script_ref(ctx.get_world()?).sub_ref(ReflectPathElem::SubReflectionIndexed{ - label:"col", - index: *idx, - get: |idx,ref_| Err(ReflectionError::InsufficientProvenance{ - path: "".to_owned(), - msg: "Cannot get column of matrix with immutable reference".to_owned() - }), - get_mut: |idx, ref_| { - if ref_.is::(){ - Ok(ref_.downcast_mut::() - .unwrap() - .col_mut(idx)) - } else { - Err(ReflectionError::CannotDowncast{from: ref_.get_represented_type_info().unwrap().type_path().into(), to:"Mat4".into()}) - } - } - }) - ) - ) - } -""", -] -import_path = "glam::f32::Mat4" - - -[[types]] -type = "DMat2" -source = "bevy_math" -lua_methods = [ - """ - mut (MetaMethod::Index) => |ctx,s,idx : LuaIndex| { - Ok(LuaDVec2::new_ref( - s.script_ref(ctx.get_world()?).sub_ref(ReflectPathElem::SubReflectionIndexed{ - label:"col", - index: *idx, - get: |idx,ref_| Err(ReflectionError::InsufficientProvenance{ - path: "".to_owned(), - msg: "Cannot get column of matrix with immutable reference".to_owned() - }), - get_mut: |idx, ref_| { - if ref_.is::(){ - Ok(ref_.downcast_mut::() - .unwrap() - .col_mut(idx)) - } else { - Err(ReflectionError::CannotDowncast{from: ref_.get_represented_type_info().unwrap().type_path().into(), to:"DMat2".into()}) - } - } - }) - ) - ) - } -""", -] -import_path = "glam::f64::DMat2" - -[[types]] -type = "DMat3" -source = "bevy_math" -lua_methods = [ - """ - mut (MetaMethod::Index) => |ctx,s,idx : LuaIndex| { - Ok(LuaDVec3::new_ref( - s.script_ref(ctx.get_world()?).sub_ref(ReflectPathElem::SubReflectionIndexed{ - label:"col", - index: *idx, - get: |idx,ref_| Err(ReflectionError::InsufficientProvenance{ - path: "".to_owned(), - msg: "Cannot get column of matrix with immutable reference".to_owned() - }), - get_mut: |idx, ref_| { - if ref_.is::(){ - Ok(ref_.downcast_mut::() - .unwrap() - .col_mut(idx)) - } else { - Err(ReflectionError::CannotDowncast{from: ref_.get_represented_type_info().unwrap().type_path().into(), to:"DMat3".into()}) - } - } - }) - ) - ) - } -""", -] -import_path = "glam::f64::DMat3" - -[[types]] -type = "DMat4" -source = "bevy_math" -lua_methods = [ - """ - mut (MetaMethod::Index) => |ctx,s,idx : LuaIndex| { - Ok(LuaDVec4::new_ref( - s.script_ref(ctx.get_world()?).sub_ref(ReflectPathElem::SubReflectionIndexed{ - label:"col", - index: *idx, - get: |idx,ref_| Err(ReflectionError::InsufficientProvenance{ - path: "".to_owned(), - msg: "Cannot get column of matrix with immutable reference".to_owned() - }), - get_mut: |idx, ref_| { - if ref_.is::(){ - Ok(ref_.downcast_mut::() - .unwrap() - .col_mut(idx)) - } else { - Err(ReflectionError::CannotDowncast{from: ref_.get_represented_type_info().unwrap().type_path().into(), to:"DMat4".into()}) - } - } - }) - ) - ) - } -""", -] -import_path = "glam::f64::DMat4" - -[[types]] -type = "Affine2" -source = "bevy_math" -import_path = "glam::f32::Affine2" - -[[types]] -type = "Affine3A" -source = "bevy_math" -import_path = "glam::f32::Affine3A" - -[[types]] -type = "DAffine2" -source = "bevy_math" -import_path = "glam::f64::DAffine2" - -[[types]] -type = "DAffine3" -source = "bevy_math" -import_path = "glam::f64::DAffine3" - -[[types]] -type = "Quat" -source = "bevy_math" -import_path = "glam::f32::Quat" - -[[types]] -type = "DQuat" -source = "bevy_math" -import_path = "glam::f64::DQuat" - -[[types]] -type = "EulerRot" -source = "bevy_math" -import_path = "glam::EulerRot" - -[[types]] -type = "Rect" -source = "bevy_math" diff --git a/architecture.md b/architecture.md new file mode 100644 index 00000000..9c940e7d --- /dev/null +++ b/architecture.md @@ -0,0 +1,199 @@ +# Architecture + +## Reflection + +`bevy_mod_scripting` first and foremost relies on `Reflection`, a feature of Bevy which allows us to interact with type erased data. This is the foundation of the scripting system, as it allows us to interact with the Bevy ECS without knowing the exact types of the components/resources our scripts will be interacting with at compile time. + +Normally in Bevy, you would define your components and resources as structs, and then use them in your systems. This is very powerful but also very limiting, as it requires you to know the exact types of the components/resources you will be interacting with at compile time. This is where [`Reflection`](https://docs.rs/bevy_reflect/0.13.1/bevy_reflect/) comes in. + +Bevy provides us with a [`TypeRegistry`](https://docs.rs/bevy_reflect/0.13.1/bevy_reflect/struct.TypeRegistry.html), which is essentially just a map from type ids to [`TypeRegistrations`](https://docs.rs/bevy_reflect/0.13.1/bevy_reflect/struct.TypeRegistration.html). A `TypeRegistration` is a container for all sorts of metadata about the type but most importantly it allows us to query [`TypeData`](https://docs.rs/bevy_reflect/0.13.1/bevy_reflect/trait.TypeData.html) of any type which was previously registered via the `TypeRegistry`. + +How is this useful ? Well it allows us to register arbitrary information including function pointers which we can then retrieve given just a `TypeId`. This is exactly what we do with [`ReflectProxyable`](https://docs.rs/bevy_mod_scripting/0.3.0/bevy_mod_scripting/api/lua/struct.ReflectLuaProxyable.html), the interface between Bevy and Lua: + +```rust,ignore +pub fn ref_to_lua<'lua>( + &self, + ref_: ReflectReference, + lua: &'lua Lua +) -> Result, Error> + +pub fn apply_lua<'lua>( + &self, + ref_: &mut ReflectReference, + lua: &'lua Lua, + new_val: Value<'lua> +) -> Result<(), Error> +``` + +A `ReflectProxyable` `TypeData` is registered for every type which we want to have custom Lua bindings for. With this we can represent any Reflectable type in any way we want in Lua. For example we can represent a `Vec3` as a table with `x`, `y`, `z` fields, or we can represent it as a userdata with a metatable which has `__index` and `__newindex` metamethods. The best part about this is we do not need to even own the types we are adding this `TypeData` for! This bypasses the pesky orphan rule and allows us to add custom Lua bindings for any type in Bevy. + +Note: for your own types you can do this by deriving `Reflect` and adding a `reflect(LuaProxyable)` attribute like so: + +```rust,ignore +#[derive(Reflect)] +#[reflect(LuaProxyable)] +pub struct MyType { + pub x: f32, + pub y: f32, + pub z: f32, +} + +impl LuaProxyable for MyType { + // ... +} +``` + +Now when you register your type with the `AppTypeRegistry` it will automatically have a `ReflectLuaProxyable` `TypeData` registered for it! You must not forget to register your type with: + +```rust,ignore +app.register_type::(); +``` + +## Script References + +All accesses to the bevy world are done via `ReflectReference` types which look like this: + +```rust,ignore +pub struct ReflectReference { + /// The reflection path from the root + pub(crate) path: ReflectionPath, + pub(crate) world_ptr: WorldPointer, +} +``` + +I.e. they are essentially just a path to the data in the Bevy world. This allows us to have a reference to a piece of data in the Bevy world which can be passed around and modified in Lua safely. + +The `ReflectionPath` itself consists of a "base" reference and a list of path segments. Most interesting of which is the base: + +```rust,ignore +pub(crate) enum ReflectBase { + /// A bevy component reference + Component { + comp: ReflectComponent, + entity: Entity, + }, + /// A bevy resource reference + Resource { res: ReflectResource }, + + /// A script owned reflect type (for example a vector constructed in lua) + ScriptOwned { val: Weak> }, +} +``` + +Given a valid base and a valid path we should always be able to get a valid reference to a piece of data in the Bevy world. Note we make use of other `TypeData` here, i.e. `ReflectComponent` and `ReflectResource` which store function pointers for the specific types of components/resources we are dealing with that allow us to interact with them. For example `ReflectComponent` let's us call: + +```rust,ignore +pub fn reflect<'a>( + &self, + entity: EntityRef<'a> +) -> Option<&'a (dyn Reflect + 'static)> +``` + +To retrieve a reflect reference to our component on a specific entity! + +You might be wondering how exactly we get a `TypeId` from a script in the first place, and the answer is we use a simple String type name! The journey begins in our custom `World` UserData: + +```rust,ignore + methods.add_method("get_type_by_name", |_, world, type_name: String| { + let w = world.read(); + + let registry: &AppTypeRegistry = w.get_resource().unwrap(); + + let registry = registry.read(); + + Ok(registry + .get_with_short_type_path(&type_name) + .or_else(|| registry.get_with_type_path(&type_name)) + .map(|registration| LuaTypeRegistration::new(Arc::new(registration.clone())))) + }); +``` + +Given a String type name like: `my_crate::MyType` we can then retrieve both `TypeId` and `TypeRegistration` structs, which we can use to retrieve any `TypeData` we need! + + +## Bevy to Lua Bridge + +Now finally our `ReflectReference` type has a custom `IntoLua` implementation which does the following: +- Check the type has a `ReflectLuaProxyable` `TypeData` +- If it does, call `ref_to_lua` on it and generate the Lua representation of the data +- If it does not, default to a "vanilla" representation of the data i.e. a [`ReflectedValue`](https://docs.rs/bevy_mod_scripting/0.3.0/bevy_mod_scripting/api/struct.ReflectedValue.html) which is a simple wrapper around a `ReflectReference`. It uses pure reflection to provide `__index` and `__newindex` metamethods for the data. + +```rust,ignore + fn into_lua(self, ctx: &'lua Lua) -> mlua::Result> { + let world = self.world_ptr.clone(); + let world = world.read(); + + let typedata = &world.resource::(); + let g = typedata.read(); + + let type_id = self.get(|s| s.type_id())?; + if let Some(v) = g.get_type_data::(type_id) { + v.ref_to_lua(self, ctx) + } else { + ReflectedValue { ref_: self }.into_lua(ctx) + } + } +``` + +Note that assigning to bevy via ReflectedValue's will check if the value we're trying to assign has a `ReflectLuaProxyable` type data, and if it does it uses it's `apply_lua` method to apply the new value to the `ReflectReference`, if it does not it expects it to be another `ReflectedValue` and will clone then apply it to itself using pure reflection. + +All primitive data types will have a `ReflectLuaProxyable` type data registered for them via their `FromLua` and `Clone` implementations. + + +## Proxy macros +We provide a set of macros to make it easier to define custom Lua bindings for your types. For example: + +```rust,ignore +#[derive(LuaProxy, Reflect, Resource, Default, Debug, Clone)] +#[reflect(Resource, LuaProxyable)] +#[proxy( + derive(clone), + functions[ + r#" + #[lua(kind="MutatingMethod")] + fn set_my_string(&mut self, another_string: Option); + "#, + r#" + #[lua(kind="MutatingMethod")] + fn set_with_another(&mut self, #[proxy] another: Self); + "#, + r#" + #[lua(kind="Method")] + fn get_my_string(&self) -> String; + "#, + r#" + #[lua(kind="Method",raw)] + fn raw_method(&self, ctx : &Lua) -> Result { + let a = ctx.globals().get::<_,String>("world").unwrap(); + let a = self.inner()?; + Ok("".to_owned()) + } + "#, + r#" + #[lua(kind="MetaMethod", metamethod="ToString")] + fn to_string(&self) -> String { + format!("{:#?}", _self) + } + "# + ]) + ] +pub struct MyProxiedStruct { + my_string: String, +} +``` + +will generate a `LuaMyProxiedStruct` which will act as the Lua representation of `MyProxiedStruct`. It will have the following methods: +- `set_my_string` which will set the `my_string` field of the struct +- `set_with_another` which will set the struct to be equal to another struct +- `get_my_string` which will return the `my_string` field of the struct +- `ToString` metamethod which will return a string representation of the struct + +It will also implement `UserData` for the proxy, meaning it can be passed around in Lua as a first class citizen. And it will implement `LuaProxyable` for `MyProxiedStruct`, meaning you can register your type and have it work in Lua with no extra work! + +## Bevy API Generation + +A good scripting system should be able to interact with the Bevy API as well as the user's own types. We provide a way to generate Lua bindings for the Bevy API using a rustc plugin. We scrape the Bevy codebase and generate proxy macro invocations like the one above for every appropriate `Reflect` implementing type, and package them in `APIProvider` structs which you can use to provide the Bevy API to your Lua scripts. + +This generator is a work in progress but it is designed with the possibility of generating bindings for ANY crate in mind. It is not limited to Bevy, and can be used to generate bindings for any crate which uses `Reflect` types. In theory you should be able to use the CLI to generate your own bindings without writing macros yourself! See the [`bevy_api_gen`](crates/bevy_api_gen/readme.md) crate for more information. + + diff --git a/assets/scripts/game_of_life.tl b/assets/scripts/game_of_life.lua similarity index 73% rename from assets/scripts/game_of_life.tl rename to assets/scripts/game_of_life.lua index f6db6efc..408e00de 100644 --- a/assets/scripts/game_of_life.tl +++ b/assets/scripts/game_of_life.lua @@ -1,9 +1,9 @@ math.randomseed(os.time()) -global function init() +function init() local LifeState = world:get_type_by_name("LifeState") - local life_state = world:get_component(entity,LifeState) as BevyAPI.LuaLifeState - local cells = life_state.cells as {integer} + local life_state = world:get_component(entity,LifeState) + local cells = life_state.cells -- set some cells alive for _=1,10000 do @@ -12,21 +12,22 @@ global function init() end end -global function on_update() +function on_update() local LifeState = world:get_type_by_name("LifeState") local Settings = world:get_type_by_name("Settings") - local life_state = world:get_component(entity,LifeState) as BevyAPI.LuaLifeState - local cells = life_state.cells as {integer} + local life_state = world:get_component(entity,LifeState) + -- note currently this is a copy of the cells, as of now the macro does not automatically support Vec proxies by reference + local cells = life_state.cells -- note that here we do not make use of LuaProxyable and just go off pure reflection - local settings = world:get_resource(Settings) as {string:any} - local dimensions = settings.physical_grid_dimensions as {integer} + local settings = world:get_resource(Settings) + local dimensions = settings.physical_grid_dimensions -- primitives are passed by value to lua, keep a hold of old state but turn 255's into 1's local prev_state = {} - for k,v in pairs(life_state.cells as {integer:integer}) do + for k,v in pairs(cells) do prev_state[k] = (not(v == 0)) and 1 or 0 end @@ -52,5 +53,6 @@ global function on_update() end end - + -- propagate the updates + life_state.cells = cells end \ No newline at end of file diff --git a/bevy_api_gen/Cargo.toml b/bevy_api_gen/Cargo.toml deleted file mode 100644 index e227864e..00000000 --- a/bevy_api_gen/Cargo.toml +++ /dev/null @@ -1,30 +0,0 @@ -[package] -name = "bevy_api_gen" -version = "0.5.0" -authors = ["Maksymilian Mozolewski "] -edition = "2021" -license = "MIT" -description = "A code generator creating macro invocations to support the changing bevy API" -repository = "https://github.com/makspll/bevy_mod_scripting" -homepage = "https://github.com/makspll/bevy_mod_scripting" -keywords = ["bevy", "gamedev", "scripting", "lua", "code-generation"] -categories = ["game-development"] -readme = "readme.md" - -[lib] -name = "bevy_api_gen_lib" -path = "src/lib.rs" - -[[bin]] -name = "bevy_api_gen" -path = "src/main.rs" - - -[dependencies] -rustdoc-types = "0.24.0" -clap = { version = "3.2.6", features = ["derive"] } -serde_json = "1.0.81" -toml = "0.5.9" -serde = { version = "1.0", features = ["derive"] } -serde_derive = "1.0.137" -indexmap = { version = "1.9.1", features = ["serde"] } diff --git a/bevy_api_gen/readme.md b/bevy_api_gen/readme.md deleted file mode 100644 index c6cc6195..00000000 --- a/bevy_api_gen/readme.md +++ /dev/null @@ -1,3 +0,0 @@ -# bevy_api_gen - -This crate is a part of the ["bevy_mod_scripting" workspace](https://github.com/makspll/bevy_mod_scripting). \ No newline at end of file diff --git a/bevy_api_gen/src/arg_validator.rs b/bevy_api_gen/src/arg_validator.rs deleted file mode 100644 index 6b21df3b..00000000 --- a/bevy_api_gen/src/arg_validator.rs +++ /dev/null @@ -1,228 +0,0 @@ -use rustdoc_types::{GenericArg, GenericArgs, Type}; - -/// A representation of valid argument types -#[derive(Debug)] -pub enum ArgType { - /// The primary identifier of the type - /// - /// Valid types right now follow the following syntax: - /// `(&)? (mut)? ident:ident` - Self_, - Base(String), - Generic { - base: Box, - args: Vec, - }, - Ref { - is_mut: bool, - ref_: Box, - }, -} - -impl fmt::Display for ArgType { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - ArgType::Base(b) => { - if b == "Self" { - f.write_str("self") - } else { - f.write_str(b) - } - } - ArgType::Ref { is_mut, ref_ } => { - if *is_mut { - f.write_str("&mut ")?; - } else { - f.write_str("&")?; - } - - ref_.fmt(f) - } - ArgType::Self_ => f.write_str("self"), - ArgType::Generic { base, args } => { - base.fmt(f)?; - f.write_str("<")?; - for (a, i) in args.iter().zip(1..) { - a.fmt(f)?; - if i != args.len() { - f.write_str(",")?; - } - } - f.write_str(">") - } - } - } -} - -impl TryFrom for ArgType { - type Error = String; - - fn try_from(value: Type) -> Result { - Self::try_from(&value) - } -} - -impl TryFrom<&Type> for ArgType { - type Error = String; - - fn try_from(value: &Type) -> Result { - match value { - Type::ResolvedPath(path) => { - let mut processed_args = Vec::default(); - - for a in &path.args { - if let GenericArgs::AngleBracketed { args, bindings } = a.as_ref() { - for generic in args { - match generic { - GenericArg::Type(type_) => processed_args.push(type_.try_into()?), - _ => { - return Err( - "Only types are allowed as generic arguments".to_owned() - ) - } - } - } - if !bindings.is_empty() { - return Err("Type bindings are not supported".to_owned()); - } - } else { - return Err("Parenthesised generics are not supported".to_owned()); - } - } - let base = Type::Primitive(path.name.to_string()).try_into()?; - if let base @ ArgType::Base(_) = base { - if !processed_args.is_empty() { - Ok(Self::Generic { - base: Box::new(base), - args: processed_args, - }) - } else { - Ok(base) - } - } else { - Err("Base is invalid".to_owned()) - } - } - Type::Primitive(name) | Type::Generic(name) => { - if name == "Self" { - Ok(Self::Self_) - } else { - Ok(Self::Base(name.split("::").last().unwrap().to_owned())) - } - } - Type::BorrowedRef { mutable, type_, .. } => Ok(Self::Ref { - is_mut: *mutable, - ref_: Box::new(type_.as_ref().try_into()?), - }), - _ => Err("".to_owned()), - } - } -} - -impl ArgType { - /// Produce an arbitrary output given the base identifier of this type or err if this is the base is a self receiver - pub fn map_base(&self, f: F) -> O - where - F: FnOnce(Result<&String, ()>) -> O, - { - match self { - ArgType::Base(b) => f(Ok(b)), - ArgType::Ref { is_mut: _, ref_ } => ref_.map_base(f), - ArgType::Self_ => f(Err(())), - ArgType::Generic { base, .. } => base.map_base(f), - } - } - - /// Produce an arbitrary output given the base identifier of this type, and optionally modify it - pub fn map_base_mut(&mut self, f: F) -> O - where - F: FnOnce(Result<&mut String, ()>) -> O, - { - match self { - ArgType::Base(b) => f(Ok(b)), - ArgType::Ref { is_mut: _, ref_ } => ref_.map_base_mut(f), - ArgType::Self_ => f(Err(())), - ArgType::Generic { base, .. } => base.map_base_mut(f), - } - } - - pub fn is_self(&self) -> bool { - self.map_base(|b| b.is_err()) - } - - /// Retrieves the base ident if this type is resolved otherwise returns None (i.e. in the case of a self receiver) - pub fn base_ident(&self) -> Option<&str> { - match self { - ArgType::Base(b) => Some(b), - ArgType::Ref { is_mut: _, ref_ } => ref_.base_ident(), - ArgType::Self_ => None, - ArgType::Generic { base, .. } => base.base_ident(), - } - } -} - -#[derive(PartialEq, Eq)] -pub enum ArgWrapperType { - Raw, - Wrapped, - /// in case of `self` argument - None, -} - -impl ArgWrapperType { - pub fn with_config(self_type: &str, type_: &ArgType, config: &Config) -> Option { - let base_ident = type_.base_ident().unwrap_or(self_type); - type_ - .is_self() - .then_some(ArgWrapperType::None) - .or_else(|| { - config - .primitives - .contains(base_ident) - .then_some(ArgWrapperType::Raw) - }) - .or_else(|| { - config - .types - .contains_key(base_ident) - .then_some(ArgWrapperType::Wrapped) - }) - } -} - -impl fmt::Display for ArgWrapperType { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - ArgWrapperType::Raw => f.write_str("Raw"), - ArgWrapperType::Wrapped => f.write_str("Wrapped"), - ArgWrapperType::None => f.write_str("None"), - } - } -} - -pub struct Arg { - pub type_: ArgType, - pub wrapper: ArgWrapperType, -} - -impl Arg { - pub fn new(type_: ArgType, wrapper: ArgWrapperType) -> Self { - Self { type_, wrapper } - } -} - -use std::fmt; - -use crate::Config; -impl fmt::Display for Arg { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let inner = self.type_.to_string(); - - match self.wrapper { - ArgWrapperType::Raw | ArgWrapperType::Wrapped => { - write!(f, "{}({inner})", self.wrapper) - } - ArgWrapperType::None => f.write_str(&inner), - } - } -} diff --git a/bevy_api_gen/src/config.rs b/bevy_api_gen/src/config.rs deleted file mode 100644 index 7909dbf8..00000000 --- a/bevy_api_gen/src/config.rs +++ /dev/null @@ -1,125 +0,0 @@ -use clap::Parser; -use indexmap::{IndexMap, IndexSet}; -use rustdoc_types::{Crate, Item, ItemEnum, Visibility}; -use serde::Deserialize; - -#[derive(Parser, Debug)] -#[clap(author, version, about, long_about = None)] -pub struct Args { - /// Paths to json files generated by `rustdoc -p --output-format json` - #[clap(short, long, value_parser)] - pub json: Vec, - - /// The path to toml config file which contains the types to be wrapped and overrides - #[clap(short, long, value_parser)] - pub config: String, - - /// if true the excluded methods will show up as commented out code with reasons for exclusion - #[clap(long)] - pub print_errors: bool, -} - -#[derive(Deserialize, Debug)] -pub struct Config { - #[serde(skip_deserializing, default)] - pub types: IndexMap, - - #[serde(rename = "types")] - pub types_: Vec, - - pub imports: String, - pub other: String, - - pub lua_api_defaults: String, - - /// Describes the set of non generic things which are representible - /// as simple lua types and don't need UserData proxies - pub primitives: IndexSet, - - pub manual_lua_types: Vec, -} - -#[derive(Deserialize, Debug)] -pub struct ManualLuaType { - pub name: String, - - /// whether or not to exclude this type from the type walker list - #[serde(default)] - pub dont_process: bool, - - /// the name exposed to scripts as global - #[serde(default)] - pub proxy_name: String, - - /// whether or not to include global proxy - #[serde(default)] - pub include_global_proxy: bool, - - /// whether or not to use a dummy instance (DummyTypeName) - #[serde(default)] - pub use_dummy_proxy: bool, -} - -#[derive(Deserialize, Debug, Hash, PartialEq, Eq)] -pub struct Newtype { - #[serde(rename = "type")] - pub type_: String, - - /// Override type-level docstring - pub doc: Option, - - #[serde(default)] - pub source: Source, - - #[serde(default)] - pub lua_methods: Vec, - - #[serde(default)] - pub derive_flags: Vec, - - #[serde(default)] - pub import_path: String, - - #[serde(default)] - pub traits: Vec, -} - -#[derive(Deserialize, Debug, PartialEq, Eq, Hash, Default)] -pub struct TraitMethods { - pub name: String, - pub import_path: String, -} - -#[derive(Deserialize, Debug, PartialEq, Eq, Hash)] -pub struct Source(pub String); - -impl Default for Source { - fn default() -> Self { - Self("bevy".to_string()) - } -} - -impl Newtype { - /// Returns true if this Type: - /// - describes the given item element - /// - if the element is fully described in the source crate - /// - if the element is a struct or enum - /// - if the element has no generics - pub fn matches_result(&self, item: &Item, source: &Crate) -> bool { - match &item.inner { - ItemEnum::Struct(s) => { - if !s.generics.params.is_empty() { - return false; - } - } - ItemEnum::Enum(_) => {} - _ => return false, - }; - - if source.external_crates.contains_key(&item.crate_id) { - return false; - }; - - matches!(item.visibility, Visibility::Public) - } -} diff --git a/bevy_api_gen/src/cratepath.rs b/bevy_api_gen/src/cratepath.rs deleted file mode 100644 index 7c5ab3fc..00000000 --- a/bevy_api_gen/src/cratepath.rs +++ /dev/null @@ -1,76 +0,0 @@ -use rustdoc_types::{Crate, Id, ItemEnum, Visibility}; - -pub(crate) fn get_path(id: &Id, source: &Crate) -> Option> { - match source.paths.get(id) { - Some(_) => return Some(vec![id.to_owned()]), - None => { - let ind = source.index.get(id)?; - if let Visibility::Restricted { parent, .. } = &ind.visibility { - if let Some(p_path) = get_path(parent, source) { - return Some(p_path); - } - } - let parents = source.index.iter().filter(|(_, p_item)| { - if let Some(name) = &ind.name { - if p_item.links.contains_key(name) { - return true; - } - } - if let ItemEnum::Impl(p_impl) = &p_item.inner { - return p_impl.items.contains(id); - } - if let ItemEnum::Import(p_import) = &p_item.inner { - if let Some(p_inner) = &p_import.id { - return p_inner == id; - } - return false; - } - if let ItemEnum::Module(p_mod) = &p_item.inner { - return p_mod.items.contains(id); - } - false - }); - - for (parent, _) in parents { - let path_o = get_path(parent, source); - if let Some(mut path) = path_o { - path.push(id.to_owned()); - return Some(path); - } - } - } - }; - None -} - -pub(crate) fn path_to_import(path: Vec, source: &Crate) -> Vec { - path.iter() - .rev() - .enumerate() - .rev() - .enumerate() - .map(|(starti, (endi, id))| { - let ind = source.index.get(id).unwrap(); - if starti == 0 { - return source.paths.get(id).unwrap().path.clone(); - } else if endi == 0 { - if let Some(name) = &ind.name { - return vec![name.to_owned()]; - } - } else if let Visibility::Restricted { parent: _, path } = &ind.visibility { - return path[2..].split("::").map(|x| x.to_string()).collect(); - } else if let ItemEnum::Module(module) = &ind.inner { - if !module.is_stripped { - return vec![source.index.get(id).unwrap().name.clone().unwrap()]; - } else { - return vec![]; - } - } - vec![] - }) - .reduce(|mut x, y| { - x.extend(y); - x - }) - .unwrap() -} diff --git a/bevy_api_gen/src/lib.rs b/bevy_api_gen/src/lib.rs deleted file mode 100644 index 7e71a388..00000000 --- a/bevy_api_gen/src/lib.rs +++ /dev/null @@ -1,23 +0,0 @@ -use rustdoc_types::Type; - -pub mod arg_validator; -pub mod config; -pub mod wrapper; -pub mod writer; - -pub use {arg_validator::*, config::*, wrapper::*, writer::*}; - -/// Currently only used for stringifying simple trait names -pub fn stringify_type(type_: &Type) -> Option { - match type_ { - Type::ResolvedPath(path) => Some(path.name.to_owned()), - Type::Generic(s) | Type::Primitive(s) => Some(s.to_owned()), - Type::QualifiedPath { - name, - args: _, - self_type: _, - trait_: _, - } => Some(name.to_owned()), - _ => None, - } -} diff --git a/bevy_api_gen/src/main.rs b/bevy_api_gen/src/main.rs deleted file mode 100644 index d479fcd5..00000000 --- a/bevy_api_gen/src/main.rs +++ /dev/null @@ -1,366 +0,0 @@ -pub mod cratepath; - -use bevy_api_gen_lib::{Args, Config, PrettyWriter, WrappedItem, WRAPPER_PREFIX}; - -use clap::Parser; -use cratepath::{get_path, path_to_import}; -use indexmap::{IndexMap, IndexSet}; -use rustdoc_types::{Crate, Impl, Item, ItemEnum}; -use serde_json::from_reader; -use std::{ - borrow::Cow, - collections::HashSet, - fs::{read_to_string, File}, - io::{self, BufReader}, -}; - -pub(crate) fn write_use_items_from_path( - module_name: &str, - path_components: &[String], - writer: &mut PrettyWriter, -) { - // generate imports for each item - writer.write_no_newline("use "); - - if module_name.starts_with("bevy") && module_name.len() > 5 { - writer.write_inline("bevy::"); - writer.write_inline(&module_name[5..]); - } else { - writer.write_inline(module_name); - } - - for item in path_components { - writer.write_inline("::"); - writer.write_inline(item); - } - writer.write_inline(";"); - writer.newline(); -} - -pub(crate) fn generate_macros( - crates: &[Crate], - config: Config, - args: &Args, -) -> Result { - // the items we want to generate macro instantiations for - let mut unmatched_types: HashSet<&String> = config.types.iter().map(|(k, _v)| k).collect(); - - let mut wrapped_items: Vec<_> = crates - .iter() - .flat_map(|source| { - source - .index - .iter() - .filter(|(_id, item)| { - item.name - .as_ref() - .and_then(|k| config.types.get(k)) - .map(|k| k.matches_result(item, source)) - .unwrap_or(false) - }) - .map(|(id, item)| { - // extract all available associated constants,methods etc available to this item - let mut self_impl: Option<&Impl> = None; - let mut impl_items: IndexMap<&str, Vec<(&Impl, &Item)>> = Default::default(); - let mut implemented_traits: IndexSet = Default::default(); - - let impls = match &item.inner { - ItemEnum::Struct(s) => &s.impls, - ItemEnum::Enum(e) => &e.impls, - _ => panic!("Only structs or enums are allowed!"), - }; - - impls.iter().for_each(|id| { - if let ItemEnum::Impl(i) = &source.index.get(id).unwrap().inner { - match &i.trait_ { - Some(t) => { - implemented_traits.insert(t.name.to_owned()); - } - None => self_impl = Some(i), - } - i.items.iter().for_each(|id| { - let it = source.index.get(id).unwrap(); - - impl_items - .entry(it.name.as_ref().unwrap().as_str()) - .or_default() - .push((i, it)); - }) - } else { - panic!("Expected impl items here!") - } - }); - - let config = config.types.get(item.name.as_ref().unwrap()).unwrap(); - - //let path_components = &source.paths.get(id).unwrap().path; - let path_components = get_path(id, source).unwrap_or_else(|| { - panic!("path not found for {:?} in {:?}", id, source.root) - }); - let path_components = path_to_import(path_components, source); - - let wrapper_name = format!("{WRAPPER_PREFIX}{}", item.name.as_ref().unwrap()); - let wrapped_type = item.name.as_ref().unwrap(); - WrappedItem { - wrapper_name, - wrapped_type, - path_components: Cow::Owned(path_components), - source, - config, - item, - self_impl, - impl_items, - crates, - has_global_methods: false, - implemented_traits, - } - }) - }) - .collect(); - - wrapped_items.iter().for_each(|v| { - unmatched_types.remove(&v.wrapped_type); - }); - - if !unmatched_types.is_empty() { - //panic!("Some types were not found in the given crates: {unmatched_types:#?}") - eprintln!("Some types were not found in the given crates: {unmatched_types:#?}") - } - - let mut writer = PrettyWriter::new(); - - // we want to preserve the original ordering from the config file - wrapped_items.sort_by_cached_key(|f| config.types.get_index_of(f.wrapped_type).unwrap()); - - writer.write_line("#![allow(clippy::all,unused_imports,deprecated)]"); - writer.write_line("// This file is generated by `bevy_mod_scripting_derive/main.rs` change the template not this file"); - writer.write_line("extern crate self as bevy_script_api;"); - writer.write_line("use bevy_mod_scripting_derive::impl_script_newtype;"); - - // user defined - config.imports.lines().for_each(|import| { - writer.write_line(import); - }); - // automatic - - wrapped_items.iter().for_each(|item| { - write_use_items_from_path( - &item.config.source.0, - &item.path_components[1..], - &mut writer, - ); - }); - - let mut imported = HashSet::::default(); - - wrapped_items.iter().for_each(|item| { - item.config.traits.iter().for_each(|trait_methods| { - if !imported.contains(&trait_methods.name) { - writer.write_no_newline("use "); - writer.write_inline(&trait_methods.import_path); - writer.write_inline(";"); - writer.newline(); - imported.insert(trait_methods.name.to_owned()); - } - }) - }); - - // make macro calls for each wrapped item - wrapped_items.iter_mut().for_each(|v| { - // macro invocation - writer.write_no_newline("impl_script_newtype!"); - writer.open_brace(); - writer.write_line("#[languages(on_feature(lua))]"); - - v.write_type_docstring(&mut writer, args); - writer.write_indentation(); - v.write_inline_full_path(&mut writer, args); - writer.write_inline(" : "); - writer.newline(); - - v.write_derive_flags_body(&config, &mut writer, args); - - writer.write_line("lua impl"); - writer.open_brace(); - v.write_impl_block_body(&mut writer, args); - writer.close_brace(); - - writer.close_brace(); - }); - - // write other code - for line in config.other.lines() { - writer.write_line(line); - } - - // now create the BevyAPIProvider - // first the globals - writer.write_line("#[cfg(feature=\"lua\")]"); - writer.write_line("#[derive(Default)]"); - writer.write_line("pub(crate) struct BevyAPIGlobals;"); - - writer.write_line("#[cfg(feature=\"lua\")]"); - writer.write_no_newline( - "impl bevy_mod_scripting_lua::tealr::mlu::ExportInstances for BevyAPIGlobals", - ); - writer.open_brace(); - writer.write_line("fn add_instances<'lua, T: bevy_mod_scripting_lua::tealr::mlu::InstanceCollector<'lua>>(self, instances: &mut T) -> bevy_mod_scripting_lua::tealr::mlu::mlua::Result<()>"); - writer.open_brace(); - for (global_name, type_, dummy_proxy) in wrapped_items - .iter() - .filter_map(|i| { - i.has_global_methods.then_some(( - i.wrapped_type.as_str(), - i.wrapper_name.as_str(), - false, - )) - }) - .chain(config.manual_lua_types.iter().filter_map(|i| { - i.include_global_proxy.then_some(( - i.proxy_name.as_str(), - i.name.as_str(), - i.use_dummy_proxy, - )) - })) - { - writer.write_no_newline("instances.add_instance("); - // type name - writer.write_inline("\""); - writer.write_inline(global_name); - writer.write_inline("\""); - // corresponding proxy - if dummy_proxy { - writer.write_inline(", crate::lua::util::DummyTypeName::<"); - writer.write_inline(type_); - writer.write_inline(">::new"); - writer.write_inline(")?;"); - writer.newline(); - } else { - writer.write_inline(", bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::<"); - writer.write_inline(type_); - writer.write_inline(">::new)?;"); - writer.newline(); - } - } - - writer.write_line("Ok(())"); - writer.close_brace(); - writer.close_brace(); - - // then the actual provider - writer.write_line("#[cfg(feature=\"lua\")]"); - writer.write_line("pub struct LuaBevyAPIProvider;"); - - // begin impl { - writer.write_line("#[cfg(feature=\"lua\")]"); - writer.write_no_newline("impl APIProvider for LuaBevyAPIProvider"); - writer.open_brace(); - - writer.write_line("type APITarget = Mutex;"); - writer.write_line("type ScriptContext = Mutex;"); - writer.write_line("type DocTarget = LuaDocFragment;"); - - // attach_api { - writer.write_no_newline( - "fn attach_api(&mut self, ctx: &mut Self::APITarget) -> Result<(), ScriptError>", - ); - writer.open_brace(); - writer.write_line("let ctx = ctx.get_mut().expect(\"Unable to acquire lock on Lua context\");"); - writer.write_line("bevy_mod_scripting_lua::tealr::mlu::set_global_env(BevyAPIGlobals,ctx).map_err(|e| ScriptError::Other(e.to_string()))"); - writer.close_brace(); - // } attach_api - - // get_doc_fragment - writer.write_no_newline("fn get_doc_fragment(&self) -> Option"); - writer.open_brace(); - writer.write_no_newline("Some(LuaDocFragment::new(\"BevyAPI\", |tw|"); - writer.open_brace(); - writer.write_line("tw"); - writer.write_line(".document_global_instance::().expect(\"Something went wrong documenting globals\")"); - - // include external types not generated by this file as well - for (type_, include_proxy) in - wrapped_items - .iter() - .map(|i| (i.wrapper_name.as_str(), i.has_global_methods)) - .chain(config.manual_lua_types.iter().filter_map(|i| { - (!i.dont_process).then_some((i.name.as_str(), i.include_global_proxy)) - })) - { - writer.write_no_newline(".process_type::<"); - writer.write_inline(type_); - writer.write_inline(">()"); - writer.newline(); - - if include_proxy { - writer.write_no_newline( - ".process_type::>()"); - writer.newline(); - } - } - - writer.close_brace(); - writer.write_line("))"); - - writer.close_brace(); - // } get_doc_fragment - - // impl default members - for line in config.lua_api_defaults.lines() { - writer.write_line(line); - } - - // register_with_app { - writer.write_no_newline("fn register_with_app(&self, app: &mut App)"); - writer.open_brace(); - for item in wrapped_items - .iter() - .map(|i| i.wrapped_type) - .chain(config.primitives.iter()) - { - writer.write_no_newline("app.register_foreign_lua_type::<"); - writer.write_inline(item); - writer.write_inline(">();"); - writer.newline(); - } - writer.close_brace(); - // } regiser_with_app - - writer.close_brace(); - // } end impl - - Ok(writer.finish()) -} - -pub fn main() -> Result<(), io::Error> { - let args = Args::parse(); - - let crates: Vec<_> = args - .json - .iter() - .map(|json| { - let f = File::open(json).unwrap_or_else(|_| panic!("Could not open {}", &json)); - let rdr = BufReader::new(f); - from_reader(rdr) - }) - .collect::, _>>()?; - - let f = read_to_string(&args.config)?; - let mut config: Config = toml::from_str(&f)?; - - config.types_.reverse(); - - while !config.types_.is_empty() { - let t = config.types_.remove(config.types_.len() - 1); - config.types.insert(t.type_.to_string(), t); - } - - let out = generate_macros(&crates, config, &args)?; - - println!("{}", out); - - Ok(()) -} diff --git a/bevy_api_gen/src/wrapper.rs b/bevy_api_gen/src/wrapper.rs deleted file mode 100644 index c9a36249..00000000 --- a/bevy_api_gen/src/wrapper.rs +++ /dev/null @@ -1,470 +0,0 @@ -use std::{borrow::Cow, collections::HashSet}; - -use indexmap::{IndexMap, IndexSet}; -use rustdoc_types::{Crate, Id, Impl, Item, ItemEnum, StructKind}; - -use crate::{Arg, ArgType, ArgWrapperType, Args, Config, Newtype, PrettyWriter}; - -pub static WRAPPER_PREFIX: &str = "Lua"; - -#[derive(Debug)] -pub struct WrappedItem<'a> { - pub wrapper_name: String, - pub wrapped_type: &'a String, - pub path_components: Cow<'a, [String]>, - pub source: &'a Crate, - pub config: &'a Newtype, - pub item: &'a Item, - /// The items coming from all trait implementations - pub impl_items: IndexMap<&'a str, Vec<(&'a Impl, &'a Item)>>, - pub implemented_traits: IndexSet, - pub self_impl: Option<&'a Impl>, - pub crates: &'a [Crate], - /// If this type has some things which are "static" this is set to true later - pub has_global_methods: bool, -} - -impl WrappedItem<'_> { - /// Writes full type path inline corresponding to `Reflect::type_name` of each type - /// - /// As: - /// ```rust,ignore - /// - /// this - /// | - /// |..........| - /// my_type_path::Type : Value : - /// UnaryOps( ... - /// ``` - pub fn write_inline_full_path(&self, writer: &mut PrettyWriter, _: &Args) { - if self.config.import_path.is_empty() { - writer.write_inline(&self.path_components.join("::")); - } else { - writer.write_inline(&self.config.import_path); - } - } - - /// Writes the docstring for the type over multiple lines - /// - /// As: - /// ```rust,ignore - /// - /// /// generated docstring - /// /// here - /// my_macro_key : Value : - /// UnaryOps( - /// ... - /// ) - /// + - /// ... - /// ``` - pub fn write_type_docstring(&self, writer: &mut PrettyWriter, _: &Args) { - let strings = if let Some(d) = &self.config.doc { - d.to_string() - } else { - self.item.docs.as_ref().cloned().unwrap_or_default() - }; - writer.set_prefix("///".into()); - strings.lines().for_each(|l| { - writer.write_line(l); - }); - writer.clear_prefix(); - } - - /// Writes the docstring for the given auto method over multiple lines - /// - /// As: - /// ```rust,ignore - /// - /// - /// my_macro_key : Value : - /// Methods( - /// /// generated docstring - /// /// here - /// my_method(usize) -> u32 - /// ) - /// + - /// ... - /// ``` - pub fn write_method_docstring(&self, id: &Id, writer: &mut PrettyWriter, _: &Args) { - writer.set_prefix("///".into()); - self.source - .index - .get(id) - .unwrap() - .docs - .as_ref() - .cloned() - .unwrap_or_else(|| "".to_owned()) - .lines() - .for_each(|l| { - writer.write_line(l); - }); - writer.clear_prefix(); - } - - /// Writes the contents of the impl block for this wrapper - /// - /// As: - /// - /// ```rust,ignore - /// impl { - /// ... // this! - /// } - /// ``` - pub fn write_impl_block_body(&self, writer: &mut PrettyWriter, _: &Args) { - self.config.lua_methods.iter().for_each(|v| { - writer.write_postfixed_line(v, ";"); - }) - } - - /// Generates all derive flags for the type, - /// - /// Returns additional imports necessary for the generated methods - /// - /// ```rust,ignore - /// my_type::Type : Value: - /// ... // flags go here - /// ``` - pub fn write_derive_flags_body( - &mut self, - config: &Config, - writer: &mut PrettyWriter, - args: &Args, - ) { - if self.implemented_traits.contains("Clone") { - // this flag requires cloning - writer.write_line("Clone +"); - } - - if self.implemented_traits.contains("Debug") { - // this flag requires cloning - writer.write_line("Debug +"); - } - - let mut used_method_identifiers: HashSet<&str> = HashSet::default(); - - writer.write_line("Methods"); - writer.open_paren(); - let mut has_global_methods = false; - self.impl_items - .iter() - .flat_map(|(_, items)| items.iter()) - .for_each(|(impl_, v)| { - // only select trait methods are allowed - if let Some(trait_) = &impl_.trait_ { - if self - .config - .traits - .iter() - .any(|f| { - trait_.name == f.name - }) - { - // keep going - } else { - return; - } - }; - - let (decl, generics) = match &v.inner { - ItemEnum::Function(f) => (&f.decl, &f.generics), - _ => return, - }; - - let mut errors = Vec::default(); - - let mut inner_writer = PrettyWriter::new(); - - self.write_method_docstring(&v.id, &mut inner_writer, args); - - inner_writer.write_inline(v.name.as_ref().unwrap()); - inner_writer.write_inline("("); - let mut is_global_method = true; - decl.inputs - .iter() - .enumerate() - .for_each(|(i, (declaration_name, tp))| { - let arg_type: Result = tp.try_into(); - - if let Ok(arg_type) = arg_type { - // if the underlying ident is self, we shouldn't wrap it when printing it - // if type is unknown no wrapper exists - let wrapper_type: Option = ArgWrapperType::with_config(self.wrapped_type, &arg_type, config); - - match wrapper_type { - Some(w) => { - inner_writer.write_inline(&Arg::new(arg_type, w).to_string()) - } - None => { - inner_writer.write_inline(&format!("")); - errors.push(format!("Unsupported argument {}, not a wrapped type or primitive", arg_type)); - return; - } - }; - - if declaration_name != "self" && i + 1 != decl.inputs.len() { - inner_writer.write_inline(","); - } else if declaration_name == "self" { - is_global_method = false; - // macro needs to recognize the self receiver - inner_writer.write_inline(":"); - } - } else { - errors.push(format!("Unsupported argument, Not a simple type: {}.", arg_type.unwrap_err())) - }; - }); - - if is_global_method { - has_global_methods = true; - } - - inner_writer.write_inline(")"); - - if let Some(tp) = &decl.output{ - let arg_type: Result = tp.try_into(); - if let Ok(arg_type) = arg_type { - if let ArgType::Ref { .. } = arg_type { - errors.push("references are not supported as return types".to_owned()); - return; - } - - // if the underlying ident is self, we shouldn't wrap it when printing it - // if type is unknown, no wrapper type exists - let wrapper_type: Option = ArgWrapperType::with_config(self.wrapped_type, &arg_type, config); - - match wrapper_type { - Some(w) => { - inner_writer.write_inline(" -> "); - inner_writer.write_inline(&Arg::new(arg_type, w).to_string()); - } - None => { - errors.push(format!("Unsupported argument, not a wrapped type or primitive {arg_type}")); - inner_writer.write_inline(&format!("")); - } - } - } else { - errors.push(format!("Unsupported argument, not a simple type: {}", arg_type.unwrap_err())) - } - }; - - if !generics.params.is_empty() { - errors.push("Generics on the method".to_owned()); - } - - if !errors.is_empty() { - if args.print_errors { - writer.set_prefix("// ".into()); - writer.write_line(&format!("Exclusion reason: {}", errors.join(","))); - writer.extend(inner_writer); - writer.clear_prefix(); - writer.newline(); - } - } else { - used_method_identifiers.insert(v.name.as_deref().unwrap()); - inner_writer.write_inline(","); - writer.extend(inner_writer); - writer.newline(); - } - }); - - self.has_global_methods = has_global_methods; - writer.close_paren(); - - writer.write_line("+ Fields"); - writer.open_paren(); - - if let ItemEnum::Struct(struct_) = &self.item.inner { - if let StructKind::Plain { - fields, - fields_stripped: _, - } = &struct_.kind - { - fields - .iter() - .map(|field_| self.source.index.get(field_).unwrap()) - .filter_map(|field_| match &field_.inner { - ItemEnum::StructField(type_) => { - Some((field_.name.as_ref().unwrap(), type_, field_)) - } - _ => None, - }) - .filter_map(|(name, type_, field_)| { - let arg_type: ArgType = type_.try_into().ok()?; - let base_ident = arg_type - .base_ident() // resolve self - .unwrap_or(self.wrapped_type.as_str()); - - // if the underlying ident is self, we shouldn't wrap it when printing it - let wrapper: ArgWrapperType = arg_type - .is_self() - .then_some(ArgWrapperType::None) - .or_else(|| { - config - .primitives - .contains(base_ident) - .then_some(ArgWrapperType::Raw) - }) - .or_else(|| { - config - .types - .contains_key(base_ident) - .then_some(ArgWrapperType::Wrapped) - }) - // we allow this since we later resolve unknown types to be resolved as ReflectedValues - .unwrap_or(ArgWrapperType::None); - - let arg = Arg::new(arg_type, wrapper); - let mut reflectable_type = arg.to_string(); - - // if we do not have an appropriate wrapper and this is not a primitive or it's not public - // we need to go back to the reflection API - if arg.wrapper == ArgWrapperType::None { - if field_.attrs.iter().any(|attr| attr == "#[reflect(ignore)]") { - return None; - } - - reflectable_type = "Raw(ReflectedValue)".to_owned(); - } - - if let Some(docs) = &field_.docs { - writer.set_prefix("/// ".into()); - docs.lines().for_each(|line| { - writer.write_line(line); - }); - writer.clear_prefix(); - }; - - // add underscore if a method with same name exists - used_method_identifiers - .contains(name.as_str()) - .then(|| writer.write_line(&format!("#[rename(\"_{name}\")]"))); - writer.write_no_newline(name); - writer.write_inline(": "); - writer.write_inline(&reflectable_type); - writer.write_inline(","); - writer.newline(); - - Some(()) - }) - .for_each(drop); - } - }; - writer.close_paren(); - - static BINARY_OPS: [(&str, &str); 5] = [ - ("add", "Add"), - ("sub", "Sub"), - ("div", "Div"), - ("mul", "Mul"), - ("rem", "Rem"), - ]; - writer.write_line("+ BinOps"); - writer.open_paren(); - BINARY_OPS.into_iter().for_each(|(op, rep)| { - if let Some(items) = self.impl_items.get(op) { - items - .iter() - .filter_map(|(impl_, item)| Some((impl_, item, (&impl_.for_).try_into().ok()?))) - .filter(|(_, _, self_type): &(&&Impl, &&Item, ArgType)| { - let base_ident = - self_type.base_ident().unwrap_or(self.wrapped_type.as_str()); - let is_self_type_the_wrapper = (base_ident == self.wrapped_type) - && config.types.contains_key(base_ident); - let is_primitive = config.primitives.contains(base_ident); - is_self_type_the_wrapper || is_primitive - }) - .for_each(|(impl_, item, _self_type)| { - let _ = match &item.inner { - ItemEnum::Function(m) => { - m.decl - .inputs - .iter() - .map(|(_, t)| { - // check arg is valid - let arg_type: ArgType = t.try_into()?; - - // if the underlying ident is self, we shouldn't wrap it when printing it - let wrapper_type = ArgWrapperType::with_config( - self.wrapped_type, - &arg_type, - config, - ) - .unwrap(); - - Ok(Arg::new(arg_type, wrapper_type).to_string()) - }) - .collect::, _>>() - .map(|v| v.join(&format!(" {} ", rep))) - .and_then(|expr| { - // then provide return type - // for these traits that's on associated types within the impl - let out_type = impl_ - .items - .iter() - .find_map(|v| { - let item = self.source.index.get(v).unwrap(); - if let ItemEnum::AssocType { default, .. } = - &item.inner - { - if let Some("Output") = item.name.as_deref() { - return Some(default.as_ref().unwrap()); - } - } - None - }) - .ok_or_else(|| expr.clone())?; - - let arg_type: ArgType = out_type.try_into()?; - // if the underlying ident is self, we shouldn't wrap it when printing it - let wrapper_type: ArgWrapperType = - ArgWrapperType::with_config( - self.wrapped_type, - &arg_type, - config, - ) - .unwrap(); - - if wrapper_type == ArgWrapperType::None { - return Err(arg_type.to_string()); - } - - let return_string = - Arg::new(arg_type, wrapper_type).to_string(); - - writer.write_no_newline(&expr); - writer.write_inline(" -> "); - writer.write_inline(&return_string); - writer.write_inline(","); - writer.newline(); - Ok(()) - }) - } - _ => panic!("Expected method"), - }; - }) - } - }); - writer.close_paren(); - - static UNARY_OPS: [(&str, &str); 1] = [("neg", "Neg")]; - - writer.write_line("+ UnaryOps"); - writer.open_paren(); - UNARY_OPS.into_iter().for_each(|(op, rep)| { - if let Some(items) = self.impl_items.get(op) { - items.iter().for_each(|(_, _)| { - writer.write_line(&format!("{rep} self -> self")); - }); - } - }); - writer.close_paren(); - - self.config.derive_flags.iter().for_each(|flag| { - writer.write_inline("+ "); - flag.lines().for_each(|line| { - writer.write_line(line); - }); - }); - } -} diff --git a/bevy_api_gen/src/writer.rs b/bevy_api_gen/src/writer.rs deleted file mode 100644 index cff94916..00000000 --- a/bevy_api_gen/src/writer.rs +++ /dev/null @@ -1,230 +0,0 @@ -use std::borrow::Cow; - -#[derive(Default)] -struct WriterState { - indentation_level: usize, - open_parenthesis: usize, - open_braces: usize, - open_brackets: usize, - prefix: Option>, -} - -/// Used to generate pretty indented code -#[derive(Default)] -pub struct PrettyWriter { - state: WriterState, - output: String, -} - -impl PrettyWriter { - pub fn new() -> Self { - Self::default() - } - - /// Combines this writer with another one. - /// - /// open brackets are inherited, the current string is indented with additional indentation - /// to match this writers indentation level. - /// If the indentation level is non-zero, it's added to this writer's. - /// Any prefixes are ignored. - pub fn extend(&mut self, other: PrettyWriter) { - for line in other.output.lines() { - self.write_line(line); - } - self.state.open_parenthesis += other.state.open_parenthesis; - self.state.open_braces += other.state.open_braces; - self.state.open_brackets += other.state.open_brackets; - self.state.indentation_level += other.state.indentation_level; - } - - /// Inserts a newline character inline - pub fn newline(&mut self) -> &mut Self { - self.output.push('\n'); - self - } - - /// Writes indentation and prefix without a newline - fn write_indented_prefix(&mut self) { - (0..self.state.indentation_level).for_each(|_| self.output.push('\t')); - - if let Some(prefix) = &self.state.prefix { - self.output.push_str(prefix); - } - } - - /// Writes a line at the current indentation level and append a newline at the end - pub fn write_line(&mut self, line: &str) -> &mut Self { - self.write_indented_prefix(); - self.output.push_str(line); - self.output.push('\n'); - self - } - - /// Writes without adding newline but keeps the indentation - pub fn write_no_newline(&mut self, line: &str) -> &mut Self { - self.write_indented_prefix(); - self.output.push_str(line); - self - } - - /// Writes a postfixed (after main text, before newline) line at the current indentation level and append a newline at the end - pub fn write_postfixed_line(&mut self, line: &str, postfix: &str) -> &mut Self { - self.write_indented_prefix(); - self.output.push_str(line); - self.output.push_str(postfix); - self.output.push('\n'); - self - } - - /// Writes a line without adding indentation or a newline - pub fn write_inline(&mut self, line: &str) -> &mut Self { - self.output.push_str(line); - self - } - - /// Writes indentation only, useful if you need to follow this by `write_inline` - pub fn write_indentation(&mut self) -> &mut Self { - self.write_indented_prefix(); - self - } - - /// Sets a prefix to be appended before every line written - pub fn set_prefix(&mut self, prefix: Cow<'static, str>) -> &mut Self { - self.state.prefix = Some(prefix); - self - } - - /// Clears the set prefix - pub fn clear_prefix(&mut self) -> &mut Self { - self.state.prefix = None; - self - } - - /// Increases intendation level permamently, does not write to the output yet - pub fn indent(&mut self) -> &mut Self { - self.state.indentation_level += 1; - self - } - - /// Decrases intendation level permamently, does not write to the output yet - pub fn dedent(&mut self) -> &mut Self { - self.state.indentation_level = self - .state - .indentation_level - .checked_sub(1) - .expect("No indentation to dedent"); - self - } - - /// Opens parenthesised section - pub fn open_paren(&mut self) -> &mut Self { - self.write_line("("); - self.indent(); - self.state.open_parenthesis += 1; - self - } - - /// Closes parenthesised section - pub fn close_paren(&mut self) -> &mut Self { - self.dedent(); - self.write_line(")"); - self.state.open_parenthesis = self - .state - .open_parenthesis - .checked_sub(1) - .expect("No parenthesis to close"); - self - } - - /// Opens braceed section - pub fn open_brace(&mut self) -> &mut Self { - self.write_line("{"); - self.indent(); - self.state.open_braces += 1; - self - } - - /// Closes braced section - pub fn close_brace(&mut self) -> &mut Self { - self.dedent(); - self.write_line("}"); - self.state.open_braces = self - .state - .open_braces - .checked_sub(1) - .expect("No brace to close"); - self - } - - /// Opens bracketed section - pub fn open_bracket(&mut self) -> &mut Self { - self.write_line("["); - self.indent(); - self.state.open_brackets += 1; - self - } - - /// Closes bracketed section - pub fn close_bracket(&mut self) -> &mut Self { - self.dedent(); - self.write_line("]"); - self.state.open_brackets = self - .state - .open_brackets - .checked_sub(1) - .expect("No bracket to close"); - self - } - - /// Consumes self and produces the output string, panics if there is unclosed parenthesis/brackets etc. - pub fn finish(self) -> String { - if self.state.open_braces > 0 { - panic!("{} unclosed braces", self.state.open_braces) - } else if self.state.open_brackets > 0 { - panic!("{} unclosed brackets", self.state.open_brackets) - } else if self.state.open_parenthesis > 0 { - panic!("{} unclosed parenthesis", self.state.open_parenthesis) - }; - - self.output - } -} - -#[cfg(test)] -mod test { - use crate::PrettyWriter; - - #[test] - fn test_indentation() { - let mut writer = PrettyWriter::new(); - - writer - .write_line("a") - .indent() - .write_line("a") - .indent() - .write_line("a") - .dedent() - .write_line("a") - .dedent() - .write_line("a"); - - assert_eq!(writer.finish(), "a\n\ta\n\t\ta\n\ta\na\n"); - } - - #[test] - fn test_parenthesis() { - let mut writer = PrettyWriter::new(); - - writer - .write_line("a") - .open_paren() - .open_paren() - .write_line("a") - .close_paren() - .close_paren() - .write_line("a"); - - assert_eq!(writer.finish(), "a\n(\n\t(\n\t\ta\n\t)\n)\na\n"); - } -} diff --git a/bevy_mod_scripting_common/src/arg.rs b/bevy_mod_scripting_common/src/arg.rs deleted file mode 100644 index 2591cba3..00000000 --- a/bevy_mod_scripting_common/src/arg.rs +++ /dev/null @@ -1,262 +0,0 @@ -use std::{borrow::Cow, result}; - -use proc_macro2::TokenStream; -use quote::ToTokens; -use syn::{ - parenthesized, - parse::{Parse, ParseStream}, - token::Paren, - Ident, Token, -}; - -#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] -pub enum SelfType { - Self_, - RefSelf, - MutSelf, -} - -impl SelfType { - /// converts this SelfType to a SimpleType given the value to substituted to self, preserves the references from self - pub fn resolve_as(self, as_: SimpleType) -> SimpleType { - match self { - SelfType::Self_ => SimpleType::BaseIdent(as_.base_ident().clone()), - SelfType::RefSelf => SimpleType::Ref { - ampersand: Some(Default::default()), - mut_: None, - type_: Box::new(as_), - }, - SelfType::MutSelf => SimpleType::Ref { - ampersand: Some(Default::default()), - mut_: Some(Default::default()), - type_: Box::new(as_), - }, - } - } - - /// Returns true if either a reference or mutable reference - pub fn is_any_ref(self) -> bool { - match self { - SelfType::Self_ => false, - SelfType::RefSelf => true, - SelfType::MutSelf => true, - } - } - - /// Returns true if mutable reference - pub fn is_mut_ref(self) -> bool { - match self { - SelfType::Self_ => false, - SelfType::RefSelf => false, - SelfType::MutSelf => true, - } - } -} - -impl Parse for SelfType { - fn parse(input: ParseStream) -> Result { - if input.peek(Token![&]) { - if input.peek2(Token![mut]) && input.peek3(Token![self]) { - input - .parse::() - .expect("Something went wrong parsing SelfType a "); - input - .parse::() - .expect("Something went wrong parsing SelfType b "); - input - .parse::() - .expect("Something went wrong parsing SelfType c"); - Ok(SelfType::MutSelf) - } else { - input - .parse::() - .expect("Something went wrong parsing SelfType d"); - input - .parse::() - .expect("Something went wrong parsing SelfType e"); - Ok(SelfType::RefSelf) - } - } else { - input.parse::()?; - Ok(SelfType::Self_) - } - } -} - -impl ToTokens for SelfType { - fn to_tokens(&self, tokens: &mut TokenStream) { - let tkns = match self { - SelfType::Self_ => quote::quote! {self}, - SelfType::RefSelf => quote::quote! {&self}, - SelfType::MutSelf => quote::quote! {&mut self}, - }; - - tokens.extend(tkns) - } -} - -#[derive(PartialEq, Eq, Hash, Debug, Clone)] -pub enum SimpleType { - BaseIdent(Ident), - Ref { - ampersand: Option, - mut_: Option, - type_: Box, - }, -} - -impl SimpleType { - /// Retrieves the base name of this simple type - pub fn base_ident(&self) -> &Ident { - match self { - SimpleType::BaseIdent(b) => b, - SimpleType::Ref { type_, .. } => type_.base_ident(), - } - } - - /// consumes self and produces the base ident - pub fn into_base_ident(self) -> Ident { - match self { - SimpleType::BaseIdent(b) => b, - SimpleType::Ref { type_, .. } => type_.into_base_ident(), - } - } - - pub fn mutate_base_ident(&mut self, mut f: F) { - match self { - SimpleType::BaseIdent(b) => f(b), - SimpleType::Ref { type_, .. } => type_.mutate_base_ident(f), - } - } - - /// Consumes self and produces a simple type without any outer references - /// e.g. `&MyType` -> `MyType` - pub fn strip_outer_refs(self) -> Self { - match self { - SimpleType::BaseIdent(_) => self, - SimpleType::Ref { type_, .. } => *type_, - } - } - - pub fn is_any_ref(&self) -> bool { - matches!(self, Self::Ref { .. }) - } - - pub fn is_mut_ref(&self) -> bool { - matches!(self, Self::Ref { mut_, .. } if mut_.is_some()) - } -} - -impl Parse for SimpleType { - fn parse(input: ParseStream) -> Result { - if input.peek(Token![&]) { - Ok(Self::Ref { - ampersand: input.parse().expect("Something went wrong"), - mut_: input.parse()?, - type_: input.parse()?, - }) - } else { - Ok(Self::BaseIdent(input.parse()?)) - } - } -} - -impl ToTokens for SimpleType { - fn to_tokens(&self, tokens: &mut TokenStream) { - match self { - SimpleType::BaseIdent(i) => tokens.extend(quote::quote!(#i)), - SimpleType::Ref { - ampersand, - mut_, - type_, - } => tokens.extend(quote::quote!(#ampersand #mut_ #type_)), - } - } -} - -#[derive(PartialEq, Eq, Hash, Debug)] -/// Raw argument expression argument received from the macro invocation -pub enum ArgType { - Raw { paren: Paren, type_: SimpleType }, - Wrapped { paren: Paren, type_: SimpleType }, - Self_(SelfType), -} - -#[allow(clippy::mixed_read_write_in_expression)] -impl Parse for ArgType { - fn parse(input: ParseStream) -> Result { - if input.peek(Ident) { - let ident: Ident = input.parse()?; - let f; - match ident.to_string().as_str() { - "Raw" => Ok(Self::Raw { paren: parenthesized!(f in input), type_: f.parse()? }), - "Wrapped" => Ok(Self::Wrapped { paren: parenthesized!(f in input), type_: f.parse()? }), - _ => panic!("Invalid argument, valid arguments are: [Raw(type),Wrapped(type),self,&self,&mut self]"), - } - } else { - Ok(Self::Self_(input.parse()?)) - } - } -} - -impl ToTokens for ArgType { - fn to_tokens(&self, tokens: &mut TokenStream) { - match self { - ArgType::Raw { type_, .. } => tokens.extend(quote::quote!(Raw(#type_))), - ArgType::Wrapped { type_, .. } => tokens.extend(quote::quote!(Wrapped(#type_))), - ArgType::Self_(s) => s.to_tokens(tokens), - }; - } -} - -impl ArgType { - /// retrieves the underlying argument type, if it's not a concrete type but a receiver, returns its type - pub fn type_(&self) -> result::Result<&SimpleType, SelfType> { - match self { - Self::Raw { type_, .. } | Self::Wrapped { type_, .. } => Ok(type_), - Self::Self_(s) => Err(*s), - } - } - - pub fn self_(&self) -> result::Result { - match self { - Self::Raw { type_, .. } | Self::Wrapped { type_, .. } => Err(type_), - Self::Self_(s) => Ok(*s), - } - } - - /// Retrieves the simple type or generates one using [`SelfType::resolve_as`](`SelfType`) if this is a self type - pub fn type_or_resolve SimpleType>(&self, mut f: F) -> Cow { - self.type_() - .map(Cow::Borrowed) - .unwrap_or_else(|self_| Cow::Owned(self_.resolve_as(f()))) - } - - pub fn is_any_ref(&self) -> bool { - match self { - ArgType::Raw { type_, .. } => type_.is_any_ref(), - ArgType::Wrapped { type_, .. } => type_.is_any_ref(), - ArgType::Self_(s) => s.is_any_ref(), - } - } - - pub fn is_mut_ref(&self) -> bool { - match self { - ArgType::Raw { type_, .. } => type_.is_mut_ref(), - ArgType::Wrapped { type_, .. } => type_.is_mut_ref(), - ArgType::Self_(s) => s.is_mut_ref(), - } - } - - pub fn is_wrapped(&self) -> bool { - matches!(self, Self::Wrapped { .. }) - } - - pub fn is_raw(&self) -> bool { - matches!(self, Self::Raw { .. }) - } - - pub fn is_self(&self) -> bool { - matches!(self, Self::Self_ { .. }) - } -} diff --git a/bevy_mod_scripting_common/src/derive_data.rs b/bevy_mod_scripting_common/src/derive_data.rs deleted file mode 100644 index 005c5de3..00000000 --- a/bevy_mod_scripting_common/src/derive_data.rs +++ /dev/null @@ -1,251 +0,0 @@ -use indexmap::IndexSet; - -use syn::{ - parenthesized, - parse::{Parse, ParseStream}, - punctuated::Punctuated, - token, Attribute, Block, DeriveInput, Field, Fields, Generics, Ident, Lit, LitStr, Meta, - MetaNameValue, Signature, Token, -}; - -pub const ATTRIBUTE_NAME: &str = "scripting"; - -pub enum ProxyData<'a> { - Struct(StructData<'a>), - TupleStruct(StructData<'a>), - UnitStruct(StructData<'a>), - Enum(EnumData<'a>), -} - -#[derive(Default, Debug)] -pub struct ProxyFlags { - flags: IndexSet, -} - -#[derive(Hash, Debug, PartialEq, Eq)] -pub enum ProxyFlag { - Debug, - Display, - Clone, - Fields, - Methods(Punctuated), - UnaryOps, - BinaryOps, -} - -#[derive(Hash, Debug, PartialEq, Eq)] -/// A representation of a proxied method, has the potential to define a full blown method as well, -/// it is up to each individual language to interpret the meaning of the attributes and method signatures. -/// -/// For example some function names may be reserved (`to_string` in lua for example) for operators. -pub struct ProxyMethod { - pub attrs: Vec, - pub sig: Signature, - pub body: Option, -} - -impl Parse for ProxyMethod { - fn parse(input: ParseStream) -> syn::Result { - Ok(Self { - attrs: input.call(Attribute::parse_outer)?, - sig: input.parse()?, - body: { - if input.peek(token::Brace) { - Some(input.parse()?) - } else { - None - } - }, - }) - } -} - -impl ProxyFlag { - pub fn from_ident_and_tokens( - ident: &Ident, - tokens: Option, - ) -> Result { - let name = ident.to_string(); - - let parse_ident_only = |f: fn() -> Self| { - if let Some(tokens) = &tokens { - let span = { - if tokens.is_empty() { - ident.span() - } else { - tokens.span() - } - }; - - Err(syn::Error::new( - span, - format!("'{name}' does not expect any arguments. Remove `({tokens})`"), - )) - } else { - Ok(f()) - } - }; - - let parse_with_body = |f: fn(ParseStream) -> Result| { - if let Some(tokens) = tokens { - f(tokens) - } else { - Err(syn::Error::new( - ident.span(), - format!("`{name}` expects arguments. Add `()`"), - )) - } - }; - - match name.as_str() { - "Clone" => parse_ident_only(|| Self::Clone), - "Debug" => parse_ident_only(|| Self::Debug), - "Methods" => parse_with_body(|input| { - Ok(Self::Methods(input.call(Punctuated::parse_terminated)?)) - }), - _ => Err(syn::Error::new_spanned(ident, "Unknown proxy flag")), - } - } -} - -pub struct ProxyMeta<'a> { - /// The name of the type being wrapped by this proxy - pub base_type_name: &'a Ident, - /// Flags representing additional required functionality - pub proxy_flags: ProxyFlags, - /// The generics defined on the base type - pub generics: &'a Generics, - /// type docstring - pub docstrings: Vec, -} - -pub struct StructData<'a> { - pub meta: ProxyMeta<'a>, - pub fields: Vec>, -} - -pub struct StructField<'a> { - pub data: &'a Field, - pub index: usize, -} - -pub struct EnumData<'a> { - pub meta: ProxyMeta<'a>, -} - -impl<'a> TryFrom<&'a DeriveInput> for ProxyData<'a> { - type Error = syn::Error; - - fn try_from(input: &'a DeriveInput) -> Result { - let flags = input - .attrs - .iter() - .filter_map(ProxyFlags::from_attribure) - .collect::, _>>()? - .into_iter() - .fold(ProxyFlags::default(), |mut a, b| { - a.merge(b); - a - }); - - let docstrings = input - .attrs - .iter() - .filter_map(|attr| { - if attr.path.is_ident("doc") { - match attr.parse_meta().unwrap() { - Meta::NameValue(MetaNameValue { - lit: Lit::Str(str), .. - }) => Some(str), - _ => unreachable!(), - } - } else { - None - } - }) - .collect::>(); - let meta = ProxyMeta { - base_type_name: &input.ident, - proxy_flags: flags, - generics: &input.generics, - docstrings, - }; - - match &input.data { - syn::Data::Struct(data) => { - let fields = Self::collect_struct_fields(&data.fields)?; - let struct_data = StructData { meta, fields }; - - match data.fields { - Fields::Named(..) => Ok(Self::Struct(struct_data)), - Fields::Unnamed(..) => Ok(Self::TupleStruct(struct_data)), - Fields::Unit => Ok(Self::UnitStruct(struct_data)), - } - } - syn::Data::Enum(_) => todo!(), - syn::Data::Union(_) => todo!(), - } - } -} - -impl ProxyData<'_> { - pub fn collect_struct_fields(fields: &Fields) -> Result, syn::Error> { - fields - .iter() - .enumerate() - .map(|(index, field)| Ok(StructField { data: field, index })) - .collect() - } -} - -impl ProxyFlags { - /// Parses a single proxy flag - pub fn parse_one(input: ParseStream) -> Result { - let attr_ident = input.parse::()?; - - // work out if there is a payload in the token - if input.peek(token::Paren) { - let tokens; - parenthesized!(tokens in input); - ProxyFlag::from_ident_and_tokens(&attr_ident, Some(&tokens)) - } else { - ProxyFlag::from_ident_and_tokens(&attr_ident, None) - } - } - - /// Parses proxy flags separated by the given separator - pub fn parse_separated( - input: ParseStream, - ) -> Result, syn::Error> { - Punctuated::<_, S>::parse_terminated_with(input, Self::parse_one) - } - - /// Parses a whole attribute with proxy flag annotations. Returns Some value if the attribute has a valid path, and None otherwise - pub fn from_attribure(attr: &Attribute) -> Option> { - if !attr.path.is_ident(ATTRIBUTE_NAME) { - return None; - } - - Some( - attr.parse_args_with(Self::parse_separated::) - .map(IntoIterator::into_iter) - .map(Iterator::collect), - ) - } - - pub fn contains(&self, flag: &ProxyFlag) -> bool { - self.flags.contains(flag) - } - - pub fn merge(&mut self, o: Self) { - self.flags.extend(o.flags) - } -} - -impl FromIterator for ProxyFlags { - fn from_iter>(iter: T) -> Self { - Self { - flags: FromIterator::from_iter(iter), - } - } -} diff --git a/bevy_mod_scripting_common/src/derive_flag.rs b/bevy_mod_scripting_common/src/derive_flag.rs deleted file mode 100644 index c283c7d9..00000000 --- a/bevy_mod_scripting_common/src/derive_flag.rs +++ /dev/null @@ -1,225 +0,0 @@ -use proc_macro2::{Span, TokenStream}; -use syn::{ - parenthesized, - parse::{Parse, ParseStream}, - punctuated::Punctuated, - token::Paren, - Attribute, Ident, Member, Token, -}; - -use crate::{ops::*, utils::impl_parse_enum}; - -use quote::ToTokens; - -use super::arg::ArgType; - -impl_parse_enum!(input,ident: -#[derive(PartialEq,Eq,Hash)] -pub enum DeriveFlag { - - /// Tells the implementors this type supports `Debug` - Debug => {Ok(Self::Debug{ident})}, - /// Tells the implementors this type supports `Display` - Display => {Ok(Self::Display{ident})}, - /// Tells the implementors this type supports `Clone` - Clone{} => {Ok(Self::Clone{ident})}, - /// Tells the implementors what fields are available on this type - Fields { - paren: Paren, - fields: Punctuated - } => { - let f; - Ok(Self::Fields { - ident, - paren: parenthesized!(f in input), - fields: f.parse_terminated(AutoField::parse)? - }) - }, - /// Tells the implementors which methods are available on this type - Methods { - paren: Paren, - methods: Punctuated - } => { - let f; - Ok(Self::Methods{ - ident, - paren: parenthesized!(f in input), - methods: f.parse_terminated(AutoMethod::parse)? - }) - }, - /// Tells the implementors which unary operations this type supports - UnaryOps{ - paren : Paren, - ops: Punctuated - - } => { - let f; - Ok(Self::UnaryOps{ - ident, - paren: parenthesized!(f in input), - ops : f.parse_terminated(OpExpr::parse)? - }) - }, - /// Tells the implementors which binary operations this type supports - BinOps { - paren: Paren, - ops: Punctuated - } => { - let f; - Ok(Self::BinOps { - ident, - paren: parenthesized!(f in input), - ops: f.parse_terminated(OpExpr::parse)?, - }) - } -} -); - -// #[derive(PartialEq, Eq, Hash, Debug)] -// pub(crate) struct MethodMacroInvokation { -// pub target: TypePath, -// pub arrow: Token![->], -// pub identifier: LuaMethodType, -// pub paren: Paren, -// pub args: Punctuated, -// } - -// #[allow(clippy::mixed_read_write_in_expression)] -// impl Parse for MethodMacroInvokation { -// fn parse(input: ParseStream) -> Result { -// let f; -// Ok(Self { -// target: input.parse()?, -// arrow: input.parse()?, -// identifier: input.parse()?, -// paren: parenthesized!(f in input), -// args: f.parse_terminated(MethodMacroArg::parse)?, -// }) -// } -// } - -#[derive(PartialEq, Eq, Hash)] -pub struct AutoMethod { - pub docstring: Vec, - pub ident: Ident, - pub paren: Paren, - pub self_: Option<(ArgType, Token![:])>, - pub args: Punctuated, - pub out: Option, -} - -impl ToTokens for AutoMethod { - fn to_tokens(&self, tokens: &mut TokenStream) { - let docstring = self.docstring.iter(); - let id = &self.ident; - let args = &self.args; - let self_ = self.self_.as_ref().map(|(a, _)| quote::quote!(#a:)); - let out = self.out.as_ref().map(|t| quote::quote! {-> #t}); - tokens.extend(quote::quote! { - #(#docstring)* - #id(#self_ #args) #out - }) - } -} - -#[allow(clippy::mixed_read_write_in_expression)] -impl Parse for AutoMethod { - fn parse(input: ParseStream) -> Result { - let f; - let o = Ok(Self { - docstring: Attribute::parse_outer(input)?, - ident: input.parse()?, - paren: parenthesized!(f in input), - self_: { - let parser = |p: ParseStream| { - Ok::<_, syn::Error>((p.parse::()?, p.parse::()?)) - }; - let fork = f.fork(); - if parser(&fork).is_ok() { - Some(parser(&f).expect("Something went wrong")) - } else { - None - } - }, - args: f.parse_terminated(ArgType::parse)?, - out: if input.peek(Token![->]) { - input.parse::]>()?; - Some(input.parse()?) - } else { - None - }, - }); - o - } -} - -#[derive(PartialEq, Eq, Hash)] -pub struct AutoFieldAttributes { - pub script_name: Option, -} - -impl TryFrom<&[Attribute]> for AutoFieldAttributes { - type Error = syn::Error; - - fn try_from(value: &[Attribute]) -> Result { - let mut out = Self { script_name: None }; - - for v in value { - let meta = v.parse_meta()?; - - if let Some(ident) = meta.path().get_ident() { - if *ident == "rename" { - if let syn::Meta::List(l) = &meta { - for nested in &l.nested { - if let syn::NestedMeta::Lit(syn::Lit::Str(s)) = nested { - out.script_name = Some(s.parse()?) - } - } - } - } - } - } - - Ok(out) - } -} - -#[derive(PartialEq, Eq, Hash)] -pub struct AutoField { - pub docstring: Vec, - pub attrs: Vec, - pub parsed_attrs: AutoFieldAttributes, - pub member: Member, - pub colon: Token![:], - pub type_: ArgType, -} - -impl Parse for AutoField { - fn parse(input: ParseStream) -> Result { - let attrs = Attribute::parse_outer(input)?; - let split_idx = attrs.partition_point(|attr| *attr.path.get_ident().unwrap() == "doc"); - Ok(Self { - docstring: attrs[0..split_idx].to_owned(), - attrs: attrs[split_idx..].to_owned(), - parsed_attrs: attrs[split_idx..].try_into()?, - member: input.parse()?, - colon: input.parse()?, - type_: input.parse()?, - }) - } -} - -impl ToTokens for AutoField { - fn to_tokens(&self, tokens: &mut TokenStream) { - let docstring = self.docstring.iter(); - let attrs = self.attrs.iter(); - let id = &self.member; - let type_ = &self.type_; - - tokens.extend(quote::quote! { - #(#docstring)* - #(#attrs)* - #id : #type_ - }) - } -} diff --git a/bevy_mod_scripting_common/src/implementor.rs b/bevy_mod_scripting_common/src/implementor.rs deleted file mode 100644 index 8c83675c..00000000 --- a/bevy_mod_scripting_common/src/implementor.rs +++ /dev/null @@ -1,75 +0,0 @@ -use proc_macro2::TokenStream; -use quote::{quote_spanned, ToTokens}; -use syn::{parse::Parse, spanned::Spanned, Result}; - -use crate::{derive_flag::DeriveFlag, newtype::Newtype}; - -/// A function on the wrapped type either wrapping an existing function or providing -/// additional functionality -pub trait WrapperFunction: Parse + ToTokens {} - -/// script-side API Implementation generator for a particular script language. -/// Helps avoid alot of boilerplate -pub trait WrapperImplementor: 'static { - type Function: WrapperFunction; - - fn module_name() -> &'static str; - - /// Generates the type definition for the given newtype - fn generate_newtype_definition(&mut self, new_type: &Newtype) -> Result; - - /// Generates the necessary trait implementations for the given newtype exposing the given functionality - fn generate_newtype_implementation<'a, I: Iterator>( - &mut self, - new_type: &'a Newtype, - functions: I, - ) -> Result; - - /// Generate methods from derive flags and newtype implementation blocks - fn generate_derive_flag_functions<'a, I: Iterator>( - &mut self, - new_type: &'a Newtype, - derive_flags: I, - ) -> Result>; - - /// Generate methods from newtype - fn generate_newtype_functions(&mut self, new_type: &Newtype) -> Result>; - - /// Turns newtype list into fully implemented wrapper types - fn generate(&mut self, new_type: Newtype) -> Result { - let definition = self.generate_newtype_definition(&new_type)?; - - let mut functions = - self.generate_derive_flag_functions(&new_type, new_type.args.flags.iter())?; - - functions.extend(self.generate_newtype_functions(&new_type)?); - - let implementation = self.generate_newtype_implementation(&new_type, functions.iter())?; - - Ok(quote_spanned! {new_type.span()=> - #definition - #implementation - }) - } - - // fn generate_all(&mut self, new_types: &NewtypeList) -> Result { - // let mut methods_so_far = IndexMap::default(); - - // let newtypes : TokenStream = new_types.new_types.iter().map(|v| { - // self.generate(v, &mut methods_so_far) - // }).collect::>()?; - - // let globals = self.generate_globals(new_types,methods_so_far)?; - // let module_name = format_ident!("{}",Self::module_name()); - // let header = &new_types.module_headers; - - // Ok(quote!{ - // #[allow(unused_parens,unreachable_patterns,unused_variables)] - // pub mod #module_name { - // #header - // #newtypes - // #globals - // } - // }) - // } -} diff --git a/bevy_mod_scripting_common/src/lib.rs b/bevy_mod_scripting_common/src/lib.rs deleted file mode 100644 index 3dbaf8d5..00000000 --- a/bevy_mod_scripting_common/src/lib.rs +++ /dev/null @@ -1,7 +0,0 @@ -pub mod arg; -pub mod derive_data; -pub mod derive_flag; -pub mod implementor; -pub mod newtype; -pub mod ops; -pub mod utils; diff --git a/bevy_mod_scripting_common/src/newtype.rs b/bevy_mod_scripting_common/src/newtype.rs deleted file mode 100644 index 3e1d76b4..00000000 --- a/bevy_mod_scripting_common/src/newtype.rs +++ /dev/null @@ -1,177 +0,0 @@ -use std::collections::HashSet; - -use indexmap::IndexSet; -use proc_macro2::TokenStream; -use syn::{ - braced, - parse::{Parse, ParseStream}, - punctuated::*, - spanned::Spanned, - token::*, - Attribute, Ident, Token, TypePath, -}; - -use crate::{derive_flag::DeriveFlag, utils::EmptyToken}; -use quote::ToTokens; - -pub struct NewtypeArgs { - pub docstring: Vec, - pub base_type: TypePath, - pub type_colon: Token![:], - pub base_type_ident: Ident, - pub wrapper_type: Ident, - pub flags: IndexSet, -} - -impl NewtypeArgs { - /// Verify the given derive flags - pub fn verify(self) -> Result { - let mut fields = None; - let mut methods = None; - - self.flags.iter().for_each(|f| match f { - DeriveFlag::Fields { .. } => fields = Some(f), - DeriveFlag::Methods { .. } => methods = Some(f), - _ => {} - }); - - let mut seen_identifiers: HashSet<&Ident> = HashSet::default(); - // verify there aren't any name clashes - if let ( - Some(DeriveFlag::Fields { fields, .. }), - Some(DeriveFlag::Methods { methods, .. }), - ) = (fields, methods) - { - for m in methods { - if seen_identifiers.contains(&m.ident) { - return Err(syn::Error::new_spanned( - m, - format!( - "Method name `{}` clashes with another field or method", - &m.ident - ), - )); - } - seen_identifiers.insert(&m.ident); - } - - for f in fields { - match &f.member { - syn::Member::Named(n) => { - let contains = if let Some(v) = &f.parsed_attrs.script_name { - seen_identifiers.contains(v) - } else { - seen_identifiers.contains(n) - }; - if contains { - return Err(syn::Error::new_spanned( - n, - format!("Field name `{}` clashes with another field or method, use #[rename(\"new_name\")] to rename the field on script side", n), - )); - } - seen_identifiers.insert(n); - } - syn::Member::Unnamed(_) => {} - } - } - } - - Ok(self) - } -} - -impl ToTokens for NewtypeArgs { - fn to_tokens(&self, tokens: &mut TokenStream) { - let docstrings = self.docstring.iter(); - let base_type = &self.base_type; - let flags = self.flags.iter(); - tokens.extend(quote::quote! { - #(#docstrings)* - #base_type : #(#flags)+* - }) - } -} - -impl Parse for NewtypeArgs { - fn parse(input: ParseStream) -> Result { - let docstring = Attribute::parse_outer(input)?; - let base_type: TypePath = input.parse()?; - let short_base_type: String = base_type - .path - .segments - .last() - .ok_or_else(|| input.error("Path does not have identifier"))? - .ident - .to_string(); - let short_wrapper_type: String = format!("Lua{}", short_base_type); - let sbt_ident = Ident::new(&short_base_type, base_type.span()); - let swt_ident = Ident::new(&short_wrapper_type, base_type.span()); - let out = Self { - docstring, - wrapper_type: swt_ident, - base_type_ident: sbt_ident, - base_type, - type_colon: input.parse()?, - flags: Punctuated::::parse_separated_nonempty(input)? - .into_iter() - .collect::>(), - }; - out.verify() - } -} - -pub struct WrapperFunctionList { - pub label: Ident, - pub impl_: Token![impl], - pub braces: Brace, - pub functions: TokenStream, -} - -impl ToTokens for WrapperFunctionList { - fn to_tokens(&self, tokens: &mut TokenStream) { - let ident = &self.label; - let functions = &self.functions; - tokens.extend(quote::quote! { - #ident impl { - #functions - } - }) - } -} - -#[allow(clippy::mixed_read_write_in_expression)] -impl Parse for WrapperFunctionList { - fn parse(input: ParseStream) -> Result { - let f; - Ok(Self { - label: input.parse()?, - impl_: input.parse()?, - braces: braced!(f in input), - functions: f.parse()?, - }) - } -} - -pub struct Newtype { - pub args: NewtypeArgs, - pub impl_blocks: Punctuated, -} - -impl ToTokens for Newtype { - fn to_tokens(&self, tokens: &mut TokenStream) { - let args = &self.args; - let functions = &self.impl_blocks; - tokens.extend(quote::quote!( - {#args #functions} - )) - } -} - -impl Parse for Newtype { - fn parse(input: ParseStream) -> Result { - Ok(Self { - args: input.parse()?, - impl_blocks: Punctuated::parse_terminated(input)?, - }) - } -} diff --git a/bevy_mod_scripting_common/src/ops.rs b/bevy_mod_scripting_common/src/ops.rs deleted file mode 100644 index cc974af8..00000000 --- a/bevy_mod_scripting_common/src/ops.rs +++ /dev/null @@ -1,160 +0,0 @@ -use proc_macro2::{Span, TokenStream}; -use quote::{quote_spanned, ToTokens}; -use syn::{ - parse::{Parse, ParseStream}, - Token, -}; - -use crate::utils::impl_parse_enum; - -use super::arg::ArgType; - -impl_parse_enum!(input,ident: -#[derive(PartialEq,Eq,Hash,Clone,Debug)] -pub enum OpName { - Add => {Ok(Self::Add{ident})}, - Sub => {Ok(Self::Sub{ident})}, - Mul => {Ok(Self::Mul{ident})}, - Div => {Ok(Self::Div{ident})}, - Rem => {Ok(Self::Rem{ident})}, - Neg => {Ok(Self::Neg{ident})}, - -} - -impl MathOpName { - pub fn to_rlua_metamethod_path(&self) -> TokenStream { - match self { - OpName::Add { ident } => quote_spanned!(ident.span()=> Add), - OpName::Sub { ident } => quote_spanned!(ident.span()=> Sub), - OpName::Mul { ident } => quote_spanned!(ident.span()=> Mul), - OpName::Div { ident } => quote_spanned!(ident.span()=> Div), - OpName::Rem { ident } => quote_spanned!(ident.span()=> Mod), - OpName::Neg { ident } => quote_spanned!(ident.span()=> Unm), - - } - } - - pub fn to_rust_method_ident(&self) -> TokenStream { - match self { - Self::Add{ident} => quote_spanned!{ident.span()=> add}, - Self::Sub{ident} => quote_spanned!{ident.span()=> sub}, - Self::Mul{ident} => quote_spanned!{ident.span()=> mul}, - Self::Div{ident} => quote_spanned!{ident.span()=> div}, - Self::Rem{ident} => quote_spanned!{ident.span()=> rem}, - Self::Neg{ident} => quote_spanned!{ident.span()=> neg}, - - } - } -} -); - -/// Left or Right -#[derive(Clone, Copy, PartialEq, Eq)] -pub enum Side { - Left, - Right, -} - -use std::fmt; -impl fmt::Display for Side { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Side::Left => f.write_str("Left"), - Side::Right => f.write_str("Right"), - } - } -} - -impl Side { - pub fn opposite(&self) -> Self { - match self { - Side::Left => Self::Right, - Side::Right => Self::Left, - } - } -} - -/// Represents either a unary or binary expression, where at least one side has the receiver (self) type -#[derive(PartialEq, Eq, Hash, Debug)] -pub struct OpExpr { - pub left: Option, - pub op: OpName, - pub right: ArgType, - pub arrow: Token![->], - pub return_type: ArgType, -} - -impl Parse for OpExpr { - fn parse(input: ParseStream) -> Result { - let s = Self { - left: (input.fork()) - .parse::() - .is_err() - .then(|| Ok::<_, syn::Error>(Some(input.parse()?))) - .unwrap_or(Ok(None))?, - op: input.parse()?, - right: input.parse()?, - arrow: input.parse()?, - return_type: input.parse()?, - }; - - if s.has_receiver() { - Ok(s) - } else { - Err(syn::Error::new_spanned(s, "Invalid expression, binary/unary expressions expect at least one side to be one of: [self,&self,&mut self]")) - } - } -} - -impl ToTokens for OpExpr { - fn to_tokens(&self, tokens: &mut TokenStream) { - let left = &self.left; - let op = &self.op; - let right = &self.right; - let return_type = &self.return_type; - - tokens.extend(quote::quote! { - #left #op #right -> #return_type - }) - } -} - -impl OpExpr { - pub fn is_binary(&self) -> bool { - self.left.is_some() - } - - fn has_receiver(&self) -> bool { - if let Some(ArgType::Self_(_)) = self.left { - true - } else if let ArgType::Self_(_) = self.right { - true - } else { - true - } - } - - pub fn has_receiver_on_side(&self, side: Side) -> bool { - match side { - Side::Left => self.left.as_ref().map(|t| t.is_self()).unwrap_or_default(), - Side::Right => self.right.is_self(), - } - } - - /// Maps the given side if it exists (right is guaranteed to exist, left is not) - pub fn map_side O>(&self, side: Side, f: F) -> Option { - match side { - Side::Left => self.left.as_ref().map(f), - Side::Right => Some(f(&self.right)), - } - } - - /// call map_side on both Left and Right sides and return the results as a tuple - pub fn map_both O>(&self, mut f: F) -> (Option, O) { - ( - self.map_side(Side::Left, |a| f(a, Side::Left)), - self.map_side(Side::Right, |a| f(a, Side::Right)) - .expect("Cannot happen"), - ) - } -} diff --git a/bevy_mod_scripting_common/src/utils.rs b/bevy_mod_scripting_common/src/utils.rs deleted file mode 100644 index b7e2369a..00000000 --- a/bevy_mod_scripting_common/src/utils.rs +++ /dev/null @@ -1,140 +0,0 @@ -/// Utility for parsing enums based on the variant identifier first -macro_rules! impl_parse_enum { - ( - $input_stream:ident,$parsed_ident:ident: - $($(#[$($meta:meta)*])+)? - $vis:vis enum $name:ident { - $( - $($(#[$($meta_inner:meta)*])+)? - $field:ident $( - { - $( - $arg_name:ident : $arg_type:ty - ),* - } - - )? => {$($parser:tt)*} - ),* - $(,)? - } - - $( - impl $_:ident { - $($other_impls:tt)* - } - )? - ) => { - $($(#[$($meta)*])+)? - $vis enum $name { - $( - $($(#[$($meta_inner)*])+)? - $field { - /// The identifier of the enum variant - ident: syn::Ident, - $( - $( - $arg_name : $arg_type - ),* - )? - } - ),* - - } - #[allow(clippy::mixed_read_write_in_expression)] - impl Parse for $name { - fn parse($input_stream: ParseStream) -> Result { - let $parsed_ident : syn::Ident = $input_stream.parse()?; - - match $parsed_ident.to_string().as_str() { - $( - stringify!($field) => {$($parser)*}, - )* - _ => Err(syn::Error::new_spanned($parsed_ident, format!("Invalid derive flag, try one of [{}]",Self::variants()))), - } - } - } - - impl ToTokens for $name { - fn to_tokens(&self, ts: &mut proc_macro2::TokenStream) { - let ident = syn::Ident::new(self.to_str(),Span::call_site()); - ts.extend(quote::quote_spanned!{syn::spanned::Spanned::span(ts)=> #ident}); - } - } - - #[allow(unused_variables)] - impl $name { - paste::paste!{ - $($($other_impls)*)? - - pub fn variants() -> &'static str{ - concat!($( - stringify!($field),"," - ),* - ) - } - - pub fn to_str(&self) -> &'static str { - match self { - $( - Self::$field{ident,$($($arg_name),*)?} => stringify!($field) - ),* - } - } - - $( - pub fn [](&self) -> bool{ - if let Self::$field{ident,$($($arg_name),*)?} = self{ - return true - } else { - return false - } - } - )* - } - - } - }; -} - -pub(crate) use impl_parse_enum; -use proc_macro2::TokenStream; -use quote::ToTokens; -use syn::{ - parse::{Parse, ParseStream}, - Attribute, Type, -}; - -pub fn attribute_to_string_lit(attrs: &Attribute) -> TokenStream { - attrs.tokens.clone().into_iter().skip(1).collect() -} - -/// Converts the given ToTokens into token stream, stringifies it and removes whitespace -pub fn stringify_token_group(t: &T) -> String { - let mut k = t.into_token_stream().to_string(); - k.retain(|c| !c.is_whitespace()); - k -} - -/// Converts simple type to base string (i.e. one which has a single type identifier) -pub fn type_base_string(t: &Type) -> Option { - match t { - Type::Paren(v) => type_base_string(&v.elem), - Type::Path(p) => Some(p.path.segments.last()?.ident.to_string()), - Type::Ptr(p) => type_base_string(&p.elem), - Type::Reference(r) => type_base_string(&r.elem), - Type::Slice(v) => type_base_string(&v.elem), - _ => None, - } -} - -#[derive(Default, Debug, Clone)] -pub struct EmptyToken; - -impl Parse for EmptyToken { - fn parse(_: ParseStream) -> Result { - Ok(Self) - } -} -impl ToTokens for EmptyToken { - fn to_tokens(&self, _: &mut TokenStream) {} -} diff --git a/bevy_mod_scripting_derive/Cargo.toml b/bevy_mod_scripting_derive/Cargo.toml deleted file mode 100644 index 2a191c3c..00000000 --- a/bevy_mod_scripting_derive/Cargo.toml +++ /dev/null @@ -1,30 +0,0 @@ -[package] -name = "bevy_mod_scripting_derive" -version = "0.5.0" -authors = ["Maksymilian Mozolewski "] -edition = "2021" -license = "MIT" -description = "Derive macros for bevy_mod_scripting" -repository = "https://github.com/makspll/bevy_mod_scripting" -homepage = "https://github.com/makspll/bevy_mod_scripting" -keywords = ["bevy", "gamedev", "scripting", "lua"] -categories = ["game-development"] -readme = "readme.md" - -[lib] -name = "bevy_mod_scripting_derive" -proc-macro = true -path = "src/lib.rs" - - -[dependencies] -bevy_mod_scripting_common = { path = "../bevy_mod_scripting_common", version = "0.5.0" } -paste = "1.0.7" -syn = { version = "1.0.57", features = ["full", "fold", "extra-traits"] } -quote = "1.0.8" -proc-macro2 = "1.0" -convert_case = "0.5.0" -rustdoc-types = "0.11.0" -serde = { version = "1.0", features = ["derive"] } -serde_derive = "1.0.137" -indexmap = { version = "1.9.1", features = ["serde"] } diff --git a/bevy_mod_scripting_derive/readme.md b/bevy_mod_scripting_derive/readme.md deleted file mode 100644 index 5bfd0c9f..00000000 --- a/bevy_mod_scripting_derive/readme.md +++ /dev/null @@ -1,3 +0,0 @@ -# bevy_mod_scripting_derive - -This crate is a part of the ["bevy_mod_scripting" workspace](https://github.com/makspll/bevy_mod_scripting). \ No newline at end of file diff --git a/bevy_mod_scripting_derive/src/lib.rs b/bevy_mod_scripting_derive/src/lib.rs deleted file mode 100644 index 745d7363..00000000 --- a/bevy_mod_scripting_derive/src/lib.rs +++ /dev/null @@ -1,161 +0,0 @@ -#![allow(dead_code, unused_variables, unused_features)] -use proc_macro::TokenStream; - -use quote::{format_ident, quote_spanned, ToTokens}; -use syn::{parse::Parse, parse_macro_input, spanned::Spanned, Attribute}; - -/// A convenience macro which derives a lotta things to make your type work in all supported/enabled scripting languages, and provide static typing where possible. -/// -/// This macro is used extensively in `bevy_mod_scripting/src/generated.rs`, for extensive usage examples see those macro invocations. -/// -/// Right now the macro supports: -/// - primitive types surrounded in `Raw()` -/// - usize -/// - isize -/// - f32 -/// - f64 -/// - u128 -/// - u64 -/// - u32 -/// - u16 -/// - u8 -/// - i128 -/// - i64 -/// - i32 -/// - i16 -/// - i8 -/// - String -/// - bool -/// - other wrapper types generated by this macro surrounded in `Wrapper()` -/// - Both mutable and immutable references to any of the above (apart from on fields) -/// - the self type and receiver (self, &self or &mut self), if used in method must be followed by `:` to differentiate it from other self arguments -/// Currently more complex types like: Option and LuaWrapper are not yet supported (although they have Proxy implementations which can be manually implemented). -/// -/// # Example -/// ```rust,ignore -/// use bevy_mod_scripting_derive::impl_script_newtype; -/// -/// pub struct MyStruct{ -/// my_field: bool -/// } -/// -/// impl MyStruct { -/// pub fn do_something(&self) -> bool { -/// self.my_field -/// } -/// } -/// impl_script_newtype!( -/// #[languages(lua,rhai)] -/// MyStruct: -/// Fields( -/// my_field: Raw(bool) -/// ) + Methods( -/// do_something(&self:) -> Raw(bool) -/// ) -/// ); -/// // a new type is created -/// // with all neccessary traits implemented -/// println!("{:?}", std::any::TypeId::Of::); -/// ``` -#[proc_macro] -pub fn impl_script_newtype(input: TokenStream) -> TokenStream { - let invocation = parse_macro_input!(input as MacroInvocation); - let mut output: proc_macro2::TokenStream = Default::default(); - // find the language implementor macro id's - match invocation.languages.parse_meta() { - Ok(syn::Meta::List(list)) => { - if !list.path.is_ident("languages") { - return syn::Error::new_spanned(list, "Expected `langauges(..)` meta list") - .to_compile_error() - .into(); - } - - // now create an invocation per language specified - for language in &list.nested { - let mut feature_gate = false; - let mut inner_language = None; - if let syn::NestedMeta::Meta(syn::Meta::List(sub_list)) = language { - if sub_list.path.is_ident("on_feature") { - if let Some(syn::NestedMeta::Meta(syn::Meta::Path(path))) = - sub_list.nested.first() - { - if let Some(ident) = path.get_ident() { - inner_language = Some(ident); - feature_gate = true; - } - } - } - } else if let syn::NestedMeta::Meta(syn::Meta::Path(path)) = language { - if let Some(ident) = path.get_ident() { - inner_language = Some(ident) - } - } - - let inner_language = - match inner_language { - Some(v) => v, - None => return syn::Error::new_spanned( - language, - "Expected `on_feature(x)` or `x` attribute where x is a valid language", - ) - .to_compile_error() - .into(), - }; - - let lang_str = inner_language.to_string(); - let macro_ident = format_ident!("impl_{}_newtype", inner_language); - let inner = invocation.inner.clone(); - let feature_gate = feature_gate.then_some(quote::quote!(#[cfg(feature=#lang_str)])); - output.extend(quote_spanned! {language.span()=> - #feature_gate - #macro_ident!{ - #inner - } - }); - } - } - _ => { - return syn::Error::new( - invocation.span(), - "Expected attribute of the form #[languages(..)]", - ) - .to_compile_error() - .into() - } - }; - - output.into() -} - -pub(crate) struct MacroInvocation { - pub languages: Attribute, - pub inner: proc_macro2::TokenStream, -} - -impl Parse for MacroInvocation { - fn parse(input: syn::parse::ParseStream) -> syn::Result { - Ok(Self { - languages: Attribute::parse_outer(input)? - .into_iter() - .next() - .ok_or_else(|| { - syn::Error::new( - input.span(), - "Expected meta attribute selecting language implementors", - ) - })?, - inner: input.parse()?, - }) - } -} - -impl ToTokens for MacroInvocation { - fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { - let languages = &self.languages; - let inner = &self.inner; - tokens.extend(quote::quote! { - #languages - #inner - }); - } -} diff --git a/bevy_script_api/src/generated.rs b/bevy_script_api/src/generated.rs deleted file mode 100644 index 5df43e58..00000000 --- a/bevy_script_api/src/generated.rs +++ /dev/null @@ -1,11346 +0,0 @@ -#![allow(clippy::all, unused_imports, deprecated)] -// This file is generated by `bevy_mod_scripting_derive/main.rs` change the template not this file -extern crate self as bevy_script_api; -use crate::{ - error::ReflectionError, - script_ref::{ReflectedValue, ValueIndex}, - sub_reflect::ReflectPathElem, -}; -use bevy::animation::AnimationPlayer; -use bevy::asset::AssetIndex; -use bevy::core::Name; -use bevy::core_pipeline::core_2d::Camera2d; -use bevy::core_pipeline::core_3d::Camera3d; -use bevy::core_pipeline::core_3d::Camera3dDepthLoadOp; -use bevy::ecs::entity::Entity; -use bevy::gltf::GltfExtras; -use bevy::hierarchy::Children; -use bevy::hierarchy::Parent; -use bevy::math::bool::BVec2; -use bevy::math::bool::BVec3; -use bevy::math::bool::BVec3A; -use bevy::math::bool::BVec4; -use bevy::math::bool::BVec4A; -use bevy::math::f32::Affine2; -use bevy::math::f32::Affine3A; -use bevy::math::f32::Mat2; -use bevy::math::f32::Mat3; -use bevy::math::f32::Mat3A; -use bevy::math::f32::Mat4; -use bevy::math::f32::Quat; -use bevy::math::f32::Vec2; -use bevy::math::f32::Vec3; -use bevy::math::f32::Vec3A; -use bevy::math::f32::Vec4; -use bevy::math::f64::DAffine2; -use bevy::math::f64::DAffine3; -use bevy::math::f64::DMat2; -use bevy::math::f64::DMat3; -use bevy::math::f64::DMat4; -use bevy::math::f64::DQuat; -use bevy::math::f64::DVec2; -use bevy::math::f64::DVec3; -use bevy::math::f64::DVec4; -use bevy::math::i32::IVec2; -use bevy::math::i32::IVec3; -use bevy::math::i32::IVec4; -use bevy::math::u32::UVec2; -use bevy::math::u32::UVec3; -use bevy::math::u32::UVec4; -use bevy::math::EulerRot; -use bevy::math::Rect; -use bevy::pbr::wireframe::Wireframe; -use bevy::pbr::wireframe::WireframeConfig; -use bevy::pbr::AlphaMode; -use bevy::pbr::AmbientLight; -use bevy::pbr::CubemapVisibleEntities; -use bevy::pbr::DirectionalLight; -use bevy::pbr::DirectionalLightShadowMap; -use bevy::pbr::NotShadowCaster; -use bevy::pbr::NotShadowReceiver; -use bevy::pbr::PointLight; -use bevy::pbr::PointLightShadowMap; -use bevy::prelude::App; -use bevy::reflect::Enum; -use bevy::render::camera::Camera; -use bevy::render::camera::CameraProjection; -use bevy::render::camera::CameraRenderGraph; -use bevy::render::camera::ClearColor; -use bevy::render::camera::ClearColorConfig; -use bevy::render::camera::OrthographicProjection; -use bevy::render::camera::PerspectiveProjection; -use bevy::render::camera::Projection; -use bevy::render::camera::RenderTarget; -use bevy::render::camera::ScalingMode; -use bevy::render::camera::Viewport; -use bevy::render::color::Color; -use bevy::render::mesh::skinning::SkinnedMesh; -use bevy::render::primitives::Aabb; -use bevy::render::primitives::CubemapFrusta; -use bevy::render::primitives::Frustum; -use bevy::render::view::visibility::InheritedVisibility; -use bevy::render::view::visibility::RenderLayers; -use bevy::render::view::visibility::ViewVisibility; -use bevy::render::view::visibility::Visibility; -use bevy::render::view::visibility::VisibleEntities; -use bevy::render::view::Msaa; -use bevy::sprite::Anchor; -use bevy::sprite::Mesh2dHandle; -use bevy::sprite::Sprite; -use bevy::sprite::TextureAtlas; -use bevy::text::JustifyText; -use bevy::text::Text; -use bevy::text::Text2dBounds; -use bevy::text::TextSection; -use bevy::text::TextStyle; -use bevy::time::Stopwatch; -use bevy::time::Timer; -use bevy::transform::components::GlobalTransform; -use bevy::transform::components::Transform; -use bevy::ui::widget::Button; -use bevy::ui::AlignContent; -use bevy::ui::AlignItems; -use bevy::ui::AlignSelf; -use bevy::ui::CalculatedClip; -use bevy::ui::Direction; -use bevy::ui::Display; -use bevy::ui::FlexDirection; -use bevy::ui::FlexWrap; -use bevy::ui::FocusPolicy; -use bevy::ui::Interaction; -use bevy::ui::JustifyContent; -use bevy::ui::Node; -use bevy::ui::Overflow; -use bevy::ui::PositionType; -use bevy::ui::Style; -use bevy::ui::UiImage; -use bevy::ui::Val; -use bevy_mod_scripting_core::prelude::*; -use bevy_mod_scripting_derive::impl_script_newtype; -use std::ops::*; -use std::sync::Mutex; -#[cfg(feature = "lua")] -use { - crate::{ - common::bevy::GetWorld, - lua::{util::LuaIndex, RegisterForeignLuaType}, - }, - bevy_mod_scripting_lua::{docs::LuaDocFragment, tealr::mlu::mlua::MetaMethod}, - bevy_mod_scripting_lua_derive::impl_lua_newtype, -}; -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Used to control how items are distributed. - ///- For Flexbox containers, controls alignment of lines if `flex_wrap` is set to [`FlexWrap::Wrap`] and there are multiple lines of items. - ///- For CSS Grid containers, controls alignment of grid rows. - /// - /// - bevy_ui::AlignContent : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Used to control how each individual item is aligned by default within the space they're given. - ///- For Flexbox containers, sets default cross axis alignment of the child items. - ///- For CSS Grid containers, controls block (vertical) axis alignment of children of this grid container within their grid areas. - /// - /// - bevy_ui::AlignItems : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Used to control how the specified item is aligned within the space it's given. - ///- For Flexbox items, controls cross axis alignment of the item. - ///- For CSS Grid items, controls block (vertical) axis alignment of a grid item within its grid area. - /// - /// - bevy_ui::AlignSelf : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Defines the text direction. - /// - ///For example, English is written LTR (left-to-right) while Arabic is written RTL (right-to-left). - bevy_ui::Direction : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Defines how flexbox items are ordered within a flexbox - bevy_ui::FlexDirection : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Defines if flexbox items appear on a single line or on multiple lines - bevy_ui::FlexWrap : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Describes whether the node should block interactions with lower nodes - bevy_ui::FocusPolicy : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Describes what type of input interaction has occurred for a UI node. - /// - ///This is commonly queried with a `Changed` filter. - /// - ///Updated in [`ui_focus_system`]. - /// - ///If a UI node has both [`Interaction`] and [`ViewVisibility`] components, - ///[`Interaction`] will always be [`Interaction::None`] - ///when [`ViewVisibility::get()`] is false. - ///This ensures that hidden UI nodes are not interactable, - ///and do not end up stuck in an active state if hidden at the wrong time. - /// - ///Note that you can also control the visibility of a node using the [`Display`](crate::ui_node::Display) property, - ///which fully collapses it during layout calculations. - /// - ///# See also - /// - ///- [`ButtonBundle`](crate::node_bundles::ButtonBundle) which includes this component - ///- [`RelativeCursorPosition`] to obtain the position of the cursor relative to current node - bevy_ui::Interaction : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Used to control how items are distributed. - ///- For Flexbox containers, controls alignment of items in the main axis. - ///- For CSS Grid containers, controls alignment of grid columns. - /// - /// - bevy_ui::JustifyContent : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Whether to show or hide overflowing items - bevy_ui::Overflow : - Clone + - Debug + - Methods - ( - ///Show overflowing items on both axes - visible() -> self, - - ///Clip overflowing items on both axes - clip() -> self, - - ///Clip overflowing items on the x axis - clip_x() -> self, - - ///Clip overflowing items on the y axis - clip_y() -> self, - - ///Overflow is visible on both axes - is_visible(&self:) -> Raw(bool), - - ) - + Fields - ( - /// Whether to show or clip overflowing items on the x axis - x: Raw(ReflectedValue), - /// Whether to show or clip overflowing items on the y axis - y: Raw(ReflectedValue), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///The strategy used to position this node - bevy_ui::PositionType : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Represents the possible value types for layout properties. - /// - ///This enum allows specifying values for various [`Style`](crate::Style) properties in different units, - ///such as logical pixels, percentages, or automatically determined values. - bevy_ui::Val : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - self Div Raw(f32) -> Wrapped(Val), - self Mul Raw(f32) -> Wrapped(Val), - ) - + UnaryOps - ( - Neg self -> self - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///The calculated clip of the node - bevy_ui::CalculatedClip : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - /// The rect of the clip - clip: Wrapped(Rect), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Base component for a UI node, which also provides the computed size of the node. - /// - ///# See also - /// - ///- [`node_bundles`](crate::node_bundles) for the list of built-in bundles that set up UI node - ///- [`RelativeCursorPosition`](crate::RelativeCursorPosition) - /// to obtain the cursor position relative to this node - ///- [`Interaction`](crate::Interaction) to obtain the interaction state of this node - bevy_ui::Node : - Clone + - Debug + - Methods - ( - ///The calculated node size as width and height in logical pixels. - /// - ///Automatically calculated by [`super::layout::ui_layout_system`]. - size(&self:) -> Wrapped(Vec2), - - ///The order of the node in the UI layout. - ///Nodes with a higher stack index are drawn on top of and recieve interactions before nodes with lower stack indices. - stack_index(&self:) -> Raw(u32), - - ///The calculated node size as width and height in logical pixels before rounding. - /// - ///Automatically calculated by [`super::layout::ui_layout_system`]. - unrounded_size(&self:) -> Wrapped(Vec2), - - ///Returns the size of the node in physical pixels based on the given scale factor and `UiScale`. - physical_size(&self:Raw(f32),Raw(f32)) -> Wrapped(Vec2), - - ///Returns the logical pixel coordinates of the UI node, based on its [`GlobalTransform`]. - logical_rect(&self:Wrapped(&GlobalTransform)) -> Wrapped(Rect), - - ///Returns the physical pixel coordinates of the UI node, based on its [`GlobalTransform`] and the scale factor. - physical_rect(&self:Wrapped(&GlobalTransform),Raw(f32),Raw(f32)) -> Wrapped(Rect), - - ///Returns the thickness of the UI node's outline. - ///If this value is negative or `0.` then no outline will be rendered. - outline_width(&self:) -> Raw(f32), - - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Describes the style of a UI container node - /// - ///Nodes can be laid out using either Flexbox or CSS Grid Layout. - /// - ///See below for general learning resources and for documentation on the individual style properties. - /// - ///### Flexbox - /// - ///- [MDN: Basic Concepts of Flexbox](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox) - ///- [A Complete Guide To Flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) by CSS Tricks. This is detailed guide with illustrations and comprehensive written explanation of the different Flexbox properties and how they work. - ///- [Flexbox Froggy](https://flexboxfroggy.com/). An interactive tutorial/game that teaches the essential parts of Flexbox in a fun engaging way. - /// - ///### CSS Grid - /// - ///- [MDN: Basic Concepts of Grid Layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Basic_Concepts_of_Grid_Layout) - ///- [A Complete Guide To CSS Grid](https://css-tricks.com/snippets/css/complete-guide-grid/) by CSS Tricks. This is detailed guide with illustrations and comprehensive written explanation of the different CSS Grid properties and how they work. - ///- [CSS Grid Garden](https://cssgridgarden.com/). An interactive tutorial/game that teaches the essential parts of CSS Grid in a fun engaging way. - bevy_ui::Style : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - /// Which layout algorithm to use when laying out this node's contents: - /// - [`Display::Flex`]: Use the Flexbox layout algorithm - /// - [`Display::Grid`]: Use the CSS Grid layout algorithm - /// - [`Display::None`]: Hide this node and perform layout as if it does not exist. - /// - /// - display: Wrapped(Display), - /// Whether a node should be laid out in-flow with, or independently of its siblings: - /// - [`PositionType::Relative`]: Layout this node in-flow with other nodes using the usual (flexbox/grid) layout algorithm. - /// - [`PositionType::Absolute`]: Layout this node on top and independently of other nodes. - /// - /// - position_type: Wrapped(PositionType), - /// Whether overflowing content should be displayed or clipped. - /// - /// - overflow: Wrapped(Overflow), - /// Defines the text direction. For example, English is written LTR (left-to-right) while Arabic is written RTL (right-to-left). - /// - /// Note: the corresponding CSS property also affects box layout order, but this isn't yet implemented in Bevy. - /// - /// - direction: Wrapped(Direction), - /// The horizontal position of the left edge of the node. - /// - For relatively positioned nodes, this is relative to the node's position as computed during regular layout. - /// - For absolutely positioned nodes, this is relative to the *parent* node's bounding box. - /// - /// - left: Wrapped(Val), - /// The horizontal position of the right edge of the node. - /// - For relatively positioned nodes, this is relative to the node's position as computed during regular layout. - /// - For absolutely positioned nodes, this is relative to the *parent* node's bounding box. - /// - /// - right: Wrapped(Val), - /// The vertical position of the top edge of the node. - /// - For relatively positioned nodes, this is relative to the node's position as computed during regular layout. - /// - For absolutely positioned nodes, this is relative to the *parent* node's bounding box. - /// - /// - top: Wrapped(Val), - /// The vertical position of the bottom edge of the node. - /// - For relatively positioned nodes, this is relative to the node's position as computed during regular layout. - /// - For absolutely positioned nodes, this is relative to the *parent* node's bounding box. - /// - /// - bottom: Wrapped(Val), - /// The ideal width of the node. `width` is used when it is within the bounds defined by `min_width` and `max_width`. - /// - /// - width: Wrapped(Val), - /// The ideal height of the node. `height` is used when it is within the bounds defined by `min_height` and `max_height`. - /// - /// - height: Wrapped(Val), - /// The minimum width of the node. `min_width` is used if it is greater than `width` and/or `max_width`. - /// - /// - min_width: Wrapped(Val), - /// The minimum height of the node. `min_height` is used if it is greater than `height` and/or `max_height`. - /// - /// - min_height: Wrapped(Val), - /// The maximum width of the node. `max_width` is used if it is within the bounds defined by `min_width` and `width`. - /// - /// - max_width: Wrapped(Val), - /// The maximum height of the node. `max_height` is used if it is within the bounds defined by `min_height` and `height`. - /// - /// - max_height: Wrapped(Val), - /// The aspect ratio of the node (defined as `width / height`) - /// - /// - aspect_ratio: Raw(ReflectedValue), - /// Used to control how each individual item is aligned by default within the space they're given. - /// - For Flexbox containers, sets default cross axis alignment of the child items. - /// - For CSS Grid containers, controls block (vertical) axis alignment of children of this grid container within their grid areas. - /// - /// This value is overridden if [`AlignSelf`] on the child node is set. - /// - /// - align_items: Wrapped(AlignItems), - /// Used to control how each individual item is aligned by default within the space they're given. - /// - For Flexbox containers, this property has no effect. See `justify_content` for main axis alignment of flex items. - /// - For CSS Grid containers, sets default inline (horizontal) axis alignment of child items within their grid areas. - /// - /// This value is overridden if [`JustifySelf`] on the child node is set. - /// - /// - justify_items: Raw(ReflectedValue), - /// Used to control how the specified item is aligned within the space it's given. - /// - For Flexbox items, controls cross axis alignment of the item. - /// - For CSS Grid items, controls block (vertical) axis alignment of a grid item within its grid area. - /// - /// If set to `Auto`, alignment is inherited from the value of [`AlignItems`] set on the parent node. - /// - /// - align_self: Wrapped(AlignSelf), - /// Used to control how the specified item is aligned within the space it's given. - /// - For Flexbox items, this property has no effect. See `justify_content` for main axis alignment of flex items. - /// - For CSS Grid items, controls inline (horizontal) axis alignment of a grid item within its grid area. - /// - /// If set to `Auto`, alignment is inherited from the value of [`JustifyItems`] set on the parent node. - /// - /// - justify_self: Raw(ReflectedValue), - /// Used to control how items are distributed. - /// - For Flexbox containers, controls alignment of lines if `flex_wrap` is set to [`FlexWrap::Wrap`] and there are multiple lines of items. - /// - For CSS Grid containers, controls alignment of grid rows. - /// - /// - align_content: Wrapped(AlignContent), - /// Used to control how items are distributed. - /// - For Flexbox containers, controls alignment of items in the main axis. - /// - For CSS Grid containers, controls alignment of grid columns. - /// - /// - justify_content: Wrapped(JustifyContent), - /// The amount of space around a node outside its border. - /// - /// If a percentage value is used, the percentage is calculated based on the width of the parent node. - /// - /// # Example - /// ``` - /// # use bevy_ui::{Style, UiRect, Val}; - /// let style = Style { - /// margin: UiRect { - /// left: Val::Percent(10.), - /// right: Val::Percent(10.), - /// top: Val::Percent(15.), - /// bottom: Val::Percent(15.) - /// }, - /// ..Default::default() - /// }; - /// ``` - /// A node with this style and a parent with dimensions of 100px by 300px will have calculated margins of 10px on both left and right edges, and 15px on both top and bottom edges. - /// - /// - margin: Raw(ReflectedValue), - /// The amount of space between the edges of a node and its contents. - /// - /// If a percentage value is used, the percentage is calculated based on the width of the parent node. - /// - /// # Example - /// ``` - /// # use bevy_ui::{Style, UiRect, Val}; - /// let style = Style { - /// padding: UiRect { - /// left: Val::Percent(1.), - /// right: Val::Percent(2.), - /// top: Val::Percent(3.), - /// bottom: Val::Percent(4.) - /// }, - /// ..Default::default() - /// }; - /// ``` - /// A node with this style and a parent with dimensions of 300px by 100px will have calculated padding of 3px on the left, 6px on the right, 9px on the top and 12px on the bottom. - /// - /// - padding: Raw(ReflectedValue), - /// The amount of space between the margins of a node and its padding. - /// - /// If a percentage value is used, the percentage is calculated based on the width of the parent node. - /// - /// The size of the node will be expanded if there are constraints that prevent the layout algorithm from placing the border within the existing node boundary. - /// - /// - border: Raw(ReflectedValue), - /// Whether a Flexbox container should be a row or a column. This property has no effect on Grid nodes. - /// - /// - flex_direction: Wrapped(FlexDirection), - /// Whether a Flexbox container should wrap its contents onto multiple lines if they overflow. This property has no effect on Grid nodes. - /// - /// - flex_wrap: Wrapped(FlexWrap), - /// Defines how much a flexbox item should grow if there's space available. Defaults to 0 (don't grow at all). - /// - /// - flex_grow: Raw(f32), - /// Defines how much a flexbox item should shrink if there's not enough space available. Defaults to 1. - /// - /// - flex_shrink: Raw(f32), - /// The initial length of a flexbox in the main axis, before flex growing/shrinking properties are applied. - /// - /// `flex_basis` overrides `size` on the main axis if both are set, but it obeys the bounds defined by `min_size` and `max_size`. - /// - /// - flex_basis: Wrapped(Val), - /// The size of the gutters between items in a vertical flexbox layout or between rows in a grid layout. - /// - /// Note: Values of `Val::Auto` are not valid and are treated as zero. - /// - /// - row_gap: Wrapped(Val), - /// The size of the gutters between items in a horizontal flexbox layout or between column in a grid layout. - /// - /// Note: Values of `Val::Auto` are not valid and are treated as zero. - /// - /// - column_gap: Wrapped(Val), - /// Controls whether automatically placed grid items are placed row-wise or column-wise as well as whether the sparse or dense packing algorithm is used. - /// Only affects Grid layouts. - /// - /// - grid_auto_flow: Raw(ReflectedValue), - /// Defines the number of rows a grid has and the sizes of those rows. If grid items are given explicit placements then more rows may - /// be implicitly generated by items that are placed out of bounds. The sizes of those rows are controlled by `grid_auto_rows` property. - /// - /// - grid_template_rows: Raw(ReflectedValue), - /// Defines the number of columns a grid has and the sizes of those columns. If grid items are given explicit placements then more columns may - /// be implicitly generated by items that are placed out of bounds. The sizes of those columns are controlled by `grid_auto_columns` property. - /// - /// - grid_template_columns: Raw(ReflectedValue), - /// Defines the size of implicitly created rows. Rows are created implicitly when grid items are given explicit placements that are out of bounds - /// of the rows explicitly created using `grid_template_rows`. - /// - /// - grid_auto_rows: Raw(ReflectedValue), - /// Defines the size of implicitly created columns. Columns are created implicitly when grid items are given explicit placements that are out of bounds - /// of the columns explicitly created using `grid_template_columns`. - /// - /// - grid_auto_columns: Raw(ReflectedValue), - /// The row in which a grid item starts and how many rows it spans. - /// - /// - grid_row: Raw(ReflectedValue), - /// The column in which a grid item starts and how many columns it spans. - /// - /// - grid_column: Raw(ReflectedValue), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///The 2D texture displayed for this UI node - bevy_ui::UiImage : - Clone + - Debug + - Methods - ( - ///Flip the image along its x-axis - with_flip_x(self:) -> self, - - ///Flip the image along its y-axis - with_flip_y(self:) -> self, - - ) - + Fields - ( - /// Handle to the texture - texture: Raw(ReflectedValue), - /// Whether the image should be flipped along its x-axis - flip_x: Raw(bool), - /// Whether the image should be flipped along its y-axis - flip_y: Raw(bool), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Marker struct for buttons - bevy_ui::widget::Button : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Defines the layout model used by this node. - /// - ///Part of the [`Style`] component. - bevy_ui::Display : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Animation controls - bevy_animation::AnimationPlayer : - Methods - ( - ///Check if the playing animation has finished, according to the repetition behavior. - is_finished(&self:) -> Raw(bool), - - ///Number of times the animation has completed. - completions(&self:) -> Raw(u32), - - ///Check if the animation is playing in reverse. - is_playback_reversed(&self:) -> Raw(bool), - - ///Pause the animation - pause(&mut self:), - - ///Unpause the animation - resume(&mut self:), - - ///Is the animation paused - is_paused(&self:) -> Raw(bool), - - ///Speed of the animation playback - speed(&self:) -> Raw(f32), - - ///Time elapsed playing the animation - elapsed(&self:) -> Raw(f32), - - ///Seek time inside of the animation. Always within the range [0.0, clip duration]. - seek_time(&self:) -> Raw(f32), - - ///Reset the animation to its initial state, as if no time has elapsed. - replay(&mut self:), - - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Component used to identify an entity. Stores a hash for faster comparisons. - /// - ///The hash is eagerly re-computed upon each update to the name. - /// - ///[`Name`] should not be treated as a globally unique identifier for entities, - ///as multiple entities can have the same name. [`Entity`] should be - ///used instead as the default unique identifier. - bevy_core::Name : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Additional untyped data that can be present on most glTF types. - /// - ///See [the relevant glTF specification section](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-extras). - bevy_gltf::GltfExtras : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - /// Content of the extra data. - value: Raw(String), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Contains references to the child entities of this entity. - /// - ///Each child must contain a [`Parent`] component that points back to this entity. - ///This component rarely needs to be created manually, - ///consider using higher level utilities like [`BuildChildren::with_children`] - ///which are safer and easier to use. - /// - ///See [`HierarchyQueryExt`] for hierarchy related methods on [`Query`]. - /// - ///[`HierarchyQueryExt`]: crate::query_extension::HierarchyQueryExt - ///[`Query`]: bevy_ecs::system::Query - ///[`Parent`]: crate::components::parent::Parent - ///[`BuildChildren::with_children`]: crate::child_builder::BuildChildren::with_children - bevy_hierarchy::Children : - Debug + - Methods - ( - ///Swaps the child at `a_index` with the child at `b_index`. - swap(&mut self:Raw(usize),Raw(usize)), - - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Holds a reference to the parent entity of this entity. - ///This component should only be present on entities that actually have a parent entity. - /// - ///Parent entity must have this entity stored in its [`Children`] component. - ///It is hard to set up parent/child relationships manually, - ///consider using higher level utilities like [`BuildChildren::with_children`]. - /// - ///See [`HierarchyQueryExt`] for hierarchy related methods on [`Query`]. - /// - ///[`HierarchyQueryExt`]: crate::query_extension::HierarchyQueryExt - ///[`Query`]: bevy_ecs::system::Query - ///[`Children`]: super::children::Children - ///[`BuildChildren::with_children`]: crate::child_builder::BuildChildren::with_children - bevy_hierarchy::Parent : - Debug + - Methods - ( - ///Gets the [`Entity`] ID of the parent. - get(&self:) -> Wrapped(Entity), - - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///The maximum width and height of text. The text will wrap according to the specified size. - ///Characters out of the bounds after wrapping will be truncated. Text is aligned according to the - ///specified [`JustifyText`](crate::text::JustifyText). - /// - ///Note: only characters that are completely out of the bounds will be truncated, so this is not a - ///reliable limit if it is necessary to contain the text strictly in the bounds. Currently this - ///component is mainly useful for text wrapping only. - bevy_text::Text2dBounds : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - /// The maximum width and height of text in logical pixels. - size: Wrapped(Vec2), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - bevy_text::Text : - Clone + - Debug + - Methods - ( - ///Returns this [`Text`] with a new [`JustifyText`]. - with_justify(self:Wrapped(JustifyText)) -> self, - - ///Returns this [`Text`] with soft wrapping disabled. - ///Hard wrapping, where text contains an explicit linebreak such as the escape sequence `\n`, will still occur. - with_no_wrap(self:) -> self, - - ) - + Fields - ( - sections: Raw(ReflectedValue), - /// The text's internal alignment. - /// Should not affect its position within a container. - justify: Wrapped(JustifyText), - /// How the text should linebreak when running out of the bounds determined by max_size - linebreak_behavior: Raw(ReflectedValue), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Describes the horizontal alignment of multiple lines of text relative to each other. - ///This only affects the internal positioning of the lines of text within a text entity and - ///does not affect the text entity's position. - /// - ///_Has no affect on a single line text entity._ - bevy_text::JustifyText : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - bevy_text::TextSection : - Clone + - Debug + - Methods - ( - ///Create an empty [`TextSection`] from a style. Useful when the value will be set dynamically. - from_style(Wrapped(TextStyle)) -> self, - - ) - + Fields - ( - value: Raw(String), - style: Wrapped(TextStyle), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - bevy_text::TextStyle : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - /// If this is not specified, then - /// * if `default_font` feature is enabled (enabled by default in `bevy` crate), - /// `FiraMono-subset.ttf` compiled into the library is used. - /// * otherwise no text will be rendered. - font: Raw(ReflectedValue), - /// The vertical height of rasterized glyphs in the font atlas in pixels. - /// - /// This is multiplied by the window scale factor and `UiScale`, but not the text entity - /// transform or camera projection. - /// - /// A new font atlas is generated for every combination of font handle and scaled font size - /// which can have a strong performance impact. - font_size: Raw(f32), - color: Wrapped(Color), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A Stopwatch is a struct that track elapsed time when started. - /// - ///# Examples - /// - ///``` - ///# use bevy_time::*; - ///use std::time::Duration; - ///let mut stopwatch = Stopwatch::new(); - ///assert_eq!(stopwatch.elapsed_secs(), 0.0); - /// - ///stopwatch.tick(Duration::from_secs_f32(1.0)); // tick one second - ///assert_eq!(stopwatch.elapsed_secs(), 1.0); - /// - ///stopwatch.pause(); - ///stopwatch.tick(Duration::from_secs_f32(1.0)); // paused stopwatches don't tick - ///assert_eq!(stopwatch.elapsed_secs(), 1.0); - /// - ///stopwatch.reset(); // reset the stopwatch - ///assert!(stopwatch.paused()); - ///assert_eq!(stopwatch.elapsed_secs(), 0.0); - ///``` - bevy_time::Stopwatch : - Clone + - Debug + - Methods - ( - ///Create a new unpaused `Stopwatch` with no elapsed time. - /// - ///# Examples - ///``` - ///# use bevy_time::*; - ///let stopwatch = Stopwatch::new(); - ///assert_eq!(stopwatch.elapsed_secs(), 0.0); - ///assert_eq!(stopwatch.paused(), false); - ///``` - new() -> self, - - ///Returns the elapsed time since the last [`reset`](Stopwatch::reset) - ///of the stopwatch, in seconds. - /// - ///# Examples - ///``` - ///# use bevy_time::*; - ///use std::time::Duration; - ///let mut stopwatch = Stopwatch::new(); - ///stopwatch.tick(Duration::from_secs(1)); - ///assert_eq!(stopwatch.elapsed_secs(), 1.0); - ///``` - /// - ///# See Also - /// - ///[`elapsed`](Stopwatch::elapsed) - if a `Duration` is desirable instead. - ///[`elapsed_secs_f64`](Stopwatch::elapsed_secs_f64) - if an `f64` is desirable instead. - elapsed_secs(&self:) -> Raw(f32), - - ///Returns the elapsed time since the last [`reset`](Stopwatch::reset) - ///of the stopwatch, in seconds, as f64. - /// - ///# See Also - /// - ///[`elapsed`](Stopwatch::elapsed) - if a `Duration` is desirable instead. - ///[`elapsed_secs`](Stopwatch::elapsed_secs) - if an `f32` is desirable instead. - elapsed_secs_f64(&self:) -> Raw(f64), - - ///Pauses the stopwatch. Any call to [`tick`](Stopwatch::tick) while - ///paused will not have any effect on the elapsed time. - /// - ///# Examples - ///``` - ///# use bevy_time::*; - ///use std::time::Duration; - ///let mut stopwatch = Stopwatch::new(); - ///stopwatch.pause(); - ///stopwatch.tick(Duration::from_secs_f32(1.5)); - ///assert!(stopwatch.paused()); - ///assert_eq!(stopwatch.elapsed_secs(), 0.0); - ///``` - pause(&mut self:), - - ///Unpauses the stopwatch. Resume the effect of ticking on elapsed time. - /// - ///# Examples - ///``` - ///# use bevy_time::*; - ///use std::time::Duration; - ///let mut stopwatch = Stopwatch::new(); - ///stopwatch.pause(); - ///stopwatch.tick(Duration::from_secs_f32(1.0)); - ///stopwatch.unpause(); - ///stopwatch.tick(Duration::from_secs_f32(1.0)); - ///assert!(!stopwatch.paused()); - ///assert_eq!(stopwatch.elapsed_secs(), 1.0); - ///``` - unpause(&mut self:), - - ///Returns `true` if the stopwatch is paused. - /// - ///# Examples - ///``` - ///# use bevy_time::*; - ///let mut stopwatch = Stopwatch::new(); - ///assert!(!stopwatch.paused()); - ///stopwatch.pause(); - ///assert!(stopwatch.paused()); - ///stopwatch.unpause(); - ///assert!(!stopwatch.paused()); - ///``` - paused(&self:) -> Raw(bool), - - ///Resets the stopwatch. The reset doesn't affect the paused state of the stopwatch. - /// - ///# Examples - ///``` - ///# use bevy_time::*; - ///use std::time::Duration; - ///let mut stopwatch = Stopwatch::new(); - ///stopwatch.tick(Duration::from_secs_f32(1.5)); - ///stopwatch.reset(); - ///assert_eq!(stopwatch.elapsed_secs(), 0.0); - ///``` - reset(&mut self:), - - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Tracks elapsed time. Enters the finished state once `duration` is reached. - /// - ///Non repeating timers will stop tracking and stay in the finished state until reset. - ///Repeating timers will only be in the finished state on each tick `duration` is reached or - ///exceeded, and can still be reset at any given point. - /// - ///Paused timers will not have elapsed time increased. - bevy_time::Timer : - Clone + - Debug + - Methods - ( - ///Returns `true` if the timer has reached its duration. - /// - ///For repeating timers, this method behaves identically to [`Timer::just_finished`]. - /// - ///# Examples - ///``` - ///# use bevy_time::*; - ///use std::time::Duration; - /// - ///let mut timer_once = Timer::from_seconds(1.0, TimerMode::Once); - ///timer_once.tick(Duration::from_secs_f32(1.5)); - ///assert!(timer_once.finished()); - ///timer_once.tick(Duration::from_secs_f32(0.5)); - ///assert!(timer_once.finished()); - /// - ///let mut timer_repeating = Timer::from_seconds(1.0, TimerMode::Repeating); - ///timer_repeating.tick(Duration::from_secs_f32(1.1)); - ///assert!(timer_repeating.finished()); - ///timer_repeating.tick(Duration::from_secs_f32(0.8)); - ///assert!(!timer_repeating.finished()); - ///timer_repeating.tick(Duration::from_secs_f32(0.6)); - ///assert!(timer_repeating.finished()); - ///``` - finished(&self:) -> Raw(bool), - - ///Returns `true` only on the tick the timer reached its duration. - /// - ///# Examples - ///``` - ///# use bevy_time::*; - ///use std::time::Duration; - ///let mut timer = Timer::from_seconds(1.0, TimerMode::Once); - ///timer.tick(Duration::from_secs_f32(1.5)); - ///assert!(timer.just_finished()); - ///timer.tick(Duration::from_secs_f32(0.5)); - ///assert!(!timer.just_finished()); - ///``` - just_finished(&self:) -> Raw(bool), - - ///Returns the time elapsed on the timer as an `f32`. - ///See also [`Timer::elapsed`](Timer::elapsed). - elapsed_secs(&self:) -> Raw(f32), - - ///Pauses the Timer. Disables the ticking of the timer. - /// - ///See also [`Stopwatch::pause`](Stopwatch::pause). - /// - ///# Examples - ///``` - ///# use bevy_time::*; - ///use std::time::Duration; - ///let mut timer = Timer::from_seconds(1.0, TimerMode::Once); - ///timer.pause(); - ///timer.tick(Duration::from_secs_f32(0.5)); - ///assert_eq!(timer.elapsed_secs(), 0.0); - ///``` - pause(&mut self:), - - ///Unpauses the Timer. Resumes the ticking of the timer. - /// - ///See also [`Stopwatch::unpause()`](Stopwatch::unpause). - /// - ///# Examples - ///``` - ///# use bevy_time::*; - ///use std::time::Duration; - ///let mut timer = Timer::from_seconds(1.0, TimerMode::Once); - ///timer.pause(); - ///timer.tick(Duration::from_secs_f32(0.5)); - ///timer.unpause(); - ///timer.tick(Duration::from_secs_f32(0.5)); - ///assert_eq!(timer.elapsed_secs(), 0.5); - ///``` - unpause(&mut self:), - - ///Returns `true` if the timer is paused. - /// - ///See also [`Stopwatch::paused`](Stopwatch::paused). - /// - ///# Examples - ///``` - ///# use bevy_time::*; - ///let mut timer = Timer::from_seconds(1.0, TimerMode::Once); - ///assert!(!timer.paused()); - ///timer.pause(); - ///assert!(timer.paused()); - ///timer.unpause(); - ///assert!(!timer.paused()); - ///``` - paused(&self:) -> Raw(bool), - - ///Resets the timer. The reset doesn't affect the `paused` state of the timer. - /// - ///See also [`Stopwatch::reset`](Stopwatch::reset). - /// - ///Examples - ///``` - ///# use bevy_time::*; - ///use std::time::Duration; - ///let mut timer = Timer::from_seconds(1.0, TimerMode::Once); - ///timer.tick(Duration::from_secs_f32(1.5)); - ///timer.reset(); - ///assert!(!timer.finished()); - ///assert!(!timer.just_finished()); - ///assert_eq!(timer.elapsed_secs(), 0.0); - ///``` - reset(&mut self:), - - ///Returns the fraction of the timer elapsed time (goes from 0.0 to 1.0). - /// - ///# Examples - ///``` - ///# use bevy_time::*; - ///use std::time::Duration; - ///let mut timer = Timer::from_seconds(2.0, TimerMode::Once); - ///timer.tick(Duration::from_secs_f32(0.5)); - ///assert_eq!(timer.fraction(), 0.25); - ///``` - fraction(&self:) -> Raw(f32), - - ///Returns the fraction of the timer remaining time (goes from 1.0 to 0.0). - /// - ///# Examples - ///``` - ///# use bevy_time::*; - ///use std::time::Duration; - ///let mut timer = Timer::from_seconds(2.0, TimerMode::Once); - ///timer.tick(Duration::from_secs_f32(0.5)); - ///assert_eq!(timer.fraction_remaining(), 0.75); - ///``` - fraction_remaining(&self:) -> Raw(f32), - - ///Returns the remaining time in seconds - /// - ///# Examples - ///``` - ///# use bevy_time::*; - ///use std::cmp::Ordering; - ///use std::time::Duration; - ///let mut timer = Timer::from_seconds(2.0, TimerMode::Once); - ///timer.tick(Duration::from_secs_f32(0.5)); - ///let result = timer.remaining_secs().total_cmp(&1.5); - ///assert_eq!(Ordering::Equal, result); - ///``` - remaining_secs(&self:) -> Raw(f32), - - ///Returns the number of times a repeating timer - ///finished during the last [`tick`](Timer::tick) call. - /// - ///For non repeating-timers, this method will only ever - ///return 0 or 1. - /// - ///# Examples - ///``` - ///# use bevy_time::*; - ///use std::time::Duration; - ///let mut timer = Timer::from_seconds(1.0, TimerMode::Repeating); - ///timer.tick(Duration::from_secs_f32(6.0)); - ///assert_eq!(timer.times_finished_this_tick(), 6); - ///timer.tick(Duration::from_secs_f32(2.0)); - ///assert_eq!(timer.times_finished_this_tick(), 2); - ///timer.tick(Duration::from_secs_f32(0.5)); - ///assert_eq!(timer.times_finished_this_tick(), 0); - ///``` - times_finished_this_tick(&self:) -> Raw(u32), - - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Lightweight identifier of an [entity](crate::entity). - /// - ///The identifier is implemented using a [generational index]: a combination of an index and a generation. - ///This allows fast insertion after data removal in an array while minimizing loss of spatial locality. - /// - ///These identifiers are only valid on the [`World`] it's sourced from. Attempting to use an `Entity` to - ///fetch entity components or metadata from a different world will either fail or return unexpected results. - /// - ///[generational index]: https://lucassardois.medium.com/generational-indices-guide-8e3c5f7fd594 - /// - ///# Usage - /// - ///This data type is returned by iterating a `Query` that has `Entity` as part of its query fetch type parameter ([learn more]). - ///It can also be obtained by calling [`EntityCommands::id`] or [`EntityWorldMut::id`]. - /// - ///``` - ///# use bevy_ecs::prelude::*; - ///# #[derive(Component)] - ///# struct SomeComponent; - ///fn setup(mut commands: Commands) { - /// // Calling `spawn` returns `EntityCommands`. - /// let entity = commands.spawn(SomeComponent).id(); - ///} - /// - ///fn exclusive_system(world: &mut World) { - /// // Calling `spawn` returns `EntityWorldMut`. - /// let entity = world.spawn(SomeComponent).id(); - ///} - ///# - ///# bevy_ecs::system::assert_is_system(setup); - ///# bevy_ecs::system::assert_is_system(exclusive_system); - ///``` - /// - ///It can be used to refer to a specific entity to apply [`EntityCommands`], or to call [`Query::get`] (or similar methods) to access its components. - /// - ///``` - ///# use bevy_ecs::prelude::*; - ///# - ///# #[derive(Component)] - ///# struct Expired; - ///# - ///fn dispose_expired_food(mut commands: Commands, query: Query>) { - /// for food_entity in &query { - /// commands.entity(food_entity).despawn(); - /// } - ///} - ///# - ///# bevy_ecs::system::assert_is_system(dispose_expired_food); - ///``` - /// - ///[learn more]: crate::system::Query#entity-id-access - ///[`EntityCommands::id`]: crate::system::EntityCommands::id - ///[`EntityWorldMut::id`]: crate::world::EntityWorldMut::id - ///[`EntityCommands`]: crate::system::EntityCommands - ///[`Query::get`]: crate::system::Query::get - ///[`World`]: crate::world::World - bevy_ecs::entity::Entity : - Clone + - Debug + - Methods - ( - ///Creates a new entity ID with the specified `index` and a generation of 1. - /// - ///# Note - /// - ///Spawning a specific `entity` value is __rarely the right choice__. Most apps should favor - ///[`Commands::spawn`](crate::system::Commands::spawn). This method should generally - ///only be used for sharing entities across apps, and only when they have a scheme - ///worked out to share an index space (which doesn't happen by default). - /// - ///In general, one should not try to synchronize the ECS by attempting to ensure that - ///`Entity` lines up between instances, but instead insert a secondary identifier as - ///a component. - from_raw(Raw(u32)) -> Wrapped(Entity), - - ///Convert to a form convenient for passing outside of rust. - /// - ///Only useful for identifying entities within the same instance of an application. Do not use - ///for serialization between runs. - /// - ///No particular structure is guaranteed for the returned bits. - to_bits(self:) -> Raw(u64), - - ///Reconstruct an `Entity` previously destructured with [`Entity::to_bits`]. - /// - ///Only useful when applied to results from `to_bits` in the same instance of an application. - /// - ///# Panics - /// - ///This method will likely panic if given `u64` values that did not come from [`Entity::to_bits`]. - from_bits(Raw(u64)) -> self, - - ///Return a transiently unique identifier. - /// - ///No two simultaneously-live entities share the same index, but dead entities' indices may collide - ///with both live and dead entities. Useful for compactly representing entities within a - ///specific snapshot of the world, such as when serializing. - index(self:) -> Raw(u32), - - ///Returns the generation of this Entity's index. The generation is incremented each time an - ///entity with a given index is despawned. This serves as a "count" of the number of times a - ///given index has been reused (index, generation) pairs uniquely identify a given Entity. - generation(self:) -> Raw(u32), - - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Describe the position of an entity. If the entity has a parent, the position is relative - ///to its parent position. - /// - ///* To place or move an entity, you should set its [`Transform`]. - ///* To get the global transform of an entity, you should get its [`GlobalTransform`]. - ///* To be displayed, an entity must have both a [`Transform`] and a [`GlobalTransform`]. - /// * You may use the [`TransformBundle`](crate::TransformBundle) to guarantee this. - /// - ///## [`Transform`] and [`GlobalTransform`] - /// - ///[`Transform`] is the position of an entity relative to its parent position, or the reference - ///frame if it doesn't have a [`Parent`](bevy_hierarchy::Parent). - /// - ///[`GlobalTransform`] is the position of an entity relative to the reference frame. - /// - ///[`GlobalTransform`] is updated from [`Transform`] by systems in the system set - ///[`TransformPropagate`](crate::TransformSystem::TransformPropagate). - /// - ///This system runs during [`PostUpdate`](bevy_app::PostUpdate). If you - ///update the [`Transform`] of an entity during this set or after, you will notice a 1 frame lag - ///before the [`GlobalTransform`] is updated. - /// - ///# Examples - /// - ///- [`transform`] - ///- [`global_vs_local_translation`] - /// - ///[`global_vs_local_translation`]: https://github.com/bevyengine/bevy/blob/latest/examples/transforms/global_vs_local_translation.rs - ///[`transform`]: https://github.com/bevyengine/bevy/blob/latest/examples/transforms/transform.rs - bevy_transform::components::Transform : - Clone + - Debug + - Methods - ( - ///Creates a new [`Transform`] at the position `(x, y, z)`. In 2d, the `z` component - ///is used for z-ordering elements: higher `z`-value will be in front of lower - ///`z`-value. - from_xyz(Raw(f32),Raw(f32),Raw(f32)) -> self, - - ///Extracts the translation, rotation, and scale from `matrix`. It must be a 3d affine - ///transformation matrix. - from_matrix(Wrapped(Mat4)) -> self, - - ///Creates a new [`Transform`], with `translation`. Rotation will be 0 and scale 1 on - ///all axes. - from_translation(Wrapped(Vec3)) -> self, - - ///Creates a new [`Transform`], with `rotation`. Translation will be 0 and scale 1 on - ///all axes. - from_rotation(Wrapped(Quat)) -> self, - - ///Creates a new [`Transform`], with `scale`. Translation will be 0 and rotation 0 on - ///all axes. - from_scale(Wrapped(Vec3)) -> self, - - ///Returns this [`Transform`] with a new rotation so that [`Transform::forward`] - ///points towards the `target` position and [`Transform::up`] points towards `up`. - /// - ///In some cases it's not possible to construct a rotation. Another axis will be picked in those cases: - ///* if `target` is the same as the transform translation, `Vec3::Z` is used instead - ///* if `up` is zero, `Vec3::Y` is used instead - ///* if the resulting forward direction is parallel with `up`, an orthogonal vector is used as the "right" direction - looking_at(self:Wrapped(Vec3),Wrapped(Vec3)) -> self, - - ///Returns this [`Transform`] with a new rotation so that [`Transform::forward`] - ///points in the given `direction` and [`Transform::up`] points towards `up`. - /// - ///In some cases it's not possible to construct a rotation. Another axis will be picked in those cases: - ///* if `direction` is zero, `Vec3::Z` is used instead - ///* if `up` is zero, `Vec3::Y` is used instead - ///* if `direction` is parallel with `up`, an orthogonal vector is used as the "right" direction - looking_to(self:Wrapped(Vec3),Wrapped(Vec3)) -> self, - - ///Returns this [`Transform`] with a new translation. - with_translation(self:Wrapped(Vec3)) -> self, - - ///Returns this [`Transform`] with a new rotation. - with_rotation(self:Wrapped(Quat)) -> self, - - ///Returns this [`Transform`] with a new scale. - with_scale(self:Wrapped(Vec3)) -> self, - - ///Returns the 3d affine transformation matrix from this transforms translation, - ///rotation, and scale. - compute_matrix(&self:) -> Wrapped(Mat4), - - ///Returns the 3d affine transformation matrix from this transforms translation, - ///rotation, and scale. - compute_affine(&self:) -> Wrapped(Affine3A), - - ///Rotates this [`Transform`] by the given rotation. - /// - ///If this [`Transform`] has a parent, the `rotation` is relative to the rotation of the parent. - /// - ///# Examples - /// - ///- [`3d_rotation`] - /// - ///[`3d_rotation`]: https://github.com/bevyengine/bevy/blob/latest/examples/transforms/3d_rotation.rs - rotate(&mut self:Wrapped(Quat)), - - ///Rotates this [`Transform`] around the given `axis` by `angle` (in radians). - /// - ///If this [`Transform`] has a parent, the `axis` is relative to the rotation of the parent. - rotate_axis(&mut self:Wrapped(Vec3),Raw(f32)), - - ///Rotates this [`Transform`] around the `X` axis by `angle` (in radians). - /// - ///If this [`Transform`] has a parent, the axis is relative to the rotation of the parent. - rotate_x(&mut self:Raw(f32)), - - ///Rotates this [`Transform`] around the `Y` axis by `angle` (in radians). - /// - ///If this [`Transform`] has a parent, the axis is relative to the rotation of the parent. - rotate_y(&mut self:Raw(f32)), - - ///Rotates this [`Transform`] around the `Z` axis by `angle` (in radians). - /// - ///If this [`Transform`] has a parent, the axis is relative to the rotation of the parent. - rotate_z(&mut self:Raw(f32)), - - ///Rotates this [`Transform`] by the given `rotation`. - /// - ///The `rotation` is relative to this [`Transform`]'s current rotation. - rotate_local(&mut self:Wrapped(Quat)), - - ///Rotates this [`Transform`] around its local `axis` by `angle` (in radians). - rotate_local_axis(&mut self:Wrapped(Vec3),Raw(f32)), - - ///Rotates this [`Transform`] around its local `X` axis by `angle` (in radians). - rotate_local_x(&mut self:Raw(f32)), - - ///Rotates this [`Transform`] around its local `Y` axis by `angle` (in radians). - rotate_local_y(&mut self:Raw(f32)), - - ///Rotates this [`Transform`] around its local `Z` axis by `angle` (in radians). - rotate_local_z(&mut self:Raw(f32)), - - ///Translates this [`Transform`] around a `point` in space. - /// - ///If this [`Transform`] has a parent, the `point` is relative to the [`Transform`] of the parent. - translate_around(&mut self:Wrapped(Vec3),Wrapped(Quat)), - - ///Rotates this [`Transform`] around a `point` in space. - /// - ///If this [`Transform`] has a parent, the `point` is relative to the [`Transform`] of the parent. - rotate_around(&mut self:Wrapped(Vec3),Wrapped(Quat)), - - ///Rotates this [`Transform`] so that [`Transform::forward`] points towards the `target` position, - ///and [`Transform::up`] points towards `up`. - /// - ///In some cases it's not possible to construct a rotation. Another axis will be picked in those cases: - ///* if `target` is the same as the transform translation, `Vec3::Z` is used instead - ///* if `up` is zero, `Vec3::Y` is used instead - ///* if the resulting forward direction is parallel with `up`, an orthogonal vector is used as the "right" direction - look_at(&mut self:Wrapped(Vec3),Wrapped(Vec3)), - - ///Rotates this [`Transform`] so that [`Transform::forward`] points in the given `direction` - ///and [`Transform::up`] points towards `up`. - /// - ///In some cases it's not possible to construct a rotation. Another axis will be picked in those cases: - ///* if `direction` is zero, `Vec3::NEG_Z` is used instead - ///* if `up` is zero, `Vec3::Y` is used instead - ///* if `direction` is parallel with `up`, an orthogonal vector is used as the "right" direction - look_to(&mut self:Wrapped(Vec3),Wrapped(Vec3)), - - ///Multiplies `self` with `transform` component by component, returning the - ///resulting [`Transform`] - mul_transform(&self:Wrapped(Transform)) -> self, - - ///Transforms the given `point`, applying scale, rotation and translation. - /// - ///If this [`Transform`] has a parent, this will transform a `point` that is - ///relative to the parent's [`Transform`] into one relative to this [`Transform`]. - /// - ///If this [`Transform`] does not have a parent, this will transform a `point` - ///that is in global space into one relative to this [`Transform`]. - /// - ///If you want to transform a `point` in global space to the local space of this [`Transform`], - ///consider using [`GlobalTransform::transform_point()`] instead. - transform_point(&self:Wrapped(Vec3)) -> Wrapped(Vec3), - - ///Returns `true` if, and only if, translation, rotation and scale all are - ///finite. If any of them contains a `NaN`, positive or negative infinity, - ///this will return `false`. - is_finite(&self:) -> Raw(bool), - - ) - + Fields - ( - /// Position of the entity. In 2d, the last value of the `Vec3` is used for z-ordering. - /// - /// See the [`translations`] example for usage. - /// - /// [`translations`]: https://github.com/bevyengine/bevy/blob/latest/examples/transforms/translation.rs - translation: Wrapped(Vec3), - /// Rotation of the entity. - /// - /// See the [`3d_rotation`] example for usage. - /// - /// [`3d_rotation`]: https://github.com/bevyengine/bevy/blob/latest/examples/transforms/3d_rotation.rs - rotation: Wrapped(Quat), - /// Scale of the entity. - /// - /// See the [`scale`] example for usage. - /// - /// [`scale`]: https://github.com/bevyengine/bevy/blob/latest/examples/transforms/scale.rs - scale: Wrapped(Vec3), - ) - + BinOps - ( - self Mul Wrapped(Vec3) -> Wrapped(Vec3), - self Mul Wrapped(Transform) -> Wrapped(Transform), - self Mul Wrapped(GlobalTransform) -> Wrapped(GlobalTransform), - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Describe the position of an entity relative to the reference frame. - /// - ///* To place or move an entity, you should set its [`Transform`]. - ///* [`GlobalTransform`] is fully managed by bevy, you cannot mutate it, use - /// [`Transform`] instead. - ///* To get the global transform of an entity, you should get its [`GlobalTransform`]. - ///* For transform hierarchies to work correctly, you must have both a [`Transform`] and a [`GlobalTransform`]. - /// * You may use the [`TransformBundle`](crate::TransformBundle) to guarantee this. - /// - ///## [`Transform`] and [`GlobalTransform`] - /// - ///[`Transform`] is the position of an entity relative to its parent position, or the reference - ///frame if it doesn't have a [`Parent`](bevy_hierarchy::Parent). - /// - ///[`GlobalTransform`] is the position of an entity relative to the reference frame. - /// - ///[`GlobalTransform`] is updated from [`Transform`] by systems in the system set - ///[`TransformPropagate`](crate::TransformSystem::TransformPropagate). - /// - ///This system runs during [`PostUpdate`](bevy_app::PostUpdate). If you - ///update the [`Transform`] of an entity in this schedule or after, you will notice a 1 frame lag - ///before the [`GlobalTransform`] is updated. - /// - ///# Examples - /// - ///- [`transform`] - /// - ///[`transform`]: https://github.com/bevyengine/bevy/blob/latest/examples/transforms/transform.rs - bevy_transform::components::GlobalTransform : - Clone + - Debug + - Methods - ( - ///Returns the 3d affine transformation matrix as a [`Mat4`]. - compute_matrix(&self:) -> Wrapped(Mat4), - - ///Returns the 3d affine transformation matrix as an [`Affine3A`]. - affine(&self:) -> Wrapped(Affine3A), - - ///Returns the transformation as a [`Transform`]. - /// - ///The transform is expected to be non-degenerate and without shearing, or the output - ///will be invalid. - compute_transform(&self:) -> Wrapped(Transform), - - ///Returns the [`Transform`] `self` would have if it was a child of an entity - ///with the `parent` [`GlobalTransform`]. - /// - ///This is useful if you want to "reparent" an [`Entity`](bevy_ecs::entity::Entity). - ///Say you have an entity `e1` that you want to turn into a child of `e2`, - ///but you want `e1` to keep the same global transform, even after re-parenting. You would use: - /// - ///``` - ///# use bevy_transform::prelude::{GlobalTransform, Transform}; - ///# use bevy_ecs::prelude::{Entity, Query, Component, Commands}; - ///# use bevy_hierarchy::{prelude::Parent, BuildChildren}; - ///#[derive(Component)] - ///struct ToReparent { - /// new_parent: Entity, - ///} - ///fn reparent_system( - /// mut commands: Commands, - /// mut targets: Query<(&mut Transform, Entity, &GlobalTransform, &ToReparent)>, - /// transforms: Query<&GlobalTransform>, - ///) { - /// for (mut transform, entity, initial, to_reparent) in targets.iter_mut() { - /// if let Ok(parent_transform) = transforms.get(to_reparent.new_parent) { - /// *transform = initial.reparented_to(parent_transform); - /// commands.entity(entity) - /// .remove::() - /// .set_parent(to_reparent.new_parent); - /// } - /// } - ///} - ///``` - /// - ///The transform is expected to be non-degenerate and without shearing, or the output - ///will be invalid. - reparented_to(&self:Wrapped(&GlobalTransform)) -> Wrapped(Transform), - - ///Return the local right vector (X). - right(&self:) -> Wrapped(Vec3), - - ///Return the local left vector (-X). - left(&self:) -> Wrapped(Vec3), - - ///Return the local up vector (Y). - up(&self:) -> Wrapped(Vec3), - - ///Return the local down vector (-Y). - down(&self:) -> Wrapped(Vec3), - - ///Return the local back vector (Z). - back(&self:) -> Wrapped(Vec3), - - ///Return the local forward vector (-Z). - forward(&self:) -> Wrapped(Vec3), - - ///Get the translation as a [`Vec3`]. - translation(&self:) -> Wrapped(Vec3), - - ///Get the translation as a [`Vec3A`]. - translation_vec3a(&self:) -> Wrapped(Vec3A), - - ///Get an upper bound of the radius from the given `extents`. - radius_vec3a(&self:Wrapped(Vec3A)) -> Raw(f32), - - ///Transforms the given `point`, applying shear, scale, rotation and translation. - /// - ///This moves `point` into the local space of this [`GlobalTransform`]. - transform_point(&self:Wrapped(Vec3)) -> Wrapped(Vec3), - - ///Multiplies `self` with `transform` component by component, returning the - ///resulting [`GlobalTransform`] - mul_transform(&self:Wrapped(Transform)) -> self, - - ) - + Fields - ( - ) - + BinOps - ( - self Mul Wrapped(Transform) -> Wrapped(GlobalTransform), - self Mul Wrapped(Vec3) -> Wrapped(Vec3), - self Mul Wrapped(GlobalTransform) -> Wrapped(GlobalTransform), - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///An ambient light, which lights the entire scene equally. - /// - ///This resource is inserted by the [`PbrPlugin`] and by default it is set to a low ambient light. - /// - ///# Examples - /// - ///Make ambient light slightly brighter: - /// - ///``` - ///# use bevy_ecs::system::ResMut; - ///# use bevy_pbr::AmbientLight; - ///fn setup_ambient_light(mut ambient_light: ResMut) { - /// ambient_light.brightness = 100.0; - ///} - ///``` - bevy_pbr::AmbientLight : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - color: Wrapped(Color), - /// A direct scale factor multiplied with `color` before being passed to the shader. - brightness: Raw(f32), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - bevy_pbr::CubemapVisibleEntities : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A Directional light. - /// - ///Directional lights don't exist in reality but they are a good - ///approximation for light sources VERY far away, like the sun or - ///the moon. - /// - ///The light shines along the forward direction of the entity's transform. With a default transform - ///this would be along the negative-Z axis. - /// - ///Valid values for `illuminance` are: - /// - ///| Illuminance (lux) | Surfaces illuminated by | - ///|-------------------|------------------------------------------------| - ///| 0.0001 | Moonless, overcast night sky (starlight) | - ///| 0.002 | Moonless clear night sky with airglow | - ///| 0.05–0.3 | Full moon on a clear night | - ///| 3.4 | Dark limit of civil twilight under a clear sky | - ///| 20–50 | Public areas with dark surroundings | - ///| 50 | Family living room lights | - ///| 80 | Office building hallway/toilet lighting | - ///| 100 | Very dark overcast day | - ///| 150 | Train station platforms | - ///| 320–500 | Office lighting | - ///| 400 | Sunrise or sunset on a clear day. | - ///| 1000 | Overcast day; typical TV studio lighting | - ///| 10,000–25,000 | Full daylight (not direct sun) | - ///| 32,000–100,000 | Direct sunlight | - /// - ///Source: [Wikipedia](https://en.wikipedia.org/wiki/Lux) - /// - ///## Shadows - /// - ///To enable shadows, set the `shadows_enabled` property to `true`. - /// - ///Shadows are produced via [cascaded shadow maps](https://developer.download.nvidia.com/SDK/10.5/opengl/src/cascaded_shadow_maps/doc/cascaded_shadow_maps.pdf). - /// - ///To modify the cascade set up, such as the number of cascades or the maximum shadow distance, - ///change the [`CascadeShadowConfig`] component of the [`DirectionalLightBundle`]. - /// - ///To control the resolution of the shadow maps, use the [`DirectionalLightShadowMap`] resource: - /// - ///``` - ///# use bevy_app::prelude::*; - ///# use bevy_pbr::DirectionalLightShadowMap; - ///App::new() - /// .insert_resource(DirectionalLightShadowMap { size: 2048 }); - ///``` - bevy_pbr::DirectionalLight : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - color: Wrapped(Color), - /// Illuminance in lux (lumens per square meter), representing the amount of - /// light projected onto surfaces by this light source. Lux is used here - /// instead of lumens because a directional light illuminates all surfaces - /// more-or-less the same way (depending on the angle of incidence). Lumens - /// can only be specified for light sources which emit light from a specific - /// area. - illuminance: Raw(f32), - shadows_enabled: Raw(bool), - shadow_depth_bias: Raw(f32), - /// A bias applied along the direction of the fragment's surface normal. It is scaled to the - /// shadow map's texel size so that it is automatically adjusted to the orthographic projection. - shadow_normal_bias: Raw(f32), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Controls the resolution of [`DirectionalLight`] shadow maps. - bevy_pbr::DirectionalLightShadowMap : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - size: Raw(usize), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Add this component to make a [`Mesh`](bevy_render::mesh::Mesh) not cast shadows. - bevy_pbr::NotShadowCaster : - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Add this component to make a [`Mesh`](bevy_render::mesh::Mesh) not receive shadows. - /// - ///**Note:** If you're using diffuse transmission, setting [`NotShadowReceiver`] will - ///cause both “regular” shadows as well as diffusely transmitted shadows to be disabled, - ///even when [`TransmittedShadowReceiver`] is being used. - bevy_pbr::NotShadowReceiver : - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A light that emits light in all directions from a central point. - /// - ///Real-world values for `intensity` (luminous power in lumens) based on the electrical power - ///consumption of the type of real-world light are: - /// - ///| Luminous Power (lumen) (i.e. the intensity member) | Incandescent non-halogen (Watts) | Incandescent halogen (Watts) | Compact fluorescent (Watts) | LED (Watts | - ///|------|-----|----|--------|-------| - ///| 200 | 25 | | 3-5 | 3 | - ///| 450 | 40 | 29 | 9-11 | 5-8 | - ///| 800 | 60 | | 13-15 | 8-12 | - ///| 1100 | 75 | 53 | 18-20 | 10-16 | - ///| 1600 | 100 | 72 | 24-28 | 14-17 | - ///| 2400 | 150 | | 30-52 | 24-30 | - ///| 3100 | 200 | | 49-75 | 32 | - ///| 4000 | 300 | | 75-100 | 40.5 | - /// - ///Source: [Wikipedia](https://en.wikipedia.org/wiki/Lumen_(unit)#Lighting) - bevy_pbr::PointLight : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - color: Wrapped(Color), - /// Luminous power in lumens, representing the amount of light emitted by this source in all directions. - intensity: Raw(f32), - range: Raw(f32), - radius: Raw(f32), - shadows_enabled: Raw(bool), - shadow_depth_bias: Raw(f32), - /// A bias applied along the direction of the fragment's surface normal. It is scaled to the - /// shadow map's texel size so that it can be small close to the camera and gets larger further - /// away. - shadow_normal_bias: Raw(f32), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - bevy_pbr::PointLightShadowMap : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - size: Raw(usize), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Sets how a material's base color alpha channel is used for transparency. - bevy_pbr::AlphaMode : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Enables wireframe rendering for any entity it is attached to. - ///It will ignore the [`WireframeConfig`] global setting. - /// - ///This requires the [`WireframePlugin`] to be enabled. - bevy_pbr::wireframe::Wireframe : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - bevy_pbr::wireframe::WireframeConfig : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - /// Whether to show wireframes for all meshes. - /// Can be overridden for individual meshes by adding a [`Wireframe`] or [`NoWireframe`] component. - global: Raw(bool), - /// If [`Self::global`] is set, any [`Entity`] that does not have a [`Wireframe`] component attached to it will have - /// wireframes using this color. Otherwise, this will be the fallback color for any entity that has a [`Wireframe`], - /// but no [`WireframeColor`]. - default_color: Wrapped(Color), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///The depth clear operation to perform for the main 3d pass. - bevy_core_pipeline::core_3d::Camera3dDepthLoadOp : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A [`Resource`] that stores the color that is used to clear the screen between frames. - /// - ///This color appears as the "background" color for simple apps, - ///when there are portions of the screen with nothing rendered. - bevy_render::camera::ClearColor : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///For a camera, specifies the color used to clear the viewport before rendering. - bevy_render::camera::ClearColorConfig : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - bevy_core_pipeline::core_2d::Camera2d : - Clone + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Configuration for the "main 3d render graph". - bevy_core_pipeline::core_3d::Camera3d : - Clone + - Methods - ( - ) - + Fields - ( - /// The depth clear operation to perform for the main 3d pass. - depth_load_op: Wrapped(Camera3dDepthLoadOp), - /// The texture usages for the depth texture created for the main 3d pass. - depth_texture_usages: Raw(ReflectedValue), - /// How many individual steps should be performed in the [`Transmissive3d`](crate::core_3d::Transmissive3d) pass. - /// - /// Roughly corresponds to how many “layers of transparency” are rendered for screen space - /// specular transmissive objects. Each step requires making one additional - /// texture copy, so it's recommended to keep this number to a resonably low value. Defaults to `1`. - /// - /// ### Notes - /// - /// - No copies will be performed if there are no transmissive materials currently being rendered, - /// regardless of this setting. - /// - Setting this to `0` disables the screen-space refraction effect entirely, and falls - /// back to refracting only the environment map light's texture. - /// - If set to more than `0`, any opaque [`clear_color`](Camera::clear_color) will obscure the environment - /// map light's texture, preventing it from being visible “through” transmissive materials. If you'd like - /// to still have the environment map show up in your refractions, you can set the clear color's alpha to `0.0`. - /// Keep in mind that depending on the platform and your window settings, this may cause the window to become - /// transparent. - screen_space_specular_transmission_steps: Raw(usize), - /// The quality of the screen space specular transmission blur effect, applied to whatever's “behind” transmissive - /// objects when their `roughness` is greater than `0.0`. - /// - /// Higher qualities are more GPU-intensive. - /// - /// **Note:** You can get better-looking results at any quality level by enabling TAA. See: [`TemporalAntiAliasPlugin`](crate::experimental::taa::TemporalAntiAliasPlugin). - screen_space_specular_transmission_quality: Raw(ReflectedValue), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///How a sprite is positioned relative to its [`Transform`](bevy_transform::components::Transform). - ///It defaults to `Anchor::Center`. - bevy_sprite::Anchor : - Clone + - Debug + - Methods - ( - as_vec(&self:) -> Wrapped(Vec2), - - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Component for rendering with meshes in the 2d pipeline, usually with a [2d material](crate::Material2d) such as [`ColorMaterial`](crate::ColorMaterial). - /// - ///It wraps a [`Handle`] to differentiate from the 3d pipelines which use the handles directly as components - bevy_sprite::Mesh2dHandle : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Component used to draw a specific section of a texture. - /// - ///It stores a handle to [`TextureAtlasLayout`] and the index of the current section of the atlas. - ///The texture atlas contains various *sections* of a given texture, allowing users to have a single - ///image file for either sprite animation or global mapping. - ///You can change the texture [`index`](Self::index) of the atlas to animate the sprite or display only a *section* of the texture - ///for efficient rendering of related game objects. - /// - ///Check the following examples for usage: - ///- [`animated sprite sheet example`](https://github.com/bevyengine/bevy/blob/latest/examples/2d/sprite_sheet.rs) - ///- [`texture atlas example`](https://github.com/bevyengine/bevy/blob/latest/examples/2d/texture_atlas.rs) - bevy_sprite::TextureAtlas : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - /// Texture atlas layout handle - layout: Raw(ReflectedValue), - /// Texture atlas section index - index: Raw(usize), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Specifies the rendering properties of a sprite. - /// - ///This is commonly used as a component within [`SpriteBundle`](crate::bundle::SpriteBundle). - bevy_sprite::Sprite : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - /// The sprite's color tint - color: Wrapped(Color), - /// Flip the sprite along the `X` axis - flip_x: Raw(bool), - /// Flip the sprite along the `Y` axis - flip_y: Raw(bool), - /// An optional custom size for the sprite that will be used when rendering, instead of the size - /// of the sprite's image - custom_size: Raw(ReflectedValue), - /// An optional rectangle representing the region of the sprite's image to render, instead of rendering - /// the full image. This is an easy one-off alternative to using a [`TextureAtlas`](crate::TextureAtlas). - /// - /// When used with a [`TextureAtlas`](crate::TextureAtlas), the rect - /// is offset by the atlas's minimal (top-left) corner position. - rect: Raw(ReflectedValue), - /// [`Anchor`] point of the sprite in the world - anchor: Wrapped(Anchor), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Describes which rendering layers an entity belongs to. - /// - ///Cameras with this component will only render entities with intersecting - ///layers. - /// - ///There are 32 layers numbered `0` - [`TOTAL_LAYERS`](RenderLayers::TOTAL_LAYERS). Entities may - ///belong to one or more layers, or no layer at all. - /// - ///The [`Default`] instance of `RenderLayers` contains layer `0`, the first layer. - /// - ///An entity with this component without any layers is invisible. - /// - ///Entities without this component belong to layer `0`. - bevy_render::view::visibility::RenderLayers : - Clone + - Debug + - Methods - ( - ///Create a new `RenderLayers` that belongs to all layers. - all() -> self, - - ///Create a new `RenderLayers` that belongs to no layers. - none() -> self, - - ///Determine if a `RenderLayers` intersects another. - /// - ///`RenderLayers`s intersect if they share any common layers. - /// - ///A `RenderLayers` with no layers will not match any other - ///`RenderLayers`, even another with no layers. - intersects(&self:Wrapped(&RenderLayers)) -> Raw(bool), - - ///get the bitmask representation of the contained layers - bits(&self:) -> Raw(u32), - - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///User indication of whether an entity is visible. Propagates down the entity hierarchy. - /// - ///If an entity is hidden in this way, all [`Children`] (and all of their children and so on) who - ///are set to [`Inherited`](Self::Inherited) will also be hidden. - /// - ///This is done by the `visibility_propagate_system` which uses the entity hierarchy and - ///`Visibility` to set the values of each entity's [`InheritedVisibility`] component. - bevy_render::view::visibility::Visibility : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Collection of entities visible from the current view. - /// - ///This component contains all entities which are visible from the currently - ///rendered view. The collection is updated automatically by the [`VisibilitySystems::CheckVisibility`] - ///system set, and renderers can use it to optimize rendering of a particular view, to - ///prevent drawing items not visible from that view. - /// - ///This component is intended to be attached to the same entity as the [`Camera`] and - ///the [`Frustum`] defining the view. - bevy_render::view::visibility::VisibleEntities : - Clone + - Debug + - Methods - ( - len(&self:) -> Raw(usize), - - is_empty(&self:) -> Raw(bool), - - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Whether or not an entity is visible in the hierarchy. - ///This will not be accurate until [`VisibilityPropagate`] runs in the [`PostUpdate`] schedule. - /// - ///If this is false, then [`ViewVisibility`] should also be false. - /// - ///[`VisibilityPropagate`]: VisibilitySystems::VisibilityPropagate - bevy_render::view::visibility::InheritedVisibility : - Clone + - Debug + - Methods - ( - ///Returns `true` if the entity is visible in the hierarchy. - ///Otherwise, returns `false`. - get(self:) -> Raw(bool), - - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Algorithmically-computed indication of whether an entity is visible and should be extracted for rendering. - /// - ///Each frame, this will be reset to `false` during [`VisibilityPropagate`] systems in [`PostUpdate`]. - ///Later in the frame, systems in [`CheckVisibility`] will mark any visible entities using [`ViewVisibility::set`]. - ///Because of this, values of this type will be marked as changed every frame, even when they do not change. - /// - ///If you wish to add custom visibility system that sets this value, make sure you add it to the [`CheckVisibility`] set. - /// - ///[`VisibilityPropagate`]: VisibilitySystems::VisibilityPropagate - ///[`CheckVisibility`]: VisibilitySystems::CheckVisibility - bevy_render::view::visibility::ViewVisibility : - Clone + - Debug + - Methods - ( - ///Returns `true` if the entity is visible in any view. - ///Otherwise, returns `false`. - get(self:) -> Raw(bool), - - ///Sets the visibility to `true`. This should not be considered reversible for a given frame, - ///as this component tracks whether or not the entity visible in _any_ view. - /// - ///This will be automatically reset to `false` every frame in [`VisibilityPropagate`] and then set - ///to the proper value in [`CheckVisibility`]. - /// - ///You should only manually set this if you are defining a custom visibility system, - ///in which case the system should be placed in the [`CheckVisibility`] set. - ///For normal user-defined entity visibility, see [`Visibility`]. - /// - ///[`VisibilityPropagate`]: VisibilitySystems::VisibilityPropagate - ///[`CheckVisibility`]: VisibilitySystems::CheckVisibility - set(&mut self:), - - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - bevy_render::mesh::skinning::SkinnedMesh : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - inverse_bindposes: Raw(ReflectedValue), - joints: Raw(ReflectedValue), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Scaling mode for [`OrthographicProjection`]. - /// - ///# Examples - /// - ///Configure the orthographic projection to two world units per window height: - /// - ///``` - ///# use bevy_render::camera::{OrthographicProjection, Projection, ScalingMode}; - ///let projection = Projection::Orthographic(OrthographicProjection { - /// scaling_mode: ScalingMode::FixedVertical(2.0), - /// ..OrthographicProjection::default() - ///}); - ///``` - bevy_render::camera::ScalingMode : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - self Div Raw(f32) -> Wrapped(ScalingMode), - self Mul Raw(f32) -> Wrapped(ScalingMode), - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - bevy_render::color::Color : - Clone + - Debug + - Methods - ( - ///New `Color` from sRGB colorspace. - /// - ///# Arguments - /// - ///* `r` - Red channel. [0.0, 1.0] - ///* `g` - Green channel. [0.0, 1.0] - ///* `b` - Blue channel. [0.0, 1.0] - /// - ///See also [`Color::rgba`], [`Color::rgb_u8`], [`Color::hex`]. - rgb(Raw(f32),Raw(f32),Raw(f32)) -> Wrapped(Color), - - ///New `Color` from sRGB colorspace. - /// - ///# Arguments - /// - ///* `r` - Red channel. [0.0, 1.0] - ///* `g` - Green channel. [0.0, 1.0] - ///* `b` - Blue channel. [0.0, 1.0] - ///* `a` - Alpha channel. [0.0, 1.0] - /// - ///See also [`Color::rgb`], [`Color::rgba_u8`], [`Color::hex`]. - rgba(Raw(f32),Raw(f32),Raw(f32),Raw(f32)) -> Wrapped(Color), - - ///New `Color` from linear RGB colorspace. - /// - ///# Arguments - /// - ///* `r` - Red channel. [0.0, 1.0] - ///* `g` - Green channel. [0.0, 1.0] - ///* `b` - Blue channel. [0.0, 1.0] - /// - ///See also [`Color::rgb`], [`Color::rgba_linear`]. - rgb_linear(Raw(f32),Raw(f32),Raw(f32)) -> Wrapped(Color), - - ///New `Color` from linear RGB colorspace. - /// - ///# Arguments - /// - ///* `r` - Red channel. [0.0, 1.0] - ///* `g` - Green channel. [0.0, 1.0] - ///* `b` - Blue channel. [0.0, 1.0] - ///* `a` - Alpha channel. [0.0, 1.0] - /// - ///See also [`Color::rgba`], [`Color::rgb_linear`]. - rgba_linear(Raw(f32),Raw(f32),Raw(f32),Raw(f32)) -> Wrapped(Color), - - ///New `Color` with HSL representation in sRGB colorspace. - /// - ///# Arguments - /// - ///* `hue` - Hue channel. [0.0, 360.0] - ///* `saturation` - Saturation channel. [0.0, 1.0] - ///* `lightness` - Lightness channel. [0.0, 1.0] - /// - ///See also [`Color::hsla`]. - hsl(Raw(f32),Raw(f32),Raw(f32)) -> Wrapped(Color), - - ///New `Color` with HSL representation in sRGB colorspace. - /// - ///# Arguments - /// - ///* `hue` - Hue channel. [0.0, 360.0] - ///* `saturation` - Saturation channel. [0.0, 1.0] - ///* `lightness` - Lightness channel. [0.0, 1.0] - ///* `alpha` - Alpha channel. [0.0, 1.0] - /// - ///See also [`Color::hsl`]. - hsla(Raw(f32),Raw(f32),Raw(f32),Raw(f32)) -> Wrapped(Color), - - ///New `Color` with LCH representation in sRGB colorspace. - /// - ///# Arguments - /// - ///* `lightness` - Lightness channel. [0.0, 1.5] - ///* `chroma` - Chroma channel. [0.0, 1.5] - ///* `hue` - Hue channel. [0.0, 360.0] - /// - ///See also [`Color::lcha`]. - lch(Raw(f32),Raw(f32),Raw(f32)) -> Wrapped(Color), - - ///New `Color` with LCH representation in sRGB colorspace. - /// - ///# Arguments - /// - ///* `lightness` - Lightness channel. [0.0, 1.5] - ///* `chroma` - Chroma channel. [0.0, 1.5] - ///* `hue` - Hue channel. [0.0, 360.0] - ///* `alpha` - Alpha channel. [0.0, 1.0] - /// - ///See also [`Color::lch`]. - lcha(Raw(f32),Raw(f32),Raw(f32),Raw(f32)) -> Wrapped(Color), - - ///New `Color` from sRGB colorspace. - /// - ///# Arguments - /// - ///* `r` - Red channel. [0, 255] - ///* `g` - Green channel. [0, 255] - ///* `b` - Blue channel. [0, 255] - /// - ///See also [`Color::rgb`], [`Color::rgba_u8`], [`Color::hex`]. - rgb_u8(Raw(u8),Raw(u8),Raw(u8)) -> Wrapped(Color), - - ///New `Color` from sRGB colorspace. - /// - ///# Arguments - /// - ///* `r` - Red channel. [0, 255] - ///* `g` - Green channel. [0, 255] - ///* `b` - Blue channel. [0, 255] - ///* `a` - Alpha channel. [0, 255] - /// - ///See also [`Color::rgba`], [`Color::rgb_u8`], [`Color::hex`]. - rgba_u8(Raw(u8),Raw(u8),Raw(u8),Raw(u8)) -> Wrapped(Color), - - ///Converts a Color to variant [`Color::Rgba`] and return red in sRGB colorspace - r(&self:) -> Raw(f32), - - ///Converts a Color to variant [`Color::Rgba`] and return green in sRGB colorspace - g(&self:) -> Raw(f32), - - ///Converts a Color to variant [`Color::Rgba`] and return blue in sRGB colorspace - b(&self:) -> Raw(f32), - - ///Converts a Color to variant [`Color::Rgba`] and return this color with red set to a new value - with_r(self:Raw(f32)) -> self, - - ///Converts a Color to variant [`Color::Rgba`] and return this color with green set to a new value - with_g(self:Raw(f32)) -> self, - - ///Converts a Color to variant [`Color::Rgba`] and return this color with blue set to a new value - with_b(self:Raw(f32)) -> self, - - ///Converts a Color to variant [`Color::Hsla`] and return hue - h(&self:) -> Raw(f32), - - ///Converts a Color to variant [`Color::Hsla`] and return saturation - s(&self:) -> Raw(f32), - - ///Converts a Color to variant [`Color::Hsla`] and return lightness - l(&self:) -> Raw(f32), - - ///Converts a Color to variant [`Color::Hsla`] and return this color with hue set to a new value - with_h(self:Raw(f32)) -> self, - - ///Converts a Color to variant [`Color::Hsla`] and return this color with saturation set to a new value - with_s(self:Raw(f32)) -> self, - - ///Converts a Color to variant [`Color::Hsla`] and return this color with lightness set to a new value - with_l(self:Raw(f32)) -> self, - - ///Get alpha. - a(&self:) -> Raw(f32), - - ///Returns this color with a new alpha value. - with_a(self:Raw(f32)) -> self, - - ///Determine if the color is fully transparent, i.e. if the alpha is 0. - /// - ///# Examples - /// - ///``` - ///# use bevy_render::color::Color; - ///// Fully transparent colors - ///assert!(Color::NONE.is_fully_transparent()); - ///assert!(Color::rgba(1.0, 0.5, 0.5, 0.0).is_fully_transparent()); - /// - ///// (Partially) opaque colors - ///assert!(!Color::BLACK.is_fully_transparent()); - ///assert!(!Color::rgba(1.0, 0.5, 0.5, 0.2).is_fully_transparent()); - ///``` - is_fully_transparent(&self:) -> Raw(bool), - - ///Converts a `Color` to variant `Color::Rgba` - as_rgba(Wrapped(&Color):) -> Wrapped(Color), - - ///Converts a `Color` to variant `Color::RgbaLinear` - as_rgba_linear(Wrapped(&Color):) -> Wrapped(Color), - - ///Converts a `Color` to variant `Color::Hsla` - as_hsla(Wrapped(&Color):) -> Wrapped(Color), - - ///Converts a `Color` to variant `Color::Lcha` - as_lcha(Wrapped(&Color):) -> Wrapped(Color), - - ///Converts `Color` to a `u32` from sRGB colorspace. - /// - ///Maps the RGBA channels in RGBA order to a little-endian byte array (GPUs are little-endian). - ///`A` will be the most significant byte and `R` the least significant. - as_rgba_u32(Wrapped(Color):) -> Raw(u32), - - ///Converts Color to a u32 from linear RGB colorspace. - /// - ///Maps the RGBA channels in RGBA order to a little-endian byte array (GPUs are little-endian). - ///`A` will be the most significant byte and `R` the least significant. - as_linear_rgba_u32(Wrapped(Color):) -> Raw(u32), - - ///Convert `Color` to RGBA and return as `Vec4`. - rgba_to_vec4(&self:) -> Wrapped(Vec4), - - ///Convert `Color` to RGBA and return as `Vec3`. - rgb_to_vec3(&self:) -> Wrapped(Vec3), - - ///Convert `Color` to linear RGBA and return as `Vec4`. - rgba_linear_to_vec4(&self:) -> Wrapped(Vec4), - - ///Convert `Color` to linear RGBA and return as `Vec3`. - rgb_linear_to_vec3(&self:) -> Wrapped(Vec3), - - ///Convert `Color` to HSLA and return as `Vec4`. - hsla_to_vec4(&self:) -> Wrapped(Vec4), - - ///Convert `Color` to HSLA and return as `Vec3`. - hsl_to_vec3(&self:) -> Wrapped(Vec3), - - ///Convert `Color` to LCHA and return as `Vec4`. - lcha_to_vec4(&self:) -> Wrapped(Vec4), - - ///Convert `Color` to LCHA and return as `Vec3`. - lch_to_vec3(&self:) -> Wrapped(Vec3), - - ) - + Fields - ( - ) - + BinOps - ( - self Add Wrapped(Color) -> Wrapped(Color), - self Mul Raw(f32) -> Wrapped(Color), - self Mul Wrapped(Vec3) -> Wrapped(Color), - self Mul Wrapped(Vec4) -> Wrapped(Color), - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///An axis-aligned bounding box, defined by: - ///- a center, - ///- the distances from the center to each faces along the axis, - ///the faces are orthogonal to the axis. - /// - ///It is typically used as a component on an entity to represent the local space - ///occupied by this entity, with faces orthogonal to its local axis. - /// - ///This component is notably used during "frustum culling", a process to determine - ///if an entity should be rendered by a [`Camera`] if its bounding box intersects - ///with the camera's [`Frustum`]. - /// - ///It will be added automatically by the systems in [`CalculateBounds`] to entities that: - ///- could be subject to frustum culling, for example with a [`Handle`] - ///or `Sprite` component, - ///- don't have the [`NoFrustumCulling`] component. - /// - ///It won't be updated automatically if the space occupied by the entity changes, - ///for example if the vertex positions of a [`Mesh`] inside a `Handle` are - ///updated. - /// - ///[`Camera`]: crate::camera::Camera - ///[`NoFrustumCulling`]: crate::view::visibility::NoFrustumCulling - ///[`CalculateBounds`]: crate::view::visibility::VisibilitySystems::CalculateBounds - ///[`Mesh`]: crate::mesh::Mesh - ///[`Handle`]: crate::mesh::Mesh - bevy_render::primitives::Aabb : - Clone + - Debug + - Methods - ( - from_min_max(Wrapped(Vec3),Wrapped(Vec3)) -> self, - - ///Calculate the relative radius of the AABB with respect to a plane - relative_radius(&self:Wrapped(&Vec3A),Wrapped(&Mat3A)) -> Raw(f32), - - min(&self:) -> Wrapped(Vec3A), - - max(&self:) -> Wrapped(Vec3A), - - ) - + Fields - ( - center: Wrapped(Vec3A), - half_extents: Wrapped(Vec3A), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - bevy_render::primitives::CubemapFrusta : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A region of 3D space defined by the intersection of 6 [`HalfSpace`]s. - /// - ///Frustums are typically an apex-truncated square pyramid (a pyramid without the top) or a cuboid. - /// - ///Half spaces are ordered left, right, top, bottom, near, far. The normal vectors - ///of the half-spaces point towards the interior of the frustum. - /// - ///A frustum component is used on an entity with a [`Camera`] component to - ///determine which entities will be considered for rendering by this camera. - ///All entities with an [`Aabb`] component that are not contained by (or crossing - ///the boundary of) the frustum will not be rendered, and not be used in rendering computations. - /// - ///This process is called frustum culling, and entities can opt out of it using - ///the [`NoFrustumCulling`] component. - /// - ///The frustum component is typically added from a bundle, either the `Camera2dBundle` - ///or the `Camera3dBundle`. - ///It is usually updated automatically by [`update_frusta`] from the - ///[`CameraProjection`] component and [`GlobalTransform`] of the camera entity. - /// - ///[`Camera`]: crate::camera::Camera - ///[`NoFrustumCulling`]: crate::view::visibility::NoFrustumCulling - ///[`update_frusta`]: crate::view::visibility::update_frusta - ///[`CameraProjection`]: crate::camera::CameraProjection - ///[`GlobalTransform`]: bevy_transform::components::GlobalTransform - bevy_render::primitives::Frustum : - Clone + - Debug + - Methods - ( - ///Returns a frustum derived from `view_projection`. - from_view_projection(Wrapped(&Mat4)) -> self, - - ///Returns a frustum derived from `view_projection`, - ///but with a custom far plane. - from_view_projection_custom_far(Wrapped(&Mat4),Wrapped(&Vec3),Wrapped(&Vec3),Raw(f32)) -> self, - - ///Checks if an Oriented Bounding Box (obb) intersects the frustum. - intersects_obb(&self:Wrapped(&Aabb),Wrapped(&Affine3A),Raw(bool),Raw(bool)) -> Raw(bool), - - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Configuration resource for [Multi-Sample Anti-Aliasing](https://en.wikipedia.org/wiki/Multisample_anti-aliasing). - /// - ///The number of samples to run for Multi-Sample Anti-Aliasing. Higher numbers result in - ///smoother edges. - ///Defaults to 4 samples. - /// - ///Note that web currently only supports 1 or 4 samples. - /// - ///# Example - ///``` - ///# use bevy_app::prelude::App; - ///# use bevy_render::prelude::Msaa; - ///App::new() - /// .insert_resource(Msaa::default()) - /// .run(); - ///``` - bevy_render::view::Msaa : - Clone + - Debug + - Methods - ( - samples(&self:) -> Raw(u32), - - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///The defining [`Component`] for camera entities, - ///storing information about how and what to render through this camera. - /// - ///The [`Camera`] component is added to an entity to define the properties of the viewpoint from - ///which rendering occurs. It defines the position of the view to render, the projection method - ///to transform the 3D objects into a 2D image, as well as the render target into which that image - ///is produced. - /// - ///Adding a camera is typically done by adding a bundle, either the `Camera2dBundle` or the - ///`Camera3dBundle`. - bevy_render::camera::Camera : - Clone + - Debug + - Methods - ( - ///The projection matrix computed using this camera's [`CameraProjection`]. - projection_matrix(&self:) -> Wrapped(Mat4), - - ) - + Fields - ( - /// If set, this camera will render to the given [`Viewport`] rectangle within the configured [`RenderTarget`]. - viewport: Raw(ReflectedValue), - /// Cameras with a higher order are rendered later, and thus on top of lower order cameras. - order: Raw(isize), - /// If this is set to `true`, this camera will be rendered to its specified [`RenderTarget`]. If `false`, this - /// camera will not be rendered. - is_active: Raw(bool), - /// The "target" that this camera will render to. - target: Wrapped(RenderTarget), - /// If this is set to `true`, the camera will use an intermediate "high dynamic range" render texture. - /// This allows rendering with a wider range of lighting values. - hdr: Raw(bool), - /// If this is enabled, a previous camera exists that shares this camera's render target, and this camera has MSAA enabled, then the previous camera's - /// outputs will be written to the intermediate multi-sampled render target textures for this camera. This enables cameras with MSAA enabled to - /// "write their results on top" of previous camera results, and include them as a part of their render results. This is enabled by default to ensure - /// cameras with MSAA enabled layer their results in the same way as cameras without MSAA enabled by default. - msaa_writeback: Raw(bool), - /// The clear color operation to perform on the render target. - clear_color: Wrapped(ClearColorConfig), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///The "target" that a [`Camera`] will render to. For example, this could be a [`Window`] - ///swapchain or an [`Image`]. - bevy_render::camera::RenderTarget : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Render viewport configuration for the [`Camera`] component. - /// - ///The viewport defines the area on the render target to which the camera renders its image. - ///You can overlay multiple cameras in a single window using viewports to create effects like - ///split screen, minimaps, and character viewers. - bevy_render::camera::Viewport : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - /// The physical position to render this viewport to within the [`RenderTarget`] of this [`Camera`]. - /// (0,0) corresponds to the top-left corner - physical_position: Wrapped(UVec2), - /// The physical size of the viewport rectangle to render to within the [`RenderTarget`] of this [`Camera`]. - /// The origin of the rectangle is in the top-left corner. - physical_size: Wrapped(UVec2), - /// The minimum and maximum depth to render (on a scale from 0.0 to 1.0). - depth: Raw(ReflectedValue), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A configurable [`CameraProjection`] that can select its projection type at runtime. - bevy_render::camera::Projection : - Clone + - Debug + - Methods - ( - get_projection_matrix(&self:) -> Wrapped(Mat4), - - update(&mut self:Raw(f32),Raw(f32)), - - far(&self:) -> Raw(f32), - - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Project a 3D space onto a 2D surface using parallel lines, i.e., unlike [`PerspectiveProjection`], - ///the size of objects remains the same regardless of their distance to the camera. - /// - ///The volume contained in the projection is called the *view frustum*. Since the viewport is rectangular - ///and projection lines are parallel, the view frustum takes the shape of a cuboid. - /// - ///Note that the scale of the projection and the apparent size of objects are inversely proportional. - ///As the size of the projection increases, the size of objects decreases. - /// - ///# Examples - /// - ///Configure the orthographic projection to one world unit per 100 window pixels: - /// - ///``` - ///# use bevy_render::camera::{OrthographicProjection, Projection, ScalingMode}; - ///let projection = Projection::Orthographic(OrthographicProjection { - /// scaling_mode: ScalingMode::WindowSize(100.0), - /// ..OrthographicProjection::default() - ///}); - ///``` - bevy_render::camera::OrthographicProjection : - Clone + - Debug + - Methods - ( - get_projection_matrix(&self:) -> Wrapped(Mat4), - - update(&mut self:Raw(f32),Raw(f32)), - - far(&self:) -> Raw(f32), - - ) - + Fields - ( - /// The distance of the near clipping plane in world units. - /// - /// Objects closer than this will not be rendered. - /// - /// Defaults to `0.0` - near: Raw(f32), - /// The distance of the far clipping plane in world units. - /// - /// Objects further than this will not be rendered. - /// - /// Defaults to `1000.0` - #[rename("_far")] - far: Raw(f32), - /// Specifies the origin of the viewport as a normalized position from 0 to 1, where (0, 0) is the bottom left - /// and (1, 1) is the top right. This determines where the camera's position sits inside the viewport. - /// - /// When the projection scales due to viewport resizing, the position of the camera, and thereby `viewport_origin`, - /// remains at the same relative point. - /// - /// Consequently, this is pivot point when scaling. With a bottom left pivot, the projection will expand - /// upwards and to the right. With a top right pivot, the projection will expand downwards and to the left. - /// Values in between will caused the projection to scale proportionally on each axis. - /// - /// Defaults to `(0.5, 0.5)`, which makes scaling affect opposite sides equally, keeping the center - /// point of the viewport centered. - viewport_origin: Wrapped(Vec2), - /// How the projection will scale to the viewport. - /// - /// Defaults to `ScalingMode::WindowSize(1.0)` - scaling_mode: Wrapped(ScalingMode), - /// Scales the projection. - /// - /// As scale increases, the apparent size of objects decreases, and vice versa. - /// - /// Note: scaling can be set by [`scaling_mode`](Self::scaling_mode) as well. - /// This parameter scales on top of that. - /// - /// This property is particularly useful in implementing zoom functionality. - /// - /// Defaults to `1.0`. - scale: Raw(f32), - /// The area that the projection covers relative to `viewport_origin`. - /// - /// Bevy's [`camera_system`](crate::camera::camera_system) automatically - /// updates this value when the viewport is resized depending on `OrthographicProjection`'s other fields. - /// In this case, `area` should not be manually modified. - /// - /// It may be necessary to set this manually for shadow projections and such. - area: Wrapped(Rect), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 3D camera projection in which distant objects appear smaller than close objects. - bevy_render::camera::PerspectiveProjection : - Clone + - Debug + - Methods - ( - get_projection_matrix(&self:) -> Wrapped(Mat4), - - update(&mut self:Raw(f32),Raw(f32)), - - far(&self:) -> Raw(f32), - - ) - + Fields - ( - /// The vertical field of view (FOV) in radians. - /// - /// Defaults to a value of π/4 radians or 45 degrees. - fov: Raw(f32), - /// The aspect ratio (width divided by height) of the viewing frustum. - /// - /// Bevy's [`camera_system`](crate::camera::camera_system) automatically - /// updates this value when the aspect ratio of the associated window changes. - /// - /// Defaults to a value of `1.0`. - aspect_ratio: Raw(f32), - /// The distance from the camera in world units of the viewing frustum's near plane. - /// - /// Objects closer to the camera than this value will not be visible. - /// - /// Defaults to a value of `0.1`. - near: Raw(f32), - /// The distance from the camera in world units of the viewing frustum's far plane. - /// - /// Objects farther from the camera than this value will not be visible. - /// - /// Defaults to a value of `1000.0`. - #[rename("_far")] - far: Raw(f32), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Configures the [`RenderGraph`](crate::render_graph::RenderGraph) name assigned to be run for a given [`Camera`] entity. - bevy_render::camera::CameraRenderGraph : - Clone + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A generational runtime-only identifier for a specific [`Asset`] stored in [`Assets`]. This is optimized for efficient runtime - ///usage and is not suitable for identifying assets across app runs. - bevy_asset::AssetIndex : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 2-dimensional vector. - glam::f32::Vec2 : - Clone + - Debug + - Methods - ( - ///Creates a new vector. - new(Raw(f32),Raw(f32)) -> self, - - ///Creates a vector with all elements set to `v`. - splat(Raw(f32)) -> self, - - ///Creates a vector from the elements in `if_true` and `if_false`, selecting which to use - ///for each element of `self`. - /// - ///A true element in the mask uses the corresponding element from `if_true`, and false - ///uses the element from `if_false`. - select(Wrapped(BVec2),self,self) -> self, - - ///Creates a 3D vector from `self` and the given `z` value. - extend(self:Raw(f32)) -> Wrapped(Vec3), - - ///Computes the dot product of `self` and `rhs`. - dot(self:self) -> Raw(f32), - - ///Returns a vector where every component is the dot product of `self` and `rhs`. - dot_into_vec(self:self) -> self, - - ///Returns a vector containing the minimum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.min(rhs.x), self.y.min(rhs.y), ..]`. - min(self:self) -> self, - - ///Returns a vector containing the maximum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.max(rhs.x), self.y.max(rhs.y), ..]`. - max(self:self) -> self, - - ///Component-wise clamping of values, similar to [`f32::clamp`]. - /// - ///Each element in `min` must be less-or-equal to the corresponding element in `max`. - /// - ///# Panics - /// - ///Will panic if `min` is greater than `max` when `glam_assert` is enabled. - clamp(self:self,self) -> self, - - ///Returns the horizontal minimum of `self`. - /// - ///In other words this computes `min(x, y, ..)`. - min_element(self:) -> Raw(f32), - - ///Returns the horizontal maximum of `self`. - /// - ///In other words this computes `max(x, y, ..)`. - max_element(self:) -> Raw(f32), - - ///Returns a vector mask containing the result of a `==` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all - ///elements. - cmpeq(self:self) -> Wrapped(BVec2), - - ///Returns a vector mask containing the result of a `!=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all - ///elements. - cmpne(self:self) -> Wrapped(BVec2), - - ///Returns a vector mask containing the result of a `>=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all - ///elements. - cmpge(self:self) -> Wrapped(BVec2), - - ///Returns a vector mask containing the result of a `>` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all - ///elements. - cmpgt(self:self) -> Wrapped(BVec2), - - ///Returns a vector mask containing the result of a `<=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all - ///elements. - cmple(self:self) -> Wrapped(BVec2), - - ///Returns a vector mask containing the result of a `<` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all - ///elements. - cmplt(self:self) -> Wrapped(BVec2), - - ///Returns a vector containing the absolute value of each element of `self`. - abs(self:) -> self, - - ///Returns a vector with elements representing the sign of `self`. - /// - ///- `1.0` if the number is positive, `+0.0` or `INFINITY` - ///- `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` - ///- `NAN` if the number is `NAN` - signum(self:) -> self, - - ///Returns a vector with signs of `rhs` and the magnitudes of `self`. - copysign(self:self) -> self, - - ///Returns a bitmask with the lowest 2 bits set to the sign bits from the elements of `self`. - /// - ///A negative element results in a `1` bit and a positive element in a `0` bit. Element `x` goes - ///into the first lowest bit, element `y` into the second, etc. - is_negative_bitmask(self:) -> Raw(u32), - - ///Returns `true` if, and only if, all elements are finite. If any element is either - ///`NaN`, positive or negative infinity, this will return `false`. - is_finite(self:) -> Raw(bool), - - ///Returns `true` if any elements are `NaN`. - is_nan(self:) -> Raw(bool), - - ///Performs `is_nan` on each element of self, returning a vector mask of the results. - /// - ///In other words, this computes `[x.is_nan(), y.is_nan(), z.is_nan(), w.is_nan()]`. - is_nan_mask(self:) -> Wrapped(BVec2), - - ///Computes the length of `self`. - length(self:) -> Raw(f32), - - ///Computes the squared length of `self`. - /// - ///This is faster than `length()` as it avoids a square root operation. - length_squared(self:) -> Raw(f32), - - ///Computes `1.0 / length()`. - /// - ///For valid results, `self` must _not_ be of length zero. - length_recip(self:) -> Raw(f32), - - ///Computes the Euclidean distance between two points in space. - distance(self:self) -> Raw(f32), - - ///Compute the squared euclidean distance between two points in space. - distance_squared(self:self) -> Raw(f32), - - ///Returns the element-wise quotient of [Euclidean division] of `self` by `rhs`. - div_euclid(self:self) -> self, - - ///Returns the element-wise remainder of [Euclidean division] of `self` by `rhs`. - /// - ///[Euclidean division]: f32::rem_euclid - rem_euclid(self:self) -> self, - - ///Returns `self` normalized to length 1.0. - /// - ///For valid results, `self` must _not_ be of length zero, nor very close to zero. - /// - ///See also [`Self::try_normalize()`] and [`Self::normalize_or_zero()`]. - /// - ///Panics - /// - ///Will panic if `self` is zero length when `glam_assert` is enabled. - normalize(self:) -> self, - - ///Returns `self` normalized to length 1.0 if possible, else returns zero. - /// - ///In particular, if the input is zero (or very close to zero), or non-finite, - ///the result of this operation will be zero. - /// - ///See also [`Self::try_normalize()`]. - normalize_or_zero(self:) -> self, - - ///Returns whether `self` is length `1.0` or not. - /// - ///Uses a precision threshold of `1e-6`. - is_normalized(self:) -> Raw(bool), - - ///Returns the vector projection of `self` onto `rhs`. - /// - ///`rhs` must be of non-zero length. - /// - ///# Panics - /// - ///Will panic if `rhs` is zero length when `glam_assert` is enabled. - project_onto(self:self) -> self, - - ///Returns the vector rejection of `self` from `rhs`. - /// - ///The vector rejection is the vector perpendicular to the projection of `self` onto - ///`rhs`, in rhs words the result of `self - self.project_onto(rhs)`. - /// - ///`rhs` must be of non-zero length. - /// - ///# Panics - /// - ///Will panic if `rhs` has a length of zero when `glam_assert` is enabled. - reject_from(self:self) -> self, - - ///Returns the vector projection of `self` onto `rhs`. - /// - ///`rhs` must be normalized. - /// - ///# Panics - /// - ///Will panic if `rhs` is not normalized when `glam_assert` is enabled. - project_onto_normalized(self:self) -> self, - - ///Returns the vector rejection of `self` from `rhs`. - /// - ///The vector rejection is the vector perpendicular to the projection of `self` onto - ///`rhs`, in rhs words the result of `self - self.project_onto(rhs)`. - /// - ///`rhs` must be normalized. - /// - ///# Panics - /// - ///Will panic if `rhs` is not normalized when `glam_assert` is enabled. - reject_from_normalized(self:self) -> self, - - ///Returns a vector containing the nearest integer to a number for each element of `self`. - ///Round half-way cases away from 0.0. - round(self:) -> self, - - ///Returns a vector containing the largest integer less than or equal to a number for each - ///element of `self`. - floor(self:) -> self, - - ///Returns a vector containing the smallest integer greater than or equal to a number for - ///each element of `self`. - ceil(self:) -> self, - - ///Returns a vector containing the integer part each element of `self`. This means numbers are - ///always truncated towards zero. - trunc(self:) -> self, - - ///Returns a vector containing the fractional part of the vector, e.g. `self - - ///self.floor()`. - /// - ///Note that this is fast but not precise for large numbers. - fract(self:) -> self, - - ///Returns a vector containing `e^self` (the exponential function) for each element of - ///`self`. - exp(self:) -> self, - - ///Returns a vector containing each element of `self` raised to the power of `n`. - powf(self:Raw(f32)) -> self, - - ///Returns a vector containing the reciprocal `1.0/n` of each element of `self`. - recip(self:) -> self, - - ///Performs a linear interpolation between `self` and `rhs` based on the value `s`. - /// - ///When `s` is `0.0`, the result will be equal to `self`. When `s` is `1.0`, the result - ///will be equal to `rhs`. When `s` is outside of range `[0, 1]`, the result is linearly - ///extrapolated. - lerp(self:self,Raw(f32)) -> self, - - ///Returns true if the absolute difference of all elements between `self` and `rhs` is - ///less than or equal to `max_abs_diff`. - /// - ///This can be used to compare if two vectors contain similar elements. It works best when - ///comparing with a known value. The `max_abs_diff` that should be used used depends on - ///the values being compared against. - /// - ///For more see - ///[comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - abs_diff_eq(self:self,Raw(f32)) -> Raw(bool), - - ///Returns a vector with a length no less than `min` and no more than `max` - /// - ///# Panics - /// - ///Will panic if `min` is greater than `max` when `glam_assert` is enabled. - clamp_length(self:Raw(f32),Raw(f32)) -> self, - - ///Returns a vector with a length no more than `max` - clamp_length_max(self:Raw(f32)) -> self, - - ///Returns a vector with a length no less than `min` - clamp_length_min(self:Raw(f32)) -> self, - - ///Fused multiply-add. Computes `(self * a) + b` element-wise with only one rounding - ///error, yielding a more accurate result than an unfused multiply-add. - /// - ///Using `mul_add` *may* be more performant than an unfused multiply-add if the target - ///architecture has a dedicated fma CPU instruction. However, this is not always true, - ///and will be heavily dependant on designing algorithms with specific target hardware in - ///mind. - mul_add(self:self,self) -> self, - - ///Creates a 2D vector containing `[angle.cos(), angle.sin()]`. This can be used in - ///conjunction with the [`rotate()`][Self::rotate()] method, e.g. - ///`Vec2::from_angle(PI).rotate(Vec2::Y)` will create the vector `[-1, 0]` - ///and rotate [`Vec2::Y`] around it returning `-Vec2::Y`. - from_angle(Raw(f32)) -> self, - - ///Returns the angle (in radians) of this vector in the range `[-π, +π]`. - /// - ///The input does not need to be a unit vector however it must be non-zero. - to_angle(self:) -> Raw(f32), - - ///Returns the angle (in radians) between `self` and `rhs` in the range `[-π, +π]`. - /// - ///The inputs do not need to be unit vectors however they must be non-zero. - angle_between(self:self) -> Raw(f32), - - ///Returns a vector that is equal to `self` rotated by 90 degrees. - perp(self:) -> self, - - ///The perpendicular dot product of `self` and `rhs`. - ///Also known as the wedge product, 2D cross product, and determinant. - perp_dot(self:self) -> Raw(f32), - - ///Returns `rhs` rotated by the angle of `self`. If `self` is normalized, - ///then this just rotation. This is what you usually want. Otherwise, - ///it will be like a rotation with a multiplication by `self`'s length. - rotate(self:self) -> self, - - ///Casts all elements of `self` to `f64`. - as_dvec2(&self:) -> Wrapped(DVec2), - - ///Casts all elements of `self` to `i32`. - as_ivec2(&self:) -> Wrapped(IVec2), - - ///Casts all elements of `self` to `u32`. - as_uvec2(&self:) -> Wrapped(UVec2), - - ) - + Fields - ( - x: Raw(f32), - y: Raw(f32), - ) - + BinOps - ( - self Add Wrapped(Vec2) -> Wrapped(Vec2), - self Add self -> Wrapped(Vec2), - self Add Raw(f32) -> Wrapped(Vec2), - self Sub Raw(f32) -> Wrapped(Vec2), - self Sub self -> Wrapped(Vec2), - self Sub Wrapped(Vec2) -> Wrapped(Vec2), - self Div Wrapped(Vec2) -> Wrapped(Vec2), - self Div self -> Wrapped(Vec2), - self Div Raw(f32) -> Wrapped(Vec2), - self Mul Wrapped(Vec2) -> Wrapped(Vec2), - self Mul Raw(f32) -> Wrapped(Vec2), - self Mul self -> Wrapped(Vec2), - self Rem Wrapped(Vec2) -> Wrapped(Vec2), - self Rem self -> Wrapped(Vec2), - self Rem Raw(f32) -> Wrapped(Vec2), - ) - + UnaryOps - ( - Neg self -> self - ) - lua impl - { - (MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}; - mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,f32)| {s.val_mut(|s| Ok(s[*idx] = val))?}; - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 3-dimensional vector. - glam::f32::Vec3 : - Clone + - Debug + - Methods - ( - ///Creates a new vector. - new(Raw(f32),Raw(f32),Raw(f32)) -> self, - - ///Creates a vector with all elements set to `v`. - splat(Raw(f32)) -> self, - - ///Creates a vector from the elements in `if_true` and `if_false`, selecting which to use - ///for each element of `self`. - /// - ///A true element in the mask uses the corresponding element from `if_true`, and false - ///uses the element from `if_false`. - select(Wrapped(BVec3),self,self) -> self, - - ///Creates a 4D vector from `self` and the given `w` value. - extend(self:Raw(f32)) -> Wrapped(Vec4), - - ///Creates a 2D vector from the `x` and `y` elements of `self`, discarding `z`. - /// - ///Truncation may also be performed by using [`self.xy()`][crate::swizzles::Vec3Swizzles::xy()]. - truncate(self:) -> Wrapped(Vec2), - - ///Computes the dot product of `self` and `rhs`. - dot(self:self) -> Raw(f32), - - ///Returns a vector where every component is the dot product of `self` and `rhs`. - dot_into_vec(self:self) -> self, - - ///Computes the cross product of `self` and `rhs`. - cross(self:self) -> self, - - ///Returns a vector containing the minimum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.min(rhs.x), self.y.min(rhs.y), ..]`. - min(self:self) -> self, - - ///Returns a vector containing the maximum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.max(rhs.x), self.y.max(rhs.y), ..]`. - max(self:self) -> self, - - ///Component-wise clamping of values, similar to [`f32::clamp`]. - /// - ///Each element in `min` must be less-or-equal to the corresponding element in `max`. - /// - ///# Panics - /// - ///Will panic if `min` is greater than `max` when `glam_assert` is enabled. - clamp(self:self,self) -> self, - - ///Returns the horizontal minimum of `self`. - /// - ///In other words this computes `min(x, y, ..)`. - min_element(self:) -> Raw(f32), - - ///Returns the horizontal maximum of `self`. - /// - ///In other words this computes `max(x, y, ..)`. - max_element(self:) -> Raw(f32), - - ///Returns a vector mask containing the result of a `==` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all - ///elements. - cmpeq(self:self) -> Wrapped(BVec3), - - ///Returns a vector mask containing the result of a `!=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all - ///elements. - cmpne(self:self) -> Wrapped(BVec3), - - ///Returns a vector mask containing the result of a `>=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all - ///elements. - cmpge(self:self) -> Wrapped(BVec3), - - ///Returns a vector mask containing the result of a `>` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all - ///elements. - cmpgt(self:self) -> Wrapped(BVec3), - - ///Returns a vector mask containing the result of a `<=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all - ///elements. - cmple(self:self) -> Wrapped(BVec3), - - ///Returns a vector mask containing the result of a `<` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all - ///elements. - cmplt(self:self) -> Wrapped(BVec3), - - ///Returns a vector containing the absolute value of each element of `self`. - abs(self:) -> self, - - ///Returns a vector with elements representing the sign of `self`. - /// - ///- `1.0` if the number is positive, `+0.0` or `INFINITY` - ///- `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` - ///- `NAN` if the number is `NAN` - signum(self:) -> self, - - ///Returns a vector with signs of `rhs` and the magnitudes of `self`. - copysign(self:self) -> self, - - ///Returns a bitmask with the lowest 3 bits set to the sign bits from the elements of `self`. - /// - ///A negative element results in a `1` bit and a positive element in a `0` bit. Element `x` goes - ///into the first lowest bit, element `y` into the second, etc. - is_negative_bitmask(self:) -> Raw(u32), - - ///Returns `true` if, and only if, all elements are finite. If any element is either - ///`NaN`, positive or negative infinity, this will return `false`. - is_finite(self:) -> Raw(bool), - - ///Returns `true` if any elements are `NaN`. - is_nan(self:) -> Raw(bool), - - ///Performs `is_nan` on each element of self, returning a vector mask of the results. - /// - ///In other words, this computes `[x.is_nan(), y.is_nan(), z.is_nan(), w.is_nan()]`. - is_nan_mask(self:) -> Wrapped(BVec3), - - ///Computes the length of `self`. - length(self:) -> Raw(f32), - - ///Computes the squared length of `self`. - /// - ///This is faster than `length()` as it avoids a square root operation. - length_squared(self:) -> Raw(f32), - - ///Computes `1.0 / length()`. - /// - ///For valid results, `self` must _not_ be of length zero. - length_recip(self:) -> Raw(f32), - - ///Computes the Euclidean distance between two points in space. - distance(self:self) -> Raw(f32), - - ///Compute the squared euclidean distance between two points in space. - distance_squared(self:self) -> Raw(f32), - - ///Returns the element-wise quotient of [Euclidean division] of `self` by `rhs`. - div_euclid(self:self) -> self, - - ///Returns the element-wise remainder of [Euclidean division] of `self` by `rhs`. - /// - ///[Euclidean division]: f32::rem_euclid - rem_euclid(self:self) -> self, - - ///Returns `self` normalized to length 1.0. - /// - ///For valid results, `self` must _not_ be of length zero, nor very close to zero. - /// - ///See also [`Self::try_normalize()`] and [`Self::normalize_or_zero()`]. - /// - ///Panics - /// - ///Will panic if `self` is zero length when `glam_assert` is enabled. - normalize(self:) -> self, - - ///Returns `self` normalized to length 1.0 if possible, else returns zero. - /// - ///In particular, if the input is zero (or very close to zero), or non-finite, - ///the result of this operation will be zero. - /// - ///See also [`Self::try_normalize()`]. - normalize_or_zero(self:) -> self, - - ///Returns whether `self` is length `1.0` or not. - /// - ///Uses a precision threshold of `1e-6`. - is_normalized(self:) -> Raw(bool), - - ///Returns the vector projection of `self` onto `rhs`. - /// - ///`rhs` must be of non-zero length. - /// - ///# Panics - /// - ///Will panic if `rhs` is zero length when `glam_assert` is enabled. - project_onto(self:self) -> self, - - ///Returns the vector rejection of `self` from `rhs`. - /// - ///The vector rejection is the vector perpendicular to the projection of `self` onto - ///`rhs`, in rhs words the result of `self - self.project_onto(rhs)`. - /// - ///`rhs` must be of non-zero length. - /// - ///# Panics - /// - ///Will panic if `rhs` has a length of zero when `glam_assert` is enabled. - reject_from(self:self) -> self, - - ///Returns the vector projection of `self` onto `rhs`. - /// - ///`rhs` must be normalized. - /// - ///# Panics - /// - ///Will panic if `rhs` is not normalized when `glam_assert` is enabled. - project_onto_normalized(self:self) -> self, - - ///Returns the vector rejection of `self` from `rhs`. - /// - ///The vector rejection is the vector perpendicular to the projection of `self` onto - ///`rhs`, in rhs words the result of `self - self.project_onto(rhs)`. - /// - ///`rhs` must be normalized. - /// - ///# Panics - /// - ///Will panic if `rhs` is not normalized when `glam_assert` is enabled. - reject_from_normalized(self:self) -> self, - - ///Returns a vector containing the nearest integer to a number for each element of `self`. - ///Round half-way cases away from 0.0. - round(self:) -> self, - - ///Returns a vector containing the largest integer less than or equal to a number for each - ///element of `self`. - floor(self:) -> self, - - ///Returns a vector containing the smallest integer greater than or equal to a number for - ///each element of `self`. - ceil(self:) -> self, - - ///Returns a vector containing the integer part each element of `self`. This means numbers are - ///always truncated towards zero. - trunc(self:) -> self, - - ///Returns a vector containing the fractional part of the vector, e.g. `self - - ///self.floor()`. - /// - ///Note that this is fast but not precise for large numbers. - fract(self:) -> self, - - ///Returns a vector containing `e^self` (the exponential function) for each element of - ///`self`. - exp(self:) -> self, - - ///Returns a vector containing each element of `self` raised to the power of `n`. - powf(self:Raw(f32)) -> self, - - ///Returns a vector containing the reciprocal `1.0/n` of each element of `self`. - recip(self:) -> self, - - ///Performs a linear interpolation between `self` and `rhs` based on the value `s`. - /// - ///When `s` is `0.0`, the result will be equal to `self`. When `s` is `1.0`, the result - ///will be equal to `rhs`. When `s` is outside of range `[0, 1]`, the result is linearly - ///extrapolated. - lerp(self:self,Raw(f32)) -> self, - - ///Returns true if the absolute difference of all elements between `self` and `rhs` is - ///less than or equal to `max_abs_diff`. - /// - ///This can be used to compare if two vectors contain similar elements. It works best when - ///comparing with a known value. The `max_abs_diff` that should be used used depends on - ///the values being compared against. - /// - ///For more see - ///[comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - abs_diff_eq(self:self,Raw(f32)) -> Raw(bool), - - ///Returns a vector with a length no less than `min` and no more than `max` - /// - ///# Panics - /// - ///Will panic if `min` is greater than `max` when `glam_assert` is enabled. - clamp_length(self:Raw(f32),Raw(f32)) -> self, - - ///Returns a vector with a length no more than `max` - clamp_length_max(self:Raw(f32)) -> self, - - ///Returns a vector with a length no less than `min` - clamp_length_min(self:Raw(f32)) -> self, - - ///Fused multiply-add. Computes `(self * a) + b` element-wise with only one rounding - ///error, yielding a more accurate result than an unfused multiply-add. - /// - ///Using `mul_add` *may* be more performant than an unfused multiply-add if the target - ///architecture has a dedicated fma CPU instruction. However, this is not always true, - ///and will be heavily dependant on designing algorithms with specific target hardware in - ///mind. - mul_add(self:self,self) -> self, - - ///Returns the angle (in radians) between two vectors. - /// - ///The inputs do not need to be unit vectors however they must be non-zero. - angle_between(self:self) -> Raw(f32), - - ///Returns some vector that is orthogonal to the given one. - /// - ///The input vector must be finite and non-zero. - /// - ///The output vector is not necessarily unit length. For that use - ///[`Self::any_orthonormal_vector()`] instead. - any_orthogonal_vector(&self:) -> self, - - ///Returns any unit vector that is orthogonal to the given one. - /// - ///The input vector must be unit length. - /// - ///# Panics - /// - ///Will panic if `self` is not normalized when `glam_assert` is enabled. - any_orthonormal_vector(&self:) -> self, - - ///Casts all elements of `self` to `f64`. - as_dvec3(&self:) -> Wrapped(DVec3), - - ///Casts all elements of `self` to `i32`. - as_ivec3(&self:) -> Wrapped(IVec3), - - ///Casts all elements of `self` to `u32`. - as_uvec3(&self:) -> Wrapped(UVec3), - - ) - + Fields - ( - x: Raw(f32), - y: Raw(f32), - z: Raw(f32), - ) - + BinOps - ( - self Add Raw(f32) -> Wrapped(Vec3), - self Add Wrapped(Vec3) -> Wrapped(Vec3), - self Add self -> Wrapped(Vec3), - self Sub self -> Wrapped(Vec3), - self Sub Wrapped(Vec3) -> Wrapped(Vec3), - self Sub Raw(f32) -> Wrapped(Vec3), - self Div Wrapped(Vec3) -> Wrapped(Vec3), - self Div self -> Wrapped(Vec3), - self Div Raw(f32) -> Wrapped(Vec3), - self Mul Raw(f32) -> Wrapped(Vec3), - self Mul self -> Wrapped(Vec3), - self Mul Wrapped(Vec3) -> Wrapped(Vec3), - self Rem Wrapped(Vec3) -> Wrapped(Vec3), - self Rem Raw(f32) -> Wrapped(Vec3), - self Rem self -> Wrapped(Vec3), - ) - + UnaryOps - ( - Neg self -> self - ) - lua impl - { - (MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}; - mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,f32)| {s.val_mut(|s| Ok(s[*idx] = val))?}; - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 3-dimensional vector. - /// - ///SIMD vector types are used for storage on supported platforms for better - ///performance than the [`Vec3`] type. - /// - ///It is possible to convert between [`Vec3`] and [`Vec3A`] types using [`From`] - ///or [`Into`] trait implementations. - /// - ///This type is 16 byte aligned. - glam::f32::Vec3A : - Clone + - Debug + - Methods - ( - ///Creates a new vector. - new(Raw(f32),Raw(f32),Raw(f32)) -> self, - - ///Creates a vector with all elements set to `v`. - splat(Raw(f32)) -> self, - - ///Creates a vector from the elements in `if_true` and `if_false`, selecting which to use - ///for each element of `self`. - /// - ///A true element in the mask uses the corresponding element from `if_true`, and false - ///uses the element from `if_false`. - select(Wrapped(BVec3A),self,self) -> self, - - ///Creates a 4D vector from `self` and the given `w` value. - extend(self:Raw(f32)) -> Wrapped(Vec4), - - ///Creates a 2D vector from the `x` and `y` elements of `self`, discarding `z`. - /// - ///Truncation may also be performed by using [`self.xy()`][crate::swizzles::Vec3Swizzles::xy()]. - truncate(self:) -> Wrapped(Vec2), - - ///Computes the dot product of `self` and `rhs`. - dot(self:self) -> Raw(f32), - - ///Returns a vector where every component is the dot product of `self` and `rhs`. - dot_into_vec(self:self) -> self, - - ///Computes the cross product of `self` and `rhs`. - cross(self:self) -> self, - - ///Returns a vector containing the minimum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.min(rhs.x), self.y.min(rhs.y), ..]`. - min(self:self) -> self, - - ///Returns a vector containing the maximum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.max(rhs.x), self.y.max(rhs.y), ..]`. - max(self:self) -> self, - - ///Component-wise clamping of values, similar to [`f32::clamp`]. - /// - ///Each element in `min` must be less-or-equal to the corresponding element in `max`. - /// - ///# Panics - /// - ///Will panic if `min` is greater than `max` when `glam_assert` is enabled. - clamp(self:self,self) -> self, - - ///Returns the horizontal minimum of `self`. - /// - ///In other words this computes `min(x, y, ..)`. - min_element(self:) -> Raw(f32), - - ///Returns the horizontal maximum of `self`. - /// - ///In other words this computes `max(x, y, ..)`. - max_element(self:) -> Raw(f32), - - ///Returns a vector mask containing the result of a `==` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all - ///elements. - cmpeq(self:self) -> Wrapped(BVec3A), - - ///Returns a vector mask containing the result of a `!=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all - ///elements. - cmpne(self:self) -> Wrapped(BVec3A), - - ///Returns a vector mask containing the result of a `>=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all - ///elements. - cmpge(self:self) -> Wrapped(BVec3A), - - ///Returns a vector mask containing the result of a `>` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all - ///elements. - cmpgt(self:self) -> Wrapped(BVec3A), - - ///Returns a vector mask containing the result of a `<=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all - ///elements. - cmple(self:self) -> Wrapped(BVec3A), - - ///Returns a vector mask containing the result of a `<` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all - ///elements. - cmplt(self:self) -> Wrapped(BVec3A), - - ///Returns a vector containing the absolute value of each element of `self`. - abs(self:) -> self, - - ///Returns a vector with elements representing the sign of `self`. - /// - ///- `1.0` if the number is positive, `+0.0` or `INFINITY` - ///- `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` - ///- `NAN` if the number is `NAN` - signum(self:) -> self, - - ///Returns a vector with signs of `rhs` and the magnitudes of `self`. - copysign(self:self) -> self, - - ///Returns a bitmask with the lowest 3 bits set to the sign bits from the elements of `self`. - /// - ///A negative element results in a `1` bit and a positive element in a `0` bit. Element `x` goes - ///into the first lowest bit, element `y` into the second, etc. - is_negative_bitmask(self:) -> Raw(u32), - - ///Returns `true` if, and only if, all elements are finite. If any element is either - ///`NaN`, positive or negative infinity, this will return `false`. - is_finite(self:) -> Raw(bool), - - ///Returns `true` if any elements are `NaN`. - is_nan(self:) -> Raw(bool), - - ///Performs `is_nan` on each element of self, returning a vector mask of the results. - /// - ///In other words, this computes `[x.is_nan(), y.is_nan(), z.is_nan(), w.is_nan()]`. - is_nan_mask(self:) -> Wrapped(BVec3A), - - ///Computes the length of `self`. - length(self:) -> Raw(f32), - - ///Computes the squared length of `self`. - /// - ///This is faster than `length()` as it avoids a square root operation. - length_squared(self:) -> Raw(f32), - - ///Computes `1.0 / length()`. - /// - ///For valid results, `self` must _not_ be of length zero. - length_recip(self:) -> Raw(f32), - - ///Computes the Euclidean distance between two points in space. - distance(self:self) -> Raw(f32), - - ///Compute the squared euclidean distance between two points in space. - distance_squared(self:self) -> Raw(f32), - - ///Returns the element-wise quotient of [Euclidean division] of `self` by `rhs`. - div_euclid(self:self) -> self, - - ///Returns the element-wise remainder of [Euclidean division] of `self` by `rhs`. - /// - ///[Euclidean division]: f32::rem_euclid - rem_euclid(self:self) -> self, - - ///Returns `self` normalized to length 1.0. - /// - ///For valid results, `self` must _not_ be of length zero, nor very close to zero. - /// - ///See also [`Self::try_normalize()`] and [`Self::normalize_or_zero()`]. - /// - ///Panics - /// - ///Will panic if `self` is zero length when `glam_assert` is enabled. - normalize(self:) -> self, - - ///Returns `self` normalized to length 1.0 if possible, else returns zero. - /// - ///In particular, if the input is zero (or very close to zero), or non-finite, - ///the result of this operation will be zero. - /// - ///See also [`Self::try_normalize()`]. - normalize_or_zero(self:) -> self, - - ///Returns whether `self` is length `1.0` or not. - /// - ///Uses a precision threshold of `1e-6`. - is_normalized(self:) -> Raw(bool), - - ///Returns the vector projection of `self` onto `rhs`. - /// - ///`rhs` must be of non-zero length. - /// - ///# Panics - /// - ///Will panic if `rhs` is zero length when `glam_assert` is enabled. - project_onto(self:self) -> self, - - ///Returns the vector rejection of `self` from `rhs`. - /// - ///The vector rejection is the vector perpendicular to the projection of `self` onto - ///`rhs`, in rhs words the result of `self - self.project_onto(rhs)`. - /// - ///`rhs` must be of non-zero length. - /// - ///# Panics - /// - ///Will panic if `rhs` has a length of zero when `glam_assert` is enabled. - reject_from(self:self) -> self, - - ///Returns the vector projection of `self` onto `rhs`. - /// - ///`rhs` must be normalized. - /// - ///# Panics - /// - ///Will panic if `rhs` is not normalized when `glam_assert` is enabled. - project_onto_normalized(self:self) -> self, - - ///Returns the vector rejection of `self` from `rhs`. - /// - ///The vector rejection is the vector perpendicular to the projection of `self` onto - ///`rhs`, in rhs words the result of `self - self.project_onto(rhs)`. - /// - ///`rhs` must be normalized. - /// - ///# Panics - /// - ///Will panic if `rhs` is not normalized when `glam_assert` is enabled. - reject_from_normalized(self:self) -> self, - - ///Returns a vector containing the nearest integer to a number for each element of `self`. - ///Round half-way cases away from 0.0. - round(self:) -> self, - - ///Returns a vector containing the largest integer less than or equal to a number for each - ///element of `self`. - floor(self:) -> self, - - ///Returns a vector containing the smallest integer greater than or equal to a number for - ///each element of `self`. - ceil(self:) -> self, - - ///Returns a vector containing the integer part each element of `self`. This means numbers are - ///always truncated towards zero. - trunc(self:) -> self, - - ///Returns a vector containing the fractional part of the vector, e.g. `self - - ///self.floor()`. - /// - ///Note that this is fast but not precise for large numbers. - fract(self:) -> self, - - ///Returns a vector containing `e^self` (the exponential function) for each element of - ///`self`. - exp(self:) -> self, - - ///Returns a vector containing each element of `self` raised to the power of `n`. - powf(self:Raw(f32)) -> self, - - ///Returns a vector containing the reciprocal `1.0/n` of each element of `self`. - recip(self:) -> self, - - ///Performs a linear interpolation between `self` and `rhs` based on the value `s`. - /// - ///When `s` is `0.0`, the result will be equal to `self`. When `s` is `1.0`, the result - ///will be equal to `rhs`. When `s` is outside of range `[0, 1]`, the result is linearly - ///extrapolated. - lerp(self:self,Raw(f32)) -> self, - - ///Returns true if the absolute difference of all elements between `self` and `rhs` is - ///less than or equal to `max_abs_diff`. - /// - ///This can be used to compare if two vectors contain similar elements. It works best when - ///comparing with a known value. The `max_abs_diff` that should be used used depends on - ///the values being compared against. - /// - ///For more see - ///[comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - abs_diff_eq(self:self,Raw(f32)) -> Raw(bool), - - ///Returns a vector with a length no less than `min` and no more than `max` - /// - ///# Panics - /// - ///Will panic if `min` is greater than `max` when `glam_assert` is enabled. - clamp_length(self:Raw(f32),Raw(f32)) -> self, - - ///Returns a vector with a length no more than `max` - clamp_length_max(self:Raw(f32)) -> self, - - ///Returns a vector with a length no less than `min` - clamp_length_min(self:Raw(f32)) -> self, - - ///Fused multiply-add. Computes `(self * a) + b` element-wise with only one rounding - ///error, yielding a more accurate result than an unfused multiply-add. - /// - ///Using `mul_add` *may* be more performant than an unfused multiply-add if the target - ///architecture has a dedicated fma CPU instruction. However, this is not always true, - ///and will be heavily dependant on designing algorithms with specific target hardware in - ///mind. - mul_add(self:self,self) -> self, - - ///Returns the angle (in radians) between two vectors. - /// - ///The inputs do not need to be unit vectors however they must be non-zero. - angle_between(self:self) -> Raw(f32), - - ///Returns some vector that is orthogonal to the given one. - /// - ///The input vector must be finite and non-zero. - /// - ///The output vector is not necessarily unit length. For that use - ///[`Self::any_orthonormal_vector()`] instead. - any_orthogonal_vector(&self:) -> self, - - ///Returns any unit vector that is orthogonal to the given one. - /// - ///The input vector must be unit length. - /// - ///# Panics - /// - ///Will panic if `self` is not normalized when `glam_assert` is enabled. - any_orthonormal_vector(&self:) -> self, - - ///Casts all elements of `self` to `f64`. - as_dvec3(&self:) -> Wrapped(DVec3), - - ///Casts all elements of `self` to `i32`. - as_ivec3(&self:) -> Wrapped(IVec3), - - ///Casts all elements of `self` to `u32`. - as_uvec3(&self:) -> Wrapped(UVec3), - - ) - + Fields - ( - ) - + BinOps - ( - self Add self -> Wrapped(Vec3A), - self Add Wrapped(Vec3A) -> Wrapped(Vec3A), - self Add Raw(f32) -> Wrapped(Vec3A), - self Sub Wrapped(Vec3A) -> Wrapped(Vec3A), - self Sub Raw(f32) -> Wrapped(Vec3A), - self Sub self -> Wrapped(Vec3A), - self Div Wrapped(Vec3A) -> Wrapped(Vec3A), - self Div Raw(f32) -> Wrapped(Vec3A), - self Div self -> Wrapped(Vec3A), - self Mul self -> Wrapped(Vec3A), - self Mul Raw(f32) -> Wrapped(Vec3A), - self Mul Wrapped(Vec3A) -> Wrapped(Vec3A), - self Rem Wrapped(Vec3A) -> Wrapped(Vec3A), - self Rem Raw(f32) -> Wrapped(Vec3A), - self Rem self -> Wrapped(Vec3A), - ) - + UnaryOps - ( - Neg self -> self - ) - lua impl - { - (MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}; - mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,f32)| {s.val_mut(|s| Ok(s[*idx] = val))?}; - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 4-dimensional vector. - /// - ///SIMD vector types are used for storage on supported platforms. - /// - ///This type is 16 byte aligned. - glam::f32::Vec4 : - Clone + - Debug + - Methods - ( - ///Creates a new vector. - new(Raw(f32),Raw(f32),Raw(f32),Raw(f32)) -> self, - - ///Creates a vector with all elements set to `v`. - splat(Raw(f32)) -> self, - - ///Creates a vector from the elements in `if_true` and `if_false`, selecting which to use - ///for each element of `self`. - /// - ///A true element in the mask uses the corresponding element from `if_true`, and false - ///uses the element from `if_false`. - select(Wrapped(BVec4A),self,self) -> self, - - ///Creates a 3D vector from the `x`, `y` and `z` elements of `self`, discarding `w`. - /// - ///Truncation to [`Vec3`] may also be performed by using [`self.xyz()`][crate::swizzles::Vec4Swizzles::xyz()]. - /// - ///To truncate to [`Vec3A`] use [`Vec3A::from()`]. - truncate(self:) -> Wrapped(Vec3), - - ///Computes the dot product of `self` and `rhs`. - dot(self:self) -> Raw(f32), - - ///Returns a vector where every component is the dot product of `self` and `rhs`. - dot_into_vec(self:self) -> self, - - ///Returns a vector containing the minimum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.min(rhs.x), self.y.min(rhs.y), ..]`. - min(self:self) -> self, - - ///Returns a vector containing the maximum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.max(rhs.x), self.y.max(rhs.y), ..]`. - max(self:self) -> self, - - ///Component-wise clamping of values, similar to [`f32::clamp`]. - /// - ///Each element in `min` must be less-or-equal to the corresponding element in `max`. - /// - ///# Panics - /// - ///Will panic if `min` is greater than `max` when `glam_assert` is enabled. - clamp(self:self,self) -> self, - - ///Returns the horizontal minimum of `self`. - /// - ///In other words this computes `min(x, y, ..)`. - min_element(self:) -> Raw(f32), - - ///Returns the horizontal maximum of `self`. - /// - ///In other words this computes `max(x, y, ..)`. - max_element(self:) -> Raw(f32), - - ///Returns a vector mask containing the result of a `==` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all - ///elements. - cmpeq(self:self) -> Wrapped(BVec4A), - - ///Returns a vector mask containing the result of a `!=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all - ///elements. - cmpne(self:self) -> Wrapped(BVec4A), - - ///Returns a vector mask containing the result of a `>=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all - ///elements. - cmpge(self:self) -> Wrapped(BVec4A), - - ///Returns a vector mask containing the result of a `>` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all - ///elements. - cmpgt(self:self) -> Wrapped(BVec4A), - - ///Returns a vector mask containing the result of a `<=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all - ///elements. - cmple(self:self) -> Wrapped(BVec4A), - - ///Returns a vector mask containing the result of a `<` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all - ///elements. - cmplt(self:self) -> Wrapped(BVec4A), - - ///Returns a vector containing the absolute value of each element of `self`. - abs(self:) -> self, - - ///Returns a vector with elements representing the sign of `self`. - /// - ///- `1.0` if the number is positive, `+0.0` or `INFINITY` - ///- `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` - ///- `NAN` if the number is `NAN` - signum(self:) -> self, - - ///Returns a vector with signs of `rhs` and the magnitudes of `self`. - copysign(self:self) -> self, - - ///Returns a bitmask with the lowest 4 bits set to the sign bits from the elements of `self`. - /// - ///A negative element results in a `1` bit and a positive element in a `0` bit. Element `x` goes - ///into the first lowest bit, element `y` into the second, etc. - is_negative_bitmask(self:) -> Raw(u32), - - ///Returns `true` if, and only if, all elements are finite. If any element is either - ///`NaN`, positive or negative infinity, this will return `false`. - is_finite(self:) -> Raw(bool), - - ///Returns `true` if any elements are `NaN`. - is_nan(self:) -> Raw(bool), - - ///Performs `is_nan` on each element of self, returning a vector mask of the results. - /// - ///In other words, this computes `[x.is_nan(), y.is_nan(), z.is_nan(), w.is_nan()]`. - is_nan_mask(self:) -> Wrapped(BVec4A), - - ///Computes the length of `self`. - length(self:) -> Raw(f32), - - ///Computes the squared length of `self`. - /// - ///This is faster than `length()` as it avoids a square root operation. - length_squared(self:) -> Raw(f32), - - ///Computes `1.0 / length()`. - /// - ///For valid results, `self` must _not_ be of length zero. - length_recip(self:) -> Raw(f32), - - ///Computes the Euclidean distance between two points in space. - distance(self:self) -> Raw(f32), - - ///Compute the squared euclidean distance between two points in space. - distance_squared(self:self) -> Raw(f32), - - ///Returns the element-wise quotient of [Euclidean division] of `self` by `rhs`. - div_euclid(self:self) -> self, - - ///Returns the element-wise remainder of [Euclidean division] of `self` by `rhs`. - /// - ///[Euclidean division]: f32::rem_euclid - rem_euclid(self:self) -> self, - - ///Returns `self` normalized to length 1.0. - /// - ///For valid results, `self` must _not_ be of length zero, nor very close to zero. - /// - ///See also [`Self::try_normalize()`] and [`Self::normalize_or_zero()`]. - /// - ///Panics - /// - ///Will panic if `self` is zero length when `glam_assert` is enabled. - normalize(self:) -> self, - - ///Returns `self` normalized to length 1.0 if possible, else returns zero. - /// - ///In particular, if the input is zero (or very close to zero), or non-finite, - ///the result of this operation will be zero. - /// - ///See also [`Self::try_normalize()`]. - normalize_or_zero(self:) -> self, - - ///Returns whether `self` is length `1.0` or not. - /// - ///Uses a precision threshold of `1e-6`. - is_normalized(self:) -> Raw(bool), - - ///Returns the vector projection of `self` onto `rhs`. - /// - ///`rhs` must be of non-zero length. - /// - ///# Panics - /// - ///Will panic if `rhs` is zero length when `glam_assert` is enabled. - project_onto(self:self) -> self, - - ///Returns the vector rejection of `self` from `rhs`. - /// - ///The vector rejection is the vector perpendicular to the projection of `self` onto - ///`rhs`, in rhs words the result of `self - self.project_onto(rhs)`. - /// - ///`rhs` must be of non-zero length. - /// - ///# Panics - /// - ///Will panic if `rhs` has a length of zero when `glam_assert` is enabled. - reject_from(self:self) -> self, - - ///Returns the vector projection of `self` onto `rhs`. - /// - ///`rhs` must be normalized. - /// - ///# Panics - /// - ///Will panic if `rhs` is not normalized when `glam_assert` is enabled. - project_onto_normalized(self:self) -> self, - - ///Returns the vector rejection of `self` from `rhs`. - /// - ///The vector rejection is the vector perpendicular to the projection of `self` onto - ///`rhs`, in rhs words the result of `self - self.project_onto(rhs)`. - /// - ///`rhs` must be normalized. - /// - ///# Panics - /// - ///Will panic if `rhs` is not normalized when `glam_assert` is enabled. - reject_from_normalized(self:self) -> self, - - ///Returns a vector containing the nearest integer to a number for each element of `self`. - ///Round half-way cases away from 0.0. - round(self:) -> self, - - ///Returns a vector containing the largest integer less than or equal to a number for each - ///element of `self`. - floor(self:) -> self, - - ///Returns a vector containing the smallest integer greater than or equal to a number for - ///each element of `self`. - ceil(self:) -> self, - - ///Returns a vector containing the integer part each element of `self`. This means numbers are - ///always truncated towards zero. - trunc(self:) -> self, - - ///Returns a vector containing the fractional part of the vector, e.g. `self - - ///self.floor()`. - /// - ///Note that this is fast but not precise for large numbers. - fract(self:) -> self, - - ///Returns a vector containing `e^self` (the exponential function) for each element of - ///`self`. - exp(self:) -> self, - - ///Returns a vector containing each element of `self` raised to the power of `n`. - powf(self:Raw(f32)) -> self, - - ///Returns a vector containing the reciprocal `1.0/n` of each element of `self`. - recip(self:) -> self, - - ///Performs a linear interpolation between `self` and `rhs` based on the value `s`. - /// - ///When `s` is `0.0`, the result will be equal to `self`. When `s` is `1.0`, the result - ///will be equal to `rhs`. When `s` is outside of range `[0, 1]`, the result is linearly - ///extrapolated. - lerp(self:self,Raw(f32)) -> self, - - ///Returns true if the absolute difference of all elements between `self` and `rhs` is - ///less than or equal to `max_abs_diff`. - /// - ///This can be used to compare if two vectors contain similar elements. It works best when - ///comparing with a known value. The `max_abs_diff` that should be used used depends on - ///the values being compared against. - /// - ///For more see - ///[comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - abs_diff_eq(self:self,Raw(f32)) -> Raw(bool), - - ///Returns a vector with a length no less than `min` and no more than `max` - /// - ///# Panics - /// - ///Will panic if `min` is greater than `max` when `glam_assert` is enabled. - clamp_length(self:Raw(f32),Raw(f32)) -> self, - - ///Returns a vector with a length no more than `max` - clamp_length_max(self:Raw(f32)) -> self, - - ///Returns a vector with a length no less than `min` - clamp_length_min(self:Raw(f32)) -> self, - - ///Fused multiply-add. Computes `(self * a) + b` element-wise with only one rounding - ///error, yielding a more accurate result than an unfused multiply-add. - /// - ///Using `mul_add` *may* be more performant than an unfused multiply-add if the target - ///architecture has a dedicated fma CPU instruction. However, this is not always true, - ///and will be heavily dependant on designing algorithms with specific target hardware in - ///mind. - mul_add(self:self,self) -> self, - - ///Casts all elements of `self` to `f64`. - as_dvec4(&self:) -> Wrapped(DVec4), - - ///Casts all elements of `self` to `i32`. - as_ivec4(&self:) -> Wrapped(IVec4), - - ///Casts all elements of `self` to `u32`. - as_uvec4(&self:) -> Wrapped(UVec4), - - ) - + Fields - ( - ) - + BinOps - ( - self Add Wrapped(Vec4) -> Wrapped(Vec4), - self Add self -> Wrapped(Vec4), - self Add Raw(f32) -> Wrapped(Vec4), - self Sub Raw(f32) -> Wrapped(Vec4), - self Sub self -> Wrapped(Vec4), - self Sub Wrapped(Vec4) -> Wrapped(Vec4), - self Div Raw(f32) -> Wrapped(Vec4), - self Div Wrapped(Vec4) -> Wrapped(Vec4), - self Div self -> Wrapped(Vec4), - self Mul self -> Wrapped(Vec4), - self Mul Raw(f32) -> Wrapped(Vec4), - self Mul Wrapped(Vec4) -> Wrapped(Vec4), - self Rem self -> Wrapped(Vec4), - self Rem Raw(f32) -> Wrapped(Vec4), - self Rem Wrapped(Vec4) -> Wrapped(Vec4), - ) - + UnaryOps - ( - Neg self -> self - ) - lua impl - { - (MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}; - mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,f32)| {s.val_mut(|s| Ok(s[*idx] = val))?}; - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 2-dimensional `bool` vector mask. - glam::bool::BVec2 : - Clone + - Debug + - Methods - ( - ///Creates a new vector mask. - new(Raw(bool),Raw(bool)) -> self, - - ///Creates a vector with all elements set to `v`. - splat(Raw(bool)) -> self, - - ///Returns a bitmask with the lowest 2 bits set from the elements of `self`. - /// - ///A true element results in a `1` bit and a false element in a `0` bit. Element `x` goes - ///into the first lowest bit, element `y` into the second, etc. - bitmask(self:) -> Raw(u32), - - ///Returns true if any of the elements are true, false otherwise. - any(self:) -> Raw(bool), - - ///Returns true if all the elements are true, false otherwise. - all(self:) -> Raw(bool), - - ///Tests the value at `index`. - /// - ///Panics if `index` is greater than 1. - test(&self:Raw(usize)) -> Raw(bool), - - ///Sets the element at `index`. - /// - ///Panics if `index` is greater than 1. - set(&mut self:Raw(usize),Raw(bool)), - - ) - + Fields - ( - x: Raw(bool), - y: Raw(bool), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 3-dimensional `bool` vector mask. - glam::bool::BVec3 : - Clone + - Debug + - Methods - ( - ///Creates a new vector mask. - new(Raw(bool),Raw(bool),Raw(bool)) -> self, - - ///Creates a vector with all elements set to `v`. - splat(Raw(bool)) -> self, - - ///Returns a bitmask with the lowest 3 bits set from the elements of `self`. - /// - ///A true element results in a `1` bit and a false element in a `0` bit. Element `x` goes - ///into the first lowest bit, element `y` into the second, etc. - bitmask(self:) -> Raw(u32), - - ///Returns true if any of the elements are true, false otherwise. - any(self:) -> Raw(bool), - - ///Returns true if all the elements are true, false otherwise. - all(self:) -> Raw(bool), - - ///Tests the value at `index`. - /// - ///Panics if `index` is greater than 2. - test(&self:Raw(usize)) -> Raw(bool), - - ///Sets the element at `index`. - /// - ///Panics if `index` is greater than 2. - set(&mut self:Raw(usize),Raw(bool)), - - ) - + Fields - ( - x: Raw(bool), - y: Raw(bool), - z: Raw(bool), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 4-dimensional `bool` vector mask. - glam::bool::BVec4 : - Clone + - Debug + - Methods - ( - ///Creates a new vector mask. - new(Raw(bool),Raw(bool),Raw(bool),Raw(bool)) -> self, - - ///Creates a vector with all elements set to `v`. - splat(Raw(bool)) -> self, - - ///Returns a bitmask with the lowest 4 bits set from the elements of `self`. - /// - ///A true element results in a `1` bit and a false element in a `0` bit. Element `x` goes - ///into the first lowest bit, element `y` into the second, etc. - bitmask(self:) -> Raw(u32), - - ///Returns true if any of the elements are true, false otherwise. - any(self:) -> Raw(bool), - - ///Returns true if all the elements are true, false otherwise. - all(self:) -> Raw(bool), - - ///Tests the value at `index`. - /// - ///Panics if `index` is greater than 3. - test(&self:Raw(usize)) -> Raw(bool), - - ///Sets the element at `index`. - /// - ///Panics if `index` is greater than 3. - set(&mut self:Raw(usize),Raw(bool)), - - ) - + Fields - ( - x: Raw(bool), - y: Raw(bool), - z: Raw(bool), - w: Raw(bool), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 3-dimensional SIMD vector mask. - /// - ///This type is 16 byte aligned. - glam::bool::BVec3A : - Clone + - Debug + - Methods - ( - ///Creates a new vector mask. - new(Raw(bool),Raw(bool),Raw(bool)) -> self, - - ///Creates a vector with all elements set to `v`. - splat(Raw(bool)) -> self, - - ///Returns a bitmask with the lowest 3 bits set from the elements of `self`. - /// - ///A true element results in a `1` bit and a false element in a `0` bit. Element `x` goes - ///into the first lowest bit, element `y` into the second, etc. - bitmask(self:) -> Raw(u32), - - ///Returns true if any of the elements are true, false otherwise. - any(self:) -> Raw(bool), - - ///Returns true if all the elements are true, false otherwise. - all(self:) -> Raw(bool), - - ///Tests the value at `index`. - /// - ///Panics if `index` is greater than 2. - test(&self:Raw(usize)) -> Raw(bool), - - ///Sets the element at `index`. - /// - ///Panics if `index` is greater than 2. - set(&mut self:Raw(usize),Raw(bool)), - - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 4-dimensional SIMD vector mask. - /// - ///This type is 16 byte aligned. - glam::bool::BVec4A : - Clone + - Debug + - Methods - ( - ///Creates a new vector mask. - new(Raw(bool),Raw(bool),Raw(bool),Raw(bool)) -> self, - - ///Creates a vector with all elements set to `v`. - splat(Raw(bool)) -> self, - - ///Returns a bitmask with the lowest 4 bits set from the elements of `self`. - /// - ///A true element results in a `1` bit and a false element in a `0` bit. Element `x` goes - ///into the first lowest bit, element `y` into the second, etc. - bitmask(self:) -> Raw(u32), - - ///Returns true if any of the elements are true, false otherwise. - any(self:) -> Raw(bool), - - ///Returns true if all the elements are true, false otherwise. - all(self:) -> Raw(bool), - - ///Tests the value at `index`. - /// - ///Panics if `index` is greater than 3. - test(&self:Raw(usize)) -> Raw(bool), - - ///Sets the element at `index`. - /// - ///Panics if `index` is greater than 3. - set(&mut self:Raw(usize),Raw(bool)), - - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 2-dimensional vector. - glam::f64::DVec2 : - Clone + - Debug + - Methods - ( - ///Creates a new vector. - new(Raw(f64),Raw(f64)) -> self, - - ///Creates a vector with all elements set to `v`. - splat(Raw(f64)) -> self, - - ///Creates a vector from the elements in `if_true` and `if_false`, selecting which to use - ///for each element of `self`. - /// - ///A true element in the mask uses the corresponding element from `if_true`, and false - ///uses the element from `if_false`. - select(Wrapped(BVec2),self,self) -> self, - - ///Creates a 3D vector from `self` and the given `z` value. - extend(self:Raw(f64)) -> Wrapped(DVec3), - - ///Computes the dot product of `self` and `rhs`. - dot(self:self) -> Raw(f64), - - ///Returns a vector where every component is the dot product of `self` and `rhs`. - dot_into_vec(self:self) -> self, - - ///Returns a vector containing the minimum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.min(rhs.x), self.y.min(rhs.y), ..]`. - min(self:self) -> self, - - ///Returns a vector containing the maximum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.max(rhs.x), self.y.max(rhs.y), ..]`. - max(self:self) -> self, - - ///Component-wise clamping of values, similar to [`f64::clamp`]. - /// - ///Each element in `min` must be less-or-equal to the corresponding element in `max`. - /// - ///# Panics - /// - ///Will panic if `min` is greater than `max` when `glam_assert` is enabled. - clamp(self:self,self) -> self, - - ///Returns the horizontal minimum of `self`. - /// - ///In other words this computes `min(x, y, ..)`. - min_element(self:) -> Raw(f64), - - ///Returns the horizontal maximum of `self`. - /// - ///In other words this computes `max(x, y, ..)`. - max_element(self:) -> Raw(f64), - - ///Returns a vector mask containing the result of a `==` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all - ///elements. - cmpeq(self:self) -> Wrapped(BVec2), - - ///Returns a vector mask containing the result of a `!=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all - ///elements. - cmpne(self:self) -> Wrapped(BVec2), - - ///Returns a vector mask containing the result of a `>=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all - ///elements. - cmpge(self:self) -> Wrapped(BVec2), - - ///Returns a vector mask containing the result of a `>` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all - ///elements. - cmpgt(self:self) -> Wrapped(BVec2), - - ///Returns a vector mask containing the result of a `<=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all - ///elements. - cmple(self:self) -> Wrapped(BVec2), - - ///Returns a vector mask containing the result of a `<` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all - ///elements. - cmplt(self:self) -> Wrapped(BVec2), - - ///Returns a vector containing the absolute value of each element of `self`. - abs(self:) -> self, - - ///Returns a vector with elements representing the sign of `self`. - /// - ///- `1.0` if the number is positive, `+0.0` or `INFINITY` - ///- `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` - ///- `NAN` if the number is `NAN` - signum(self:) -> self, - - ///Returns a vector with signs of `rhs` and the magnitudes of `self`. - copysign(self:self) -> self, - - ///Returns a bitmask with the lowest 2 bits set to the sign bits from the elements of `self`. - /// - ///A negative element results in a `1` bit and a positive element in a `0` bit. Element `x` goes - ///into the first lowest bit, element `y` into the second, etc. - is_negative_bitmask(self:) -> Raw(u32), - - ///Returns `true` if, and only if, all elements are finite. If any element is either - ///`NaN`, positive or negative infinity, this will return `false`. - is_finite(self:) -> Raw(bool), - - ///Returns `true` if any elements are `NaN`. - is_nan(self:) -> Raw(bool), - - ///Performs `is_nan` on each element of self, returning a vector mask of the results. - /// - ///In other words, this computes `[x.is_nan(), y.is_nan(), z.is_nan(), w.is_nan()]`. - is_nan_mask(self:) -> Wrapped(BVec2), - - ///Computes the length of `self`. - length(self:) -> Raw(f64), - - ///Computes the squared length of `self`. - /// - ///This is faster than `length()` as it avoids a square root operation. - length_squared(self:) -> Raw(f64), - - ///Computes `1.0 / length()`. - /// - ///For valid results, `self` must _not_ be of length zero. - length_recip(self:) -> Raw(f64), - - ///Computes the Euclidean distance between two points in space. - distance(self:self) -> Raw(f64), - - ///Compute the squared euclidean distance between two points in space. - distance_squared(self:self) -> Raw(f64), - - ///Returns the element-wise quotient of [Euclidean division] of `self` by `rhs`. - div_euclid(self:self) -> self, - - ///Returns the element-wise remainder of [Euclidean division] of `self` by `rhs`. - /// - ///[Euclidean division]: f64::rem_euclid - rem_euclid(self:self) -> self, - - ///Returns `self` normalized to length 1.0. - /// - ///For valid results, `self` must _not_ be of length zero, nor very close to zero. - /// - ///See also [`Self::try_normalize()`] and [`Self::normalize_or_zero()`]. - /// - ///Panics - /// - ///Will panic if `self` is zero length when `glam_assert` is enabled. - normalize(self:) -> self, - - ///Returns `self` normalized to length 1.0 if possible, else returns zero. - /// - ///In particular, if the input is zero (or very close to zero), or non-finite, - ///the result of this operation will be zero. - /// - ///See also [`Self::try_normalize()`]. - normalize_or_zero(self:) -> self, - - ///Returns whether `self` is length `1.0` or not. - /// - ///Uses a precision threshold of `1e-6`. - is_normalized(self:) -> Raw(bool), - - ///Returns the vector projection of `self` onto `rhs`. - /// - ///`rhs` must be of non-zero length. - /// - ///# Panics - /// - ///Will panic if `rhs` is zero length when `glam_assert` is enabled. - project_onto(self:self) -> self, - - ///Returns the vector rejection of `self` from `rhs`. - /// - ///The vector rejection is the vector perpendicular to the projection of `self` onto - ///`rhs`, in rhs words the result of `self - self.project_onto(rhs)`. - /// - ///`rhs` must be of non-zero length. - /// - ///# Panics - /// - ///Will panic if `rhs` has a length of zero when `glam_assert` is enabled. - reject_from(self:self) -> self, - - ///Returns the vector projection of `self` onto `rhs`. - /// - ///`rhs` must be normalized. - /// - ///# Panics - /// - ///Will panic if `rhs` is not normalized when `glam_assert` is enabled. - project_onto_normalized(self:self) -> self, - - ///Returns the vector rejection of `self` from `rhs`. - /// - ///The vector rejection is the vector perpendicular to the projection of `self` onto - ///`rhs`, in rhs words the result of `self - self.project_onto(rhs)`. - /// - ///`rhs` must be normalized. - /// - ///# Panics - /// - ///Will panic if `rhs` is not normalized when `glam_assert` is enabled. - reject_from_normalized(self:self) -> self, - - ///Returns a vector containing the nearest integer to a number for each element of `self`. - ///Round half-way cases away from 0.0. - round(self:) -> self, - - ///Returns a vector containing the largest integer less than or equal to a number for each - ///element of `self`. - floor(self:) -> self, - - ///Returns a vector containing the smallest integer greater than or equal to a number for - ///each element of `self`. - ceil(self:) -> self, - - ///Returns a vector containing the integer part each element of `self`. This means numbers are - ///always truncated towards zero. - trunc(self:) -> self, - - ///Returns a vector containing the fractional part of the vector, e.g. `self - - ///self.floor()`. - /// - ///Note that this is fast but not precise for large numbers. - fract(self:) -> self, - - ///Returns a vector containing `e^self` (the exponential function) for each element of - ///`self`. - exp(self:) -> self, - - ///Returns a vector containing each element of `self` raised to the power of `n`. - powf(self:Raw(f64)) -> self, - - ///Returns a vector containing the reciprocal `1.0/n` of each element of `self`. - recip(self:) -> self, - - ///Performs a linear interpolation between `self` and `rhs` based on the value `s`. - /// - ///When `s` is `0.0`, the result will be equal to `self`. When `s` is `1.0`, the result - ///will be equal to `rhs`. When `s` is outside of range `[0, 1]`, the result is linearly - ///extrapolated. - lerp(self:self,Raw(f64)) -> self, - - ///Returns true if the absolute difference of all elements between `self` and `rhs` is - ///less than or equal to `max_abs_diff`. - /// - ///This can be used to compare if two vectors contain similar elements. It works best when - ///comparing with a known value. The `max_abs_diff` that should be used used depends on - ///the values being compared against. - /// - ///For more see - ///[comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - abs_diff_eq(self:self,Raw(f64)) -> Raw(bool), - - ///Returns a vector with a length no less than `min` and no more than `max` - /// - ///# Panics - /// - ///Will panic if `min` is greater than `max` when `glam_assert` is enabled. - clamp_length(self:Raw(f64),Raw(f64)) -> self, - - ///Returns a vector with a length no more than `max` - clamp_length_max(self:Raw(f64)) -> self, - - ///Returns a vector with a length no less than `min` - clamp_length_min(self:Raw(f64)) -> self, - - ///Fused multiply-add. Computes `(self * a) + b` element-wise with only one rounding - ///error, yielding a more accurate result than an unfused multiply-add. - /// - ///Using `mul_add` *may* be more performant than an unfused multiply-add if the target - ///architecture has a dedicated fma CPU instruction. However, this is not always true, - ///and will be heavily dependant on designing algorithms with specific target hardware in - ///mind. - mul_add(self:self,self) -> self, - - ///Creates a 2D vector containing `[angle.cos(), angle.sin()]`. This can be used in - ///conjunction with the [`rotate()`][Self::rotate()] method, e.g. - ///`DVec2::from_angle(PI).rotate(DVec2::Y)` will create the vector `[-1, 0]` - ///and rotate [`DVec2::Y`] around it returning `-DVec2::Y`. - from_angle(Raw(f64)) -> self, - - ///Returns the angle (in radians) of this vector in the range `[-π, +π]`. - /// - ///The input does not need to be a unit vector however it must be non-zero. - to_angle(self:) -> Raw(f64), - - ///Returns the angle (in radians) between `self` and `rhs` in the range `[-π, +π]`. - /// - ///The inputs do not need to be unit vectors however they must be non-zero. - angle_between(self:self) -> Raw(f64), - - ///Returns a vector that is equal to `self` rotated by 90 degrees. - perp(self:) -> self, - - ///The perpendicular dot product of `self` and `rhs`. - ///Also known as the wedge product, 2D cross product, and determinant. - perp_dot(self:self) -> Raw(f64), - - ///Returns `rhs` rotated by the angle of `self`. If `self` is normalized, - ///then this just rotation. This is what you usually want. Otherwise, - ///it will be like a rotation with a multiplication by `self`'s length. - rotate(self:self) -> self, - - ///Casts all elements of `self` to `f32`. - as_vec2(&self:) -> Wrapped(Vec2), - - ///Casts all elements of `self` to `i32`. - as_ivec2(&self:) -> Wrapped(IVec2), - - ///Casts all elements of `self` to `u32`. - as_uvec2(&self:) -> Wrapped(UVec2), - - ) - + Fields - ( - x: Raw(f64), - y: Raw(f64), - ) - + BinOps - ( - self Add self -> Wrapped(DVec2), - self Add Raw(f64) -> Wrapped(DVec2), - self Add Wrapped(DVec2) -> Wrapped(DVec2), - self Sub Raw(f64) -> Wrapped(DVec2), - self Sub Wrapped(DVec2) -> Wrapped(DVec2), - self Sub self -> Wrapped(DVec2), - self Div Raw(f64) -> Wrapped(DVec2), - self Div Wrapped(DVec2) -> Wrapped(DVec2), - self Div self -> Wrapped(DVec2), - self Mul Raw(f64) -> Wrapped(DVec2), - self Mul self -> Wrapped(DVec2), - self Mul Wrapped(DVec2) -> Wrapped(DVec2), - self Rem self -> Wrapped(DVec2), - self Rem Raw(f64) -> Wrapped(DVec2), - self Rem Wrapped(DVec2) -> Wrapped(DVec2), - ) - + UnaryOps - ( - Neg self -> self - ) - lua impl - { - (MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}; - mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,f64)| {s.val_mut(|s| Ok(s[*idx] = val))?}; - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 3-dimensional vector. - glam::f64::DVec3 : - Clone + - Debug + - Methods - ( - ///Creates a new vector. - new(Raw(f64),Raw(f64),Raw(f64)) -> self, - - ///Creates a vector with all elements set to `v`. - splat(Raw(f64)) -> self, - - ///Creates a vector from the elements in `if_true` and `if_false`, selecting which to use - ///for each element of `self`. - /// - ///A true element in the mask uses the corresponding element from `if_true`, and false - ///uses the element from `if_false`. - select(Wrapped(BVec3),self,self) -> self, - - ///Creates a 4D vector from `self` and the given `w` value. - extend(self:Raw(f64)) -> Wrapped(DVec4), - - ///Creates a 2D vector from the `x` and `y` elements of `self`, discarding `z`. - /// - ///Truncation may also be performed by using [`self.xy()`][crate::swizzles::Vec3Swizzles::xy()]. - truncate(self:) -> Wrapped(DVec2), - - ///Computes the dot product of `self` and `rhs`. - dot(self:self) -> Raw(f64), - - ///Returns a vector where every component is the dot product of `self` and `rhs`. - dot_into_vec(self:self) -> self, - - ///Computes the cross product of `self` and `rhs`. - cross(self:self) -> self, - - ///Returns a vector containing the minimum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.min(rhs.x), self.y.min(rhs.y), ..]`. - min(self:self) -> self, - - ///Returns a vector containing the maximum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.max(rhs.x), self.y.max(rhs.y), ..]`. - max(self:self) -> self, - - ///Component-wise clamping of values, similar to [`f64::clamp`]. - /// - ///Each element in `min` must be less-or-equal to the corresponding element in `max`. - /// - ///# Panics - /// - ///Will panic if `min` is greater than `max` when `glam_assert` is enabled. - clamp(self:self,self) -> self, - - ///Returns the horizontal minimum of `self`. - /// - ///In other words this computes `min(x, y, ..)`. - min_element(self:) -> Raw(f64), - - ///Returns the horizontal maximum of `self`. - /// - ///In other words this computes `max(x, y, ..)`. - max_element(self:) -> Raw(f64), - - ///Returns a vector mask containing the result of a `==` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all - ///elements. - cmpeq(self:self) -> Wrapped(BVec3), - - ///Returns a vector mask containing the result of a `!=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all - ///elements. - cmpne(self:self) -> Wrapped(BVec3), - - ///Returns a vector mask containing the result of a `>=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all - ///elements. - cmpge(self:self) -> Wrapped(BVec3), - - ///Returns a vector mask containing the result of a `>` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all - ///elements. - cmpgt(self:self) -> Wrapped(BVec3), - - ///Returns a vector mask containing the result of a `<=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all - ///elements. - cmple(self:self) -> Wrapped(BVec3), - - ///Returns a vector mask containing the result of a `<` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all - ///elements. - cmplt(self:self) -> Wrapped(BVec3), - - ///Returns a vector containing the absolute value of each element of `self`. - abs(self:) -> self, - - ///Returns a vector with elements representing the sign of `self`. - /// - ///- `1.0` if the number is positive, `+0.0` or `INFINITY` - ///- `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` - ///- `NAN` if the number is `NAN` - signum(self:) -> self, - - ///Returns a vector with signs of `rhs` and the magnitudes of `self`. - copysign(self:self) -> self, - - ///Returns a bitmask with the lowest 3 bits set to the sign bits from the elements of `self`. - /// - ///A negative element results in a `1` bit and a positive element in a `0` bit. Element `x` goes - ///into the first lowest bit, element `y` into the second, etc. - is_negative_bitmask(self:) -> Raw(u32), - - ///Returns `true` if, and only if, all elements are finite. If any element is either - ///`NaN`, positive or negative infinity, this will return `false`. - is_finite(self:) -> Raw(bool), - - ///Returns `true` if any elements are `NaN`. - is_nan(self:) -> Raw(bool), - - ///Performs `is_nan` on each element of self, returning a vector mask of the results. - /// - ///In other words, this computes `[x.is_nan(), y.is_nan(), z.is_nan(), w.is_nan()]`. - is_nan_mask(self:) -> Wrapped(BVec3), - - ///Computes the length of `self`. - length(self:) -> Raw(f64), - - ///Computes the squared length of `self`. - /// - ///This is faster than `length()` as it avoids a square root operation. - length_squared(self:) -> Raw(f64), - - ///Computes `1.0 / length()`. - /// - ///For valid results, `self` must _not_ be of length zero. - length_recip(self:) -> Raw(f64), - - ///Computes the Euclidean distance between two points in space. - distance(self:self) -> Raw(f64), - - ///Compute the squared euclidean distance between two points in space. - distance_squared(self:self) -> Raw(f64), - - ///Returns the element-wise quotient of [Euclidean division] of `self` by `rhs`. - div_euclid(self:self) -> self, - - ///Returns the element-wise remainder of [Euclidean division] of `self` by `rhs`. - /// - ///[Euclidean division]: f64::rem_euclid - rem_euclid(self:self) -> self, - - ///Returns `self` normalized to length 1.0. - /// - ///For valid results, `self` must _not_ be of length zero, nor very close to zero. - /// - ///See also [`Self::try_normalize()`] and [`Self::normalize_or_zero()`]. - /// - ///Panics - /// - ///Will panic if `self` is zero length when `glam_assert` is enabled. - normalize(self:) -> self, - - ///Returns `self` normalized to length 1.0 if possible, else returns zero. - /// - ///In particular, if the input is zero (or very close to zero), or non-finite, - ///the result of this operation will be zero. - /// - ///See also [`Self::try_normalize()`]. - normalize_or_zero(self:) -> self, - - ///Returns whether `self` is length `1.0` or not. - /// - ///Uses a precision threshold of `1e-6`. - is_normalized(self:) -> Raw(bool), - - ///Returns the vector projection of `self` onto `rhs`. - /// - ///`rhs` must be of non-zero length. - /// - ///# Panics - /// - ///Will panic if `rhs` is zero length when `glam_assert` is enabled. - project_onto(self:self) -> self, - - ///Returns the vector rejection of `self` from `rhs`. - /// - ///The vector rejection is the vector perpendicular to the projection of `self` onto - ///`rhs`, in rhs words the result of `self - self.project_onto(rhs)`. - /// - ///`rhs` must be of non-zero length. - /// - ///# Panics - /// - ///Will panic if `rhs` has a length of zero when `glam_assert` is enabled. - reject_from(self:self) -> self, - - ///Returns the vector projection of `self` onto `rhs`. - /// - ///`rhs` must be normalized. - /// - ///# Panics - /// - ///Will panic if `rhs` is not normalized when `glam_assert` is enabled. - project_onto_normalized(self:self) -> self, - - ///Returns the vector rejection of `self` from `rhs`. - /// - ///The vector rejection is the vector perpendicular to the projection of `self` onto - ///`rhs`, in rhs words the result of `self - self.project_onto(rhs)`. - /// - ///`rhs` must be normalized. - /// - ///# Panics - /// - ///Will panic if `rhs` is not normalized when `glam_assert` is enabled. - reject_from_normalized(self:self) -> self, - - ///Returns a vector containing the nearest integer to a number for each element of `self`. - ///Round half-way cases away from 0.0. - round(self:) -> self, - - ///Returns a vector containing the largest integer less than or equal to a number for each - ///element of `self`. - floor(self:) -> self, - - ///Returns a vector containing the smallest integer greater than or equal to a number for - ///each element of `self`. - ceil(self:) -> self, - - ///Returns a vector containing the integer part each element of `self`. This means numbers are - ///always truncated towards zero. - trunc(self:) -> self, - - ///Returns a vector containing the fractional part of the vector, e.g. `self - - ///self.floor()`. - /// - ///Note that this is fast but not precise for large numbers. - fract(self:) -> self, - - ///Returns a vector containing `e^self` (the exponential function) for each element of - ///`self`. - exp(self:) -> self, - - ///Returns a vector containing each element of `self` raised to the power of `n`. - powf(self:Raw(f64)) -> self, - - ///Returns a vector containing the reciprocal `1.0/n` of each element of `self`. - recip(self:) -> self, - - ///Performs a linear interpolation between `self` and `rhs` based on the value `s`. - /// - ///When `s` is `0.0`, the result will be equal to `self`. When `s` is `1.0`, the result - ///will be equal to `rhs`. When `s` is outside of range `[0, 1]`, the result is linearly - ///extrapolated. - lerp(self:self,Raw(f64)) -> self, - - ///Returns true if the absolute difference of all elements between `self` and `rhs` is - ///less than or equal to `max_abs_diff`. - /// - ///This can be used to compare if two vectors contain similar elements. It works best when - ///comparing with a known value. The `max_abs_diff` that should be used used depends on - ///the values being compared against. - /// - ///For more see - ///[comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - abs_diff_eq(self:self,Raw(f64)) -> Raw(bool), - - ///Returns a vector with a length no less than `min` and no more than `max` - /// - ///# Panics - /// - ///Will panic if `min` is greater than `max` when `glam_assert` is enabled. - clamp_length(self:Raw(f64),Raw(f64)) -> self, - - ///Returns a vector with a length no more than `max` - clamp_length_max(self:Raw(f64)) -> self, - - ///Returns a vector with a length no less than `min` - clamp_length_min(self:Raw(f64)) -> self, - - ///Fused multiply-add. Computes `(self * a) + b` element-wise with only one rounding - ///error, yielding a more accurate result than an unfused multiply-add. - /// - ///Using `mul_add` *may* be more performant than an unfused multiply-add if the target - ///architecture has a dedicated fma CPU instruction. However, this is not always true, - ///and will be heavily dependant on designing algorithms with specific target hardware in - ///mind. - mul_add(self:self,self) -> self, - - ///Returns the angle (in radians) between two vectors. - /// - ///The inputs do not need to be unit vectors however they must be non-zero. - angle_between(self:self) -> Raw(f64), - - ///Returns some vector that is orthogonal to the given one. - /// - ///The input vector must be finite and non-zero. - /// - ///The output vector is not necessarily unit length. For that use - ///[`Self::any_orthonormal_vector()`] instead. - any_orthogonal_vector(&self:) -> self, - - ///Returns any unit vector that is orthogonal to the given one. - /// - ///The input vector must be unit length. - /// - ///# Panics - /// - ///Will panic if `self` is not normalized when `glam_assert` is enabled. - any_orthonormal_vector(&self:) -> self, - - ///Casts all elements of `self` to `f32`. - as_vec3(&self:) -> Wrapped(Vec3), - - ///Casts all elements of `self` to `f32`. - as_vec3a(&self:) -> Wrapped(Vec3A), - - ///Casts all elements of `self` to `i32`. - as_ivec3(&self:) -> Wrapped(IVec3), - - ///Casts all elements of `self` to `u32`. - as_uvec3(&self:) -> Wrapped(UVec3), - - ) - + Fields - ( - x: Raw(f64), - y: Raw(f64), - z: Raw(f64), - ) - + BinOps - ( - self Add Raw(f64) -> Wrapped(DVec3), - self Add Wrapped(DVec3) -> Wrapped(DVec3), - self Add self -> Wrapped(DVec3), - self Sub Wrapped(DVec3) -> Wrapped(DVec3), - self Sub Raw(f64) -> Wrapped(DVec3), - self Sub self -> Wrapped(DVec3), - self Div self -> Wrapped(DVec3), - self Div Wrapped(DVec3) -> Wrapped(DVec3), - self Div Raw(f64) -> Wrapped(DVec3), - self Mul self -> Wrapped(DVec3), - self Mul Wrapped(DVec3) -> Wrapped(DVec3), - self Mul Raw(f64) -> Wrapped(DVec3), - self Rem self -> Wrapped(DVec3), - self Rem Raw(f64) -> Wrapped(DVec3), - self Rem Wrapped(DVec3) -> Wrapped(DVec3), - ) - + UnaryOps - ( - Neg self -> self - ) - lua impl - { - (MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}; - mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,f64)| {s.val_mut(|s| Ok(s[*idx] = val))?}; - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 4-dimensional vector. - glam::f64::DVec4 : - Clone + - Debug + - Methods - ( - ///Creates a new vector. - new(Raw(f64),Raw(f64),Raw(f64),Raw(f64)) -> self, - - ///Creates a vector with all elements set to `v`. - splat(Raw(f64)) -> self, - - ///Creates a vector from the elements in `if_true` and `if_false`, selecting which to use - ///for each element of `self`. - /// - ///A true element in the mask uses the corresponding element from `if_true`, and false - ///uses the element from `if_false`. - select(Wrapped(BVec4),self,self) -> self, - - ///Creates a 3D vector from the `x`, `y` and `z` elements of `self`, discarding `w`. - /// - ///Truncation to [`DVec3`] may also be performed by using [`self.xyz()`][crate::swizzles::Vec4Swizzles::xyz()]. - truncate(self:) -> Wrapped(DVec3), - - ///Computes the dot product of `self` and `rhs`. - dot(self:self) -> Raw(f64), - - ///Returns a vector where every component is the dot product of `self` and `rhs`. - dot_into_vec(self:self) -> self, - - ///Returns a vector containing the minimum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.min(rhs.x), self.y.min(rhs.y), ..]`. - min(self:self) -> self, - - ///Returns a vector containing the maximum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.max(rhs.x), self.y.max(rhs.y), ..]`. - max(self:self) -> self, - - ///Component-wise clamping of values, similar to [`f64::clamp`]. - /// - ///Each element in `min` must be less-or-equal to the corresponding element in `max`. - /// - ///# Panics - /// - ///Will panic if `min` is greater than `max` when `glam_assert` is enabled. - clamp(self:self,self) -> self, - - ///Returns the horizontal minimum of `self`. - /// - ///In other words this computes `min(x, y, ..)`. - min_element(self:) -> Raw(f64), - - ///Returns the horizontal maximum of `self`. - /// - ///In other words this computes `max(x, y, ..)`. - max_element(self:) -> Raw(f64), - - ///Returns a vector mask containing the result of a `==` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all - ///elements. - cmpeq(self:self) -> Wrapped(BVec4), - - ///Returns a vector mask containing the result of a `!=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all - ///elements. - cmpne(self:self) -> Wrapped(BVec4), - - ///Returns a vector mask containing the result of a `>=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all - ///elements. - cmpge(self:self) -> Wrapped(BVec4), - - ///Returns a vector mask containing the result of a `>` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all - ///elements. - cmpgt(self:self) -> Wrapped(BVec4), - - ///Returns a vector mask containing the result of a `<=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all - ///elements. - cmple(self:self) -> Wrapped(BVec4), - - ///Returns a vector mask containing the result of a `<` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all - ///elements. - cmplt(self:self) -> Wrapped(BVec4), - - ///Returns a vector containing the absolute value of each element of `self`. - abs(self:) -> self, - - ///Returns a vector with elements representing the sign of `self`. - /// - ///- `1.0` if the number is positive, `+0.0` or `INFINITY` - ///- `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` - ///- `NAN` if the number is `NAN` - signum(self:) -> self, - - ///Returns a vector with signs of `rhs` and the magnitudes of `self`. - copysign(self:self) -> self, - - ///Returns a bitmask with the lowest 4 bits set to the sign bits from the elements of `self`. - /// - ///A negative element results in a `1` bit and a positive element in a `0` bit. Element `x` goes - ///into the first lowest bit, element `y` into the second, etc. - is_negative_bitmask(self:) -> Raw(u32), - - ///Returns `true` if, and only if, all elements are finite. If any element is either - ///`NaN`, positive or negative infinity, this will return `false`. - is_finite(self:) -> Raw(bool), - - ///Returns `true` if any elements are `NaN`. - is_nan(self:) -> Raw(bool), - - ///Performs `is_nan` on each element of self, returning a vector mask of the results. - /// - ///In other words, this computes `[x.is_nan(), y.is_nan(), z.is_nan(), w.is_nan()]`. - is_nan_mask(self:) -> Wrapped(BVec4), - - ///Computes the length of `self`. - length(self:) -> Raw(f64), - - ///Computes the squared length of `self`. - /// - ///This is faster than `length()` as it avoids a square root operation. - length_squared(self:) -> Raw(f64), - - ///Computes `1.0 / length()`. - /// - ///For valid results, `self` must _not_ be of length zero. - length_recip(self:) -> Raw(f64), - - ///Computes the Euclidean distance between two points in space. - distance(self:self) -> Raw(f64), - - ///Compute the squared euclidean distance between two points in space. - distance_squared(self:self) -> Raw(f64), - - ///Returns the element-wise quotient of [Euclidean division] of `self` by `rhs`. - div_euclid(self:self) -> self, - - ///Returns the element-wise remainder of [Euclidean division] of `self` by `rhs`. - /// - ///[Euclidean division]: f64::rem_euclid - rem_euclid(self:self) -> self, - - ///Returns `self` normalized to length 1.0. - /// - ///For valid results, `self` must _not_ be of length zero, nor very close to zero. - /// - ///See also [`Self::try_normalize()`] and [`Self::normalize_or_zero()`]. - /// - ///Panics - /// - ///Will panic if `self` is zero length when `glam_assert` is enabled. - normalize(self:) -> self, - - ///Returns `self` normalized to length 1.0 if possible, else returns zero. - /// - ///In particular, if the input is zero (or very close to zero), or non-finite, - ///the result of this operation will be zero. - /// - ///See also [`Self::try_normalize()`]. - normalize_or_zero(self:) -> self, - - ///Returns whether `self` is length `1.0` or not. - /// - ///Uses a precision threshold of `1e-6`. - is_normalized(self:) -> Raw(bool), - - ///Returns the vector projection of `self` onto `rhs`. - /// - ///`rhs` must be of non-zero length. - /// - ///# Panics - /// - ///Will panic if `rhs` is zero length when `glam_assert` is enabled. - project_onto(self:self) -> self, - - ///Returns the vector rejection of `self` from `rhs`. - /// - ///The vector rejection is the vector perpendicular to the projection of `self` onto - ///`rhs`, in rhs words the result of `self - self.project_onto(rhs)`. - /// - ///`rhs` must be of non-zero length. - /// - ///# Panics - /// - ///Will panic if `rhs` has a length of zero when `glam_assert` is enabled. - reject_from(self:self) -> self, - - ///Returns the vector projection of `self` onto `rhs`. - /// - ///`rhs` must be normalized. - /// - ///# Panics - /// - ///Will panic if `rhs` is not normalized when `glam_assert` is enabled. - project_onto_normalized(self:self) -> self, - - ///Returns the vector rejection of `self` from `rhs`. - /// - ///The vector rejection is the vector perpendicular to the projection of `self` onto - ///`rhs`, in rhs words the result of `self - self.project_onto(rhs)`. - /// - ///`rhs` must be normalized. - /// - ///# Panics - /// - ///Will panic if `rhs` is not normalized when `glam_assert` is enabled. - reject_from_normalized(self:self) -> self, - - ///Returns a vector containing the nearest integer to a number for each element of `self`. - ///Round half-way cases away from 0.0. - round(self:) -> self, - - ///Returns a vector containing the largest integer less than or equal to a number for each - ///element of `self`. - floor(self:) -> self, - - ///Returns a vector containing the smallest integer greater than or equal to a number for - ///each element of `self`. - ceil(self:) -> self, - - ///Returns a vector containing the integer part each element of `self`. This means numbers are - ///always truncated towards zero. - trunc(self:) -> self, - - ///Returns a vector containing the fractional part of the vector, e.g. `self - - ///self.floor()`. - /// - ///Note that this is fast but not precise for large numbers. - fract(self:) -> self, - - ///Returns a vector containing `e^self` (the exponential function) for each element of - ///`self`. - exp(self:) -> self, - - ///Returns a vector containing each element of `self` raised to the power of `n`. - powf(self:Raw(f64)) -> self, - - ///Returns a vector containing the reciprocal `1.0/n` of each element of `self`. - recip(self:) -> self, - - ///Performs a linear interpolation between `self` and `rhs` based on the value `s`. - /// - ///When `s` is `0.0`, the result will be equal to `self`. When `s` is `1.0`, the result - ///will be equal to `rhs`. When `s` is outside of range `[0, 1]`, the result is linearly - ///extrapolated. - lerp(self:self,Raw(f64)) -> self, - - ///Returns true if the absolute difference of all elements between `self` and `rhs` is - ///less than or equal to `max_abs_diff`. - /// - ///This can be used to compare if two vectors contain similar elements. It works best when - ///comparing with a known value. The `max_abs_diff` that should be used used depends on - ///the values being compared against. - /// - ///For more see - ///[comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - abs_diff_eq(self:self,Raw(f64)) -> Raw(bool), - - ///Returns a vector with a length no less than `min` and no more than `max` - /// - ///# Panics - /// - ///Will panic if `min` is greater than `max` when `glam_assert` is enabled. - clamp_length(self:Raw(f64),Raw(f64)) -> self, - - ///Returns a vector with a length no more than `max` - clamp_length_max(self:Raw(f64)) -> self, - - ///Returns a vector with a length no less than `min` - clamp_length_min(self:Raw(f64)) -> self, - - ///Fused multiply-add. Computes `(self * a) + b` element-wise with only one rounding - ///error, yielding a more accurate result than an unfused multiply-add. - /// - ///Using `mul_add` *may* be more performant than an unfused multiply-add if the target - ///architecture has a dedicated fma CPU instruction. However, this is not always true, - ///and will be heavily dependant on designing algorithms with specific target hardware in - ///mind. - mul_add(self:self,self) -> self, - - ///Casts all elements of `self` to `f32`. - as_vec4(&self:) -> Wrapped(Vec4), - - ///Casts all elements of `self` to `i32`. - as_ivec4(&self:) -> Wrapped(IVec4), - - ///Casts all elements of `self` to `u32`. - as_uvec4(&self:) -> Wrapped(UVec4), - - ) - + Fields - ( - x: Raw(f64), - y: Raw(f64), - z: Raw(f64), - w: Raw(f64), - ) - + BinOps - ( - self Add Raw(f64) -> Wrapped(DVec4), - self Add Wrapped(DVec4) -> Wrapped(DVec4), - self Add self -> Wrapped(DVec4), - self Sub Wrapped(DVec4) -> Wrapped(DVec4), - self Sub self -> Wrapped(DVec4), - self Sub Raw(f64) -> Wrapped(DVec4), - self Div Wrapped(DVec4) -> Wrapped(DVec4), - self Div Raw(f64) -> Wrapped(DVec4), - self Div self -> Wrapped(DVec4), - self Mul Wrapped(DVec4) -> Wrapped(DVec4), - self Mul Raw(f64) -> Wrapped(DVec4), - self Mul self -> Wrapped(DVec4), - self Rem self -> Wrapped(DVec4), - self Rem Raw(f64) -> Wrapped(DVec4), - self Rem Wrapped(DVec4) -> Wrapped(DVec4), - ) - + UnaryOps - ( - Neg self -> self - ) - lua impl - { - (MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}; - mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,f64)| {s.val_mut(|s| Ok(s[*idx] = val))?}; - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 2-dimensional vector. - glam::i32::IVec2 : - Clone + - Debug + - Methods - ( - ///Creates a new vector. - new(Raw(i32),Raw(i32)) -> self, - - ///Creates a vector with all elements set to `v`. - splat(Raw(i32)) -> self, - - ///Creates a vector from the elements in `if_true` and `if_false`, selecting which to use - ///for each element of `self`. - /// - ///A true element in the mask uses the corresponding element from `if_true`, and false - ///uses the element from `if_false`. - select(Wrapped(BVec2),self,self) -> self, - - ///Creates a 3D vector from `self` and the given `z` value. - extend(self:Raw(i32)) -> Wrapped(IVec3), - - ///Computes the dot product of `self` and `rhs`. - dot(self:self) -> Raw(i32), - - ///Returns a vector where every component is the dot product of `self` and `rhs`. - dot_into_vec(self:self) -> self, - - ///Returns a vector containing the minimum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.min(rhs.x), self.y.min(rhs.y), ..]`. - min(self:self) -> self, - - ///Returns a vector containing the maximum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.max(rhs.x), self.y.max(rhs.y), ..]`. - max(self:self) -> self, - - ///Component-wise clamping of values, similar to [`i32::clamp`]. - /// - ///Each element in `min` must be less-or-equal to the corresponding element in `max`. - /// - ///# Panics - /// - ///Will panic if `min` is greater than `max` when `glam_assert` is enabled. - clamp(self:self,self) -> self, - - ///Returns the horizontal minimum of `self`. - /// - ///In other words this computes `min(x, y, ..)`. - min_element(self:) -> Raw(i32), - - ///Returns the horizontal maximum of `self`. - /// - ///In other words this computes `max(x, y, ..)`. - max_element(self:) -> Raw(i32), - - ///Returns a vector mask containing the result of a `==` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all - ///elements. - cmpeq(self:self) -> Wrapped(BVec2), - - ///Returns a vector mask containing the result of a `!=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all - ///elements. - cmpne(self:self) -> Wrapped(BVec2), - - ///Returns a vector mask containing the result of a `>=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all - ///elements. - cmpge(self:self) -> Wrapped(BVec2), - - ///Returns a vector mask containing the result of a `>` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all - ///elements. - cmpgt(self:self) -> Wrapped(BVec2), - - ///Returns a vector mask containing the result of a `<=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all - ///elements. - cmple(self:self) -> Wrapped(BVec2), - - ///Returns a vector mask containing the result of a `<` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all - ///elements. - cmplt(self:self) -> Wrapped(BVec2), - - ///Returns a vector containing the absolute value of each element of `self`. - abs(self:) -> self, - - ///Returns a vector with elements representing the sign of `self`. - /// - /// - `0` if the number is zero - /// - `1` if the number is positive - /// - `-1` if the number is negative - signum(self:) -> self, - - ///Returns a bitmask with the lowest 2 bits set to the sign bits from the elements of `self`. - /// - ///A negative element results in a `1` bit and a positive element in a `0` bit. Element `x` goes - ///into the first lowest bit, element `y` into the second, etc. - is_negative_bitmask(self:) -> Raw(u32), - - ///Computes the squared length of `self`. - length_squared(self:) -> Raw(i32), - - ///Compute the squared euclidean distance between two points in space. - distance_squared(self:self) -> Raw(i32), - - ///Returns the element-wise quotient of [Euclidean division] of `self` by `rhs`. - /// - ///# Panics - ///This function will panic if any `rhs` element is 0 or the division results in overflow. - div_euclid(self:self) -> self, - - ///Returns the element-wise remainder of [Euclidean division] of `self` by `rhs`. - /// - ///# Panics - ///This function will panic if any `rhs` element is 0 or the division results in overflow. - /// - ///[Euclidean division]: i32::rem_euclid - rem_euclid(self:self) -> self, - - ///Returns a vector that is equal to `self` rotated by 90 degrees. - perp(self:) -> self, - - ///The perpendicular dot product of `self` and `rhs`. - ///Also known as the wedge product, 2D cross product, and determinant. - perp_dot(self:self) -> Raw(i32), - - ///Returns `rhs` rotated by the angle of `self`. If `self` is normalized, - ///then this just rotation. This is what you usually want. Otherwise, - ///it will be like a rotation with a multiplication by `self`'s length. - rotate(self:self) -> self, - - ///Casts all elements of `self` to `f32`. - as_vec2(&self:) -> Wrapped(Vec2), - - ///Casts all elements of `self` to `f64`. - as_dvec2(&self:) -> Wrapped(DVec2), - - ///Casts all elements of `self` to `u32`. - as_uvec2(&self:) -> Wrapped(UVec2), - - ///Returns a vector containing the wrapping addition of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_add(rhs.x), self.y.wrapping_add(rhs.y), ..]`. - wrapping_add(self:self) -> self, - - ///Returns a vector containing the wrapping subtraction of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_sub(rhs.x), self.y.wrapping_sub(rhs.y), ..]`. - wrapping_sub(self:self) -> self, - - ///Returns a vector containing the wrapping multiplication of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_mul(rhs.x), self.y.wrapping_mul(rhs.y), ..]`. - wrapping_mul(self:self) -> self, - - ///Returns a vector containing the wrapping division of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_div(rhs.x), self.y.wrapping_div(rhs.y), ..]`. - wrapping_div(self:self) -> self, - - ///Returns a vector containing the saturating addition of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_add(rhs.x), self.y.saturating_add(rhs.y), ..]`. - saturating_add(self:self) -> self, - - ///Returns a vector containing the saturating subtraction of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_sub(rhs.x), self.y.saturating_sub(rhs.y), ..]`. - saturating_sub(self:self) -> self, - - ///Returns a vector containing the saturating multiplication of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_mul(rhs.x), self.y.saturating_mul(rhs.y), ..]`. - saturating_mul(self:self) -> self, - - ///Returns a vector containing the saturating division of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_div(rhs.x), self.y.saturating_div(rhs.y), ..]`. - saturating_div(self:self) -> self, - - ) - + Fields - ( - x: Raw(i32), - y: Raw(i32), - ) - + BinOps - ( - self Add Wrapped(IVec2) -> Wrapped(IVec2), - self Add Raw(i32) -> Wrapped(IVec2), - self Add self -> Wrapped(IVec2), - self Sub Wrapped(IVec2) -> Wrapped(IVec2), - self Sub self -> Wrapped(IVec2), - self Sub Raw(i32) -> Wrapped(IVec2), - self Div Raw(i32) -> Wrapped(IVec2), - self Div self -> Wrapped(IVec2), - self Div Wrapped(IVec2) -> Wrapped(IVec2), - self Mul self -> Wrapped(IVec2), - self Mul Wrapped(IVec2) -> Wrapped(IVec2), - self Mul Raw(i32) -> Wrapped(IVec2), - self Rem self -> Wrapped(IVec2), - self Rem Raw(i32) -> Wrapped(IVec2), - self Rem Wrapped(IVec2) -> Wrapped(IVec2), - ) - + UnaryOps - ( - Neg self -> self - ) - lua impl - { - (MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}; - mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,i32)| {s.val_mut(|s| Ok(s[*idx] = val))?}; - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 3-dimensional vector. - glam::i32::IVec3 : - Clone + - Debug + - Methods - ( - ///Creates a new vector. - new(Raw(i32),Raw(i32),Raw(i32)) -> self, - - ///Creates a vector with all elements set to `v`. - splat(Raw(i32)) -> self, - - ///Creates a vector from the elements in `if_true` and `if_false`, selecting which to use - ///for each element of `self`. - /// - ///A true element in the mask uses the corresponding element from `if_true`, and false - ///uses the element from `if_false`. - select(Wrapped(BVec3),self,self) -> self, - - ///Creates a 4D vector from `self` and the given `w` value. - extend(self:Raw(i32)) -> Wrapped(IVec4), - - ///Creates a 2D vector from the `x` and `y` elements of `self`, discarding `z`. - /// - ///Truncation may also be performed by using [`self.xy()`][crate::swizzles::Vec3Swizzles::xy()]. - truncate(self:) -> Wrapped(IVec2), - - ///Computes the dot product of `self` and `rhs`. - dot(self:self) -> Raw(i32), - - ///Returns a vector where every component is the dot product of `self` and `rhs`. - dot_into_vec(self:self) -> self, - - ///Computes the cross product of `self` and `rhs`. - cross(self:self) -> self, - - ///Returns a vector containing the minimum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.min(rhs.x), self.y.min(rhs.y), ..]`. - min(self:self) -> self, - - ///Returns a vector containing the maximum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.max(rhs.x), self.y.max(rhs.y), ..]`. - max(self:self) -> self, - - ///Component-wise clamping of values, similar to [`i32::clamp`]. - /// - ///Each element in `min` must be less-or-equal to the corresponding element in `max`. - /// - ///# Panics - /// - ///Will panic if `min` is greater than `max` when `glam_assert` is enabled. - clamp(self:self,self) -> self, - - ///Returns the horizontal minimum of `self`. - /// - ///In other words this computes `min(x, y, ..)`. - min_element(self:) -> Raw(i32), - - ///Returns the horizontal maximum of `self`. - /// - ///In other words this computes `max(x, y, ..)`. - max_element(self:) -> Raw(i32), - - ///Returns a vector mask containing the result of a `==` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all - ///elements. - cmpeq(self:self) -> Wrapped(BVec3), - - ///Returns a vector mask containing the result of a `!=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all - ///elements. - cmpne(self:self) -> Wrapped(BVec3), - - ///Returns a vector mask containing the result of a `>=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all - ///elements. - cmpge(self:self) -> Wrapped(BVec3), - - ///Returns a vector mask containing the result of a `>` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all - ///elements. - cmpgt(self:self) -> Wrapped(BVec3), - - ///Returns a vector mask containing the result of a `<=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all - ///elements. - cmple(self:self) -> Wrapped(BVec3), - - ///Returns a vector mask containing the result of a `<` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all - ///elements. - cmplt(self:self) -> Wrapped(BVec3), - - ///Returns a vector containing the absolute value of each element of `self`. - abs(self:) -> self, - - ///Returns a vector with elements representing the sign of `self`. - /// - /// - `0` if the number is zero - /// - `1` if the number is positive - /// - `-1` if the number is negative - signum(self:) -> self, - - ///Returns a bitmask with the lowest 3 bits set to the sign bits from the elements of `self`. - /// - ///A negative element results in a `1` bit and a positive element in a `0` bit. Element `x` goes - ///into the first lowest bit, element `y` into the second, etc. - is_negative_bitmask(self:) -> Raw(u32), - - ///Computes the squared length of `self`. - length_squared(self:) -> Raw(i32), - - ///Compute the squared euclidean distance between two points in space. - distance_squared(self:self) -> Raw(i32), - - ///Returns the element-wise quotient of [Euclidean division] of `self` by `rhs`. - /// - ///# Panics - ///This function will panic if any `rhs` element is 0 or the division results in overflow. - div_euclid(self:self) -> self, - - ///Returns the element-wise remainder of [Euclidean division] of `self` by `rhs`. - /// - ///# Panics - ///This function will panic if any `rhs` element is 0 or the division results in overflow. - /// - ///[Euclidean division]: i32::rem_euclid - rem_euclid(self:self) -> self, - - ///Casts all elements of `self` to `f32`. - as_vec3(&self:) -> Wrapped(Vec3), - - ///Casts all elements of `self` to `f32`. - as_vec3a(&self:) -> Wrapped(Vec3A), - - ///Casts all elements of `self` to `f64`. - as_dvec3(&self:) -> Wrapped(DVec3), - - ///Casts all elements of `self` to `u32`. - as_uvec3(&self:) -> Wrapped(UVec3), - - ///Returns a vector containing the wrapping addition of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_add(rhs.x), self.y.wrapping_add(rhs.y), ..]`. - wrapping_add(self:self) -> self, - - ///Returns a vector containing the wrapping subtraction of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_sub(rhs.x), self.y.wrapping_sub(rhs.y), ..]`. - wrapping_sub(self:self) -> self, - - ///Returns a vector containing the wrapping multiplication of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_mul(rhs.x), self.y.wrapping_mul(rhs.y), ..]`. - wrapping_mul(self:self) -> self, - - ///Returns a vector containing the wrapping division of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_div(rhs.x), self.y.wrapping_div(rhs.y), ..]`. - wrapping_div(self:self) -> self, - - ///Returns a vector containing the saturating addition of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_add(rhs.x), self.y.saturating_add(rhs.y), ..]`. - saturating_add(self:self) -> self, - - ///Returns a vector containing the saturating subtraction of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_sub(rhs.x), self.y.saturating_sub(rhs.y), ..]`. - saturating_sub(self:self) -> self, - - ///Returns a vector containing the saturating multiplication of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_mul(rhs.x), self.y.saturating_mul(rhs.y), ..]`. - saturating_mul(self:self) -> self, - - ///Returns a vector containing the saturating division of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_div(rhs.x), self.y.saturating_div(rhs.y), ..]`. - saturating_div(self:self) -> self, - - ) - + Fields - ( - x: Raw(i32), - y: Raw(i32), - z: Raw(i32), - ) - + BinOps - ( - self Add Raw(i32) -> Wrapped(IVec3), - self Add self -> Wrapped(IVec3), - self Add Wrapped(IVec3) -> Wrapped(IVec3), - self Sub Wrapped(IVec3) -> Wrapped(IVec3), - self Sub Raw(i32) -> Wrapped(IVec3), - self Sub self -> Wrapped(IVec3), - self Div self -> Wrapped(IVec3), - self Div Wrapped(IVec3) -> Wrapped(IVec3), - self Div Raw(i32) -> Wrapped(IVec3), - self Mul Raw(i32) -> Wrapped(IVec3), - self Mul self -> Wrapped(IVec3), - self Mul Wrapped(IVec3) -> Wrapped(IVec3), - self Rem Wrapped(IVec3) -> Wrapped(IVec3), - self Rem self -> Wrapped(IVec3), - self Rem Raw(i32) -> Wrapped(IVec3), - ) - + UnaryOps - ( - Neg self -> self - ) - lua impl - { - (MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}; - mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,i32)| {s.val_mut(|s| Ok(s[*idx] = val))?}; - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 4-dimensional vector. - glam::i32::IVec4 : - Clone + - Debug + - Methods - ( - ///Creates a new vector. - new(Raw(i32),Raw(i32),Raw(i32),Raw(i32)) -> self, - - ///Creates a vector with all elements set to `v`. - splat(Raw(i32)) -> self, - - ///Creates a vector from the elements in `if_true` and `if_false`, selecting which to use - ///for each element of `self`. - /// - ///A true element in the mask uses the corresponding element from `if_true`, and false - ///uses the element from `if_false`. - select(Wrapped(BVec4),self,self) -> self, - - ///Creates a 3D vector from the `x`, `y` and `z` elements of `self`, discarding `w`. - /// - ///Truncation to [`IVec3`] may also be performed by using [`self.xyz()`][crate::swizzles::Vec4Swizzles::xyz()]. - truncate(self:) -> Wrapped(IVec3), - - ///Computes the dot product of `self` and `rhs`. - dot(self:self) -> Raw(i32), - - ///Returns a vector where every component is the dot product of `self` and `rhs`. - dot_into_vec(self:self) -> self, - - ///Returns a vector containing the minimum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.min(rhs.x), self.y.min(rhs.y), ..]`. - min(self:self) -> self, - - ///Returns a vector containing the maximum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.max(rhs.x), self.y.max(rhs.y), ..]`. - max(self:self) -> self, - - ///Component-wise clamping of values, similar to [`i32::clamp`]. - /// - ///Each element in `min` must be less-or-equal to the corresponding element in `max`. - /// - ///# Panics - /// - ///Will panic if `min` is greater than `max` when `glam_assert` is enabled. - clamp(self:self,self) -> self, - - ///Returns the horizontal minimum of `self`. - /// - ///In other words this computes `min(x, y, ..)`. - min_element(self:) -> Raw(i32), - - ///Returns the horizontal maximum of `self`. - /// - ///In other words this computes `max(x, y, ..)`. - max_element(self:) -> Raw(i32), - - ///Returns a vector mask containing the result of a `==` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all - ///elements. - cmpeq(self:self) -> Wrapped(BVec4), - - ///Returns a vector mask containing the result of a `!=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all - ///elements. - cmpne(self:self) -> Wrapped(BVec4), - - ///Returns a vector mask containing the result of a `>=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all - ///elements. - cmpge(self:self) -> Wrapped(BVec4), - - ///Returns a vector mask containing the result of a `>` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all - ///elements. - cmpgt(self:self) -> Wrapped(BVec4), - - ///Returns a vector mask containing the result of a `<=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all - ///elements. - cmple(self:self) -> Wrapped(BVec4), - - ///Returns a vector mask containing the result of a `<` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all - ///elements. - cmplt(self:self) -> Wrapped(BVec4), - - ///Returns a vector containing the absolute value of each element of `self`. - abs(self:) -> self, - - ///Returns a vector with elements representing the sign of `self`. - /// - /// - `0` if the number is zero - /// - `1` if the number is positive - /// - `-1` if the number is negative - signum(self:) -> self, - - ///Returns a bitmask with the lowest 4 bits set to the sign bits from the elements of `self`. - /// - ///A negative element results in a `1` bit and a positive element in a `0` bit. Element `x` goes - ///into the first lowest bit, element `y` into the second, etc. - is_negative_bitmask(self:) -> Raw(u32), - - ///Computes the squared length of `self`. - length_squared(self:) -> Raw(i32), - - ///Compute the squared euclidean distance between two points in space. - distance_squared(self:self) -> Raw(i32), - - ///Returns the element-wise quotient of [Euclidean division] of `self` by `rhs`. - /// - ///# Panics - ///This function will panic if any `rhs` element is 0 or the division results in overflow. - div_euclid(self:self) -> self, - - ///Returns the element-wise remainder of [Euclidean division] of `self` by `rhs`. - /// - ///# Panics - ///This function will panic if any `rhs` element is 0 or the division results in overflow. - /// - ///[Euclidean division]: i32::rem_euclid - rem_euclid(self:self) -> self, - - ///Casts all elements of `self` to `f32`. - as_vec4(&self:) -> Wrapped(Vec4), - - ///Casts all elements of `self` to `f64`. - as_dvec4(&self:) -> Wrapped(DVec4), - - ///Casts all elements of `self` to `u32`. - as_uvec4(&self:) -> Wrapped(UVec4), - - ///Returns a vector containing the wrapping addition of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_add(rhs.x), self.y.wrapping_add(rhs.y), ..]`. - wrapping_add(self:self) -> self, - - ///Returns a vector containing the wrapping subtraction of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_sub(rhs.x), self.y.wrapping_sub(rhs.y), ..]`. - wrapping_sub(self:self) -> self, - - ///Returns a vector containing the wrapping multiplication of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_mul(rhs.x), self.y.wrapping_mul(rhs.y), ..]`. - wrapping_mul(self:self) -> self, - - ///Returns a vector containing the wrapping division of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_div(rhs.x), self.y.wrapping_div(rhs.y), ..]`. - wrapping_div(self:self) -> self, - - ///Returns a vector containing the saturating addition of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_add(rhs.x), self.y.saturating_add(rhs.y), ..]`. - saturating_add(self:self) -> self, - - ///Returns a vector containing the saturating subtraction of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_sub(rhs.x), self.y.saturating_sub(rhs.y), ..]`. - saturating_sub(self:self) -> self, - - ///Returns a vector containing the saturating multiplication of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_mul(rhs.x), self.y.saturating_mul(rhs.y), ..]`. - saturating_mul(self:self) -> self, - - ///Returns a vector containing the saturating division of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_div(rhs.x), self.y.saturating_div(rhs.y), ..]`. - saturating_div(self:self) -> self, - - ) - + Fields - ( - x: Raw(i32), - y: Raw(i32), - z: Raw(i32), - w: Raw(i32), - ) - + BinOps - ( - self Add self -> Wrapped(IVec4), - self Add Wrapped(IVec4) -> Wrapped(IVec4), - self Add Raw(i32) -> Wrapped(IVec4), - self Sub self -> Wrapped(IVec4), - self Sub Raw(i32) -> Wrapped(IVec4), - self Sub Wrapped(IVec4) -> Wrapped(IVec4), - self Div self -> Wrapped(IVec4), - self Div Wrapped(IVec4) -> Wrapped(IVec4), - self Div Raw(i32) -> Wrapped(IVec4), - self Mul Raw(i32) -> Wrapped(IVec4), - self Mul self -> Wrapped(IVec4), - self Mul Wrapped(IVec4) -> Wrapped(IVec4), - self Rem self -> Wrapped(IVec4), - self Rem Wrapped(IVec4) -> Wrapped(IVec4), - self Rem Raw(i32) -> Wrapped(IVec4), - ) - + UnaryOps - ( - Neg self -> self - ) - lua impl - { - (MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}; - mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,i32)| {s.val_mut(|s| Ok(s[*idx] = val))?}; - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 2-dimensional vector. - glam::u32::UVec2 : - Clone + - Debug + - Methods - ( - ///Creates a new vector. - new(Raw(u32),Raw(u32)) -> self, - - ///Creates a vector with all elements set to `v`. - splat(Raw(u32)) -> self, - - ///Creates a vector from the elements in `if_true` and `if_false`, selecting which to use - ///for each element of `self`. - /// - ///A true element in the mask uses the corresponding element from `if_true`, and false - ///uses the element from `if_false`. - select(Wrapped(BVec2),self,self) -> self, - - ///Creates a 3D vector from `self` and the given `z` value. - extend(self:Raw(u32)) -> Wrapped(UVec3), - - ///Computes the dot product of `self` and `rhs`. - dot(self:self) -> Raw(u32), - - ///Returns a vector where every component is the dot product of `self` and `rhs`. - dot_into_vec(self:self) -> self, - - ///Returns a vector containing the minimum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.min(rhs.x), self.y.min(rhs.y), ..]`. - min(self:self) -> self, - - ///Returns a vector containing the maximum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.max(rhs.x), self.y.max(rhs.y), ..]`. - max(self:self) -> self, - - ///Component-wise clamping of values, similar to [`u32::clamp`]. - /// - ///Each element in `min` must be less-or-equal to the corresponding element in `max`. - /// - ///# Panics - /// - ///Will panic if `min` is greater than `max` when `glam_assert` is enabled. - clamp(self:self,self) -> self, - - ///Returns the horizontal minimum of `self`. - /// - ///In other words this computes `min(x, y, ..)`. - min_element(self:) -> Raw(u32), - - ///Returns the horizontal maximum of `self`. - /// - ///In other words this computes `max(x, y, ..)`. - max_element(self:) -> Raw(u32), - - ///Returns a vector mask containing the result of a `==` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all - ///elements. - cmpeq(self:self) -> Wrapped(BVec2), - - ///Returns a vector mask containing the result of a `!=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all - ///elements. - cmpne(self:self) -> Wrapped(BVec2), - - ///Returns a vector mask containing the result of a `>=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all - ///elements. - cmpge(self:self) -> Wrapped(BVec2), - - ///Returns a vector mask containing the result of a `>` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all - ///elements. - cmpgt(self:self) -> Wrapped(BVec2), - - ///Returns a vector mask containing the result of a `<=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all - ///elements. - cmple(self:self) -> Wrapped(BVec2), - - ///Returns a vector mask containing the result of a `<` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all - ///elements. - cmplt(self:self) -> Wrapped(BVec2), - - ///Computes the squared length of `self`. - length_squared(self:) -> Raw(u32), - - ///Casts all elements of `self` to `f32`. - as_vec2(&self:) -> Wrapped(Vec2), - - ///Casts all elements of `self` to `f64`. - as_dvec2(&self:) -> Wrapped(DVec2), - - ///Casts all elements of `self` to `i32`. - as_ivec2(&self:) -> Wrapped(IVec2), - - ///Returns a vector containing the wrapping addition of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_add(rhs.x), self.y.wrapping_add(rhs.y), ..]`. - wrapping_add(self:self) -> self, - - ///Returns a vector containing the wrapping subtraction of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_sub(rhs.x), self.y.wrapping_sub(rhs.y), ..]`. - wrapping_sub(self:self) -> self, - - ///Returns a vector containing the wrapping multiplication of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_mul(rhs.x), self.y.wrapping_mul(rhs.y), ..]`. - wrapping_mul(self:self) -> self, - - ///Returns a vector containing the wrapping division of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_div(rhs.x), self.y.wrapping_div(rhs.y), ..]`. - wrapping_div(self:self) -> self, - - ///Returns a vector containing the saturating addition of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_add(rhs.x), self.y.saturating_add(rhs.y), ..]`. - saturating_add(self:self) -> self, - - ///Returns a vector containing the saturating subtraction of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_sub(rhs.x), self.y.saturating_sub(rhs.y), ..]`. - saturating_sub(self:self) -> self, - - ///Returns a vector containing the saturating multiplication of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_mul(rhs.x), self.y.saturating_mul(rhs.y), ..]`. - saturating_mul(self:self) -> self, - - ///Returns a vector containing the saturating division of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_div(rhs.x), self.y.saturating_div(rhs.y), ..]`. - saturating_div(self:self) -> self, - - ) - + Fields - ( - x: Raw(u32), - y: Raw(u32), - ) - + BinOps - ( - self Add Wrapped(UVec2) -> Wrapped(UVec2), - self Add self -> Wrapped(UVec2), - self Add Raw(u32) -> Wrapped(UVec2), - self Sub Raw(u32) -> Wrapped(UVec2), - self Sub self -> Wrapped(UVec2), - self Sub Wrapped(UVec2) -> Wrapped(UVec2), - self Div self -> Wrapped(UVec2), - self Div Wrapped(UVec2) -> Wrapped(UVec2), - self Div Raw(u32) -> Wrapped(UVec2), - self Mul self -> Wrapped(UVec2), - self Mul Wrapped(UVec2) -> Wrapped(UVec2), - self Mul Raw(u32) -> Wrapped(UVec2), - self Rem self -> Wrapped(UVec2), - self Rem Wrapped(UVec2) -> Wrapped(UVec2), - self Rem Raw(u32) -> Wrapped(UVec2), - ) - + UnaryOps - ( - ) - lua impl - { - (MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}; - mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,u32)| {s.val_mut(|s| Ok(s[*idx] = val))?}; - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 3-dimensional vector. - glam::u32::UVec3 : - Clone + - Debug + - Methods - ( - ///Creates a new vector. - new(Raw(u32),Raw(u32),Raw(u32)) -> self, - - ///Creates a vector with all elements set to `v`. - splat(Raw(u32)) -> self, - - ///Creates a vector from the elements in `if_true` and `if_false`, selecting which to use - ///for each element of `self`. - /// - ///A true element in the mask uses the corresponding element from `if_true`, and false - ///uses the element from `if_false`. - select(Wrapped(BVec3),self,self) -> self, - - ///Creates a 4D vector from `self` and the given `w` value. - extend(self:Raw(u32)) -> Wrapped(UVec4), - - ///Creates a 2D vector from the `x` and `y` elements of `self`, discarding `z`. - /// - ///Truncation may also be performed by using [`self.xy()`][crate::swizzles::Vec3Swizzles::xy()]. - truncate(self:) -> Wrapped(UVec2), - - ///Computes the dot product of `self` and `rhs`. - dot(self:self) -> Raw(u32), - - ///Returns a vector where every component is the dot product of `self` and `rhs`. - dot_into_vec(self:self) -> self, - - ///Computes the cross product of `self` and `rhs`. - cross(self:self) -> self, - - ///Returns a vector containing the minimum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.min(rhs.x), self.y.min(rhs.y), ..]`. - min(self:self) -> self, - - ///Returns a vector containing the maximum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.max(rhs.x), self.y.max(rhs.y), ..]`. - max(self:self) -> self, - - ///Component-wise clamping of values, similar to [`u32::clamp`]. - /// - ///Each element in `min` must be less-or-equal to the corresponding element in `max`. - /// - ///# Panics - /// - ///Will panic if `min` is greater than `max` when `glam_assert` is enabled. - clamp(self:self,self) -> self, - - ///Returns the horizontal minimum of `self`. - /// - ///In other words this computes `min(x, y, ..)`. - min_element(self:) -> Raw(u32), - - ///Returns the horizontal maximum of `self`. - /// - ///In other words this computes `max(x, y, ..)`. - max_element(self:) -> Raw(u32), - - ///Returns a vector mask containing the result of a `==` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all - ///elements. - cmpeq(self:self) -> Wrapped(BVec3), - - ///Returns a vector mask containing the result of a `!=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all - ///elements. - cmpne(self:self) -> Wrapped(BVec3), - - ///Returns a vector mask containing the result of a `>=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all - ///elements. - cmpge(self:self) -> Wrapped(BVec3), - - ///Returns a vector mask containing the result of a `>` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all - ///elements. - cmpgt(self:self) -> Wrapped(BVec3), - - ///Returns a vector mask containing the result of a `<=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all - ///elements. - cmple(self:self) -> Wrapped(BVec3), - - ///Returns a vector mask containing the result of a `<` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all - ///elements. - cmplt(self:self) -> Wrapped(BVec3), - - ///Computes the squared length of `self`. - length_squared(self:) -> Raw(u32), - - ///Casts all elements of `self` to `f32`. - as_vec3(&self:) -> Wrapped(Vec3), - - ///Casts all elements of `self` to `f32`. - as_vec3a(&self:) -> Wrapped(Vec3A), - - ///Casts all elements of `self` to `f64`. - as_dvec3(&self:) -> Wrapped(DVec3), - - ///Casts all elements of `self` to `i32`. - as_ivec3(&self:) -> Wrapped(IVec3), - - ///Returns a vector containing the wrapping addition of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_add(rhs.x), self.y.wrapping_add(rhs.y), ..]`. - wrapping_add(self:self) -> self, - - ///Returns a vector containing the wrapping subtraction of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_sub(rhs.x), self.y.wrapping_sub(rhs.y), ..]`. - wrapping_sub(self:self) -> self, - - ///Returns a vector containing the wrapping multiplication of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_mul(rhs.x), self.y.wrapping_mul(rhs.y), ..]`. - wrapping_mul(self:self) -> self, - - ///Returns a vector containing the wrapping division of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_div(rhs.x), self.y.wrapping_div(rhs.y), ..]`. - wrapping_div(self:self) -> self, - - ///Returns a vector containing the saturating addition of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_add(rhs.x), self.y.saturating_add(rhs.y), ..]`. - saturating_add(self:self) -> self, - - ///Returns a vector containing the saturating subtraction of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_sub(rhs.x), self.y.saturating_sub(rhs.y), ..]`. - saturating_sub(self:self) -> self, - - ///Returns a vector containing the saturating multiplication of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_mul(rhs.x), self.y.saturating_mul(rhs.y), ..]`. - saturating_mul(self:self) -> self, - - ///Returns a vector containing the saturating division of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_div(rhs.x), self.y.saturating_div(rhs.y), ..]`. - saturating_div(self:self) -> self, - - ) - + Fields - ( - x: Raw(u32), - y: Raw(u32), - z: Raw(u32), - ) - + BinOps - ( - self Add Wrapped(UVec3) -> Wrapped(UVec3), - self Add Raw(u32) -> Wrapped(UVec3), - self Add self -> Wrapped(UVec3), - self Sub Wrapped(UVec3) -> Wrapped(UVec3), - self Sub Raw(u32) -> Wrapped(UVec3), - self Sub self -> Wrapped(UVec3), - self Div self -> Wrapped(UVec3), - self Div Raw(u32) -> Wrapped(UVec3), - self Div Wrapped(UVec3) -> Wrapped(UVec3), - self Mul self -> Wrapped(UVec3), - self Mul Wrapped(UVec3) -> Wrapped(UVec3), - self Mul Raw(u32) -> Wrapped(UVec3), - self Rem Raw(u32) -> Wrapped(UVec3), - self Rem Wrapped(UVec3) -> Wrapped(UVec3), - self Rem self -> Wrapped(UVec3), - ) - + UnaryOps - ( - ) - lua impl - { - (MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}; - mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,u32)| {s.val_mut(|s| Ok(s[*idx] = val))?}; - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 4-dimensional vector. - glam::u32::UVec4 : - Clone + - Debug + - Methods - ( - ///Creates a new vector. - new(Raw(u32),Raw(u32),Raw(u32),Raw(u32)) -> self, - - ///Creates a vector with all elements set to `v`. - splat(Raw(u32)) -> self, - - ///Creates a vector from the elements in `if_true` and `if_false`, selecting which to use - ///for each element of `self`. - /// - ///A true element in the mask uses the corresponding element from `if_true`, and false - ///uses the element from `if_false`. - select(Wrapped(BVec4),self,self) -> self, - - ///Creates a 3D vector from the `x`, `y` and `z` elements of `self`, discarding `w`. - /// - ///Truncation to [`UVec3`] may also be performed by using [`self.xyz()`][crate::swizzles::Vec4Swizzles::xyz()]. - truncate(self:) -> Wrapped(UVec3), - - ///Computes the dot product of `self` and `rhs`. - dot(self:self) -> Raw(u32), - - ///Returns a vector where every component is the dot product of `self` and `rhs`. - dot_into_vec(self:self) -> self, - - ///Returns a vector containing the minimum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.min(rhs.x), self.y.min(rhs.y), ..]`. - min(self:self) -> self, - - ///Returns a vector containing the maximum values for each element of `self` and `rhs`. - /// - ///In other words this computes `[self.x.max(rhs.x), self.y.max(rhs.y), ..]`. - max(self:self) -> self, - - ///Component-wise clamping of values, similar to [`u32::clamp`]. - /// - ///Each element in `min` must be less-or-equal to the corresponding element in `max`. - /// - ///# Panics - /// - ///Will panic if `min` is greater than `max` when `glam_assert` is enabled. - clamp(self:self,self) -> self, - - ///Returns the horizontal minimum of `self`. - /// - ///In other words this computes `min(x, y, ..)`. - min_element(self:) -> Raw(u32), - - ///Returns the horizontal maximum of `self`. - /// - ///In other words this computes `max(x, y, ..)`. - max_element(self:) -> Raw(u32), - - ///Returns a vector mask containing the result of a `==` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all - ///elements. - cmpeq(self:self) -> Wrapped(BVec4), - - ///Returns a vector mask containing the result of a `!=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all - ///elements. - cmpne(self:self) -> Wrapped(BVec4), - - ///Returns a vector mask containing the result of a `>=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all - ///elements. - cmpge(self:self) -> Wrapped(BVec4), - - ///Returns a vector mask containing the result of a `>` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all - ///elements. - cmpgt(self:self) -> Wrapped(BVec4), - - ///Returns a vector mask containing the result of a `<=` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all - ///elements. - cmple(self:self) -> Wrapped(BVec4), - - ///Returns a vector mask containing the result of a `<` comparison for each element of - ///`self` and `rhs`. - /// - ///In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all - ///elements. - cmplt(self:self) -> Wrapped(BVec4), - - ///Computes the squared length of `self`. - length_squared(self:) -> Raw(u32), - - ///Casts all elements of `self` to `f32`. - as_vec4(&self:) -> Wrapped(Vec4), - - ///Casts all elements of `self` to `f64`. - as_dvec4(&self:) -> Wrapped(DVec4), - - ///Casts all elements of `self` to `i32`. - as_ivec4(&self:) -> Wrapped(IVec4), - - ///Returns a vector containing the wrapping addition of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_add(rhs.x), self.y.wrapping_add(rhs.y), ..]`. - wrapping_add(self:self) -> self, - - ///Returns a vector containing the wrapping subtraction of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_sub(rhs.x), self.y.wrapping_sub(rhs.y), ..]`. - wrapping_sub(self:self) -> self, - - ///Returns a vector containing the wrapping multiplication of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_mul(rhs.x), self.y.wrapping_mul(rhs.y), ..]`. - wrapping_mul(self:self) -> self, - - ///Returns a vector containing the wrapping division of `self` and `rhs`. - /// - ///In other words this computes `[self.x.wrapping_div(rhs.x), self.y.wrapping_div(rhs.y), ..]`. - wrapping_div(self:self) -> self, - - ///Returns a vector containing the saturating addition of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_add(rhs.x), self.y.saturating_add(rhs.y), ..]`. - saturating_add(self:self) -> self, - - ///Returns a vector containing the saturating subtraction of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_sub(rhs.x), self.y.saturating_sub(rhs.y), ..]`. - saturating_sub(self:self) -> self, - - ///Returns a vector containing the saturating multiplication of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_mul(rhs.x), self.y.saturating_mul(rhs.y), ..]`. - saturating_mul(self:self) -> self, - - ///Returns a vector containing the saturating division of `self` and `rhs`. - /// - ///In other words this computes `[self.x.saturating_div(rhs.x), self.y.saturating_div(rhs.y), ..]`. - saturating_div(self:self) -> self, - - ) - + Fields - ( - x: Raw(u32), - y: Raw(u32), - z: Raw(u32), - w: Raw(u32), - ) - + BinOps - ( - self Add self -> Wrapped(UVec4), - self Add Raw(u32) -> Wrapped(UVec4), - self Add Wrapped(UVec4) -> Wrapped(UVec4), - self Sub self -> Wrapped(UVec4), - self Sub Raw(u32) -> Wrapped(UVec4), - self Sub Wrapped(UVec4) -> Wrapped(UVec4), - self Div self -> Wrapped(UVec4), - self Div Raw(u32) -> Wrapped(UVec4), - self Div Wrapped(UVec4) -> Wrapped(UVec4), - self Mul Raw(u32) -> Wrapped(UVec4), - self Mul Wrapped(UVec4) -> Wrapped(UVec4), - self Mul self -> Wrapped(UVec4), - self Rem Wrapped(UVec4) -> Wrapped(UVec4), - self Rem self -> Wrapped(UVec4), - self Rem Raw(u32) -> Wrapped(UVec4), - ) - + UnaryOps - ( - ) - lua impl - { - (MetaMethod::Index) => |_,s,idx: LuaIndex| {Ok(s.inner()?[*idx])}; - mut (MetaMethod::NewIndex) => |_,s,(idx,val): (LuaIndex,u32)| {s.val_mut(|s| Ok(s[*idx] = val))?}; - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 3x3 column major matrix. - /// - ///This 3x3 matrix type features convenience methods for creating and using linear and - ///affine transformations. If you are primarily dealing with 2D affine transformations the - ///[`Affine2`](crate::Affine2) type is much faster and more space efficient than - ///using a 3x3 matrix. - /// - ///Linear transformations including 3D rotation and scale can be created using methods - ///such as [`Self::from_diagonal()`], [`Self::from_quat()`], [`Self::from_axis_angle()`], - ///[`Self::from_rotation_x()`], [`Self::from_rotation_y()`], or - ///[`Self::from_rotation_z()`]. - /// - ///The resulting matrices can be use to transform 3D vectors using regular vector - ///multiplication. - /// - ///Affine transformations including 2D translation, rotation and scale can be created - ///using methods such as [`Self::from_translation()`], [`Self::from_angle()`], - ///[`Self::from_scale()`] and [`Self::from_scale_angle_translation()`]. - /// - ///The [`Self::transform_point2()`] and [`Self::transform_vector2()`] convenience methods - ///are provided for performing affine transforms on 2D vectors and points. These multiply - ///2D inputs as 3D vectors with an implicit `z` value of `1` for points and `0` for - ///vectors respectively. These methods assume that `Self` contains a valid affine - ///transform. - glam::f32::Mat3 : - Clone + - Debug + - Methods - ( - ///Creates a 3x3 matrix from three column vectors. - from_cols(Wrapped(Vec3),Wrapped(Vec3),Wrapped(Vec3)) -> self, - - ///Creates a 3x3 matrix with its diagonal set to `diagonal` and all other entries set to 0. - from_diagonal(Wrapped(Vec3)) -> self, - - ///Creates a 3x3 matrix from a 4x4 matrix, discarding the 4th row and column. - from_mat4(Wrapped(Mat4)) -> self, - - ///Creates a 3D rotation matrix from the given quaternion. - /// - ///# Panics - /// - ///Will panic if `rotation` is not normalized when `glam_assert` is enabled. - from_quat(Wrapped(Quat)) -> self, - - ///Creates a 3D rotation matrix from a normalized rotation `axis` and `angle` (in - ///radians). - /// - ///# Panics - /// - ///Will panic if `axis` is not normalized when `glam_assert` is enabled. - from_axis_angle(Wrapped(Vec3),Raw(f32)) -> self, - - ///Creates a 3D rotation matrix from the given euler rotation sequence and the angles (in - ///radians). - from_euler(Wrapped(EulerRot),Raw(f32),Raw(f32),Raw(f32)) -> self, - - ///Creates a 3D rotation matrix from `angle` (in radians) around the x axis. - from_rotation_x(Raw(f32)) -> self, - - ///Creates a 3D rotation matrix from `angle` (in radians) around the y axis. - from_rotation_y(Raw(f32)) -> self, - - ///Creates a 3D rotation matrix from `angle` (in radians) around the z axis. - from_rotation_z(Raw(f32)) -> self, - - ///Creates an affine transformation matrix from the given 2D `translation`. - /// - ///The resulting matrix can be used to transform 2D points and vectors. See - ///[`Self::transform_point2()`] and [`Self::transform_vector2()`]. - from_translation(Wrapped(Vec2)) -> self, - - ///Creates an affine transformation matrix from the given 2D rotation `angle` (in - ///radians). - /// - ///The resulting matrix can be used to transform 2D points and vectors. See - ///[`Self::transform_point2()`] and [`Self::transform_vector2()`]. - from_angle(Raw(f32)) -> self, - - ///Creates an affine transformation matrix from the given 2D `scale`, rotation `angle` (in - ///radians) and `translation`. - /// - ///The resulting matrix can be used to transform 2D points and vectors. See - ///[`Self::transform_point2()`] and [`Self::transform_vector2()`]. - from_scale_angle_translation(Wrapped(Vec2),Raw(f32),Wrapped(Vec2)) -> self, - - ///Creates an affine transformation matrix from the given non-uniform 2D `scale`. - /// - ///The resulting matrix can be used to transform 2D points and vectors. See - ///[`Self::transform_point2()`] and [`Self::transform_vector2()`]. - /// - ///# Panics - /// - ///Will panic if all elements of `scale` are zero when `glam_assert` is enabled. - from_scale(Wrapped(Vec2)) -> self, - - ///Creates an affine transformation matrix from the given 2x2 matrix. - /// - ///The resulting matrix can be used to transform 2D points and vectors. See - ///[`Self::transform_point2()`] and [`Self::transform_vector2()`]. - from_mat2(Wrapped(Mat2)) -> self, - - ///Returns the matrix column for the given `index`. - /// - ///# Panics - /// - ///Panics if `index` is greater than 2. - col(&self:Raw(usize)) -> Wrapped(Vec3), - - ///Returns the matrix row for the given `index`. - /// - ///# Panics - /// - ///Panics if `index` is greater than 2. - row(&self:Raw(usize)) -> Wrapped(Vec3), - - ///Returns `true` if, and only if, all elements are finite. - ///If any element is either `NaN`, positive or negative infinity, this will return `false`. - is_finite(&self:) -> Raw(bool), - - ///Returns `true` if any elements are `NaN`. - is_nan(&self:) -> Raw(bool), - - ///Returns the transpose of `self`. - transpose(&self:) -> self, - - ///Returns the determinant of `self`. - determinant(&self:) -> Raw(f32), - - ///Returns the inverse of `self`. - /// - ///If the matrix is not invertible the returned matrix will be invalid. - /// - ///# Panics - /// - ///Will panic if the determinant of `self` is zero when `glam_assert` is enabled. - inverse(&self:) -> self, - - ///Transforms the given 2D vector as a point. - /// - ///This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `1`. - /// - ///This method assumes that `self` contains a valid affine transform. - /// - ///# Panics - /// - ///Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled. - transform_point2(&self:Wrapped(Vec2)) -> Wrapped(Vec2), - - ///Rotates the given 2D vector. - /// - ///This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `0`. - /// - ///This method assumes that `self` contains a valid affine transform. - /// - ///# Panics - /// - ///Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled. - transform_vector2(&self:Wrapped(Vec2)) -> Wrapped(Vec2), - - ///Transforms a 3D vector. - mul_vec3(&self:Wrapped(Vec3)) -> Wrapped(Vec3), - - ///Transforms a [`Vec3A`]. - mul_vec3a(&self:Wrapped(Vec3A)) -> Wrapped(Vec3A), - - ///Multiplies two 3x3 matrices. - mul_mat3(&self:&self) -> self, - - ///Adds two 3x3 matrices. - add_mat3(&self:&self) -> self, - - ///Subtracts two 3x3 matrices. - sub_mat3(&self:&self) -> self, - - ///Multiplies a 3x3 matrix by a scalar. - mul_scalar(&self:Raw(f32)) -> self, - - ///Returns true if the absolute difference of all elements between `self` and `rhs` - ///is less than or equal to `max_abs_diff`. - /// - ///This can be used to compare if two matrices contain similar elements. It works best - ///when comparing with a known value. The `max_abs_diff` that should be used used - ///depends on the values being compared against. - /// - ///For more see - ///[comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - abs_diff_eq(&self:self,Raw(f32)) -> Raw(bool), - - as_dmat3(&self:) -> Wrapped(DMat3), - - ) - + Fields - ( - x_axis: Wrapped(Vec3), - y_axis: Wrapped(Vec3), - z_axis: Wrapped(Vec3), - ) - + BinOps - ( - self Add self -> Wrapped(Mat3), - self Sub self -> Wrapped(Mat3), - self Mul Wrapped(Mat3) -> Wrapped(Mat3), - self Mul self -> Wrapped(Mat3), - self Mul Wrapped(Affine2) -> Wrapped(Mat3), - self Mul Wrapped(Vec3A) -> Wrapped(Vec3A), - self Mul Raw(f32) -> Wrapped(Mat3), - self Mul Wrapped(Vec3) -> Wrapped(Vec3), - ) - + UnaryOps - ( - Neg self -> self - ) - lua impl - { - - mut (MetaMethod::Index) => |ctx,s,idx : LuaIndex| { - Ok(LuaVec3::new_ref( - s.script_ref(ctx.get_world()?).sub_ref(ReflectPathElem::SubReflectionIndexed{ - label:"col", - index: *idx, - get: |idx,ref_| Err(ReflectionError::InsufficientProvenance{ - path: "".to_owned(), - msg: "Cannot get column of matrix with immutable reference".to_owned() - }), - get_mut: |idx, ref_| { - if ref_.is::(){ - Ok(ref_.downcast_mut::() - .unwrap() - .col_mut(idx)) - } else { - Err(ReflectionError::CannotDowncast{from: ref_.get_represented_type_info().unwrap().type_path().into(), to:"Mat3".into()}) - } - } - }) - ) - ) - } -; - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 2x2 column major matrix. - /// - ///SIMD vector types are used for storage on supported platforms. - /// - ///This type is 16 byte aligned. - glam::f32::Mat2 : - Clone + - Debug + - Methods - ( - ///Creates a 2x2 matrix from two column vectors. - from_cols(Wrapped(Vec2),Wrapped(Vec2)) -> self, - - ///Creates a 2x2 matrix with its diagonal set to `diagonal` and all other entries set to 0. - from_diagonal(Wrapped(Vec2)) -> self, - - ///Creates a 2x2 matrix containing the combining non-uniform `scale` and rotation of - ///`angle` (in radians). - from_scale_angle(Wrapped(Vec2),Raw(f32)) -> self, - - ///Creates a 2x2 matrix containing a rotation of `angle` (in radians). - from_angle(Raw(f32)) -> self, - - ///Creates a 2x2 matrix from a 3x3 matrix, discarding the 2nd row and column. - from_mat3(Wrapped(Mat3)) -> self, - - ///Creates a 2x2 matrix from a 3x3 matrix, discarding the 2nd row and column. - from_mat3a(Wrapped(Mat3A)) -> self, - - ///Returns the matrix column for the given `index`. - /// - ///# Panics - /// - ///Panics if `index` is greater than 1. - col(&self:Raw(usize)) -> Wrapped(Vec2), - - ///Returns the matrix row for the given `index`. - /// - ///# Panics - /// - ///Panics if `index` is greater than 1. - row(&self:Raw(usize)) -> Wrapped(Vec2), - - ///Returns `true` if, and only if, all elements are finite. - ///If any element is either `NaN`, positive or negative infinity, this will return `false`. - is_finite(&self:) -> Raw(bool), - - ///Returns `true` if any elements are `NaN`. - is_nan(&self:) -> Raw(bool), - - ///Returns the transpose of `self`. - transpose(&self:) -> self, - - ///Returns the determinant of `self`. - determinant(&self:) -> Raw(f32), - - ///Returns the inverse of `self`. - /// - ///If the matrix is not invertible the returned matrix will be invalid. - /// - ///# Panics - /// - ///Will panic if the determinant of `self` is zero when `glam_assert` is enabled. - inverse(&self:) -> self, - - ///Transforms a 2D vector. - mul_vec2(&self:Wrapped(Vec2)) -> Wrapped(Vec2), - - ///Multiplies two 2x2 matrices. - mul_mat2(&self:&self) -> self, - - ///Adds two 2x2 matrices. - add_mat2(&self:&self) -> self, - - ///Subtracts two 2x2 matrices. - sub_mat2(&self:&self) -> self, - - ///Multiplies a 2x2 matrix by a scalar. - mul_scalar(&self:Raw(f32)) -> self, - - ///Returns true if the absolute difference of all elements between `self` and `rhs` - ///is less than or equal to `max_abs_diff`. - /// - ///This can be used to compare if two matrices contain similar elements. It works best - ///when comparing with a known value. The `max_abs_diff` that should be used used - ///depends on the values being compared against. - /// - ///For more see - ///[comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - abs_diff_eq(&self:self,Raw(f32)) -> Raw(bool), - - as_dmat2(&self:) -> Wrapped(DMat2), - - ) - + Fields - ( - ) - + BinOps - ( - self Add self -> Wrapped(Mat2), - self Sub self -> Wrapped(Mat2), - self Mul Wrapped(Mat2) -> Wrapped(Mat2), - self Mul self -> Wrapped(Mat2), - self Mul Raw(f32) -> Wrapped(Mat2), - self Mul Wrapped(Vec2) -> Wrapped(Vec2), - ) - + UnaryOps - ( - Neg self -> self - ) - lua impl - { - - mut (MetaMethod::Index) => |ctx,s,idx : LuaIndex| { - Ok(LuaVec2::new_ref( - s.script_ref(ctx.get_world()?).sub_ref(ReflectPathElem::SubReflectionIndexed{ - label:"col", - index: *idx, - get: |idx,ref_| Err(ReflectionError::InsufficientProvenance{ - path: "".to_owned(), - msg: "Cannot get column of matrix with immutable reference".to_owned() - }), - get_mut: |idx, ref_| { - if ref_.is::(){ - Ok(ref_.downcast_mut::() - .unwrap() - .col_mut(idx)) - } else { - Err(ReflectionError::CannotDowncast{from: ref_.get_represented_type_info().unwrap().type_path().into(), to:"Mat2".into()}) - } - } - }) - ) - ) - } -; - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 3x3 column major matrix. - /// - ///This 3x3 matrix type features convenience methods for creating and using linear and - ///affine transformations. If you are primarily dealing with 2D affine transformations the - ///[`Affine2`](crate::Affine2) type is much faster and more space efficient than - ///using a 3x3 matrix. - /// - ///Linear transformations including 3D rotation and scale can be created using methods - ///such as [`Self::from_diagonal()`], [`Self::from_quat()`], [`Self::from_axis_angle()`], - ///[`Self::from_rotation_x()`], [`Self::from_rotation_y()`], or - ///[`Self::from_rotation_z()`]. - /// - ///The resulting matrices can be use to transform 3D vectors using regular vector - ///multiplication. - /// - ///Affine transformations including 2D translation, rotation and scale can be created - ///using methods such as [`Self::from_translation()`], [`Self::from_angle()`], - ///[`Self::from_scale()`] and [`Self::from_scale_angle_translation()`]. - /// - ///The [`Self::transform_point2()`] and [`Self::transform_vector2()`] convenience methods - ///are provided for performing affine transforms on 2D vectors and points. These multiply - ///2D inputs as 3D vectors with an implicit `z` value of `1` for points and `0` for - ///vectors respectively. These methods assume that `Self` contains a valid affine - ///transform. - glam::f32::Mat3A : - Clone + - Debug + - Methods - ( - ///Creates a 3x3 matrix from three column vectors. - from_cols(Wrapped(Vec3A),Wrapped(Vec3A),Wrapped(Vec3A)) -> self, - - ///Creates a 3x3 matrix with its diagonal set to `diagonal` and all other entries set to 0. - from_diagonal(Wrapped(Vec3)) -> self, - - ///Creates a 3x3 matrix from a 4x4 matrix, discarding the 4th row and column. - from_mat4(Wrapped(Mat4)) -> self, - - ///Creates a 3D rotation matrix from the given quaternion. - /// - ///# Panics - /// - ///Will panic if `rotation` is not normalized when `glam_assert` is enabled. - from_quat(Wrapped(Quat)) -> self, - - ///Creates a 3D rotation matrix from a normalized rotation `axis` and `angle` (in - ///radians). - /// - ///# Panics - /// - ///Will panic if `axis` is not normalized when `glam_assert` is enabled. - from_axis_angle(Wrapped(Vec3),Raw(f32)) -> self, - - ///Creates a 3D rotation matrix from the given euler rotation sequence and the angles (in - ///radians). - from_euler(Wrapped(EulerRot),Raw(f32),Raw(f32),Raw(f32)) -> self, - - ///Creates a 3D rotation matrix from `angle` (in radians) around the x axis. - from_rotation_x(Raw(f32)) -> self, - - ///Creates a 3D rotation matrix from `angle` (in radians) around the y axis. - from_rotation_y(Raw(f32)) -> self, - - ///Creates a 3D rotation matrix from `angle` (in radians) around the z axis. - from_rotation_z(Raw(f32)) -> self, - - ///Creates an affine transformation matrix from the given 2D `translation`. - /// - ///The resulting matrix can be used to transform 2D points and vectors. See - ///[`Self::transform_point2()`] and [`Self::transform_vector2()`]. - from_translation(Wrapped(Vec2)) -> self, - - ///Creates an affine transformation matrix from the given 2D rotation `angle` (in - ///radians). - /// - ///The resulting matrix can be used to transform 2D points and vectors. See - ///[`Self::transform_point2()`] and [`Self::transform_vector2()`]. - from_angle(Raw(f32)) -> self, - - ///Creates an affine transformation matrix from the given 2D `scale`, rotation `angle` (in - ///radians) and `translation`. - /// - ///The resulting matrix can be used to transform 2D points and vectors. See - ///[`Self::transform_point2()`] and [`Self::transform_vector2()`]. - from_scale_angle_translation(Wrapped(Vec2),Raw(f32),Wrapped(Vec2)) -> self, - - ///Creates an affine transformation matrix from the given non-uniform 2D `scale`. - /// - ///The resulting matrix can be used to transform 2D points and vectors. See - ///[`Self::transform_point2()`] and [`Self::transform_vector2()`]. - /// - ///# Panics - /// - ///Will panic if all elements of `scale` are zero when `glam_assert` is enabled. - from_scale(Wrapped(Vec2)) -> self, - - ///Creates an affine transformation matrix from the given 2x2 matrix. - /// - ///The resulting matrix can be used to transform 2D points and vectors. See - ///[`Self::transform_point2()`] and [`Self::transform_vector2()`]. - from_mat2(Wrapped(Mat2)) -> self, - - ///Returns the matrix column for the given `index`. - /// - ///# Panics - /// - ///Panics if `index` is greater than 2. - col(&self:Raw(usize)) -> Wrapped(Vec3A), - - ///Returns the matrix row for the given `index`. - /// - ///# Panics - /// - ///Panics if `index` is greater than 2. - row(&self:Raw(usize)) -> Wrapped(Vec3A), - - ///Returns `true` if, and only if, all elements are finite. - ///If any element is either `NaN`, positive or negative infinity, this will return `false`. - is_finite(&self:) -> Raw(bool), - - ///Returns `true` if any elements are `NaN`. - is_nan(&self:) -> Raw(bool), - - ///Returns the transpose of `self`. - transpose(&self:) -> self, - - ///Returns the determinant of `self`. - determinant(&self:) -> Raw(f32), - - ///Returns the inverse of `self`. - /// - ///If the matrix is not invertible the returned matrix will be invalid. - /// - ///# Panics - /// - ///Will panic if the determinant of `self` is zero when `glam_assert` is enabled. - inverse(&self:) -> self, - - ///Transforms the given 2D vector as a point. - /// - ///This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `1`. - /// - ///This method assumes that `self` contains a valid affine transform. - /// - ///# Panics - /// - ///Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled. - transform_point2(&self:Wrapped(Vec2)) -> Wrapped(Vec2), - - ///Rotates the given 2D vector. - /// - ///This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `0`. - /// - ///This method assumes that `self` contains a valid affine transform. - /// - ///# Panics - /// - ///Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled. - transform_vector2(&self:Wrapped(Vec2)) -> Wrapped(Vec2), - - ///Transforms a 3D vector. - mul_vec3(&self:Wrapped(Vec3)) -> Wrapped(Vec3), - - ///Transforms a [`Vec3A`]. - mul_vec3a(&self:Wrapped(Vec3A)) -> Wrapped(Vec3A), - - ///Multiplies two 3x3 matrices. - mul_mat3(&self:&self) -> self, - - ///Adds two 3x3 matrices. - add_mat3(&self:&self) -> self, - - ///Subtracts two 3x3 matrices. - sub_mat3(&self:&self) -> self, - - ///Multiplies a 3x3 matrix by a scalar. - mul_scalar(&self:Raw(f32)) -> self, - - ///Returns true if the absolute difference of all elements between `self` and `rhs` - ///is less than or equal to `max_abs_diff`. - /// - ///This can be used to compare if two matrices contain similar elements. It works best - ///when comparing with a known value. The `max_abs_diff` that should be used used - ///depends on the values being compared against. - /// - ///For more see - ///[comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - abs_diff_eq(&self:self,Raw(f32)) -> Raw(bool), - - as_dmat3(&self:) -> Wrapped(DMat3), - - ) - + Fields - ( - x_axis: Wrapped(Vec3A), - y_axis: Wrapped(Vec3A), - z_axis: Wrapped(Vec3A), - ) - + BinOps - ( - self Add self -> Wrapped(Mat3A), - self Sub self -> Wrapped(Mat3A), - self Mul self -> Wrapped(Mat3A), - self Mul Wrapped(Affine2) -> Wrapped(Mat3A), - self Mul Wrapped(Vec3) -> Wrapped(Vec3), - self Mul Raw(f32) -> Wrapped(Mat3A), - self Mul Wrapped(Vec3A) -> Wrapped(Vec3A), - self Mul Wrapped(Mat3A) -> Wrapped(Mat3A), - ) - + UnaryOps - ( - Neg self -> self - ) - lua impl - { - - mut (MetaMethod::Index) => |ctx,s,idx : LuaIndex| { - Ok(LuaVec3A::new_ref( - s.script_ref(ctx.get_world()?).sub_ref(ReflectPathElem::SubReflectionIndexed{ - label:"col", - index: *idx, - get: |idx,ref_| Err(ReflectionError::InsufficientProvenance{ - path: "".to_owned(), - msg: "Cannot get column of matrix with immutable reference".to_owned() - }), - get_mut: |idx, ref_| { - if ref_.is::(){ - Ok(ref_.downcast_mut::() - .unwrap() - .col_mut(idx)) - } else { - Err(ReflectionError::CannotDowncast{from: ref_.get_represented_type_info().unwrap().type_path().into(), to:"Mat3A".into()}) - } - } - }) - ) - ) - } -; - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 4x4 column major matrix. - /// - ///This 4x4 matrix type features convenience methods for creating and using affine transforms and - ///perspective projections. If you are primarily dealing with 3D affine transformations - ///considering using [`Affine3A`](crate::Affine3A) which is faster than a 4x4 matrix - ///for some affine operations. - /// - ///Affine transformations including 3D translation, rotation and scale can be created - ///using methods such as [`Self::from_translation()`], [`Self::from_quat()`], - ///[`Self::from_scale()`] and [`Self::from_scale_rotation_translation()`]. - /// - ///Orthographic projections can be created using the methods [`Self::orthographic_lh()`] for - ///left-handed coordinate systems and [`Self::orthographic_rh()`] for right-handed - ///systems. The resulting matrix is also an affine transformation. - /// - ///The [`Self::transform_point3()`] and [`Self::transform_vector3()`] convenience methods - ///are provided for performing affine transformations on 3D vectors and points. These - ///multiply 3D inputs as 4D vectors with an implicit `w` value of `1` for points and `0` - ///for vectors respectively. These methods assume that `Self` contains a valid affine - ///transform. - /// - ///Perspective projections can be created using methods such as - ///[`Self::perspective_lh()`], [`Self::perspective_infinite_lh()`] and - ///[`Self::perspective_infinite_reverse_lh()`] for left-handed co-ordinate systems and - ///[`Self::perspective_rh()`], [`Self::perspective_infinite_rh()`] and - ///[`Self::perspective_infinite_reverse_rh()`] for right-handed co-ordinate systems. - /// - ///The resulting perspective project can be use to transform 3D vectors as points with - ///perspective correction using the [`Self::project_point3()`] convenience method. - glam::f32::Mat4 : - Clone + - Debug + - Methods - ( - ///Creates a 4x4 matrix from four column vectors. - from_cols(Wrapped(Vec4),Wrapped(Vec4),Wrapped(Vec4),Wrapped(Vec4)) -> self, - - ///Creates a 4x4 matrix with its diagonal set to `diagonal` and all other entries set to 0. - from_diagonal(Wrapped(Vec4)) -> self, - - ///Creates an affine transformation matrix from the given 3D `scale`, `rotation` and - ///`translation`. - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - /// - ///# Panics - /// - ///Will panic if `rotation` is not normalized when `glam_assert` is enabled. - from_scale_rotation_translation(Wrapped(Vec3),Wrapped(Quat),Wrapped(Vec3)) -> self, - - ///Creates an affine transformation matrix from the given 3D `translation`. - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - /// - ///# Panics - /// - ///Will panic if `rotation` is not normalized when `glam_assert` is enabled. - from_rotation_translation(Wrapped(Quat),Wrapped(Vec3)) -> self, - - ///Creates an affine transformation matrix from the given `rotation` quaternion. - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - /// - ///# Panics - /// - ///Will panic if `rotation` is not normalized when `glam_assert` is enabled. - from_quat(Wrapped(Quat)) -> self, - - ///Creates an affine transformation matrix from the given 3x3 linear transformation - ///matrix. - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - from_mat3(Wrapped(Mat3)) -> self, - - ///Creates an affine transformation matrix from the given 3x3 linear transformation - ///matrix. - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - from_mat3a(Wrapped(Mat3A)) -> self, - - ///Creates an affine transformation matrix from the given 3D `translation`. - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - from_translation(Wrapped(Vec3)) -> self, - - ///Creates an affine transformation matrix containing a 3D rotation around a normalized - ///rotation `axis` of `angle` (in radians). - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - /// - ///# Panics - /// - ///Will panic if `axis` is not normalized when `glam_assert` is enabled. - from_axis_angle(Wrapped(Vec3),Raw(f32)) -> self, - - ///Creates a affine transformation matrix containing a rotation from the given euler - ///rotation sequence and angles (in radians). - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - from_euler(Wrapped(EulerRot),Raw(f32),Raw(f32),Raw(f32)) -> self, - - ///Creates an affine transformation matrix containing a 3D rotation around the x axis of - ///`angle` (in radians). - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - from_rotation_x(Raw(f32)) -> self, - - ///Creates an affine transformation matrix containing a 3D rotation around the y axis of - ///`angle` (in radians). - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - from_rotation_y(Raw(f32)) -> self, - - ///Creates an affine transformation matrix containing a 3D rotation around the z axis of - ///`angle` (in radians). - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - from_rotation_z(Raw(f32)) -> self, - - ///Creates an affine transformation matrix containing the given 3D non-uniform `scale`. - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - /// - ///# Panics - /// - ///Will panic if all elements of `scale` are zero when `glam_assert` is enabled. - from_scale(Wrapped(Vec3)) -> self, - - ///Returns the matrix column for the given `index`. - /// - ///# Panics - /// - ///Panics if `index` is greater than 3. - col(&self:Raw(usize)) -> Wrapped(Vec4), - - ///Returns the matrix row for the given `index`. - /// - ///# Panics - /// - ///Panics if `index` is greater than 3. - row(&self:Raw(usize)) -> Wrapped(Vec4), - - ///Returns `true` if, and only if, all elements are finite. - ///If any element is either `NaN`, positive or negative infinity, this will return `false`. - is_finite(&self:) -> Raw(bool), - - ///Returns `true` if any elements are `NaN`. - is_nan(&self:) -> Raw(bool), - - ///Returns the transpose of `self`. - transpose(&self:) -> self, - - ///Returns the determinant of `self`. - determinant(&self:) -> Raw(f32), - - ///Returns the inverse of `self`. - /// - ///If the matrix is not invertible the returned matrix will be invalid. - /// - ///# Panics - /// - ///Will panic if the determinant of `self` is zero when `glam_assert` is enabled. - inverse(&self:) -> self, - - ///Creates a left-handed view matrix using a camera position, an up direction, and a facing - ///direction. - /// - ///For a view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`. - look_to_lh(Wrapped(Vec3),Wrapped(Vec3),Wrapped(Vec3)) -> self, - - ///Creates a right-handed view matrix using a camera position, an up direction, and a facing - ///direction. - /// - ///For a view coordinate system with `+X=right`, `+Y=up` and `+Z=back`. - look_to_rh(Wrapped(Vec3),Wrapped(Vec3),Wrapped(Vec3)) -> self, - - ///Creates a left-handed view matrix using a camera position, an up direction, and a focal - ///point. - ///For a view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`. - /// - ///# Panics - /// - ///Will panic if `up` is not normalized when `glam_assert` is enabled. - look_at_lh(Wrapped(Vec3),Wrapped(Vec3),Wrapped(Vec3)) -> self, - - ///Creates a right-handed view matrix using a camera position, an up direction, and a focal - ///point. - ///For a view coordinate system with `+X=right`, `+Y=up` and `+Z=back`. - /// - ///# Panics - /// - ///Will panic if `up` is not normalized when `glam_assert` is enabled. - look_at_rh(Wrapped(Vec3),Wrapped(Vec3),Wrapped(Vec3)) -> self, - - ///Creates a right-handed perspective projection matrix with [-1,1] depth range. - ///This is the same as the OpenGL `gluPerspective` function. - ///See - perspective_rh_gl(Raw(f32),Raw(f32),Raw(f32),Raw(f32)) -> self, - - ///Creates a left-handed perspective projection matrix with `[0,1]` depth range. - /// - ///# Panics - /// - ///Will panic if `z_near` or `z_far` are less than or equal to zero when `glam_assert` is - ///enabled. - perspective_lh(Raw(f32),Raw(f32),Raw(f32),Raw(f32)) -> self, - - ///Creates a right-handed perspective projection matrix with `[0,1]` depth range. - /// - ///# Panics - /// - ///Will panic if `z_near` or `z_far` are less than or equal to zero when `glam_assert` is - ///enabled. - perspective_rh(Raw(f32),Raw(f32),Raw(f32),Raw(f32)) -> self, - - ///Creates an infinite left-handed perspective projection matrix with `[0,1]` depth range. - /// - ///# Panics - /// - ///Will panic if `z_near` is less than or equal to zero when `glam_assert` is enabled. - perspective_infinite_lh(Raw(f32),Raw(f32),Raw(f32)) -> self, - - ///Creates an infinite left-handed perspective projection matrix with `[0,1]` depth range. - /// - ///# Panics - /// - ///Will panic if `z_near` is less than or equal to zero when `glam_assert` is enabled. - perspective_infinite_reverse_lh(Raw(f32),Raw(f32),Raw(f32)) -> self, - - ///Creates an infinite right-handed perspective projection matrix with - ///`[0,1]` depth range. - perspective_infinite_rh(Raw(f32),Raw(f32),Raw(f32)) -> self, - - ///Creates an infinite reverse right-handed perspective projection matrix - ///with `[0,1]` depth range. - perspective_infinite_reverse_rh(Raw(f32),Raw(f32),Raw(f32)) -> self, - - ///Creates a right-handed orthographic projection matrix with `[-1,1]` depth - ///range. This is the same as the OpenGL `glOrtho` function in OpenGL. - ///See - /// - orthographic_rh_gl(Raw(f32),Raw(f32),Raw(f32),Raw(f32),Raw(f32),Raw(f32)) -> self, - - ///Creates a left-handed orthographic projection matrix with `[0,1]` depth range. - orthographic_lh(Raw(f32),Raw(f32),Raw(f32),Raw(f32),Raw(f32),Raw(f32)) -> self, - - ///Creates a right-handed orthographic projection matrix with `[0,1]` depth range. - orthographic_rh(Raw(f32),Raw(f32),Raw(f32),Raw(f32),Raw(f32),Raw(f32)) -> self, - - ///Transforms the given 3D vector as a point, applying perspective correction. - /// - ///This is the equivalent of multiplying the 3D vector as a 4D vector where `w` is `1.0`. - ///The perspective divide is performed meaning the resulting 3D vector is divided by `w`. - /// - ///This method assumes that `self` contains a projective transform. - project_point3(&self:Wrapped(Vec3)) -> Wrapped(Vec3), - - ///Transforms the given 3D vector as a point. - /// - ///This is the equivalent of multiplying the 3D vector as a 4D vector where `w` is - ///`1.0`. - /// - ///This method assumes that `self` contains a valid affine transform. It does not perform - ///a persective divide, if `self` contains a perspective transform, or if you are unsure, - ///the [`Self::project_point3()`] method should be used instead. - /// - ///# Panics - /// - ///Will panic if the 3rd row of `self` is not `(0, 0, 0, 1)` when `glam_assert` is enabled. - transform_point3(&self:Wrapped(Vec3)) -> Wrapped(Vec3), - - ///Transforms the give 3D vector as a direction. - /// - ///This is the equivalent of multiplying the 3D vector as a 4D vector where `w` is - ///`0.0`. - /// - ///This method assumes that `self` contains a valid affine transform. - /// - ///# Panics - /// - ///Will panic if the 3rd row of `self` is not `(0, 0, 0, 1)` when `glam_assert` is enabled. - transform_vector3(&self:Wrapped(Vec3)) -> Wrapped(Vec3), - - ///Transforms the given [`Vec3A`] as 3D point. - /// - ///This is the equivalent of multiplying the [`Vec3A`] as a 4D vector where `w` is `1.0`. - transform_point3a(&self:Wrapped(Vec3A)) -> Wrapped(Vec3A), - - ///Transforms the give [`Vec3A`] as 3D vector. - /// - ///This is the equivalent of multiplying the [`Vec3A`] as a 4D vector where `w` is `0.0`. - transform_vector3a(&self:Wrapped(Vec3A)) -> Wrapped(Vec3A), - - ///Transforms a 4D vector. - mul_vec4(&self:Wrapped(Vec4)) -> Wrapped(Vec4), - - ///Multiplies two 4x4 matrices. - mul_mat4(&self:&self) -> self, - - ///Adds two 4x4 matrices. - add_mat4(&self:&self) -> self, - - ///Subtracts two 4x4 matrices. - sub_mat4(&self:&self) -> self, - - ///Multiplies a 4x4 matrix by a scalar. - mul_scalar(&self:Raw(f32)) -> self, - - ///Returns true if the absolute difference of all elements between `self` and `rhs` - ///is less than or equal to `max_abs_diff`. - /// - ///This can be used to compare if two matrices contain similar elements. It works best - ///when comparing with a known value. The `max_abs_diff` that should be used used - ///depends on the values being compared against. - /// - ///For more see - ///[comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - abs_diff_eq(&self:self,Raw(f32)) -> Raw(bool), - - as_dmat4(&self:) -> Wrapped(DMat4), - - ) - + Fields - ( - x_axis: Wrapped(Vec4), - y_axis: Wrapped(Vec4), - z_axis: Wrapped(Vec4), - w_axis: Wrapped(Vec4), - ) - + BinOps - ( - self Add self -> Wrapped(Mat4), - self Sub self -> Wrapped(Mat4), - self Mul Wrapped(Vec4) -> Wrapped(Vec4), - self Mul Wrapped(Affine3A) -> Wrapped(Mat4), - self Mul Raw(f32) -> Wrapped(Mat4), - self Mul self -> Wrapped(Mat4), - self Mul Wrapped(Mat4) -> Wrapped(Mat4), - ) - + UnaryOps - ( - Neg self -> self - ) - lua impl - { - - mut (MetaMethod::Index) => |ctx,s,idx : LuaIndex| { - Ok(LuaVec4::new_ref( - s.script_ref(ctx.get_world()?).sub_ref(ReflectPathElem::SubReflectionIndexed{ - label:"col", - index: *idx, - get: |idx,ref_| Err(ReflectionError::InsufficientProvenance{ - path: "".to_owned(), - msg: "Cannot get column of matrix with immutable reference".to_owned() - }), - get_mut: |idx, ref_| { - if ref_.is::(){ - Ok(ref_.downcast_mut::() - .unwrap() - .col_mut(idx)) - } else { - Err(ReflectionError::CannotDowncast{from: ref_.get_represented_type_info().unwrap().type_path().into(), to:"Mat4".into()}) - } - } - }) - ) - ) - } -; - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 2x2 column major matrix. - glam::f64::DMat2 : - Clone + - Debug + - Methods - ( - ///Creates a 2x2 matrix from two column vectors. - from_cols(Wrapped(DVec2),Wrapped(DVec2)) -> self, - - ///Creates a 2x2 matrix with its diagonal set to `diagonal` and all other entries set to 0. - from_diagonal(Wrapped(DVec2)) -> self, - - ///Creates a 2x2 matrix containing the combining non-uniform `scale` and rotation of - ///`angle` (in radians). - from_scale_angle(Wrapped(DVec2),Raw(f64)) -> self, - - ///Creates a 2x2 matrix containing a rotation of `angle` (in radians). - from_angle(Raw(f64)) -> self, - - ///Creates a 2x2 matrix from a 3x3 matrix, discarding the 2nd row and column. - from_mat3(Wrapped(DMat3)) -> self, - - ///Returns the matrix column for the given `index`. - /// - ///# Panics - /// - ///Panics if `index` is greater than 1. - col(&self:Raw(usize)) -> Wrapped(DVec2), - - ///Returns the matrix row for the given `index`. - /// - ///# Panics - /// - ///Panics if `index` is greater than 1. - row(&self:Raw(usize)) -> Wrapped(DVec2), - - ///Returns `true` if, and only if, all elements are finite. - ///If any element is either `NaN`, positive or negative infinity, this will return `false`. - is_finite(&self:) -> Raw(bool), - - ///Returns `true` if any elements are `NaN`. - is_nan(&self:) -> Raw(bool), - - ///Returns the transpose of `self`. - transpose(&self:) -> self, - - ///Returns the determinant of `self`. - determinant(&self:) -> Raw(f64), - - ///Returns the inverse of `self`. - /// - ///If the matrix is not invertible the returned matrix will be invalid. - /// - ///# Panics - /// - ///Will panic if the determinant of `self` is zero when `glam_assert` is enabled. - inverse(&self:) -> self, - - ///Transforms a 2D vector. - mul_vec2(&self:Wrapped(DVec2)) -> Wrapped(DVec2), - - ///Multiplies two 2x2 matrices. - mul_mat2(&self:&self) -> self, - - ///Adds two 2x2 matrices. - add_mat2(&self:&self) -> self, - - ///Subtracts two 2x2 matrices. - sub_mat2(&self:&self) -> self, - - ///Multiplies a 2x2 matrix by a scalar. - mul_scalar(&self:Raw(f64)) -> self, - - ///Returns true if the absolute difference of all elements between `self` and `rhs` - ///is less than or equal to `max_abs_diff`. - /// - ///This can be used to compare if two matrices contain similar elements. It works best - ///when comparing with a known value. The `max_abs_diff` that should be used used - ///depends on the values being compared against. - /// - ///For more see - ///[comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - abs_diff_eq(&self:self,Raw(f64)) -> Raw(bool), - - as_mat2(&self:) -> Wrapped(Mat2), - - ) - + Fields - ( - x_axis: Wrapped(DVec2), - y_axis: Wrapped(DVec2), - ) - + BinOps - ( - self Add self -> Wrapped(DMat2), - self Sub self -> Wrapped(DMat2), - self Mul self -> Wrapped(DMat2), - self Mul Wrapped(DMat2) -> Wrapped(DMat2), - self Mul Wrapped(DVec2) -> Wrapped(DVec2), - self Mul Raw(f64) -> Wrapped(DMat2), - ) - + UnaryOps - ( - Neg self -> self - ) - lua impl - { - - mut (MetaMethod::Index) => |ctx,s,idx : LuaIndex| { - Ok(LuaDVec2::new_ref( - s.script_ref(ctx.get_world()?).sub_ref(ReflectPathElem::SubReflectionIndexed{ - label:"col", - index: *idx, - get: |idx,ref_| Err(ReflectionError::InsufficientProvenance{ - path: "".to_owned(), - msg: "Cannot get column of matrix with immutable reference".to_owned() - }), - get_mut: |idx, ref_| { - if ref_.is::(){ - Ok(ref_.downcast_mut::() - .unwrap() - .col_mut(idx)) - } else { - Err(ReflectionError::CannotDowncast{from: ref_.get_represented_type_info().unwrap().type_path().into(), to:"DMat2".into()}) - } - } - }) - ) - ) - } -; - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 3x3 column major matrix. - /// - ///This 3x3 matrix type features convenience methods for creating and using linear and - ///affine transformations. If you are primarily dealing with 2D affine transformations the - ///[`DAffine2`](crate::DAffine2) type is much faster and more space efficient than - ///using a 3x3 matrix. - /// - ///Linear transformations including 3D rotation and scale can be created using methods - ///such as [`Self::from_diagonal()`], [`Self::from_quat()`], [`Self::from_axis_angle()`], - ///[`Self::from_rotation_x()`], [`Self::from_rotation_y()`], or - ///[`Self::from_rotation_z()`]. - /// - ///The resulting matrices can be use to transform 3D vectors using regular vector - ///multiplication. - /// - ///Affine transformations including 2D translation, rotation and scale can be created - ///using methods such as [`Self::from_translation()`], [`Self::from_angle()`], - ///[`Self::from_scale()`] and [`Self::from_scale_angle_translation()`]. - /// - ///The [`Self::transform_point2()`] and [`Self::transform_vector2()`] convenience methods - ///are provided for performing affine transforms on 2D vectors and points. These multiply - ///2D inputs as 3D vectors with an implicit `z` value of `1` for points and `0` for - ///vectors respectively. These methods assume that `Self` contains a valid affine - ///transform. - glam::f64::DMat3 : - Clone + - Debug + - Methods - ( - ///Creates a 3x3 matrix from three column vectors. - from_cols(Wrapped(DVec3),Wrapped(DVec3),Wrapped(DVec3)) -> self, - - ///Creates a 3x3 matrix with its diagonal set to `diagonal` and all other entries set to 0. - from_diagonal(Wrapped(DVec3)) -> self, - - ///Creates a 3x3 matrix from a 4x4 matrix, discarding the 4th row and column. - from_mat4(Wrapped(DMat4)) -> self, - - ///Creates a 3D rotation matrix from the given quaternion. - /// - ///# Panics - /// - ///Will panic if `rotation` is not normalized when `glam_assert` is enabled. - from_quat(Wrapped(DQuat)) -> self, - - ///Creates a 3D rotation matrix from a normalized rotation `axis` and `angle` (in - ///radians). - /// - ///# Panics - /// - ///Will panic if `axis` is not normalized when `glam_assert` is enabled. - from_axis_angle(Wrapped(DVec3),Raw(f64)) -> self, - - ///Creates a 3D rotation matrix from the given euler rotation sequence and the angles (in - ///radians). - from_euler(Wrapped(EulerRot),Raw(f64),Raw(f64),Raw(f64)) -> self, - - ///Creates a 3D rotation matrix from `angle` (in radians) around the x axis. - from_rotation_x(Raw(f64)) -> self, - - ///Creates a 3D rotation matrix from `angle` (in radians) around the y axis. - from_rotation_y(Raw(f64)) -> self, - - ///Creates a 3D rotation matrix from `angle` (in radians) around the z axis. - from_rotation_z(Raw(f64)) -> self, - - ///Creates an affine transformation matrix from the given 2D `translation`. - /// - ///The resulting matrix can be used to transform 2D points and vectors. See - ///[`Self::transform_point2()`] and [`Self::transform_vector2()`]. - from_translation(Wrapped(DVec2)) -> self, - - ///Creates an affine transformation matrix from the given 2D rotation `angle` (in - ///radians). - /// - ///The resulting matrix can be used to transform 2D points and vectors. See - ///[`Self::transform_point2()`] and [`Self::transform_vector2()`]. - from_angle(Raw(f64)) -> self, - - ///Creates an affine transformation matrix from the given 2D `scale`, rotation `angle` (in - ///radians) and `translation`. - /// - ///The resulting matrix can be used to transform 2D points and vectors. See - ///[`Self::transform_point2()`] and [`Self::transform_vector2()`]. - from_scale_angle_translation(Wrapped(DVec2),Raw(f64),Wrapped(DVec2)) -> self, - - ///Creates an affine transformation matrix from the given non-uniform 2D `scale`. - /// - ///The resulting matrix can be used to transform 2D points and vectors. See - ///[`Self::transform_point2()`] and [`Self::transform_vector2()`]. - /// - ///# Panics - /// - ///Will panic if all elements of `scale` are zero when `glam_assert` is enabled. - from_scale(Wrapped(DVec2)) -> self, - - ///Creates an affine transformation matrix from the given 2x2 matrix. - /// - ///The resulting matrix can be used to transform 2D points and vectors. See - ///[`Self::transform_point2()`] and [`Self::transform_vector2()`]. - from_mat2(Wrapped(DMat2)) -> self, - - ///Returns the matrix column for the given `index`. - /// - ///# Panics - /// - ///Panics if `index` is greater than 2. - col(&self:Raw(usize)) -> Wrapped(DVec3), - - ///Returns the matrix row for the given `index`. - /// - ///# Panics - /// - ///Panics if `index` is greater than 2. - row(&self:Raw(usize)) -> Wrapped(DVec3), - - ///Returns `true` if, and only if, all elements are finite. - ///If any element is either `NaN`, positive or negative infinity, this will return `false`. - is_finite(&self:) -> Raw(bool), - - ///Returns `true` if any elements are `NaN`. - is_nan(&self:) -> Raw(bool), - - ///Returns the transpose of `self`. - transpose(&self:) -> self, - - ///Returns the determinant of `self`. - determinant(&self:) -> Raw(f64), - - ///Returns the inverse of `self`. - /// - ///If the matrix is not invertible the returned matrix will be invalid. - /// - ///# Panics - /// - ///Will panic if the determinant of `self` is zero when `glam_assert` is enabled. - inverse(&self:) -> self, - - ///Transforms the given 2D vector as a point. - /// - ///This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `1`. - /// - ///This method assumes that `self` contains a valid affine transform. - /// - ///# Panics - /// - ///Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled. - transform_point2(&self:Wrapped(DVec2)) -> Wrapped(DVec2), - - ///Rotates the given 2D vector. - /// - ///This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `0`. - /// - ///This method assumes that `self` contains a valid affine transform. - /// - ///# Panics - /// - ///Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled. - transform_vector2(&self:Wrapped(DVec2)) -> Wrapped(DVec2), - - ///Transforms a 3D vector. - mul_vec3(&self:Wrapped(DVec3)) -> Wrapped(DVec3), - - ///Multiplies two 3x3 matrices. - mul_mat3(&self:&self) -> self, - - ///Adds two 3x3 matrices. - add_mat3(&self:&self) -> self, - - ///Subtracts two 3x3 matrices. - sub_mat3(&self:&self) -> self, - - ///Multiplies a 3x3 matrix by a scalar. - mul_scalar(&self:Raw(f64)) -> self, - - ///Returns true if the absolute difference of all elements between `self` and `rhs` - ///is less than or equal to `max_abs_diff`. - /// - ///This can be used to compare if two matrices contain similar elements. It works best - ///when comparing with a known value. The `max_abs_diff` that should be used used - ///depends on the values being compared against. - /// - ///For more see - ///[comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - abs_diff_eq(&self:self,Raw(f64)) -> Raw(bool), - - as_mat3(&self:) -> Wrapped(Mat3), - - ) - + Fields - ( - x_axis: Wrapped(DVec3), - y_axis: Wrapped(DVec3), - z_axis: Wrapped(DVec3), - ) - + BinOps - ( - self Add self -> Wrapped(DMat3), - self Sub self -> Wrapped(DMat3), - self Mul Raw(f64) -> Wrapped(DMat3), - self Mul Wrapped(DAffine2) -> Wrapped(DMat3), - self Mul self -> Wrapped(DMat3), - self Mul Wrapped(DMat3) -> Wrapped(DMat3), - self Mul Wrapped(DVec3) -> Wrapped(DVec3), - ) - + UnaryOps - ( - Neg self -> self - ) - lua impl - { - - mut (MetaMethod::Index) => |ctx,s,idx : LuaIndex| { - Ok(LuaDVec3::new_ref( - s.script_ref(ctx.get_world()?).sub_ref(ReflectPathElem::SubReflectionIndexed{ - label:"col", - index: *idx, - get: |idx,ref_| Err(ReflectionError::InsufficientProvenance{ - path: "".to_owned(), - msg: "Cannot get column of matrix with immutable reference".to_owned() - }), - get_mut: |idx, ref_| { - if ref_.is::(){ - Ok(ref_.downcast_mut::() - .unwrap() - .col_mut(idx)) - } else { - Err(ReflectionError::CannotDowncast{from: ref_.get_represented_type_info().unwrap().type_path().into(), to:"DMat3".into()}) - } - } - }) - ) - ) - } -; - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 4x4 column major matrix. - /// - ///This 4x4 matrix type features convenience methods for creating and using affine transforms and - ///perspective projections. If you are primarily dealing with 3D affine transformations - ///considering using [`DAffine3`](crate::DAffine3) which is faster than a 4x4 matrix - ///for some affine operations. - /// - ///Affine transformations including 3D translation, rotation and scale can be created - ///using methods such as [`Self::from_translation()`], [`Self::from_quat()`], - ///[`Self::from_scale()`] and [`Self::from_scale_rotation_translation()`]. - /// - ///Orthographic projections can be created using the methods [`Self::orthographic_lh()`] for - ///left-handed coordinate systems and [`Self::orthographic_rh()`] for right-handed - ///systems. The resulting matrix is also an affine transformation. - /// - ///The [`Self::transform_point3()`] and [`Self::transform_vector3()`] convenience methods - ///are provided for performing affine transformations on 3D vectors and points. These - ///multiply 3D inputs as 4D vectors with an implicit `w` value of `1` for points and `0` - ///for vectors respectively. These methods assume that `Self` contains a valid affine - ///transform. - /// - ///Perspective projections can be created using methods such as - ///[`Self::perspective_lh()`], [`Self::perspective_infinite_lh()`] and - ///[`Self::perspective_infinite_reverse_lh()`] for left-handed co-ordinate systems and - ///[`Self::perspective_rh()`], [`Self::perspective_infinite_rh()`] and - ///[`Self::perspective_infinite_reverse_rh()`] for right-handed co-ordinate systems. - /// - ///The resulting perspective project can be use to transform 3D vectors as points with - ///perspective correction using the [`Self::project_point3()`] convenience method. - glam::f64::DMat4 : - Clone + - Debug + - Methods - ( - ///Creates a 4x4 matrix from four column vectors. - from_cols(Wrapped(DVec4),Wrapped(DVec4),Wrapped(DVec4),Wrapped(DVec4)) -> self, - - ///Creates a 4x4 matrix with its diagonal set to `diagonal` and all other entries set to 0. - from_diagonal(Wrapped(DVec4)) -> self, - - ///Creates an affine transformation matrix from the given 3D `scale`, `rotation` and - ///`translation`. - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - /// - ///# Panics - /// - ///Will panic if `rotation` is not normalized when `glam_assert` is enabled. - from_scale_rotation_translation(Wrapped(DVec3),Wrapped(DQuat),Wrapped(DVec3)) -> self, - - ///Creates an affine transformation matrix from the given 3D `translation`. - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - /// - ///# Panics - /// - ///Will panic if `rotation` is not normalized when `glam_assert` is enabled. - from_rotation_translation(Wrapped(DQuat),Wrapped(DVec3)) -> self, - - ///Creates an affine transformation matrix from the given `rotation` quaternion. - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - /// - ///# Panics - /// - ///Will panic if `rotation` is not normalized when `glam_assert` is enabled. - from_quat(Wrapped(DQuat)) -> self, - - ///Creates an affine transformation matrix from the given 3x3 linear transformation - ///matrix. - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - from_mat3(Wrapped(DMat3)) -> self, - - ///Creates an affine transformation matrix from the given 3D `translation`. - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - from_translation(Wrapped(DVec3)) -> self, - - ///Creates an affine transformation matrix containing a 3D rotation around a normalized - ///rotation `axis` of `angle` (in radians). - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - /// - ///# Panics - /// - ///Will panic if `axis` is not normalized when `glam_assert` is enabled. - from_axis_angle(Wrapped(DVec3),Raw(f64)) -> self, - - ///Creates a affine transformation matrix containing a rotation from the given euler - ///rotation sequence and angles (in radians). - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - from_euler(Wrapped(EulerRot),Raw(f64),Raw(f64),Raw(f64)) -> self, - - ///Creates an affine transformation matrix containing a 3D rotation around the x axis of - ///`angle` (in radians). - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - from_rotation_x(Raw(f64)) -> self, - - ///Creates an affine transformation matrix containing a 3D rotation around the y axis of - ///`angle` (in radians). - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - from_rotation_y(Raw(f64)) -> self, - - ///Creates an affine transformation matrix containing a 3D rotation around the z axis of - ///`angle` (in radians). - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - from_rotation_z(Raw(f64)) -> self, - - ///Creates an affine transformation matrix containing the given 3D non-uniform `scale`. - /// - ///The resulting matrix can be used to transform 3D points and vectors. See - ///[`Self::transform_point3()`] and [`Self::transform_vector3()`]. - /// - ///# Panics - /// - ///Will panic if all elements of `scale` are zero when `glam_assert` is enabled. - from_scale(Wrapped(DVec3)) -> self, - - ///Returns the matrix column for the given `index`. - /// - ///# Panics - /// - ///Panics if `index` is greater than 3. - col(&self:Raw(usize)) -> Wrapped(DVec4), - - ///Returns the matrix row for the given `index`. - /// - ///# Panics - /// - ///Panics if `index` is greater than 3. - row(&self:Raw(usize)) -> Wrapped(DVec4), - - ///Returns `true` if, and only if, all elements are finite. - ///If any element is either `NaN`, positive or negative infinity, this will return `false`. - is_finite(&self:) -> Raw(bool), - - ///Returns `true` if any elements are `NaN`. - is_nan(&self:) -> Raw(bool), - - ///Returns the transpose of `self`. - transpose(&self:) -> self, - - ///Returns the determinant of `self`. - determinant(&self:) -> Raw(f64), - - ///Returns the inverse of `self`. - /// - ///If the matrix is not invertible the returned matrix will be invalid. - /// - ///# Panics - /// - ///Will panic if the determinant of `self` is zero when `glam_assert` is enabled. - inverse(&self:) -> self, - - ///Creates a left-handed view matrix using a camera position, an up direction, and a facing - ///direction. - /// - ///For a view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`. - look_to_lh(Wrapped(DVec3),Wrapped(DVec3),Wrapped(DVec3)) -> self, - - ///Creates a right-handed view matrix using a camera position, an up direction, and a facing - ///direction. - /// - ///For a view coordinate system with `+X=right`, `+Y=up` and `+Z=back`. - look_to_rh(Wrapped(DVec3),Wrapped(DVec3),Wrapped(DVec3)) -> self, - - ///Creates a left-handed view matrix using a camera position, an up direction, and a focal - ///point. - ///For a view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`. - /// - ///# Panics - /// - ///Will panic if `up` is not normalized when `glam_assert` is enabled. - look_at_lh(Wrapped(DVec3),Wrapped(DVec3),Wrapped(DVec3)) -> self, - - ///Creates a right-handed view matrix using a camera position, an up direction, and a focal - ///point. - ///For a view coordinate system with `+X=right`, `+Y=up` and `+Z=back`. - /// - ///# Panics - /// - ///Will panic if `up` is not normalized when `glam_assert` is enabled. - look_at_rh(Wrapped(DVec3),Wrapped(DVec3),Wrapped(DVec3)) -> self, - - ///Creates a right-handed perspective projection matrix with [-1,1] depth range. - ///This is the same as the OpenGL `gluPerspective` function. - ///See - perspective_rh_gl(Raw(f64),Raw(f64),Raw(f64),Raw(f64)) -> self, - - ///Creates a left-handed perspective projection matrix with `[0,1]` depth range. - /// - ///# Panics - /// - ///Will panic if `z_near` or `z_far` are less than or equal to zero when `glam_assert` is - ///enabled. - perspective_lh(Raw(f64),Raw(f64),Raw(f64),Raw(f64)) -> self, - - ///Creates a right-handed perspective projection matrix with `[0,1]` depth range. - /// - ///# Panics - /// - ///Will panic if `z_near` or `z_far` are less than or equal to zero when `glam_assert` is - ///enabled. - perspective_rh(Raw(f64),Raw(f64),Raw(f64),Raw(f64)) -> self, - - ///Creates an infinite left-handed perspective projection matrix with `[0,1]` depth range. - /// - ///# Panics - /// - ///Will panic if `z_near` is less than or equal to zero when `glam_assert` is enabled. - perspective_infinite_lh(Raw(f64),Raw(f64),Raw(f64)) -> self, - - ///Creates an infinite left-handed perspective projection matrix with `[0,1]` depth range. - /// - ///# Panics - /// - ///Will panic if `z_near` is less than or equal to zero when `glam_assert` is enabled. - perspective_infinite_reverse_lh(Raw(f64),Raw(f64),Raw(f64)) -> self, - - ///Creates an infinite right-handed perspective projection matrix with - ///`[0,1]` depth range. - perspective_infinite_rh(Raw(f64),Raw(f64),Raw(f64)) -> self, - - ///Creates an infinite reverse right-handed perspective projection matrix - ///with `[0,1]` depth range. - perspective_infinite_reverse_rh(Raw(f64),Raw(f64),Raw(f64)) -> self, - - ///Creates a right-handed orthographic projection matrix with `[-1,1]` depth - ///range. This is the same as the OpenGL `glOrtho` function in OpenGL. - ///See - /// - orthographic_rh_gl(Raw(f64),Raw(f64),Raw(f64),Raw(f64),Raw(f64),Raw(f64)) -> self, - - ///Creates a left-handed orthographic projection matrix with `[0,1]` depth range. - orthographic_lh(Raw(f64),Raw(f64),Raw(f64),Raw(f64),Raw(f64),Raw(f64)) -> self, - - ///Creates a right-handed orthographic projection matrix with `[0,1]` depth range. - orthographic_rh(Raw(f64),Raw(f64),Raw(f64),Raw(f64),Raw(f64),Raw(f64)) -> self, - - ///Transforms the given 3D vector as a point, applying perspective correction. - /// - ///This is the equivalent of multiplying the 3D vector as a 4D vector where `w` is `1.0`. - ///The perspective divide is performed meaning the resulting 3D vector is divided by `w`. - /// - ///This method assumes that `self` contains a projective transform. - project_point3(&self:Wrapped(DVec3)) -> Wrapped(DVec3), - - ///Transforms the given 3D vector as a point. - /// - ///This is the equivalent of multiplying the 3D vector as a 4D vector where `w` is - ///`1.0`. - /// - ///This method assumes that `self` contains a valid affine transform. It does not perform - ///a persective divide, if `self` contains a perspective transform, or if you are unsure, - ///the [`Self::project_point3()`] method should be used instead. - /// - ///# Panics - /// - ///Will panic if the 3rd row of `self` is not `(0, 0, 0, 1)` when `glam_assert` is enabled. - transform_point3(&self:Wrapped(DVec3)) -> Wrapped(DVec3), - - ///Transforms the give 3D vector as a direction. - /// - ///This is the equivalent of multiplying the 3D vector as a 4D vector where `w` is - ///`0.0`. - /// - ///This method assumes that `self` contains a valid affine transform. - /// - ///# Panics - /// - ///Will panic if the 3rd row of `self` is not `(0, 0, 0, 1)` when `glam_assert` is enabled. - transform_vector3(&self:Wrapped(DVec3)) -> Wrapped(DVec3), - - ///Transforms a 4D vector. - mul_vec4(&self:Wrapped(DVec4)) -> Wrapped(DVec4), - - ///Multiplies two 4x4 matrices. - mul_mat4(&self:&self) -> self, - - ///Adds two 4x4 matrices. - add_mat4(&self:&self) -> self, - - ///Subtracts two 4x4 matrices. - sub_mat4(&self:&self) -> self, - - ///Multiplies a 4x4 matrix by a scalar. - mul_scalar(&self:Raw(f64)) -> self, - - ///Returns true if the absolute difference of all elements between `self` and `rhs` - ///is less than or equal to `max_abs_diff`. - /// - ///This can be used to compare if two matrices contain similar elements. It works best - ///when comparing with a known value. The `max_abs_diff` that should be used used - ///depends on the values being compared against. - /// - ///For more see - ///[comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - abs_diff_eq(&self:self,Raw(f64)) -> Raw(bool), - - as_mat4(&self:) -> Wrapped(Mat4), - - ) - + Fields - ( - x_axis: Wrapped(DVec4), - y_axis: Wrapped(DVec4), - z_axis: Wrapped(DVec4), - w_axis: Wrapped(DVec4), - ) - + BinOps - ( - self Add self -> Wrapped(DMat4), - self Sub self -> Wrapped(DMat4), - self Mul Raw(f64) -> Wrapped(DMat4), - self Mul Wrapped(DMat4) -> Wrapped(DMat4), - self Mul self -> Wrapped(DMat4), - self Mul Wrapped(DVec4) -> Wrapped(DVec4), - self Mul Wrapped(DAffine3) -> Wrapped(DMat4), - ) - + UnaryOps - ( - Neg self -> self - ) - lua impl - { - - mut (MetaMethod::Index) => |ctx,s,idx : LuaIndex| { - Ok(LuaDVec4::new_ref( - s.script_ref(ctx.get_world()?).sub_ref(ReflectPathElem::SubReflectionIndexed{ - label:"col", - index: *idx, - get: |idx,ref_| Err(ReflectionError::InsufficientProvenance{ - path: "".to_owned(), - msg: "Cannot get column of matrix with immutable reference".to_owned() - }), - get_mut: |idx, ref_| { - if ref_.is::(){ - Ok(ref_.downcast_mut::() - .unwrap() - .col_mut(idx)) - } else { - Err(ReflectionError::CannotDowncast{from: ref_.get_represented_type_info().unwrap().type_path().into(), to:"DMat4".into()}) - } - } - }) - ) - ) - } -; - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 2D affine transform, which can represent translation, rotation, scaling and shear. - glam::f32::Affine2 : - Clone + - Debug + - Methods - ( - ///Creates an affine transform from three column vectors. - from_cols(Wrapped(Vec2),Wrapped(Vec2),Wrapped(Vec2)) -> self, - - ///Creates an affine transform that changes scale. - ///Note that if any scale is zero the transform will be non-invertible. - from_scale(Wrapped(Vec2)) -> self, - - ///Creates an affine transform from the given rotation `angle`. - from_angle(Raw(f32)) -> self, - - ///Creates an affine transformation from the given 2D `translation`. - from_translation(Wrapped(Vec2)) -> self, - - ///Creates an affine transform from a 2x2 matrix (expressing scale, shear and rotation) - from_mat2(Wrapped(Mat2)) -> self, - - ///Creates an affine transform from a 2x2 matrix (expressing scale, shear and rotation) and a - ///translation vector. - /// - ///Equivalent to - ///`Affine2::from_translation(translation) * Affine2::from_mat2(mat2)` - from_mat2_translation(Wrapped(Mat2),Wrapped(Vec2)) -> self, - - ///Creates an affine transform from the given 2D `scale`, rotation `angle` (in radians) and - ///`translation`. - /// - ///Equivalent to `Affine2::from_translation(translation) * - ///Affine2::from_angle(angle) * Affine2::from_scale(scale)` - from_scale_angle_translation(Wrapped(Vec2),Raw(f32),Wrapped(Vec2)) -> self, - - ///Creates an affine transform from the given 2D rotation `angle` (in radians) and - ///`translation`. - /// - ///Equivalent to `Affine2::from_translation(translation) * Affine2::from_angle(angle)` - from_angle_translation(Raw(f32),Wrapped(Vec2)) -> self, - - ///The given `Mat3` must be an affine transform, - from_mat3(Wrapped(Mat3)) -> self, - - ///The given [`Mat3A`] must be an affine transform, - from_mat3a(Wrapped(Mat3A)) -> self, - - ///Transforms the given 2D point, applying shear, scale, rotation and translation. - transform_point2(&self:Wrapped(Vec2)) -> Wrapped(Vec2), - - ///Transforms the given 2D vector, applying shear, scale and rotation (but NOT - ///translation). - /// - ///To also apply translation, use [`Self::transform_point2()`] instead. - transform_vector2(&self:Wrapped(Vec2)) -> Wrapped(Vec2), - - ///Returns `true` if, and only if, all elements are finite. - /// - ///If any element is either `NaN`, positive or negative infinity, this will return - ///`false`. - is_finite(&self:) -> Raw(bool), - - ///Returns `true` if any elements are `NaN`. - is_nan(&self:) -> Raw(bool), - - ///Returns true if the absolute difference of all elements between `self` and `rhs` - ///is less than or equal to `max_abs_diff`. - /// - ///This can be used to compare if two 3x4 matrices contain similar elements. It works - ///best when comparing with a known value. The `max_abs_diff` that should be used used - ///depends on the values being compared against. - /// - ///For more see - ///[comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - abs_diff_eq(&self:self,Raw(f32)) -> Raw(bool), - - ///Return the inverse of this transform. - /// - ///Note that if the transform is not invertible the result will be invalid. - inverse(&self:) -> self, - - ) - + Fields - ( - matrix2: Wrapped(Mat2), - translation: Wrapped(Vec2), - ) - + BinOps - ( - self Mul Wrapped(Mat3) -> Wrapped(Mat3), - self Mul Wrapped(Affine2) -> Wrapped(Affine2), - self Mul Wrapped(Mat3A) -> Wrapped(Mat3A), - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 3D affine transform, which can represent translation, rotation, scaling and shear. - /// - ///This type is 16 byte aligned. - glam::f32::Affine3A : - Clone + - Debug + - Methods - ( - ///Creates an affine transform from three column vectors. - from_cols(Wrapped(Vec3A),Wrapped(Vec3A),Wrapped(Vec3A),Wrapped(Vec3A)) -> self, - - ///Creates an affine transform that changes scale. - ///Note that if any scale is zero the transform will be non-invertible. - from_scale(Wrapped(Vec3)) -> self, - - ///Creates an affine transform from the given `rotation` quaternion. - from_quat(Wrapped(Quat)) -> self, - - ///Creates an affine transform containing a 3D rotation around a normalized - ///rotation `axis` of `angle` (in radians). - from_axis_angle(Wrapped(Vec3),Raw(f32)) -> self, - - ///Creates an affine transform containing a 3D rotation around the x axis of - ///`angle` (in radians). - from_rotation_x(Raw(f32)) -> self, - - ///Creates an affine transform containing a 3D rotation around the y axis of - ///`angle` (in radians). - from_rotation_y(Raw(f32)) -> self, - - ///Creates an affine transform containing a 3D rotation around the z axis of - ///`angle` (in radians). - from_rotation_z(Raw(f32)) -> self, - - ///Creates an affine transformation from the given 3D `translation`. - from_translation(Wrapped(Vec3)) -> self, - - ///Creates an affine transform from a 3x3 matrix (expressing scale, shear and - ///rotation) - from_mat3(Wrapped(Mat3)) -> self, - - ///Creates an affine transform from a 3x3 matrix (expressing scale, shear and rotation) - ///and a translation vector. - /// - ///Equivalent to `Affine3A::from_translation(translation) * Affine3A::from_mat3(mat3)` - from_mat3_translation(Wrapped(Mat3),Wrapped(Vec3)) -> self, - - ///Creates an affine transform from the given 3D `scale`, `rotation` and - ///`translation`. - /// - ///Equivalent to `Affine3A::from_translation(translation) * - ///Affine3A::from_quat(rotation) * Affine3A::from_scale(scale)` - from_scale_rotation_translation(Wrapped(Vec3),Wrapped(Quat),Wrapped(Vec3)) -> self, - - ///Creates an affine transform from the given 3D `rotation` and `translation`. - /// - ///Equivalent to `Affine3A::from_translation(translation) * Affine3A::from_quat(rotation)` - from_rotation_translation(Wrapped(Quat),Wrapped(Vec3)) -> self, - - ///The given `Mat4` must be an affine transform, - ///i.e. contain no perspective transform. - from_mat4(Wrapped(Mat4)) -> self, - - ///Creates a left-handed view transform using a camera position, an up direction, and a facing - ///direction. - /// - ///For a view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`. - look_to_lh(Wrapped(Vec3),Wrapped(Vec3),Wrapped(Vec3)) -> self, - - ///Creates a right-handed view transform using a camera position, an up direction, and a facing - ///direction. - /// - ///For a view coordinate system with `+X=right`, `+Y=up` and `+Z=back`. - look_to_rh(Wrapped(Vec3),Wrapped(Vec3),Wrapped(Vec3)) -> self, - - ///Creates a left-handed view transform using a camera position, an up direction, and a focal - ///point. - ///For a view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`. - /// - ///# Panics - /// - ///Will panic if `up` is not normalized when `glam_assert` is enabled. - look_at_lh(Wrapped(Vec3),Wrapped(Vec3),Wrapped(Vec3)) -> self, - - ///Creates a right-handed view transform using a camera position, an up direction, and a focal - ///point. - ///For a view coordinate system with `+X=right`, `+Y=up` and `+Z=back`. - /// - ///# Panics - /// - ///Will panic if `up` is not normalized when `glam_assert` is enabled. - look_at_rh(Wrapped(Vec3),Wrapped(Vec3),Wrapped(Vec3)) -> self, - - ///Transforms the given 3D points, applying shear, scale, rotation and translation. - transform_point3(&self:Wrapped(Vec3)) -> Wrapped(Vec3), - - ///Transforms the given 3D vector, applying shear, scale and rotation (but NOT - ///translation). - /// - ///To also apply translation, use [`Self::transform_point3()`] instead. - transform_vector3(&self:Wrapped(Vec3)) -> Wrapped(Vec3), - - ///Transforms the given [`Vec3A`], applying shear, scale, rotation and translation. - transform_point3a(&self:Wrapped(Vec3A)) -> Wrapped(Vec3A), - - ///Transforms the given [`Vec3A`], applying shear, scale and rotation (but NOT - ///translation). - /// - ///To also apply translation, use [`Self::transform_point3a()`] instead. - transform_vector3a(&self:Wrapped(Vec3A)) -> Wrapped(Vec3A), - - ///Returns `true` if, and only if, all elements are finite. - /// - ///If any element is either `NaN`, positive or negative infinity, this will return - ///`false`. - is_finite(&self:) -> Raw(bool), - - ///Returns `true` if any elements are `NaN`. - is_nan(&self:) -> Raw(bool), - - ///Returns true if the absolute difference of all elements between `self` and `rhs` - ///is less than or equal to `max_abs_diff`. - /// - ///This can be used to compare if two 3x4 matrices contain similar elements. It works - ///best when comparing with a known value. The `max_abs_diff` that should be used used - ///depends on the values being compared against. - /// - ///For more see - ///[comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - abs_diff_eq(&self:self,Raw(f32)) -> Raw(bool), - - ///Return the inverse of this transform. - /// - ///Note that if the transform is not invertible the result will be invalid. - inverse(&self:) -> self, - - ) - + Fields - ( - matrix3: Wrapped(Mat3A), - translation: Wrapped(Vec3A), - ) - + BinOps - ( - self Mul Wrapped(Mat4) -> Wrapped(Mat4), - self Mul Wrapped(Affine3A) -> Wrapped(Affine3A), - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 2D affine transform, which can represent translation, rotation, scaling and shear. - glam::f64::DAffine2 : - Clone + - Debug + - Methods - ( - ///Creates an affine transform from three column vectors. - from_cols(Wrapped(DVec2),Wrapped(DVec2),Wrapped(DVec2)) -> self, - - ///Creates an affine transform that changes scale. - ///Note that if any scale is zero the transform will be non-invertible. - from_scale(Wrapped(DVec2)) -> self, - - ///Creates an affine transform from the given rotation `angle`. - from_angle(Raw(f64)) -> self, - - ///Creates an affine transformation from the given 2D `translation`. - from_translation(Wrapped(DVec2)) -> self, - - ///Creates an affine transform from a 2x2 matrix (expressing scale, shear and rotation) - from_mat2(Wrapped(DMat2)) -> self, - - ///Creates an affine transform from a 2x2 matrix (expressing scale, shear and rotation) and a - ///translation vector. - /// - ///Equivalent to - ///`DAffine2::from_translation(translation) * DAffine2::from_mat2(mat2)` - from_mat2_translation(Wrapped(DMat2),Wrapped(DVec2)) -> self, - - ///Creates an affine transform from the given 2D `scale`, rotation `angle` (in radians) and - ///`translation`. - /// - ///Equivalent to `DAffine2::from_translation(translation) * - ///DAffine2::from_angle(angle) * DAffine2::from_scale(scale)` - from_scale_angle_translation(Wrapped(DVec2),Raw(f64),Wrapped(DVec2)) -> self, - - ///Creates an affine transform from the given 2D rotation `angle` (in radians) and - ///`translation`. - /// - ///Equivalent to `DAffine2::from_translation(translation) * DAffine2::from_angle(angle)` - from_angle_translation(Raw(f64),Wrapped(DVec2)) -> self, - - ///The given `DMat3` must be an affine transform, - from_mat3(Wrapped(DMat3)) -> self, - - ///Transforms the given 2D point, applying shear, scale, rotation and translation. - transform_point2(&self:Wrapped(DVec2)) -> Wrapped(DVec2), - - ///Transforms the given 2D vector, applying shear, scale and rotation (but NOT - ///translation). - /// - ///To also apply translation, use [`Self::transform_point2()`] instead. - transform_vector2(&self:Wrapped(DVec2)) -> Wrapped(DVec2), - - ///Returns `true` if, and only if, all elements are finite. - /// - ///If any element is either `NaN`, positive or negative infinity, this will return - ///`false`. - is_finite(&self:) -> Raw(bool), - - ///Returns `true` if any elements are `NaN`. - is_nan(&self:) -> Raw(bool), - - ///Returns true if the absolute difference of all elements between `self` and `rhs` - ///is less than or equal to `max_abs_diff`. - /// - ///This can be used to compare if two 3x4 matrices contain similar elements. It works - ///best when comparing with a known value. The `max_abs_diff` that should be used used - ///depends on the values being compared against. - /// - ///For more see - ///[comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - abs_diff_eq(&self:self,Raw(f64)) -> Raw(bool), - - ///Return the inverse of this transform. - /// - ///Note that if the transform is not invertible the result will be invalid. - inverse(&self:) -> self, - - ) - + Fields - ( - matrix2: Wrapped(DMat2), - translation: Wrapped(DVec2), - ) - + BinOps - ( - self Mul Wrapped(DAffine2) -> Wrapped(DAffine2), - self Mul Wrapped(DMat3) -> Wrapped(DMat3), - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A 3D affine transform, which can represent translation, rotation, scaling and shear. - glam::f64::DAffine3 : - Clone + - Debug + - Methods - ( - ///Creates an affine transform from three column vectors. - from_cols(Wrapped(DVec3),Wrapped(DVec3),Wrapped(DVec3),Wrapped(DVec3)) -> self, - - ///Creates an affine transform that changes scale. - ///Note that if any scale is zero the transform will be non-invertible. - from_scale(Wrapped(DVec3)) -> self, - - ///Creates an affine transform from the given `rotation` quaternion. - from_quat(Wrapped(DQuat)) -> self, - - ///Creates an affine transform containing a 3D rotation around a normalized - ///rotation `axis` of `angle` (in radians). - from_axis_angle(Wrapped(DVec3),Raw(f64)) -> self, - - ///Creates an affine transform containing a 3D rotation around the x axis of - ///`angle` (in radians). - from_rotation_x(Raw(f64)) -> self, - - ///Creates an affine transform containing a 3D rotation around the y axis of - ///`angle` (in radians). - from_rotation_y(Raw(f64)) -> self, - - ///Creates an affine transform containing a 3D rotation around the z axis of - ///`angle` (in radians). - from_rotation_z(Raw(f64)) -> self, - - ///Creates an affine transformation from the given 3D `translation`. - from_translation(Wrapped(DVec3)) -> self, - - ///Creates an affine transform from a 3x3 matrix (expressing scale, shear and - ///rotation) - from_mat3(Wrapped(DMat3)) -> self, - - ///Creates an affine transform from a 3x3 matrix (expressing scale, shear and rotation) - ///and a translation vector. - /// - ///Equivalent to `DAffine3::from_translation(translation) * DAffine3::from_mat3(mat3)` - from_mat3_translation(Wrapped(DMat3),Wrapped(DVec3)) -> self, - - ///Creates an affine transform from the given 3D `scale`, `rotation` and - ///`translation`. - /// - ///Equivalent to `DAffine3::from_translation(translation) * - ///DAffine3::from_quat(rotation) * DAffine3::from_scale(scale)` - from_scale_rotation_translation(Wrapped(DVec3),Wrapped(DQuat),Wrapped(DVec3)) -> self, - - ///Creates an affine transform from the given 3D `rotation` and `translation`. - /// - ///Equivalent to `DAffine3::from_translation(translation) * DAffine3::from_quat(rotation)` - from_rotation_translation(Wrapped(DQuat),Wrapped(DVec3)) -> self, - - ///The given `DMat4` must be an affine transform, - ///i.e. contain no perspective transform. - from_mat4(Wrapped(DMat4)) -> self, - - ///Creates a left-handed view transform using a camera position, an up direction, and a facing - ///direction. - /// - ///For a view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`. - look_to_lh(Wrapped(DVec3),Wrapped(DVec3),Wrapped(DVec3)) -> self, - - ///Creates a right-handed view transform using a camera position, an up direction, and a facing - ///direction. - /// - ///For a view coordinate system with `+X=right`, `+Y=up` and `+Z=back`. - look_to_rh(Wrapped(DVec3),Wrapped(DVec3),Wrapped(DVec3)) -> self, - - ///Creates a left-handed view transform using a camera position, an up direction, and a focal - ///point. - ///For a view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`. - /// - ///# Panics - /// - ///Will panic if `up` is not normalized when `glam_assert` is enabled. - look_at_lh(Wrapped(DVec3),Wrapped(DVec3),Wrapped(DVec3)) -> self, - - ///Creates a right-handed view transform using a camera position, an up direction, and a focal - ///point. - ///For a view coordinate system with `+X=right`, `+Y=up` and `+Z=back`. - /// - ///# Panics - /// - ///Will panic if `up` is not normalized when `glam_assert` is enabled. - look_at_rh(Wrapped(DVec3),Wrapped(DVec3),Wrapped(DVec3)) -> self, - - ///Transforms the given 3D points, applying shear, scale, rotation and translation. - transform_point3(&self:Wrapped(DVec3)) -> Wrapped(DVec3), - - ///Transforms the given 3D vector, applying shear, scale and rotation (but NOT - ///translation). - /// - ///To also apply translation, use [`Self::transform_point3()`] instead. - transform_vector3(&self:Wrapped(DVec3)) -> Wrapped(DVec3), - - ///Returns `true` if, and only if, all elements are finite. - /// - ///If any element is either `NaN`, positive or negative infinity, this will return - ///`false`. - is_finite(&self:) -> Raw(bool), - - ///Returns `true` if any elements are `NaN`. - is_nan(&self:) -> Raw(bool), - - ///Returns true if the absolute difference of all elements between `self` and `rhs` - ///is less than or equal to `max_abs_diff`. - /// - ///This can be used to compare if two 3x4 matrices contain similar elements. It works - ///best when comparing with a known value. The `max_abs_diff` that should be used used - ///depends on the values being compared against. - /// - ///For more see - ///[comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - abs_diff_eq(&self:self,Raw(f64)) -> Raw(bool), - - ///Return the inverse of this transform. - /// - ///Note that if the transform is not invertible the result will be invalid. - inverse(&self:) -> self, - - ) - + Fields - ( - matrix3: Wrapped(DMat3), - translation: Wrapped(DVec3), - ) - + BinOps - ( - self Mul Wrapped(DAffine3) -> Wrapped(DAffine3), - self Mul Wrapped(DMat4) -> Wrapped(DMat4), - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A quaternion representing an orientation. - /// - ///This quaternion is intended to be of unit length but may denormalize due to - ///floating point "error creep" which can occur when successive quaternion - ///operations are applied. - /// - ///SIMD vector types are used for storage on supported platforms. - /// - ///This type is 16 byte aligned. - glam::f32::Quat : - Clone + - Debug + - Methods - ( - ///Creates a new rotation quaternion. - /// - ///This should generally not be called manually unless you know what you are doing. - ///Use one of the other constructors instead such as `identity` or `from_axis_angle`. - /// - ///`from_xyzw` is mostly used by unit tests and `serde` deserialization. - /// - ///# Preconditions - /// - ///This function does not check if the input is normalized, it is up to the user to - ///provide normalized input or to normalized the resulting quaternion. - from_xyzw(Raw(f32),Raw(f32),Raw(f32),Raw(f32)) -> self, - - ///Creates a new rotation quaternion from a 4D vector. - /// - ///# Preconditions - /// - ///This function does not check if the input is normalized, it is up to the user to - ///provide normalized input or to normalized the resulting quaternion. - from_vec4(Wrapped(Vec4)) -> self, - - ///Create a quaternion for a normalized rotation `axis` and `angle` (in radians). - /// - ///The axis must be a unit vector. - /// - ///# Panics - /// - ///Will panic if `axis` is not normalized when `glam_assert` is enabled. - from_axis_angle(Wrapped(Vec3),Raw(f32)) -> self, - - ///Create a quaternion that rotates `v.length()` radians around `v.normalize()`. - /// - ///`from_scaled_axis(Vec3::ZERO)` results in the identity quaternion. - from_scaled_axis(Wrapped(Vec3)) -> self, - - ///Creates a quaternion from the `angle` (in radians) around the x axis. - from_rotation_x(Raw(f32)) -> self, - - ///Creates a quaternion from the `angle` (in radians) around the y axis. - from_rotation_y(Raw(f32)) -> self, - - ///Creates a quaternion from the `angle` (in radians) around the z axis. - from_rotation_z(Raw(f32)) -> self, - - ///Creates a quaternion from the given Euler rotation sequence and the angles (in radians). - from_euler(Wrapped(EulerRot),Raw(f32),Raw(f32),Raw(f32)) -> self, - - ///Creates a quaternion from a 3x3 rotation matrix. - from_mat3(Wrapped(&Mat3)) -> self, - - ///Creates a quaternion from a 3x3 SIMD aligned rotation matrix. - from_mat3a(Wrapped(&Mat3A)) -> self, - - ///Creates a quaternion from a 3x3 rotation matrix inside a homogeneous 4x4 matrix. - from_mat4(Wrapped(&Mat4)) -> self, - - ///Gets the minimal rotation for transforming `from` to `to`. The rotation is in the - ///plane spanned by the two vectors. Will rotate at most 180 degrees. - /// - ///The inputs must be unit vectors. - /// - ///`from_rotation_arc(from, to) * from ≈ to`. - /// - ///For near-singular cases (from≈to and from≈-to) the current implementation - ///is only accurate to about 0.001 (for `f32`). - /// - ///# Panics - /// - ///Will panic if `from` or `to` are not normalized when `glam_assert` is enabled. - from_rotation_arc(Wrapped(Vec3),Wrapped(Vec3)) -> self, - - ///Gets the minimal rotation for transforming `from` to either `to` or `-to`. This means - ///that the resulting quaternion will rotate `from` so that it is colinear with `to`. - /// - ///The rotation is in the plane spanned by the two vectors. Will rotate at most 90 - ///degrees. - /// - ///The inputs must be unit vectors. - /// - ///`to.dot(from_rotation_arc_colinear(from, to) * from).abs() ≈ 1`. - /// - ///# Panics - /// - ///Will panic if `from` or `to` are not normalized when `glam_assert` is enabled. - from_rotation_arc_colinear(Wrapped(Vec3),Wrapped(Vec3)) -> self, - - ///Gets the minimal rotation for transforming `from` to `to`. The resulting rotation is - ///around the z axis. Will rotate at most 180 degrees. - /// - ///The inputs must be unit vectors. - /// - ///`from_rotation_arc_2d(from, to) * from ≈ to`. - /// - ///For near-singular cases (from≈to and from≈-to) the current implementation - ///is only accurate to about 0.001 (for `f32`). - /// - ///# Panics - /// - ///Will panic if `from` or `to` are not normalized when `glam_assert` is enabled. - from_rotation_arc_2d(Wrapped(Vec2),Wrapped(Vec2)) -> self, - - ///Returns the rotation axis scaled by the rotation in radians. - to_scaled_axis(self:) -> Wrapped(Vec3), - - ///Returns the vector part of the quaternion. - xyz(self:) -> Wrapped(Vec3), - - ///Returns the quaternion conjugate of `self`. For a unit quaternion the - ///conjugate is also the inverse. - conjugate(self:) -> self, - - ///Returns the inverse of a normalized quaternion. - /// - ///Typically quaternion inverse returns the conjugate of a normalized quaternion. - ///Because `self` is assumed to already be unit length this method *does not* normalize - ///before returning the conjugate. - /// - ///# Panics - /// - ///Will panic if `self` is not normalized when `glam_assert` is enabled. - inverse(self:) -> self, - - ///Computes the dot product of `self` and `rhs`. The dot product is - ///equal to the cosine of the angle between two quaternion rotations. - dot(self:self) -> Raw(f32), - - ///Computes the length of `self`. - length(self:) -> Raw(f32), - - ///Computes the squared length of `self`. - /// - ///This is generally faster than `length()` as it avoids a square - ///root operation. - length_squared(self:) -> Raw(f32), - - ///Computes `1.0 / length()`. - /// - ///For valid results, `self` must _not_ be of length zero. - length_recip(self:) -> Raw(f32), - - ///Returns `self` normalized to length 1.0. - /// - ///For valid results, `self` must _not_ be of length zero. - /// - ///Panics - /// - ///Will panic if `self` is zero length when `glam_assert` is enabled. - normalize(self:) -> self, - - ///Returns `true` if, and only if, all elements are finite. - ///If any element is either `NaN`, positive or negative infinity, this will return `false`. - is_finite(self:) -> Raw(bool), - - is_nan(self:) -> Raw(bool), - - ///Returns whether `self` of length `1.0` or not. - /// - ///Uses a precision threshold of `1e-6`. - is_normalized(self:) -> Raw(bool), - - is_near_identity(self:) -> Raw(bool), - - ///Returns the angle (in radians) for the minimal rotation - ///for transforming this quaternion into another. - /// - ///Both quaternions must be normalized. - /// - ///# Panics - /// - ///Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled. - angle_between(self:self) -> Raw(f32), - - ///Returns true if the absolute difference of all elements between `self` and `rhs` - ///is less than or equal to `max_abs_diff`. - /// - ///This can be used to compare if two quaternions contain similar elements. It works - ///best when comparing with a known value. The `max_abs_diff` that should be used used - ///depends on the values being compared against. - /// - ///For more see - ///[comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - abs_diff_eq(self:self,Raw(f32)) -> Raw(bool), - - ///Performs a linear interpolation between `self` and `rhs` based on - ///the value `s`. - /// - ///When `s` is `0.0`, the result will be equal to `self`. When `s` - ///is `1.0`, the result will be equal to `rhs`. - /// - ///# Panics - /// - ///Will panic if `self` or `end` are not normalized when `glam_assert` is enabled. - lerp(self:self,Raw(f32)) -> self, - - ///Performs a spherical linear interpolation between `self` and `end` - ///based on the value `s`. - /// - ///When `s` is `0.0`, the result will be equal to `self`. When `s` - ///is `1.0`, the result will be equal to `end`. - /// - ///# Panics - /// - ///Will panic if `self` or `end` are not normalized when `glam_assert` is enabled. - slerp(self:self,Raw(f32)) -> self, - - ///Multiplies a quaternion and a 3D vector, returning the rotated vector. - /// - ///# Panics - /// - ///Will panic if `self` is not normalized when `glam_assert` is enabled. - mul_vec3(self:Wrapped(Vec3)) -> Wrapped(Vec3), - - ///Multiplies two quaternions. If they each represent a rotation, the result will - ///represent the combined rotation. - /// - ///Note that due to floating point rounding the result may not be perfectly normalized. - /// - ///# Panics - /// - ///Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled. - mul_quat(self:self) -> self, - - ///Creates a quaternion from a 3x3 rotation matrix inside a 3D affine transform. - from_affine3(Wrapped(&Affine3A)) -> self, - - ///Multiplies a quaternion and a 3D vector, returning the rotated vector. - mul_vec3a(self:Wrapped(Vec3A)) -> Wrapped(Vec3A), - - as_dquat(self:) -> Wrapped(DQuat), - - as_f64(self:) -> Wrapped(DQuat), - - ) - + Fields - ( - ) - + BinOps - ( - self Add self -> Wrapped(Quat), - self Sub self -> Wrapped(Quat), - self Div Raw(f32) -> Wrapped(Quat), - self Mul self -> Wrapped(Quat), - self Mul Wrapped(Vec3) -> Wrapped(Vec3), - self Mul Raw(f32) -> Wrapped(Quat), - self Mul Wrapped(Vec3A) -> Wrapped(Vec3A), - ) - + UnaryOps - ( - Neg self -> self - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A quaternion representing an orientation. - /// - ///This quaternion is intended to be of unit length but may denormalize due to - ///floating point "error creep" which can occur when successive quaternion - ///operations are applied. - glam::f64::DQuat : - Clone + - Debug + - Methods - ( - ///Creates a new rotation quaternion. - /// - ///This should generally not be called manually unless you know what you are doing. - ///Use one of the other constructors instead such as `identity` or `from_axis_angle`. - /// - ///`from_xyzw` is mostly used by unit tests and `serde` deserialization. - /// - ///# Preconditions - /// - ///This function does not check if the input is normalized, it is up to the user to - ///provide normalized input or to normalized the resulting quaternion. - from_xyzw(Raw(f64),Raw(f64),Raw(f64),Raw(f64)) -> self, - - ///Creates a new rotation quaternion from a 4D vector. - /// - ///# Preconditions - /// - ///This function does not check if the input is normalized, it is up to the user to - ///provide normalized input or to normalized the resulting quaternion. - from_vec4(Wrapped(DVec4)) -> self, - - ///Create a quaternion for a normalized rotation `axis` and `angle` (in radians). - /// - ///The axis must be a unit vector. - /// - ///# Panics - /// - ///Will panic if `axis` is not normalized when `glam_assert` is enabled. - from_axis_angle(Wrapped(DVec3),Raw(f64)) -> self, - - ///Create a quaternion that rotates `v.length()` radians around `v.normalize()`. - /// - ///`from_scaled_axis(Vec3::ZERO)` results in the identity quaternion. - from_scaled_axis(Wrapped(DVec3)) -> self, - - ///Creates a quaternion from the `angle` (in radians) around the x axis. - from_rotation_x(Raw(f64)) -> self, - - ///Creates a quaternion from the `angle` (in radians) around the y axis. - from_rotation_y(Raw(f64)) -> self, - - ///Creates a quaternion from the `angle` (in radians) around the z axis. - from_rotation_z(Raw(f64)) -> self, - - ///Creates a quaternion from the given Euler rotation sequence and the angles (in radians). - from_euler(Wrapped(EulerRot),Raw(f64),Raw(f64),Raw(f64)) -> self, - - ///Creates a quaternion from a 3x3 rotation matrix. - from_mat3(Wrapped(&DMat3)) -> self, - - ///Creates a quaternion from a 3x3 rotation matrix inside a homogeneous 4x4 matrix. - from_mat4(Wrapped(&DMat4)) -> self, - - ///Gets the minimal rotation for transforming `from` to `to`. The rotation is in the - ///plane spanned by the two vectors. Will rotate at most 180 degrees. - /// - ///The inputs must be unit vectors. - /// - ///`from_rotation_arc(from, to) * from ≈ to`. - /// - ///For near-singular cases (from≈to and from≈-to) the current implementation - ///is only accurate to about 0.001 (for `f32`). - /// - ///# Panics - /// - ///Will panic if `from` or `to` are not normalized when `glam_assert` is enabled. - from_rotation_arc(Wrapped(DVec3),Wrapped(DVec3)) -> self, - - ///Gets the minimal rotation for transforming `from` to either `to` or `-to`. This means - ///that the resulting quaternion will rotate `from` so that it is colinear with `to`. - /// - ///The rotation is in the plane spanned by the two vectors. Will rotate at most 90 - ///degrees. - /// - ///The inputs must be unit vectors. - /// - ///`to.dot(from_rotation_arc_colinear(from, to) * from).abs() ≈ 1`. - /// - ///# Panics - /// - ///Will panic if `from` or `to` are not normalized when `glam_assert` is enabled. - from_rotation_arc_colinear(Wrapped(DVec3),Wrapped(DVec3)) -> self, - - ///Gets the minimal rotation for transforming `from` to `to`. The resulting rotation is - ///around the z axis. Will rotate at most 180 degrees. - /// - ///The inputs must be unit vectors. - /// - ///`from_rotation_arc_2d(from, to) * from ≈ to`. - /// - ///For near-singular cases (from≈to and from≈-to) the current implementation - ///is only accurate to about 0.001 (for `f32`). - /// - ///# Panics - /// - ///Will panic if `from` or `to` are not normalized when `glam_assert` is enabled. - from_rotation_arc_2d(Wrapped(DVec2),Wrapped(DVec2)) -> self, - - ///Returns the rotation axis scaled by the rotation in radians. - to_scaled_axis(self:) -> Wrapped(DVec3), - - ///Returns the vector part of the quaternion. - xyz(self:) -> Wrapped(DVec3), - - ///Returns the quaternion conjugate of `self`. For a unit quaternion the - ///conjugate is also the inverse. - conjugate(self:) -> self, - - ///Returns the inverse of a normalized quaternion. - /// - ///Typically quaternion inverse returns the conjugate of a normalized quaternion. - ///Because `self` is assumed to already be unit length this method *does not* normalize - ///before returning the conjugate. - /// - ///# Panics - /// - ///Will panic if `self` is not normalized when `glam_assert` is enabled. - inverse(self:) -> self, - - ///Computes the dot product of `self` and `rhs`. The dot product is - ///equal to the cosine of the angle between two quaternion rotations. - dot(self:self) -> Raw(f64), - - ///Computes the length of `self`. - length(self:) -> Raw(f64), - - ///Computes the squared length of `self`. - /// - ///This is generally faster than `length()` as it avoids a square - ///root operation. - length_squared(self:) -> Raw(f64), - - ///Computes `1.0 / length()`. - /// - ///For valid results, `self` must _not_ be of length zero. - length_recip(self:) -> Raw(f64), - - ///Returns `self` normalized to length 1.0. - /// - ///For valid results, `self` must _not_ be of length zero. - /// - ///Panics - /// - ///Will panic if `self` is zero length when `glam_assert` is enabled. - normalize(self:) -> self, - - ///Returns `true` if, and only if, all elements are finite. - ///If any element is either `NaN`, positive or negative infinity, this will return `false`. - is_finite(self:) -> Raw(bool), - - is_nan(self:) -> Raw(bool), - - ///Returns whether `self` of length `1.0` or not. - /// - ///Uses a precision threshold of `1e-6`. - is_normalized(self:) -> Raw(bool), - - is_near_identity(self:) -> Raw(bool), - - ///Returns the angle (in radians) for the minimal rotation - ///for transforming this quaternion into another. - /// - ///Both quaternions must be normalized. - /// - ///# Panics - /// - ///Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled. - angle_between(self:self) -> Raw(f64), - - ///Returns true if the absolute difference of all elements between `self` and `rhs` - ///is less than or equal to `max_abs_diff`. - /// - ///This can be used to compare if two quaternions contain similar elements. It works - ///best when comparing with a known value. The `max_abs_diff` that should be used used - ///depends on the values being compared against. - /// - ///For more see - ///[comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - abs_diff_eq(self:self,Raw(f64)) -> Raw(bool), - - ///Performs a linear interpolation between `self` and `rhs` based on - ///the value `s`. - /// - ///When `s` is `0.0`, the result will be equal to `self`. When `s` - ///is `1.0`, the result will be equal to `rhs`. - /// - ///# Panics - /// - ///Will panic if `self` or `end` are not normalized when `glam_assert` is enabled. - lerp(self:self,Raw(f64)) -> self, - - ///Performs a spherical linear interpolation between `self` and `end` - ///based on the value `s`. - /// - ///When `s` is `0.0`, the result will be equal to `self`. When `s` - ///is `1.0`, the result will be equal to `end`. - /// - ///# Panics - /// - ///Will panic if `self` or `end` are not normalized when `glam_assert` is enabled. - slerp(self:self,Raw(f64)) -> self, - - ///Multiplies a quaternion and a 3D vector, returning the rotated vector. - /// - ///# Panics - /// - ///Will panic if `self` is not normalized when `glam_assert` is enabled. - mul_vec3(self:Wrapped(DVec3)) -> Wrapped(DVec3), - - ///Multiplies two quaternions. If they each represent a rotation, the result will - ///represent the combined rotation. - /// - ///Note that due to floating point rounding the result may not be perfectly normalized. - /// - ///# Panics - /// - ///Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled. - mul_quat(self:self) -> self, - - ///Creates a quaternion from a 3x3 rotation matrix inside a 3D affine transform. - from_affine3(Wrapped(&DAffine3)) -> self, - - as_quat(self:) -> Wrapped(Quat), - - as_f32(self:) -> Wrapped(Quat), - - ) - + Fields - ( - x: Raw(f64), - y: Raw(f64), - z: Raw(f64), - w: Raw(f64), - ) - + BinOps - ( - self Add self -> Wrapped(DQuat), - self Sub self -> Wrapped(DQuat), - self Div Raw(f64) -> Wrapped(DQuat), - self Mul self -> Wrapped(DQuat), - self Mul Raw(f64) -> Wrapped(DQuat), - self Mul Wrapped(DVec3) -> Wrapped(DVec3), - ) - + UnaryOps - ( - Neg self -> self - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///Euler rotation sequences. - /// - ///The angles are applied starting from the right. - ///E.g. XYZ will first apply the z-axis rotation. - /// - ///YXZ can be used for yaw (y-axis), pitch (x-axis), roll (z-axis). - glam::EulerRot : - Clone + - Debug + - Methods - ( - ) - + Fields - ( - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -impl_script_newtype! { - #[languages(on_feature(lua))] - ///A rectangle defined by two opposite corners. - /// - ///The rectangle is axis aligned, and defined by its minimum and maximum coordinates, - ///stored in `Rect::min` and `Rect::max`, respectively. The minimum/maximum invariant - ///must be upheld by the user when directly assigning the fields, otherwise some methods - ///produce invalid results. It is generally recommended to use one of the constructor - ///methods instead, which will ensure this invariant is met, unless you already have - ///the minimum and maximum corners. - bevy_math::Rect : - Clone + - Debug + - Methods - ( - ///Create a new rectangle from two corner points. - /// - ///The two points do not need to be the minimum and/or maximum corners. - ///They only need to be two opposite corners. - /// - ///# Examples - /// - ///``` - ///# use bevy_math::Rect; - ///let r = Rect::new(0., 4., 10., 6.); // w=10 h=2 - ///let r = Rect::new(2., 3., 5., -1.); // w=3 h=4 - ///``` - new(Raw(f32),Raw(f32),Raw(f32),Raw(f32)) -> self, - - ///Create a new rectangle from two corner points. - /// - ///The two points do not need to be the minimum and/or maximum corners. - ///They only need to be two opposite corners. - /// - ///# Examples - /// - ///``` - ///# use bevy_math::{Rect, Vec2}; - ///// Unit rect from [0,0] to [1,1] - ///let r = Rect::from_corners(Vec2::ZERO, Vec2::ONE); // w=1 h=1 - ///// Same; the points do not need to be ordered - ///let r = Rect::from_corners(Vec2::ONE, Vec2::ZERO); // w=1 h=1 - ///``` - from_corners(Wrapped(Vec2),Wrapped(Vec2)) -> self, - - ///Create a new rectangle from its center and size. - /// - ///# Panics - /// - ///This method panics if any of the components of the size is negative. - /// - ///# Examples - /// - ///``` - ///# use bevy_math::{Rect, Vec2}; - ///let r = Rect::from_center_size(Vec2::ZERO, Vec2::ONE); // w=1 h=1 - ///assert!(r.min.abs_diff_eq(Vec2::splat(-0.5), 1e-5)); - ///assert!(r.max.abs_diff_eq(Vec2::splat(0.5), 1e-5)); - ///``` - from_center_size(Wrapped(Vec2),Wrapped(Vec2)) -> self, - - ///Create a new rectangle from its center and half-size. - /// - ///# Panics - /// - ///This method panics if any of the components of the half-size is negative. - /// - ///# Examples - /// - ///``` - ///# use bevy_math::{Rect, Vec2}; - ///let r = Rect::from_center_half_size(Vec2::ZERO, Vec2::ONE); // w=2 h=2 - ///assert!(r.min.abs_diff_eq(Vec2::splat(-1.), 1e-5)); - ///assert!(r.max.abs_diff_eq(Vec2::splat(1.), 1e-5)); - ///``` - from_center_half_size(Wrapped(Vec2),Wrapped(Vec2)) -> self, - - ///Check if the rectangle is empty. - /// - ///# Examples - /// - ///``` - ///# use bevy_math::{Rect, Vec2}; - ///let r = Rect::from_corners(Vec2::ZERO, Vec2::new(0., 1.)); // w=0 h=1 - ///assert!(r.is_empty()); - ///``` - is_empty(&self:) -> Raw(bool), - - ///Rectangle width (max.x - min.x). - /// - ///# Examples - /// - ///``` - ///# use bevy_math::Rect; - ///let r = Rect::new(0., 0., 5., 1.); // w=5 h=1 - ///assert!((r.width() - 5.).abs() <= 1e-5); - ///``` - width(&self:) -> Raw(f32), - - ///Rectangle height (max.y - min.y). - /// - ///# Examples - /// - ///``` - ///# use bevy_math::Rect; - ///let r = Rect::new(0., 0., 5., 1.); // w=5 h=1 - ///assert!((r.height() - 1.).abs() <= 1e-5); - ///``` - height(&self:) -> Raw(f32), - - ///Rectangle size. - /// - ///# Examples - /// - ///``` - ///# use bevy_math::{Rect, Vec2}; - ///let r = Rect::new(0., 0., 5., 1.); // w=5 h=1 - ///assert!(r.size().abs_diff_eq(Vec2::new(5., 1.), 1e-5)); - ///``` - size(&self:) -> Wrapped(Vec2), - - ///Rectangle half-size. - /// - ///# Examples - /// - ///``` - ///# use bevy_math::{Rect, Vec2}; - ///let r = Rect::new(0., 0., 5., 1.); // w=5 h=1 - ///assert!(r.half_size().abs_diff_eq(Vec2::new(2.5, 0.5), 1e-5)); - ///``` - half_size(&self:) -> Wrapped(Vec2), - - ///The center point of the rectangle. - /// - ///# Examples - /// - ///``` - ///# use bevy_math::{Rect, Vec2}; - ///let r = Rect::new(0., 0., 5., 1.); // w=5 h=1 - ///assert!(r.center().abs_diff_eq(Vec2::new(2.5, 0.5), 1e-5)); - ///``` - center(&self:) -> Wrapped(Vec2), - - ///Check if a point lies within this rectangle, inclusive of its edges. - /// - ///# Examples - /// - ///``` - ///# use bevy_math::Rect; - ///let r = Rect::new(0., 0., 5., 1.); // w=5 h=1 - ///assert!(r.contains(r.center())); - ///assert!(r.contains(r.min)); - ///assert!(r.contains(r.max)); - ///``` - contains(&self:Wrapped(Vec2)) -> Raw(bool), - - ///Build a new rectangle formed of the union of this rectangle and another rectangle. - /// - ///The union is the smallest rectangle enclosing both rectangles. - /// - ///# Examples - /// - ///``` - ///# use bevy_math::{Rect, Vec2}; - ///let r1 = Rect::new(0., 0., 5., 1.); // w=5 h=1 - ///let r2 = Rect::new(1., -1., 3., 3.); // w=2 h=4 - ///let r = r1.union(r2); - ///assert!(r.min.abs_diff_eq(Vec2::new(0., -1.), 1e-5)); - ///assert!(r.max.abs_diff_eq(Vec2::new(5., 3.), 1e-5)); - ///``` - union(&self:self) -> self, - - ///Build a new rectangle formed of the union of this rectangle and a point. - /// - ///The union is the smallest rectangle enclosing both the rectangle and the point. If the - ///point is already inside the rectangle, this method returns a copy of the rectangle. - /// - ///# Examples - /// - ///``` - ///# use bevy_math::{Rect, Vec2}; - ///let r = Rect::new(0., 0., 5., 1.); // w=5 h=1 - ///let u = r.union_point(Vec2::new(3., 6.)); - ///assert!(u.min.abs_diff_eq(Vec2::ZERO, 1e-5)); - ///assert!(u.max.abs_diff_eq(Vec2::new(5., 6.), 1e-5)); - ///``` - union_point(&self:Wrapped(Vec2)) -> self, - - ///Build a new rectangle formed of the intersection of this rectangle and another rectangle. - /// - ///The intersection is the largest rectangle enclosed in both rectangles. If the intersection - ///is empty, this method returns an empty rectangle ([`Rect::is_empty()`] returns `true`), but - ///the actual values of [`Rect::min`] and [`Rect::max`] are implementation-dependent. - /// - ///# Examples - /// - ///``` - ///# use bevy_math::{Rect, Vec2}; - ///let r1 = Rect::new(0., 0., 5., 1.); // w=5 h=1 - ///let r2 = Rect::new(1., -1., 3., 3.); // w=2 h=4 - ///let r = r1.intersect(r2); - ///assert!(r.min.abs_diff_eq(Vec2::new(1., 0.), 1e-5)); - ///assert!(r.max.abs_diff_eq(Vec2::new(3., 1.), 1e-5)); - ///``` - intersect(&self:self) -> self, - - ///Create a new rectangle with a constant inset. - /// - ///The inset is the extra border on all sides. A positive inset produces a larger rectangle, - ///while a negative inset is allowed and produces a smaller rectangle. If the inset is negative - ///and its absolute value is larger than the rectangle half-size, the created rectangle is empty. - /// - ///# Examples - /// - ///``` - ///# use bevy_math::{Rect, Vec2}; - ///let r = Rect::new(0., 0., 5., 1.); // w=5 h=1 - ///let r2 = r.inset(3.); // w=11 h=7 - ///assert!(r2.min.abs_diff_eq(Vec2::splat(-3.), 1e-5)); - ///assert!(r2.max.abs_diff_eq(Vec2::new(8., 4.), 1e-5)); - /// - ///let r = Rect::new(0., -1., 6., 7.); // w=6 h=8 - ///let r2 = r.inset(-2.); // w=11 h=7 - ///assert!(r2.min.abs_diff_eq(Vec2::new(2., 1.), 1e-5)); - ///assert!(r2.max.abs_diff_eq(Vec2::new(4., 5.), 1e-5)); - ///``` - inset(&self:Raw(f32)) -> self, - - ///Build a new rectangle from this one with its coordinates expressed - ///relative to `other` in a normalized ([0..1] x [0..1]) coordinate system. - /// - ///# Examples - /// - ///``` - ///# use bevy_math::{Rect, Vec2}; - ///let r = Rect::new(2., 3., 4., 6.); - ///let s = Rect::new(0., 0., 10., 10.); - ///let n = r.normalize(s); - /// - ///assert_eq!(n.min.x, 0.2); - ///assert_eq!(n.min.y, 0.3); - ///assert_eq!(n.max.x, 0.4); - ///assert_eq!(n.max.y, 0.6); - ///``` - normalize(&self:self) -> self, - - ) - + Fields - ( - /// The minimum corner point of the rect. - min: Wrapped(Vec2), - /// The maximum corner point of the rect. - max: Wrapped(Vec2), - ) - + BinOps - ( - ) - + UnaryOps - ( - ) - lua impl - { - } -} -#[cfg(feature = "lua")] -crate::impl_tealr_generic!(pub(crate) struct T); -#[cfg(feature = "lua")] -#[derive(Default)] -pub(crate) struct BevyAPIGlobals; -#[cfg(feature = "lua")] -impl bevy_mod_scripting_lua::tealr::mlu::ExportInstances for BevyAPIGlobals { - fn add_instances<'lua, T: bevy_mod_scripting_lua::tealr::mlu::InstanceCollector<'lua>>( - self, - instances: &mut T, - ) -> bevy_mod_scripting_lua::tealr::mlu::mlua::Result<()> { - instances.add_instance( - "Overflow", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "UiImage", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "Name", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "Text", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "TextSection", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "Stopwatch", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "Timer", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "Entity", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "Transform", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "RenderLayers", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "Color", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "Aabb", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "Frustum", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "CameraRenderGraph", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "Vec2", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "Vec3", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "Vec3A", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "Vec4", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "BVec2", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "BVec3", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "BVec4", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "BVec3A", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "BVec4A", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "DVec2", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "DVec3", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "DVec4", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "IVec2", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "IVec3", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "IVec4", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "UVec2", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "UVec3", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "UVec4", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "Mat3", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "Mat2", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "Mat3A", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "Mat4", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "DMat2", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "DMat3", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "DMat4", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "Affine2", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "Affine3A", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "DAffine2", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "DAffine3", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "Quat", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "DQuat", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "Rect", - bevy_mod_scripting_lua::tealr::mlu::UserDataProxy::::new, - )?; - instances.add_instance( - "world", - crate::lua::util::DummyTypeName::::new, - )?; - instances.add_instance( - "script", - crate::lua::util::DummyTypeName::::new, - )?; - instances.add_instance( - "entity", - crate::lua::util::DummyTypeName::::new, - )?; - Ok(()) - } -} -#[cfg(feature = "lua")] -pub struct LuaBevyAPIProvider; -#[cfg(feature = "lua")] -impl APIProvider for LuaBevyAPIProvider { - type APITarget = Mutex; - type ScriptContext = Mutex; - type DocTarget = LuaDocFragment; - fn attach_api(&mut self, ctx: &mut Self::APITarget) -> Result<(), ScriptError> { - let ctx = ctx - .get_mut() - .expect("Unable to acquire lock on Lua context"); - bevy_mod_scripting_lua::tealr::mlu::set_global_env(BevyAPIGlobals, ctx) - .map_err(|e| ScriptError::Other(e.to_string())) - } - fn get_doc_fragment(&self) -> Option { - Some(LuaDocFragment::new("BevyAPI", |tw| { - tw - .document_global_instance::().expect("Something went wrong documenting globals") - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::>() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::>() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::>() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::>() - .process_type::() - .process_type::() - .process_type::>() - .process_type::() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::>() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::() - .process_type::>() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::() - .process_type::>() - .process_type::() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::() - .process_type::>() - .process_type::() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - .process_type::() - .process_type::>() - })) - } - fn setup_script( - &mut self, - script_data: &ScriptData, - ctx: &mut Self::ScriptContext, - ) -> Result<(), ScriptError> { - let ctx = ctx.get_mut().expect("Could not get context"); - let globals = ctx.globals(); - globals - .set( - "entity", - crate::lua::bevy::LuaEntity::new(script_data.entity), - ) - .map_err(ScriptError::new_other)?; - globals - .set::<_, crate::lua::bevy::LuaScriptData>("script", script_data.into()) - .map_err(ScriptError::new_other)?; - - Ok(()) - } - - fn setup_script_runtime( - &mut self, - world_ptr: bevy_mod_scripting_core::world::WorldPointer, - _script_data: &ScriptData, - ctx: &mut Self::ScriptContext, - ) -> Result<(), ScriptError> { - let ctx = ctx.get_mut().expect("Could not get context"); - let globals = ctx.globals(); - globals - .set("world", crate::lua::bevy::LuaWorld::new(world_ptr)) - .map_err(ScriptError::new_other) - } - fn register_with_app(&self, app: &mut App) { - app.register_foreign_lua_type::(); - app.register_foreign_lua_type::(); - app.register_foreign_lua_type::(); - app.register_foreign_lua_type::(); - app.register_foreign_lua_type::(); - app.register_foreign_lua_type::(); - app.register_foreign_lua_type::(); - app.register_foreign_lua_type::(); - app.register_foreign_lua_type::(); - app.register_foreign_lua_type::(); - app.register_foreign_lua_type::(); - app.register_foreign_lua_type::(); - app.register_foreign_lua_type::(); - app.register_foreign_lua_type::(); - app.register_foreign_lua_type::