Mercurial > touhou
comparison examples/anmrenderer.rs @ 643:01849ffd0180
Add an anmrenderer binary.
author | Emmanuel Gil Peyrot <linkmauve@linkmauve.fr> |
---|---|
date | Fri, 02 Aug 2019 20:24:45 +0200 |
parents | |
children | f983a4c98410 |
comparison
equal
deleted
inserted
replaced
642:9e40bd5cc26d | 643:01849ffd0180 |
---|---|
1 use image::GenericImageView; | |
2 use luminance::context::GraphicsContext; | |
3 use luminance::framebuffer::Framebuffer; | |
4 use luminance::pipeline::BoundTexture; | |
5 use luminance::pixel::{RGB, Floating}; | |
6 use luminance::render_state::RenderState; | |
7 use luminance::shader::program::{Program, Uniform}; | |
8 use luminance::tess::{Mode, TessBuilder}; | |
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::util::math::{perspective, setup_camera}; | |
16 use std::cell::RefCell; | |
17 use std::fs::File; | |
18 use std::io::{BufReader, Read}; | |
19 use std::rc::Rc; | |
20 use std::env; | |
21 use std::path::Path; | |
22 | |
23 const VS: &str = r#" | |
24 in ivec3 in_position; | |
25 in vec2 in_texcoord; | |
26 in uvec4 in_color; | |
27 | |
28 uniform mat4 mvp; | |
29 | |
30 out vec2 texcoord; | |
31 out vec4 color; | |
32 | |
33 void main() | |
34 { | |
35 gl_Position = mvp * vec4(vec3(in_position), 1.0); | |
36 texcoord = vec2(in_texcoord); | |
37 | |
38 // Normalized from the u8 being passed. | |
39 color = vec4(in_color) / 255.; | |
40 } | |
41 "#; | |
42 | |
43 const FS: &str = r#" | |
44 in vec2 texcoord; | |
45 in vec4 color; | |
46 | |
47 uniform sampler2D color_map; | |
48 | |
49 out vec4 frag_color; | |
50 | |
51 void main() | |
52 { | |
53 frag_color = texture(color_map, texcoord) * color; | |
54 } | |
55 "#; | |
56 | |
57 #[derive(Clone, Copy, Debug, Eq, PartialEq, Semantics)] | |
58 pub enum Semantics { | |
59 #[sem(name = "in_position", repr = "[i16; 3]", wrapper = "VertexPosition")] | |
60 Position, | |
61 | |
62 #[sem(name = "in_texcoord", repr = "[f32; 2]", wrapper = "VertexTexcoord")] | |
63 Texcoord, | |
64 | |
65 #[sem(name = "in_color", repr = "[u8; 4]", wrapper = "VertexColor")] | |
66 Color, | |
67 } | |
68 | |
69 #[repr(C)] | |
70 #[derive(Clone, Copy, Debug, PartialEq, Vertex)] | |
71 #[vertex(sem = "Semantics")] | |
72 struct Vertex { | |
73 pos: VertexPosition, | |
74 uv: VertexTexcoord, | |
75 rgba: VertexColor, | |
76 } | |
77 | |
78 #[derive(UniformInterface)] | |
79 struct ShaderInterface { | |
80 // the 'static lifetime acts as “anything” here | |
81 color_map: Uniform<&'static BoundTexture<'static, Flat, Dim2, Floating>>, | |
82 | |
83 #[uniform(name = "mvp")] | |
84 mvp: Uniform<[[f32; 4]; 4]>, | |
85 } | |
86 | |
87 fn main() { | |
88 // Parse arguments. | |
89 let args: Vec<_> = env::args().collect(); | |
90 if args.len() != 4 { | |
91 eprintln!("Usage: {} <ANM file> <PNG file> <script number>", args[0]); | |
92 return; | |
93 } | |
94 let anm_filename = &args[1]; | |
95 let png_filename = &args[2]; | |
96 let script: u8 = args[3].parse().expect("number"); | |
97 | |
98 // Open the ANM file. | |
99 let file = File::open(anm_filename).unwrap(); | |
100 let mut file = BufReader::new(file); | |
101 let mut buf = vec![]; | |
102 file.read_to_end(&mut buf).unwrap(); | |
103 let anm0 = Anm0::from_slice(&buf).unwrap(); | |
104 | |
105 if !anm0.scripts.contains_key(&script) { | |
106 eprintln!("This anm0 doesn’t contain a script named {}.", script); | |
107 return; | |
108 } | |
109 | |
110 // Create the sprite. | |
111 let sprite = Rc::new(RefCell::new(Sprite::new(0., 0.))); | |
112 | |
113 // Create the AnmRunner from the ANM and the sprite. | |
114 let mut anm_runner = AnmRunner::new(&anm0, script, sprite.clone(), 0); | |
115 | |
116 assert_eq!(std::mem::size_of::<Vertex>(), std::mem::size_of::<FakeVertex>()); | |
117 let mut vertices: [Vertex; 4] = unsafe { std::mem::uninitialized() }; | |
118 fill_vertices(sprite.clone(), &mut vertices); | |
119 | |
120 let mut surface = GlfwSurface::new(WindowDim::Windowed(384, 448), "Touhou", WindowOpt::default()).unwrap(); | |
121 | |
122 // Open the image atlas matching this ANM. | |
123 println!("{} {}", anm0.first_name, png_filename); | |
124 let tex = load_from_disk(&mut surface, Path::new(png_filename)).expect("texture loading"); | |
125 | |
126 // set the uniform interface to our type so that we can read textures from the shader | |
127 let (program, _) = | |
128 Program::<Semantics, (), ShaderInterface>::from_strings(None, VS, None, FS).expect("program creation"); | |
129 | |
130 let mut tess = TessBuilder::new(&mut surface) | |
131 .add_vertices(vertices) | |
132 .set_mode(Mode::TriangleFan) | |
133 .build() | |
134 .unwrap(); | |
135 | |
136 let mut back_buffer = Framebuffer::back_buffer(surface.size()); | |
137 let mut frame = 0; | |
138 let mut i = 0; | |
139 | |
140 'app: loop { | |
141 for event in surface.poll_events() { | |
142 match event { | |
143 WindowEvent::Close | WindowEvent::Key(Key::Escape, _, Action::Release, _) => break 'app, | |
144 | |
145 WindowEvent::FramebufferSize(width, height) => { | |
146 back_buffer = Framebuffer::back_buffer([width as u32, height as u32]); | |
147 } | |
148 | |
149 _ => (), | |
150 } | |
151 } | |
152 | |
153 { | |
154 let mut slice = tess | |
155 .as_slice_mut() | |
156 .unwrap(); | |
157 | |
158 anm_runner.run_frame(); | |
159 fill_vertices_ptr(sprite.clone(), slice.as_mut_ptr()); | |
160 } | |
161 | |
162 // here, we need to bind the pipeline variable; it will enable us to bind the texture to the GPU | |
163 // and use it in the shader | |
164 surface | |
165 .pipeline_builder() | |
166 .pipeline(&back_buffer, [0., 0., 0., 0.], |pipeline, shd_gate| { | |
167 // bind our fancy texture to the GPU: it gives us a bound texture we can use with the shader | |
168 let bound_tex = pipeline.bind_texture(&tex); | |
169 | |
170 shd_gate.shade(&program, |rdr_gate, iface| { | |
171 // update the texture; strictly speaking, this update doesn’t do much: it just tells the GPU | |
172 // to use the texture passed as argument (no allocation or copy is performed) | |
173 iface.color_map.update(&bound_tex); | |
174 //let mvp = ortho_2d(0., 384., 448., 0.); | |
175 let proj = perspective(0.5235987755982988, 384. / 448., 101010101./2010101., 101010101./10101.); | |
176 let view = setup_camera(0., 0., 1.); | |
177 let mvp = view * proj; | |
178 //println!("{:#?}", mvp); | |
179 // TODO: check how to pass by reference. | |
180 iface.mvp.update(*mvp.borrow_inner()); | |
181 | |
182 rdr_gate.render(RenderState::default(), |tess_gate| { | |
183 // render the tessellation to the surface the regular way and let the vertex shader’s | |
184 // magic do the rest! | |
185 tess_gate.render(&mut surface, (&tess).into()); | |
186 }); | |
187 }); | |
188 }); | |
189 | |
190 surface.swap_buffers(); | |
191 } | |
192 } | |
193 | |
194 fn fill_vertices_ptr(sprite: Rc<RefCell<Sprite>>, vertices: *mut Vertex) { | |
195 let mut fake_vertices = unsafe { std::mem::transmute::<*mut Vertex, &mut [FakeVertex; 4]>(vertices) }; | |
196 sprite.borrow().fill_vertices(&mut fake_vertices); | |
197 } | |
198 | |
199 fn fill_vertices(sprite: Rc<RefCell<Sprite>>, vertices: &mut [Vertex; 4]) { | |
200 let mut fake_vertices = unsafe { std::mem::transmute::<&mut [Vertex; 4], &mut [FakeVertex; 4]>(vertices) }; | |
201 sprite.borrow().fill_vertices(&mut fake_vertices); | |
202 } | |
203 | |
204 fn load_from_disk(surface: &mut GlfwSurface, path: &Path) -> Option<Texture<Flat, Dim2, RGB>> { | |
205 // load the texture into memory as a whole bloc (i.e. no streaming) | |
206 match image::open(&path) { | |
207 Ok(img) => { | |
208 let (width, height) = img.dimensions(); | |
209 let texels = img | |
210 .pixels() | |
211 .map(|(x, y, rgb)| (rgb[0], rgb[1], rgb[2])) | |
212 .collect::<Vec<_>>(); | |
213 | |
214 // create the luminance texture; the third argument is the number of mipmaps we want (leave it | |
215 // to 0 for now) and the latest is a the sampler to use when sampling the texels in the | |
216 // shader (we’ll just use the default one) | |
217 let tex = | |
218 Texture::new(surface, [width, height], 0, &Sampler::default()).expect("luminance texture creation"); | |
219 | |
220 // the first argument disables mipmap generation (we don’t care so far) | |
221 tex.upload(GenMipmaps::No, &texels); | |
222 | |
223 Some(tex) | |
224 } | |
225 | |
226 Err(e) => { | |
227 eprintln!("cannot open image {}: {}", path.display(), e); | |
228 None | |
229 } | |
230 } | |
231 } |