Skip to content

Commit

Permalink
Use AHash to get color from entity in bevy_gizmos (#8960)
Browse files Browse the repository at this point in the history
# 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.
  • Loading branch information
nicopap committed Jun 26, 2023
1 parent aeea4b0 commit 1e73312
Showing 1 changed file with 8 additions and 1 deletion.
9 changes: 8 additions & 1 deletion crates/bevy_gizmos/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
//!
//! See the documentation on [`Gizmos`](crate::gizmos::Gizmos) for more examples.

use std::hash::{Hash, Hasher};
use std::mem;

use bevy_app::{Last, Plugin, Update};
Expand Down Expand Up @@ -52,6 +53,7 @@ use bevy_render::{
Extract, ExtractSchedule, Render, RenderApp, RenderSet,
};
use bevy_transform::components::{GlobalTransform, Transform};
use bevy_utils::AHasher;

pub mod gizmos;

Expand Down Expand Up @@ -229,7 +231,12 @@ fn draw_all_aabbs(
}

fn color_from_entity(entity: Entity) -> Color {
let hue = entity.to_bits() as f32 * 100_000. % 360.;
const U64_TO_DEGREES: f32 = 360.0 / u64::MAX as f32;

let mut hasher = AHasher::default();
entity.hash(&mut hasher);

let hue = hasher.finish() as f32 * U64_TO_DEGREES;
Color::hsl(hue, 1., 0.5)
}

Expand Down

0 comments on commit 1e73312

Please sign in to comment.