cotis-raylib 0.1.0-alpha

Raylib-backed renderer for Cotis
Documentation
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
//! Raylib draw implementations for `cotis-defaults` render commands and custom drawables.
//!
//! [`RaylibDrawable`] is the extension trait for types that can be drawn by [`RaylibRender`](crate::renderer::RaylibRender).
//! Built-in impls cover [`Rectangle`], [`Text`], [`Border`], [`Image`], [`ClipStart`]/[`ClipEnd`], and
//! [`RenderTList`](cotis_defaults::render_commands::render_t_list::RenderTList).
//!
//! # Custom drawables
//!
//! ```rust,ignore
//! use cotis_raylib::drawables::{RaylibDrawable, RaylibDrawContext};
//!
//! struct CircleDrawable { cx: f32, cy: f32, radius: f32 }
//!
//! impl RaylibDrawable for CircleDrawable {
//!     fn draw(self: Box<Self>, ctx: &mut RaylibDrawContext<'_, '_>) {
//!         // ctx.d.draw_circle(...)
//!     }
//!     fn scale_by(&mut self, factor: f32) {
//!         self.cx *= factor;
//!         self.cy *= factor;
//!         self.radius *= factor;
//!     }
//! }
//! ```
//!
//! # Color conversion
//!
//! Solid colors are converted by truncating each `f32` channel to `u8`
//! (expects cotis-defaults `0..=255` range; values outside that range are not clamped).

use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use raylib::drawing::{RaylibDraw, RaylibDrawHandle};
use raylib::math::Vector2;

use crate::fonts::ScalableFont;
use crate::raylib_images::GenericCompatibleImage;
use crate::renderer::RaylibRender;
use cotis_defaults::colors::Color as CotisColor;
use cotis_defaults::render_commands::render_t_list::{IsRenderList, RenderTList};
use cotis_defaults::render_commands::*;
use cotis_utils::math::BoundingBox;
use raylib::texture::Texture2D;

/// Per-frame drawing context passed to [`RaylibDrawable::draw`].
pub struct RaylibDrawContext<'d, 'rl> {
    /// Active raylib draw handle for the current frame.
    pub d: &'d mut RaylibDrawHandle<'rl>,
    /// Shared font table from [`RaylibRender`](crate::renderer::RaylibRender).
    pub fonts: Arc<Mutex<HashMap<usize, ScalableFont>>>,
    /// Stack of active clip rectangles `(x, y, width, height)` in layout coordinates.
    pub clip_stack: &'d mut Vec<(f32, f32, f32, f32)>,
    /// Path-keyed texture cache; `Some` for [`RenderTList`](cotis_defaults::render_commands::render_t_list::RenderTList) drawing, `None` for `Box<dyn RaylibDrawable>`.
    pub image_cache: Option<&'d HashMap<String, Arc<Texture2D>>>,
}

/// Types that can be drawn by [`RaylibRender`](crate::renderer::RaylibRender).
pub trait RaylibDrawable {
    /// Renders this command using context `ctx`.
    fn draw(self: Box<Self>, ctx: &mut RaylibDrawContext<'_, '_>);
    /// Scales all positional and size data by `factor` in-place (not colors).
    ///
    /// Used by [`RayTestRender`](crate::test_render::RayTestRender) for logical-resolution scaling.
    fn scale_by(&mut self, factor: f32);
    /// Preloads path-based images into [`RaylibRender::image_cache`](crate::renderer::RaylibRender::image_cache).
    ///
    /// Default no-op; [`RenderTList`](cotis_defaults::render_commands::render_t_list::RenderTList) calls this before drawing.
    fn preload_generic_images(&self, _render: &mut RaylibRender) {}
}

// ── Helpers ──────────────────────────────────────────────────────────────────

/// Converts a cotis-defaults [`CotisColor`] to a raylib color by truncating each channel `f32` to `u8`.
///
/// Expects channel values in the `0..=255` range per cotis-defaults. Values outside that range are
/// not clamped (`256.0` truncates to `0`).
pub(crate) fn cotis_to_raylib_color(c: CotisColor) -> raylib::color::Color {
    raylib::color::Color::new(c.r as u8, c.g as u8, c.b as u8, c.a as u8)
}

fn scale_corner_radii(r: &mut CornerRadii, factor: f32) {
    r.top_left *= factor;
    r.top_right *= factor;
    r.bottom_left *= factor;
    r.bottom_right *= factor;
}

fn scale_bounding_box(bb: &mut BoundingBox, factor: f32) {
    bb.x *= factor;
    bb.y *= factor;
    bb.width *= factor;
    bb.height *= factor;
}

