1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
use crate::Pt;
use std::sync::Arc;
/// Rectangle bounds for defining sub-regions of images.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Bounds {
/// X coordinate of the top-left corner.
pub(crate) x: Pt,
/// Y coordinate of the top-left corner.
pub(crate) y: Pt,
/// Width of the bounds.
pub(crate) width: Pt,
/// Height of the bounds.
pub(crate) height: Pt,
}
impl Bounds {
/// Returns the width of the bounds.
pub fn width(&self) -> Pt {
self.width
}
/// Returns the height of the bounds.
pub fn height(&self) -> Pt {
self.height
}
/// Returns the X coordinate of the top-left corner.
pub fn x(&self) -> Pt {
self.x
}
/// Returns the Y coordinate of the top-left corner.
pub fn y(&self) -> Pt {
self.y
}
}
impl Bounds {
/// Creates new bounds with the specified dimensions.
pub fn new(x: Pt, y: Pt, width: Pt, height: Pt) -> Self {
Self {
x,
y,
width,
height,
}
}
}
/// Handle to an image resource.
///
/// Images are GPU textures that can be drawn to the screen. They are reference-counted
/// and can be cloned cheaply.
#[derive(Debug, Clone, Copy)]
pub struct Image {
pub(crate) id: u32,
pub(crate) x: Pt,
pub(crate) y: Pt,
pub(crate) width: Pt,
pub(crate) height: Pt,
pub(crate) pixel_width: u32,
pub(crate) pixel_height: u32,
}
impl Image {
/// Creates a new image from RGBA8 data.
///
/// `width` and `height` are logical sizes in [`Pt`][crate::Pt]. The pixel
/// dimensions used for atlas packing are derived from those logical values.
///
/// When starting from encoded image bytes, prefer the helpers in
/// [`crate::utils::image`] (behind the `utils` feature) so the original
/// pixel dimensions are preserved and the logical size is derived from the
/// current scale factor.
pub fn new(
ctx: &mut crate::Context,
width: Pt,
height: Pt,
rgba: &[u8],
) -> anyhow::Result<Self> {
Self::new_from_rgba8(ctx, width, height, rgba)
}
/// Returns the logical width of the image.
pub fn width(&self) -> Pt {
self.width
}
/// Returns the logical height of the image.
pub fn height(&self) -> Pt {
self.height
}
/// Returns the internal unique identifier for this image.
pub fn id(&self) -> u32 {
self.id
}
/// Returns true if the image is ready for rendering.
pub fn is_ready(&self, ctx: &crate::Context) -> bool {
ctx.registry
.images
.get(self.index())
.and_then(|v| v.as_ref())
.map(|e| e.is_ready())
.unwrap_or(false)
}
}
impl Image {
pub(crate) fn index(self) -> usize {
self.id as usize
}
}
impl PartialEq for Image {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for Image {}
impl std::hash::Hash for Image {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
impl Image {
/// Errors
/// Returns an error if the data length doesn't match width * height * 4.
pub(crate) fn new_from_rgba8(
ctx: &mut crate::Context,
width: Pt,
height: Pt,
rgba: &[u8],
) -> anyhow::Result<Self> {
let pixel_width = width.to_u32_clamped().max(1);
let pixel_height = height.to_u32_clamped().max(1);
let expected_len = (pixel_width as usize) * (pixel_height as usize) * 4;
if rgba.len() != expected_len {
anyhow::bail!(
"RGBA data length mismatch: expected {} ({}x{}x4), got {}",
expected_len,
pixel_width,
pixel_height,
rgba.len()
);
}
let image = ctx.register_image(pixel_width, pixel_height, width, height, rgba);
Ok(image)
}
#[cfg(feature = "utils")]
pub(crate) fn new_from_rgba8_with_pixels(
ctx: &mut crate::Context,
pixel_width: u32,
pixel_height: u32,
width: Pt,
height: Pt,
rgba: &[u8],
) -> anyhow::Result<Self> {
let expected_len = (pixel_width as usize) * (pixel_height as usize) * 4;
if rgba.len() != expected_len {
anyhow::bail!(
"RGBA data length mismatch: expected {} ({}x{}x4), got {}",
expected_len,
pixel_width,
pixel_height,
rgba.len()
);
}
let image = ctx.register_image(pixel_width, pixel_height, width, height, rgba);
Ok(image)
}
/// Arguments
/// * `image` - The source image to copy
pub fn from_image(ctx: &mut crate::Context, image: Image) -> anyhow::Result<Self> {
Self::sub_image(
ctx,
image,
Bounds {
x: image.x,
y: image.y,
width: image.width,
height: image.height,
},
)
}
/// Creates a sub-image from a region of an existing image.
///
/// The sub-image shares the same GPU texture as the source image but renders
/// only the specified region.
///
/// # Arguments
/// * `image` - The source image
/// * `bounds` - The region to extract
///
/// # Errors
/// Returns an error if the bounds are out of range.
pub fn sub_image(
ctx: &mut crate::Context,
image: Image,
bounds: Bounds,
) -> anyhow::Result<Self> {
// Validation: Ensure sub-image bounds are within parent image bounds
// Note: We use a small epsilon for float comparisons if needed, but here direct bounds check is usually fine
if bounds.x.0 < 0.0
|| bounds.y.0 < 0.0
|| bounds.x.0 + bounds.width.0 > image.width.0 + 0.001
|| bounds.y.0 + bounds.height.0 > image.height.0 + 0.001
{
anyhow::bail!(
"Sub-image bounds [x:{}, y:{}, w:{}, h:{}] are out of range for parent image [w:{}, h:{}]",
bounds.x.0,
bounds.y.0,
bounds.width.0,
bounds.height.0,
image.width.0,
image.height.0
);
}
let id = ctx.register_sub_image(image, bounds)?;
Ok(Self {
id,
x: bounds.x,
y: bounds.y,
width: bounds.width,
height: bounds.height,
pixel_width: ((image.pixel_width as f32) * (bounds.width.0 / image.width.0))
.round()
.max(1.0) as u32,
pixel_height: ((image.pixel_height as f32) * (bounds.height.0 / image.height.0))
.round()
.max(1.0) as u32,
})
}
/// Draws this image to the context with the specified options.
///
/// # Arguments
/// * `context` - The drawing context to add this image to
/// * `options` - Drawing options (position, rotation, scale)
///
/// # Example
/// ```ignore
/// # use spottedcat::{Context, Image, DrawOption, Pt};
/// # let mut ctx = Context::new();
/// # let rgba = vec![255u8; 2 * 2 * 4];
/// # let image = Image::new(&mut ctx, Pt::from(2.0), Pt::from(2.0), &rgba).unwrap();
/// let mut opts = DrawOption::default();
/// opts = opts.with_position([spottedcat::Pt::from(100.0), spottedcat::Pt::from(100.0)]);
/// opts = opts.with_scale([2.0, 2.0]);
/// image.draw(&mut ctx, opts);
/// ```
pub fn draw(self, ctx: &mut crate::Context, options: crate::DrawOption) {
ctx.push(crate::drawable::DrawCommand::Image(Box::new(
crate::drawable::ImageCommand {
id: self.id,
opts: options,
shader_id: 0,
shader_opts: crate::ShaderOpts::default(),
size: [self.width, self.height],
},
)));
}
/// Draws this image with a custom image shader registered through the context.
pub fn draw_with_shader(
self,
ctx: &mut crate::Context,
shader_id: u32,
options: crate::DrawOption,
shader_opts: crate::ShaderOpts,
) {
ctx.push(crate::drawable::DrawCommand::Image(Box::new(
crate::drawable::ImageCommand {
id: self.id,
opts: options,
shader_id,
shader_opts,
size: [self.width, self.height],
},
)));
}
#[allow(dead_code)]
pub fn clear(self, ctx: &mut crate::Context, color: [f32; 4]) -> anyhow::Result<()> {
ctx.push(crate::drawable::DrawCommand::ClearImage(self.id, color));
Ok(())
}
#[allow(dead_code)]
pub fn copy_from(self, ctx: &mut crate::Context, src: Image) -> anyhow::Result<()> {
ctx.push(crate::drawable::DrawCommand::CopyImage(self.id, src.id));
Ok(())
}
/// Returns the source-texture bounds of this image.
///
/// For sub-images, this represents the region relative to the parent atlas.
pub fn bounds(self) -> anyhow::Result<Bounds> {
Ok(Bounds {
x: self.x,
y: self.y,
width: self.width,
height: self.height,
})
}
/// Destroys the image and frees its GPU resources.
///
/// Returns true if the image was successfully destroyed.
pub fn destroy(self, ctx: &mut crate::Context) -> bool {
ctx.registry
.images
.get_mut(self.index())
.and_then(|v| v.take())
.is_some()
}
/// Returns the global screen-space bounds of this image when drawn.
///
/// # Arguments
/// * `options` - The same DrawOption used when calling `draw()`
pub(crate) fn screen_bounds(self, options: crate::DrawOption) -> [Pt; 4] {
let pos = options.position();
let scale = options.scale();
let x = pos[0];
let y = pos[1];
let w = self.width * scale[0];
let h = self.height * scale[1];
[x, y, w, h]
}
pub fn with_clip_scope_draw<F, D>(
self,
ctx: &mut crate::Context,
options: crate::DrawOption,
draw: D,
f: F,
) where
D: FnOnce(Self, &mut crate::Context, crate::DrawOption),
F: FnOnce(&mut crate::Context),
{
// First, draw the parent image to establish the clip region
draw(self, ctx, options);
// Then set up the clipping state for child elements
let parent_opts_abs = if let Some(info) = ctx.last_image_draw_info(self.id) {
info.opts
} else {
let state = ctx.current_draw_state();
options.apply_state(&state)
};
let parent_pos_abs = parent_opts_abs.position();
let parent_bounds = self.screen_bounds(parent_opts_abs);
// Get the current origin to calculate relative position
let current_origin = ctx.current_draw_state().position;
let parent_pos_relative = [
parent_pos_abs[0] - current_origin[0],
parent_pos_abs[1] - current_origin[1],
];
let state = crate::DrawState {
position: parent_pos_relative,
clip: Some([
parent_bounds[0],
parent_bounds[1],
parent_bounds[2],
parent_bounds[3],
]),
shader_id: ctx.current_draw_state().shader_id,
shader_opts: ctx.current_draw_state().shader_opts,
layer: 0,
};
ctx.push_state(state);
f(ctx);
ctx.pop_state();
}
pub fn with_clip_scope<F>(self, ctx: &mut crate::Context, options: crate::DrawOption, f: F)
where
F: FnOnce(&mut crate::Context),
{
self.with_clip_scope_draw(ctx, options, |img, ctx, opts| img.draw(ctx, opts), f);
}
pub fn with_shader_scope<F>(
self,
ctx: &mut crate::Context,
shader_id: u32,
shader_opts: crate::ShaderOpts,
f: F,
) where
F: FnOnce(&mut crate::Context),
{
let state = crate::DrawState {
shader_id: Some(shader_id),
shader_opts: Some(shader_opts),
..Default::default()
};
// We do NOT set position or clip here.
// position will be (0,0) so it won't shift children.
// clip is None, so push_state will retain the current clip.
ctx.push_state(state);
f(ctx);
ctx.pop_state();
}
}
#[derive(Debug, Clone)]
pub(crate) struct ImageEntry {
pub(crate) atlas_index: Option<u32>,
pub(crate) bounds: Bounds,
pub(crate) pixel_width: u32,
pub(crate) pixel_height: u32,
pub(crate) uv_rect: Option<[f32; 4]>, // [u, v, w, h]
pub(crate) visible: bool,
pub(crate) raw_data: Option<Arc<[u8]>>,
pub(crate) parent_id: Option<u32>,
}
impl ImageEntry {
pub(crate) fn new(
atlas_index: Option<u32>,
bounds: Bounds,
pixel_width: u32,
pixel_height: u32,
uv_rect: Option<[f32; 4]>,
raw_data: Option<Arc<[u8]>>,
parent_id: Option<u32>,
) -> Self {
Self {
atlas_index,
bounds,
pixel_width,
pixel_height,
uv_rect,
visible: true,
raw_data,
parent_id,
}
}
pub(crate) fn is_ready(&self) -> bool {
self.atlas_index.is_some() && self.uv_rect.is_some()
}
}