1use super::{
4 Arc, Color, ColorMap, Duration, Error, HeatmapUniform, Instant, MAX_PORTABLE_SHADER_VALUE,
5 RenderReport, RenderStatus, RenderTarget2d, RendererFrameError, RendererSurfaceStatus,
6 ScalarField, ScalarFieldSampling, TessellationStats, WgpuRenderer,
7 clone_scalar_field_for_restore, color_map_lut, compact_scalar_field_for_retention,
8 create_cached_color_map, create_scalar_field_texture, create_scalar_field_texture_resources,
9 fmt, is_portable_shader_source, premultiplied_wgpu_color, prepared_scene_belongs_to,
10 render_report, scalar_field_sources_are_portable, scalar_normalization_is_portable,
11 scalar_region_result_range, scalar_value_range_extent, upload_scalar_field_texture,
12 upload_scalar_field_texture_region, validate_scalar_field_device_extent,
13 validate_scalar_field_texture_region,
14};
15
16pub struct ScalarFieldTexture {
18 pub(super) renderer_identity: Arc<()>,
19 pub(super) texture: wgpu::Texture,
20 pub(super) field: ScalarField,
21 pub(super) source_minimum: f32,
22 pub(super) source_maximum: f32,
23}
24
25impl ScalarFieldTexture {
26 pub fn width(&self) -> usize {
28 self.field.width()
29 }
30
31 pub fn height(&self) -> usize {
33 self.field.height()
34 }
35
36 pub fn field(&self) -> &ScalarField {
38 &self.field
39 }
40
41 pub fn recovery_memory_bytes(&self) -> usize {
43 self.field.value_allocation_bytes()
44 }
45
46 pub fn gpu_allocation_bytes(&self) -> usize {
49 self.field
50 .values()
51 .len()
52 .saturating_mul(std::mem::size_of::<f32>())
53 }
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum ScalarFieldTextureError {
59 RendererMismatch,
61 DimensionsTooLarge,
63 UpdateRegionOutOfBounds,
65 InvalidUpdateValueCount,
67 NonFiniteUpdateValue,
69 NonPortableValue,
71 AllocationFailed {
73 requested_bytes: usize,
75 },
76}
77
78impl fmt::Display for ScalarFieldTextureError {
79 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
80 match self {
81 Self::RendererMismatch => write!(
82 formatter,
83 "scalar field texture belongs to a different renderer"
84 ),
85 Self::DimensionsTooLarge => write!(
86 formatter,
87 "scalar field dimensions exceed GPU texture limits"
88 ),
89 Self::UpdateRegionOutOfBounds => {
90 write!(formatter, "scalar texture update region is out of bounds")
91 }
92 Self::InvalidUpdateValueCount => {
93 write!(
94 formatter,
95 "scalar texture update values do not match the region"
96 )
97 }
98 Self::NonFiniteUpdateValue => {
99 write!(formatter, "scalar texture update values must be finite")
100 }
101 Self::NonPortableValue => write!(
102 formatter,
103 "scalar values must be normal-or-zero and remain inside the portable GPU arithmetic envelope"
104 ),
105 Self::AllocationFailed { requested_bytes } => write!(
106 formatter,
107 "could not reserve {requested_bytes} bytes for scalar field recovery data"
108 ),
109 }
110 }
111}
112
113impl Error for ScalarFieldTextureError {}
114
115#[derive(Debug, Clone, Copy, PartialEq)]
117pub enum ScalarFieldRenderError {
118 RendererMismatch,
120 InvalidValueRange {
122 minimum: f32,
124 maximum: f32,
126 },
127 InvalidBackground,
129 Frame(RendererFrameError),
131}
132
133impl fmt::Display for ScalarFieldRenderError {
134 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
135 match self {
136 Self::RendererMismatch => write!(
137 formatter,
138 "scalar field texture belongs to a different renderer"
139 ),
140 Self::InvalidValueRange { minimum, maximum } => {
141 write!(formatter, "invalid scalar value range {minimum}..{maximum}")
142 }
143 Self::InvalidBackground => {
144 write!(formatter, "scalar field background must be normalized")
145 }
146 Self::Frame(error) => write!(formatter, "scalar field frame failed: {error}"),
147 }
148 }
149}
150
151impl Error for ScalarFieldRenderError {}
152
153#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub struct ScalarFieldUploadReport {
156 upload: Duration,
157 reallocated: bool,
158}
159
160impl ScalarFieldUploadReport {
161 pub fn upload(self) -> Duration {
163 self.upload
164 }
165
166 pub fn reallocated(self) -> bool {
168 self.reallocated
169 }
170}
171
172impl WgpuRenderer {
173 pub fn create_scalar_field_texture(
175 &self,
176 field: ScalarField,
177 ) -> Result<ScalarFieldTexture, ScalarFieldTextureError> {
178 create_scalar_field_texture_resources(
179 &self.device,
180 &self.queue,
181 Arc::clone(&self.renderer_identity),
182 field,
183 )
184 }
185
186 pub fn update_scalar_field_texture(
188 &self,
189 texture: &mut ScalarFieldTexture,
190 field: ScalarField,
191 ) -> Result<ScalarFieldUploadReport, ScalarFieldTextureError> {
192 let upload_started_at = Instant::now();
193 self.validate_scalar_field_texture(texture)?;
194 validate_scalar_field_device_extent(&self.device, &field)?;
195 if !scalar_field_sources_are_portable(&field) {
196 return Err(ScalarFieldTextureError::NonPortableValue);
197 }
198 let field = compact_scalar_field_for_retention(field)?;
199 let (source_minimum, source_maximum) = field.value_range();
200 let reallocated = texture.width() != field.width() || texture.height() != field.height();
201 if reallocated {
202 texture.texture = create_scalar_field_texture(&self.device, &field)?;
203 }
204 upload_scalar_field_texture(&self.queue, &texture.texture, &field)?;
205 texture.field = field;
206 texture.source_minimum = source_minimum;
207 texture.source_maximum = source_maximum;
208 Ok(ScalarFieldUploadReport {
209 upload: upload_started_at.elapsed(),
210 reallocated,
211 })
212 }
213
214 pub fn update_scalar_field_texture_region(
216 &self,
217 texture: &mut ScalarFieldTexture,
218 x: usize,
219 y: usize,
220 width: usize,
221 height: usize,
222 values: &[f32],
223 ) -> Result<ScalarFieldUploadReport, ScalarFieldTextureError> {
224 let upload_started_at = Instant::now();
225 self.validate_scalar_field_texture(texture)?;
226 if values.iter().any(|value| !value.is_finite()) {
227 return Err(ScalarFieldTextureError::NonFiniteUpdateValue);
228 }
229 if values
230 .iter()
231 .copied()
232 .any(|value| !is_portable_shader_source(value))
233 {
234 return Err(ScalarFieldTextureError::NonPortableValue);
235 }
236 validate_scalar_field_texture_region(
237 texture.width(),
238 texture.height(),
239 x,
240 y,
241 width,
242 height,
243 values.len(),
244 )?;
245 let update_minimum = values.iter().copied().fold(f32::INFINITY, f32::min);
246 let update_maximum = values.iter().copied().fold(f32::NEG_INFINITY, f32::max);
247 let overwrites_extremum = (y..y + height).any(|row| {
248 let start = row * texture.width() + x;
249 texture.field.values()[start..start + width]
250 .iter()
251 .any(|value| *value == texture.source_minimum || *value == texture.source_maximum)
252 });
253 let (source_minimum, source_maximum) = if overwrites_extremum {
254 scalar_region_result_range(&texture.field, x, y, width, height, values)
255 } else {
256 (
257 texture.source_minimum.min(update_minimum),
258 texture.source_maximum.max(update_maximum),
259 )
260 };
261 let source_extent = f64::from(source_maximum) - f64::from(source_minimum);
262 if !source_extent.is_finite() || source_extent > f64::from(MAX_PORTABLE_SHADER_VALUE) {
263 return Err(ScalarFieldTextureError::NonPortableValue);
264 }
265 texture
266 .field
267 .replace_region(x, y, width, height, values)
268 .map_err(|error| match error {
269 crate::ScalarFieldError::InvalidValueCount { .. } => {
270 ScalarFieldTextureError::InvalidUpdateValueCount
271 }
272 crate::ScalarFieldError::NonFiniteValue => {
273 ScalarFieldTextureError::NonFiniteUpdateValue
274 }
275 _ => ScalarFieldTextureError::UpdateRegionOutOfBounds,
276 })?;
277 upload_scalar_field_texture_region(
278 &self.queue,
279 &texture.texture,
280 x,
281 y,
282 width,
283 height,
284 values,
285 )?;
286 texture.source_minimum = source_minimum;
287 texture.source_maximum = source_maximum;
288 Ok(ScalarFieldUploadReport {
289 upload: upload_started_at.elapsed(),
290 reallocated: false,
291 })
292 }
293
294 pub fn restore_scalar_field_texture(
296 &self,
297 source: &ScalarFieldTexture,
298 ) -> Result<ScalarFieldTexture, ScalarFieldTextureError> {
299 validate_scalar_field_device_extent(&self.device, &source.field)?;
300 let field = clone_scalar_field_for_restore(&source.field)?;
301 self.create_scalar_field_texture(field)
302 }
303
304 pub fn render_scalar_field_texture(
309 &mut self,
310 texture: &ScalarFieldTexture,
311 color_map: &ColorMap,
312 value_range: (f32, f32),
313 background: Color,
314 ) -> Result<RenderStatus, ScalarFieldRenderError> {
315 self.render_scalar_field_texture_with_metrics(texture, color_map, value_range, background)
316 .map(RenderReport::status)
317 }
318
319 pub fn render_scalar_field_texture_with_metrics(
321 &mut self,
322 texture: &ScalarFieldTexture,
323 color_map: &ColorMap,
324 (minimum, maximum): (f32, f32),
325 background: Color,
326 ) -> Result<RenderReport, ScalarFieldRenderError> {
327 self.validate_scalar_field_texture(texture)
328 .map_err(|_| ScalarFieldRenderError::RendererMismatch)?;
329 let value_extent = scalar_value_range_extent(minimum, maximum)
330 .ok_or(ScalarFieldRenderError::InvalidValueRange { minimum, maximum })?;
331 if !scalar_normalization_is_portable(texture, minimum, value_extent) {
332 return Err(ScalarFieldRenderError::InvalidValueRange { minimum, maximum });
333 }
334 if !background.is_normalized() {
335 return Err(ScalarFieldRenderError::InvalidBackground);
336 }
337 self.draw_scalar_field_texture(
338 texture,
339 color_map,
340 minimum,
341 value_extent,
342 ScalarFieldSampling::Nearest,
343 background,
344 Instant::now(),
345 )
346 .map_err(ScalarFieldRenderError::Frame)
347 }
348
349 pub fn render_scalar_field_texture_with_sampling(
351 &mut self,
352 texture: &ScalarFieldTexture,
353 color_map: &ColorMap,
354 (minimum, maximum): (f32, f32),
355 sampling: ScalarFieldSampling,
356 background: Color,
357 ) -> Result<RenderStatus, ScalarFieldRenderError> {
358 self.validate_scalar_field_texture(texture)
359 .map_err(|_| ScalarFieldRenderError::RendererMismatch)?;
360 let value_extent = scalar_value_range_extent(minimum, maximum)
361 .ok_or(ScalarFieldRenderError::InvalidValueRange { minimum, maximum })?;
362 if !scalar_normalization_is_portable(texture, minimum, value_extent) {
363 return Err(ScalarFieldRenderError::InvalidValueRange { minimum, maximum });
364 }
365 if !background.is_normalized() {
366 return Err(ScalarFieldRenderError::InvalidBackground);
367 }
368 self.draw_scalar_field_texture(
369 texture,
370 color_map,
371 minimum,
372 value_extent,
373 sampling,
374 background,
375 Instant::now(),
376 )
377 .map(RenderReport::status)
378 .map_err(ScalarFieldRenderError::Frame)
379 }
380
381 pub fn render_scalar_field_texture_to_target(
383 &mut self,
384 target: &RenderTarget2d,
385 texture: &ScalarFieldTexture,
386 color_map: &ColorMap,
387 value_range: (f32, f32),
388 background: Color,
389 ) -> Result<RenderReport, ScalarFieldRenderError> {
390 self.render_scalar_field_texture_to_target_with_sampling(
391 target,
392 texture,
393 color_map,
394 value_range,
395 ScalarFieldSampling::Nearest,
396 background,
397 )
398 }
399
400 pub fn render_scalar_field_texture_to_target_with_sampling(
402 &mut self,
403 target: &RenderTarget2d,
404 texture: &ScalarFieldTexture,
405 color_map: &ColorMap,
406 (minimum, maximum): (f32, f32),
407 sampling: ScalarFieldSampling,
408 background: Color,
409 ) -> Result<RenderReport, ScalarFieldRenderError> {
410 self.validate_render_target(target)
411 .map_err(|_| ScalarFieldRenderError::RendererMismatch)?;
412 self.validate_scalar_field_texture(texture)
413 .map_err(|_| ScalarFieldRenderError::RendererMismatch)?;
414 let value_extent = scalar_value_range_extent(minimum, maximum)
415 .ok_or(ScalarFieldRenderError::InvalidValueRange { minimum, maximum })?;
416 if !scalar_normalization_is_portable(texture, minimum, value_extent) {
417 return Err(ScalarFieldRenderError::InvalidValueRange { minimum, maximum });
418 }
419 if !background.is_normalized() {
420 return Err(ScalarFieldRenderError::InvalidBackground);
421 }
422 Ok(self.draw_scalar_field_texture_to_target(
423 target,
424 texture,
425 color_map,
426 minimum,
427 value_extent,
428 sampling,
429 background,
430 Instant::now(),
431 ))
432 }
433
434 #[allow(clippy::too_many_arguments)]
435 fn draw_scalar_field_texture(
436 &mut self,
437 texture: &ScalarFieldTexture,
438 color_map: &ColorMap,
439 minimum: f32,
440 value_extent: f32,
441 sampling: ScalarFieldSampling,
442 background: Color,
443 frame_started_at: Instant,
444 ) -> Result<RenderReport, RendererFrameError> {
445 let uniform = HeatmapUniform::new(
446 minimum,
447 value_extent,
448 texture.width(),
449 texture.height(),
450 sampling,
451 );
452 let acquire_started_at = Instant::now();
453 let surface_texture = match self.surface.get_current_texture() {
454 wgpu::CurrentSurfaceTexture::Success(texture)
455 | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
456 wgpu::CurrentSurfaceTexture::Timeout => {
457 return Ok(render_report(
458 RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
459 Duration::ZERO,
460 Duration::ZERO,
461 Duration::ZERO,
462 acquire_started_at.elapsed(),
463 Duration::ZERO,
464 frame_started_at.elapsed(),
465 false,
466 true,
467 TessellationStats::default(),
468 ));
469 }
470 wgpu::CurrentSurfaceTexture::Occluded => {
471 return Ok(render_report(
472 RenderStatus::Skipped(RendererSurfaceStatus::Occluded),
473 Duration::ZERO,
474 Duration::ZERO,
475 Duration::ZERO,
476 acquire_started_at.elapsed(),
477 Duration::ZERO,
478 frame_started_at.elapsed(),
479 false,
480 true,
481 TessellationStats::default(),
482 ));
483 }
484 wgpu::CurrentSurfaceTexture::Outdated => {
485 let _ = self.resize(self.config.width, self.config.height);
486 return Ok(render_report(
487 RenderStatus::Skipped(RendererSurfaceStatus::Outdated),
488 Duration::ZERO,
489 Duration::ZERO,
490 Duration::ZERO,
491 acquire_started_at.elapsed(),
492 Duration::ZERO,
493 frame_started_at.elapsed(),
494 false,
495 true,
496 TessellationStats::default(),
497 ));
498 }
499 wgpu::CurrentSurfaceTexture::Lost => {
500 return Err(RendererFrameError::Surface(RendererSurfaceStatus::Lost));
501 }
502 wgpu::CurrentSurfaceTexture::Validation => {
503 return Err(RendererFrameError::Surface(
504 RendererSurfaceStatus::Validation,
505 ));
506 }
507 };
508 let surface_acquire = acquire_started_at.elapsed();
509 let upload_started_at = Instant::now();
510 let color_map_view = self.color_map_view(color_map);
511 let scalar_view = texture
512 .texture
513 .create_view(&wgpu::TextureViewDescriptor::default());
514 self.queue.write_buffer(
515 &self.heatmap_uniform_buffer,
516 0,
517 bytemuck::bytes_of(&uniform),
518 );
519 let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
520 label: Some("sim-engine heatmap bind group"),
521 layout: &self.heatmap_bind_group_layout,
522 entries: &[
523 wgpu::BindGroupEntry {
524 binding: 0,
525 resource: wgpu::BindingResource::TextureView(&scalar_view),
526 },
527 wgpu::BindGroupEntry {
528 binding: 1,
529 resource: wgpu::BindingResource::TextureView(&color_map_view),
530 },
531 wgpu::BindGroupEntry {
532 binding: 2,
533 resource: self.heatmap_uniform_buffer.as_entire_binding(),
534 },
535 ],
536 });
537 let upload = upload_started_at.elapsed();
538 let encode_started_at = Instant::now();
539 let surface_view = surface_texture
540 .texture
541 .create_view(&wgpu::TextureViewDescriptor::default());
542 let (view, resolve_target) = match &self.multisample_target {
543 Some(target) => (&target.view, Some(&surface_view)),
544 None => (&surface_view, None),
545 };
546 let mut encoder = self
547 .device
548 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
549 label: Some("sim-engine heatmap encoder"),
550 });
551 {
552 let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
553 label: Some("sim-engine heatmap pass"),
554 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
555 view,
556 depth_slice: None,
557 resolve_target,
558 ops: wgpu::Operations {
559 load: wgpu::LoadOp::Clear(background.to_wgpu()),
560 store: wgpu::StoreOp::Store,
561 },
562 })],
563 depth_stencil_attachment: None,
564 timestamp_writes: None,
565 occlusion_query_set: None,
566 multiview_mask: None,
567 });
568 pass.set_pipeline(&self.heatmap_pipeline);
569 pass.set_bind_group(0, &bind_group, &[]);
570 pass.draw(0..6, 0..1);
571 }
572 self.queue.submit([encoder.finish()]);
573 self.notify_before_present();
574 self.queue.present(surface_texture);
575 Ok(render_report(
576 RenderStatus::Drawn,
577 Duration::ZERO,
578 upload,
579 Duration::ZERO,
580 surface_acquire,
581 encode_started_at.elapsed(),
582 frame_started_at.elapsed(),
583 false,
584 true,
585 TessellationStats::default(),
586 ))
587 }
588
589 #[allow(clippy::too_many_arguments)]
590 fn draw_scalar_field_texture_to_target(
591 &mut self,
592 target: &RenderTarget2d,
593 texture: &ScalarFieldTexture,
594 color_map: &ColorMap,
595 minimum: f32,
596 value_extent: f32,
597 sampling: ScalarFieldSampling,
598 background: Color,
599 frame_started_at: Instant,
600 ) -> RenderReport {
601 let upload_started_at = Instant::now();
602 let color_map_view = self.color_map_view(color_map);
603 let scalar_view = texture
604 .texture
605 .create_view(&wgpu::TextureViewDescriptor::default());
606 self.queue.write_buffer(
607 &self.heatmap_uniform_buffer,
608 0,
609 bytemuck::bytes_of(&HeatmapUniform::new(
610 minimum,
611 value_extent,
612 texture.width(),
613 texture.height(),
614 sampling,
615 )),
616 );
617 let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
618 label: Some("sim-engine target heatmap bind group"),
619 layout: &self.heatmap_bind_group_layout,
620 entries: &[
621 wgpu::BindGroupEntry {
622 binding: 0,
623 resource: wgpu::BindingResource::TextureView(&scalar_view),
624 },
625 wgpu::BindGroupEntry {
626 binding: 1,
627 resource: wgpu::BindingResource::TextureView(&color_map_view),
628 },
629 wgpu::BindGroupEntry {
630 binding: 2,
631 resource: self.heatmap_uniform_buffer.as_entire_binding(),
632 },
633 ],
634 });
635 let upload = upload_started_at.elapsed();
636 let encode_started_at = Instant::now();
637 let mut encoder = self
638 .device
639 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
640 label: Some("sim-engine render-target heatmap encoder"),
641 });
642 {
643 let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
644 label: Some("sim-engine render-target heatmap pass"),
645 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
646 view: &target.view,
647 depth_slice: None,
648 resolve_target: None,
649 ops: wgpu::Operations {
650 load: wgpu::LoadOp::Clear(premultiplied_wgpu_color(background)),
651 store: wgpu::StoreOp::Store,
652 },
653 })],
654 depth_stencil_attachment: None,
655 timestamp_writes: None,
656 occlusion_query_set: None,
657 multiview_mask: None,
658 });
659 pass.set_pipeline(&self.target_heatmap_pipeline);
660 pass.set_bind_group(0, &bind_group, &[]);
661 pass.draw(0..6, 0..1);
662 }
663 self.queue.submit([encoder.finish()]);
664 render_report(
665 RenderStatus::Drawn,
666 Duration::ZERO,
667 upload,
668 Duration::ZERO,
669 Duration::ZERO,
670 encode_started_at.elapsed(),
671 frame_started_at.elapsed(),
672 false,
673 true,
674 TessellationStats::default(),
675 )
676 }
677
678 pub(super) fn validate_scalar_field_texture(
679 &self,
680 texture: &ScalarFieldTexture,
681 ) -> Result<(), ScalarFieldTextureError> {
682 prepared_scene_belongs_to(&self.renderer_identity, &texture.renderer_identity)
683 .then_some(())
684 .ok_or(ScalarFieldTextureError::RendererMismatch)
685 }
686
687 pub(super) fn color_map_view(&mut self, color_map: &ColorMap) -> wgpu::TextureView {
688 let lut = color_map_lut(color_map);
689 if let Some(cached) = self
690 .color_map_cache
691 .as_ref()
692 .filter(|cached| cached.lut == lut)
693 {
694 return cached.view.clone();
695 }
696 let cached = create_cached_color_map(&self.device, &self.queue, lut);
697 let view = cached.view.clone();
698 self.color_map_cache = Some(cached);
699 view
700 }
701}