kiran 1.0.0

Kiran — AI-native game engine for AGNOS
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
//! GPU rendering backend via soorat, prakash, and ranga
//!
//! Bridges the AGNOS rendering stack with kiran's Renderer trait and ECS:
//! - **soorat** — GPU rendering engine (sprites, meshes, PBR pipeline, shadows, etc.)
//! - **prakash** — Physically-based optics (BRDF math, spectral color, atmosphere, lenses)
//! - **ranga** — Image processing (pixel buffers, blend modes, filters, compositing)
//!
//! Provides a [`SooratRenderer`] that implements kiran's [`Renderer`] trait.

// ---------------------------------------------------------------------------
// soorat — GPU rendering
// ---------------------------------------------------------------------------

pub use soorat::GpuContext;
pub use soorat::animation::{AnimationClip, JointUniforms, Skeleton};
pub use soorat::capabilities::GpuCapabilities;
pub use soorat::color::Color;
pub use soorat::compute::ComputePipeline;
pub use soorat::debug_draw::{LineBatch, LinePipeline, LineVertex};
pub use soorat::fluid_render::FluidColorMode;
pub use soorat::gpu_particles::{GpuParticle, GpuParticleSystem, SimParams};
pub use soorat::hdr::{BloomPipeline, BloomUniforms, HdrFramebuffer};
pub use soorat::instancing::{InstanceBuffer, InstanceData};
pub use soorat::lights::{GpuLight, LightArrayUniforms};
pub use soorat::lod::{LodChain, TerrainLod};
pub use soorat::mesh_pipeline::{
    CameraUniforms, DepthBuffer, LightUniforms, Mesh, MeshDrawParams, MeshPipeline,
};
pub use soorat::pbr_material::MaterialUniforms;
pub use soorat::pipeline::{
    FrameStats, SpriteBatchDrawParams, SpriteBuffers, SpritePipeline, batch_to_vertices,
};
pub use soorat::postprocess::{PostProcessPipeline, PostProcessUniforms, ToneMapMode};
pub use soorat::profiler::{FrameProfiler as GpuFrameProfiler, GpuTimestamps, PassTiming};
pub use soorat::render_graph::{PassType, RenderGraph, RenderPassNode};
pub use soorat::render_target::RenderTarget;
pub use soorat::shadow::{ShadowMap, ShadowPipeline, ShadowUniforms};
pub use soorat::sprite::{Sprite, SpriteBatch, UvRect};
pub use soorat::ssao::{SsaoPipeline, SsaoUniforms};
pub use soorat::terrain::{TerrainConfig, TerrainData};
pub use soorat::text::{BitmapFont, TextBatch};
pub use soorat::texture::{Texture, TextureCache, create_default_sampler};
pub use soorat::ui::{UiBatch, UiLabel, UiPanel};
pub use soorat::vertex::{SkinnedVertex3D, Vertex2D, Vertex3D};
pub use soorat::window::{
    self as soorat_window, Window as SooratWindow, WindowConfig as SooratWindowConfig,
};

// ---------------------------------------------------------------------------
// prakash — physically-based optics
// ---------------------------------------------------------------------------

/// PBR shading math (Cook-Torrance BRDF, Fresnel, GGX distribution, geometry,
/// anisotropic, clearcoat, sheen, iridescence, subsurface).
pub use prakash::pbr;

/// Spectral color science (wavelength↔RGB, blackbody, CIE, color temperature).
pub use prakash::spectral;

/// Geometric optics (Snell's law, Fresnel equations, critical angle, dispersion).
pub use prakash::ray;

/// Wave optics (interference, diffraction, polarization, coherence).
pub use prakash::wave;

/// Lens/mirror geometry (thin/thick, aberrations, MTF, depth of field).
pub use prakash::lens;

/// Atmospheric scattering (Rayleigh, Mie, sky color, optical depth).
pub use prakash::atmosphere;

pub use prakash::PrakashError;

// ---------------------------------------------------------------------------
// ranga — image processing
// ---------------------------------------------------------------------------

/// Pixel buffers and formats.
pub use ranga::pixel::{BufferPool, PixelBuffer, PixelFormat, PixelView, PixelViewMut};

