Skip to main content

oa/render/
texture.rs

1//! Packed buffer-backed texture values and explicit host boundaries.
2
3use std::{
4	path::Path,
5	rc::Rc,
6	sync::atomic::{AtomicU64, Ordering},
7};
8
9/// Raw Vulkan image and view info returned by [`Texture::render_target_image`].
10type 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, Error, Image, ImageFormat, ImageLayout, Matrix, Result, Runtime};
19
20/// Internal backing for a `Texture` value.
21#[derive(Clone)]
22enum TextureBacking {
23	/// Buffer-backed: a U8 Matrix `[H, W, 4]` plus an uploaded native image.
24	BufferBacked {
25		data: Matrix,
26		native: Rc<crate::runtime::NativeRgbaImage>,
27	},
28	/// Render-target-backed: a non-owning view of an already-allocated native
29	/// color image (R8G8B8A8_UNORM, SHADER_READ_ONLY after draw).
30	/// Readback is not available through this backing; use the owning
31	/// `RenderFrame::consume_readback` instead.
32	RenderTarget {
33		runtime: crate::runtime::RuntimeHandle,
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/// Stable semantic identity for one texture value.
44///
45/// Assigned once at creation, never reused.  Used for semantic-graph lineage
46/// tracking in the same way `ImageSemantic` and `MatrixSemantic` track Image and
47/// Matrix values.
48#[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/// Packed RGBA8 texture value reusable by Render, Presenter, Image, and UI.
62///
63/// Two backings are currently admitted:
64/// - **Buffer-backed**: uploaded from host bytes or a Matrix; supports `read_rgba8`.
65/// - **Render-target-backed**: a non-owning alias of a `Renderer` slot's color
66///   image; valid only while the originating `RenderFrame` is live.
67///   Readback uses `RenderFrame::consume_readback`, not `read_rgba8`.
68#[derive(Clone)]
69pub struct Texture {
70	backing: TextureBacking,
71	semantic: Rc<TextureSemantic>,
72}
73
74impl Texture {
75	/// Return the stable semantic identity for this texture value.
76	///
77	/// Used for semantic-graph lineage tracking and future UI/plot value
78	/// identity checks.
79	#[allow(dead_code)]
80	pub(crate) fn value_id(&self) -> u64 {
81		self.semantic.id
82	}
83
84	pub(crate) fn runtime(&self) -> &crate::runtime::RuntimeHandle {
85		match &self.backing {
86			TextureBacking::BufferBacked { data, .. } => data.runtime(),
87			TextureBacking::RenderTarget { runtime, .. } => runtime,
88		}
89	}
90
91	/// Return the texture width.
92	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	/// Return the texture height.
100	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	/// Return the packed byte dtype (always `U8` for RGBA8 textures).
108	pub fn dtype(&self) -> DType {
109		match &self.backing {
110			TextureBacking::BufferBacked { data, .. } => data.dtype(),
111			TextureBacking::RenderTarget { .. } => DType::U8,
112		}
113	}
114
115	/// Read packed row-major RGBA8 pixels to host memory.
116	///
117	/// Only available for buffer-backed textures. Render-target-backed textures
118	/// must use `RenderFrame::consume_readback` instead.
119	///
120	/// # Errors
121	///
122	/// Returns an error when submission, completion, mapping, or cache
123	/// invalidation fails, or when called on a render-target-backed Texture.
124	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				runtime,
149				owner,
150				lease,
151				..
152			} => {
153				if !runtime.owns_event(event) {
154					return Err(Error::invalid_argument(
155						"render target consumer event belongs to another Runtime",
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	/// Return the raw Vulkan image and view for render-target-backed presentation.
169	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
192/// Upload one exact packed row-major RGBA8 host image as a Texture.
193///
194/// # Errors
195///
196/// Returns an error for zero or overflowing dimensions, a mismatched byte
197/// count, exhausted semantic identity, or device allocation/upload failure.
198///
199/// This variant uploads on this thread's default runtime. An runtime
200/// initialization failure is returned before the upload starts.
201pub fn texture_from_rgba8(rgba: &[u8], width: usize, height: usize) -> Result<Texture> {
202	texture_from_rgba8_on(&Runtime::current()?, rgba, width, height)
203}
204
205/// Upload one exact packed row-major RGBA8 host image as a Texture on a
206/// particular runtime.
207///
208/// # Errors
209///
210/// Returns the same errors as [`texture_from_rgba8`].
211pub fn texture_from_rgba8_on(
212	runtime: &Runtime,
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(runtime, [height, width, 4], rgba)?;
232	texture_from_matrix(data, width, height)
233}
234
235/// Convert one packed RGBA8 HWC image into an independent Texture value.
236///
237/// The operation retains the texture/image semantic distinction and performs a
238/// device-side deep copy. Other image layouts, channel orders, and scalar
239/// representations require an explicit image conversion before this boundary.
240///
241/// # Errors
242///
243/// Returns an error unless `image` is an unbatched U8 HWC RGBA image or its
244/// device copy cannot be recorded.
245pub 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
260/// Decode a still-image file directly into a packed RGBA8 Texture.
261///
262/// This host codec boundary uploads the decoded pixels once, without converting
263/// through normalized planar FP32 Image storage or reading device pixels back.
264/// Donor composition: `oa/ui/viewer.cpp::openImage`, `FnImage::decodeFile` and
265/// `FnTexture::fromImage`; adapted to Rust's device-resident Image distinction.
266///
267/// # Errors
268///
269/// Returns an error for inaccessible, unsupported or malformed media, or failed
270/// checked texture allocation/upload.
271///
272/// This variant uploads on this thread's default runtime. An runtime
273/// initialization failure is returned before decoding starts.
274pub fn texture_from_file(path: impl AsRef<Path>) -> Result<Texture> {
275	let path = path.as_ref();
276	texture_from_file_on(&Runtime::current()?, path)
277}
278/// Decode a still-image file directly into a packed RGBA8 Texture on a
279/// particular runtime.
280///
281/// # Errors
282///
283/// Returns the same errors as [`texture_from_file`].
284pub fn texture_from_file_on(runtime: &Runtime, 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		runtime,
294		decoded.as_raw(),
295		decoded.width() as usize,
296		decoded.height() as usize,
297	)
298}
299
300/// Deep-copy a packed Texture into independent device storage.
301///
302/// This is the currently admitted whole-surface `FnTexture::blit` equivalent.
303/// Rectangle and scaled blits remain unavailable because the C++ donor also
304/// rejects them rather than silently selecting different sampling semantics.
305///
306/// # Errors
307///
308/// Returns an error when the device copy cannot be recorded.
309pub 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
321/// Return an independent packed Texture filled with one RGBA8 clear color.
322///
323/// The result has the source extent but does not alias source storage. This is
324/// Rust's immutable-value spelling of the C++ donor's in-place clear.
325///
326/// # Errors
327///
328/// Returns an error for non-finite or out-of-range color components, exhausted
329/// texture identity, or failed device allocation/upload.
330pub 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_runtime(texture, &pixels)
346}
347
348fn texture_from_rgba8_from_runtime(texture: &Texture, rgba: &[u8]) -> Result<Texture> {
349	let runtime = texture.runtime().clone();
350	let element_count = rgba.len();
351	let data = Matrix::allocate(
352		&runtime,
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		.runtime()
368		.upload_native_rgba_image(data.storage(), w32, h32)?;
369	let semantic = Rc::new(TextureSemantic::new()?);
370	// Keep value metadata on the Texture itself. Like Matrix constructors,
371	// construction does not add an unused external value to the eager graph.
372	// A real consuming operation owns semantic admission and physical bindings.
373
374	Ok(Texture {
375		backing: TextureBacking::BufferBacked { data, native },
376		semantic,
377	})
378}
379
380/// Create a non-owning render-target-backed Texture alias.
381///
382/// The caller is responsible for ensuring the backing image remains live
383/// (via the `RenderFrame`'s `Weak` reference to `RendererState`).
384pub(super) fn texture_from_render_target(
385	runtime: crate::runtime::RuntimeHandle,
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	// Render-target textures are aliases; a fresh semantic id distinguishes
394	// them from their backing image and from each other across frames.
395	let semantic = TextureSemantic::new().unwrap_or(TextureSemantic { id: 0 });
396	Texture {
397		backing: TextureBacking::RenderTarget {
398			runtime,
399			owner,
400			lease,
401			image,
402			view,
403			width,
404			height,
405		},
406		semantic: Rc::new(semantic),
407	}
408}
409
410/// Monotonic texture value identity counter.
411fn 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
422/// Read and save one packed RGBA8 Texture using its path extension.
423///
424/// Supported extensions are `.jpg`, `.jpeg`, `.png`, `.webp`, `.bmp`, and
425/// `.tga`. This is an explicit blocking readback and filesystem boundary.
426///
427/// # Errors
428///
429/// Returns an error for unsupported paths, failed device observation, codec
430/// failure, or filesystem failure.
431pub 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}