Renamed pool method typed_ref to try_get (#846)

* replaced the BorrowAs trait with ObjectOrVariant trait; added explicit trait bounds in pool and graph's typed_ref method.

* renamed pool's typed_ref to try_get

* renamed try_get to try_get_node in BaseSceneGraph

* deleted try_get_mut from impl Graph, and replaced all occurrences with try_get_node_mut

* renamed typed_ref in SceneGraph to try_get

* added graph::prelude which contains AbstractSceneGraph, BaseSceneGraph and SceneGraph traits; added use graph::prelude::* in the script template to expose try_get functionalities.

* resolved merge issues

* formatted code

* added use fyrox::graph::prelude::* to template game/src/lib.rs to expose UserInterface's try_get functionality

* added "#[allow(unused_imports)]" on game template and script template
This commit is contained in:
LuoZheng2002
2025-10-01 20:54:17 +03:00
committed by GitHub
parent 34f60ecc3b
commit 7ec002f00c
67 changed files with 231 additions and 224 deletions
+2 -1
View File
@@ -38,6 +38,7 @@ use crate::{
script::Script,
};
use fyrox_core::visitor::error::VisitError;
use fyrox_graph::BaseSceneGraph;
use std::{
ops::Deref,
sync::{mpsc::Sender, Arc},
@@ -74,7 +75,7 @@ impl SceneState {
for index in 0..scene.graph.capacity() {
let handle = scene.graph.handle_from_index(index);
let Some(node) = scene.graph.try_get_mut(handle) else {
let Some(node) = scene.graph.try_get_node_mut(handle) else {
continue;
};
+5 -3
View File
@@ -636,7 +636,7 @@ impl ScriptMessageDispatcher {
ScriptMessageKind::Hierarchical { root, routing } => match routing {
RoutingStrategy::Up => {
let mut node = root;
while let Some(node_ref) = scene.graph.try_get(node) {
while let Some(node_ref) = scene.graph.try_get_node(node) {
let parent = node_ref.parent();
let mut context = ScriptMessageContext {
@@ -2012,7 +2012,9 @@ impl Engine {
{
let payload = result.payload;
if let Some(scene) = self.scenes.try_get_mut(node_task_handler.scene_handle) {
if let Some(node) = scene.graph.try_get_mut(node_task_handler.node_handle) {
if let Some(node) =
scene.graph.try_get_node_mut(node_task_handler.node_handle)
{
if let Some(mut script) = node
.scripts
.get_mut(node_task_handler.script_index)
@@ -2040,7 +2042,7 @@ impl Engine {
);
if let Some(node) =
scene.graph.try_get_mut(node_task_handler.node_handle)
scene.graph.try_get_node_mut(node_task_handler.node_handle)
{
if let Some(entry) =
node.scripts.get_mut(node_task_handler.script_index)
+1 -1
View File
@@ -891,7 +891,7 @@ impl RenderDataBundleStorage {
if let Some(lod_group) = node.lod_group() {
for level in lod_group.levels.iter() {
for &object in level.objects.iter() {
if let Some(object_ref) = graph.try_get(object) {
if let Some(object_ref) = graph.try_get_node(object) {
let distance = observer_position
.translation
.metric_distance(&object_ref.global_position());
+2 -2
View File
@@ -114,7 +114,7 @@ impl TileBuffer {
fn inflated_world_aabb(graph: &Graph, object: Handle<Node>) -> Option<AxisAlignedBoundingBox> {
let mut aabb = graph
.try_get(object)
.try_get_node(object)
.map(|node_ref| node_ref.world_bounding_box())?;
aabb.inflate(Vector3::repeat(0.01));
Some(aabb)
@@ -228,7 +228,7 @@ impl OcclusionTester {
let mut lines = Vec::new();
for (object_index, object) in self.objects_to_test.iter().enumerate() {
let object_index = object_index as u32;
let Some(node_ref) = graph.try_get(*object) else {
let Some(node_ref) = graph.try_get_node(*object) else {
continue;
};
+1 -1
View File
@@ -282,7 +282,7 @@ impl VisibilityCache {
/// Updates the cache by removing unused data.
pub fn update(&mut self, graph: &Graph) {
self.observers.retain(|observer, data| {
let Some(observer_ref) = graph.try_get(*observer) else {
let Some(observer_ref) = graph.try_get_node(*observer) else {
return false;
};
+1 -1
View File
@@ -112,7 +112,7 @@ impl ImportedTarget {
self.binding.value_binding()
}
fn value_in_graph(&self, graph: &Graph) -> Option<Box<[f32]>> {
let node: &Node = graph.try_get(self.handle)?;
let node: &Node = graph.try_get_node(self.handle)?;
match self.binding {
ImportedBinding::Position => {
Some(node.local_transform().position().data.as_slice().into())
+3 -3
View File
@@ -170,13 +170,13 @@ fn get_ancestor_names<'a>(
fn get_ancestor_name(mut handle: Handle<Node>, depth: usize, graph: &Graph) -> Option<&str> {
for _ in 0..depth {
if let Some(n) = graph.try_get(handle) {
if let Some(n) = graph.try_get_node(handle) {
handle = n.parent();
} else {
return None;
}
}
graph.try_get(handle).map(Node::name)
graph.try_get_node(handle).map(Node::name)
}
fn contains_duplicate_name(names: &[&str]) -> bool {
@@ -192,7 +192,7 @@ fn contains_duplicate_name(names: &[&str]) -> bool {
fn count_ancestor_depth(mut handle: Handle<Node>, list: &[Handle<Node>], graph: &Graph) -> usize {
let mut count: usize = 0;
while let Some(node) = graph.try_get(handle) {
while let Some(node) = graph.try_get_node(handle) {
handle = node.parent();
if list.contains(&handle) {
count += 1;
+1 -1
View File
@@ -333,7 +333,7 @@ impl NodeTrait for AnimationBlendingStateMachine {
fn validate(&self, scene: &Scene) -> Result<(), String> {
if scene
.graph
.try_get(*self.animation_player)
.try_get_node(*self.animation_player)
.and_then(|n| n.component_ref::<AnimationPlayer>())
.is_none()
{
+2 -2
View File
@@ -119,7 +119,7 @@ impl AnimationPoseExt for AnimationPose {
for (node, local_pose) in self.poses() {
if node.is_none() {
Log::writeln(MessageKind::Error, "Invalid node handle found for animation pose, most likely it means that animation retargeting failed!");
} else if let Some(node) = graph.try_get_mut(*node) {
} else if let Some(node) = graph.try_get_node_mut(*node) {
local_pose.values.apply(node);
}
}
@@ -132,7 +132,7 @@ impl AnimationPoseExt for AnimationPose {
for (node, local_pose) in self.poses() {
if node.is_none() {
Log::writeln(MessageKind::Error, "Invalid node handle found for animation pose, most likely it means that animation retargeting failed!");
} else if let Some(node_ref) = graph.try_get_mut(*node) {
} else if let Some(node_ref) = graph.try_get_node_mut(*node) {
callback(node_ref, *node, local_pose);
}
}
+1 -1
View File
@@ -1124,7 +1124,7 @@ impl Base {
if let Some(ancestor_node) = model
.get_scene()
.graph
.try_get(self.original_handle_in_resource)
.try_get_node(self.original_handle_in_resource)
{
return if ancestor_node.resource.is_none() {
Some(resource.clone())
+1 -1
View File
@@ -1044,7 +1044,7 @@ impl NodeTrait for Collider {
if scene
.graph
.try_get(self.parent())
.try_get_node(self.parent())
.and_then(|p| p.component_ref::<RigidBody>())
.is_none()
{
+1 -1
View File
@@ -703,7 +703,7 @@ impl NodeTrait for Collider {
if scene
.graph
.try_get(self.parent())
.try_get_node(self.parent())
.and_then(|p| p.component_ref::<RigidBody>())
.is_none()
{
+2 -2
View File
@@ -594,13 +594,13 @@ impl NodeTrait for Joint {
}
fn validate(&self, scene: &Scene) -> Result<(), String> {
if scene.graph.typed_ref(self.body1()).is_none() {
if scene.graph.try_get(self.body1()).is_none() {
return Err("2D Joint has invalid or unassigned handle to a \
first body, the joint will not operate!"
.to_string());
}
if scene.graph.typed_ref(self.body2()).is_none() {
if scene.graph.try_get(self.body2()).is_none() {
return Err("2D Joint has invalid or unassigned handle to a \
second body, the joint will not operate!"
.to_string());
+8 -9
View File
@@ -847,12 +847,12 @@ impl PhysicsWorld {
}),
exclude_collider: filter
.exclude_collider
.and_then(|h| graph.try_get(h))
.and_then(|h| graph.try_get_node(h))
.and_then(|n| n.component_ref::<dim2::collider::Collider>())
.map(|c| c.native.get()),
exclude_rigid_body: filter
.exclude_collider
.and_then(|h| graph.try_get(h))
.and_then(|h| graph.try_get_node(h))
.and_then(|n| n.component_ref::<dim2::rigidbody::RigidBody>())
.map(|c| c.native.get()),
predicate: Some(&predicate),
@@ -1242,12 +1242,12 @@ impl PhysicsWorld {
if let Some(native) = self.joints.set.get_mut(joint.native.get(), false) {
joint.body1.try_sync_model(|v| {
if let Some(rigid_body_node) = nodes.typed_ref(v) {
if let Some(rigid_body_node) = nodes.try_get(v) {
native.body1 = rigid_body_node.native.get();
}
});
joint.body2.try_sync_model(|v| {
if let Some(rigid_body_node) = nodes.typed_ref(v) {
if let Some(rigid_body_node) = nodes.try_get(v) {
native.body2 = rigid_body_node.native.get();
}
});
@@ -1295,10 +1295,9 @@ impl PhysicsWorld {
});
let mut local_frames = joint.local_frames.borrow_mut();
if local_frames.is_none() {
if let (Some(body1), Some(body2)) = (
nodes.typed_ref(joint.body1()),
nodes.typed_ref(joint.body2()),
) {
if let (Some(body1), Some(body2)) =
(nodes.try_get(joint.body1()), nodes.try_get(joint.body2()))
{
let (local_frame1, local_frame2) = calculate_local_frames(joint, body1, body2);
native.data =
convert_joint_params((*joint.params).clone(), local_frame1, local_frame2);
@@ -1312,7 +1311,7 @@ impl PhysicsWorld {
// A native joint can be created iff both rigid bodies are correctly assigned.
if let (Some(body1), Some(body2)) =
(nodes.typed_ref(body1_handle), nodes.typed_ref(body2_handle))
(nodes.try_get(body1_handle), nodes.try_get(body2_handle))
{
// Calculate local frames first (if needed).
let mut local_frames = joint.local_frames.borrow_mut();
+24 -33
View File
@@ -483,12 +483,6 @@ impl Graph {
self.root
}
/// Tries to mutably borrow a node, returns Some(node) if the handle is valid, None - otherwise.
#[inline]
pub fn try_get_mut(&mut self, handle: Handle<Node>) -> Option<&mut Node> {
self.pool.try_borrow_mut(handle)
}
/// Begins multi-borrow that allows you borrow to as many shared references to the graph
/// nodes as you need and only one mutable reference to a node. See
/// [`MultiBorrowContext::try_get`] for more info.
@@ -873,7 +867,7 @@ impl Graph {
where
F: FnMut(Handle<Node>, &Node) -> bool,
{
graph.try_get(node).and_then(|n| {
graph.try_get_node(node).and_then(|n| {
if filter(node, n) {
let mut aabb = n.local_bounding_box();
if aabb.is_invalid_or_degenerate() {
@@ -1083,7 +1077,7 @@ impl Graph {
func: &mut impl FnMut(Handle<Node>),
) {
func(from);
if let Some(node) = graph.try_get(from) {
if let Some(node) = graph.try_get_node(from) {
for &child in node.children() {
traverse_recursive(graph, child, func)
}
@@ -1534,7 +1528,7 @@ impl Graph {
#[inline]
pub fn global_scale(&self, mut node: Handle<Node>) -> Vector3<f32> {
let mut global_scale = Vector3::repeat(1.0);
while let Some(node_ref) = self.try_get(node) {
while let Some(node_ref) = self.try_get_node(node) {
global_scale = global_scale.component_mul(node_ref.local_transform().scale());
node = node_ref.parent;
}
@@ -1548,7 +1542,7 @@ impl Graph {
where
T: ScriptTrait,
{
self.try_get(node)
self.try_get_node(node)
.and_then(|node| node.try_get_script::<T>())
}
@@ -1560,7 +1554,7 @@ impl Graph {
&self,
node: Handle<Node>,
) -> Option<impl Iterator<Item = &T>> {
self.try_get(node).map(|n| n.try_get_scripts())
self.try_get_node(node).map(|n| n.try_get_scripts())
}
/// Tries to borrow a node using the given handle and searches the script buffer for a script
@@ -1570,7 +1564,7 @@ impl Graph {
where
T: ScriptTrait,
{
self.try_get_mut(node)
self.try_get_node_mut(node)
.and_then(|node| node.try_get_script_mut::<T>())
}
@@ -1582,7 +1576,7 @@ impl Graph {
&mut self,
node: Handle<Node>,
) -> Option<impl Iterator<Item = &mut T>> {
self.try_get_mut(node).map(|n| n.try_get_scripts_mut())
self.try_get_node_mut(node).map(|n| n.try_get_scripts_mut())
}
/// Tries to borrow a node and find a component of the given type `C` across **all** available
@@ -1593,7 +1587,7 @@ impl Graph {
where
C: Any,
{
self.try_get(node)
self.try_get_node(node)
.and_then(|node| node.try_get_script_component())
}
@@ -1605,7 +1599,7 @@ impl Graph {
where
C: Any,
{
self.try_get_mut(node)
self.try_get_node_mut(node)
.and_then(|node| node.try_get_script_component_mut())
}
@@ -1634,7 +1628,7 @@ impl<T: ObjectOrVariant<Node>> Index<Handle<T>> for Graph {
#[inline]
fn index(&self, index: Handle<T>) -> &Self::Output {
self.typed_ref(index)
self.try_get(index)
.expect("The node handle is invalid or the object it points to has different type.")
}
}
@@ -1642,7 +1636,7 @@ impl<T: ObjectOrVariant<Node>> Index<Handle<T>> for Graph {
impl<T: ObjectOrVariant<Node>> IndexMut<Handle<T>> for Graph {
#[inline]
fn index_mut(&mut self, index: Handle<T>) -> &mut Self::Output {
self.typed_mut(index)
self.try_get_mut(index)
.expect("The node handle is invalid or the object it points to has different type.")
}
}
@@ -1808,12 +1802,12 @@ impl BaseSceneGraph for Graph {
}
#[inline]
fn try_get(&self, handle: Handle<Self::Node>) -> Option<&Self::Node> {
fn try_get_node(&self, handle: Handle<Self::Node>) -> Option<&Self::Node> {
self.pool.try_borrow(handle)
}
#[inline]
fn try_get_mut(&mut self, handle: Handle<Self::Node>) -> Option<&mut Self::Node> {
fn try_get_node_mut(&mut self, handle: Handle<Self::Node>) -> Option<&mut Self::Node> {
self.pool.try_borrow_mut(handle)
}
@@ -1847,12 +1841,12 @@ impl SceneGraph for Graph {
self.pool.iter_mut()
}
fn typed_ref<U: ObjectOrVariant<Node>>(&self, handle: Handle<U>) -> Option<&U> {
self.pool.typed_ref(handle)
fn try_get<U: ObjectOrVariant<Node>>(&self, handle: Handle<U>) -> Option<&U> {
self.pool.try_get(handle)
}
fn typed_mut<U: ObjectOrVariant<Node>>(&mut self, handle: Handle<U>) -> Option<&mut U> {
self.pool.typed_mut(handle)
fn try_get_mut<U: ObjectOrVariant<Node>>(&mut self, handle: Handle<U>) -> Option<&mut U> {
self.pool.try_get_mut(handle)
}
}
@@ -2351,7 +2345,7 @@ mod test {
assert!(graph[c].global_visibility());
assert!(graph[d].global_visibility());
assert!(!graph.pool.typed_ref(a).unwrap().is_globally_enabled());
assert!(!graph.pool.try_get(a).unwrap().is_globally_enabled());
assert!(!graph[b].is_globally_enabled());
assert!(!graph[c].is_globally_enabled());
assert!(!graph[d].is_globally_enabled());
@@ -2363,21 +2357,18 @@ mod test {
let pivot = PivotBuilder::new(BaseBuilder::new()).build(&mut graph);
let rigid_body = RigidBodyBuilder::new(BaseBuilder::new()).build(&mut graph);
assert!(graph.pool.typed_ref(pivot).is_some());
assert!(graph.pool.typed_ref(pivot.transmute::<Pivot>()).is_some());
assert!(graph
.pool
.typed_ref(pivot.transmute::<RigidBody>())
.is_none());
assert!(graph.pool.try_get(pivot).is_some());
assert!(graph.pool.try_get(pivot.transmute::<Pivot>()).is_some());
assert!(graph.pool.try_get(pivot.transmute::<RigidBody>()).is_none());
assert!(graph.pool.typed_ref(rigid_body).is_some());
assert!(graph.pool.try_get(rigid_body).is_some());
assert!(graph
.pool
.typed_ref(rigid_body.transmute::<RigidBody>())
.try_get(rigid_body.transmute::<RigidBody>())
.is_some());
assert!(graph
.pool
.typed_ref(rigid_body.transmute::<Pivot>())
.try_get(rigid_body.transmute::<Pivot>())
.is_none());
}
}
+9 -10
View File
@@ -1331,12 +1331,12 @@ impl PhysicsWorld {
}),
exclude_collider: filter
.exclude_collider
.and_then(|h| graph.try_get(h))
.and_then(|h| graph.try_get_node(h))
.and_then(|n| n.component_ref::<collider::Collider>())
.map(|c| c.native.get()),
exclude_rigid_body: filter
.exclude_collider
.and_then(|h| graph.try_get(h))
.and_then(|h| graph.try_get_node(h))
.and_then(|n| n.component_ref::<rigidbody::RigidBody>())
.map(|c| c.native.get()),
predicate: Some(&predicate),
@@ -1802,12 +1802,12 @@ impl PhysicsWorld {
if let Some(native) = self.joints.set.get_mut(joint.native.get(), false) {
joint.body1.try_sync_model(|v| {
if let Some(rigid_body_node) = nodes.typed_ref(v) {
if let Some(rigid_body_node) = nodes.try_get(v) {
native.body1 = rigid_body_node.native.get();
}
});
joint.body2.try_sync_model(|v| {
if let Some(rigid_body_node) = nodes.typed_ref(v) {
if let Some(rigid_body_node) = nodes.try_get(v) {
native.body2 = rigid_body_node.native.get();
}
});
@@ -1859,10 +1859,9 @@ impl PhysicsWorld {
let mut local_frames = joint.local_frames.borrow_mut();
if local_frames.is_none() {
if let (Some(body1), Some(body2)) = (
nodes.typed_ref(joint.body1()),
nodes.typed_ref(joint.body2()),
) {
if let (Some(body1), Some(body2)) =
(nodes.try_get(joint.body1()), nodes.try_get(joint.body2()))
{
let (local_frame1, local_frame2) = calculate_local_frames(joint, body1, body2);
native.data =
convert_joint_params((*joint.params).clone(), local_frame1, local_frame2);
@@ -1878,10 +1877,10 @@ impl PhysicsWorld {
// native bodies exists.
if let (Some(body1), Some(body2)) = (
nodes
.typed_ref(body1_handle)
.try_get(body1_handle)
.filter(|b| self.bodies.get(b.native.get()).is_some()),
nodes
.typed_ref(body2_handle)
.try_get(body2_handle)
.filter(|b| self.bodies.get(b.native.get()).is_some()),
) {
// Calculate local frames first (if needed).
+2 -2
View File
@@ -679,13 +679,13 @@ impl NodeTrait for Joint {
}
fn validate(&self, scene: &Scene) -> Result<(), String> {
if scene.graph.typed_ref(self.body1()).is_none() {
if scene.graph.try_get(self.body1()).is_none() {
return Err("3D Joint has invalid or unassigned handle to a \
first body, the joint will not operate!"
.to_string());
}
if scene.graph.typed_ref(self.body2()).is_none() {
if scene.graph.try_get(self.body2()).is_none() {
return Err("3D Joint has invalid or unassigned handle to a \
second body, the joint will not operate!"
.to_string());
+3 -1
View File
@@ -775,7 +775,9 @@ impl NodeTrait for Mesh {
.bones
.iter()
.map(|bone_handle| {
if let Some(bone_node) = ctx.graph.try_get(*bone_handle) {
if let Some(bone_node) =
ctx.graph.try_get_node(*bone_handle)
{
bone_node.global_transform()
* bone_node.inv_bind_pose_transform()
} else {
+4 -4
View File
@@ -50,7 +50,7 @@ use std::{
use crate::engine::input::InputState;
pub use fyrox_core_derive::ScriptMessagePayload;
use fyrox_graph::BaseSceneGraph;
pub mod constructor;
pub(crate) trait UniversalScriptContext {
@@ -424,7 +424,7 @@ pub struct ScriptContext<'a, 'b, 'c> {
impl UniversalScriptContext for ScriptContext<'_, '_, '_> {
fn node(&mut self) -> Option<&mut Node> {
self.scene.graph.try_get_mut(self.handle)
self.scene.graph.try_get_node_mut(self.handle)
}
fn destroy_script_deferred(&self, script: Script, index: usize) {
@@ -508,7 +508,7 @@ pub struct ScriptMessageContext<'a, 'b, 'c> {
impl UniversalScriptContext for ScriptMessageContext<'_, '_, '_> {
fn node(&mut self) -> Option<&mut Node> {
self.scene.graph.try_get_mut(self.handle)
self.scene.graph.try_get_node_mut(self.handle)
}
fn destroy_script_deferred(&self, script: Script, index: usize) {
@@ -583,7 +583,7 @@ pub struct ScriptDeinitContext<'a, 'b, 'c> {
impl UniversalScriptContext for ScriptDeinitContext<'_, '_, '_> {
fn node(&mut self) -> Option<&mut Node> {
self.scene.graph.try_get_mut(self.node_handle)
self.scene.graph.try_get_node_mut(self.node_handle)
}
fn destroy_script_deferred(&self, script: Script, index: usize) {