/// Blend modes (Porter-Duff: Normal, Multiply, Screen, Overlay, etc.).
pub use ranga::blend::{self, BlendMode};

/// Image filters (blur, sharpen, brightness, contrast, saturation, etc.).
pub use ranga::filter;

/// Layer compositing (masks, transitions, gradients, premultiplied alpha).
pub use ranga::composite;

/// Color space conversions (sRGB, linear, HSL, Oklab, CIE, P3, CMYK).
pub use ranga::color as ranga_color;

/// Histograms (luminance, RGB, equalization, auto-levels).
pub use ranga::histogram;

/// Spatial transforms (crop, resize, affine, perspective, flip).
pub use ranga::transform;

/// Pixel format conversion (BT.601/709/2020, ARGB↔NV12).
pub use ranga::convert;

/// ICC color profile parsing (v2/v4, tone curves, embedded sRGB).
pub use ranga::icc;

pub use ranga::RangaError;

use crate::render::{Camera, DrawCommand, MeshDesc, RenderConfig, Renderer};
use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// Texture processing pipeline
// ---------------------------------------------------------------------------

/// A filter operation in a texture processing pipeline.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub enum TextureFilter {
    /// Brightness offset (-1.0 to 1.0).
    Brightness(f32),
    /// Contrast multiplier (1.0 = unchanged).
    Contrast(f32),
    /// Saturation multiplier (0.0 = grayscale, 1.0 = unchanged).
    Saturation(f32),
    /// Hue rotation in degrees.
    HueShift(f32),
    /// Convert to grayscale (BT.709 luminance).
    Grayscale,
    /// Invert colors.
    Invert,
    /// Gaussian blur with the given radius.
    GaussianBlur(u32),
    /// Unsharp mask sharpening.
    Sharpen {
        /// Sharpening strength.
        amount: f32,
        /// Blur radius for the unsharp mask.
        radius: u32,
    },
    /// Vignette darkening at edges (0.0–1.0).
    Vignette(f32),
    /// Vibrance (selective saturation boost).
    Vibrance(f32),
}

/// Texture processor — applies a chain of filters to a pixel buffer.
///
/// Attach to an entity alongside a texture asset to process it at load time,
/// or use standalone for runtime texture manipulation.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "rendering")] {
/// use kiran::gpu::{TextureProcessor, TextureFilter};
///
/// let proc = TextureProcessor::new()
///     .push(TextureFilter::Brightness(0.1))
///     .push(TextureFilter::Contrast(1.2))
///     .push(TextureFilter::Sharpen { amount: 0.5, radius: 1 });
/// assert_eq!(proc.len(), 3);
/// # }
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TextureProcessor {
    /// Ordered list of filters to apply.
    pub filters: Vec<TextureFilter>,
}

impl TextureProcessor {
    /// Create an empty texture processor.
    pub fn new() -> Self {
        Self::default()
    }

    /// Append a filter to the pipeline.
    pub fn push(mut self, filter: TextureFilter) -> Self {
        self.filters.push(filter);
        self
    }

    /// Number of filters in the pipeline.
    #[must_use]
    #[inline]
    pub fn len(&self) -> usize {
        self.filters.len()
    }