fn intersect_clip(a: (f32, f32, f32, f32), b: (f32, f32, f32, f32)) -> (f32, f32, f32, f32) {
    let ax2 = a.0 + a.2;
    let ay2 = a.1 + a.3;
    let bx2 = b.0 + b.2;
    let by2 = b.1 + b.3;
    let x = a.0.max(b.0);
    let y = a.1.max(b.1);
    let w = ax2.min(bx2) - x;
    let h = ay2.min(by2) - y;
    (x, y, w.max(0.0), h.max(0.0))
}

// ── Rectangle ────────────────────────────────────────────────────────────────
//
// Solid fill via raylib rectangles/rounded rects. With `complex-color`, delegates to gradient painting.
// Rounded corners use only `corner_radii.top_left` for the radius formula.

impl<'a, E> RaylibDrawable for Rectangle<'a, E> {
    fn draw(self: Box<Self>, ctx: &mut RaylibDrawContext<'_, '_>) {
        let bb = self.info.bounding_box;

        #[cfg(feature = "complex-color")]
        {
            let clip = ctx.clip_stack.last().copied();
            crate::color_paint::draw_color_layer_in_rect(
                ctx.d,
                bb.x,
                bb.y,
                bb.width,
                bb.height,
                &self.color,
                &self.corner_radii,
                clip,
            );
        }

        #[cfg(not(feature = "complex-color"))]
        {
            if self.color.a > 0.0 {
                if self.corner_radii.top_left > 0.0 {
                    let radius = (self.corner_radii.top_left * 2.0)
                        / if bb.width > bb.height {
                            bb.height
                        } else {
                            bb.width
                        };
                    ctx.d.draw_rectangle_rounded(
                        raylib::math::Rectangle::new(bb.x, bb.y, bb.width, bb.height),
                        radius,
                        8,
                        cotis_to_raylib_color(self.color),
                    );
                } else {
                    ctx.d.draw_rectangle(
                        bb.x as i32,
                        bb.y as i32,
                        bb.width as i32,
                        bb.height as i32,
                        cotis_to_raylib_color(self.color),
                    );
                }
            }
        }
    }

    fn scale_by(&mut self, factor: f32) {
        scale_bounding_box(&mut self.info.bounding_box, factor);
        scale_corner_radii(&mut self.corner_radii, factor);
    }
}

// ── Text ─────────────────────────────────────────────────────────────────────
//
// Uses the font ID from the command; missing fonts fall back to raylib's default font.
// With `complex-color`, draws per-glyph gradient tints.

impl<'a, E> RaylibDrawable for Text<'a, E> {
    fn draw(self: Box<Self>, ctx: &mut RaylibDrawContext<'_, '_>) {
        let bb = self.info.bounding_box;
        let text_str: &str = self.text.as_ref();

        let fonts_arc = ctx.fonts.clone();
        let mut guard = fonts_arc.lock().unwrap();

        #[cfg(feature = "complex-color")]
        {
            if let Some(font) = guard.get_mut(&(self.font_id as usize)) {
                let f = font.get_font_for_size(self.font_size as usize);
                crate::color_paint::draw_text_color_layer(
                    ctx.d,
                    f,
                    text_str,
                    Vector2::new(bb.x, bb.y),
                    self.font_size,
                    self.letter_spacing,
                    &self.color,
                );
            } else {
                let c = crate::color_paint::text_color_at(&self.color, 0.0);
                ctx.d.draw_text(
                    text_str,
                    bb.x as i32,
                    bb.y as i32,
                    self.font_size as i32,
                    crate::color_paint::cotis_color_to_raylib(c),
                );
            }
        }

        #[cfg(not(feature = "complex-color"))]
        {
            if let Some(font) = guard.get_mut(&(self.font_id as usize)) {
                let raylib_font = font.get_font_for_size(self.font_size as usize);
                ctx.d.draw_text_ex(
                    raylib_font,
                    text_str,
                    Vector2::new(bb.x, bb.y),
                    self.font_size,
                    self.letter_spacing,
                    cotis_to_raylib_color(self.color),
                );
            } else {
                ctx.d.draw_text(
                    text_str,
                    bb.x as i32,
                    bb.y as i32,
                    self.font_size as i32,
                    cotis_to_raylib_color(self.color),
                );
            }
        }
    }

    fn scale_by(&mut self, factor: f32) {
        scale_bounding_box(&mut self.info.bounding_box, factor);
        self.font_size *= factor;
        self.letter_spacing *= factor;
        self.line_height *= factor;
    }
}

// ── Border ───────────────────────────────────────────────────────────────────
//
// Four edge rectangles plus corner arc rings. `width.between_children` is scaled but not drawn.

