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.
This commit is contained in:
Nicola Papale 2023-06-26 18:38:31 +02:00 committed by GitHub
parent aeea4b0344
commit 1e73312e49
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -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};
@ -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;
@ -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)
}