    /// Whether the pipeline is empty.
    #[must_use]
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.filters.is_empty()
    }

    /// Apply the filter pipeline to a pixel buffer (CPU path).
    pub fn apply(&self, buf: &mut PixelBuffer) -> Result<(), RangaError> {
        for f in &self.filters {
            match f {
                TextureFilter::Brightness(v) => filter::brightness(buf, *v)?,
                TextureFilter::Contrast(v) => filter::contrast(buf, *v)?,
                TextureFilter::Saturation(v) => filter::saturation(buf, *v)?,
                TextureFilter::HueShift(deg) => filter::hue_shift(buf, *deg)?,
                TextureFilter::Grayscale => filter::grayscale(buf)?,
                TextureFilter::Invert => filter::invert(buf)?,
                TextureFilter::GaussianBlur(r) => {
                    *buf = filter::gaussian_blur(buf, *r)?;
                }
                TextureFilter::Sharpen { amount, radius } => {
                    *buf = filter::unsharp_mask(buf, *radius, *amount)?;
                }
                TextureFilter::Vignette(s) => filter::vignette(buf, *s)?,
                TextureFilter::Vibrance(v) => filter::vibrance(buf, *v)?,
            }
        }
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Color grading
// ---------------------------------------------------------------------------

/// Color grading settings for post-processing.
///
/// Controls exposure, temperature, hue, and saturation for cinematic visuals.
/// Can be attached as an ECS resource or per-camera component.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ColorGrading {
    /// Exposure adjustment in stops (-5.0 to 5.0).
    pub exposure: f32,
    /// Hue rotation in degrees.
    pub hue_shift: f32,
    /// Saturation multiplier (0.0 = grayscale, 1.0 = unchanged).
    pub saturation: f32,
    /// Vibrance (selective saturation, less aggressive than saturation).
    pub vibrance: f32,
    /// Brightness offset (-1.0 to 1.0).
    pub brightness: f32,
    /// Contrast multiplier.
    pub contrast: f32,
    /// Vignette strength (0.0 = none).
    pub vignette: f32,
}

impl Default for ColorGrading {
    fn default() -> Self {
        Self {
            exposure: 0.0,
            hue_shift: 0.0,
            saturation: 1.0,
            vibrance: 0.0,
            brightness: 0.0,
            contrast: 1.0,
            vignette: 0.0,
        }
    }
}

impl ColorGrading {
    /// Create neutral color grading (no adjustments).
    pub fn neutral() -> Self {
        Self::default()
    }

    /// Apply this grading to a pixel buffer.
    pub fn apply(&self, buf: &mut PixelBuffer) -> Result<(), RangaError> {
        if (self.brightness).abs() > f32::EPSILON {
            filter::brightness(buf, self.brightness)?;
        }
        if (self.contrast - 1.0).abs() > f32::EPSILON {
            filter::contrast(buf, self.contrast)?;
        }
        if (self.saturation - 1.0).abs() > f32::EPSILON {
            filter::saturation(buf, self.saturation)?;
        }
        if (self.vibrance).abs() > f32::EPSILON {
            filter::vibrance(buf, self.vibrance)?;
        }
        if (self.hue_shift).abs() > f32::EPSILON {
            filter::hue_shift(buf, self.hue_shift)?;
        }
        if self.vignette > f32::EPSILON {
            filter::vignette(buf, self.vignette)?;
        }
        Ok(())
    }

    /// Whether all settings are at neutral (no-op).
    #[must_use]
    pub fn is_neutral(&self) -> bool {
        (self.exposure).abs() < f32::EPSILON
            && (self.hue_shift).abs() < f32::EPSILON
            && (self.saturation - 1.0).abs() < f32::EPSILON
            && (self.vibrance).abs() < f32::EPSILON
            && (self.brightness).abs() < f32::EPSILON
            && (self.contrast - 1.0).abs() < f32::EPSILON
            && self.vignette < f32::EPSILON
    }
}

// ---------------------------------------------------------------------------
// Screen capture analysis
// ---------------------------------------------------------------------------

/// Histogram analysis of a captured frame.
///
/// Use for performance debugging, QA validation, or adaptive rendering.
#[derive(Debug, Clone)]
pub struct FrameHistogram {
    /// Luminance histogram (256 bins, normalized 0.0–1.0).
    pub luminance: Vec<f64>,
    /// Per-channel RGB histograms (256 bins each).
    pub red: Vec<f64>,
    /// Green channel histogram.
    pub green: Vec<f64>,
    /// Blue channel histogram.
    pub blue: Vec<f64>,
}

impl FrameHistogram {
    /// Compute histograms from a pixel buffer.
    pub fn from_buffer(buf: &PixelBuffer) -> Result<Self, RangaError> {
        let luminance = histogram::luminance_histogram(buf, 256)?;
        let [red, green, blue] = histogram::rgb_histograms(buf)?;
        Ok(Self {
            luminance,
            red,
            green,
            blue,
        })
    }

    /// Average luminance (0.0 = black, 1.0 = white).
    #[must_use]
    pub fn average_luminance(&self) -> f64 {
        self.luminance
            .iter()
            .enumerate()
            .map(|(i, &v)| (i as f64 / 255.0) * v)
            .sum()
    }