impl<'a, E> RaylibDrawable for Border<'a, E> {
    fn draw(self: Box<Self>, ctx: &mut RaylibDrawContext<'_, '_>) {
        let bb = self.info.bounding_box;
        let color = cotis_to_raylib_color(self.color);

        if self.width.left > 0.0 {
            ctx.d.draw_rectangle(
                bb.x as i32,
                (bb.y + self.corner_radii.top_left) as i32,
                self.width.left as i32,
                (bb.height - self.corner_radii.top_left - self.corner_radii.bottom_left) as i32,
                color,
            );
        }
        if self.width.right > 0.0 {
            ctx.d.draw_rectangle(
                (bb.x + bb.width - self.width.right) as i32,
                (bb.y + self.corner_radii.top_right) as i32,
                self.width.right as i32,
                (bb.height - self.corner_radii.top_right - self.corner_radii.bottom_right) as i32,
                color,
            );
        }
        if self.width.top > 0.0 {
            ctx.d.draw_rectangle(
                (bb.x + self.corner_radii.top_left) as i32,
                bb.y as i32,
                (bb.width - self.corner_radii.top_left - self.corner_radii.top_right) as i32,
                self.width.top as i32,
                color,
            );
        }
        if self.width.bottom > 0.0 {
            ctx.d.draw_rectangle(
                (bb.x + self.corner_radii.bottom_left) as i32,
                (bb.y + bb.height - self.width.bottom) as i32,
                (bb.width - self.corner_radii.bottom_left - self.corner_radii.bottom_right) as i32,
                self.width.bottom as i32,
                color,
            );
        }

        if self.corner_radii.top_left > 0.0 {
            ctx.d.draw_ring(
                Vector2::new(
                    bb.x + self.corner_radii.top_left,
                    bb.y + self.corner_radii.top_left,
                ),
                self.corner_radii.top_left - self.width.top,
                self.corner_radii.top_left,
                180.0,
                270.0,
                10,
                color,
            );
        }
        if self.corner_radii.top_right > 0.0 {
            ctx.d.draw_ring(
                Vector2::new(
                    bb.x + bb.width - self.corner_radii.top_right,
                    bb.y + self.corner_radii.top_right,
                ),
                self.corner_radii.top_right - self.width.top,
                self.corner_radii.top_right,
                270.0,
                360.0,
                10,
                color,
            );
        }
        if self.corner_radii.bottom_left > 0.0 {
            ctx.d.draw_ring(
                Vector2::new(
                    bb.x + self.corner_radii.bottom_left,
                    bb.y + bb.height - self.corner_radii.bottom_left,
                ),
                self.corner_radii.bottom_left - self.width.bottom,
                self.corner_radii.bottom_left,
                90.0,
                180.0,
                10,
                color,
            );
        }
        if self.corner_radii.bottom_right > 0.0 {
            ctx.d.draw_ring(
                Vector2::new(
                    bb.x + bb.width - self.corner_radii.bottom_right,
                    bb.y + bb.height - self.corner_radii.bottom_right,
                ),
                self.corner_radii.bottom_right - self.width.bottom,
                self.corner_radii.bottom_right,
                0.0,
                90.0,
                10,
                color,
            );
        }
    }

    fn scale_by(&mut self, factor: f32) {
        scale_bounding_box(&mut self.info.bounding_box, factor);
        scale_corner_radii(&mut self.corner_radii, factor);
        self.width.left *= factor;
        self.width.right *= factor;
        self.width.top *= factor;
        self.width.bottom *= factor;
        self.width.between_children *= factor;
    }
}

// ── Image ────────────────────────────────────────────────────────────────────
//
// Textures are scaled horizontally to `bounding_box.width`. Requires preload via
// [`RaylibDrawable::preload_generic_images`] or [`RaylibRender::translate_generic_image`].

impl<'a, I: GenericCompatibleImage, E> RaylibDrawable for Image<'a, I, E> {
    fn draw(self: Box<Self>, ctx: &mut RaylibDrawContext<'_, '_>) {
        GenericCompatibleImage::load_texture(self.data.as_ref(), ctx);
        let texture = GenericCompatibleImage::get_texture(self.data.as_ref(), ctx);

        let bb = self.info.bounding_box;
        #[cfg(feature = "complex-color")]
        {
            let clip = ctx.clip_stack.last().copied();
            crate::color_paint::draw_color_layer_in_rect(
                ctx.d,
                bb.x,
                bb.y,
                bb.width,
                bb.height,
                &self.background_color,
                &self.corner_radii,
                clip,
            );
        }

        #[cfg(not(feature = "complex-color"))]
        {
            if self.background_color.a > 0.0 {
                ctx.d.draw_rectangle(
                    bb.x as i32,
                    bb.y as i32,
                    bb.width as i32,
                    bb.height as i32,
                    cotis_to_raylib_color(self.background_color),
                );
            }
        }

        ctx.d.draw_texture_ex(
            &*texture,
            Vector2::new(bb.x, bb.y),
            0.0,
            bb.width / texture.width as f32,
            raylib::color::Color::WHITE,
        );
    }

