1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
//     https://www.apache.org/licenses/LICENSE-2.0

//! Drawing API for `kas_wgpu`

use std::any::Any;
use std::f32::consts::FRAC_PI_2;
use wgpu::TextureView;
use wgpu_glyph::GlyphBrushBuilder;

use super::{
    flat_round, shaded_round, shaded_square, CustomPipe, CustomPipeBuilder, CustomWindow, DrawPipe,
    DrawWindow, ShaderManager, TEX_FORMAT,
};
use kas::draw::{Colour, Draw, DrawRounded, DrawShaded, DrawShared, Pass};
use kas::geom::{Coord, Quad, Rect, Size, Vec2};

fn make_depth_texture(device: &wgpu::Device, size: Size) -> Option<TextureView> {
    // NOTE: initially the DrawWindow is created with Size::ZERO to calculate
    // initial window size. Wgpu does not support creation of zero-sized
    // textures, so as a special case we return None here:
    if size.0 * size.1 == 0 {
        return None;
    }

    let tex = device.create_texture(&wgpu::TextureDescriptor {
        size: wgpu::Extent3d {
            width: size.0,
            height: size.1,
            depth: 1,
        },
        array_layer_count: 1,
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: super::DEPTH_FORMAT,
        usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT,
        label: None,
    });
    Some(tex.create_default_view())
}

impl<C: CustomPipe> DrawPipe<C> {
    /// Construct
    pub fn new<CB: CustomPipeBuilder<Pipe = C>>(
        mut custom: CB,
        device: &wgpu::Device,
        shaders: &ShaderManager,
    ) -> Self {
        let shaded_square = shaded_square::Pipeline::new(device, shaders);
        let shaded_round = shaded_round::Pipeline::new(device, shaders);
        let flat_round = flat_round::Pipeline::new(device, shaders);
        let custom = custom.build(&device, TEX_FORMAT, super::DEPTH_FORMAT);

        DrawPipe {
            fonts: vec![],
            shaded_square,
            shaded_round,
            flat_round,
            custom,
        }
    }

    /// Construct per-window state
    // TODO: device should be &, not &mut (but for glyph_brush)
    pub fn new_window(&self, device: &wgpu::Device, size: Size) -> DrawWindow<C::Window> {
        // Light dir: `(a, b)` where `0 ≤ a < pi/2` is the angle to the screen
        // normal (i.e. `a = 0` is straight at the screen) and `b` is the bearing
        // (from UP, clockwise), both in radians.
        let dir: (f32, f32) = (0.3, 0.4);
        assert!(dir.0 >= 0.0);
        assert!(dir.0 < FRAC_PI_2);
        let a = (dir.0.sin(), dir.0.cos());
        // We normalise intensity:
        let f = a.0 / a.1;
        let norm = [dir.1.sin() * f, -dir.1.cos() * f, 1.0];

        let rect = Rect {
            pos: Coord::ZERO,
            size,
        };

        let shaded_square = self.shaded_square.new_window(device, size, norm);
        let shaded_round = self.shaded_round.new_window(device, size, norm);
        let flat_round = self.flat_round.new_window(device, size);
        let custom = self.custom.new_window(device, size);

        let glyph_brush = GlyphBrushBuilder::using_fonts(self.fonts.clone())
            .depth_stencil_state(super::GLPYH_DEPTH_DESC)
            .build(device, TEX_FORMAT);

        DrawWindow {
            depth: make_depth_texture(device, size),
            clip_regions: vec![rect],
            shaded_square,
            shaded_round,
            flat_round,
            custom,
            glyph_brush,
        }
    }

