1use std::{
17 cell::RefCell,
18 collections::HashMap,
19 rc::{Rc, Weak},
20};
21
22use crate::{
23 Color, Error, Event, Result, Runtime,
24 render::material::{FlatColorMaterial, SurfaceMaterial, TextureHandle, UnlitMaterial},
25 runtime::{
26 GraphicsPipeline, MeshBuffer, NativeRgbaImage, RenderTarget, SceneDrawCmd,
27 SurfaceDescriptorArena, SurfaceDescriptorLayouts, UnlitDescriptorArena, UnlitDescriptorLayouts,
28 },
29};
30
31use super::{
32 Camera, MeshData, Scene, Texture, blit,
33 scene::compile_scene_packets,
34 texture::{RenderTargetLease, texture_from_render_target, texture_from_rgba8_on},
35};
36
37#[derive(Clone, Debug, PartialEq)]
41pub struct RendererConfig {
42 pub width: u32,
44 pub height: u32,
46 pub target_slot_count: u32,
48 pub max_vertex_count: u32,
50 pub max_index_count: u32,
52 pub clear_color: Color,
54 pub light_direction: [f32; 3],
57 pub ambient: f32,
59 pub max_materials_per_scene: u32,
64}
65
66impl Default for RendererConfig {
67 fn default() -> Self {
68 Self {
69 width: 256,
70 height: 192,
71 target_slot_count: 3,
72 max_vertex_count: 4096,
73 max_index_count: 12288,
74 clear_color: Color::new(0.02, 0.03, 0.05, 1.0),
75 light_direction: [0.35, 0.82, 0.45],
76 ambient: 0.24,
77 max_materials_per_scene: 8,
78 }
79 }
80}
81
82pub struct Renderer<'runtime> {
90 runtime: &'runtime Runtime,
91 config: RendererConfig,
92 state: Rc<RefCell<RendererState>>,
93}
94
95#[must_use]
97pub struct RenderFrame {
98 slot: usize,
99 generation: u64,
100 texture: Texture,
101 producer: Event,
102 is_graphics: bool,
104 state: Weak<RefCell<RendererState>>,
105 released: bool,
106}
107
108pub(super) struct RendererState {
111 pipeline: Option<GraphicsPipeline>,
113 flat_color_pipeline: Option<GraphicsPipeline>,
115 unlit_pipeline: Option<GraphicsPipeline>,
117 unlit_descriptors: Option<UnlitDescriptorArena>,
119 _unlit_layouts: Option<UnlitDescriptorLayouts>,
122 surface_pipeline: Option<GraphicsPipeline>,
124 surface_blend_pipeline: Option<GraphicsPipeline>,
129 canvas_grid_pipeline: Option<GraphicsPipeline>,
131 surface_descriptors: Option<SurfaceDescriptorArena>,
132 _surface_layouts: Option<SurfaceDescriptorLayouts>,
135 textures: HashMap<TextureHandle, Texture>,
136 white_texture: Option<Texture>,
137 slots: Vec<Slot>,
138 building: Option<Building>,
139 closed: bool,
140}
141
142struct Slot {
143 generation: u64,
144 state: SlotState,
145 graphics: Option<GraphicsSlot>,
147 sampled_image: Option<Rc<NativeRgbaImage>>,
148 texture_lease: Option<Weak<crate::render::texture::TextureSemantic>>,
149}
150
151struct GraphicsSlot {
152 target: RenderTarget,
153 vertex_buf: MeshBuffer,
154 index_buf: MeshBuffer,
155 scene_uniform: MeshBuffer,
156 material_uniforms: Vec<MeshBuffer>,
158}
159
160struct Building {
161 slot: usize,
162 generation: u64,
163 source: BuildingSource,
164}
165
166struct PendingDraw {
168 index_start: u32,
169 index_count: u32,
170 push_data: [u8; 128],
172 mat_index: usize,
174 material_data: Box<[u8; MATERIAL_PARAMS_SIZE]>,
176 base_texture: Option<TextureHandle>,
178 orm_texture: Option<TextureHandle>,
179 normal_texture: Option<TextureHandle>,
180 is_blend: bool,
182}
183
184enum BuildingSource {
185 Texture(Texture),
186 Mesh {
188 index_count: u32,
189 push_data: [u8; 80],
190 },
191 FlatColor {
193 index_count: u32,
194 push_data: [u8; 96],
195 },
196 Unlit {
198 index_count: u32,
199 push_data: [u8; 96],
200 texture: Rc<NativeRgbaImage>,
201 },
202 Surface {
204 scene_data: Box<[u8; SCENE_LIGHTS_SIZE]>,
205 draws: Vec<PendingDraw>,
206 },
207 CanvasGrid {
209 push_data: [u8; 100],
210 },
211}
212
213enum SlotState {
214 Free,
215 Building,
216 Submitted(Event),
217}
218
219impl RendererState {
220 pub(super) fn mark_texture_consumed(
221 &mut self,
222 slot_index: usize,
223 generation: u64,
224 event: &Event,
225 ) -> Result<()> {
226 let slot = self
227 .slots
228 .get_mut(slot_index)
229 .ok_or_else(|| Error::failed_precondition("render target slot is no longer available"))?;
230 if slot.generation != generation {
231 return Err(Error::failed_precondition(
232 "render target slot belongs to a later frame",
233 ));
234 }
235 let SlotState::Submitted(current) = &mut slot.state else {
236 return Err(Error::failed_precondition(
237 "render target has no submitted producer",
238 ));
239 };
240 if !event.follows_or_equals(current) {
241 return Err(Error::invalid_argument(
242 "render target consumer event precedes its producer or another consumer",
243 ));
244 }
245 *current = event.clone();
246 Ok(())
247 }
248}
249
250impl Drop for RendererState {
251 fn drop(&mut self) {
252 let has_unretired_submission = self.slots.iter().any(|slot| match &slot.state {
253 SlotState::Submitted(event) => !matches!(event.is_complete(), Ok(true)),
254 SlotState::Free | SlotState::Building => false,
255 });
256 if !has_unretired_submission {
257 return;
258 }
259
260 std::mem::forget(std::mem::take(&mut self.slots));
264 std::mem::forget(std::mem::take(&mut self.textures));
265 std::mem::forget(self.white_texture.take());
266 std::mem::forget(self.pipeline.take());
267 std::mem::forget(self.flat_color_pipeline.take());
268 std::mem::forget(self.unlit_pipeline.take());
269 std::mem::forget(self.unlit_descriptors.take());
270 std::mem::forget(self._unlit_layouts.take());
271 std::mem::forget(self.surface_pipeline.take());
272 std::mem::forget(self.surface_blend_pipeline.take());
273 std::mem::forget(self.canvas_grid_pipeline.take());
274 std::mem::forget(self.surface_descriptors.take());
275 std::mem::forget(self._surface_layouts.take());
276 }
277}
278
279type DrawParams = (
283 u32,
284 Vec<u8>,
285 vk::ShaderStageFlags,
286 vk::Pipeline,
287 vk::PipelineLayout,
288 Vec<vk::DescriptorSet>,
289);
290
291const VERTEX_STRIDE: usize = 48;
294const SCENE_LIGHTS_SIZE: usize = 416;
295const MATERIAL_PARAMS_SIZE: usize = 80;
296
297#[derive(Clone, Copy, Debug, PartialEq)]
302pub struct CanvasGridFrame {
303 pub dst_x: i32,
305 pub dst_y: i32,
306 pub dst_w: u32,
307 pub dst_h: u32,
308 pub origin: [f32; 2],
310 pub minor_spacing: [f32; 2],
312 pub major_every: u32,
314 pub super_major_every: u32,
316 pub thickness: [f32; 4],
318 pub background_top_rgba: u32,
319 pub background_bottom_rgba: u32,
320 pub minor_rgba: u32,
321 pub major_rgba: u32,
322 pub super_major_rgba: u32,
323 pub axis_rgba: u32,
324 pub fade_center: [f32; 2],
326 pub fade_radii: [f32; 2],
328 pub flags: u32,
332}
333
334impl CanvasGridFrame {
335 pub const ALL_FLAGS: u32 = 1 | 2 | 4 | 8 | 16;
337
338 pub(crate) fn validate(&self) -> Result<()> {
339 if self.dst_w == 0 || self.dst_h == 0 {
340 return Err(Error::invalid_argument(
341 "canvas-grid destination size must be non-zero",
342 ));
343 }
344 if self
345 .thickness
346 .iter()
347 .chain(self.minor_spacing.iter())
348 .chain(self.origin.iter())
349 .chain(self.fade_center.iter())
350 .chain(self.fade_radii.iter())
351 .any(|v| !v.is_finite())
352 {
353 return Err(Error::invalid_argument(
354 "canvas-grid parameters must be finite",
355 ));
356 }
357 if self.minor_spacing.iter().any(|v| *v <= 0.0) {
358 return Err(Error::invalid_argument(
359 "canvas-grid minor spacing must be positive",
360 ));
361 }
362 if self.major_every == 0 || self.super_major_every == 0 {
363 return Err(Error::invalid_argument(
364 "canvas-grid tier multipliers must be non-zero",
365 ));
366 }
367 if self.flags & !Self::ALL_FLAGS != 0 {
368 return Err(Error::invalid_argument(
369 "canvas-grid flags contain an unknown layer bit",
370 ));
371 }
372 Ok(())
373 }
374
375 pub(crate) fn pack_push(&self) -> [u8; 100] {
376 let mut data = [0u8; 100];
377 let ints = [self.dst_x as u32, self.dst_y as u32, self.dst_w, self.dst_h];
378 let floats = [
379 self.origin[0],
380 self.origin[1],
381 self.minor_spacing[0],
382 self.minor_spacing[1],
383 ];
384 let tier = [self.major_every, self.super_major_every];
385 let colors = [
386 self.background_top_rgba,
387 self.background_bottom_rgba,
388 self.minor_rgba,
389 self.major_rgba,
390 self.super_major_rgba,
391 self.axis_rgba,
392 ];
393 let fade = [
394 self.fade_center[0],
395 self.fade_center[1],
396 self.fade_radii[0],
397 self.fade_radii[1],
398 ];
399 let mut off = 0;
400 let mut put_u32 = |v: u32| {
401 data[off..off + 4].copy_from_slice(&v.to_le_bytes());
402 off += 4;
403 };
404 for v in ints {
405 put_u32(v);
406 }
407 for v in floats {
408 put_u32(v.to_bits());
409 }
410 for v in tier {
411 put_u32(v);
412 }
413 for v in self.thickness {
414 put_u32(v.to_bits());
415 }
416 for v in colors {
417 put_u32(v);
418 }
419 for v in fade {
420 put_u32(v.to_bits());
421 }
422 put_u32(self.flags);
423 debug_assert_eq!(off, 100);
424 data
425 }
426}
427
428fn build_vcl_push(vp: &crate::vlm::Mat4, light: [f32; 3], ambient: f32) -> [u8; 80] {
430 let mut data = [0u8; 80];
431 for (i, row) in vp.m.iter().enumerate() {
432 for (j, val) in row.iter().enumerate() {
433 let off = (i * 4 + j) * 4;
434 data[off..off + 4].copy_from_slice(&val.to_le_bytes());
435 }
436 }
437 data[64..68].copy_from_slice(&light[0].to_le_bytes());
438 data[68..72].copy_from_slice(&light[1].to_le_bytes());
439 data[72..76].copy_from_slice(&light[2].to_le_bytes());
440 data[76..80].copy_from_slice(&ambient.to_le_bytes());
441 data
442}
443
444fn build_flat_color_push(mvp: &crate::vlm::Mat4, mat: &FlatColorMaterial) -> [u8; 96] {
446 let mut data = [0u8; 96];
447 for (i, row) in mvp.m.iter().enumerate() {
448 for (j, val) in row.iter().enumerate() {
449 let off = (i * 4 + j) * 4;
450 data[off..off + 4].copy_from_slice(&val.to_le_bytes());
451 }
452 }
453 for (k, c) in mat.color.to_array().iter().enumerate() {
455 data[64 + k * 4..64 + k * 4 + 4].copy_from_slice(&c.to_le_bytes());
456 }
457 data[80..84].copy_from_slice(&mat.opacity.to_le_bytes());
459 data
460}
461
462fn build_unlit_push(mvp: &crate::vlm::Mat4, mat: &UnlitMaterial) -> [u8; 96] {
464 let mut data = [0u8; 96];
465 for (i, row) in mvp.m.iter().enumerate() {
466 for (j, val) in row.iter().enumerate() {
467 let off = (i * 4 + j) * 4;
468 data[off..off + 4].copy_from_slice(&val.to_le_bytes());
469 }
470 }
471 for (k, c) in mat.tint.to_array().iter().enumerate() {
473 data[64 + k * 4..64 + k * 4 + 4].copy_from_slice(&c.to_le_bytes());
474 }
475 data[80..84].copy_from_slice(&mat.uv_scale[0].to_le_bytes());
477 data[84..88].copy_from_slice(&mat.uv_scale[1].to_le_bytes());
478 data[88..92].copy_from_slice(&mat.uv_offset[0].to_le_bytes());
480 data[92..96].copy_from_slice(&mat.uv_offset[1].to_le_bytes());
481 data
482}
483
484fn build_surface_push(mvp: &crate::vlm::Mat4, model: &crate::vlm::Mat4) -> [u8; 128] {
486 let mut data = [0u8; 128];
487 for (i, row) in mvp.m.iter().enumerate() {
488 for (j, val) in row.iter().enumerate() {
489 let off = (i * 4 + j) * 4;
490 data[off..off + 4].copy_from_slice(&val.to_le_bytes());
491 }
492 }
493 for (i, row) in model.m.iter().enumerate() {
494 for (j, val) in row.iter().enumerate() {
495 let off = 64 + (i * 4 + j) * 4;
496 data[off..off + 4].copy_from_slice(&val.to_le_bytes());
497 }
498 }
499 data
500}
501
502fn build_scene_lights(config: &RendererConfig) -> [u8; SCENE_LIGHTS_SIZE] {
503 let mut data = [0_u8; SCENE_LIGHTS_SIZE];
504 for (index, value) in config.light_direction.iter().enumerate() {
505 data[index * 4..index * 4 + 4].copy_from_slice(&value.to_le_bytes());
506 }
507 data[12..16].copy_from_slice(&1.0_f32.to_le_bytes());
508 for offset in [16, 20, 24] {
509 data[offset..offset + 4].copy_from_slice(&1.0_f32.to_le_bytes());
510 }
511 data[384..388].copy_from_slice(&1_i32.to_le_bytes());
512 data[388..392].copy_from_slice(&0_i32.to_le_bytes());
513 data[392..396].copy_from_slice(&1.0_f32.to_le_bytes());
514 data[396..400].copy_from_slice(&config.ambient.to_le_bytes());
515 for offset in [400, 404, 408] {
516 data[offset..offset + 4].copy_from_slice(&1.0_f32.to_le_bytes());
517 }
518 data[412..416].copy_from_slice(&0_i32.to_le_bytes());
519 data
520}
521
522fn build_material_params(material: &SurfaceMaterial) -> [u8; MATERIAL_PARAMS_SIZE] {
523 let mut data = [0_u8; MATERIAL_PARAMS_SIZE];
524 let mut write = |offset: usize, value: f32| {
525 data[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
526 };
527 for (index, value) in material.base_color.iter().enumerate() {
528 write(index * 4, *value);
529 }
530 write(12, material.metalness);
531 write(16, material.roughness);
532 write(20, material.normal_scale);
533 write(24, material.specular_ior);
534 write(28, material.emission_scale);
535 for (index, value) in material.specular_tint.iter().enumerate() {
536 write(32 + index * 4, *value);
537 }
538 write(44, material.opacity);
539 for (index, value) in material.emission_color.iter().enumerate() {
540 write(48 + index * 4, *value);
541 }
542 write(64, material.uv_scale[0]);
543 write(68, material.uv_scale[1]);
544 write(72, material.uv_offset[0]);
545 write(76, material.uv_offset[1]);
546 data
547}
548
549fn mesh_vertex_bytes(mesh: &MeshData) -> Vec<u8> {
550 let mut out = Vec::with_capacity(mesh.vertices.len() * VERTEX_STRIDE);
551 for v in &mesh.vertices {
552 out.extend_from_slice(&v.position.x.to_le_bytes());
553 out.extend_from_slice(&v.position.y.to_le_bytes());
554 out.extend_from_slice(&v.position.z.to_le_bytes());
555 out.extend_from_slice(&v.normal.x.to_le_bytes());
556 out.extend_from_slice(&v.normal.y.to_le_bytes());
557 out.extend_from_slice(&v.normal.z.to_le_bytes());
558 out.extend_from_slice(&v.uv.x.to_le_bytes());
559 out.extend_from_slice(&v.uv.y.to_le_bytes());
560 out.extend_from_slice(&v.color.x.to_le_bytes());
561 out.extend_from_slice(&v.color.y.to_le_bytes());
562 out.extend_from_slice(&v.color.z.to_le_bytes());
563 out.extend_from_slice(&v.color.w.to_le_bytes());
564 }
565 out
566}
567
568impl<'runtime> Renderer<'runtime> {
571 pub(crate) fn owns_frame(&self, frame: &RenderFrame) -> bool {
572 frame
573 .state
574 .upgrade()
575 .is_some_and(|state| Rc::ptr_eq(&state, &self.state))
576 && frame.texture.runtime().same_as(&self.runtime.handle())
577 }
578
579 pub fn new(runtime: &'runtime Runtime, config: RendererConfig) -> Result<Self> {
591 validate_config(&config)?;
592 let mesh_enabled =
593 config.max_vertex_count > 0 && config.max_index_count > 0 && runtime.has_graphics();
594 let handle = runtime.handle();
595
596 let (
597 pipeline,
598 flat_color_pipeline,
599 unlit_pipeline,
600 unlit_descriptors,
601 unlit_layouts,
602 surface_pipeline,
603 surface_blend_pipeline,
604 canvas_grid_pipeline,
605 surface_descriptors,
606 surface_layouts,
607 ) = if mesh_enabled {
608 let vcl = handle.create_graphics_pipeline()?;
609 let fc = handle.create_flat_color_pipeline()?;
610 let unlit_layouts = handle.create_unlit_descriptor_layouts()?;
611 let unlit_descriptors = handle
612 .create_unlit_descriptor_arena(unlit_layouts.sampler_layout, config.target_slot_count)?;
613 let unlit = handle.create_unlit_pipeline(unlit_layouts.sampler_layout)?;
614 let surface_layouts = handle.create_surface_descriptor_layouts()?;
615 let surface_descriptors = handle.create_surface_descriptor_arena(
616 surface_layouts.scene_layout,
617 surface_layouts.material_layout,
618 config.target_slot_count,
619 config.max_materials_per_scene,
620 )?;
621 let surface = handle.create_surface_pipeline(
622 surface_layouts.scene_layout,
623 surface_layouts.material_layout,
624 )?;
625 let surface_blend = handle.create_surface_blend_pipeline(surface.layout())?;
627 let canvas_grid = handle.create_canvas_grid_pipeline()?;
628 (
629 Some(vcl),
630 Some(fc),
631 Some(unlit),
632 Some(unlit_descriptors),
633 Some(unlit_layouts),
634 Some(surface),
635 Some(surface_blend),
636 Some(canvas_grid),
637 Some(surface_descriptors),
638 Some(surface_layouts),
639 )
640 } else {
641 (None, None, None, None, None, None, None, None, None, None)
642 };
643 let white_texture = mesh_enabled
644 .then(|| texture_from_rgba8_on(runtime, &[255, 255, 255, 255], 1, 1))
645 .transpose()?;
646
647 let vertex_cap = config.max_vertex_count as usize * VERTEX_STRIDE;
648 let index_cap = config.max_index_count as usize * size_of::<u32>();
649 let mut slots = Vec::with_capacity(config.target_slot_count as usize);
650 for _ in 0..config.target_slot_count {
651 let graphics = if mesh_enabled {
652 let target = handle.allocate_render_target(config.width, config.height)?;
653 let vertex_buf =
654 handle.allocate_mesh_buffer(vertex_cap, vk::BufferUsageFlagBits::VERTEX_BUFFER_BIT)?;
655 let index_buf =
656 handle.allocate_mesh_buffer(index_cap, vk::BufferUsageFlagBits::INDEX_BUFFER_BIT)?;
657 let scene_uniform = handle.allocate_mesh_buffer(
658 SCENE_LIGHTS_SIZE,
659 vk::BufferUsageFlagBits::UNIFORM_BUFFER_BIT,
660 )?;
661 let mut material_uniforms = Vec::with_capacity(config.max_materials_per_scene as usize);
662 for _ in 0..config.max_materials_per_scene {
663 material_uniforms.push(handle.allocate_mesh_buffer(
664 MATERIAL_PARAMS_SIZE,
665 vk::BufferUsageFlagBits::UNIFORM_BUFFER_BIT,
666 )?);
667 }
668 Some(GraphicsSlot {
669 target,
670 vertex_buf,
671 index_buf,
672 scene_uniform,
673 material_uniforms,
674 })
675 } else {
676 None
677 };
678 slots.push(Slot {
679 generation: 0,
680 state: SlotState::Free,
681 graphics,
682 sampled_image: None,
683 texture_lease: None,
684 });
685 }
686 Ok(Self {
687 runtime,
688 config,
689 state: Rc::new(RefCell::new(RendererState {
690 pipeline,
691 flat_color_pipeline,
692 unlit_pipeline,
693 unlit_descriptors,
694 _unlit_layouts: unlit_layouts,
695 surface_pipeline,
696 surface_blend_pipeline,
697 canvas_grid_pipeline,
698 surface_descriptors,
699 _surface_layouts: surface_layouts,
700 textures: HashMap::new(),
701 white_texture,
702 slots,
703 building: None,
704 closed: false,
705 })),
706 })
707 }
708
709 pub fn config(&self) -> &RendererConfig {
711 &self.config
712 }
713
714 pub fn has_mesh_path(&self) -> bool {
716 self.state.borrow().pipeline.is_some()
717 }
718
719 pub fn register_texture(&self, handle: TextureHandle, texture: &Texture) -> Result<()> {
725 if handle.0 == 0 {
726 return Err(Error::invalid_argument(
727 "render::Renderer texture handles must be non-zero",
728 ));
729 }
730 if !texture.runtime().same_as(&self.runtime.handle()) {
731 return Err(Error::invalid_argument(
732 "render::Renderer registered Texture belongs to a different Runtime",
733 ));
734 }
735 if texture.native().is_none() {
736 return Err(Error::failed_precondition(
737 "render::Renderer sampled textures require native image backing",
738 ));
739 }
740 let mut state = self.state.borrow_mut();
741 if state.closed {
742 return Err(Error::failed_precondition("render::Renderer is closed"));
743 }
744 state.textures.insert(handle, texture.clone());
745 Ok(())
746 }
747
748 pub fn begin_frame(&self, source: &Texture) -> Result<()> {
752 if !source.runtime().same_as(&self.runtime.handle()) {
753 return Err(Error::invalid_argument(
754 "render::Renderer source Texture belongs to a different Runtime",
755 ));
756 }
757 if source.width() != self.config.width as usize
758 || source.height() != self.config.height as usize
759 {
760 return Err(Error::invalid_argument(format!(
761 "render::Renderer source extent {}x{} does not match configured {}x{}",
762 source.width(),
763 source.height(),
764 self.config.width,
765 self.config.height,
766 )));
767 }
768 let (slot, generation) = self.acquire_free_slot()?;
769 match blit(source) {
770 Ok(texture) => {
771 self.state.borrow_mut().building = Some(Building {
772 slot,
773 generation,
774 source: BuildingSource::Texture(texture),
775 });
776 Ok(())
777 }
778 Err(error) => {
779 self.release_slot(slot, generation);
780 Err(error)
781 }
782 }
783 }
784
785 pub fn begin_frame_mesh(&self, mesh: &MeshData, camera: &Camera) -> Result<()> {
789 self.require_graphics("mesh")?;
790 camera.validate()?;
791 self.validate_mesh_capacity(mesh)?;
792 let (slot_idx, generation) = self.acquire_free_slot()?;
793 let vp = camera.get_view_projection_matrix();
794 let push_data = build_vcl_push(&vp, self.config.light_direction, self.config.ambient);
795 let index_count = u32::try_from(mesh.indices.len())
796 .map_err(|_| Error::out_of_range("mesh index count overflows u32"))?;
797 if let Err(e) = self.write_mesh_to_slot(slot_idx, mesh) {
798 self.release_slot(slot_idx, generation);
799 return Err(e);
800 }
801 self.state.borrow_mut().building = Some(Building {
802 slot: slot_idx,
803 generation,
804 source: BuildingSource::Mesh {
805 index_count,
806 push_data,
807 },
808 });
809 Ok(())
810 }
811
812 pub fn begin_frame_flat_color(
817 &self,
818 mesh: &MeshData,
819 camera: &Camera,
820 material: &FlatColorMaterial,
821 ) -> Result<()> {
822 self.require_graphics("flat_color")?;
823 material.validate()?;
824 camera.validate()?;
825 self.validate_mesh_capacity(mesh)?;
826 let (slot_idx, generation) = self.acquire_free_slot()?;
827 let mvp = camera.get_view_projection_matrix();
828 let push_data = build_flat_color_push(&mvp, material);
829 let index_count = u32::try_from(mesh.indices.len())
830 .map_err(|_| Error::out_of_range("mesh index count overflows u32"))?;
831 if let Err(e) = self.write_mesh_to_slot(slot_idx, mesh) {
832 self.release_slot(slot_idx, generation);
833 return Err(e);
834 }
835 self.state.borrow_mut().building = Some(Building {
836 slot: slot_idx,
837 generation,
838 source: BuildingSource::FlatColor {
839 index_count,
840 push_data,
841 },
842 });
843 Ok(())
844 }
845
846 pub fn begin_frame_canvas_grid(&self, frame: &CanvasGridFrame) -> Result<()> {
852 self.require_graphics("canvas_grid")?;
853 frame.validate()?;
854 if frame.dst_x < 0
855 || frame.dst_y < 0
856 || frame.dst_x as u64 + u64::from(frame.dst_w) > u64::from(self.config.width)
857 || frame.dst_y as u64 + u64::from(frame.dst_h) > u64::from(self.config.height)
858 {
859 return Err(Error::out_of_range(
860 "canvas-grid destination rect must lie inside the render target",
861 ));
862 }
863 let (slot_idx, generation) = self.acquire_free_slot()?;
864 self.state.borrow_mut().building = Some(Building {
865 slot: slot_idx,
866 generation,
867 source: BuildingSource::CanvasGrid {
868 push_data: frame.pack_push(),
869 },
870 });
871 Ok(())
872 }
873
874 pub fn begin_frame_unlit(
881 &self,
882 mesh: &MeshData,
883 camera: &Camera,
884 material: &UnlitMaterial,
885 ) -> Result<()> {
886 self.require_graphics("unlit")?;
887 material.validate()?;
888 camera.validate()?;
889 self.validate_mesh_capacity(mesh)?;
890 let texture = {
891 let state = self.state.borrow();
892 let texture = if let Some(handle) = material.base_color_texture {
893 state.textures.get(&handle).ok_or_else(|| {
894 Error::invalid_argument(format!(
895 "render::Renderer has no Texture registered for handle {}",
896 handle.0
897 ))
898 })?
899 } else {
900 state
901 .white_texture
902 .as_ref()
903 .ok_or_else(|| Error::failed_precondition("unlit default texture unavailable"))?
904 };
905 texture
906 .native()
907 .ok_or_else(|| Error::failed_precondition("unlit Texture is not image-backed"))?
908 };
909 let (slot_idx, generation) = self.acquire_free_slot()?;
910 let mvp = camera.get_view_projection_matrix();
911 let push_data = build_unlit_push(&mvp, material);
912 let index_count = u32::try_from(mesh.indices.len())
913 .map_err(|_| Error::out_of_range("mesh index count overflows u32"))?;
914 if let Err(e) = self.write_mesh_to_slot(slot_idx, mesh) {
915 self.release_slot(slot_idx, generation);
916 return Err(e);
917 }
918 self.state.borrow_mut().building = Some(Building {
919 slot: slot_idx,
920 generation,
921 source: BuildingSource::Unlit {
922 index_count,
923 push_data,
924 texture,
925 },
926 });
927 Ok(())
928 }
929
930 pub fn begin_frame_scene(&self, scene: &Scene, camera: &Camera) -> Result<()> {
951 self.require_graphics("scene")?;
952 camera.validate()?;
953 let (compiled, packets) = compile_scene_packets(scene)?;
954 if compiled.vertices.is_empty() || compiled.indices.is_empty() {
955 return Err(Error::invalid_argument(
956 "render::Renderer begin_frame_scene: compiled scene contains no visible geometry",
957 ));
958 }
959 self.validate_mesh_capacity(&compiled)?;
960
961 let max_mat = self.config.max_materials_per_scene as usize;
964 let mut mat_slot_map: std::collections::HashMap<Option<crate::render::MaterialId>, usize> =
965 std::collections::HashMap::new();
966 for packet in &packets {
967 let key = packet.material_id;
968 if !mat_slot_map.contains_key(&key) {
969 let next = mat_slot_map.len();
970 if next >= max_mat {
971 return Err(Error::resource_exhausted(
972 "render::Renderer scene exceeds max_materials_per_scene; increase \
973 RendererConfig::max_materials_per_scene",
974 ));
975 }
976 mat_slot_map.insert(key, next);
977 }
978 }
979
980 let mvp = camera.get_view_projection_matrix();
982 let model = crate::vlm::Mat4::identity();
983 let push_data = build_surface_push(&mvp, &model);
984 let scene_data = Box::new(build_scene_lights(&self.config));
985
986 let mut draws: Vec<PendingDraw> = Vec::with_capacity(packets.len());
987 for packet in &packets {
988 let mat_index = mat_slot_map[&packet.material_id];
989 let material = packet
990 .material_id
991 .and_then(|id| scene.materials.iter().find(|m| m.id == id))
992 .map(|entry| &entry.data);
993 let surface = match material {
994 Some(super::Material::Surface(m)) => m.clone(),
995 Some(_) => {
996 return Err(Error::invalid_argument(
997 "render::Renderer scene path requires Surface materials; \
998 FlatColor and Unlit are not supported in begin_frame_scene",
999 ));
1000 }
1001 None => SurfaceMaterial::default(),
1002 };
1003 draws.push(PendingDraw {
1004 index_start: packet.index_start,
1005 index_count: packet.index_count,
1006 push_data,
1007 mat_index,
1008 material_data: Box::new(build_material_params(&surface)),
1009 base_texture: surface.base_color_texture,
1010 orm_texture: surface.orm_texture,
1011 normal_texture: surface.normal_texture,
1012 is_blend: surface.alpha_mode == crate::render::material::AlphaMode::Blend,
1013 });
1014 }
1015
1016 let (slot_idx, generation) = self.acquire_free_slot()?;
1017 if let Err(e) = self.write_mesh_to_slot(slot_idx, &compiled) {
1018 self.release_slot(slot_idx, generation);
1019 return Err(e);
1020 }
1021 self.state.borrow_mut().building = Some(Building {
1022 slot: slot_idx,
1023 generation,
1024 source: BuildingSource::Surface { scene_data, draws },
1025 });
1026 Ok(())
1027 }
1028
1029 pub fn submit_frame(&self) -> Result<RenderFrame> {
1031 let building = self
1032 .state
1033 .borrow_mut()
1034 .building
1035 .take()
1036 .ok_or_else(|| Error::failed_precondition("render::Renderer has no frame in progress"))?;
1037
1038 match building.source {
1039 BuildingSource::Texture(texture) => {
1040 let producer = match self.runtime.checkpoint() {
1041 Ok(event) => event,
1042 Err(error) => {
1043 self.release_slot(building.slot, building.generation);
1044 return Err(error);
1045 }
1046 };
1047 let mut state = self.state.borrow_mut();
1048 let slot = &mut state.slots[building.slot];
1049 if slot.generation != building.generation || !matches!(slot.state, SlotState::Building) {
1050 return Err(Error::failed_precondition(
1051 "render::Renderer frame lease was invalidated",
1052 ));
1053 }
1054 slot.state = SlotState::Submitted(producer.clone());
1055 Ok(RenderFrame {
1056 slot: building.slot,
1057 generation: building.generation,
1058 texture,
1059 producer,
1060 is_graphics: false,
1061 state: Rc::downgrade(&self.state),
1062 released: false,
1063 })
1064 }
1065
1066 BuildingSource::Surface { scene_data, draws } => {
1068 let handle = self.runtime.handle();
1069 let producer = {
1070 let mut state = self.state.borrow_mut();
1071 let p = state
1073 .surface_pipeline
1074 .as_ref()
1075 .ok_or_else(|| Error::failed_precondition("surface pipeline unavailable"))?
1076 .raw();
1077 let pl = state.surface_pipeline.as_ref().unwrap().layout();
1078 let slot_ref = &mut state.slots[building.slot];
1080 let gfx = slot_ref
1081 .graphics
1082 .as_mut()
1083 .ok_or_else(|| Error::failed_precondition("surface graphics slot missing"))?;
1084 gfx.scene_uniform.write_and_flush(scene_data.as_ref())?;
1085 let scene_raw = gfx.scene_uniform.raw();
1086 let white_view = state
1088 .white_texture
1089 .as_ref()
1090 .and_then(|t| t.native())
1091 .map(|n| n.view())
1092 .ok_or_else(|| {
1093 Error::failed_precondition("surface white fallback texture unavailable")
1094 })?;
1095 let scene_set = state
1097 .surface_descriptors
1098 .as_ref()
1099 .ok_or_else(|| Error::failed_precondition("surface descriptor arena unavailable"))?
1100 .write_scene_slot(building.slot, scene_raw, SCENE_LIGHTS_SIZE as u64)?;
1101 let mut draw_cmds: Vec<SceneDrawCmd> = Vec::with_capacity(draws.len());
1103 for draw in &draws {
1104 let mat_uniform = state.slots[building.slot]
1105 .graphics
1106 .as_mut()
1107 .ok_or_else(|| {
1108 Error::failed_precondition("surface graphics slot missing (material)")
1109 })?
1110 .material_uniforms
1111 .get(draw.mat_index)
1112 .ok_or_else(|| {
1113 Error::internal("surface material UBO index exceeds allocated count")
1114 })?;
1115 mat_uniform.write_and_flush(draw.material_data.as_ref())?;
1116 let mat_raw = mat_uniform.raw();
1117 let base_view = draw
1118 .base_texture
1119 .and_then(|h| state.textures.get(&h))
1120 .and_then(|t| t.native())
1121 .map(|n| n.view());
1122 let orm_view = draw
1123 .orm_texture
1124 .and_then(|h| state.textures.get(&h))
1125 .and_then(|t| t.native())
1126 .map(|n| n.view());
1127 let normal_view = draw
1128 .normal_texture
1129 .and_then(|h| state.textures.get(&h))
1130 .and_then(|t| t.native())
1131 .map(|n| n.view());
1132 let mat_set = state
1133 .surface_descriptors
1134 .as_ref()
1135 .unwrap()
1136 .write_material_slot(
1137 building.slot,
1138 draw.mat_index,
1139 mat_raw,
1140 MATERIAL_PARAMS_SIZE as u64,
1141 base_view,
1142 orm_view,
1143 normal_view,
1144 white_view,
1145 )?;
1146 draw_cmds.push(SceneDrawCmd {
1147 index_start: draw.index_start,
1148 index_count: draw.index_count,
1149 push_data: draw.push_data.to_vec(),
1150 material_set: mat_set,
1151 is_blend: draw.is_blend,
1152 });
1153 }
1154 draw_cmds.sort_by(|a, b| match (a.is_blend, b.is_blend) {
1160 (false, true) => std::cmp::Ordering::Less,
1161 (true, false) => std::cmp::Ordering::Greater,
1162 (true, true) => b.index_start.cmp(&a.index_start),
1163 (false, false) => std::cmp::Ordering::Equal,
1164 });
1165 let blend_p = state
1167 .surface_blend_pipeline
1168 .as_ref()
1169 .ok_or_else(|| Error::failed_precondition("surface blend pipeline unavailable"))?
1170 .raw();
1171 let slot_mut = &mut state.slots[building.slot];
1172 let gfx_mut = slot_mut.graphics.as_mut().expect("graphics slot populated");
1173 let result = handle.record_and_submit_scene_frame(
1174 &mut gfx_mut.target,
1175 &gfx_mut.vertex_buf,
1176 &gfx_mut.index_buf,
1177 self.config.clear_color.to_array(),
1178 vk::ShaderStageFlagBits::VERTEX_BIT,
1179 p,
1180 blend_p,
1181 pl,
1182 scene_set,
1183 &draw_cmds,
1184 );
1185 match result {
1186 Ok(event) => event,
1187 Err(e) => {
1188 slot_mut.state = SlotState::Free;
1189 slot_mut.sampled_image = None;
1190 return Err(e);
1191 }
1192 }
1193 };
1194 let texture = {
1195 let state = self.state.borrow();
1196 let gfx = state.slots[building.slot]
1197 .graphics
1198 .as_ref()
1199 .expect("graphics slot populated");
1200 texture_from_render_target(
1201 handle,
1202 self.state.clone(),
1203 RenderTargetLease {
1204 slot: building.slot,
1205 generation: building.generation,
1206 },
1207 gfx.target.color_image,
1208 gfx.target.color_view,
1209 gfx.target.width,
1210 gfx.target.height,
1211 )
1212 };
1213 {
1214 let mut state = self.state.borrow_mut();
1215 state.slots[building.slot].state = SlotState::Submitted(producer.clone());
1216 state.slots[building.slot].sampled_image = None;
1217 state.slots[building.slot].texture_lease = Some(texture.lease_weak());
1218 }
1219 Ok(RenderFrame {
1220 slot: building.slot,
1221 generation: building.generation,
1222 texture,
1223 producer,
1224 is_graphics: true,
1225 state: Rc::downgrade(&self.state),
1226 released: false,
1227 })
1228 }
1229
1230 source => {
1232 let (index_count, push_bytes, push_stages, pipeline_vk, pipeline_layout, descriptor_sets) =
1233 {
1234 let state = self.state.borrow();
1235 self.resolve_graphics_source(&state, building.slot, &source)
1236 }?;
1237 let vertexless = matches!(source, BuildingSource::CanvasGrid { .. });
1238 let sampled_image = match &source {
1239 BuildingSource::Unlit { texture, .. } => Some(texture.clone()),
1240 _ => None,
1241 };
1242 let handle = self.runtime.handle();
1243 let producer = {
1244 let mut state = self.state.borrow_mut();
1245 let slot = &mut state.slots[building.slot];
1246 let gfx = slot.graphics.as_mut().expect("graphics slot populated");
1247 let result = if vertexless {
1248 handle.record_and_submit_vertexless_frame(
1249 &mut gfx.target,
1250 index_count,
1251 self.config.clear_color.to_array(),
1252 &push_bytes,
1253 push_stages,
1254 pipeline_vk,
1255 pipeline_layout,
1256 &descriptor_sets,
1257 )
1258 } else {
1259 handle.record_and_submit_mesh_frame(
1260 &mut gfx.target,
1261 &gfx.vertex_buf,
1262 &gfx.index_buf,
1263 index_count,
1264 self.config.clear_color.to_array(),
1265 &push_bytes,
1266 push_stages,
1267 pipeline_vk,
1268 pipeline_layout,
1269 &descriptor_sets,
1270 )
1271 };
1272 match result {
1273 Ok(event) => event,
1274 Err(e) => {
1275 slot.state = SlotState::Free;
1276 slot.sampled_image = None;
1277 return Err(e);
1278 }
1279 }
1280 };
1281 let texture = {
1282 let state = self.state.borrow();
1283 let gfx = state.slots[building.slot]
1284 .graphics
1285 .as_ref()
1286 .expect("graphics slot populated");
1287 texture_from_render_target(
1288 handle,
1289 self.state.clone(),
1290 RenderTargetLease {
1291 slot: building.slot,
1292 generation: building.generation,
1293 },
1294 gfx.target.color_image,
1295 gfx.target.color_view,
1296 gfx.target.width,
1297 gfx.target.height,
1298 )
1299 };
1300 {
1301 let mut state = self.state.borrow_mut();
1302 state.slots[building.slot].state = SlotState::Submitted(producer.clone());
1303 state.slots[building.slot].sampled_image = sampled_image;
1304 state.slots[building.slot].texture_lease = Some(texture.lease_weak());
1305 }
1306 Ok(RenderFrame {
1307 slot: building.slot,
1308 generation: building.generation,
1309 texture,
1310 producer,
1311 is_graphics: true,
1312 state: Rc::downgrade(&self.state),
1313 released: false,
1314 })
1315 }
1316 }
1317 }
1318
1319 pub fn cancel_frame(&self) -> Result<()> {
1321 let building = self
1322 .state
1323 .borrow_mut()
1324 .building
1325 .take()
1326 .ok_or_else(|| Error::failed_precondition("render::Renderer has no frame in progress"))?;
1327 self.release_slot(building.slot, building.generation);
1328 Ok(())
1329 }
1330
1331 pub fn collect(&self) -> Result<usize> {
1333 let mut state = self.state.borrow_mut();
1334 let mut released = 0;
1335 for slot in &mut state.slots {
1336 if let SlotState::Submitted(event) = &slot.state
1337 && event.is_complete()?
1338 && slot
1339 .texture_lease
1340 .as_ref()
1341 .is_none_or(|lease| lease.strong_count() == 0)
1342 {
1343 slot.state = SlotState::Free;
1344 slot.sampled_image = None;
1345 slot.texture_lease = None;
1346 released += 1;
1347 }
1348 }
1349 Ok(released)
1350 }
1351
1352 pub fn close(&self) -> Result<()> {
1354 let events = {
1355 let mut state = self.state.borrow_mut();
1356 if state.closed {
1357 return Ok(());
1358 }
1359 if state.building.is_some() {
1360 return Err(Error::failed_precondition(
1361 "render::Renderer cannot close with a frame in progress; submit or cancel it",
1362 ));
1363 }
1364 state.closed = true;
1365 state
1366 .slots
1367 .iter()
1368 .filter_map(|slot| match &slot.state {
1369 SlotState::Submitted(event) => Some(event.clone()),
1370 _ => None,
1371 })
1372 .collect::<Vec<_>>()
1373 };
1374 for event in events {
1375 event.wait()?;
1376 }
1377 self.collect()?;
1378 Ok(())
1379 }
1380
1381 fn require_graphics(&self, path: &str) -> Result<()> {
1384 if self.state.borrow().pipeline.is_none() {
1385 Err(Error::failed_precondition(format!(
1386 "render::Renderer {path} path requires a graphics-capable Runtime and non-zero \
1387 max_vertex_count/max_index_count in RendererConfig",
1388 )))
1389 } else {
1390 Ok(())
1391 }
1392 }
1393
1394 fn validate_mesh_capacity(&self, mesh: &MeshData) -> Result<()> {
1395 if mesh.vertices.is_empty() || mesh.indices.is_empty() || !mesh.indices.len().is_multiple_of(3)
1396 {
1397 return Err(Error::invalid_argument(
1398 "render::Renderer requires a non-empty indexed triangle-list mesh",
1399 ));
1400 }
1401 if mesh.vertices.len() > self.config.max_vertex_count as usize {
1402 return Err(Error::resource_exhausted(
1403 "render::Renderer mesh vertex count exceeds max_vertex_count",
1404 ));
1405 }
1406 if mesh.indices.len() > self.config.max_index_count as usize {
1407 return Err(Error::resource_exhausted(
1408 "render::Renderer mesh index count exceeds max_index_count",
1409 ));
1410 }
1411 Ok(())
1412 }
1413
1414 fn write_mesh_to_slot(&self, slot_idx: usize, mesh: &MeshData) -> Result<()> {
1415 let state = self.state.borrow();
1416 let gfx = state.slots[slot_idx]
1417 .graphics
1418 .as_ref()
1419 .expect("mesh slot has graphics");
1420 let vbytes = mesh_vertex_bytes(mesh);
1421 let ibytes: Vec<u8> = mesh.indices.iter().flat_map(|i| i.to_le_bytes()).collect();
1422 gfx
1423 .vertex_buf
1424 .write_and_flush(&vbytes)
1425 .and_then(|()| gfx.index_buf.write_and_flush(&ibytes))
1426 }
1427
1428 fn resolve_graphics_source(
1434 &self,
1435 state: &RendererState,
1436 slot: usize,
1437 source: &BuildingSource,
1438 ) -> Result<DrawParams> {
1439 match source {
1440 BuildingSource::Mesh {
1441 index_count,
1442 push_data,
1443 } => {
1444 let p = state.pipeline.as_ref().expect("vcl pipeline live");
1445 Ok((
1446 *index_count,
1447 push_data.to_vec(),
1448 vk::ShaderStageFlagBits::VERTEX_BIT,
1449 p.raw(),
1450 p.layout(),
1451 Vec::new(),
1452 ))
1453 }
1454 BuildingSource::FlatColor {
1455 index_count,
1456 push_data,
1457 } => {
1458 let p = state
1459 .flat_color_pipeline
1460 .as_ref()
1461 .ok_or_else(|| Error::failed_precondition("flat-color pipeline unavailable"))?;
1462 Ok((
1463 *index_count,
1464 push_data.to_vec(),
1465 vk::ShaderStageFlagBits::VERTEX_BIT | vk::ShaderStageFlagBits::FRAGMENT_BIT,
1466 p.raw(),
1467 p.layout(),
1468 Vec::new(),
1469 ))
1470 }
1471 BuildingSource::Unlit {
1472 index_count,
1473 push_data,
1474 texture,
1475 } => {
1476 let p = state
1477 .unlit_pipeline
1478 .as_ref()
1479 .ok_or_else(|| Error::failed_precondition("unlit pipeline unavailable"))?;
1480 let descriptors = state
1481 .unlit_descriptors
1482 .as_ref()
1483 .ok_or_else(|| Error::failed_precondition("unlit descriptor arena unavailable"))?;
1484 let set = descriptors.write_sampled_image(slot, texture.view())?;
1485 Ok((
1486 *index_count,
1487 push_data.to_vec(),
1488 vk::ShaderStageFlagBits::VERTEX_BIT | vk::ShaderStageFlagBits::FRAGMENT_BIT,
1489 p.raw(),
1490 p.layout(),
1491 vec![set],
1492 ))
1493 }
1494 BuildingSource::CanvasGrid { push_data } => {
1495 let p = state
1496 .canvas_grid_pipeline
1497 .as_ref()
1498 .ok_or_else(|| Error::failed_precondition("canvas-grid pipeline unavailable"))?;
1499 Ok((
1500 3,
1501 push_data.to_vec(),
1502 vk::ShaderStageFlagBits::FRAGMENT_BIT,
1503 p.raw(),
1504 p.layout(),
1505 Vec::new(),
1506 ))
1507 }
1508 BuildingSource::Surface { .. } => {
1509 unreachable!("Surface source handled in the Surface match arm")
1510 }
1511 BuildingSource::Texture(_) => {
1512 unreachable!("Texture source handled before resolve_graphics_source")
1513 }
1514 }
1515 }
1516
1517 fn acquire_free_slot(&self) -> Result<(usize, u64)> {
1518 let mut state = self.state.borrow_mut();
1519 if state.closed {
1520 return Err(Error::failed_precondition("render::Renderer is closed"));
1521 }
1522 if state.building.is_some() {
1523 return Err(Error::failed_precondition(
1524 "render::Renderer already has a frame in progress",
1525 ));
1526 }
1527 let Some((idx, entry)) = state
1528 .slots
1529 .iter_mut()
1530 .enumerate()
1531 .find(|(_, s)| matches!(s.state, SlotState::Free))
1532 else {
1533 return Err(Error::resource_exhausted(
1534 "render::Renderer target ring has no reusable slot; consume or collect a frame",
1535 ));
1536 };
1537 entry.generation = entry.generation.checked_add(1).ok_or_else(|| {
1538 Error::resource_exhausted("render::Renderer target generation space is exhausted")
1539 })?;
1540 entry.sampled_image = None;
1541 entry.texture_lease = None;
1542 entry.state = SlotState::Building;
1543 Ok((idx, entry.generation))
1544 }
1545
1546 fn release_slot(&self, slot: usize, generation: u64) {
1547 let mut state = self.state.borrow_mut();
1548 if let Some(entry) = state.slots.get_mut(slot)
1549 && entry.generation == generation
1550 {
1551 entry.state = SlotState::Free;
1552 entry.sampled_image = None;
1553 entry.texture_lease = None;
1554 }
1555 }
1556}
1557
1558impl RenderFrame {
1561 pub const fn color(&self) -> &Texture {
1563 &self.texture
1564 }
1565
1566 pub const fn producer(&self) -> &Event {
1568 &self.producer
1569 }
1570
1571 pub fn width(&self) -> usize {
1573 self.texture.width()
1574 }
1575
1576 pub fn height(&self) -> usize {
1578 self.texture.height()
1579 }
1580
1581 pub fn consume_readback(mut self) -> Result<Vec<u8>> {
1583 let result = if self.is_graphics {
1584 self.producer.wait()?;
1585 if let Some(state) = self.state.upgrade() {
1586 let state = state.borrow();
1587 state.slots[self.slot]
1588 .graphics
1589 .as_ref()
1590 .ok_or_else(|| Error::failed_precondition("render::RenderFrame graphics slot missing"))?
1591 .target
1592 .read_color_rgba8()
1593 } else {
1594 Err(Error::failed_precondition(
1595 "render::RenderFrame renderer has been dropped",
1596 ))
1597 }
1598 } else {
1599 self.producer.wait()?;
1600 self.texture.read_rgba8()
1601 };
1602 if result.is_ok() {
1603 self.release_completed();
1604 } else {
1605 self.do_release();
1606 }
1607 self.released = true;
1608 result
1609 }
1610
1611 pub fn abandon(mut self) {
1613 self.do_release();
1614 self.released = true;
1615 }
1616
1617 fn do_release(&self) {
1618 if let Some(state) = self.state.upgrade() {
1619 let mut state = state.borrow_mut();
1620 if let Some(slot) = state.slots.get_mut(self.slot)
1621 && slot.generation == self.generation
1622 && !matches!(&slot.state, SlotState::Submitted(event) if event.follows_or_equals(&self.producer))
1623 {
1624 slot.state = SlotState::Submitted(self.producer.clone());
1625 }
1626 }
1627 }
1628
1629 fn release_completed(&self) {
1630 if let Some(state) = self.state.upgrade() {
1631 let mut state = state.borrow_mut();
1632 if let Some(slot) = state.slots.get_mut(self.slot)
1638 && slot.generation == self.generation
1639 && (!self.is_graphics || self.texture.lease_strong_count() == 1)
1640 && matches!(&slot.state, SlotState::Submitted(event) if matches!(event.is_complete(), Ok(true)))
1641 {
1642 slot.state = SlotState::Free;
1643 slot.sampled_image = None;
1644 slot.texture_lease = None;
1645 }
1646 }
1647 }
1648}
1649
1650impl Drop for RenderFrame {
1651 fn drop(&mut self) {
1652 if !self.released {
1653 self.do_release();
1654 }
1655 }
1656}
1657
1658fn validate_config(config: &RendererConfig) -> Result<()> {
1661 if config.width == 0
1662 || config.height == 0
1663 || config.target_slot_count == 0
1664 || config.target_slot_count > 4
1665 {
1666 return Err(Error::invalid_argument(
1667 "render::RendererConfig requires non-zero extent and 1–4 target slots",
1668 ));
1669 }
1670 if !config
1671 .clear_color
1672 .to_array()
1673 .iter()
1674 .all(|v| v.is_finite() && (0.0..=1.0).contains(v))
1675 {
1676 return Err(Error::invalid_argument(
1677 "render::RendererConfig clear_color must be finite values in [0, 1]",
1678 ));
1679 }
1680 if !config.light_direction.iter().all(|v| v.is_finite())
1681 || !config.ambient.is_finite()
1682 || !(0.0..=1.0).contains(&config.ambient)
1683 {
1684 return Err(Error::invalid_argument(
1685 "render::RendererConfig light_direction must be finite; ambient must be in [0, 1]",
1686 ));
1687 }
1688 if config.max_materials_per_scene == 0 || config.max_materials_per_scene > 64 {
1689 return Err(Error::invalid_argument(
1690 "render::RendererConfig max_materials_per_scene must be in [1, 64]",
1691 ));
1692 }
1693 Ok(())
1694}