comparison runners/src/bin/stagerunner.rs @ 757:21b186be2590

Split the Rust version into multiple crates.
author Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
date Tue, 05 Jan 2021 02:16:32 +0100
parents examples/stagerunner.rs@a662dddd4a2b
children
comparison
equal deleted inserted replaced
756:4d91790cf8ab 757:21b186be2590
1 use luminance::blending::{Equation, Factor};
2 use luminance::context::GraphicsContext;
3 use luminance::pipeline::{BoundTexture, PipelineState};
4 use luminance::pixel::NormUnsigned;
5 use luminance::render_state::RenderState;
6 use luminance::shader::program::{Program, Uniform};
7 use luminance::tess::{Mode, TessBuilder};
8 use luminance::texture::Dim2Array;
9 use luminance_derive::{Semantics, Vertex, UniformInterface};
10 use luminance_glfw::{Action, Key, WindowEvent, GlfwSurface, Surface, WindowDim, WindowOpt};
11 use touhou_formats::th06::anm0::Anm0;
12 use touhou_formats::th06::ecl::{Ecl, Rank, MainInstruction};
13 use touhou_interpreters::th06::anm0::Vertex as FakeVertex;
14 use touhou_interpreters::th06::ecl::EclRunner;
15 use touhou_interpreters::th06::enemy::{Enemy, Game, Position};
16 use touhou_utils::math::{perspective, setup_camera};
17 use touhou_utils::prng::Prng;
18 use std::cell::RefCell;
19 use std::rc::Rc;
20 use std::env;
21 use std::path::Path;
22
23 use touhou_runners::common::{load_file_into_vec, load_multiple_anm_images, LoadedTexture};
24
25 const VS: &str = r#"
26 in ivec3 in_position;
27 in uint in_layer;
28 in vec2 in_texcoord;
29 in uvec4 in_color;
30
31 uniform mat4 mvp;
32
33 flat out uint layer;
34 out vec2 texcoord;
35 out vec4 color;
36
37 void main()
38 {
39 gl_Position = mvp * vec4(vec3(in_position), 1.0);
40 texcoord = vec2(in_texcoord);
41
42 // Normalized from the u8 being passed.
43 color = vec4(in_color) / 255.;
44
45 layer = in_layer;
46 }
47 "#;
48
49 const FS: &str = r#"
50 flat in uint layer;
51 in vec2 texcoord;
52 in vec4 color;
53
54 uniform sampler2DArray color_map;
55
56 out vec4 frag_color;
57
58 void main()
59 {
60 frag_color = texture(color_map, vec3(texcoord, layer)) * color;
61 }
62 "#;
63
64 #[derive(Clone, Copy, Debug, Eq, PartialEq, Semantics)]
65 pub enum Semantics {
66 #[sem(name = "in_position", repr = "[i16; 3]", wrapper = "VertexPosition")]
67 Position,
68
69 #[sem(name = "in_layer", repr = "u16", wrapper = "VertexLayer")]
70 Layer,
71
72 #[sem(name = "in_texcoord", repr = "[f32; 2]", wrapper = "VertexTexcoord")]
73 Texcoord,
74
75 #[sem(name = "in_color", repr = "[u8; 4]", wrapper = "VertexColor")]
76 Color,
77 }
78
79 #[repr(C)]
80 #[derive(Clone, Copy, Debug, PartialEq, Vertex)]
81 #[vertex(sem = "Semantics")]
82 struct Vertex {
83 pos: VertexPosition,
84 layer: VertexLayer,
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, Dim2Array, NormUnsigned>>,
93
94 #[uniform(name = "mvp")]
95 mvp: Uniform<[[f32; 4]; 4]>,
96 }
97
98 fn main() {
99 // Parse arguments.
100 let args: Vec<_> = env::args().collect();
101 if args.len() != 4 {
102 eprintln!("Usage: {} <unarchived ST.DAT directory> <stage number> <easy|normal|hard|lunatic>", args[0]);
103 return;
104 }
105 let directory = Path::new(&args[1]);
106 let stage_number: u8 = args[2].parse().expect("stage");
107 let rank: Rank = args[3].parse().expect("rank");
108
109 // Open the ECL file.
110 let buf = load_file_into_vec(directory.join(format!("ecldata{}.ecl", stage_number))).unwrap();
111 let (_, ecl) = Ecl::from_slice(&buf).unwrap();
112 assert_eq!(ecl.mains.len(), 1);
113 let main = ecl.mains[0].clone();
114
115 // Open the ANM file.
116 let anm_filename = directory.join(format!("stg{}enm.anm", stage_number));
117 let buf = load_file_into_vec(&anm_filename).unwrap();
118 let (_, mut anms) = Anm0::from_slice(&buf).unwrap();
119 let anm0 = anms.pop().unwrap();
120
121 // Open the second ANM file.
122 let anm2_filename = directory.join(format!("stg{}enm2.anm", stage_number));
123 let buf = load_file_into_vec(&anm2_filename).unwrap();
124 let (_, mut anms) = Anm0::from_slice(&buf).unwrap();
125 let anm0_bis = anms.pop().unwrap();
126
127 let anms = [anm0, anm0_bis];
128
129 // Get the time since January 1970 as a seed for the PRNG.
130 let time = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap();
131 let prng = Rc::new(RefCell::new(Prng::new(time.subsec_micros() as u16)));
132
133 // Create the Game god object.
134 let game = Game::new(prng, rank);
135 let game = Rc::new(RefCell::new(game));
136
137 assert_eq!(std::mem::size_of::<Vertex>(), std::mem::size_of::<FakeVertex>());
138 let vertices: [Vertex; 4] = {
139 let data = std::mem::MaybeUninit::uninit();
140 unsafe { data.assume_init() }
141 };
142
143 let mut surface = GlfwSurface::new(WindowDim::Windowed(384, 448), "Touhou", WindowOpt::default()).unwrap();
144
145 // Open the image atlas matching this ANM.
146 let tex = load_multiple_anm_images(&mut surface, &anms, &anm_filename).expect("image loading");
147 let anms = Rc::new(RefCell::new(anms));
148
149 // set the uniform interface to our type so that we can read textures from the shader
150 let program =
151 Program::<Semantics, (), ShaderInterface>::from_strings(None, VS, None, FS).expect("program creation").ignore_warnings();
152
153 let mut tess = TessBuilder::new(&mut surface)
154 .add_vertices(vertices)
155 .set_mode(Mode::TriangleFan)
156 .build()
157 .unwrap();
158
159 let mut back_buffer = surface.back_buffer().unwrap();
160 let mut resize = false;
161 let mut frame = 0;
162 let mut ecl_runners = vec![];
163
164 'app: loop {
165 for event in surface.poll_events() {
166 match event {
167 WindowEvent::Close | WindowEvent::Key(Key::Escape, _, Action::Release, _) => break 'app,
168
169 WindowEvent::FramebufferSize(..) => {
170 resize = true;
171 }
172
173 _ => (),
174 }
175 }
176
177 if resize {
178 back_buffer = surface.back_buffer().unwrap();
179 resize = false;
180 }
181
182 for call in main.instructions.iter() {
183 if call.time == frame {
184 let sub = call.sub;
185 let instr = call.instr;
186 let (x, y, _z, life, bonus, score, mirror) = match instr {
187 MainInstruction::SpawnEnemy(x, y, z, life, bonus, score) => (x, y, z, life, bonus, score, false),
188 MainInstruction::SpawnEnemyMirrored(x, y, z, life, bonus, score) => (x, y, z, life, bonus, score, true),
189 MainInstruction::SpawnEnemyRandom(x, y, z, life, bonus, score) => (x, y, z, life, bonus, score, false),
190 MainInstruction::SpawnEnemyMirroredRandom(x, y, z, life, bonus, score) => (x, y, z, life, bonus, score, true),
191 _ => continue,
192 };
193 let enemy = Enemy::new(Position::new(x, y), life, bonus, score, mirror, Rc::downgrade(&anms), Rc::downgrade(&game));
194 let runner = EclRunner::new(&ecl, enemy, sub);
195 ecl_runners.push(runner);
196 }
197 }
198
199 for runner in ecl_runners.iter_mut() {
200 runner.run_frame();
201 let mut enemy = runner.enemy.borrow_mut();
202 enemy.update();
203 }
204
205 // here, we need to bind the pipeline variable; it will enable us to bind the texture to the GPU
206 // and use it in the shader
207 surface
208 .pipeline_builder()
209 .pipeline(&back_buffer, &PipelineState::default(), |pipeline, mut shd_gate| {
210 // bind our fancy texture to the GPU: it gives us a bound texture we can use with the shader
211 let bound_tex = match &tex {
212 LoadedTexture::Rgb(tex) => unreachable!(),
213 LoadedTexture::Rgba(tex) => unreachable!(),
214 LoadedTexture::RgbaArray(tex) => pipeline.bind_texture(tex),
215 };
216
217 shd_gate.shade(&program, |iface, mut rdr_gate| {
218 // update the texture; strictly speaking, this update doesn’t do much: it just tells the GPU
219 // to use the texture passed as argument (no allocation or copy is performed)
220 iface.color_map.update(&bound_tex);
221 //let mvp = ortho_2d(0., 384., 448., 0.);
222 let proj = perspective(0.5235987755982988, 384. / 448., 101010101./2010101., 101010101./10101.);
223 let view = setup_camera(0., 0., 1.);
224 let mvp = view * proj;
225 //println!("{:#?}", mvp);
226 // TODO: check how to pass by reference.
227 iface.mvp.update(*mvp.borrow_inner());
228
229 let render_state = RenderState::default()
230 .set_depth_test(None)
231 .set_blending((Equation::Additive, Factor::SrcAlpha, Factor::SrcAlphaComplement));
232
233 rdr_gate.render(&render_state, |mut tess_gate| {
234 let mut game = game.borrow_mut();
235 game.run_frame();
236
237 for (x, y, z, sprite) in game.get_sprites() {
238 {
239 let mut slice = tess
240 .as_slice_mut()
241 .unwrap();
242
243 let sprite = sprite.borrow();
244 let fake_vertices = unsafe { std::mem::transmute::<*mut Vertex, &mut [FakeVertex; 4]>(slice.as_mut_ptr()) };
245 sprite.fill_vertices(fake_vertices, x, y, z);
246 }
247
248 // render the tessellation to the surface the regular way and let the vertex shader’s
249 // magic do the rest!
250 tess_gate.render(&tess);
251 }
252 });
253 });
254 });
255
256 surface.swap_buffers();
257 frame += 1;
258 }
259 }