1use std::num::NonZeroU32;
20use std::ffi::CString;
21use std::time::{Duration, Instant};
22
23use glutin::config::ConfigTemplateBuilder;
24use glutin::context::{ContextApi, ContextAttributesBuilder, NotCurrentGlContext,
25 PossiblyCurrentContext, Version};
26use glutin::display::{GetGlDisplay, GlDisplay};
27use glutin::surface::{GlSurface, Surface, WindowSurface};
28use glutin_winit::{DisplayBuilder, GlWindow};
29use glow::HasContext;
30use raw_window_handle::HasWindowHandle;
31use winit::dpi::LogicalSize;
32use winit::event::{ElementState, Event, MouseButton, MouseScrollDelta, WindowEvent};
33use winit::event_loop::EventLoop;
34use winit::keyboard::{KeyCode, PhysicalKey};
35use winit::platform::pump_events::{EventLoopExtPumpEvents, PumpStatus};
36use winit::window::Window;
37use glam::{Mat4, Vec2, Vec3};
38use bytemuck::cast_slice;
39
40use crate::config::{EngineConfig, RenderConfig};
41use crate::scene::Scene;
42use crate::render::camera::ProofCamera;
43use crate::render::postfx::PostFxPipeline;
44use crate::input::{InputState, Key};
45use crate::glyph::atlas::FontAtlas;
46use crate::glyph::batch::GlyphInstance;
47use crate::render::ui_layer::UiLayer;
48use crate::render::screen_fx::ScreenFx;
49use crate::particle::gpu_density::{GpuDensityEntityData, GpuDensityRenderer};
50
51const VERT_SRC: &str = r#"
54#version 330 core
55
56layout(location = 0) in vec2 v_pos;
57layout(location = 1) in vec2 v_uv;
58
59layout(location = 2) in vec3 i_position;
60layout(location = 3) in vec2 i_scale;
61layout(location = 4) in float i_rotation;
62layout(location = 5) in vec4 i_color;
63layout(location = 6) in float i_emission;
64layout(location = 7) in vec3 i_glow_color;
65layout(location = 8) in float i_glow_radius;
66layout(location = 9) in vec2 i_uv_offset;
67layout(location = 10) in vec2 i_uv_size;
68// x: 1.0 for a fill (ground, panel) that must not cast shadow.
69layout(location = 11) in vec2 i_flags;
70
71uniform mat4 u_view_proj;
72// Oversampling: each base instance is rendered u_n_copies times.
73// vertex_attrib_divisor is set to u_n_copies so all copies share the same
74// instance attributes. gl_InstanceID / u_n_copies selects the base particle;
75// gl_InstanceID % u_n_copies selects the copy and drives the jitter hash.
76uniform uint u_n_copies;
77
78out vec2 f_uv;
79out vec4 f_color;
80out float f_emission;
81out vec3 f_glow_color;
82out float f_glow_radius;
83out float f_fill;
84
85// Hash matching the CPU hf(seed, v) function — same constants, same bit ops.
86float hf(uint seed, uint v) {
87 uint n = seed * 374761393u + v * 668265263u;
88 n ^= (n >> 13u);
89 n *= 0x5851F42Du;
90 n ^= (n >> 16u);
91 return float(n & 0x00FFFFFFu) / float(0x01000000u);
92}
93
94void main() {
95 float c = cos(i_rotation);
96 float s = sin(i_rotation);
97 vec2 rotated = vec2(
98 v_pos.x * c - v_pos.y * s,
99 v_pos.x * s + v_pos.y * c
100 ) * i_scale;
101
102 // Per-copy position jitter — only active when oversampling.
103 // Seeds mirror the CPU oversampling: seed = real_id*17 + copy_id, slots 30/31.
104 vec3 jitter = vec3(0.0);
105 if (u_n_copies > 1u) {
106 uint real_id = uint(gl_InstanceID) / u_n_copies;
107 uint copy_id = uint(gl_InstanceID) % u_n_copies;
108 uint jseed = real_id * 17u + copy_id;
109 jitter = vec3(
110 (hf(jseed, 30u) - 0.5) * i_scale.x * 0.70,
111 (hf(jseed, 31u) - 0.5) * i_scale.y * 0.70,
112 0.0
113 );
114 }
115
116 gl_Position = u_view_proj * vec4(i_position + jitter + vec3(rotated, 0.0), 1.0);
117 gl_Position.y = -gl_Position.y; // FBO renders upside-down relative to screen
118
119 f_uv = i_uv_offset + v_uv * i_uv_size;
120 // Divide alpha and emission by n_copies so n_copies additive contributions
121 // sum to the same luminance as a single unscaled instance.
122 float inv_n = 1.0 / float(u_n_copies);
123 f_color = vec4(i_color.rgb, i_color.a * inv_n);
124 f_emission = i_emission * inv_n;
125 f_glow_color = i_glow_color;
126 f_glow_radius = i_glow_radius;
127 f_fill = i_flags.x;
128}
129"#;
130
131const FRAG_SRC: &str = r#"
139#version 330 core
140
141in vec2 f_uv;
142in vec4 f_color;
143in float f_emission;
144in vec3 f_glow_color;
145in float f_glow_radius;
146in float f_fill;
147
148uniform sampler2D u_atlas;
149
150layout(location = 0) out vec4 o_color;
151layout(location = 1) out vec4 o_emission;
152// Coverage of matter, for the light map's shadows. Fills write none, and
153// cover whatever was under them.
154layout(location = 2) out vec4 o_occluder;
155
156void main() {
157 float dist = texture(u_atlas, f_uv).r;
158
159 // SDF thresholds (in normalized distance, 0.5 = edge)
160 float edge = 0.5;
161 float softness = 0.08; // edge softness (antialiasing)
162
163 // Core glyph alpha (sharp edge with antialiasing)
164 float alpha = smoothstep(edge - softness, edge + softness, dist);
165
166 // Outline: a band just outside the edge
167 float outline_width = 0.06;
168 float outline_alpha = smoothstep(edge - outline_width - softness, edge - outline_width, dist)
169 * (1.0 - smoothstep(edge - softness * 0.5, edge + softness * 0.5, dist));
170 vec3 outline_color = f_glow_color * 0.6;
171
172 // Glow halo: soft falloff outside the glyph
173 float glow_size = 0.15 + f_glow_radius * 0.05;
174 float glow_alpha = smoothstep(edge - glow_size - 0.1, edge - 0.02, dist) * (1.0 - alpha);
175 glow_alpha *= clamp(f_glow_radius * 0.3, 0.0, 0.5);
176
177 // Drop shadow (offset sample)
178 vec2 shadow_offset = vec2(0.003, -0.004);
179 float shadow_dist = texture(u_atlas, f_uv + shadow_offset).r;
180 float shadow_alpha = smoothstep(edge - softness, edge + softness, shadow_dist) * 0.2;
181
182 // Discard if nothing visible
183 float total_alpha = max(max(alpha, outline_alpha), max(glow_alpha, shadow_alpha));
184 if (total_alpha < 0.01) discard;
185
186 // Composite layers
187 float em = clamp(f_emission * 0.5, 0.0, 1.0);
188 vec3 base_col = mix(f_color.rgb, f_glow_color, em);
189
190 // Shadow (darkest layer)
191 vec3 col = vec3(0.0);
192 float a = shadow_alpha * f_color.a * 0.3;
193
194 // Glow halo (behind outline)
195 col = mix(col, f_glow_color * 0.5, glow_alpha);
196 a = max(a, glow_alpha * f_color.a * 0.4);
197
198 // Outline
199 col = mix(col, outline_color, outline_alpha);
200 a = max(a, outline_alpha * f_color.a * 0.7);
201
202 // Core fill (on top)
203 col = mix(col, base_col, alpha);
204 a = max(a, alpha * f_color.a);
205
206 o_color = vec4(col, a);
207
208 // Emission for bloom
209 float bloom_strength = clamp(f_emission - 0.3, 0.0, 1.0);
210 float glow_boost = clamp(f_glow_radius * 0.15, 0.0, 0.8);
211 float em_alpha = max(alpha, glow_alpha * 0.5) * f_color.a;
212 o_emission = vec4(f_glow_color * (bloom_strength + glow_boost), em_alpha);
213 o_occluder = vec4(alpha * f_color.a * (1.0 - f_fill), 0.0, 0.0, a);
214}
215"#;
216
217#[rustfmt::skip]
221const QUAD_VERTS: [f32; 24] = [
222 -0.5, 0.5, 0.0, 1.0,
223 -0.5, -0.5, 0.0, 0.0,
224 0.5, 0.5, 1.0, 1.0,
225 -0.5, -0.5, 0.0, 0.0,
226 0.5, -0.5, 1.0, 0.0,
227 0.5, 0.5, 1.0, 1.0,
228];
229
230#[derive(Clone, Debug, Default)]
234pub struct FrameStats {
235 pub fps: f32,
237 pub dt: f32,
239 pub glyph_count: usize,
241 pub particle_count: usize,
243 pub draw_calls: u32,
245 pub frame_number: u64,
247}
248
249struct FpsCounter {
251 samples: [f32; 60],
252 head: usize,
253 filled: bool,
254}
255
256impl FpsCounter {
257 fn new() -> Self { Self { samples: [0.016; 60], head: 0, filled: false } }
258
259 fn push(&mut self, dt: f32) {
260 self.samples[self.head] = dt.max(f32::EPSILON);
261 self.head = (self.head + 1) % 60;
262 if self.head == 0 { self.filled = true; }
263 }
264
265 fn fps(&self) -> f32 {
266 let count = if self.filled { 60 } else { self.head.max(1) };
267 let avg_dt: f32 = self.samples[..count].iter().sum::<f32>() / count as f32;
268 1.0 / avg_dt
269 }
270}
271
272#[allow(dead_code)]
280pub struct Pipeline {
281 pub width: u32,
283 pub height: u32,
284 pub stats: FrameStats,
285 running: bool,
286
287 render_config: RenderConfig,
289
290 event_loop: EventLoop<()>,
292 window: Window,
293 surface: Surface<WindowSurface>,
294 context: PossiblyCurrentContext,
295
296 gl: glow::Context,
298 program: glow::Program,
299 vao: glow::VertexArray,
300 quad_vbo: glow::Buffer,
301 instance_vbo: glow::Buffer,
302 atlas_tex: glow::Texture,
303 loc_view_proj: glow::UniformLocation,
304 loc_n_copies: Option<glow::UniformLocation>,
305
306 postfx: PostFxPipeline,
308
309 atlas: FontAtlas,
311
312 ui_renderer: super::ui_layer_renderer::UiLayerRenderer,
316 ui_prepared: bool,
319
320 density: Option<GpuDensityRenderer>,
323 density_entities: Vec<GpuDensityEntityData>,
324 density_budget: u32,
325
326 pub svogi: crate::svogi::integration::CascadedSvogi,
328
329 pub fog: crate::volumetric_fog::VolumetricFogPipeline,
331
332 instances: Vec<GlyphInstance>,
334
335 fps_counter: FpsCounter,
337 frame_start: Instant,
338 scene_time: f32,
339
340 mouse_pos: Vec2,
342 mouse_pos_prev: Vec2,
343 mouse_ndc: Vec2,
345
346 pub raw_window_events: Vec<winit::event::WindowEvent>,
349}
350
351impl Pipeline {
352 pub fn init(config: &EngineConfig) -> Self {
354 let event_loop = EventLoop::new().expect("EventLoop::new");
356
357 let window_attrs = Window::default_attributes()
359 .with_title(&config.window_title)
360 .with_inner_size(LogicalSize::new(config.window_width, config.window_height))
361 .with_resizable(true);
362
363 let template = ConfigTemplateBuilder::new()
365 .with_alpha_size(8)
366 .with_depth_size(0);
367
368 let display_builder = DisplayBuilder::new()
369 .with_window_attributes(Some(window_attrs));
370
371 let (window, gl_config) = display_builder
372 .build(&event_loop, template, |mut configs| {
373 configs.next().expect("no suitable GL config found")
374 })
375 .expect("DisplayBuilder::build failed");
376
377 let window = window.expect("window was not created");
378 let display = gl_config.display();
379
380 let raw_handle = window.window_handle().unwrap().as_raw();
382 let ctx_attrs_43 = ContextAttributesBuilder::new()
383 .with_context_api(ContextApi::OpenGl(Some(Version::new(4, 3))))
384 .build(Some(raw_handle));
385 let ctx_attrs_33 = ContextAttributesBuilder::new()
386 .with_context_api(ContextApi::OpenGl(Some(Version::new(3, 3))))
387 .build(Some(raw_handle));
388
389 let not_current = unsafe {
390 display.create_context(&gl_config, &ctx_attrs_43)
391 .unwrap_or_else(|_| {
392 display.create_context(&gl_config, &ctx_attrs_33)
393 .expect("create_context failed (both GL 4.3 and 3.3)")
394 })
395 };
396
397 let size = window.inner_size();
399 let w = size.width.max(1);
400 let h = size.height.max(1);
401
402 let surface_attrs = window
403 .build_surface_attributes(Default::default())
404 .expect("build_surface_attributes failed");
405
406 let surface = unsafe {
407 display.create_window_surface(&gl_config, &surface_attrs)
408 .expect("create_window_surface failed")
409 };
410
411 let context = not_current.make_current(&surface)
413 .expect("make_current failed");
414 if config.render.vsync {
415 use glutin::surface::SwapInterval;
416 if let Err(e) = surface.set_swap_interval(
417 &context,
418 SwapInterval::Wait(NonZeroU32::new(1).unwrap()),
419 ) {
420 log::warn!("vsync unavailable: {e}");
421 }
422 }
423
424 let gl = unsafe {
426 glow::Context::from_loader_function(|sym| {
427 let sym_c = CString::new(sym).unwrap();
428 display.get_proc_address(sym_c.as_c_str()) as *const _
429 })
430 };
431
432 let program = unsafe { compile_program(&gl, VERT_SRC, FRAG_SRC) };
434 let loc_view_proj = unsafe {
435 gl.get_uniform_location(program, "u_view_proj")
436 .expect("uniform u_view_proj not found")
437 };
438 let loc_n_copies = unsafe {
439 gl.get_uniform_location(program, "u_n_copies")
440 };
441 unsafe {
442 gl.use_program(Some(program));
443 if let Some(loc) = gl.get_uniform_location(program, "u_atlas") {
444 gl.uniform_1_i32(Some(&loc), 0);
445 }
446 if let Some(ref loc) = loc_n_copies {
448 gl.uniform_1_u32(Some(loc), 1u32);
449 }
450 }
451
452 let (vao, quad_vbo, instance_vbo) = unsafe { setup_vao(&gl) };
454
455 let atlas = FontAtlas::build(config.render.font_size as f32);
457 let atlas_tex = unsafe { upload_atlas(&gl, &atlas) };
458
459 let postfx = unsafe { PostFxPipeline::new(&gl, w, h, config.render.render_scale) };
461
462 unsafe {
464 gl.enable(glow::BLEND);
465 gl.blend_func(glow::SRC_ALPHA, glow::ONE_MINUS_SRC_ALPHA);
466 gl.clear_color(0.02, 0.02, 0.05, 1.0);
467 gl.viewport(0, 0, w as i32, h as i32);
468 }
469
470 log::info!(
471 "Pipeline ready — {}×{} — font atlas {}×{} ({} chars) — PostFxPipeline wired",
472 w, h, atlas.width, atlas.height, atlas.uvs.len()
473 );
474
475 Self {
476 width: w, height: h,
477 stats: FrameStats::default(),
478 running: true,
479 render_config: config.render.clone(),
480 event_loop, window, surface, context,
481 gl, program, vao, quad_vbo, instance_vbo, atlas_tex, loc_view_proj, loc_n_copies,
482 postfx,
483 atlas,
484 ui_renderer: super::ui_layer_renderer::UiLayerRenderer::new(),
485 ui_prepared: false,
486 density: None,
487 density_entities: Vec::new(),
488 density_budget: 0,
489 instances: Vec::with_capacity(8192),
490 fps_counter: FpsCounter::new(),
491 frame_start: Instant::now(),
492 scene_time: 0.0,
493 mouse_pos: Vec2::ZERO,
494 mouse_pos_prev: Vec2::ZERO,
495 mouse_ndc: Vec2::ZERO,
496 raw_window_events: Vec::new(),
497 svogi: crate::svogi::integration::CascadedSvogi::new(3, 64, 50.0),
498 fog: crate::volumetric_fog::VolumetricFogPipeline::new(
499 crate::volumetric_fog::FogPresets::combat()
500 ),
501 }
502 }
503
504 pub fn set_density_entities(&mut self, entities: &[GpuDensityEntityData], budget: u32) {
508 self.density_entities.clear();
509 self.density_entities.extend_from_slice(entities);
510 self.density_budget = budget;
511 if !self.density_entities.is_empty() && self.density.is_none() {
512 self.density = Some(unsafe { GpuDensityRenderer::new(&self.gl) });
513 }
514 }
515
516 pub fn update_render_config(&mut self, config: &RenderConfig) {
519 let old_scale = self.render_config.render_scale;
520 self.render_config = config.clone();
521 if (config.render_scale - old_scale).abs() > 1e-4 {
523 unsafe { self.postfx.resize(&self.gl, self.width, self.height, config.render_scale); }
524 }
525 }
526
527 pub fn poll_events(&mut self, input: &mut InputState) -> bool {
529 input.clear_frame();
530 self.mouse_pos_prev = self.mouse_pos;
531
532 let mut should_exit = false;
533 let mut resize: Option<(u32, u32)> = None;
534 let mut key_events: Vec<(KeyCode, bool)> = Vec::new();
535 let mut mouse_moved: Option<(f64, f64)> = None;
536 let mut mouse_buttons: Vec<(MouseButton, bool)> = Vec::new();
537 let mut scroll_delta: f32 = 0.0;
538
539 self.raw_window_events.clear();
540
541 #[allow(deprecated)]
542 let status = self.event_loop.pump_events(Some(Duration::ZERO), |event, elwt| {
543 match event {
544 Event::WindowEvent { event: we, .. } => match we {
545 WindowEvent::CloseRequested => {
546 should_exit = true;
547 elwt.exit();
548 }
549 WindowEvent::Resized(s) => {
550 resize = Some((s.width, s.height));
551 }
552 WindowEvent::KeyboardInput { event: key_ev, .. } => {
553 if let PhysicalKey::Code(kc) = key_ev.physical_key {
554 let pressed = key_ev.state == ElementState::Pressed;
555 key_events.push((kc, pressed));
556 }
557 }
558 WindowEvent::CursorMoved { position, .. } => {
559 mouse_moved = Some((position.x, position.y));
560 }
561 WindowEvent::MouseInput { button, state, .. } => {
562 let pressed = state == ElementState::Pressed;
563 mouse_buttons.push((button, pressed));
564 }
565 WindowEvent::MouseWheel { delta, .. } => {
566 scroll_delta += match delta {
567 MouseScrollDelta::LineDelta(_, y) => y,
568 MouseScrollDelta::PixelDelta(d) => d.y as f32 / 40.0,
569 };
570 }
571 _ => {}
572 }
573 _ => {}
574 }
575 });
576
577 if let Some((w, h)) = resize {
579 if w > 0 && h > 0 {
580 self.surface.resize(
581 &self.context,
582 NonZeroU32::new(w).unwrap(),
583 NonZeroU32::new(h).unwrap(),
584 );
585 unsafe { self.gl.viewport(0, 0, w as i32, h as i32); }
586 self.width = w;
587 self.height = h;
588 input.window_resized = Some((w, h));
589 unsafe { self.postfx.resize(&self.gl, w, h, self.render_config.render_scale); }
590 }
591 }
592
593 for (kc, pressed) in key_events {
595 if let Some(key) = keycode_to_engine(kc) {
596 if pressed {
597 input.keys_pressed.insert(key);
598 input.keys_just_pressed.insert(key);
599 } else {
600 input.keys_pressed.remove(&key);
601 input.keys_just_released.insert(key);
602 }
603 }
604 }
605
606 if let Some((x, y)) = mouse_moved {
608 self.mouse_pos = Vec2::new(x as f32, y as f32);
609 input.mouse_x = x as f32;
610 input.mouse_y = y as f32;
611 let w = self.width.max(1) as f32;
613 let h = self.height.max(1) as f32;
614 self.mouse_ndc = Vec2::new(
615 (x as f32 / w) * 2.0 - 1.0,
616 1.0 - (y as f32 / h) * 2.0,
617 );
618 input.mouse_ndc = self.mouse_ndc;
619 input.mouse_delta = self.mouse_pos - self.mouse_pos_prev;
620 }
621
622 for (button, pressed) in mouse_buttons {
623 match button {
624 MouseButton::Left => {
625 if pressed { input.mouse_left_just_pressed = true; }
626 else { input.mouse_left_just_released = true; }
627 input.mouse_left = pressed;
628 }
629 MouseButton::Right => {
630 if pressed { input.mouse_right_just_pressed = true; }
631 else { input.mouse_right_just_released = true; }
632 input.mouse_right = pressed;
633 }
634 MouseButton::Middle => {
635 if pressed { input.mouse_middle_just_pressed = true; }
636 input.mouse_middle = pressed;
637 }
638 _ => {}
639 }
640 }
641
642 input.scroll_delta = scroll_delta;
643
644 if should_exit || matches!(status, PumpStatus::Exit(_)) {
646 self.running = false;
647 }
648 self.running
649 }
650
651 pub fn render(&mut self, scene: &Scene, camera: &ProofCamera) {
654 let fx = ScreenFx::default();
655 self.render_frame(scene, camera, None, &fx);
656 }
657
658 pub fn render_frame(
666 &mut self,
667 scene: &Scene,
668 camera: &ProofCamera,
669 ui: Option<&UiLayer>,
670 fx: &ScreenFx,
671 ) {
672 let now = Instant::now();
674 let dt = now.duration_since(self.frame_start).as_secs_f32().min(0.1);
675 self.frame_start = now;
676 self.scene_time = scene.time;
677
678 self.fps_counter.push(dt);
679 self.stats.fps = self.fps_counter.fps();
680 self.stats.dt = dt;
681 self.stats.frame_number += 1;
682
683 let pos = camera.position.position();
685 let tgt = camera.target.position();
686 let fov = camera.fov.position;
687 let aspect = if self.height > 0 { self.width as f32 / self.height as f32 } else { 1.0 };
688 let view = Mat4::look_at_rh(pos, tgt, Vec3::Y);
689 let proj = Mat4::perspective_rh_gl(fov.to_radians(), aspect, camera.near, camera.far);
690 let view_proj = proj * view;
691
692 if self.render_config.global_illumination {
694 use crate::svogi::inject::{LightSource, DirectionalLight, PointLight};
695 let sun = LightSource::Directional(DirectionalLight {
696 direction: Vec3::new(-0.5, 1.0, 0.8).normalize(),
697 color: Vec3::new(0.8, 0.75, 0.65),
698 intensity: 1.0,
699 });
700 let mut all_lights = vec![sun];
701 let mut emissive_count = 0;
703 for (_, glyph) in scene.glyphs.iter() {
704 if glyph.emission > 0.5 && emissive_count < 50 {
705 all_lights.push(LightSource::Point(PointLight {
706 position: glyph.position,
707 color: glyph.glow_color,
708 intensity: glyph.emission * 0.3,
709 radius: glyph.glow_radius * 2.0,
710 }));
711 emissive_count += 1;
712 }
713 }
714 self.svogi.update(dt, &[], &all_lights, &[]);
715 }
716
717 if self.render_config.volumetric_fog {
719 use crate::volumetric_fog::FogLight;
720 let inv_vp = view_proj.inverse();
721 let fog_lights = vec![
722 FogLight::Directional {
723 direction: Vec3::new(-0.3, -0.8, -0.5).normalize(),
724 color: Vec3::new(0.6, 0.55, 0.5),
725 intensity: 0.5,
726 },
727 ];
728 self.fog.update(dt, &inv_vp, pos, &fog_lights, &[]);
729 }
730
731 self.instances.clear();
733 let mut glyph_count = 0;
734 let mut particle_count = 0;
735
736 for (_, glyph) in scene.glyphs.iter() {
738 if !glyph.visible { continue; }
739 let life_scale = if let Some(ref f) = glyph.life_function {
740 f.evaluate(scene.time, 0.0)
741 } else {
742 1.0
743 };
744 let uv = self.atlas.uv_for(glyph.character);
745
746 let dist = (glyph.position - pos).length();
748 let fog_density = 0.003; let fog_factor = (-dist * fog_density).exp(); let fog_color = [0.03f32, 0.04, 0.06]; let mut color = glyph.color.to_array();
752 color[0] = color[0] * fog_factor + fog_color[0] * (1.0 - fog_factor);
753 color[1] = color[1] * fog_factor + fog_color[1] * (1.0 - fog_factor);
754 color[2] = color[2] * fog_factor + fog_color[2] * (1.0 - fog_factor);
755 color[3] *= fog_factor.max(0.1); let emission_fogged = glyph.emission * fog_factor;
757
758 self.instances.push(GlyphInstance {
759 position: glyph.position.to_array(),
760 scale: [glyph.scale.x * life_scale, glyph.scale.y * life_scale],
761 rotation: glyph.rotation,
762 color,
763 emission: emission_fogged,
764 glow_color: glyph.glow_color.to_array(),
765 glow_radius: glyph.glow_radius * fog_factor,
766 uv_offset: uv.offset(),
767 uv_size: uv.size(),
768 _pad: [0.0; 2],
769 });
770 glyph_count += 1;
771 }
772
773 for particle in scene.particles.iter() {
774 let g = &particle.glyph;
775 if !g.visible { continue; }
776 let uv = self.atlas.uv_for(g.character);
777 let dist = (g.position - pos).length();
779 let fog_factor = (-dist * 0.003).exp();
780 let fog_color = [0.03f32, 0.04, 0.06];
781 let mut color = g.color.to_array();
782 color[0] = color[0] * fog_factor + fog_color[0] * (1.0 - fog_factor);
783 color[1] = color[1] * fog_factor + fog_color[1] * (1.0 - fog_factor);
784 color[2] = color[2] * fog_factor + fog_color[2] * (1.0 - fog_factor);
785 color[3] *= fog_factor.max(0.1);
786
787 self.instances.push(GlyphInstance {
788 position: g.position.to_array(),
789 scale: [g.scale.x, g.scale.y],
790 rotation: g.rotation,
791 color,
792 emission: g.emission * fog_factor,
793 glow_color: g.glow_color.to_array(),
794 glow_radius: g.glow_radius * fog_factor,
795 uv_offset: uv.offset(),
796 uv_size: uv.size(),
797 _pad: [0.0; 2],
798 });
799 particle_count += 1;
800 }
801
802 self.stats.glyph_count = glyph_count;
803 self.stats.particle_count = particle_count;
804 self.stats.draw_calls = 0;
805
806 let mut world_proj = None;
812 if let Some(ui) = ui {
813 self.ui_renderer.build_instances(ui, &self.atlas);
814 self.ui_prepared = true;
815 if self.render_config.world_ui_in_scene && self.ui_renderer.world_count() > 0 {
816 let trauma = camera.shake.trauma.clamp(0.0, 1.0);
817 let amp = trauma * trauma * self.render_config.shake_pixels;
818 let t = self.scene_time;
819 let shake = Vec3::new((t * 47.3).sin() * amp, (t * 31.7).cos() * amp, 0.0);
820 world_proj = Some(ui.world_projection() * Mat4::from_translation(shake));
821 }
822 }
823
824 unsafe { self.execute_render_passes(view_proj, world_proj, fx); }
826 }
827
828 pub fn render_ui(&mut self, ui: &super::ui_layer::UiLayer) {
836 let prepared = std::mem::replace(&mut self.ui_prepared, false);
837 if ui.command_count() == 0 {
838 return;
839 }
840 if !prepared {
841 self.ui_renderer.build_instances(ui, &self.atlas);
842 }
843 let proj = ui.projection();
844 if !self.render_config.world_ui_in_scene && self.ui_renderer.world_count() > 0 {
847 unsafe { self.draw_ui_pass(proj, true) };
848 self.stats.draw_calls += 1;
849 }
850 if self.ui_renderer.glyph_count() == 0 {
851 return;
852 }
853 unsafe { self.draw_ui_pass(proj, false) };
854 self.stats.draw_calls += 1;
855 }
856
857 unsafe fn draw_ui_pass(&mut self, proj: Mat4, world: bool) {
861 let gl = &self.gl;
862 let (bytes, count) = if world {
863 (self.ui_renderer.world_bytes(), self.ui_renderer.world_count())
864 } else {
865 (self.ui_renderer.glyph_bytes(), self.ui_renderer.glyph_count())
866 };
867
868 gl.bind_framebuffer(glow::FRAMEBUFFER, None);
870 gl.viewport(0, 0, self.width as i32, self.height as i32);
871
872 gl.disable(glow::DEPTH_TEST);
875 gl.enable(glow::BLEND);
876 gl.blend_func(glow::SRC_ALPHA, glow::ONE_MINUS_SRC_ALPHA);
877
878 gl.bind_buffer(glow::ARRAY_BUFFER, Some(self.instance_vbo));
879 gl.buffer_data_u8_slice(glow::ARRAY_BUFFER, bytes, glow::DYNAMIC_DRAW);
880
881 gl.use_program(Some(self.program));
882 gl.uniform_matrix_4_f32_slice(Some(&self.loc_view_proj), false, &proj.to_cols_array());
883 gl.uniform_1_u32(self.loc_n_copies.as_ref(), 1);
886 gl.active_texture(glow::TEXTURE0);
887 gl.bind_texture(glow::TEXTURE_2D, Some(self.atlas_tex));
888 gl.bind_vertex_array(Some(self.vao));
889 for loc in 2u32..=11 {
890 gl.vertex_attrib_divisor(loc, 1);
891 }
892 gl.draw_arrays_instanced(glow::TRIANGLES, 0, 6, count as i32);
893
894 gl.enable(glow::DEPTH_TEST);
896 }
897
898 pub fn swap(&mut self) -> bool {
900 if let Err(e) = self.surface.swap_buffers(&self.context) {
901 log::error!("swap_buffers failed: {e}");
902 self.running = false;
903 }
904 self.running
905 }
906
907 pub fn gl(&self) -> &glow::Context {
912 &self.gl
913 }
914
915 pub fn window(&self) -> &Window {
917 &self.window
918 }
919
920 pub fn render_size(&self) -> (u32, u32) {
926 (self.width, self.height)
927 }
928
929 pub fn read_frame(&self) -> (u32, u32, Vec<u8>) {
935 let (w, h) = (self.width, self.height);
936 let mut buf = vec![0u8; (w as usize) * (h as usize) * 4];
937 unsafe {
938 let gl = &self.gl;
939 gl.bind_framebuffer(glow::FRAMEBUFFER, None);
940 gl.read_buffer(glow::BACK);
941 gl.pixel_store_i32(glow::PACK_ALIGNMENT, 1);
942 gl.read_pixels(
943 0,
944 0,
945 w as i32,
946 h as i32,
947 glow::RGBA,
948 glow::UNSIGNED_BYTE,
949 glow::PixelPackData::Slice(Some(&mut buf)),
950 );
951 }
952 (w, h, buf)
953 }
954
955 pub fn window_size(&self) -> (u32, u32) {
957 let size = self.window.inner_size();
958 (size.width, size.height)
959 }
960
961 unsafe fn execute_render_passes(
964 &mut self,
965 view_proj: Mat4,
966 world_proj: Option<Mat4>,
967 fx: &ScreenFx,
968 ) {
969 let gl = &self.gl;
970
971 let (sw, sh) = self.postfx.scene_size();
977 gl.bind_framebuffer(glow::FRAMEBUFFER, Some(self.postfx.scene_fbo));
978 gl.viewport(0, 0, sw as i32, sh as i32);
979 gl.clear_color(0.02, 0.025, 0.04, 1.0);
980 gl.clear(glow::COLOR_BUFFER_BIT);
981 gl.clear_buffer_f32_slice(glow::COLOR, 2, &[0.0, 0.0, 0.0, 0.0]);
983 gl.enable(glow::BLEND);
984 gl.blend_func(glow::SRC_ALPHA, glow::ONE_MINUS_SRC_ALPHA);
985
986 if !self.instances.is_empty() {
989 gl.bind_buffer(glow::ARRAY_BUFFER, Some(self.instance_vbo));
991 gl.buffer_data_u8_slice(
992 glow::ARRAY_BUFFER,
993 cast_slice(self.instances.as_slice()),
994 glow::DYNAMIC_DRAW,
995 );
996
997 let n_copies = self.render_config.particle_multiplier
1002 .ceil().max(1.0) as u32;
1003
1004 gl.use_program(Some(self.program));
1005 gl.uniform_matrix_4_f32_slice(
1006 Some(&self.loc_view_proj),
1007 false,
1008 &view_proj.to_cols_array(),
1009 );
1010 gl.uniform_1_u32(self.loc_n_copies.as_ref(), n_copies);
1011 gl.active_texture(glow::TEXTURE0);
1012 gl.bind_texture(glow::TEXTURE_2D, Some(self.atlas_tex));
1013 gl.bind_vertex_array(Some(self.vao));
1014 for loc in 2u32..=11 {
1017 gl.vertex_attrib_divisor(loc, n_copies);
1018 }
1019 gl.draw_arrays_instanced(
1020 glow::TRIANGLES, 0, 6,
1021 (self.instances.len() as u32 * n_copies) as i32,
1022 );
1023 self.stats.draw_calls += 1;
1024 }
1025
1026 if let Some(ref mut density) = self.density {
1032 if !self.density_entities.is_empty() {
1033 let draws = density.draw(
1034 gl,
1035 &self.density_entities,
1036 self.density_budget,
1037 &view_proj,
1038 (sw, sh),
1039 self.scene_time,
1040 );
1041 self.stats.draw_calls += draws;
1042 self.stats.particle_count += density.drawn as usize;
1043 }
1044 }
1045
1046 if let Some(wp) = world_proj {
1052 let count = self.ui_renderer.world_count();
1053 if count > 0 {
1054 gl.bind_buffer(glow::ARRAY_BUFFER, Some(self.instance_vbo));
1055 gl.buffer_data_u8_slice(
1056 glow::ARRAY_BUFFER,
1057 self.ui_renderer.world_bytes(),
1058 glow::DYNAMIC_DRAW,
1059 );
1060 gl.use_program(Some(self.program));
1061 gl.uniform_matrix_4_f32_slice(
1062 Some(&self.loc_view_proj),
1063 false,
1064 &wp.to_cols_array(),
1065 );
1066 gl.uniform_1_u32(self.loc_n_copies.as_ref(), 1);
1069 gl.active_texture(glow::TEXTURE0);
1070 gl.bind_texture(glow::TEXTURE_2D, Some(self.atlas_tex));
1071 gl.bind_vertex_array(Some(self.vao));
1072 for loc in 2u32..=11 {
1073 gl.vertex_attrib_divisor(loc, 1);
1074 }
1075 gl.draw_arrays_instanced(glow::TRIANGLES, 0, 6, count as i32);
1076 self.stats.draw_calls += 1;
1077 }
1078 }
1079
1080 let draws = self.postfx.run(
1082 gl, &self.render_config, fx, self.width, self.height, self.scene_time,
1083 );
1084 self.stats.draw_calls += draws;
1085 }
1086}
1087
1088unsafe fn compile_program(gl: &glow::Context, vert_src: &str, frag_src: &str) -> glow::Program {
1092 let vs = gl.create_shader(glow::VERTEX_SHADER).expect("create vertex shader");
1093 gl.shader_source(vs, vert_src);
1094 gl.compile_shader(vs);
1095 if !gl.get_shader_compile_status(vs) {
1096 let log = gl.get_shader_info_log(vs);
1097 panic!("Vertex shader compile error:\n{log}");
1098 }
1099
1100 let fs = gl.create_shader(glow::FRAGMENT_SHADER).expect("create fragment shader");
1101 gl.shader_source(fs, frag_src);
1102 gl.compile_shader(fs);
1103 if !gl.get_shader_compile_status(fs) {
1104 let log = gl.get_shader_info_log(fs);
1105 panic!("Fragment shader compile error:\n{log}");
1106 }
1107
1108 let prog = gl.create_program().expect("create shader program");
1109 gl.attach_shader(prog, vs);
1110 gl.attach_shader(prog, fs);
1111 gl.link_program(prog);
1112 if !gl.get_program_link_status(prog) {
1113 let log = gl.get_program_info_log(prog);
1114 panic!("Shader link error:\n{log}");
1115 }
1116
1117 gl.detach_shader(prog, vs);
1118 gl.detach_shader(prog, fs);
1119 gl.delete_shader(vs);
1120 gl.delete_shader(fs);
1121 prog
1122}
1123
1124unsafe fn setup_vao(gl: &glow::Context) -> (glow::VertexArray, glow::Buffer, glow::Buffer) {
1126 let vao = gl.create_vertex_array().expect("create vao");
1127 gl.bind_vertex_array(Some(vao));
1128
1129 let quad_vbo = gl.create_buffer().expect("create quad_vbo");
1131 gl.bind_buffer(glow::ARRAY_BUFFER, Some(quad_vbo));
1132 gl.buffer_data_u8_slice(glow::ARRAY_BUFFER, cast_slice(&QUAD_VERTS), glow::STATIC_DRAW);
1133 gl.vertex_attrib_pointer_f32(0, 2, glow::FLOAT, false, 16, 0);
1135 gl.enable_vertex_attrib_array(0);
1136 gl.vertex_attrib_pointer_f32(1, 2, glow::FLOAT, false, 16, 8);
1138 gl.enable_vertex_attrib_array(1);
1139
1140 let instance_vbo = gl.create_buffer().expect("create instance_vbo");
1142 gl.bind_buffer(glow::ARRAY_BUFFER, Some(instance_vbo));
1143
1144 let stride = std::mem::size_of::<GlyphInstance>() as i32;
1145
1146 macro_rules! inst_attr {
1148 ($loc:expr, $count:expr, $off:expr) => {{
1149 gl.vertex_attrib_pointer_f32($loc, $count, glow::FLOAT, false, stride, $off);
1150 gl.enable_vertex_attrib_array($loc);
1151 gl.vertex_attrib_divisor($loc, 1); }};
1153 }
1154
1155 inst_attr!(2, 3, 0); inst_attr!(3, 2, 12); inst_attr!(4, 1, 20); inst_attr!(5, 4, 24); inst_attr!(6, 1, 40); inst_attr!(7, 3, 44); inst_attr!(8, 1, 56); inst_attr!(9, 2, 60); inst_attr!(10, 2, 68); inst_attr!(11, 2, 76); (vao, quad_vbo, instance_vbo)
1167}
1168
1169unsafe fn upload_atlas(gl: &glow::Context, atlas: &FontAtlas) -> glow::Texture {
1171 let tex = gl.create_texture().expect("create atlas texture");
1172 gl.bind_texture(glow::TEXTURE_2D, Some(tex));
1173 gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, 1);
1174 gl.tex_image_2d(
1175 glow::TEXTURE_2D, 0, glow::R8 as i32,
1176 atlas.width as i32, atlas.height as i32,
1177 0, glow::RED, glow::UNSIGNED_BYTE,
1178 glow::PixelUnpackData::Slice(Some(&atlas.pixels)),
1179 );
1180 gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MIN_FILTER, glow::LINEAR as i32);
1181 gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MAG_FILTER, glow::LINEAR as i32);
1182 gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_S, glow::CLAMP_TO_EDGE as i32);
1183 gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_T, glow::CLAMP_TO_EDGE as i32);
1184 tex
1185}
1186
1187fn keycode_to_engine(kc: KeyCode) -> Option<Key> {
1191 Some(match kc {
1192 KeyCode::KeyA => Key::A, KeyCode::KeyB => Key::B, KeyCode::KeyC => Key::C,
1193 KeyCode::KeyD => Key::D, KeyCode::KeyE => Key::E, KeyCode::KeyF => Key::F,
1194 KeyCode::KeyG => Key::G, KeyCode::KeyH => Key::H, KeyCode::KeyI => Key::I,
1195 KeyCode::KeyJ => Key::J, KeyCode::KeyK => Key::K, KeyCode::KeyL => Key::L,
1196 KeyCode::KeyM => Key::M, KeyCode::KeyN => Key::N, KeyCode::KeyO => Key::O,
1197 KeyCode::KeyP => Key::P, KeyCode::KeyQ => Key::Q, KeyCode::KeyR => Key::R,
1198 KeyCode::KeyS => Key::S, KeyCode::KeyT => Key::T, KeyCode::KeyU => Key::U,
1199 KeyCode::KeyV => Key::V, KeyCode::KeyW => Key::W, KeyCode::KeyX => Key::X,
1200 KeyCode::KeyY => Key::Y, KeyCode::KeyZ => Key::Z,
1201 KeyCode::Digit1 => Key::Num1, KeyCode::Digit2 => Key::Num2,
1202 KeyCode::Digit3 => Key::Num3, KeyCode::Digit4 => Key::Num4,
1203 KeyCode::Digit5 => Key::Num5, KeyCode::Digit6 => Key::Num6,
1204 KeyCode::Digit7 => Key::Num7, KeyCode::Digit8 => Key::Num8,
1205 KeyCode::Digit9 => Key::Num9, KeyCode::Digit0 => Key::Num0,
1206 KeyCode::ArrowUp => Key::Up, KeyCode::ArrowDown => Key::Down,
1207 KeyCode::ArrowLeft => Key::Left, KeyCode::ArrowRight => Key::Right,
1208 KeyCode::Enter | KeyCode::NumpadEnter => Key::Enter,
1209 KeyCode::Escape => Key::Escape,
1210 KeyCode::Space => Key::Space,
1211 KeyCode::Backspace => Key::Backspace,
1212 KeyCode::Tab => Key::Tab,
1213 KeyCode::ShiftLeft => Key::LShift, KeyCode::ShiftRight => Key::RShift,
1214 KeyCode::ControlLeft => Key::LCtrl, KeyCode::ControlRight => Key::RCtrl,
1215 KeyCode::AltLeft => Key::LAlt, KeyCode::AltRight => Key::RAlt,
1216 KeyCode::F1 => Key::F1, KeyCode::F2 => Key::F2, KeyCode::F3 => Key::F3,
1217 KeyCode::F4 => Key::F4, KeyCode::F5 => Key::F5, KeyCode::F6 => Key::F6,
1218 KeyCode::F7 => Key::F7, KeyCode::F8 => Key::F8, KeyCode::F9 => Key::F9,
1219 KeyCode::F10 => Key::F10, KeyCode::F11 => Key::F11, KeyCode::F12 => Key::F12,
1220 KeyCode::Slash => Key::Slash,
1221 KeyCode::Backslash => Key::Backslash,
1222 KeyCode::Period => Key::Period,
1223 KeyCode::Comma => Key::Comma,
1224 KeyCode::Semicolon => Key::Semicolon,
1225 KeyCode::Quote => Key::Quote,
1226 KeyCode::BracketLeft => Key::LBracket,
1227 KeyCode::BracketRight => Key::RBracket,
1228 KeyCode::Minus => Key::Minus,
1229 KeyCode::Equal => Key::Equals,
1230 KeyCode::Backquote => Key::Backtick,
1231 KeyCode::PageUp => Key::PageUp,
1232 KeyCode::PageDown => Key::PageDown,
1233 KeyCode::Home => Key::Home,
1234 KeyCode::End => Key::End,
1235 KeyCode::Insert => Key::Insert,
1236 KeyCode::Delete => Key::Delete,
1237 _ => return None,
1238 })
1239}