    /// Whether the frame is predominantly dark (avg luminance < 0.2).
    #[must_use]
    pub fn is_underexposed(&self) -> bool {
        self.average_luminance() < 0.2
    }

    /// Whether the frame is predominantly bright (avg luminance > 0.8).
    #[must_use]
    pub fn is_overexposed(&self) -> bool {
        self.average_luminance() > 0.8
    }
}

// ---------------------------------------------------------------------------
// SooratRenderer — bridges soorat with kiran's Renderer trait
// ---------------------------------------------------------------------------

/// GPU-accelerated renderer backed by soorat (wgpu).
///
/// Implements kiran's `Renderer` trait, translating `DrawCommand`s to soorat
/// sprite batches. This is a **data-layer bridge** — it collects and sorts
/// sprites but does not perform GPU rendering directly. Actual GPU rendering
/// happens through soorat's `Window::run()` + `SpritePipeline::draw()` which
/// require a live window and surface.
///
/// For headless testing, this behaves like NullRenderer with soorat types.
/// For real rendering, access `sprite_batch()` and `clear_color()` after
/// `end_frame()` and pass them to soorat's pipeline.
pub struct SooratRenderer {
    config: RenderConfig,
    initialized: bool,
    in_frame: bool,
    frame_count: u64,
    /// Sprites queued for the current frame.
    sprite_batch: SpriteBatch,
    /// Mesh draw commands queued for the current frame.
    mesh_queue: Vec<MeshDesc>,
    /// Clear color for the frame.
    clear_color: Color,
    /// Current camera (updated via SetCamera commands).
    camera: Option<Camera>,
}

impl SooratRenderer {
    /// Create a new soorat-backed renderer (headless-safe).
    pub fn new() -> Self {
        Self {
            config: RenderConfig::default(),
            initialized: false,
            in_frame: false,
            frame_count: 0,
            sprite_batch: SpriteBatch::new(),
            mesh_queue: Vec::new(),
            clear_color: Color::CORNFLOWER_BLUE,
            camera: None,
        }
    }

    /// Get the clear color for the current frame.
    pub fn clear_color(&self) -> Color {
        self.clear_color
    }

    /// Get the number of sprites queued this frame.
    pub fn sprite_count(&self) -> usize {
        self.sprite_batch.len()
    }

    /// Get the total frames rendered.
    pub fn frame_count(&self) -> u64 {
        self.frame_count
    }

    /// Get the current camera, if set.
    pub fn camera(&self) -> Option<&Camera> {
        self.camera.as_ref()
    }

    /// Access the sprite batch.
    pub fn sprite_batch(&self) -> &SpriteBatch {
        &self.sprite_batch
    }

    /// Access the mesh draw queue.
    pub fn mesh_queue(&self) -> &[MeshDesc] {
        &self.mesh_queue
    }

    /// Number of meshes queued this frame.
    pub fn mesh_count(&self) -> usize {
        self.mesh_queue.len()
    }

    /// Get the render config.
    pub fn config(&self) -> &RenderConfig {
        &self.config
    }
}

impl Default for SooratRenderer {
    fn default() -> Self {
        Self::new()
    }
}

impl Renderer for SooratRenderer {
    fn init(&mut self, config: &RenderConfig) -> Result<(), String> {
        self.config = config.clone();
        self.initialized = true;
        tracing::info!(
            width = config.width,
            height = config.height,
            vsync = config.vsync,
            "soorat renderer initialized"
        );
        Ok(())
    }

    fn begin_frame(&mut self) -> Result<(), String> {
        if !self.initialized {
            return Err("SooratRenderer not initialized".into());
        }
        self.sprite_batch.clear();
        self.mesh_queue.clear();
        self.clear_color = Color::CORNFLOWER_BLUE;
        self.in_frame = true;
        Ok(())
    }