    fn scale_by(&mut self, factor: f32) {
        scale_bounding_box(&mut self.info.bounding_box, factor);
        scale_corner_radii(&mut self.corner_radii, factor);
    }

    fn preload_generic_images(&self, render: &mut RaylibRender) {
        render.translate_generic_image(self.data.as_ref());
    }
}

// ── ClipStart ────────────────────────────────────────────────────────────────
//
// Pushes an intersected scissor rect onto `clip_stack` and enables raylib scissor mode.

impl<'a, E> RaylibDrawable for ClipStart<'a, E> {
    fn draw(self: Box<Self>, ctx: &mut RaylibDrawContext<'_, '_>) {
        let bb = self.info.bounding_box;
        let clip_rect = (bb.x, bb.y, bb.width.max(0.0), bb.height.max(0.0));
        let effective = if let Some(parent) = ctx.clip_stack.last().copied() {
            intersect_clip(parent, clip_rect)
        } else {
            clip_rect
        };
        ctx.clip_stack.push(effective);
        unsafe {
            raylib::ffi::BeginScissorMode(
                effective.0 as i32,
                effective.1 as i32,
                effective.2 as i32,
                effective.3 as i32,
            );
        }
    }

    fn scale_by(&mut self, factor: f32) {
        scale_bounding_box(&mut self.info.bounding_box, factor);
        scale_corner_radii(&mut self.corner_radii, factor);
    }
}

// ── ClipEnd ──────────────────────────────────────────────────────────────────
//
// Pops the clip stack and restores the parent scissor rect if any.

impl RaylibDrawable for ClipEnd {
    fn draw(self: Box<Self>, ctx: &mut RaylibDrawContext<'_, '_>) {
        if ctx.clip_stack.pop().is_some() {
            unsafe {
                raylib::ffi::EndScissorMode();
                if let Some(prev) = ctx.clip_stack.last().copied() {
                    raylib::ffi::BeginScissorMode(
                        prev.0 as i32,
                        prev.1 as i32,
                        prev.2 as i32,
                        prev.3 as i32,
                    );
                }
            }
        }
    }

    fn scale_by(&mut self, _factor: f32) {}
}

// ── RenderOutputToDrawables ───────────────────────────────────────────────────

// ── RenderTList ───────────────────────────────────────────────────────────────
//
// These two impls allow `RenderTList` heterogeneous command lists to be drawn by raylib.
// The recursive case handles `RenderTList<T, L>` where `L` itself implements `RaylibDrawable`
// (i.e. a non-terminal tail), and the base case handles `RenderTList<T, ()>` (terminal tail).

impl<T: RaylibDrawable, L: RaylibDrawable + IsRenderList> RaylibDrawable for RenderTList<T, L> {
    fn draw(self: Box<Self>, ctx: &mut RaylibDrawContext<'_, '_>) {
        match *self {
            RenderTList::Type(t) => Box::new(t).draw(ctx),
            RenderTList::List(l) => Box::new(l).draw(ctx),
        }
    }

    fn scale_by(&mut self, factor: f32) {
        match self {
            RenderTList::Type(t) => t.scale_by(factor),
            RenderTList::List(l) => l.scale_by(factor),
        }
    }

    fn preload_generic_images(&self, render: &mut RaylibRender) {
        match self {
            RenderTList::Type(t) => t.preload_generic_images(render),
            RenderTList::List(l) => l.preload_generic_images(render),
        }
    }
}

impl<T: RaylibDrawable> RaylibDrawable for RenderTList<T, ()> {
    fn draw(self: Box<Self>, ctx: &mut RaylibDrawContext<'_, '_>) {
        match *self {
            RenderTList::Type(t) => Box::new(t).draw(ctx),
            RenderTList::List(()) => {}
        }
    }

    fn scale_by(&mut self, factor: f32) {
        match self {
            RenderTList::Type(t) => t.scale_by(factor),
            RenderTList::List(()) => {}
        }
    }

    fn preload_generic_images(&self, render: &mut RaylibRender) {
        match self {
            RenderTList::Type(t) => t.preload_generic_images(render),
            RenderTList::List(()) => {}
        }
    }
}

// TryFromRenderOutput impls for cotis's concrete types live in cotis-layout,
// since TryFromRenderOutput is defined there (local trait on foreign types = allowed).
// Custom types like CircleDrawable implement TryFromRenderOutput directly where they
// are defined, since they are local types (local type implementing foreign trait = allowed).