summaryrefslogtreecommitdiff
path: root/src/gfx/map.rs
blob: d95a4d27737aa9e3a6ea3b386703b192590d2d8b (plain)
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
use super::{media::MediaMgr, state::State, util::MatrixUniform};
use cgmath::{prelude::*, Matrix4, Point3, Vector3};
use mt_net::{MapBlock, NodeDef};
use rand::Rng;
use std::{collections::HashMap, ops::Range};
use wgpu::util::DeviceExt;

pub struct MapRender {
    pipeline: wgpu::RenderPipeline,
    textures: HashMap<String, [Range<f32>; 2]>,
    nodes: HashMap<u16, NodeDef>,
    atlas: wgpu::BindGroup,
    model: wgpu::BindGroupLayout,
    blocks: HashMap<[i16; 3], BlockMesh>,
}

#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct Vertex {
    pos: [f32; 3],
    tex_coords: [f32; 2],
}

impl Vertex {
    const ATTRIBS: [wgpu::VertexAttribute; 2] =
        wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x2];

    fn desc<'a>() -> wgpu::VertexBufferLayout<'a> {
        wgpu::VertexBufferLayout {
            array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
            step_mode: wgpu::VertexStepMode::Vertex,
            attributes: &Self::ATTRIBS,
        }
    }
}

struct BlockMesh {
    vertex_buffer: wgpu::Buffer,
    num_vertices: u32,
    model: MatrixUniform,
}

