concinnity_core/components/sprite.rs
1// Screen-space sprite overlay schema.
2
3use crate::ecs::TextureHandle;
4use crate::ecs::asset_id::AssetId;
5use crate::ecs::asset_id::de_opt_asset_ref;
6use crate::ecs::de_opt_texture_handle;
7
8/// Screen-space 2D rectangle drawn as a UI overlay each frame.
9///
10/// Sprites are pixel-anchored quads with an RGBA tint. They draw alongside
11/// [TextLabel](#textlabel)s, ordered behind labels so text sits on top.
12///
13/// A sprite with a `texture` draws that image, multiplied by the tint (use a
14/// white tint to show the image unchanged; the tint's alpha fades it).
15/// Without one, the tint is drawn as a solid-coloured rectangle.
16///
17/// ```rust
18/// # use concinnity_core::components::Sprite;
19/// Sprite {
20/// x: 0.0,
21/// y: 0.0,
22/// width: 1280.0,
23/// height: 720.0,
24/// tint: [0.04, 0.06, 0.1, 1.0],
25/// ..Default::default()
26/// };
27/// ```
28#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
29#[serde(default)]
30pub struct Sprite {
31 /// Assigned by the loader; not authored.
32 #[serde(skip)]
33 pub asset_id: AssetId,
34 /// Left edge in screen pixels from the window's top-left.
35 pub x: f32,
36 /// Top edge in screen pixels from the window's top-left.
37 pub y: f32,
38 /// Width in screen pixels.
39 pub width: f32,
40 /// Height in screen pixels.
41 pub height: f32,
42 /// [Texture](#texture) to draw, sampled over the sprite's rect and
43 /// multiplied by `tint`. Omitted, the sprite is a solid `tint` fill.
44 #[serde(deserialize_with = "de_opt_texture_handle")]
45 pub texture: Option<TextureHandle>,
46 /// RGBA colour the rectangle is filled with, each channel in [0, 1].
47 pub tint: [f32; 4],
48 /// When true, the sprite acts as an in-engine cursor: it is drawn on top of
49 /// the other overlays as an arrow pointer tracking the mouse, with the
50 /// pointer at the arrow's tip. `tint` is the arrow fill (a contrasting
51 /// outline is added automatically) and `height` its size; `width` is
52 /// ignored so the arrow keeps its shape. The system cursor is hidden while
53 /// a visible `follow_cursor` sprite exists.
54 pub follow_cursor: bool,
55 /// When false the sprite is skipped each frame.
56 pub visible: bool,
57 /// [Screen](#screen) this sprite belongs to. Resolved automatically from
58 /// the naming convention (`<screen>_*`); you don't set this directly.
59 /// `None` means the sprite is always visible (e.g. a scene background).
60 #[serde(default, deserialize_with = "de_opt_asset_ref")]
61 pub screen: Option<AssetId>,
62 /// How a screen-owned sprite maps from the reference canvas to the window
63 /// when their aspect ratios differ.
64 pub fit: SpriteFit,
65 /// Corner rounding radius in the sprite's own pixel space. `0` keeps
66 /// sharp corners; larger values round each corner with a quarter-circle
67 /// arc (clamped to half the sprite's shorter side). The rounded edge is
68 /// softly anti-aliased.
69 pub corner_radius: f32,
70 /// Border stroke width in the sprite's own pixel space, drawn just inside
71 /// the sprite's outline and following its rounded corners. `0` draws no
72 /// border; larger values paint a ring of that width in `border_color`
73 /// (clamped to half the sprite's shorter side). An opaque fill is inset
74 /// under the ring; a translucent fill keeps the whole rect, so the ring
75 /// sits over its edge and whatever is behind still shows through.
76 pub border_width: f32,
77 /// RGBA colour of the border stroke, each channel in [0, 1]. Ignored when
78 /// `border_width` is `0`.
79 pub border_color: [f32; 4],
80}
81
82/// How a screen-owned overlay element (a [Sprite](#sprite), [TextLabel](#textlabel),
83/// or [HitRegion](#hitregion)) maps from the 1280x720 reference canvas to the
84/// live window when their aspect ratios differ.
85///
86/// Screen-owned UI is authored against a fixed reference canvas and uniformly
87/// scaled to the window at runtime.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, Default)]
89#[serde(rename_all = "lowercase")]
90pub enum SpriteFit {
91 /// The canvas fits inside the window, centered, leaving margins on the
92 /// shorter axis. UI elements keep their proportions and stay fully
93 /// visible.
94 #[default]
95 Fit,
96 /// The canvas fills the window, centered, cropping the overflowing axis
97 /// equally on both sides. Full-bleed stage imagery (scene backdrops,
98 /// character portraits) reaches the window edges without distorting, and
99 /// content anchored to a canvas edge stays flush with the window edge.
100 Cover,
101 /// The canvas keeps the `fit` scale (no cropping), but the whole overlay is
102 /// shifted so the reference bottom edge lands on the window bottom edge.
103 /// Bottom-anchored furniture (a visual-novel dialog box and its controls)
104 /// hugs the window bottom at any aspect ratio instead of floating above a
105 /// letterbox margin.
106 Bottom,
107}
108
109impl Default for Sprite {
110 fn default() -> Self {
111 Self {
112 asset_id: AssetId::default(),
113 x: 0.0,
114 y: 0.0,
115 width: 100.0,
116 height: 100.0,
117 texture: None,
118 tint: [1.0, 1.0, 1.0, 1.0],
119 follow_cursor: false,
120 visible: true,
121 screen: None,
122 fit: SpriteFit::Fit,
123 corner_radius: 0.0,
124 border_width: 0.0,
125 border_color: [0.0, 0.0, 0.0, 1.0],
126 }
127 }
128}
129
130#[cfg(test)]
131mod tests {
132 use super::*;
133
134 #[test]
135 fn a_blank_sprite_is_a_visible_untinted_square_with_no_border() {
136 let s = Sprite::default();
137 assert_eq!((s.width, s.height), (100.0, 100.0));
138 assert_eq!(s.tint, [1.0, 1.0, 1.0, 1.0]);
139 assert!(s.visible);
140 assert!(!s.follow_cursor);
141 assert_eq!(s.fit, SpriteFit::Fit);
142 assert_eq!(s.corner_radius, 0.0);
143 // Zero width is what suppresses the border, so its colour is irrelevant.
144 assert_eq!(s.border_width, 0.0);
145 assert!(s.texture.is_none());
146 assert!(s.screen.is_none());
147 assert_eq!(SpriteFit::default(), SpriteFit::Fit);
148 }
149
150 #[test]
151 fn fit_names_parse_in_lowercase() {
152 let f = |s: &str| serde_json::from_str::<SpriteFit>(s).unwrap();
153 assert_eq!(f(r#""fit""#), SpriteFit::Fit);
154 assert_eq!(f(r#""cover""#), SpriteFit::Cover);
155 assert_eq!(f(r#""bottom""#), SpriteFit::Bottom);
156 assert_eq!(
157 serde_json::to_string(&SpriteFit::Bottom).unwrap(),
158 r#""bottom""#
159 );
160 }
161
162 #[test]
163 fn a_cursor_sprite_parses_and_round_trips_through_postcard() {
164 crate::test_support::install_resolvers();
165 let s: Sprite = serde_json::from_str(
166 r#"{"x":10,"y":20,"width":32,"height":32,"texture":"tex_cursor",
167 "tint":[1,1,1,0.8],"follow_cursor":true,"visible":false,"screen":"menu",
168 "fit":"cover","corner_radius":4,"border_width":2,"border_color":[1,0,0,1]}"#,
169 )
170 .unwrap();
171 assert_eq!(s.texture, Some(TextureHandle(10)));
172 assert_eq!(s.screen, Some(AssetId(4)));
173 assert!(s.follow_cursor);
174 assert!(!s.visible);
175
176 let bytes = postcard::to_allocvec(&s).unwrap();
177 let back: Sprite = postcard::from_bytes(&bytes).unwrap();
178 assert_eq!((back.x, back.y), (10.0, 20.0));
179 assert_eq!(back.tint, [1.0, 1.0, 1.0, 0.8]);
180 assert_eq!(back.fit, SpriteFit::Cover);
181 assert_eq!(back.corner_radius, 4.0);
182 assert_eq!(back.border_width, 2.0);
183 assert_eq!(back.border_color, [1.0, 0.0, 0.0, 1.0]);
184 assert_eq!(back.asset_id, AssetId::default());
185 }
186}