AnyBot/src/avatar.rs

534 lines
24 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Bot avatars: a simple shape in the bot's colour with two slanted oval eyes,
// drawn in the style of the original's bot faces (not copied from its pictures).
use eframe::egui::{self, pos2, vec2, Color32, Pos2, Rect, Shape, Stroke};
use std::f32::consts::PI;
pub const SHAPES: [&str; 14] = [
"squircle", "blob", "capsule", "egg", "hex", "gem", "cloud", "arch", "star", "heart", "shield", "pebble", "moon",
"pumpkin",
];
pub fn shape_label(s: &str) -> &'static str {
match s {
"squircle" => "圓角方",
"blob" => "圓球",
"capsule" => "膠囊",
"egg" => "蛋",
"hex" => "六角",
"gem" => "寶石",
"cloud" => "雲",
"arch" => "拱門",
"star" => "星星",
"heart" => "愛心",
"shield" => "盾牌",
"pebble" => "石頭",
"moon" => "月牙",
"pumpkin" => "南瓜",
_ => "圓球",
}
}
/// Where the face sits, in units of the shape's half-size: (inset, dx, dy, eye-separation).
///
/// The eyes are placed from the outline, so a concave shape (a star's rays, a moon's
/// wedge) has less real room than its bounding box looks, and the eyes cross the
/// outline at the resting size. Each shape declares how much of its half-size the face
/// may use, the offset to its solid part, and how far apart the eyes sit; the eyes
/// scale and move by it. `paint` and `paint_posed` both read this, so a thinking
/// face's eyes do not jump.
fn face_fit(shape: &str) -> (f32, f32, f32, f32) {
match shape {
// The star's solid core is the pentagon under the rays (inradius ~0.48s):
// small eyes, drawn closer together so they keep a face's spacing.
"star" => (0.52, 0.0, 0.08, 0.20),
// The moon keeps its wedge (mouth) on the right; the face rides left of it.
"moon" => (0.55, -0.3, 0.0, 0.27),
// The pumpkin's face rides on the middle row of its ribs, a touch low.
"pumpkin" => (0.70, 0.0, -0.02, 0.27),
_ => (1.0, 0.0, 0.0, 0.27),
}
}
/// Where the eyes rest, in half-size units of the shape (centre at the origin):
/// each eye's (centre, half-width, half-height). The paint paths draw from this, and
/// the tests below check the eyes stay inside every shape's body.
pub fn eye_rects(shape: &str) -> [(Pos2, f32, f32); 2] {
let (k, fx, fy, sep) = face_fit(shape);
[-sep, sep].map(|dx| (pos2(dx * k + fx, 0.02 + fy), 0.11 * k, 0.22 * k))
}
/// Bot colours, from the original's bubble fills (index CSS --sand-fill-*-bubble-user).
pub const COLORS: [(&str, &str, [u8; 3]); 10] = [
("black", "黑色", [0x1c, 0x1c, 0x1c]),
("red", "紅", [0xc8, 0x25, 0x32]),
("orange", "橘", [0xd2, 0x55, 0x0a]),
("yellow", "黃", [0xc2, 0x73, 0x0b]),
("green", "綠", [0x0d, 0x96, 0x55]),
("cyan", "青", [0x0d, 0x93, 0x81]),
("blue", "藍", [0x12, 0x6f, 0xd4]),
("purple", "紫", [0x74, 0x42, 0xd1]),
("magenta", "洋紅", [0xc8, 0x27, 0x79]),
("brown", "棕", [0x86, 0x59, 0x2e]),
];
/// A colour is a preset name, or custom: the name is then its hex, "#rrggbb".
pub fn color(name: &str) -> Color32 {
if let Some(c) = hex_color(name) {
return c;
}
let c = COLORS.iter().find(|c| c.0 == name).map(|c| c.2).unwrap_or(COLORS[0].2);
Color32::from_rgb(c[0], c[1], c[2])
}
pub fn is_custom(name: &str) -> bool {
name.starts_with('#')
}
fn hex_color(name: &str) -> Option<Color32> {
let h = name.trim().trim_start_matches('#');
if h.len() == 6 && h.chars().all(|c| c.is_ascii_hexdigit()) {
let v = u32::from_str_radix(h, 16).ok()?;
return Some(Color32::from_rgb((v >> 16) as u8, (v >> 8) as u8, v as u8));
}
None
}
/// The colour as hue (0..360), saturation and value (0..1) — for the picker's sliders.
pub fn hsv_of(name: &str) -> [f32; 3] {
let c = color(name);
let (r, g, b) = (c.r() as f32 / 255.0, c.g() as f32 / 255.0, c.b() as f32 / 255.0);
let (mx, mn) = (r.max(g).max(b), r.min(g).min(b));
let d = mx - mn;
let h = if d == 0.0 {
0.0
} else if mx == r {
60.0 * (((g - b) / d) % 6.0)
} else if mx == g {
60.0 * ((b - r) / d + 2.0)
} else {
60.0 * ((r - g) / d + 4.0)
};
[if h < 0.0 { h + 360.0 } else { h }, if mx == 0.0 { 0.0 } else { d / mx }, mx]
}
/// The picker's answer: sliders back to a hex name.
pub fn hex_of_hsv(hsv: [f32; 3]) -> String {
let (h, s, v) = (hsv[0].rem_euclid(360.0), hsv[1].clamp(0.0, 1.0), hsv[2].clamp(0.0, 1.0));
let c = v * s;
let x = c * (1.0 - ((h / 60.0) % 2.0 - 1.0).abs());
let m = v - c;
let (r, g, b) = match (h / 60.0) as u32 {
0 => (c, x, 0.0),
1 => (x, c, 0.0),
2 => (0.0, c, x),
3 => (0.0, x, c),
4 => (x, 0.0, c),
_ => (c, 0.0, x),
};
let q = |f: f32| (f * 255.0).round().clamp(0.0, 255.0) as u8;
format!("#{:02x}{:02x}{:02x}", q(r + m), q(g + m), q(b + m))
}
/// Hues across the custom colour grid.
pub const SWATCH_COLUMNS: usize = 12;
/// The custom colours to click (Bot 設定 › 頭像 › 自訂), rows of `SWATCH_COLUMNS`: four tones of
/// twelve hues — soft, clear, deep, dark — then a grey row from light to dark. Each is a "#rrggbb"
/// the bot keeps as its colour.
pub fn custom_swatches() -> Vec<Vec<String>> {
let tones = [(0.30, 0.92), (0.62, 0.86), (0.78, 0.66), (0.70, 0.42)];
let mut rows: Vec<Vec<String>> = tones.iter().map(|&(s, v)| (0..SWATCH_COLUMNS).map(|i| hex_of_hsv([i as f32 * 360.0 / SWATCH_COLUMNS as f32, s, v])).collect()).collect();
rows.push((0..SWATCH_COLUMNS).map(|i| hex_of_hsv([0.0, 0.0, 0.92 - 0.8 * i as f32 / (SWATCH_COLUMNS - 1) as f32])).collect());
rows
}
/// A colour the person typed ("6B4A55", "#6b4a55 "): "#rrggbb" in lowercase, or None.
pub fn parse_hex(s: &str) -> Option<String> {
let h = s.trim().trim_start_matches('#');
(h.len() == 6 && h.chars().all(|c| c.is_ascii_hexdigit())).then(|| format!("#{}", h.to_ascii_lowercase()))
}
fn ellipse_points(c: Pos2, rx: f32, ry: f32, rot: f32, n: usize) -> Vec<Pos2> {
let (s, co) = rot.sin_cos();
(0..n)
.map(|i| {
let t = i as f32 / n as f32 * 2.0 * PI;
let (x, y) = (rx * t.cos(), ry * t.sin());
pos2(c.x + x * co - y * s, c.y + x * s + y * co)
})
.collect()
}
fn rounded_poly(rect: Rect, r: f32) -> Vec<Pos2> {
let mut pts = vec![];
let corners = [
(rect.right_bottom() - vec2(r, r), 0.0),
(rect.left_bottom() + vec2(r, -r), 0.5 * PI),
(rect.left_top() + vec2(r, r), PI),
(rect.right_top() + vec2(-r, r), 1.5 * PI),
];
for (c, a0) in corners {
for k in 0..=6 {
let a = a0 + k as f32 / 6.0 * 0.5 * PI;
pts.push(pos2(c.x + r * a.cos(), c.y + r * a.sin()));
}
}
pts
}
/// How a face is held at this moment (the original's mark: gaze, blink, squash, lift, spin).
/// What the eyes are doing besides looking: open, smiling (it just finished), or two flat
/// lines (something went wrong).
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub enum Eyes {
#[default]
Open,
Smile,
Flat,
}
#[derive(Clone, Copy, Debug)]
pub struct Pose {
pub eyes: Eyes,
/// Where it looks, -1…1 on each axis (y up).
pub gaze: egui::Vec2,
/// 0 = open, 1 = shut.
pub blink: f32,
/// Horizontal / vertical scale (a bounce squashes and stretches).
pub squash: egui::Vec2,
/// Upward hop, as a share of the size.
pub lift: f32,
/// Turn around the vertical axis in degrees (a spin).
pub yaw: f32,
/// Nod: eyes drop a little.
pub pitch: f32,
/// Turn around the middle, degrees (the face spins slowly while the bot thinks).
pub spin: f32,
}
impl Default for Pose {
fn default() -> Self {
Pose { eyes: Eyes::Open, gaze: egui::Vec2::ZERO, blink: 0.0, squash: vec2(1.0, 1.0), lift: 0.0, yaw: 0.0, pitch: 0.0, spin: 0.0 }
}
}
/// A point turned around a middle (the thinking spin).
fn spin_about(p: Pos2, c: Pos2, a: f32) -> Pos2 {
let d = p - c;
let (s, co) = a.sin_cos();
pos2(c.x + d.x * co - d.y * s, c.y + d.x * s + d.y * co)
}
/// A face with a pose: the body leans toward the gaze (the original turns it up to 26° sideways
/// and 19° up/down; drawn flat here as a shift), the eyes move further, blink and spin.
pub fn paint_posed(painter: &egui::Painter, rect: Rect, shape: &str, col: Color32, pose: Pose) {
// Not edge to edge: the face sits inside its cell with a little room around it.
let rect = Rect::from_center_size(rect.center(), rect.size() * 0.84);
let s = rect.width().min(rect.height()) / 2.0;
let turn = pose.yaw.to_radians().cos();
let sx = pose.squash.x * turn.abs().max(0.06);
let sy = pose.squash.y;
let shift = vec2(pose.gaze.x * 0.05 * s, -pose.gaze.y * 0.04 * s - pose.lift * s * 0.55);
let body = Rect::from_center_size(rect.center() + shift, vec2(rect.width() * sx, rect.height() * sy));
// Squash from the feet: keep the bottom where it was when it flattens.
let body = body.translate(vec2(0.0, (1.0 - sy) * rect.height() / 2.0));
let spin = pose.spin.to_radians();
paint_body(painter, body, shape, col, spin);
if turn <= 0.0 {
return;
}
let c = body.center();
let bs = body.width().min(body.height()) / 2.0;
let eye = eye_colour(col);
let open = (1.0 - pose.blink).clamp(0.06, 1.0);
let (k, fx, fy, sep) = face_fit(shape);
let look = vec2(pose.gaze.x * 0.16 * s * turn, -pose.gaze.y * 0.12 * s + pose.pitch * 0.01 * s);
for dx in [-sep, sep] {
let center =
spin_about(pos2(c.x + dx * k * body.width() / 2.0 + fx * s * sx, c.y + (0.02 + fy) * bs) + look, c, spin);
match pose.eyes {
Eyes::Open => {
painter.add(Shape::convex_polygon(ellipse_points(center, s * 0.11 * k * sx, s * 0.22 * k * open * sy, -0.35 + spin, 20), eye, Stroke::NONE));
}
// An arc, open downward (a smiling eye).
Eyes::Smile => {
let (w, h) = (s * 0.17 * k * sx, s * 0.17 * k * sy);
let pts: Vec<Pos2> = (0..=12).map(|k| { let a = PI + k as f32 / 12.0 * PI; spin_about(pos2(center.x + w * a.cos(), center.y + h * 0.5 + h * a.sin()), c, spin) }).collect();
painter.add(Shape::line(pts, Stroke::new((s * 0.1).max(1.5), eye)));
}
Eyes::Flat => {
let w = s * 0.17 * k * sx;
let (a, b) = (spin_about(pos2(center.x - w, center.y), c, spin), spin_about(pos2(center.x + w, center.y), c, spin));
painter.add(Shape::line(vec![a, b], Stroke::new((s * 0.1).max(1.5), eye)));
}
}
}
}
fn eye_colour(col: Color32) -> Color32 {
if col.r() as u32 + col.g() as u32 + col.b() as u32 > 600 { Color32::from_rgb(0x1c, 0x1c, 0x1c) } else { Color32::from_rgb(0xfc, 0xfc, 0xfc) }
}
pub fn paint(painter: &egui::Painter, rect: Rect, shape: &str, col: Color32) {
paint_body(painter, rect, shape, col, 0.0);
let c = rect.center();
let s = rect.width().min(rect.height()) / 2.0;
let eye = eye_colour(col);
for (p, rx, ry) in eye_rects(shape) {
painter.add(Shape::convex_polygon(ellipse_points(pos2(c.x + p.x * s, c.y + p.y * s), s * rx, s * ry, -0.35, 20), eye, Stroke::NONE));
}
}
fn paint_body(painter: &egui::Painter, rect: Rect, shape: &str, col: Color32, spin: f32) {
let c = rect.center();
let s = rect.width().min(rect.height()) / 2.0;
// The whole body (every shape, every circle) turns around the middle while the bot thinks.
let body = |pts: Vec<Pos2>| Shape::convex_polygon(if spin == 0.0 { pts } else { pts.into_iter().map(|p| spin_about(p, c, spin)).collect() }, col, Stroke::NONE);
let cc = |p: Pos2| if spin == 0.0 { p } else { spin_about(p, c, spin) };
match shape {
"squircle" => painter.add(body(rounded_poly(Rect::from_center_size(c, vec2(2.0 * s, 2.0 * s) * 0.92), s * 0.42))),
"capsule" => painter.add(body(rounded_poly(Rect::from_center_size(c, vec2(1.35 * s, 2.0 * s)), s * 0.66))),
"egg" => painter.add(body(
(0..48)
.map(|i| {
let t = i as f32 / 48.0 * 2.0 * PI;
let ry = if t.sin() < 0.0 { s * 1.0 } else { s * 0.86 };
pos2(c.x + s * 0.8 * t.cos(), c.y + 0.08 * s + ry * t.sin())
})
.collect(),
)),
"hex" => painter.add(body((0..6).map(|i| { let a = i as f32 / 6.0 * 2.0 * PI + PI / 6.0; pos2(c.x + s * a.cos(), c.y + s * a.sin()) }).collect())),
"gem" => painter.add(body(vec![pos2(c.x - s * 0.55, c.y - s * 0.8), pos2(c.x + s * 0.55, c.y - s * 0.8), pos2(c.x + s, c.y - s * 0.2), pos2(c.x, c.y + s), pos2(c.x - s, c.y - s * 0.2)])),
"arch" => painter.add(body(
(0..=24)
.map(|i| { let a = PI + i as f32 / 24.0 * PI; pos2(c.x + s * 0.85 * a.cos(), c.y - s * 0.15 + s * 0.85 * a.sin()) })
.chain([pos2(c.x + s * 0.85, c.y + s), pos2(c.x - s * 0.85, c.y + s)])
.collect(),
)),
"shield" => painter.add(body(vec![
pos2(c.x - s * 0.85, c.y - s * 0.9),
pos2(c.x + s * 0.85, c.y - s * 0.9),
pos2(c.x + s * 0.85, c.y + s * 0.05),
pos2(c.x + s * 0.5, c.y + s * 0.65),
pos2(c.x, c.y + s),
pos2(c.x - s * 0.5, c.y + s * 0.65),
pos2(c.x - s * 0.85, c.y + s * 0.05),
])),
"pebble" => painter.add(body(ellipse_points(c, s, s * 0.78, -0.25, 48))),
"cloud" => {
for (dx, dy, r) in [(-0.45, 0.15, 0.55), (0.45, 0.15, 0.55), (0.0, -0.2, 0.65), (0.0, 0.35, 0.55)] {
painter.circle_filled(cc(pos2(c.x + dx * s, c.y + dy * s)), r * s, col);
}
painter.add(Shape::Noop)
}
"heart" => {
painter.circle_filled(cc(pos2(c.x - s * 0.45, c.y - s * 0.25)), s * 0.55, col);
painter.circle_filled(cc(pos2(c.x + s * 0.45, c.y - s * 0.25)), s * 0.55, col);
painter.add(body(vec![pos2(c.x - s * 0.97, c.y - s * 0.1), pos2(c.x + s * 0.97, c.y - s * 0.1), pos2(c.x, c.y + s)]))
}
"star" => {
let pt = |i: usize, r: f32| { let a = -PI / 2.0 + i as f32 * PI / 5.0; pos2(c.x + r * a.cos(), c.y + 0.08 * s + r * a.sin()) };
for i in 0..5 {
painter.add(body(vec![pt(2 * i + 9, s * 0.48), pt(2 * i, s * 1.05), pt(2 * i + 1, s * 0.48)]));
}
painter.add(body((0..10).filter(|i| i % 2 == 1).map(|i| pt(i, s * 0.5)).collect()))
}
"moon" => {
// A circle with a wedge open to the right, split at a diameter so every
// part is convex (a crescent as one outline is not, and egui shapes are
// convex polygons). The mouth reads at 24 px; a thin crescent does not.
let sector = |a0: f32, a1: f32| {
let pts = std::iter::once(pos2(c.x, c.y))
.chain((0..=20).map(move |i| {
let a = a0 + (a1 - a0) * i as f32 / 20.0;
pos2(c.x + 0.95 * s * a.cos(), c.y + 0.95 * s * a.sin())
}))
.map(cc)
.collect();
body(pts)
};
painter.add(sector(0.6981, 4.0143)); // 40°..230°
painter.add(sector(4.0143, 5.5851)) // 230°..320°
}
"pumpkin" => {
// Rows of overlapping ellipses, a stem on top, two ribs drawn in.
painter.add(Shape::convex_polygon(
rounded_poly(Rect::from_center_size(cc(pos2(c.x + 0.02 * s, c.y - 0.8 * s)), vec2(0.14 * s, 0.36 * s)), 0.05 * s),
col.linear_multiply(0.72),
Stroke::NONE,
));
for (dx, dy, rx, ry) in [(-0.52, 0.05, 0.46, 0.72), (0.52, 0.05, 0.46, 0.72), (0.0, 0.12, 0.55, 0.8), (0.0, 0.3, 0.5, 0.62)] {
painter.add(Shape::convex_polygon(ellipse_points(cc(pos2(c.x + dx * s, c.y + dy * s)), rx * s, ry * s, 0.0, 32), col, Stroke::NONE));
}
let rib = Stroke::new(s * 0.045, col.linear_multiply(0.62));
for dx in [-0.26f32, 0.26] {
let pts: Vec<Pos2> = (0..=10)
.map(|i| {
let t = i as f32 / 10.0;
let y = -0.5 + 1.2 * t;
pos2(c.x + s * (dx + 0.1 * dx * (1.0 - (y / 0.62).powi(2))), c.y + s * (y + 0.1))
})
.map(cc)
.collect();
painter.add(Shape::line(pts, rib));
}
painter.add(Shape::Noop)
}
_ => painter.add(Shape::convex_polygon(ellipse_points(c, rect.width() / 2.0 * 0.95, rect.height() / 2.0 * 0.95, spin, 48), col, Stroke::NONE)),
};
}
pub fn avatar(ui: &mut egui::Ui, size: f32, shape: &str, col: Color32) -> egui::Response {
let (rect, resp) = ui.allocate_exact_size(vec2(size, size), egui::Sense::click());
paint(ui.painter(), rect, shape, col);
resp
}
#[cfg(test)]
mod tests {
use super::*;
/// 自訂顏色是點的,不是滑的:每列 12 個色相(淡→深四列),最後一列灰階;全部是不同的
/// 色碼,都算「自訂」。
#[test]
fn custom_swatches_are_a_grid_of_distinct_hex_colours() {
let rows = custom_swatches();
assert_eq!(rows.len(), 5);
assert!(rows.iter().all(|r| r.len() == SWATCH_COLUMNS));
let all: Vec<&String> = rows.iter().flatten().collect();
let mut uniq = all.clone();
uniq.sort();
uniq.dedup();
assert_eq!(uniq.len(), all.len(), "every swatch is a different colour");
assert!(all.iter().all(|h| is_custom(h) && parse_hex(h).as_deref() == Some(h.as_str())));
// The grey row runs light → dark.
let grey = &rows[4];
assert!(color(&grey[0]).r() > color(&grey[SWATCH_COLUMNS - 1]).r());
}
/// 色碼欄:有沒有 #、大小寫、前後空白都收;不是六位十六進位就不收。
#[test]
fn a_typed_hex_is_cleaned_or_refused() {
assert_eq!(parse_hex("#6B4A55").as_deref(), Some("#6b4a55"));
assert_eq!(parse_hex(" 6b4a55 ").as_deref(), Some("#6b4a55"));
assert_eq!(parse_hex("#6b4a5"), None);
assert_eq!(parse_hex("#6b4a5g"), None);
assert_eq!(parse_hex(""), None);
assert_eq!(parse_hex("red"), None);
}
#[test]
fn custom_hex_roundtrip() {
assert!(is_custom("#7a4bd6"));
assert!(!is_custom("blue"));
assert_eq!(color("#ff8000"), Color32::from_rgb(0xff, 0x80, 0x00));
// The picker's sliders are a stable round trip for every solid colour.
for name in ["#000000", "#ffffff", "#ff0000", "#00ff00", "#0000ff", "#7a4bd6", "#1c1c1c"] {
let hex = hex_of_hsv(hsv_of(name));
assert_eq!(color(&hex), color(name), "{name} -> {hex}");
}
// Presets answer too, so "make it custom" starts from the colour you had.
assert_eq!(color(&hex_of_hsv(hsv_of("blue"))), color("blue"));
}
/// Is `p` inside the closed polygon `pts` (even-odd ray test).
fn in_poly(p: Pos2, pts: &[Pos2]) -> bool {
let mut inside = false;
for i in 0..pts.len() {
let (a, b) = (pts[i], pts[(i + 1) % pts.len()]);
if (a.y > p.y) != (b.y > p.y) && p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x {
inside = !inside;
}
}
inside
}
fn in_ellipse(p: Pos2, c: Pos2, rx: f32, ry: f32, rot: f32) -> bool {
let (s, co) = rot.sin_cos();
let (dx, dy) = (p.x - c.x, p.y - c.y);
let (u, v) = (dx * co + dy * s, -dx * s + dy * co);
(u / rx).powi(2) + (v / ry).powi(2) <= 1.0
}
/// The body's real area in half-size units (centre at the origin), for the shapes
/// whose paint_body draws more than one convex part (cloud, heart, star, moon, pumpkin).
fn body_regions(shape: &str) -> Vec<(Pos2, f32, f32)> {
match shape {
"cloud" => [(-0.45f32, 0.15f32, 0.55f32), (0.45, 0.15, 0.55), (0.0, -0.2, 0.65), (0.0, 0.35, 0.55)]
.into_iter()
.map(|(x, y, r)| (pos2(x, y), r, r))
.collect(),
"heart" => vec![(pos2(-0.45, -0.25), 0.55, 0.55), (pos2(0.45, -0.25), 0.55, 0.55)],
_ => vec![],
}
}
fn star_pt(i: usize, r: f32) -> Pos2 {
let a = -PI / 2.0 + i as f32 * PI / 5.0;
pos2(r * a.cos(), 0.08 + r * a.sin())
}
/// The moon's body: a 0.95 disc with its wedge (mouth, ±40° around the +x axis) open.
fn in_moon(p: Pos2) -> bool {
let a = p.y.atan2(p.x);
p.to_vec2().length() <= 0.95 && (a - 0.6981).rem_euclid(2.0 * PI) <= 4.887
}
/// Is a point on the body (not the background)?
fn on_body(shape: &str, p: Pos2) -> bool {
if body_regions(shape).iter().any(|&(c, rx, ry)| in_ellipse(p, c, rx, ry, 0.0)) {
return true;
}
match shape {
"squircle" | "capsule" => {
let (hw, hh, r) = match shape {
"squircle" => (0.92, 0.92, 0.42),
_ => (0.675, 1.0, 0.66),
};
let inner = Rect::from_center_size(Pos2::ZERO, vec2(2.0 * (hw - r), 2.0 * (hh - r)));
let cx = p.x.clamp(inner.min.x, inner.max.x);
let cy = p.y.clamp(inner.min.y, inner.max.y);
(p.x - cx).powi(2) + (p.y - cy).powi(2) <= r * r
}
"egg" => in_ellipse(p, pos2(0.0, 0.08), 0.8, if p.y < 0.08 { 1.0 } else { 0.86 }, 0.0),
"hex" => in_poly(p, &(0..6).map(|i| { let a = i as f32 / 6.0 * 2.0 * PI + PI / 6.0; pos2(a.cos(), a.sin()) }).collect::<Vec<_>>()),
"gem" => in_poly(p, &[pos2(-0.55, -0.8), pos2(0.55, -0.8), pos2(1.0, -0.2), pos2(0.0, 1.0), pos2(-1.0, -0.2)]),
"arch" => {
if in_ellipse(p, pos2(0.0, -0.15), 0.85, 0.85, 0.0) && p.y <= -0.15 {
return true;
}
in_poly(p, &[pos2(-0.85, -0.15), pos2(0.85, -0.15), pos2(0.85, 1.0), pos2(-0.85, 1.0)])
}
"shield" => in_poly(p, &[pos2(-0.85, -0.9), pos2(0.85, -0.9), pos2(0.85, 0.05), pos2(0.5, 0.65), pos2(0.0, 1.0), pos2(-0.5, 0.65), pos2(-0.85, 0.05)]),
"pebble" => in_ellipse(p, Pos2::ZERO, 1.0, 0.78, -0.25),
"star" => {
let core: Vec<Pos2> = (0..10).filter(|i| i % 2 == 1).map(|i| star_pt(i, 0.5)).collect();
in_poly(p, &core) || (0..5).any(|i| in_poly(p, &[star_pt(2 * i + 9, 0.48), star_pt(2 * i, 1.05), star_pt(2 * i + 1, 0.48)]))
}
"moon" => in_moon(p),
"pumpkin" => [(-0.52f32, 0.05f32, 0.46f32, 0.72f32), (0.52, 0.05, 0.46, 0.72), (0.0, 0.12, 0.55, 0.8), (0.0, 0.3, 0.5, 0.62)]
.into_iter()
.any(|(x, y, rx, ry)| in_ellipse(p, pos2(x, y), rx, ry, 0.0)),
// The default is the blob's plain ellipse, sized from the rect (square here).
_ => in_ellipse(p, Pos2::ZERO, 0.95, 0.95, 0.0),
}
}
/// The eyes are placed from the outline, so a new concave shape without its
/// `face_fit` entry puts eyes on the background — the star did, quietly.
#[test]
fn eyes_stay_inside_every_shape() {
for shape in SHAPES {
for (c, rx, ry) in eye_rects(shape) {
// The eye is a rotated ellipse; its four corners bound it.
let (co, si) = 0.35f32.sin_cos();
for (ux, uy) in [(1.0, 1.0), (1.0, -1.0), (-1.0, 1.0), (-1.0, -1.0)] {
let p = pos2(c.x + (rx * ux * co - ry * uy * si), c.y + (rx * ux * si + ry * uy * co));
assert!(on_body(shape, p), "{shape}: eye corner ({:.3}, {:.3}) is off the body", p.x, p.y);
}
}
}
}
}