Skip to content

Commit 1e73312

Browse files
authored
Use AHash to get color from entity in bevy_gizmos (#8960)
# Objective `color_from_entity` uses the poor man's hash to get a fixed random color for an entity. While the poor man's hash is succinct, it has a tendency to clump. As a result, bevy_gizmos has a tendency to re-use very similar colors for different entities. This is bad, we would want non-similar colors that take the whole range of possible hues. This way, each bevy_gizmos aabb gizmo is easy to identify. ## Solution AHash is a nice and fast hash that just so happen to be available to use, so we use it.
1 parent aeea4b0 commit 1e73312

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

crates/bevy_gizmos/src/lib.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
//!
1717
//! See the documentation on [`Gizmos`](crate::gizmos::Gizmos) for more examples.
1818
19+
use std::hash::{Hash, Hasher};
1920
use std::mem;
2021

2122
use bevy_app::{Last, Plugin, Update};
@@ -52,6 +53,7 @@ use bevy_render::{
5253
Extract, ExtractSchedule, Render, RenderApp, RenderSet,
5354
};
5455
use bevy_transform::components::{GlobalTransform, Transform};
56+
use bevy_utils::AHasher;
5557

5658
pub mod gizmos;
5759

@@ -229,7 +231,12 @@ fn draw_all_aabbs(
229231
}
230232

231233
fn color_from_entity(entity: Entity) -> Color {
232-
let hue = entity.to_bits() as f32 * 100_000. % 360.;
234+
const U64_TO_DEGREES: f32 = 360.0 / u64::MAX as f32;
235+
236+
let mut hasher = AHasher::default();
237+
entity.hash(&mut hasher);
238+
239+
let hue = hasher.finish() as f32 * U64_TO_DEGREES;
233240
Color::hsl(hue, 1., 0.5)
234241
}
235242

0 commit comments

Comments
 (0)