    fn submit(&mut self, command: DrawCommand) -> Result<(), String> {
        if !self.in_frame {
            return Err("Not in a frame".into());
        }
        match command {
            DrawCommand::Clear(color) => {
                self.clear_color = Color::new(color[0], color[1], color[2], color[3]);
            }
            DrawCommand::Sprite(desc) => {
                self.sprite_batch.push(Sprite {
                    x: desc.x,
                    y: desc.y,
                    width: desc.width,
                    height: desc.height,
                    rotation: desc.rotation,
                    color: Color::new(desc.color[0], desc.color[1], desc.color[2], desc.color[3]),
                    texture_id: desc.texture_id,
                    z_order: 0,
                    uv: UvRect::FULL,
                });
            }
            DrawCommand::Mesh(desc) => {
                self.mesh_queue.push(desc);
            }
            DrawCommand::SetCamera(cam) => {
                self.camera = Some(cam);
            }
        }
        Ok(())
    }

    fn end_frame(&mut self) -> Result<(), String> {
        if !self.in_frame {
            return Err("Not in a frame".into());
        }
        self.sprite_batch.sort_by_z();
        self.in_frame = false;
        self.frame_count += 1;
        Ok(())
    }

    fn shutdown(&mut self) -> Result<(), String> {
        self.initialized = false;
        self.in_frame = false;
        tracing::info!("soorat renderer shut down");
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::render::{DrawCommand, RenderConfig, Renderer, SpriteDesc};

    #[test]
    fn soorat_renderer_lifecycle() {
        let mut r = SooratRenderer::new();
        assert!(!r.initialized);

        r.init(&RenderConfig::default()).unwrap();
        assert!(r.initialized);

        r.begin_frame().unwrap();
        r.submit(DrawCommand::Clear([0.1, 0.2, 0.3, 1.0])).unwrap();
        r.end_frame().unwrap();

        assert_eq!(r.frame_count(), 1);

        r.shutdown().unwrap();
        assert!(!r.initialized);
    }

    #[test]
    fn soorat_renderer_clear_color() {
        let mut r = SooratRenderer::new();
        r.init(&RenderConfig::default()).unwrap();
        r.begin_frame().unwrap();

        r.submit(DrawCommand::Clear([0.5, 0.6, 0.7, 1.0])).unwrap();
        assert!((r.clear_color().r - 0.5).abs() < f32::EPSILON);
        assert!((r.clear_color().g - 0.6).abs() < f32::EPSILON);

        r.end_frame().unwrap();
    }

    #[test]
    fn soorat_renderer_sprites() {
        let mut r = SooratRenderer::new();
        r.init(&RenderConfig::default()).unwrap();
        r.begin_frame().unwrap();

        r.submit(DrawCommand::Sprite(SpriteDesc {
            texture_id: 1,
            x: 10.0,
            y: 20.0,
            width: 64.0,
            height: 64.0,
            rotation: 0.0,
            color: [1.0, 0.0, 0.0, 1.0],
        }))
        .unwrap();

        r.submit(DrawCommand::Sprite(SpriteDesc {
            texture_id: 2,
            x: 100.0,
            y: 200.0,
            width: 32.0,
            height: 32.0,
            rotation: 1.57,
            color: [0.0, 1.0, 0.0, 1.0],
        }))
        .unwrap();

        assert_eq!(r.sprite_count(), 2);
        r.end_frame().unwrap();
    }

    #[test]
    fn soorat_renderer_camera() {
        let mut r = SooratRenderer::new();
        r.init(&RenderConfig::default()).unwrap();
        r.begin_frame().unwrap();

        assert!(r.camera().is_none());

        let cam = Camera::default();
        r.submit(DrawCommand::SetCamera(cam)).unwrap();
        assert!(r.camera().is_some());

        r.end_frame().unwrap();
    }

    #[test]
    fn soorat_renderer_begin_without_init() {
        let mut r = SooratRenderer::new();
        assert!(r.begin_frame().is_err());
    }

    #[test]
    fn soorat_renderer_submit_outside_frame() {
        let mut r = SooratRenderer::new();
        r.init(&RenderConfig::default()).unwrap();
        assert!(r.submit(DrawCommand::Clear([0.0; 4])).is_err());
    }

    #[test]
    fn soorat_renderer_end_without_begin() {
        let mut r = SooratRenderer::new();
        r.init(&RenderConfig::default()).unwrap();
        assert!(r.end_frame().is_err());
    }

    #[test]
    fn soorat_renderer_multiple_frames() {
        let mut r = SooratRenderer::new();
        r.init(&RenderConfig::default()).unwrap();

        for _ in 0..5 {
            r.begin_frame().unwrap();
            r.submit(DrawCommand::Clear([0.0, 0.0, 0.0, 1.0])).unwrap();
            r.end_frame().unwrap();
        }
        assert_eq!(r.frame_count(), 5);
    }

    #[test]
    fn soorat_color_bridge() {
        // Verify soorat Color types are accessible
        let c = Color::from_hex(0xFF0000FF);
        assert_eq!(c.r, 1.0);

        let lerped = Color::RED.lerp(Color::BLUE, 0.5);
        assert!((lerped.r - 0.5).abs() < f32::EPSILON);
    }

    #[test]
    fn soorat_sprite_bridge() {
        let sprite = Sprite::new(10.0, 20.0, 64.0, 64.0)
            .with_color(Color::GREEN)
            .with_z_order(3);
        assert_eq!(sprite.z_order, 3);
        assert_eq!(sprite.center(), (42.0, 52.0));
    }

    #[test]
    fn soorat_renderer_mesh_no_panic() {
        use crate::render::MeshDesc;

        let mut r = SooratRenderer::new();
        r.init(&RenderConfig::default()).unwrap();
        r.begin_frame().unwrap();

        r.submit(DrawCommand::Mesh(MeshDesc {
            mesh_id: 1,
            transform: [
                1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
            ],
            material_id: 0,
        }))
        .unwrap();

        // Mesh doesn't add to sprite count
        assert_eq!(r.sprite_count(), 0);
        r.end_frame().unwrap();
    }

    #[test]
    fn soorat_renderer_sprite_batch_clears_between_frames() {
        let mut r = SooratRenderer::new();
        r.init(&RenderConfig::default()).unwrap();

        // Frame 1: add 3 sprites
        r.begin_frame().unwrap();
        for _ in 0..3 {
            r.submit(DrawCommand::Sprite(SpriteDesc {
                texture_id: 0,
                x: 0.0,
                y: 0.0,
                width: 10.0,
                height: 10.0,
                rotation: 0.0,
                color: [1.0; 4],
            }))
            .unwrap();
        }
        assert_eq!(r.sprite_count(), 3);
        r.end_frame().unwrap();

        // Frame 2: batch should be empty
        r.begin_frame().unwrap();
        assert_eq!(r.sprite_count(), 0);
        r.end_frame().unwrap();
    }

    #[test]
    fn soorat_renderer_default_clear_color() {
        let r = SooratRenderer::new();
        assert_eq!(r.clear_color(), Color::CORNFLOWER_BLUE);
    }

    #[test]
    fn soorat_renderer_config() {
        let mut r = SooratRenderer::new();
        let cfg = RenderConfig {
            width: 1920,
            height: 1080,
            vsync: false,
            fullscreen: true,
            title: "Test".into(),
        };
        r.init(&cfg).unwrap();

        assert_eq!(r.config().width, 1920);
        assert_eq!(r.config().height, 1080);
        assert!(!r.config().vsync);
        assert!(r.config().fullscreen);
    }

    #[test]
    fn soorat_renderer_shutdown_reinit() {
        let mut r = SooratRenderer::new();
        r.init(&RenderConfig::default()).unwrap();
        r.begin_frame().unwrap();
        r.end_frame().unwrap();
        assert_eq!(r.frame_count(), 1);

        r.shutdown().unwrap();
        assert!(!r.initialized);

        // Re-init
        r.init(&RenderConfig::default()).unwrap();
        r.begin_frame().unwrap();
        r.end_frame().unwrap();
        assert_eq!(r.frame_count(), 2);
    }

    #[test]
    fn soorat_renderer_camera_persists_across_frames() {
        let mut r = SooratRenderer::new();
        r.init(&RenderConfig::default()).unwrap();

        // Frame 1: set camera
        r.begin_frame().unwrap();
        r.submit(DrawCommand::SetCamera(Camera::default())).unwrap();
        r.end_frame().unwrap();

        // Frame 2: camera should still be set
        r.begin_frame().unwrap();
        assert!(r.camera().is_some());
        r.end_frame().unwrap();
    }
}