    /// Process window resize
    pub fn resize(
        &self,
        window: &mut DrawWindow<C::Window>,
        device: &wgpu::Device,
        size: Size,
    ) -> wgpu::CommandBuffer {
        window.depth = make_depth_texture(device, size);
        window.clip_regions[0].size = size;
        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("resize"),
        });
        window.shaded_square.resize(device, &mut encoder, size);
        window.shaded_round.resize(device, &mut encoder, size);
        self.custom
            .resize(&mut window.custom, device, &mut encoder, size);
        window.flat_round.resize(device, &mut encoder, size);
        encoder.finish()
    }

    /// Render batched draw instructions via `rpass`
    pub fn render(
        &self,
        window: &mut DrawWindow<C::Window>,
        device: &mut wgpu::Device,
        frame_view: &wgpu::TextureView,
        clear_color: wgpu::Color,
    ) -> wgpu::CommandBuffer {
        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("render"),
        });

        self.custom.update(&mut window.custom, device, &mut encoder);

        let mut color_attachments = [wgpu::RenderPassColorAttachmentDescriptor {
            attachment: frame_view,
            resolve_target: None,
            load_op: wgpu::LoadOp::Clear,
            store_op: wgpu::StoreOp::Store,
            clear_color,
        }];
        let mut depth_stencil_attachment = wgpu::RenderPassDepthStencilAttachmentDescriptor {
            attachment: window.depth.as_ref().unwrap(),
            depth_load_op: wgpu::LoadOp::Clear,
            depth_store_op: wgpu::StoreOp::Store,
            stencil_load_op: wgpu::LoadOp::Clear,
            stencil_store_op: wgpu::StoreOp::Store,
            clear_depth: kas_theme::START_PASS.depth(),
            clear_stencil: 0,
        };

        // We use a separate render pass for each clipped region.
        for (pass, rect) in window.clip_regions.iter().enumerate() {
            let ss = self
                .shaded_square
                .render_buf(&mut window.shaded_square, device, pass);
            let sr = self
                .shaded_round
                .render_buf(&mut window.shaded_round, device, pass);
            let fr = self
                .flat_round
                .render_buf(&mut window.flat_round, device, pass);

            {
                let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                    color_attachments: &color_attachments,
                    depth_stencil_attachment: Some(depth_stencil_attachment.clone()),
                });
                rpass.set_scissor_rect(
                    rect.pos.0 as u32,
                    rect.pos.1 as u32,
                    rect.size.0,
                    rect.size.1,
                );

                ss.as_ref().map(|buf| buf.render(&mut rpass));
                sr.as_ref().map(|buf| buf.render(&mut rpass));
                fr.as_ref().map(|buf| buf.render(&mut rpass));
                self.custom
                    .render_pass(&mut window.custom, device, pass, &mut rpass);
            }

            color_attachments[0].load_op = wgpu::LoadOp::Load;
            depth_stencil_attachment.depth_load_op = wgpu::LoadOp::Load;
            depth_stencil_attachment.stencil_load_op = wgpu::LoadOp::Load;
        }

        // Fonts and custom pipes use their own render pass(es).
        let size = window.clip_regions[0].size;

        self.custom.render_final(
            &mut window.custom,
            device,
            &mut encoder,
            frame_view,
            depth_stencil_attachment.clone(),
            size,
        );

        window
            .glyph_brush
            .draw_queued(
                device,
                &mut encoder,
                frame_view,
                depth_stencil_attachment,
                size.0,
                size.1,
            )
            .expect("glyph_brush.draw_queued");

        // Keep only first clip region (which is the entire window)
        window.clip_regions.truncate(1);

        encoder.finish()
    }
}

impl<C: CustomPipe> DrawShared for DrawPipe<C> {
    type Draw = DrawWindow<C::Window>;
}

impl<CW: CustomWindow + 'static> Draw for DrawWindow<CW> {
    #[inline]
    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn add_clip_region(&mut self, rect: Rect, depth: f32) -> Pass {
        let pass = self.clip_regions.len();
        self.clip_regions.push(rect);
        Pass::new_pass_with_depth(pass as u32, depth)
    }

    #[inline]
    fn rect(&mut self, pass: Pass, rect: Quad, col: Colour) {
        self.shaded_square.rect(pass, rect, col);
    }

    #[inline]
    fn frame(&mut self, pass: Pass, outer: Quad, inner: Quad, col: Colour) {
        self.shaded_square.frame(pass, outer, inner, col);
    }
}

impl<CW: CustomWindow + 'static> DrawRounded for DrawWindow<CW> {
    #[inline]
    fn rounded_line(&mut self, pass: Pass, p1: Vec2, p2: Vec2, radius: f32, col: Colour) {
        self.flat_round.line(pass, p1, p2, radius, col);
    }

    #[inline]
    fn circle(&mut self, pass: Pass, rect: Quad, inner_radius: f32, col: Colour) {
        self.flat_round.circle(pass, rect, inner_radius, col);
    }

    #[inline]
    fn rounded_frame(
        &mut self,
        pass: Pass,
        outer: Quad,
        inner: Quad,
        inner_radius: f32,
        col: Colour,
    ) {
        self.flat_round
            .rounded_frame(pass, outer, inner, inner_radius, col);
    }
}

impl<CW: CustomWindow + 'static> DrawShaded for DrawWindow<CW> {
    #[inline]
    fn shaded_square(&mut self, pass: Pass, rect: Quad, norm: (f32, f32), col: Colour) {
        self.shaded_square
            .shaded_rect(pass, rect, Vec2::from(norm), col);
    }

    #[inline]
    fn shaded_circle(&mut self, pass: Pass, rect: Quad, norm: (f32, f32), col: Colour) {
        self.shaded_round.circle(pass, rect, Vec2::from(norm), col);
    }

    #[inline]
    fn shaded_square_frame(
        &mut self,
        pass: Pass,
        outer: Quad,
        inner: Quad,
        norm: (f32, f32),
        col: Colour,
    ) {
        self.shaded_square
            .shaded_frame(pass, outer, inner, Vec2::from(norm), col);
    }

    #[inline]
    fn shaded_round_frame(
        &mut self,
        pass: Pass,
        outer: Quad,
        inner: Quad,
        norm: (f32, f32),
        col: Colour,
    ) {
        self.shaded_round
            .shaded_frame(pass, outer, inner, Vec2::from(norm), col);
    }
}