1use std::{
4 path::Path,
5 rc::Rc,
6 sync::atomic::{AtomicU64, Ordering},
7};
8
9type RenderTargetImageInfo = (vk::Image, vk::ImageView, u32, u32, Rc<dyn std::any::Any>);
11
12#[derive(Clone, Copy)]
13pub(super) struct RenderTargetLease {
14 pub(super) slot: usize,
15 pub(super) generation: u64,
16}
17
18use crate::{Color, DType, Engine, Error, Image, ImageFormat, ImageLayout, Matrix, Result};
19
20#[derive(Clone)]
22enum TextureBacking {
23 BufferBacked {
25 data: Matrix,
26 native: Rc<crate::runtime::NativeRgbaImage>,
27 },
28 RenderTarget {
33 engine_handle: crate::runtime::EngineHandle,
34 owner: Rc<std::cell::RefCell<super::renderer::RendererState>>,
35 lease: RenderTargetLease,
36 image: vk::Image,
37 view: vk::ImageView,
38 width: u32,
39 height: u32,
40 },
41}
42
43#[derive(Clone)]
49pub(crate) struct TextureSemantic {
50 pub(crate) id: u64,
51}
52
53impl TextureSemantic {
54 fn new() -> crate::Result<Self> {
55 Ok(Self {
56 id: next_texture_value_id()?,
57 })
58 }
59}
60
61#[derive(Clone)]
69pub struct Texture {
70 backing: TextureBacking,
71 semantic: Rc<TextureSemantic>,
72}
73
74impl Texture {
75 #[allow(dead_code)]
80 pub(crate) fn value_id(&self) -> u64 {
81 self.semantic.id
82 }
83
84 pub(crate) fn engine_handle(&self) -> &crate::runtime::EngineHandle {
85 match &self.backing {
86 TextureBacking::BufferBacked { data, .. } => data.engine_handle(),
87 TextureBacking::RenderTarget { engine_handle, .. } => engine_handle,
88 }
89 }
90
91 pub fn width(&self) -> usize {
93 match &self.backing {
94 TextureBacking::BufferBacked { data, .. } => data.shape()[1],
95 TextureBacking::RenderTarget { width, .. } => *width as usize,
96 }
97 }
98
99 pub fn height(&self) -> usize {
101 match &self.backing {
102 TextureBacking::BufferBacked { data, .. } => data.shape()[0],
103 TextureBacking::RenderTarget { height, .. } => *height as usize,
104 }
105 }
106
107 pub fn dtype(&self) -> DType {
109 match &self.backing {
110 TextureBacking::BufferBacked { data, .. } => data.dtype(),
111 TextureBacking::RenderTarget { .. } => DType::U8,
112 }
113 }
114
115 pub fn read_rgba8(&self) -> Result<Vec<u8>> {
125 match &self.backing {
126 TextureBacking::BufferBacked { data, .. } => data.read::<u8>(),
127 TextureBacking::RenderTarget { .. } => Err(Error::failed_precondition(
128 "render::Texture::read_rgba8 is not available for render-target-backed textures; \
129 use RenderFrame::consume_readback",
130 )),
131 }
132 }
133
134 pub(crate) fn native(&self) -> Option<Rc<crate::runtime::NativeRgbaImage>> {
135 match &self.backing {
136 TextureBacking::BufferBacked { native, .. } => Some(native.clone()),
137 TextureBacking::RenderTarget { .. } => None,
138 }
139 }
140
141 pub(crate) const fn is_render_target(&self) -> bool {
142 matches!(self.backing, TextureBacking::RenderTarget { .. })
143 }
144
145 pub(crate) fn mark_consumed(&self, event: &crate::Event) -> Result<()> {
146 match &self.backing {
147 TextureBacking::RenderTarget {
148 engine_handle,
149 owner,
150 lease,
151 ..
152 } => {
153 if !engine_handle.owns_event(event) {
154 return Err(Error::invalid_argument(
155 "render target consumer event belongs to another Engine",
156 ));
157 }
158 owner
159 .borrow_mut()
160 .mark_texture_consumed(lease.slot, lease.generation, event)
161 }
162 TextureBacking::BufferBacked { .. } => Err(Error::failed_precondition(
163 "consumer completion applies only to render-target-backed textures",
164 )),
165 }
166 }
167
168 pub(crate) fn render_target_image(&self) -> Option<RenderTargetImageInfo> {
170 match &self.backing {
171 TextureBacking::RenderTarget {
172 owner,
173 image,
174 view,
175 width,
176 height,
177 ..
178 } => Some((*image, *view, *width, *height, owner.clone())),
179 TextureBacking::BufferBacked { .. } => None,
180 }
181 }
182
183 pub(crate) fn lease_weak(&self) -> std::rc::Weak<TextureSemantic> {
184 Rc::downgrade(&self.semantic)
185 }
186
187 pub(crate) fn lease_strong_count(&self) -> usize {
188 Rc::strong_count(&self.semantic)
189 }
190}
191
192pub fn texture_from_rgba8(rgba: &[u8], width: usize, height: usize) -> Result<Texture> {
202 texture_from_rgba8_on(&Engine::current()?, rgba, width, height)
203}
204
205pub fn texture_from_rgba8_on(
212 engine: &Engine,
213 rgba: &[u8],
214 width: usize,
215 height: usize,
216) -> Result<Texture> {
217 if width == 0 || height == 0 {
218 return Err(Error::invalid_argument(
219 "render::texture_from_rgba8 dimensions must be non-zero",
220 ));
221 }
222 let expected = width
223 .checked_mul(height)
224 .and_then(|pixels| pixels.checked_mul(4))
225 .ok_or_else(|| Error::out_of_range("texture byte count overflows usize"))?;
226 if rgba.len() != expected {
227 return Err(Error::invalid_argument(
228 "render::texture_from_rgba8 requires exactly width * height * 4 bytes",
229 ));
230 }
231 let data = Matrix::new_from_slice_on(engine, [height, width, 4], rgba)?;
232 texture_from_matrix(data, width, height)
233}
234
235pub fn texture_from_image(image: &Image) -> Result<Texture> {
246 if image.layout() != ImageLayout::Hwc
247 || image.format() != ImageFormat::Rgba
248 || image.dtype() != DType::U8
249 {
250 return Err(Error::invalid_argument(
251 "render::texture_from_image requires an HWC RGBA U8 image",
252 ));
253 }
254 let data = crate::matrix::copy(image.as_matrix())?;
255 let width = image.as_matrix().shape()[1];
256 let height = image.as_matrix().shape()[0];
257 texture_from_matrix(data, width, height)
258}
259
260pub fn texture_from_file(path: impl AsRef<Path>) -> Result<Texture> {
275 let path = path.as_ref();
276 texture_from_file_on(&Engine::current()?, path)
277}
278pub fn texture_from_file_on(engine: &Engine, path: impl AsRef<Path>) -> Result<Texture> {
285 let decoded = image_codec::ImageReader::open(path)
286 .map_err(|source| Error::io("texture image file open", source))?
287 .with_guessed_format()
288 .map_err(|source| Error::io("texture image format probe", source))?
289 .decode()
290 .map_err(|source| Error::backend_failure("image", "texture decode", source))?
291 .to_rgba8();
292 texture_from_rgba8_on(
293 engine,
294 decoded.as_raw(),
295 decoded.width() as usize,
296 decoded.height() as usize,
297 )
298}
299
300pub fn blit(texture: &Texture) -> Result<Texture> {
310 let data = match &texture.backing {
311 TextureBacking::BufferBacked { data, .. } => crate::matrix::copy(data)?,
312 TextureBacking::RenderTarget { .. } => {
313 return Err(Error::failed_precondition(
314 "render::blit is not available for render-target-backed textures",
315 ));
316 }
317 };
318 texture_from_matrix(data, texture.width(), texture.height())
319}
320
321pub fn clear(texture: &Texture, color: Color) -> Result<Texture> {
331 let rgba = color.to_u32().to_be_bytes();
332 let pixel_count = texture
333 .width()
334 .checked_mul(texture.height())
335 .ok_or_else(|| Error::out_of_range("texture pixel count overflows usize"))?;
336 let mut pixels = vec![
337 0_u8;
338 pixel_count.checked_mul(4).ok_or_else(|| {
339 Error::out_of_range("texture clear byte count overflows usize")
340 })?
341 ];
342 for pixel in pixels.chunks_mut(4) {
343 pixel.copy_from_slice(&rgba);
344 }
345 texture_from_rgba8_from_engine(texture, &pixels)
346}
347
348fn texture_from_rgba8_from_engine(texture: &Texture, rgba: &[u8]) -> Result<Texture> {
349 let engine_handle = texture.engine_handle().clone();
350 let element_count = rgba.len();
351 let data = Matrix::allocate(
352 &engine_handle,
353 vec![texture.height(), texture.width(), 4],
354 element_count,
355 DType::U8,
356 )?;
357 data.write_values(rgba)?;
358 texture_from_matrix(data, texture.width(), texture.height())
359}
360
361pub(crate) fn texture_from_matrix(data: Matrix, width: usize, height: usize) -> Result<Texture> {
362 let w32 =
363 u32::try_from(width).map_err(|_| Error::out_of_range("texture width exceeds Vulkan limits"))?;
364 let h32 = u32::try_from(height)
365 .map_err(|_| Error::out_of_range("texture height exceeds Vulkan limits"))?;
366 let native = data
367 .engine_handle()
368 .upload_native_rgba_image(data.storage(), w32, h32)?;
369 let semantic = Rc::new(TextureSemantic::new()?);
370 Ok(Texture {
375 backing: TextureBacking::BufferBacked { data, native },
376 semantic,
377 })
378}
379
380pub(super) fn texture_from_render_target(
385 engine_handle: crate::runtime::EngineHandle,
386 owner: Rc<std::cell::RefCell<super::renderer::RendererState>>,
387 lease: RenderTargetLease,
388 image: vk::Image,
389 view: vk::ImageView,
390 width: u32,
391 height: u32,
392) -> Texture {
393 let semantic = TextureSemantic::new().unwrap_or(TextureSemantic { id: 0 });
396 Texture {
397 backing: TextureBacking::RenderTarget {
398 engine_handle,
399 owner,
400 lease,
401 image,
402 view,
403 width,
404 height,
405 },
406 semantic: Rc::new(semantic),
407 }
408}
409
410fn next_texture_value_id() -> crate::Result<u64> {
412 static NEXT_TEXTURE_VALUE_ID: AtomicU64 = AtomicU64::new(1);
413 let id = NEXT_TEXTURE_VALUE_ID.fetch_add(1, Ordering::Relaxed);
414 if id == u64::MAX {
415 return Err(crate::Error::resource_exhausted(
416 "texture semantic value identity space is exhausted",
417 ));
418 }
419 Ok(id)
420}
421
422pub fn save_texture_file(texture: &Texture, path: impl AsRef<Path>, quality: u32) -> Result<()> {
432 let width = u32::try_from(texture.width())
433 .map_err(|_| Error::out_of_range("texture width exceeds codec limits"))?;
434 let height = u32::try_from(texture.height())
435 .map_err(|_| Error::out_of_range("texture height exceeds codec limits"))?;
436 let rgba = texture.read_rgba8()?;
437 crate::image::save_rgba_file(&rgba, width, height, path, quality)
438}