webizen_render/wgpu_renderer/
draw.rs1#[cfg(not(feature = "qualia"))]
4use super::pipelines::AmbientConfig;
5use super::pipelines::ScreenVertex;
6#[cfg(not(feature = "qualia"))]
7use super::vegetation_effects;
8use super::{Camera, ScreenPoint, Vec3, WgpuRenderer};
9
10impl<'a> WgpuRenderer<'a> {
11 pub(super) fn parse_color(color: &str, alpha: f64) -> [f32; 4] {
13 let (r, g, b, a) = if color.starts_with('#') {
14 let hex = color.trim_start_matches('#');
15 let len = hex.len();
16 if len == 6 {
17 let r = u8::from_str_radix(&hex[0..2], 16).unwrap_or(0);
18 let g = u8::from_str_radix(&hex[2..4], 16).unwrap_or(0);
19 let b = u8::from_str_radix(&hex[4..6], 16).unwrap_or(0);
20 (r, g, b, (alpha * 255.0) as u8)
21 } else if len == 3 {
22 let r = u8::from_str_radix(&hex[0..1], 16).unwrap_or(0) * 17;
23 let g = u8::from_str_radix(&hex[1..2], 16).unwrap_or(0) * 17;
24 let b = u8::from_str_radix(&hex[2..3], 16).unwrap_or(0) * 17;
25 (r, g, b, (alpha * 255.0) as u8)
26 } else {
27 (0, 0, 0, (alpha * 255.0) as u8)
28 }
29 } else if color.starts_with("rgb(") {
30 let parts: Vec<&str> = color
31 .trim_start_matches("rgb(")
32 .trim_start_matches("rgba(")
33 .trim_end_matches(')')
34 .split(',')
35 .collect();
36 let r = parts
37 .first()
38 .and_then(|s| s.trim().parse::<u8>().ok())
39 .unwrap_or(0);
40 let g = parts
41 .get(1)
42 .and_then(|s| s.trim().parse::<u8>().ok())
43 .unwrap_or(0);
44 let b = parts
45 .get(2)
46 .and_then(|s| s.trim().parse::<u8>().ok())
47 .unwrap_or(0);
48 let a = if parts.len() > 3 {
49 parts
50 .get(3)
51 .and_then(|s| s.trim().parse::<f64>().ok())
52 .unwrap_or(alpha)
53 } else {
54 alpha
55 };
56 (r, g, b, (a * 255.0) as u8)
57 } else {
58 (0, 0, 0, (alpha * 255.0) as u8)
59 };
60
61 [
62 r as f32 / 255.0,
63 g as f32 / 255.0,
64 b as f32 / 255.0,
65 a as f32 / 255.0,
66 ]
67 }
68
69 pub fn viewport(&self) -> (f64, f64) {
71 self.viewport_size
72 }
73
74 pub fn set_camera(&mut self, camera: Camera) {
76 self.camera = camera;
77 }
78
79 #[cfg(not(feature = "qualia"))]
81 pub fn set_ambient_config(&mut self, config: AmbientConfig) {
82 self.ambient_config = config;
83 }
84
85 #[cfg(not(feature = "qualia"))]
87 pub fn get_ambient_config(&self) -> AmbientConfig {
88 self.ambient_config
89 }
90
91 #[cfg(not(feature = "qualia"))]
95 pub fn emit_ambient_effect(
96 &mut self,
97 event: vegetation_effects::EffectEvent,
98 time_seconds: f32,
99 ) -> vegetation_effects::SpawnOutcome {
100 let outcome = self.ambient_effects.emit(event);
101 if matches!(outcome, vegetation_effects::SpawnOutcome::Queued) {
102 let frame = vegetation_effects::WorldFrame::from_time(
103 time_seconds,
104 vegetation_effects::DEFAULT_WORLD_SEED,
105 );
106 let telemetry = vegetation_effects::SystemTelemetry::default();
107 self.ambient_effects.update(
108 frame,
109 vegetation_effects::WindField::from_telemetry(&telemetry),
110 );
111 if let Some(buffer) = &self.particle_buffer {
112 self.queue.write_buffer(
113 buffer,
114 0,
115 bytemuck::cast_slice(self.ambient_effects.particles()),
116 );
117 }
118 }
119 outcome
120 }
121
122 pub fn clear(&self, color: &str) {
124 let rgba = Self::parse_color(color, 1.0);
125 let frame = match self.begin_frame() {
126 Ok(frame) => frame,
127 Err(_) => return,
128 };
129
130 let mut encoder = self
131 .device
132 .create_command_encoder(&etalon::CommandEncoderDescriptor {
133 label: Some("webizen-clear-encoder"),
134 });
135
136 {
137 let _render_pass = encoder.begin_render_pass(&etalon::RenderPassDescriptor {
138 label: Some("webizen-clear-pass"),
139 color_attachments: &[Some(etalon::RenderPassColorAttachment {
140 view: frame.view(),
141 depth_slice: None,
142 resolve_target: None,
143 ops: etalon::Operations {
144 load: etalon::LoadOp::Clear(etalon::Color {
145 r: rgba[0] as f64,
146 g: rgba[1] as f64,
147 b: rgba[2] as f64,
148 a: rgba[3] as f64,
149 }),
150 store: etalon::StoreOp::Store,
151 },
152 })],
153 depth_stencil_attachment: None,
154 timestamp_writes: None,
155 occlusion_query_set: None,
156 multiview_mask: None,
157 });
158 }
159
160 self.queue.submit(Some(encoder.finish()));
161 frame.present(&self.queue);
162 }
163
164 pub fn project(&self, world: Vec3) -> Option<ScreenPoint> {
166 self.camera.project(world, self.viewport_size)
167 }
168
169 pub fn clear_node_positions(&mut self) {
171 self.node_positions.clear();
172 }
173
174 pub fn get_node_positions(&self) -> &[(usize, ScreenPoint, f64)] {
176 &self.node_positions
177 }
178
179 pub fn hit_test(&self, point: ScreenPoint) -> Option<usize> {
184 for (index, pos, radius) in self.node_positions.iter().rev() {
185 let dx = point.x - pos.x;
186 let dy = point.y - pos.y;
187 let distance_squared = dx * dx + dy * dy;
188 let radius_squared = *radius * *radius;
189
190 if distance_squared <= radius_squared {
191 return Some(*index);
192 }
193 }
194 None
195 }
196
197 pub fn pick_anchor(&self, x: f64, y: f64) -> Option<usize> {
199 let point = ScreenPoint { x, y };
200 self.hit_test(point)
201 }
202
203 #[deprecated(note = "Use pick_anchor() for epistemic anchor coordination")]
205 pub fn pick(&self, x: f64, y: f64) -> Option<usize> {
206 self.pick_anchor(x, y)
207 }
208
209 pub fn hover_anchor(&self, x: f64, y: f64) -> Option<usize> {
211 let point = ScreenPoint { x, y };
212 self.hit_test(point)
213 }
214
215 #[deprecated(note = "Use hover_anchor() for epistemic anchor coordination")]
217 pub fn hover(&self, x: f64, y: f64) -> Option<usize> {
218 self.hover_anchor(x, y)
219 }
220
221 pub fn line(&self, a: ScreenPoint, b: ScreenPoint, color: &str, alpha: f64, width: f64) {
223 let rgba = Self::parse_color(color, alpha);
224
225 let width_px = self.viewport_size.0 as f32;
226 let height_px = self.viewport_size.1 as f32;
227
228 let x1 = ((a.x as f32 / width_px) * 2.0 - 1.0) * (width_px / height_px);
229 let y1 = 1.0 - (a.y as f32 / height_px) * 2.0;
230 let x2 = ((b.x as f32 / width_px) * 2.0 - 1.0) * (width_px / height_px);
231 let y2 = 1.0 - (b.y as f32 / height_px) * 2.0;
232
233 let line_width = width as f32 / width_px;
234 let dx = x2 - x1;
235 let dy = y2 - y1;
236 let len = (dx * dx + dy * dy).sqrt();
237 let nx = -dy / len * line_width;
238 let ny = dx / len * line_width;
239
240 let vertices = [
241 ScreenVertex {
242 position: [x1 + nx, y1 + ny],
243 color: rgba,
244 },
245 ScreenVertex {
246 position: [x1 - nx, y1 - ny],
247 color: rgba,
248 },
249 ScreenVertex {
250 position: [x2 + nx, y2 + ny],
251 color: rgba,
252 },
253 ScreenVertex {
254 position: [x2 - nx, y2 - ny],
255 color: rgba,
256 },
257 ];
258
259 self.render_vertices(&vertices, etalon::PrimitiveTopology::TriangleStrip);
260 }
261
262 pub fn point(&self, p: ScreenPoint, radius: f64, color: &str, alpha: f64) {
264 let rgba = Self::parse_color(color, alpha);
265
266 let width_px = self.viewport_size.0 as f32;
267 let height_px = self.viewport_size.1 as f32;
268
269 let cx = ((p.x as f32 / width_px) * 2.0 - 1.0) * (width_px / height_px);
270 let cy = 1.0 - (p.y as f32 / height_px) * 2.0;
271 let r = (radius as f32 / width_px) * 2.0;
272
273 let segments = 16;
274 let mut vertices = Vec::with_capacity(segments + 2);
275 vertices.push(ScreenVertex {
276 position: [cx, cy],
277 color: rgba,
278 });
279
280 for i in 0..=segments {
281 let angle = (i as f32 / segments as f32) * std::f32::consts::PI * 2.0;
282 let x = cx + angle.cos() * r;
283 let y = cy + angle.sin() * r;
284 vertices.push(ScreenVertex {
285 position: [x, y],
286 color: rgba,
287 });
288 }
289
290 self.render_vertices(&vertices, etalon::PrimitiveTopology::TriangleList);
291 }
292
293 pub fn fill_polygon(&self, points: &[ScreenPoint], color: &str, alpha: f64) {
295 if points.len() < 3 {
296 return;
297 }
298
299 let rgba = Self::parse_color(color, alpha);
300
301 let width_px = self.viewport_size.0 as f32;
302 let height_px = self.viewport_size.1 as f32;
303
304 let vertices: Vec<ScreenVertex> = points
305 .iter()
306 .map(|p| {
307 let x = ((p.x as f32 / width_px) * 2.0 - 1.0) * (width_px / height_px);
308 let y = 1.0 - (p.y as f32 / height_px) * 2.0;
309 ScreenVertex {
310 position: [x, y],
311 color: rgba,
312 }
313 })
314 .collect();
315
316 self.render_vertices(&vertices, etalon::PrimitiveTopology::TriangleList);
317 }
318
319 fn render_vertices(&self, vertices: &[ScreenVertex], _topology: etalon::PrimitiveTopology) {
320 if vertices.is_empty() || vertices.len() > self.max_vertices {
321 return;
322 }
323
324 let frame = match self.begin_frame() {
325 Ok(frame) => frame,
326 Err(_) => return,
327 };
328
329 self.queue
330 .write_buffer(&self.vertex_buffer, 0, bytemuck::cast_slice(vertices));
331
332 let mut encoder = self
333 .device
334 .create_command_encoder(&etalon::CommandEncoderDescriptor {
335 label: Some("webizen-render-encoder"),
336 });
337
338 {
339 let mut render_pass = encoder.begin_render_pass(&etalon::RenderPassDescriptor {
340 label: Some("webizen-render-pass"),
341 color_attachments: &[Some(etalon::RenderPassColorAttachment {
342 view: frame.view(),
343 depth_slice: None,
344 resolve_target: None,
345 ops: etalon::Operations {
346 load: etalon::LoadOp::Load,
347 store: etalon::StoreOp::Store,
348 },
349 })],
350 depth_stencil_attachment: None,
351 timestamp_writes: None,
352 occlusion_query_set: None,
353 multiview_mask: None,
354 });
355
356 render_pass.set_pipeline(&self.render_pipeline);
357 render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
358 render_pass.draw(0..vertices.len() as u32, 0..1);
359 }
360
361 self.queue.submit(Some(encoder.finish()));
362 frame.present(&self.queue);
363 }
364}