impl MapRender {
    pub fn render<'a>(&'a self, state: &'a State, pass: &mut wgpu::RenderPass<'a>) {
        pass.set_pipeline(&self.pipeline);
        pass.set_bind_group(0, &self.atlas, &[]);
        pass.set_bind_group(1, &state.camera_uniform.bind_group, &[]);

        for mesh in self.blocks.values() {
            pass.set_bind_group(2, &mesh.model.bind_group, &[]);
            pass.set_vertex_buffer(0, mesh.vertex_buffer.slice(..));
            pass.draw(0..mesh.num_vertices, 0..1);
        }
    }

    pub fn add_block(&mut self, state: &mut State, pos: Point3<i16>, block: Box<MapBlock>) {
        let mut vertices = Vec::with_capacity(10000);
        for (index, content) in block.param_0.iter().enumerate() {
            let def = match self.nodes.get(content) {
                Some(x) => x,
                None => continue,
            };

            use lerp::Lerp;
            use mt_net::DrawType;
            use std::array::from_fn as array;

            match def.draw_type {
                DrawType::Cube => {
                    let pos: [i16; 3] = array(|i| ((index >> (4 * i)) & 0xf) as i16);
                    for (f, face) in CUBE.iter().enumerate() {
                        let dir = FACE_DIR[f];
                        let npos: [i16; 3] = array(|i| dir[i] + pos[i]);
                        if npos.iter().all(|x| (0..16).contains(x)) {
                            let nindex = npos[0] | (npos[1] << 4) | (npos[2] << 8);

                            if let Some(ndef) = self.nodes.get(&block.param_0[nindex as usize]) {
                                if ndef.draw_type == DrawType::Cube {
                                    continue;
                                }
                            }
                        }

                        let tile = &def.tiles[f];
                        let rect = self.textures.get(&tile.texture).unwrap();

                        for vertex in face.iter() {
                            /*println!(
                                "{:?} {:?} {:?} {:?}",
                                (vertex.1[0], vertex.1[1]),
                                (rect[0].start, rect[1].start),
                                (rect[0].end, rect[1].end),
                                (
                                    vertex.1[0].lerp(rect[0].start, rect[0].end),
                                    vertex.1[1].lerp(rect[1].start, rect[1].end)
                                )
                            );*/
                            vertices.push(Vertex {
                                pos: array(|i| pos[i] as f32 - 8.5 + vertex.0[i]),
                                tex_coords: array(|i| rect[i].start.lerp(rect[i].end, vertex.1[i])),
                            })
                        }
                    }
                }
                DrawType::None => {}
                _ => {
                    // TODO
                }
            }
        }

        self.blocks.insert(
            pos.into(),
            BlockMesh {
                vertex_buffer: state
                    .device
                    .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                        label: Some("mapblock.vertex_buffer"),
                        contents: bytemuck::cast_slice(&vertices),
                        usage: wgpu::BufferUsages::VERTEX,
                    }),
                num_vertices: vertices.len() as u32,
                model: MatrixUniform::new(
                    &state.device,
                    &self.model,
                    Matrix4::from_translation(
                        pos.cast::<f32>().unwrap().to_vec() * 16.0 + Vector3::new(8.5, 8.5, 8.5),
                    ),
                    "mapblock",
                    false,
                ),
            },
        );
    }

    pub fn new(state: &mut State, media: &MediaMgr, nodes: HashMap<u16, NodeDef>) -> Self {
        let mut rng = rand::thread_rng();
        let mut atlas_map = HashMap::new();
        let mut atlas_alloc = guillotiere::SimpleAtlasAllocator::new(guillotiere::size2(1, 1));

        for node in nodes.values() {
            let tiles = node
                .tiles
                .iter()
                .chain(node.overlay_tiles.iter())
                .chain(node.special_tiles.iter());

            let load_texture = |texture: &str| {
                let payload = media
                    .get(texture)
                    .ok_or_else(|| format!("texture not found: {texture}"))?;

                image::load_from_memory(payload)
                    .or_else(|_| {
                        image::load_from_memory_with_format(payload, image::ImageFormat::Tga)
                    })
                    .map_err(|e| format!("failed to load texture {texture}: {e}"))
                    .map(|x| image::imageops::flip_vertical(&x))
            };

            let mut make_texture = |texture: &str| {
                texture
                    .split('^')
                    .map(|part| match load_texture(part) {
                        Ok(v) => v,
                        Err(e) => {
                            if !texture.is_empty() && !texture.contains('[') {
                                eprintln!("{e}");
                            }

                            let mut img = image::RgbImage::new(1, 1);
                            rng.fill(&mut img.get_pixel_mut(0, 0).0);

                            image::DynamicImage::from(img).to_rgba8()
                        }
                    })
                    .reduce(|mut base, top| {
                        image::imageops::overlay(&mut base, &top, 0, 0);
                        base
                    })
                    .unwrap()
            };

            for tile in tiles {
                atlas_map.entry(tile.texture.clone()).or_insert_with(|| {
                    let img = make_texture(&tile.texture);

                    let dimensions = img.dimensions();
                    let size = guillotiere::size2(dimensions.0 as i32, dimensions.1 as i32);

                    loop {
                        match atlas_alloc.allocate(size) {
                            None => {
                                let mut atlas_size = atlas_alloc.size();
                                atlas_size.width *= 2;
                                atlas_size.height *= 2;
                                atlas_alloc.grow(atlas_size);
                            }
                            Some(v) => return (img, v),
                        }
                    }
                });
            }
        }

        let atlas_size = atlas_alloc.size();
        let mut atlas = image::RgbaImage::new(atlas_size.width as u32, atlas_size.height as u32);

        let textures = atlas_map
            .into_iter()
            .map(|(name, (img, rect))| {
                let w = atlas_size.width as f32;
                let h = atlas_size.height as f32;

                let x = (rect.min.x as f32 / w)..(rect.max.x as f32 / w);
                let y = (rect.min.y as f32 / h)..(rect.max.y as f32 / h);

                use image::GenericImage;
                atlas
                    .copy_from(&img, rect.min.x as u32, rect.min.y as u32)
                    .unwrap();

                (name, [x, y])
            })
            .collect();

        let size = wgpu::Extent3d {
            width: atlas_size.width as u32,
            height: atlas_size.height as u32,
            depth_or_array_layers: 1,
        };

        let atlas_texture = state.device.create_texture(&wgpu::TextureDescriptor {
            size,
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba8UnormSrgb,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            label: Some("tile_atlas"),
            view_formats: &[],
        });

        state.queue.write_texture(
            wgpu::ImageCopyTexture {
                texture: &atlas_texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            &atlas,
            wgpu::ImageDataLayout {
                offset: 0,
                bytes_per_row: std::num::NonZeroU32::new(4 * atlas_size.width as u32),
                rows_per_image: std::num::NonZeroU32::new(atlas_size.height as u32),
            },
            size,
        );

        let atlas_view = atlas_texture.create_view(&wgpu::TextureViewDescriptor::default());

        let atlas_sampler = state.device.create_sampler(&wgpu::SamplerDescriptor {
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            address_mode_w: wgpu::AddressMode::ClampToEdge,
            // "We've got you surrounded, stop using Nearest filter"
            // - "I hate bilinear filtering I hate bilinear filtering I hate bilinear filtering"
            mag_filter: wgpu::FilterMode::Nearest,
            min_filter: wgpu::FilterMode::Nearest,
            mipmap_filter: wgpu::FilterMode::Nearest,
            ..Default::default()
        });

        let atlas_bind_group_layout =
            state
                .device
                .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                    entries: &[
                        wgpu::BindGroupLayoutEntry {
                            binding: 0,
                            visibility: wgpu::ShaderStages::FRAGMENT,
                            ty: wgpu::BindingType::Texture {
                                multisampled: false,
                                view_dimension: wgpu::TextureViewDimension::D2,
                                sample_type: wgpu::TextureSampleType::Float { filterable: true },
                            },
                            count: None,
                        },
                        wgpu::BindGroupLayoutEntry {
                            binding: 1,
                            visibility: wgpu::ShaderStages::FRAGMENT,
                            ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                            count: None,
                        },
                    ],
                    label: Some("atlas.bind_group_layout"),
                });

        let atlas_bind_group = state.device.create_bind_group(&wgpu::BindGroupDescriptor {
            layout: &atlas_bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&atlas_view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&atlas_sampler),
                },
            ],
            label: Some("atlas.bind_group"),
        });

        let model_bind_group_layout = MatrixUniform::layout(&state.device, "mapblock");

        let shader = state
            .device
            .create_shader_module(wgpu::include_wgsl!("../../assets/shaders/map.wgsl"));

        let pipeline_layout =
            state
                .device
                .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                    label: None,
                    bind_group_layouts: &[
                        &atlas_bind_group_layout,
                        &model_bind_group_layout,
                        &state.camera_bind_group_layout,
                    ],
                    push_constant_ranges: &[],
                });

        let pipeline = state
            .device
            .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: None,
                layout: Some(&pipeline_layout),
                vertex: wgpu::VertexState {
                    module: &shader,
                    entry_point: "vs_main",
                    buffers: &[Vertex::desc()],
                },
                fragment: Some(wgpu::FragmentState {
                    module: &shader,
                    entry_point: "fs_main",
                    targets: &[Some(wgpu::ColorTargetState {
                        format: state.config.format,
                        blend: Some(wgpu::BlendState::REPLACE),
                        write_mask: wgpu::ColorWrites::ALL,
                    })],
                }),
                primitive: wgpu::PrimitiveState {
                    topology: wgpu::PrimitiveTopology::TriangleList,
                    strip_index_format: None,
                    front_face: wgpu::FrontFace::Ccw,
                    cull_mode: Some(wgpu::Face::Back),
                    polygon_mode: wgpu::PolygonMode::Fill,
                    unclipped_depth: false,
                    conservative: false,
                },
                depth_stencil: Some(wgpu::DepthStencilState {
                    format: wgpu::TextureFormat::Depth32Float,
                    depth_write_enabled: true,
                    depth_compare: wgpu::CompareFunction::Less,
                    stencil: wgpu::StencilState::default(),
                    bias: wgpu::DepthBiasState::default(),
                }),
                multisample: wgpu::MultisampleState {
                    count: 1,
                    mask: !0,
                    alpha_to_coverage_enabled: false,
                },
                multiview: None,
            });

        Self {
            pipeline,
            nodes,
            textures,
            atlas: atlas_bind_group,
            model: model_bind_group_layout,
            blocks: HashMap::new(),
        }
    }
}

