scirs2_metrics/visualization/advanced_interactive/
rendering.rs

1//! Rendering engine for interactive visualization
2//!
3//! This module provides WebGL-accelerated rendering capabilities for
4//! high-performance interactive dashboards.
5
6#![allow(clippy::too_many_arguments)]
7#![allow(dead_code)]
8
9use super::widgets::{RenderContext, ShaderProgram, UniformValue, WidgetRender};
10use crate::error::{MetricsError, Result};
11use serde::{Deserialize, Serialize};
12use std::collections::HashMap;
13
14/// Rendering engine trait
15pub trait RenderingEngine: std::fmt::Debug + Send + Sync {
16    /// Initialize rendering engine
17    fn initialize(&mut self, config: RenderingConfig) -> Result<()>;
18
19    /// Render widget
20    fn render_widget(&self, widget_render: &WidgetRender, context: &RenderContext) -> Result<()>;
21
22    /// Clear render target
23    fn clear(&self, color: [f32; 4]) -> Result<()>;
24
25    /// Present rendered frame
26    fn present(&self) -> Result<()>;
27
28    /// Get rendering capabilities
29    fn capabilities(&self) -> RenderingCapabilities;
30
31    /// Create shader program
32    fn create_shader(&self, program: &ShaderProgram) -> Result<String>;
33
34    /// Update uniform values
35    fn update_uniforms(
36        &self,
37        shader_id: &str,
38        uniforms: &HashMap<String, UniformValue>,
39    ) -> Result<()>;
40
41    /// Set viewport
42    fn set_viewport(&self, x: u32, y: u32, width: u32, height: u32) -> Result<()>;
43}
44
45/// Rendering configuration
46#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct RenderingConfig {
48    /// Backend type
49    pub backend: RenderingBackend,
50    /// Enable anti-aliasing
51    pub antialiasing: bool,
52    /// Render quality
53    pub quality: RenderQuality,
54    /// Performance settings
55    pub performance: PerformanceSettings,
56    /// Buffer configuration
57    pub buffers: BufferConfig,
58}
59
60/// Rendering backend enumeration
61#[derive(Debug, Clone, Serialize, Deserialize)]
62pub enum RenderingBackend {
63    /// WebGL 2.0
64    WebGL2,
65    /// WebGL 1.0
66    WebGL1,
67    /// Canvas 2D
68    Canvas2D,
69    /// SVG
70    SVG,
71    /// WebGPU (future)
72    WebGPU,
73}
74
75/// Render quality enumeration
76#[derive(Debug, Clone, Serialize, Deserialize)]
77pub enum RenderQuality {
78    /// Low quality (performance)
79    Low,
80    /// Medium quality
81    Medium,
82    /// High quality
83    High,
84    /// Ultra quality
85    Ultra,
86}
87
88/// Performance settings
89#[derive(Debug, Clone, Serialize, Deserialize)]
90pub struct PerformanceSettings {
91    /// Enable frustum culling
92    pub frustum_culling: bool,
93    /// Enable occlusion culling
94    pub occlusion_culling: bool,
95    /// Level of detail enabled
96    pub lod_enabled: bool,
97    /// Instanced rendering
98    pub instanced_rendering: bool,
99    /// Batch rendering
100    pub batch_rendering: bool,
101    /// Target FPS
102    pub target_fps: u32,
103}
104
105/// Buffer configuration
106#[derive(Debug, Clone, Serialize, Deserialize)]
107pub struct BufferConfig {
108    /// Color buffer format
109    pub color_format: ColorFormat,
110    /// Depth buffer enabled
111    pub depth_buffer: bool,
112    /// Stencil buffer enabled
113    pub stencil_buffer: bool,
114    /// Multisampling level
115    pub msaa_samples: u32,
116}
117
118/// Color format enumeration
119#[derive(Debug, Clone, Serialize, Deserialize)]
120pub enum ColorFormat {
121    /// RGBA8
122    RGBA8,
123    /// RGBA16F
124    RGBA16F,
125    /// RGBA32F
126    RGBA32F,
127    /// RGB8
128    RGB8,
129}
130
131/// Rendering capabilities
132#[derive(Debug, Clone)]
133pub struct RenderingCapabilities {
134    /// Maximum texture size
135    pub max_texture_size: u32,
136    /// Maximum render buffer size
137    pub max_render_buffer_size: u32,
138    /// Supported extensions
139    pub extensions: Vec<String>,
140    /// Shader language version
141    pub shader_version: String,
142    /// WebGL version
143    pub webgl_version: f32,
144}
145
146/// Update manager for real-time updates
147#[derive(Debug)]
148pub struct UpdateManager {
149    /// Update configuration
150    config: UpdateConfig,
151    /// Update queue
152    update_queue: Vec<UpdateRequest>,
153    /// Performance monitor
154    performance_monitor: PerformanceMonitor,
155}
156
157/// Update configuration
158#[derive(Debug, Clone, Serialize, Deserialize)]
159pub struct UpdateConfig {
160    /// Update interval
161    pub update_interval: std::time::Duration,
162    /// Batch size
163    pub batch_size: usize,
164    /// Enable delta updates
165    pub delta_updates: bool,
166    /// Prioritization enabled
167    pub prioritization: bool,
168}
169
170/// Update request
171#[derive(Debug, Clone)]
172pub struct UpdateRequest {
173    /// Widget ID
174    pub widget_id: String,
175    /// Update type
176    pub update_type: UpdateType,
177    /// Update data
178    pub data: serde_json::Value,
179    /// Priority
180    pub priority: UpdatePriority,
181    /// Timestamp
182    pub timestamp: std::time::Instant,
183}
184
185/// Update type enumeration
186#[derive(Debug, Clone)]
187pub enum UpdateType {
188    /// Data update
189    Data,
190    /// Style update
191    Style,
192    /// Position update
193    Position,
194    /// Size update
195    Size,
196    /// Full refresh
197    FullRefresh,
198}
199
200/// Update priority enumeration
201#[derive(Debug, Clone)]
202pub enum UpdatePriority {
203    /// Low priority
204    Low,
205    /// Normal priority
206    Normal,
207    /// High priority
208    High,
209    /// Critical priority
210    Critical,
211}
212
213/// Performance monitor
214#[derive(Debug)]
215pub struct PerformanceMonitor {
216    /// Frame times
217    frame_times: std::collections::VecDeque<std::time::Duration>,
218    /// Render statistics
219    stats: RenderStatistics,
220    /// Configuration
221    config: PerformanceConfig,
222}
223
224/// Render statistics
225#[derive(Debug, Clone)]
226pub struct RenderStatistics {
227    /// Average frame time
228    pub avg_frame_time: std::time::Duration,
229    /// Current FPS
230    pub fps: f64,
231    /// Draw calls count
232    pub draw_calls: u32,
233    /// Triangles rendered
234    pub triangles: u32,
235    /// Memory usage
236    pub memory_usage: u64,
237}
238
239/// Performance configuration
240#[derive(Debug, Clone, Serialize, Deserialize)]
241pub struct PerformanceConfig {
242    /// Monitoring enabled
243    pub enabled: bool,
244    /// Sample size for averaging
245    pub sample_size: usize,
246    /// Performance alerts
247    pub alerts_enabled: bool,
248    /// Target FPS threshold
249    pub fps_threshold: f64,
250}
251
252impl UpdateManager {
253    /// Create new update manager
254    pub fn new(config: UpdateConfig) -> Self {
255        Self {
256            config,
257            update_queue: Vec::new(),
258            performance_monitor: PerformanceMonitor::new(),
259        }
260    }
261
262    /// Queue update request
263    pub fn queue_update(&mut self, request: UpdateRequest) {
264        self.update_queue.push(request);
265
266        // Sort by priority and timestamp
267        self.update_queue.sort_by(|a, b| {
268            match (a.priority.priority_value(), b.priority.priority_value()) {
269                (a_prio, b_prio) if a_prio != b_prio => b_prio.cmp(&a_prio),
270                _ => a.timestamp.cmp(&b.timestamp),
271            }
272        });
273    }
274
275    /// Process update queue
276    pub fn process_updates(&mut self) -> Result<Vec<UpdateRequest>> {
277        let batch_size = self.config.batch_size.min(self.update_queue.len());
278        let updates = self.update_queue.drain(0..batch_size).collect();
279        Ok(updates)
280    }
281}
282
283impl PerformanceMonitor {
284    /// Create new performance monitor
285    pub fn new() -> Self {
286        Self {
287            frame_times: std::collections::VecDeque::new(),
288            stats: RenderStatistics::default(),
289            config: PerformanceConfig::default(),
290        }
291    }
292
293    /// Record frame time
294    pub fn record_frame_time(&mut self, frame_time: std::time::Duration) {
295        if self.frame_times.len() >= self.config.sample_size {
296            self.frame_times.pop_front();
297        }
298        self.frame_times.push_back(frame_time);
299
300        self.update_statistics();
301    }
302
303    /// Update statistics
304    fn update_statistics(&mut self) {
305        if self.frame_times.is_empty() {
306            return;
307        }
308
309        let total_time: std::time::Duration = self.frame_times.iter().sum();
310        self.stats.avg_frame_time = total_time / self.frame_times.len() as u32;
311        self.stats.fps = 1.0 / self.stats.avg_frame_time.as_secs_f64();
312    }
313
314    /// Get current statistics
315    pub fn get_statistics(&self) -> &RenderStatistics {
316        &self.stats
317    }
318}
319
320impl UpdatePriority {
321    /// Get numeric priority value
322    fn priority_value(&self) -> u32 {
323        match self {
324            UpdatePriority::Low => 1,
325            UpdatePriority::Normal => 2,
326            UpdatePriority::High => 3,
327            UpdatePriority::Critical => 4,
328        }
329    }
330}
331
332impl Default for RenderingConfig {
333    fn default() -> Self {
334        Self {
335            backend: RenderingBackend::WebGL2,
336            antialiasing: true,
337            quality: RenderQuality::High,
338            performance: PerformanceSettings::default(),
339            buffers: BufferConfig::default(),
340        }
341    }
342}
343
344impl Default for PerformanceSettings {
345    fn default() -> Self {
346        Self {
347            frustum_culling: true,
348            occlusion_culling: false,
349            lod_enabled: true,
350            instanced_rendering: true,
351            batch_rendering: true,
352            target_fps: 60,
353        }
354    }
355}
356
357impl Default for BufferConfig {
358    fn default() -> Self {
359        Self {
360            color_format: ColorFormat::RGBA8,
361            depth_buffer: true,
362            stencil_buffer: false,
363            msaa_samples: 4,
364        }
365    }
366}
367
368impl Default for UpdateConfig {
369    fn default() -> Self {
370        Self {
371            update_interval: std::time::Duration::from_millis(16), // ~60 FPS
372            batch_size: 50,
373            delta_updates: true,
374            prioritization: true,
375        }
376    }
377}
378
379impl Default for PerformanceConfig {
380    fn default() -> Self {
381        Self {
382            enabled: true,
383            sample_size: 60,
384            alerts_enabled: true,
385            fps_threshold: 30.0,
386        }
387    }
388}
389
390impl Default for RenderStatistics {
391    fn default() -> Self {
392        Self {
393            avg_frame_time: std::time::Duration::from_millis(16),
394            fps: 60.0,
395            draw_calls: 0,
396            triangles: 0,
397            memory_usage: 0,
398        }
399    }
400}