Mercurial > touhou
comparison examples/stdrenderer.rs @ 679:6020e33d4fc4
Implement a .std renderer, and its associated VM.
author | Emmanuel Gil Peyrot <linkmauve@linkmauve.fr> |
---|---|
date | Fri, 16 Aug 2019 13:40:38 +0200 |
parents | |
children | ef2dbd676a91 |
comparison
equal
deleted
inserted
replaced
678:1d81a449c436 | 679:6020e33d4fc4 |
---|---|
1 use image::GenericImageView; | |
2 use luminance::context::GraphicsContext; | |
3 use luminance::framebuffer::Framebuffer; | |
4 use luminance::pipeline::BoundTexture; | |
5 use luminance::pixel::{NormRGB8UI, Floating}; | |
6 use luminance::render_state::RenderState; | |
7 use luminance::shader::program::{Program, Uniform}; | |
8 use luminance::tess::{Mode, TessBuilder, TessSliceIndex}; | |
9 use luminance::texture::{Dim2, Flat, Sampler, Texture, GenMipmaps}; | |
10 use luminance_derive::{Semantics, Vertex, UniformInterface}; | |
11 use luminance_glfw::event::{Action, Key, WindowEvent}; | |
12 use luminance_glfw::surface::{GlfwSurface, Surface, WindowDim, WindowOpt}; | |
13 use touhou::th06::anm0::Anm0; | |
14 use touhou::th06::anm0_vm::{AnmRunner, Sprite, Vertex as FakeVertex}; | |
15 use touhou::th06::std::{Stage, Position}; | |
16 use touhou::th06::std_vm::StageRunner; | |
17 use touhou::util::prng::Prng; | |
18 use touhou::util::math::perspective; | |
19 use std::cell::RefCell; | |
20 use std::fs::File; | |
21 use std::io::{BufReader, Read}; | |
22 use std::rc::Rc; | |
23 use std::env; | |
24 use std::path::Path; | |
25 | |
26 const VS: &str = r#" | |
27 in ivec3 in_position; | |
28 in vec2 in_texcoord; | |
29 in uvec4 in_color; | |
30 | |
31 uniform mat4 mvp; | |
32 uniform vec3 instance_position; | |
33 | |
34 out vec2 texcoord; | |
35 out vec4 color; | |
36 | |
37 void main() | |
38 { | |
39 vec3 position = vec3(in_position) + instance_position; | |
40 gl_Position = mvp * vec4(position, 1.0); | |
41 texcoord = vec2(in_texcoord); | |
42 | |
43 // Normalized from the u8 being passed. | |
44 color = vec4(in_color) / 255.; | |
45 } | |
46 "#; | |
47 | |
48 const FS: &str = r#" | |
49 in vec2 texcoord; | |
50 in vec4 color; | |
51 | |
52 uniform sampler2D color_map; | |
53 uniform float fog_scale; | |
54 uniform float fog_end; | |
55 uniform vec4 fog_color; | |
56 | |
57 out vec4 frag_color; | |
58 | |
59 void main() | |
60 { | |
61 vec4 temp_color = texture(color_map, texcoord) * color; | |
62 float depth = gl_FragCoord.z / gl_FragCoord.w; | |
63 float fog_density = clamp((fog_end - depth) * fog_scale, 0.0, 1.0); | |
64 frag_color = vec4(mix(fog_color, temp_color, fog_density).rgb, temp_color.a); | |
65 } | |
66 "#; | |
67 | |
68 #[derive(Clone, Copy, Debug, Eq, PartialEq, Semantics)] | |
69 pub enum Semantics { | |
70 #[sem(name = "in_position", repr = "[i16; 3]", wrapper = "VertexPosition")] | |
71 Position, | |
72 | |
73 #[sem(name = "in_texcoord", repr = "[f32; 2]", wrapper = "VertexTexcoord")] | |
74 Texcoord, | |
75 | |
76 #[sem(name = "in_color", repr = "[u8; 4]", wrapper = "VertexColor")] | |
77 Color, | |
78 } | |
79 | |
80 #[repr(C)] | |
81 #[derive(Clone, Copy, Debug, PartialEq, Vertex)] | |
82 #[vertex(sem = "Semantics")] | |
83 struct Vertex { | |
84 pos: VertexPosition, | |
85 uv: VertexTexcoord, | |
86 rgba: VertexColor, | |
87 } | |
88 | |
89 #[derive(UniformInterface)] | |
90 struct ShaderInterface { | |
91 // the 'static lifetime acts as “anything” here | |
92 color_map: Uniform<&'static BoundTexture<'static, Flat, Dim2, Floating>>, | |
93 | |
94 #[uniform(name = "mvp")] | |
95 mvp: Uniform<[[f32; 4]; 4]>, | |
96 | |
97 #[uniform(name = "instance_position")] | |
98 instance_position: Uniform<[f32; 3]>, | |
99 | |
100 #[uniform(name = "fog_scale")] | |
101 fog_scale: Uniform<f32>, | |
102 | |
103 #[uniform(name = "fog_end")] | |
104 fog_end: Uniform<f32>, | |
105 | |
106 #[uniform(name = "fog_color")] | |
107 fog_color: Uniform<[f32; 4]>, | |
108 } | |
109 | |
110 fn main() { | |
111 // Parse arguments. | |
112 let args: Vec<_> = env::args().collect(); | |
113 if args.len() != 4 { | |
114 eprintln!("Usage: {} <STD file> <ANM file> <PNG file>", args[0]); | |
115 return; | |
116 } | |
117 let std_filename = &args[1]; | |
118 let anm_filename = &args[2]; | |
119 let png_filename = &args[3]; | |
120 | |
121 // Open the STD file. | |
122 let file = File::open(std_filename).unwrap(); | |
123 let mut file = BufReader::new(file); | |
124 let mut buf = vec![]; | |
125 file.read_to_end(&mut buf).unwrap(); | |
126 let (_, stage) = Stage::from_slice(&buf).unwrap(); | |
127 | |
128 // Open the ANM file. | |
129 let file = File::open(anm_filename).unwrap(); | |
130 let mut file = BufReader::new(file); | |
131 let mut buf = vec![]; | |
132 file.read_to_end(&mut buf).unwrap(); | |
133 let anm0 = Anm0::from_slice(&buf).unwrap(); | |
134 | |
135 // TODO: seed this PRNG with a valid seed. | |
136 let prng = Rc::new(RefCell::new(Prng::new(0))); | |
137 | |
138 assert_eq!(std::mem::size_of::<Vertex>(), std::mem::size_of::<FakeVertex>()); | |
139 let mut vertices: Vec<Vertex> = vec![]; | |
140 let mut indices = vec![]; | |
141 | |
142 { | |
143 for model in stage.models.iter() { | |
144 let begin = vertices.len(); | |
145 for quad in model.quads.iter() { | |
146 let Position { x, y, z } = quad.pos; | |
147 | |
148 // Create the AnmRunner from the ANM and the sprite. | |
149 let sprite = Rc::new(RefCell::new(Sprite::new())); | |
150 let _anm_runner = AnmRunner::new(&anm0, quad.anm_script as u8, sprite.clone(), Rc::downgrade(&prng), 0); | |
151 let mut new_vertices: [Vertex; 6] = unsafe { std::mem::uninitialized() }; | |
152 fill_vertices(sprite.clone(), &mut new_vertices, x, y, z); | |
153 new_vertices[4] = new_vertices[0]; | |
154 new_vertices[5] = new_vertices[2]; | |
155 vertices.extend(&new_vertices); | |
156 } | |
157 let end = vertices.len(); | |
158 indices.push((begin, end)); | |
159 } | |
160 } | |
161 | |
162 let mut stage_runner = StageRunner::new(Rc::new(RefCell::new(stage))); | |
163 | |
164 let mut surface = GlfwSurface::new(WindowDim::Windowed(384, 448), "Touhou", WindowOpt::default()).unwrap(); | |
165 | |
166 // Open the image atlas matching this ANM. | |
167 let tex = load_from_disk(&mut surface, Path::new(png_filename)).expect("texture loading"); | |
168 | |
169 // set the uniform interface to our type so that we can read textures from the shader | |
170 let (program, _) = | |
171 Program::<Semantics, (), ShaderInterface>::from_strings(None, VS, None, FS).expect("program creation"); | |
172 | |
173 let tess = TessBuilder::new(&mut surface) | |
174 .add_vertices(vertices) | |
175 .set_mode(Mode::Triangle) | |
176 .build() | |
177 .unwrap(); | |
178 | |
179 let mut back_buffer = Framebuffer::back_buffer(surface.size()); | |
180 | |
181 'app: loop { | |
182 for event in surface.poll_events() { | |
183 match event { | |
184 WindowEvent::Close | WindowEvent::Key(Key::Escape, _, Action::Release, _) => break 'app, | |
185 | |
186 WindowEvent::FramebufferSize(width, height) => { | |
187 back_buffer = Framebuffer::back_buffer([width as u32, height as u32]); | |
188 } | |
189 | |
190 _ => (), | |
191 } | |
192 } | |
193 | |
194 { | |
195 stage_runner.run_frame(); | |
196 //let sprites = stage.get_sprites(); | |
197 //fill_vertices_ptr(sprites, slice.as_mut_ptr()); | |
198 } | |
199 | |
200 // here, we need to bind the pipeline variable; it will enable us to bind the texture to the GPU | |
201 // and use it in the shader | |
202 surface | |
203 .pipeline_builder() | |
204 .pipeline(&back_buffer, [0., 0., 0., 0.], |pipeline, shd_gate| { | |
205 // bind our fancy texture to the GPU: it gives us a bound texture we can use with the shader | |
206 let bound_tex = pipeline.bind_texture(&tex); | |
207 | |
208 shd_gate.shade(&program, |rdr_gate, iface| { | |
209 // update the texture; strictly speaking, this update doesn’t do much: it just tells the GPU | |
210 // to use the texture passed as argument (no allocation or copy is performed) | |
211 iface.color_map.update(&bound_tex); | |
212 | |
213 let proj = perspective(0.5235987755982988, 384. / 448., 101010101./2010101., 101010101./10101.); | |
214 let model_view = stage_runner.get_model_view(); | |
215 let mvp = model_view * proj; | |
216 // TODO: check how to pass by reference. | |
217 iface.mvp.update(*mvp.borrow_inner()); | |
218 | |
219 let near = stage_runner.fog_near - 101010101. / 2010101.; | |
220 let far = stage_runner.fog_far - 101010101. / 2010101.; | |
221 iface.fog_color.update(stage_runner.fog_color); | |
222 iface.fog_scale.update(1. / (far - near)); | |
223 iface.fog_end.update(far); | |
224 | |
225 let stage = stage_runner.stage.borrow(); | |
226 for instance in stage.instances.iter() { | |
227 iface.instance_position.update([instance.pos.x, instance.pos.y, instance.pos.z]); | |
228 | |
229 rdr_gate.render(RenderState::default(), |tess_gate| { | |
230 let (begin, end) = indices[instance.id as usize]; | |
231 tess_gate.render(&mut surface, tess.slice(begin..end)); | |
232 }); | |
233 } | |
234 }); | |
235 }); | |
236 | |
237 surface.swap_buffers(); | |
238 } | |
239 } | |
240 | |
241 fn fill_vertices(sprite: Rc<RefCell<Sprite>>, vertices: &mut [Vertex; 6], x: f32, y: f32, z: f32) { | |
242 let mut fake_vertices = unsafe { std::mem::transmute::<&mut [Vertex; 6], &mut [FakeVertex; 4]>(vertices) }; | |
243 let sprite = sprite.borrow(); | |
244 sprite.fill_vertices(&mut fake_vertices, x, y, z); | |
245 } | |
246 | |
247 fn load_from_disk(surface: &mut GlfwSurface, path: &Path) -> Option<Texture<Flat, Dim2, NormRGB8UI>> { | |
248 // load the texture into memory as a whole bloc (i.e. no streaming) | |
249 match image::open(&path) { | |
250 Ok(img) => { | |
251 let (width, height) = img.dimensions(); | |
252 let texels = img | |
253 .pixels() | |
254 .map(|(_x, _y, rgb)| (rgb[0], rgb[1], rgb[2])) | |
255 .collect::<Vec<_>>(); | |
256 | |
257 // create the luminance texture; the third argument is the number of mipmaps we want (leave it | |
258 // to 0 for now) and the latest is a the sampler to use when sampling the texels in the | |
259 // shader (we’ll just use the default one) | |
260 let tex = | |
261 Texture::new(surface, [width, height], 0, &Sampler::default()).expect("luminance texture creation"); | |
262 | |
263 // the first argument disables mipmap generation (we don’t care so far) | |
264 tex.upload(GenMipmaps::No, &texels); | |
265 | |
266 Some(tex) | |
267 } | |
268 | |
269 Err(e) => { | |
270 eprintln!("cannot open image {}: {}", path.display(), e); | |
271 None | |
272 } | |
273 } | |
274 } |