#[rustfmt::skip]
const CUBE: [[([f32; 3], [f32; 2]); 6]; 6] = [
	[
		([-0.5,  0.5, -0.5], [ 0.0,  1.0]),
		([ 0.5,  0.5,  0.5], [ 1.0,  0.0]),
		([ 0.5,  0.5, -0.5], [ 1.0,  1.0]),
		([ 0.5,  0.5,  0.5], [ 1.0,  0.0]),
		([-0.5,  0.5, -0.5], [ 0.0,  1.0]),
		([-0.5,  0.5,  0.5], [ 0.0,  0.0]),
	],
	[
		([-0.5, -0.5, -0.5], [ 0.0,  1.0]),
		([ 0.5, -0.5, -0.5], [ 1.0,  1.0]),
		([ 0.5, -0.5,  0.5], [ 1.0,  0.0]),
		([ 0.5, -0.5,  0.5], [ 1.0,  0.0]),
		([-0.5, -0.5,  0.5], [ 0.0,  0.0]),
		([-0.5, -0.5, -0.5], [ 0.0,  1.0]),
	],
	[
		([ 0.5,  0.5,  0.5], [ 1.0,  1.0]),
		([ 0.5, -0.5, -0.5], [ 0.0,  0.0]),
		([ 0.5,  0.5, -0.5], [ 0.0,  1.0]),
		([ 0.5, -0.5, -0.5], [ 0.0,  0.0]),
		([ 0.5,  0.5,  0.5], [ 1.0,  1.0]),
		([ 0.5, -0.5,  0.5], [ 1.0,  0.0]),
	],
	[
		([-0.5,  0.5,  0.5], [ 1.0,  1.0]),
		([-0.5,  0.5, -0.5], [ 0.0,  1.0]),
		([-0.5, -0.5, -0.5], [ 0.0,  0.0]),
		([-0.5, -0.5, -0.5], [ 0.0,  0.0]),
		([-0.5, -0.5,  0.5], [ 1.0,  0.0]),
		([-0.5,  0.5,  0.5], [ 1.0,  1.0]),
	],
	[
		([-0.5, -0.5,  0.5], [ 0.0,  0.0]),
		([ 0.5, -0.5,  0.5], [ 1.0,  0.0]),
		([ 0.5,  0.5,  0.5], [ 1.0,  1.0]),
		([ 0.5,  0.5,  0.5], [ 1.0,  1.0]),
		([-0.5,  0.5,  0.5], [ 0.0,  1.0]),
		([-0.5, -0.5,  0.5], [ 0.0,  0.0]),
	],
	[
		([-0.5, -0.5, -0.5], [ 0.0,  0.0]),
		([ 0.5,  0.5, -0.5], [ 1.0,  1.0]),
		([ 0.5, -0.5, -0.5], [ 1.0,  0.0]),
		([ 0.5,  0.5, -0.5], [ 1.0,  1.0]),
		([-0.5, -0.5, -0.5], [ 0.0,  0.0]),
		([-0.5,  0.5, -0.5], [ 0.0,  1.0]),
	],
];

#[rustfmt::skip]
const FACE_DIR: [[i16; 3]; 6] = [
	[ 0,  1,  0],
	[ 0, -1,  0],
	[ 1,  0,  0],
	[-1,  0,  0],
	[ 0,  0,  1],
	[ 0,  0, -1],
];