forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBb0eb8adIvan Molodetskikh3 months ago2857 commits

shader_element.rs549 lines, 19.5 KiBHistoryRawDownload
1use std::collections::HashMap;
2use std::ffi::CString;
3use std::rc::Rc;
4
5use glam::{Mat3, Vec2};
6use smithay::backend::renderer::element::{Element, Id, Kind, RenderElement, UnderlyingStorage};
7use smithay::backend::renderer::gles::{
8 ffi, link_program, Capability, GlesError, GlesFrame, GlesRenderer, GlesTexture, Uniform,
9 UniformDesc, UniformName,
10};
11use smithay::backend::renderer::utils::{CommitCounter, OpaqueRegions};
12use smithay::backend::renderer::DebugFlags;
13use smithay::utils::user_data::UserDataMap;
14use smithay::utils::{Buffer, Logical, Physical, Point, Rectangle, Scale, Size};
15
16use super::renderer::AsGlesFrame;
17use super::resources::Resources;
18use super::shaders::{ProgramType, Shaders};
19use crate::backend::tty::{TtyFrame, TtyRenderer, TtyRendererError};
20
21/// Renders a shader with optional texture input, on the primary GPU.
22#[derive(Debug, Clone)]
23pub struct ShaderRenderElement {
24 program: ProgramType,
25 id: Id,
26 commit_counter: CommitCounter,
27 area: Rectangle<f64, Logical>,
28 opaque_regions: Vec<Rectangle<f64, Logical>>,
29 // Should only be used for visual improvements, i.e. corner radius anti-aliasing.
30 scale: f32,
31 alpha: f32,
32 additional_uniforms: Rc<[Uniform<'static>]>,
33 textures: HashMap<String, GlesTexture>,
34 kind: Kind,
35}
36
37#[derive(Debug, Clone)]
38pub struct ShaderProgram(Rc<ShaderProgramInner>);
39
40#[derive(Debug)]
41struct ShaderProgramInner {
42 normal: ShaderProgramInternal,
43 debug: ShaderProgramInternal,
44 uniform_tint: ffi::types::GLint,
45}
46
47#[derive(Debug)]
48struct ShaderProgramInternal {
49 program: ffi::types::GLuint,
50 uniform_tex_matrix: ffi::types::GLint,
51 uniform_matrix: ffi::types::GLint,
52 uniform_size: ffi::types::GLint,
53 uniform_scale: ffi::types::GLint,
54 uniform_alpha: ffi::types::GLint,
55 attrib_vert: ffi::types::GLint,
56 attrib_vert_position: ffi::types::GLint,
57 additional_uniforms: HashMap<String, UniformDesc>,
58 texture_uniforms: HashMap<String, ffi::types::GLint>,
59}
60
61impl PartialEq for ShaderProgram {
62 fn eq(&self, other: &Self) -> bool {
63 Rc::ptr_eq(&self.0, &other.0)
64 }
65}
66
67unsafe fn compile_program(
68 gl: &ffi::Gles2,
69 src: &str,
70 additional_uniforms: &[UniformName<'_>],
71 texture_uniforms: &[&str],
72 // destruction_callback_sender: Sender<CleanupResource>,
73) -> Result<ShaderProgram, GlesError> {
74 let shader = format!("#version 100\n{src}");
75 let program = unsafe { link_program(gl, include_str!("shaders/texture.vert"), &shader)? };
76 let debug_shader = format!("#version 100\n#define DEBUG_FLAGS\n{src}");
77 let debug_program =
78 unsafe { link_program(gl, include_str!("shaders/texture.vert"), &debug_shader)? };
79
80 let vert = c"vert";
81 let vert_position = c"vert_position";
82 let matrix = c"matrix";
83 let tex_matrix = c"tex_matrix";
84 let size = c"niri_size";
85 let scale = c"niri_scale";
86 let alpha = c"niri_alpha";
87 let tint = c"niri_tint";
88
89 Ok(ShaderProgram(Rc::new(ShaderProgramInner {
90 normal: ShaderProgramInternal {
91 program,
92 uniform_matrix: gl.GetUniformLocation(program, matrix.as_ptr()),
93 uniform_tex_matrix: gl.GetUniformLocation(program, tex_matrix.as_ptr()),
94 uniform_size: gl.GetUniformLocation(program, size.as_ptr()),
95 uniform_scale: gl.GetUniformLocation(program, scale.as_ptr()),
96 uniform_alpha: gl.GetUniformLocation(program, alpha.as_ptr()),
97 attrib_vert: gl.GetAttribLocation(program, vert.as_ptr()),
98 attrib_vert_position: gl.GetAttribLocation(program, vert_position.as_ptr()),
99 additional_uniforms: additional_uniforms
100 .iter()
101 .map(|uniform| {
102 let name =
103 CString::new(uniform.name.as_bytes()).expect("Interior null in name");
104 let location = gl.GetUniformLocation(program, name.as_ptr());
105 (
106 uniform.name.clone().into_owned(),
107 UniformDesc {
108 location,
109 type_: uniform.type_,
110 },
111 )
112 })
113 .collect(),
114 texture_uniforms: texture_uniforms
115 .iter()
116 .map(|name_| {
117 let name = CString::new(name_.as_bytes()).expect("Interior null in name");
118 let location = gl.GetUniformLocation(program, name.as_ptr());
119 (name_.to_string(), location)
120 })
121 .collect(),
122 },
123 debug: ShaderProgramInternal {
124 program: debug_program,
125 uniform_matrix: gl.GetUniformLocation(debug_program, matrix.as_ptr()),
126 uniform_tex_matrix: gl.GetUniformLocation(debug_program, tex_matrix.as_ptr()),
127 uniform_size: gl.GetUniformLocation(debug_program, size.as_ptr()),
128 uniform_scale: gl.GetUniformLocation(debug_program, scale.as_ptr()),
129 uniform_alpha: gl.GetUniformLocation(debug_program, alpha.as_ptr()),
130 attrib_vert: gl.GetAttribLocation(debug_program, vert.as_ptr()),
131 attrib_vert_position: gl.GetAttribLocation(debug_program, vert_position.as_ptr()),
132 additional_uniforms: additional_uniforms
133 .iter()
134 .map(|uniform| {
135 let name =
136 CString::new(uniform.name.as_bytes()).expect("Interior null in name");
137 let location = gl.GetUniformLocation(debug_program, name.as_ptr());
138 (
139 uniform.name.clone().into_owned(),
140 UniformDesc {
141 location,
142 type_: uniform.type_,
143 },
144 )
145 })
146 .collect(),
147 texture_uniforms: texture_uniforms
148 .iter()
149 .map(|name_| {
150 let name = CString::new(name_.as_bytes()).expect("Interior null in name");
151 let location = gl.GetUniformLocation(debug_program, name.as_ptr());
152 (name_.to_string(), location)
153 })
154 .collect(),
155 },
156 uniform_tint: gl.GetUniformLocation(debug_program, tint.as_ptr()),
157 })))
158}
159
160impl ShaderProgram {
161 pub fn compile(
162 renderer: &mut GlesRenderer,
163 src: &str,
164 additional_uniforms: &[UniformName<'_>],
165 texture_uniforms: &[&str],
166 ) -> Result<Self, GlesError> {
167 renderer.with_context(move |gl| unsafe {
168 compile_program(gl, src, additional_uniforms, texture_uniforms)
169 })?
170 }
171
172 pub fn destroy(self, renderer: &mut GlesRenderer) -> Result<(), GlesError> {
173 renderer.with_context(move |gl| unsafe {
174 gl.DeleteProgram(self.0.normal.program);
175 gl.DeleteProgram(self.0.debug.program);
176 })
177 }
178}
179
180impl ShaderRenderElement {
181 #[allow(clippy::too_many_arguments)]
182 pub fn new(
183 program: ProgramType,
184 size: Size<f64, Logical>,
185 opaque_regions: Option<Vec<Rectangle<f64, Logical>>>,
186 // Should only be used for visual improvements, i.e. corner radius anti-aliasing.
187 scale: f32,
188 alpha: f32,
189 additional_uniforms: Rc<[Uniform<'static>]>,
190 textures: HashMap<String, GlesTexture>,
191 kind: Kind,
192 ) -> Self {
193 Self {
194 program,
195 id: Id::new(),
196 commit_counter: CommitCounter::default(),
197 area: Rectangle::from_size(size),
198 opaque_regions: opaque_regions.unwrap_or_default(),
199 scale,
200 alpha,
201 additional_uniforms,
202 textures,
203 kind,
204 }
205 }
206
207 pub fn empty(program: ProgramType, kind: Kind) -> Self {
208 Self {
209 program,
210 id: Id::new(),
211 commit_counter: CommitCounter::default(),
212 area: Rectangle::default(),
213 opaque_regions: vec![],
214 scale: 1.,
215 alpha: 1.,
216 additional_uniforms: Rc::new([]),
217 textures: HashMap::new(),
218 kind,
219 }
220 }
221
222 pub fn damage_all(&mut self) {
223 self.commit_counter.increment();
224 }
225
226 pub fn update(
227 &mut self,
228 size: Size<f64, Logical>,
229 opaque_regions: Option<Vec<Rectangle<f64, Logical>>>,
230 scale: f32,
231 alpha: f32,
232 uniforms: Rc<[Uniform<'static>]>,
233 textures: HashMap<String, GlesTexture>,
234 ) {
235 self.area.size = size;
236 self.opaque_regions = opaque_regions.unwrap_or_default();
237 self.scale = scale;
238 self.alpha = alpha;
239 self.additional_uniforms = uniforms;
240 self.textures = textures;
241
242 self.commit_counter.increment();
243 }
244
245 pub fn with_location(mut self, location: Point<f64, Logical>) -> Self {
246 self.area.loc = location;
247 self
248 }
249
250 pub fn with_alpha(mut self, alpha: f32) -> Self {
251 self.alpha = alpha;
252 self
253 }
254}
255
256impl Element for ShaderRenderElement {
257 fn id(&self) -> &Id {
258 &self.id
259 }
260
261 fn current_commit(&self) -> CommitCounter {
262 self.commit_counter
263 }
264
265 fn src(&self) -> Rectangle<f64, Buffer> {
266 Rectangle::from_size(Size::from((1., 1.)))
267 }
268
269 fn geometry(&self, scale: Scale<f64>) -> Rectangle<i32, Physical> {
270 self.area.to_physical_precise_round(scale)
271 }
272
273 fn opaque_regions(&self, scale: Scale<f64>) -> OpaqueRegions<i32, Physical> {
274 self.opaque_regions
275 .iter()
276 .map(|region| region.to_physical_precise_down(scale))
277 .collect()
278 }
279
280 fn alpha(&self) -> f32 {
281 self.alpha
282 }
283
284 fn kind(&self) -> Kind {
285 self.kind
286 }
287}
288
289impl RenderElement<GlesRenderer> for ShaderRenderElement {
290 fn draw(
291 &self,
292 frame: &mut GlesFrame<'_, '_>,
293 src: Rectangle<f64, Buffer>,
294 dest: Rectangle<i32, Physical>,
295 damage: &[Rectangle<i32, Physical>],
296 _opaque_regions: &[Rectangle<i32, Physical>],
297 _cache: Option<&UserDataMap>,
298 ) -> Result<(), GlesError> {
299 let _span = tracy_client::span!("ShaderRenderElement::draw");
300
301 let frame = frame.as_gles_frame();
302
303 let Some(shader) = Shaders::get_from_frame(frame).program(self.program) else {
304 return Ok(());
305 };
306
307 let Some(resources) = Resources::get(frame) else {
308 return Ok(());
309 };
310 let mut resources = resources.borrow_mut();
311
312 let supports_instancing = frame.capabilities().contains(&Capability::Instancing);
313
314 // prepare the vertices
315 resources.vertices.clear();
316 if supports_instancing {
317 resources.vertices.extend(damage.iter().flat_map(|rect| {
318 let dest_size = dest.size;
319
320 let rect_constrained_loc = rect
321 .loc
322 .constrain(Rectangle::from_extremities((0, 0), dest_size.to_point()));
323 let rect_clamped_size = rect.size.clamp(
324 (0, 0),
325 (dest_size.to_point() - rect_constrained_loc).to_size(),
326 );
327
328 let rect = Rectangle::new(rect_constrained_loc, rect_clamped_size);
329 [
330 rect.loc.x as f32,
331 rect.loc.y as f32,
332 rect.size.w as f32,
333 rect.size.h as f32,
334 ]
335 }));
336 } else {
337 resources.vertices.extend(damage.iter().flat_map(|rect| {
338 let dest_size = dest.size;
339
340 let rect_constrained_loc = rect
341 .loc
342 .constrain(Rectangle::from_extremities((0, 0), dest_size.to_point()));
343 let rect_clamped_size = rect.size.clamp(
344 (0, 0),
345 (dest_size.to_point() - rect_constrained_loc).to_size(),
346 );
347
348 let rect = Rectangle::new(rect_constrained_loc, rect_clamped_size);
349 // Add the 4 f32s per damage rectangle for each of the 6 vertices.
350 (0..6).flat_map(move |_| {
351 [
352 rect.loc.x as f32,
353 rect.loc.y as f32,
354 rect.size.w as f32,
355 rect.size.h as f32,
356 ]
357 })
358 }));
359 }
360
361 if resources.vertices.is_empty() {
362 return Ok(());
363 }
364
365 // dest position and scale
366 let mut matrix = Mat3::from_translation(Vec2::new(dest.loc.x as f32, dest.loc.y as f32));
367
368 let scale = src.size.to_f64() / dest.size.to_f64();
369 let tex_matrix = Mat3::from_scale(Vec2::new(scale.x as f32, scale.y as f32));
370 let tex_matrix =
371 Mat3::from_translation(Vec2::new(src.loc.x as f32, src.loc.y as f32)) * tex_matrix;
372
373 //apply output transformation
374 matrix = Mat3::from_cols_array(frame.projection()) * matrix;
375
376 let has_debug = !frame.debug_flags().is_empty();
377 let has_tint = frame.debug_flags().contains(DebugFlags::TINT);
378
379 // render
380 let span_loc = smithay::gpu_span_location!("draw shader");
381 frame.with_profiled_context(span_loc, move |gl| -> Result<(), GlesError> {
382 let program = if has_debug {
383 &shader.0.debug
384 } else {
385 &shader.0.normal
386 };
387
388 unsafe {
389 for (i, texture) in self.textures.values().enumerate() {
390 gl.ActiveTexture(ffi::TEXTURE0 + i as u32);
391 gl.BindTexture(ffi::TEXTURE_2D, texture.tex_id());
392 gl.TexParameteri(ffi::TEXTURE_2D, ffi::TEXTURE_MIN_FILTER, ffi::LINEAR as i32);
393 gl.TexParameteri(ffi::TEXTURE_2D, ffi::TEXTURE_MAG_FILTER, ffi::LINEAR as i32);
394 gl.TexParameteri(
395 ffi::TEXTURE_2D,
396 ffi::TEXTURE_WRAP_S,
397 ffi::CLAMP_TO_BORDER as i32,
398 );
399 gl.TexParameteri(
400 ffi::TEXTURE_2D,
401 ffi::TEXTURE_WRAP_T,
402 ffi::CLAMP_TO_BORDER as i32,
403 );
404 }
405
406 gl.UseProgram(program.program);
407
408 for (i, name) in self.textures.keys().enumerate() {
409 gl.Uniform1i(program.texture_uniforms[name], i as i32);
410 }
411
412 gl.UniformMatrix3fv(
413 program.uniform_matrix,
414 1,
415 ffi::FALSE,
416 matrix.as_ref().as_ptr(),
417 );
418 gl.UniformMatrix3fv(
419 program.uniform_tex_matrix,
420 1,
421 ffi::FALSE,
422 tex_matrix.as_ref().as_ptr(),
423 );
424 gl.Uniform2f(program.uniform_size, dest.size.w as f32, dest.size.h as f32);
425 gl.Uniform1f(program.uniform_scale, self.scale);
426 gl.Uniform1f(program.uniform_alpha, self.alpha);
427
428 let tint = if has_tint { 1.0f32 } else { 0.0f32 };
429 if has_debug {
430 gl.Uniform1f(shader.0.uniform_tint, tint);
431 }
432
433 for uniform in &*self.additional_uniforms {
434 let desc =
435 program
436 .additional_uniforms
437 .get(&*uniform.name)
438 .ok_or_else(|| {
439 GlesError::UnknownUniform(uniform.name.clone().into_owned())
440 })?;
441 uniform.value.set(gl, desc)?;
442 }
443
444 gl.EnableVertexAttribArray(program.attrib_vert as u32);
445 gl.BindBuffer(ffi::ARRAY_BUFFER, resources.vbos[0]);
446 gl.VertexAttribPointer(
447 program.attrib_vert as u32,
448 2,
449 ffi::FLOAT,
450 ffi::FALSE,
451 0,
452 std::ptr::null(),
453 );
454
455 // vert_position
456 gl.EnableVertexAttribArray(program.attrib_vert_position as u32);
457 gl.BindBuffer(ffi::ARRAY_BUFFER, resources.vbos[1]);
458 gl.BufferData(
459 ffi::ARRAY_BUFFER,
460 (std::mem::size_of::<ffi::types::GLfloat>() * resources.vertices.len())
461 as isize,
462 resources.vertices.as_ptr() as *const _,
463 ffi::STREAM_DRAW,
464 );
465
466 gl.VertexAttribPointer(
467 program.attrib_vert_position as u32,
468 4,
469 ffi::FLOAT,
470 ffi::FALSE,
471 0,
472 std::ptr::null(),
473 );
474
475 let damage_len = damage.len() as i32;
476 if supports_instancing {
477 gl.VertexAttribDivisor(program.attrib_vert as u32, 0);
478 gl.VertexAttribDivisor(program.attrib_vert_position as u32, 1);
479 gl.DrawArraysInstanced(ffi::TRIANGLE_STRIP, 0, 4, damage_len);
480 } else {
481 // When we have more than 10 rectangles, draw them in batches of 10.
482 for i in 0..(damage_len - 1) / 10 {
483 gl.DrawArrays(ffi::TRIANGLES, 0, 6);
484
485 // Set damage pointer to the next 10 rectangles.
486 let offset =
487 (i + 1) as usize * 6 * 4 * std::mem::size_of::<ffi::types::GLfloat>();
488 gl.VertexAttribPointer(
489 program.attrib_vert_position as u32,
490 4,
491 ffi::FLOAT,
492 ffi::FALSE,
493 0,
494 offset as *const _,
495 );
496 }
497
498 // Draw the up to 10 remaining rectangles.
499 let count = ((damage_len - 1) % 10 + 1) * 6;
500 gl.DrawArrays(ffi::TRIANGLES, 0, count);
501 }
502
503 gl.BindBuffer(ffi::ARRAY_BUFFER, 0);
504 gl.BindTexture(ffi::TEXTURE_2D, 0);
505 gl.ActiveTexture(ffi::TEXTURE0);
506 gl.BindTexture(ffi::TEXTURE_2D, 0);
507 gl.DisableVertexAttribArray(program.attrib_vert as u32);
508 gl.DisableVertexAttribArray(program.attrib_vert_position as u32);
509 }
510
511 Ok(())
512 })??;
513
514 Ok(())
515 }
516
517 fn underlying_storage(&self, _renderer: &mut GlesRenderer) -> Option<UnderlyingStorage<'_>> {
518 // If scanout for things other than Wayland buffers is implemented, this will need to take
519 // the target GPU into account.
520 None
521 }
522}
523
524impl<'render> RenderElement<TtyRenderer<'render>> for ShaderRenderElement {
525 fn draw(
526 &self,
527 frame: &mut TtyFrame<'_, '_, '_>,
528 src: Rectangle<f64, Buffer>,
529 dst: Rectangle<i32, Physical>,
530 damage: &[Rectangle<i32, Physical>],
531 opaque_regions: &[Rectangle<i32, Physical>],
532 cache: Option<&UserDataMap>,
533 ) -> Result<(), TtyRendererError<'render>> {
534 let frame = frame.as_gles_frame();
535
536 RenderElement::<GlesRenderer>::draw(self, frame, src, dst, damage, opaque_regions, cache)?;
537
538 Ok(())
539 }
540
541 fn underlying_storage(
542 &self,
543 _renderer: &mut TtyRenderer<'render>,
544 ) -> Option<UnderlyingStorage<'_>> {
545 // If scanout for things other than Wayland buffers is implemented, this will need to take
546 // the target GPU into account.
547 None
548 }
549}