Skip to main content

oa/image/
geometric.gen.rs

1// @generated by tool/gen/fn/generate.py; DO NOT EDIT.
2// schema=image.json schema_version=1 generator_version=64
3// schema_sha256=4c3af0f4b2504702bcaaa32134afcbd07ca92d06660d4847a5eeb5a0691dde61
4//! Stateless geometric image transformations.
5
6use crate::{
7	DType, Error, Image, ImageLayout, Matrix, OpAttribute, Result,
8	runtime::{
9		BufferBinding, ComputeDispatch, ImageSemanticDispatch, ImageSemanticInput, ImageSemanticOutput,
10		KernelId, PushConstant,
11	},
12};
13
14/// Sampling rule used by [`resize`].
15#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
16pub enum InterpolationMode {
17	/// Select the source pixel containing the scaled output coordinate.
18	Nearest,
19	/// Use half-pixel-center bilinear sampling with `align_corners = false`.
20	#[default]
21	Bilinear,
22}
23
24impl InterpolationMode {
25	pub(super) const fn token(self) -> &'static str {
26		match self {
27			Self::Nearest => "nearest",
28			Self::Bilinear => "bilinear",
29		}
30	}
31
32	const fn kernel(self) -> KernelId {
33		match self {
34			Self::Nearest => KernelId::ImageResizeNearestF32,
35			Self::Bilinear => KernelId::ImageResizeBilinearF32,
36		}
37	}
38
39	pub(super) const fn code(self) -> u32 {
40		match self {
41			Self::Nearest => 0,
42			Self::Bilinear => 1,
43		}
44	}
45}
46
47/// Sampling behavior for coordinates outside an image.
48#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
49pub enum BorderMode {
50	/// Return the caller-provided constant value.
51	#[default]
52	Constant,
53	/// Extend the nearest edge pixel.
54	Replicate,
55	/// Reflect coordinates while repeating the edge pixel.
56	Reflect,
57	/// Reflect coordinates without repeating the edge pixel.
58	Reflect101,
59	/// Wrap coordinates periodically.
60	Wrap,
61}
62
63impl BorderMode {
64	pub(super) const fn token(self) -> &'static str {
65		match self {
66			Self::Constant => "constant",
67			Self::Replicate => "replicate",
68			Self::Reflect => "reflect",
69			Self::Reflect101 => "reflect_101",
70			Self::Wrap => "wrap",
71		}
72	}
73
74	pub(super) const fn code(self) -> u32 {
75		match self {
76			Self::Constant => 0,
77			Self::Replicate => 1,
78			Self::Reflect => 2,
79			Self::Reflect101 => 3,
80			Self::Wrap => 4,
81		}
82	}
83}
84
85#[derive(Clone, Copy)]
86struct ImageExtent {
87	batch: u32,
88	channels: u32,
89	height: u32,
90	width: u32,
91}
92
93/// Resize an FP32 channel-first image while preserving its layout and format.
94///
95/// NCHW and CHW storage are supported. Nearest sampling follows the donor OA
96/// floor-coordinate rule. Bilinear sampling uses half-pixel centers with
97/// `align_corners = false`.
98///
99/// The call records work asynchronously and returns an Image immediately.
100/// Reading its backing matrix is an explicit submission and observation point.
101///
102/// # Errors
103///
104/// Returns an error for a zero target extent, an empty source extent, a dtype or
105/// layout outside the admitted checkpoint, checked-size overflow, or a runtime
106/// recording failure.
107pub fn resize(
108	input: &Image,
109	target_width: u32,
110	target_height: u32,
111	interpolation: InterpolationMode,
112) -> Result<Image> {
113	if target_width == 0 || target_height == 0 {
114		return Err(Error::invalid_argument(
115			"image::resize target width and height must be non-zero",
116		));
117	}
118	if input.dtype() != DType::F32 {
119		return Err(Error::invalid_argument(format!(
120			"image::resize requires f32 storage; received {}",
121			input.dtype().token()
122		)));
123	}
124	if !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw) {
125		return Err(Error::invalid_argument(format!(
126			"image::resize currently supports Nchw and Chw layouts; received {:?}",
127			input.layout()
128		)));
129	}
130	if input.batch_size() == 0 || input.width() == 0 || input.height() == 0 {
131		return Err(Error::invalid_argument(
132			"image::resize source batch, width, and height must be non-zero",
133		));
134	}
135
136	let batch = u32_extent(input.batch_size(), "image::resize batch")?;
137	let channels = u32_extent(input.channels(), "image::resize channels")?;
138	let input_height = u32_extent(input.height(), "image::resize input height")?;
139	let input_width = u32_extent(input.width(), "image::resize input width")?;
140	u32_extent(
141		input.as_matrix().num_elements(),
142		"image::resize input element count",
143	)?;
144	let batch_channels = batch
145		.checked_mul(channels)
146		.ok_or_else(|| Error::out_of_range("image::resize batch-channel dispatch exceeds u32"))?;
147	let target_width_usize = usize::try_from(target_width)
148		.map_err(|_| Error::out_of_range("image::resize target width exceeds usize"))?;
149	let target_height_usize = usize::try_from(target_height)
150		.map_err(|_| Error::out_of_range("image::resize target height exceeds usize"))?;
151	let output_shape = match input.layout() {
152		ImageLayout::Nchw => vec![
153			input.batch_size(),
154			input.channels(),
155			target_height_usize,
156			target_width_usize,
157		],
158		ImageLayout::Chw => vec![input.channels(), target_height_usize, target_width_usize],
159		_ => unreachable!("unsupported layouts returned above"),
160	};
161	let output_elements = output_shape
162		.iter()
163		.copied()
164		.try_fold(1_usize, |count, extent| {
165			count
166				.checked_mul(extent)
167				.ok_or_else(|| Error::out_of_range("image::resize output element count exceeds usize"))
168		})?;
169	u32_extent(output_elements, "image::resize output element count")?;
170	let output_matrix = Matrix::allocate(
171		input.engine_handle(),
172		output_shape,
173		output_elements,
174		DType::F32,
175	)?;
176	let output = Image::new(output_matrix, input.layout(), input.format())?;
177	let kernel = interpolation.kernel();
178	let buffers = [
179		BufferBinding::read(input.storage()),
180		BufferBinding::write(output.storage()),
181	];
182	let push_constants = [
183		PushConstant::U32(batch),
184		PushConstant::U32(channels),
185		PushConstant::U32(input_height),
186		PushConstant::U32(input_width),
187		PushConstant::U32(target_height),
188		PushConstant::U32(target_width),
189	];
190	let mut workgroups = kernel.output_workgroups(target_width, target_height);
191	workgroups[2] = batch_channels;
192	let attributes = [
193		OpAttribute::UnsignedInteger {
194			name: "target_width".into(),
195			value: u64::from(target_width),
196		},
197		OpAttribute::UnsignedInteger {
198			name: "target_height".into(),
199			value: u64::from(target_height),
200		},
201		OpAttribute::Enum {
202			name: "interpolation".into(),
203			value: interpolation.token().into(),
204		},
205	];
206	input.engine_handle().record_image_semantic(
207		ComputeDispatch {
208			kernel,
209			buffers: &buffers,
210			push_constants: &push_constants,
211			workgroups,
212			indirect: None,
213		},
214		ImageSemanticDispatch {
215			contract: crate::core::operation::image::RESIZE,
216			inputs: &[ImageSemanticInput::Image(input)],
217			outputs: &[ImageSemanticOutput::Image(&output)],
218			attributes: &attributes,
219		},
220	)?;
221	Ok(output)
222}
223
224/// Extract a region, clipping its right and bottom edges to the source extent.
225pub fn crop(input: &Image, x: u32, y: u32, width: u32, height: u32) -> Result<Image> {
226	let extent = validate_image(input, "image::crop")?;
227	if width == 0 || height == 0 || x >= extent.width || y >= extent.height {
228		return Err(Error::invalid_argument(
229			"image::crop requires a nonzero region whose origin is inside the image",
230		));
231	}
232	let output_width = width.min(extent.width - x);
233	let output_height = height.min(extent.height - y);
234	let output = allocate_image(input, output_width, output_height, "image::crop")?;
235	let dispatch_width = u32_extent(output.width(), "image operation output width")?;
236	let dispatch_height = u32_extent(output.height(), "image operation output height")?;
237	let planes = u32_extent(
238		output
239			.batch_size()
240			.checked_mul(output.channels())
241			.ok_or_else(|| Error::out_of_range("image operation batch-channel dispatch exceeds usize"))?,
242		"image operation batch-channel dispatch",
243	)?;
244	let mut workgroups = KernelId::ImageCropF32.output_workgroups(dispatch_width, dispatch_height);
245	workgroups[2] = planes;
246	input.engine_handle().record_image_semantic(
247		ComputeDispatch {
248			kernel: KernelId::ImageCropF32,
249			buffers: &[
250				BufferBinding::read(input.storage()),
251				BufferBinding::write(output.storage()),
252			],
253			push_constants: &[
254				PushConstant::U32(extent.batch),
255				PushConstant::U32(extent.channels),
256				PushConstant::U32(extent.height),
257				PushConstant::U32(extent.width),
258				PushConstant::U32(x),
259				PushConstant::U32(y),
260				PushConstant::U32(output_height),
261				PushConstant::U32(output_width),
262			],
263			workgroups,
264			indirect: None,
265		},
266		ImageSemanticDispatch {
267			contract: crate::core::operation::image::CROP,
268			inputs: &[ImageSemanticInput::Image(input)],
269			outputs: &[ImageSemanticOutput::Image(&output)],
270			attributes: &[
271				unsigned("x", x),
272				unsigned("y", y),
273				unsigned("width", width),
274				unsigned("height", height),
275			],
276		},
277	)?;
278	Ok(output)
279}
280
281/// Flip an image horizontally, vertically, or along both axes.
282pub fn flip(input: &Image, horizontal: bool, vertical: bool) -> Result<Image> {
283	let extent = validate_image(input, "image::flip")?;
284	let output = allocate_image(input, extent.width, extent.height, "image::flip")?;
285	let dispatch_width = u32_extent(output.width(), "image operation output width")?;
286	let dispatch_height = u32_extent(output.height(), "image operation output height")?;
287	let planes = u32_extent(
288		output
289			.batch_size()
290			.checked_mul(output.channels())
291			.ok_or_else(|| Error::out_of_range("image operation batch-channel dispatch exceeds usize"))?,
292		"image operation batch-channel dispatch",
293	)?;
294	let mut workgroups = KernelId::ImageFlipF32.output_workgroups(dispatch_width, dispatch_height);
295	workgroups[2] = planes;
296	input.engine_handle().record_image_semantic(
297		ComputeDispatch {
298			kernel: KernelId::ImageFlipF32,
299			buffers: &[
300				BufferBinding::read(input.storage()),
301				BufferBinding::write(output.storage()),
302			],
303			push_constants: &[
304				PushConstant::U32(extent.batch),
305				PushConstant::U32(extent.channels),
306				PushConstant::U32(extent.height),
307				PushConstant::U32(extent.width),
308				PushConstant::U32(u32::from(horizontal)),
309				PushConstant::U32(u32::from(vertical)),
310			],
311			workgroups,
312			indirect: None,
313		},
314		ImageSemanticDispatch {
315			contract: crate::core::operation::image::FLIP,
316			inputs: &[ImageSemanticInput::Image(input)],
317			outputs: &[ImageSemanticOutput::Image(&output)],
318			attributes: &[
319				boolean("horizontal", horizontal),
320				boolean("vertical", vertical),
321			],
322		},
323	)?;
324	Ok(output)
325}
326
327/// Rotate clockwise by a multiple of 90 degrees.
328pub fn rotate(input: &Image, degrees: u32) -> Result<Image> {
329	let extent = validate_image(input, "image::rotate")?;
330	let normalized = degrees % 360;
331	if !matches!(normalized, 0 | 90 | 180 | 270) {
332		return Err(Error::invalid_argument(
333			"image::rotate degrees must be a multiple of 90",
334		));
335	}
336	let (output_width, output_height) = if matches!(normalized, 90 | 270) {
337		(extent.height, extent.width)
338	} else {
339		(extent.width, extent.height)
340	};
341	let output = allocate_image(input, output_width, output_height, "image::rotate")?;
342	let dispatch_width = u32_extent(output.width(), "image operation output width")?;
343	let dispatch_height = u32_extent(output.height(), "image operation output height")?;
344	let planes = u32_extent(
345		output
346			.batch_size()
347			.checked_mul(output.channels())
348			.ok_or_else(|| Error::out_of_range("image operation batch-channel dispatch exceeds usize"))?,
349		"image operation batch-channel dispatch",
350	)?;
351	let mut workgroups = KernelId::ImageRotateF32.output_workgroups(dispatch_width, dispatch_height);
352	workgroups[2] = planes;
353	input.engine_handle().record_image_semantic(
354		ComputeDispatch {
355			kernel: KernelId::ImageRotateF32,
356			buffers: &[
357				BufferBinding::read(input.storage()),
358				BufferBinding::write(output.storage()),
359			],
360			push_constants: &[
361				PushConstant::U32(extent.batch),
362				PushConstant::U32(extent.channels),
363				PushConstant::U32(extent.height),
364				PushConstant::U32(extent.width),
365				PushConstant::U32(output_height),
366				PushConstant::U32(output_width),
367				PushConstant::U32(normalized),
368			],
369			workgroups,
370			indirect: None,
371		},
372		ImageSemanticDispatch {
373			contract: crate::core::operation::image::ROTATE,
374			inputs: &[ImageSemanticInput::Image(input)],
375			outputs: &[ImageSemanticOutput::Image(&output)],
376			attributes: &[unsigned("degrees", degrees)],
377		},
378	)?;
379	Ok(output)
380}
381
382/// Add asymmetric padding with an explicit border policy.
383#[allow(clippy::too_many_arguments)]
384pub fn pad(
385	input: &Image,
386	left: u32,
387	right: u32,
388	top: u32,
389	bottom: u32,
390	border: BorderMode,
391	border_value: f32,
392) -> Result<Image> {
393	let extent = validate_image(input, "image::pad")?;
394	if !border_value.is_finite() {
395		return Err(Error::invalid_argument(
396			"image::pad border value must be finite",
397		));
398	}
399	let output_width = extent
400		.width
401		.checked_add(left)
402		.and_then(|value| value.checked_add(right))
403		.ok_or_else(|| Error::out_of_range("image::pad output width exceeds u32"))?;
404	let output_height = extent
405		.height
406		.checked_add(top)
407		.and_then(|value| value.checked_add(bottom))
408		.ok_or_else(|| Error::out_of_range("image::pad output height exceeds u32"))?;
409	let output = allocate_image(input, output_width, output_height, "image::pad")?;
410	let dispatch_width = u32_extent(output.width(), "image operation output width")?;
411	let dispatch_height = u32_extent(output.height(), "image operation output height")?;
412	let planes = u32_extent(
413		output
414			.batch_size()
415			.checked_mul(output.channels())
416			.ok_or_else(|| Error::out_of_range("image operation batch-channel dispatch exceeds usize"))?,
417		"image operation batch-channel dispatch",
418	)?;
419	let mut workgroups = KernelId::ImagePadF32.output_workgroups(dispatch_width, dispatch_height);
420	workgroups[2] = planes;
421	input.engine_handle().record_image_semantic(
422		ComputeDispatch {
423			kernel: KernelId::ImagePadF32,
424			buffers: &[
425				BufferBinding::read(input.storage()),
426				BufferBinding::write(output.storage()),
427			],
428			push_constants: &[
429				PushConstant::U32(extent.batch),
430				PushConstant::U32(extent.channels),
431				PushConstant::U32(extent.height),
432				PushConstant::U32(extent.width),
433				PushConstant::U32(output_height),
434				PushConstant::U32(output_width),
435				PushConstant::U32(top),
436				PushConstant::U32(left),
437				PushConstant::U32(border.code()),
438				PushConstant::F32(border_value),
439			],
440			workgroups,
441			indirect: None,
442		},
443		ImageSemanticDispatch {
444			contract: crate::core::operation::image::PAD,
445			inputs: &[ImageSemanticInput::Image(input)],
446			outputs: &[ImageSemanticOutput::Image(&output)],
447			attributes: &[
448				unsigned("left", left),
449				unsigned("right", right),
450				unsigned("top", top),
451				unsigned("bottom", bottom),
452				enumeration("border", border.token()),
453				float("border_value", border_value),
454			],
455		},
456	)?;
457	Ok(output)
458}
459
460/// Extract a centered region with the requested exact extent.
461pub fn center_crop(input: &Image, width: u32, height: u32) -> Result<Image> {
462	let extent = validate_image(input, "image::center_crop")?;
463	if width == 0 || height == 0 || width > extent.width || height > extent.height {
464		return Err(Error::invalid_argument(
465			"image::center_crop extent must be nonzero and fit inside the image",
466		));
467	}
468	let x = (extent.width - width) / 2;
469	let y = (extent.height - height) / 2;
470	let output = allocate_image(input, width, height, "image::center_crop")?;
471	let dispatch_width = u32_extent(output.width(), "image operation output width")?;
472	let dispatch_height = u32_extent(output.height(), "image operation output height")?;
473	let planes = u32_extent(
474		output
475			.batch_size()
476			.checked_mul(output.channels())
477			.ok_or_else(|| Error::out_of_range("image operation batch-channel dispatch exceeds usize"))?,
478		"image operation batch-channel dispatch",
479	)?;
480	let mut workgroups =
481		KernelId::ImageCenterCropF32.output_workgroups(dispatch_width, dispatch_height);
482	workgroups[2] = planes;
483	input.engine_handle().record_image_semantic(
484		ComputeDispatch {
485			kernel: KernelId::ImageCenterCropF32,
486			buffers: &[
487				BufferBinding::read(input.storage()),
488				BufferBinding::write(output.storage()),
489			],
490			push_constants: &[
491				PushConstant::U32(extent.batch),
492				PushConstant::U32(extent.channels),
493				PushConstant::U32(extent.height),
494				PushConstant::U32(extent.width),
495				PushConstant::U32(x),
496				PushConstant::U32(y),
497				PushConstant::U32(height),
498				PushConstant::U32(width),
499			],
500			workgroups,
501			indirect: None,
502		},
503		ImageSemanticDispatch {
504			contract: crate::core::operation::image::CENTER_CROP,
505			inputs: &[ImageSemanticInput::Image(input)],
506			outputs: &[ImageSemanticOutput::Image(&output)],
507			attributes: &[unsigned("width", width), unsigned("height", height)],
508		},
509	)?;
510	Ok(output)
511}
512
513/// Resample an image from an FP32 absolute-coordinate map shaped
514/// `[1|batch, 2, output_height, output_width]`.
515pub fn remap(
516	input: &Image,
517	map: &Matrix,
518	interpolation: InterpolationMode,
519	border: BorderMode,
520	border_value: f32,
521) -> Result<Image> {
522	let extent = validate_warp_inputs(input, map, "image::remap", border_value)?;
523	if map.shape().len() != 4
524		|| map.shape()[1] != 2
525		|| map.shape()[2] == 0
526		|| map.shape()[3] == 0
527		|| !matches!(map.shape()[0], 1) && map.shape()[0] != input.batch_size()
528	{
529		return Err(Error::invalid_argument(
530			"image::remap map must have shape [1|batch, 2, output_height, output_width]",
531		));
532	}
533	let map_batch = u32_extent(map.shape()[0], "image::remap map batch")?;
534	let output_height = u32_extent(map.shape()[2], "image::remap output height")?;
535	let output_width = u32_extent(map.shape()[3], "image::remap output width")?;
536	let output = allocate_image(input, output_width, output_height, "image::remap")?;
537	let dispatch_width = u32_extent(output.width(), "image operation output width")?;
538	let dispatch_height = u32_extent(output.height(), "image operation output height")?;
539	let planes = u32_extent(
540		output
541			.batch_size()
542			.checked_mul(output.channels())
543			.ok_or_else(|| Error::out_of_range("image operation batch-channel dispatch exceeds usize"))?,
544		"image operation batch-channel dispatch",
545	)?;
546	let mut workgroups = KernelId::ImageRemapF32.output_workgroups(dispatch_width, dispatch_height);
547	workgroups[2] = planes;
548	input.engine_handle().record_image_semantic(
549		ComputeDispatch {
550			kernel: KernelId::ImageRemapF32,
551			buffers: &[
552				BufferBinding::read(input.storage()),
553				BufferBinding::read(map.storage()),
554				BufferBinding::write(output.storage()),
555			],
556			push_constants: &[
557				PushConstant::U32(extent.batch),
558				PushConstant::U32(extent.channels),
559				PushConstant::U32(extent.height),
560				PushConstant::U32(extent.width),
561				PushConstant::U32(output_height),
562				PushConstant::U32(output_width),
563				PushConstant::U32(interpolation.code()),
564				PushConstant::U32(border.code()),
565				PushConstant::U32(map_batch),
566				PushConstant::F32(border_value),
567			],
568			workgroups,
569			indirect: None,
570		},
571		ImageSemanticDispatch {
572			contract: crate::core::operation::image::REMAP,
573			inputs: &[
574				ImageSemanticInput::Image(input),
575				ImageSemanticInput::Matrix(map),
576			],
577			outputs: &[ImageSemanticOutput::Image(&output)],
578			attributes: &[
579				enumeration("interpolation", interpolation.token()),
580				enumeration("border", border.token()),
581				float("border_value", border_value),
582			],
583		},
584	)?;
585	Ok(output)
586}
587
588/// Apply an inverse FP32 2x3 affine transform to an image.
589#[allow(clippy::too_many_arguments)]
590pub fn warp_affine(
591	input: &Image,
592	transform: &Matrix,
593	width: u32,
594	height: u32,
595	interpolation: InterpolationMode,
596	border: BorderMode,
597	border_value: f32,
598) -> Result<Image> {
599	if transform.shape() != [2, 3] {
600		return Err(Error::invalid_argument(
601			"image::warp_affine transform must have shape [2, 3]",
602		));
603	}
604	if width == 0 || height == 0 {
605		return Err(Error::invalid_argument(
606			"image::warp_affine output width and height must be nonzero",
607		));
608	}
609	let extent = validate_warp_inputs(input, transform, "image::warp_affine", border_value)?;
610	let output = allocate_image(input, width, height, "image::warp_affine")?;
611	let dispatch_width = u32_extent(output.width(), "image operation output width")?;
612	let dispatch_height = u32_extent(output.height(), "image operation output height")?;
613	let planes = u32_extent(
614		output
615			.batch_size()
616			.checked_mul(output.channels())
617			.ok_or_else(|| Error::out_of_range("image operation batch-channel dispatch exceeds usize"))?,
618		"image operation batch-channel dispatch",
619	)?;
620	let mut workgroups =
621		KernelId::ImageWarpAffineF32.output_workgroups(dispatch_width, dispatch_height);
622	workgroups[2] = planes;
623	input.engine_handle().record_image_semantic(
624		ComputeDispatch {
625			kernel: KernelId::ImageWarpAffineF32,
626			buffers: &[
627				BufferBinding::read(input.storage()),
628				BufferBinding::read(transform.storage()),
629				BufferBinding::write(output.storage()),
630			],
631			push_constants: &[
632				PushConstant::U32(extent.batch),
633				PushConstant::U32(extent.channels),
634				PushConstant::U32(extent.height),
635				PushConstant::U32(extent.width),
636				PushConstant::U32(height),
637				PushConstant::U32(width),
638				PushConstant::U32(interpolation.code()),
639				PushConstant::U32(border.code()),
640				PushConstant::F32(border_value),
641			],
642			workgroups,
643			indirect: None,
644		},
645		ImageSemanticDispatch {
646			contract: crate::core::operation::image::WARP_AFFINE,
647			inputs: &[
648				ImageSemanticInput::Image(input),
649				ImageSemanticInput::Matrix(transform),
650			],
651			outputs: &[ImageSemanticOutput::Image(&output)],
652			attributes: &[
653				unsigned("width", width),
654				unsigned("height", height),
655				enumeration("interpolation", interpolation.token()),
656				enumeration("border", border.token()),
657				float("border_value", border_value),
658			],
659		},
660	)?;
661	Ok(output)
662}
663
664/// Apply an inverse FP32 3x3 perspective transform to an image.
665#[allow(clippy::too_many_arguments)]
666pub fn warp_perspective(
667	input: &Image,
668	transform: &Matrix,
669	width: u32,
670	height: u32,
671	interpolation: InterpolationMode,
672	border: BorderMode,
673	border_value: f32,
674) -> Result<Image> {
675	if transform.shape() != [3, 3] {
676		return Err(Error::invalid_argument(
677			"image::warp_perspective transform must have shape [3, 3]",
678		));
679	}
680	if width == 0 || height == 0 {
681		return Err(Error::invalid_argument(
682			"image::warp_perspective output width and height must be nonzero",
683		));
684	}
685	let extent = validate_warp_inputs(input, transform, "image::warp_perspective", border_value)?;
686	let output = allocate_image(input, width, height, "image::warp_perspective")?;
687	let dispatch_width = u32_extent(output.width(), "image operation output width")?;
688	let dispatch_height = u32_extent(output.height(), "image operation output height")?;
689	let planes = u32_extent(
690		output
691			.batch_size()
692			.checked_mul(output.channels())
693			.ok_or_else(|| Error::out_of_range("image operation batch-channel dispatch exceeds usize"))?,
694		"image operation batch-channel dispatch",
695	)?;
696	let mut workgroups =
697		KernelId::ImageWarpPerspectiveF32.output_workgroups(dispatch_width, dispatch_height);
698	workgroups[2] = planes;
699	input.engine_handle().record_image_semantic(
700		ComputeDispatch {
701			kernel: KernelId::ImageWarpPerspectiveF32,
702			buffers: &[
703				BufferBinding::read(input.storage()),
704				BufferBinding::read(transform.storage()),
705				BufferBinding::write(output.storage()),
706			],
707			push_constants: &[
708				PushConstant::U32(extent.batch),
709				PushConstant::U32(extent.channels),
710				PushConstant::U32(extent.height),
711				PushConstant::U32(extent.width),
712				PushConstant::U32(height),
713				PushConstant::U32(width),
714				PushConstant::U32(interpolation.code()),
715				PushConstant::U32(border.code()),
716				PushConstant::F32(border_value),
717			],
718			workgroups,
719			indirect: None,
720		},
721		ImageSemanticDispatch {
722			contract: crate::core::operation::image::WARP_PERSPECTIVE,
723			inputs: &[
724				ImageSemanticInput::Image(input),
725				ImageSemanticInput::Matrix(transform),
726			],
727			outputs: &[ImageSemanticOutput::Image(&output)],
728			attributes: &[
729				unsigned("width", width),
730				unsigned("height", height),
731				enumeration("interpolation", interpolation.token()),
732				enumeration("border", border.token()),
733				float("border_value", border_value),
734			],
735		},
736	)?;
737	Ok(output)
738}
739
740fn validate_image(input: &Image, operation: &str) -> Result<ImageExtent> {
741	if input.dtype() != DType::F32 {
742		return Err(Error::invalid_argument(format!(
743			"{operation} requires f32 storage; received {}",
744			input.dtype().token()
745		)));
746	}
747	if !matches!(input.layout(), ImageLayout::Nchw | ImageLayout::Chw) {
748		return Err(Error::invalid_argument(format!(
749			"{operation} supports Nchw and Chw layouts; received {:?}",
750			input.layout()
751		)));
752	}
753	if input.batch_size() == 0 || input.channels() == 0 || input.height() == 0 || input.width() == 0 {
754		return Err(Error::invalid_argument(format!(
755			"{operation} requires a nonempty image"
756		)));
757	}
758	Ok(ImageExtent {
759		batch: u32_extent(input.batch_size(), &format!("{operation} batch"))?,
760		channels: u32_extent(input.channels(), &format!("{operation} channels"))?,
761		height: u32_extent(input.height(), &format!("{operation} height"))?,
762		width: u32_extent(input.width(), &format!("{operation} width"))?,
763	})
764}
765
766fn validate_warp_inputs(
767	input: &Image,
768	coordinates: &Matrix,
769	operation: &str,
770	border_value: f32,
771) -> Result<ImageExtent> {
772	let extent = validate_image(input, operation)?;
773	if coordinates.dtype() != DType::F32 {
774		return Err(Error::invalid_argument(format!(
775			"{operation} coordinates must use f32 storage"
776		)));
777	}
778	if !input.engine_handle().same_as(coordinates.engine_handle()) {
779		return Err(Error::invalid_argument(format!(
780			"{operation} inputs must belong to the same engine"
781		)));
782	}
783	if !border_value.is_finite() {
784		return Err(Error::invalid_argument(format!(
785			"{operation} border value must be finite"
786		)));
787	}
788	u32_extent(
789		coordinates.num_elements(),
790		&format!("{operation} coordinate element count"),
791	)?;
792	Ok(extent)
793}
794
795fn allocate_image(input: &Image, width: u32, height: u32, operation: &str) -> Result<Image> {
796	let width = usize::try_from(width)
797		.map_err(|_| Error::out_of_range(format!("{operation} width exceeds usize")))?;
798	let height = usize::try_from(height)
799		.map_err(|_| Error::out_of_range(format!("{operation} height exceeds usize")))?;
800	let shape = match input.layout() {
801		ImageLayout::Nchw => vec![input.batch_size(), input.channels(), height, width],
802		ImageLayout::Chw => vec![input.channels(), height, width],
803		_ => unreachable!("layout was validated before allocation"),
804	};
805	let elements = shape.iter().copied().try_fold(1_usize, |count, extent| {
806		count
807			.checked_mul(extent)
808			.ok_or_else(|| Error::out_of_range(format!("{operation} output size exceeds usize")))
809	})?;
810	u32_extent(elements, &format!("{operation} output element count"))?;
811	let matrix = Matrix::allocate(input.engine_handle(), shape, elements, DType::F32)?;
812	Image::new(matrix, input.layout(), input.format())
813}
814
815fn unsigned(name: &str, value: u32) -> OpAttribute {
816	OpAttribute::UnsignedInteger {
817		name: name.into(),
818		value: u64::from(value),
819	}
820}
821
822fn boolean(name: &str, value: bool) -> OpAttribute {
823	OpAttribute::Boolean {
824		name: name.into(),
825		value,
826	}
827}
828
829fn enumeration(name: &str, value: &str) -> OpAttribute {
830	OpAttribute::Enum {
831		name: name.into(),
832		value: value.into(),
833	}
834}
835
836fn float(name: &str, value: f32) -> OpAttribute {
837	OpAttribute::Float {
838		name: name.into(),
839		value: f64::from(value),
840	}
841}
842
843fn u32_extent(value: usize, label: &str) -> Result<u32> {
844	u32::try_from(value).map_err(|_| Error::out_of_range(format!("{label} exceeds u32")))
845}