# HG changeset patch # User Emmanuel Gil Peyrot # Date 1579371591 -3600 # Node ID 0ebf6467e4ffb66abee76bc3525f43261f3fb388 # Parent 90e907859bae1b37fbe5c110b9c709600ffbebe3 examples: Add a menu example. diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ license = "GPL-3.0-or-later" [dependencies] nom = "5" encoding_rs = "0.8" -image = { version = "0.22", default-features = false, features = ["png_codec"] } +image = { version = "0.22", default-features = false, features = ["png_codec", "jpeg"] } bitflags = "1" luminance = "0.38" luminance-glfw = { version = "0.12", default-features = false, features = ["log-errors"] } diff --git a/examples/common.rs b/examples/common.rs --- a/examples/common.rs +++ b/examples/common.rs @@ -45,8 +45,11 @@ fn merge_rgb_alpha(rgb: &DynamicImage, a .collect::>() } -fn load_rgb_png(surface: &mut GlfwSurface, path: &Path) -> Result { - let img = open_rgb_png(&path)?; +pub fn load_from_data(data: &[u8]) -> Result { + image::load_from_memory(data) +} + +pub fn upload_texture_from_rgb_image(surface: &mut GlfwSurface, img: DynamicImage) -> Result { let (width, height) = img.dimensions(); let texels = img .pixels() @@ -65,6 +68,11 @@ fn load_rgb_png(surface: &mut GlfwSurfac Ok(LoadedTexture::Rgb(tex)) } +pub fn load_rgb_texture(surface: &mut GlfwSurface, path: &Path) -> Result { + let img = open_rgb_png(&path)?; + upload_texture_from_rgb_image(surface, img) +} + fn load_rgb_a_pngs(surface: &mut GlfwSurface, rgb: &Path, alpha: &Path) -> Result { let img = open_alpha_png(&alpha)?; let alpha = match img.grayscale() { @@ -99,7 +107,7 @@ pub fn load_anm_image>(mu load_rgb_a_pngs(&mut surface, &png_filename, &alpha_filename) }, None => { - load_rgb_png(&mut surface, &png_filename) + load_rgb_texture(&mut surface, &png_filename) } } } diff --git a/examples/menu.rs b/examples/menu.rs new file mode 100644 --- /dev/null +++ b/examples/menu.rs @@ -0,0 +1,182 @@ +use luminance::blending::{Equation, Factor}; +use luminance::context::GraphicsContext; +use luminance::pipeline::{BoundTexture, PipelineState}; +use luminance::pixel::NormUnsigned; +use luminance::render_state::RenderState; +use luminance::shader::program::{Program, Uniform}; +use luminance::tess::{Mode, TessBuilder}; +use luminance::texture::{Dim2, Flat}; +use luminance_derive::{Semantics, Vertex, UniformInterface}; +use luminance_glfw::{Action, Key, WindowEvent, GlfwSurface, Surface, WindowDim, WindowOpt}; +use touhou::th06::pbg3; +use touhou::th06::anm0::Anm0; +use touhou::th06::anm0_vm::{AnmRunner, Sprite, Vertex as FakeVertex}; +use touhou::util::math::{perspective, setup_camera, ortho_2d}; +use touhou::util::prng::Prng; +use std::cell::RefCell; +use std::rc::Rc; +use std::env; +use std::path::Path; + +#[path = "common.rs"] +mod common; +use common::LoadedTexture; + +const VS: &str = r#" +in ivec3 in_position; +in vec2 in_texcoord; +in vec4 in_color; + +uniform mat4 mvp; + +out vec2 texcoord; +out vec4 color; + +void main() +{ + gl_Position = mvp * vec4(vec3(in_position), 1.0); + texcoord = vec2(in_texcoord); + + // It’s already normalized from the u8 being passed. + color = in_color; +} +"#; + +const FS: &str = r#" +in vec2 texcoord; +in vec4 color; + +uniform sampler2D color_map; + +out vec4 frag_color; + +void main() +{ + frag_color = texture(color_map, texcoord) * color; +} +"#; + +#[derive(Clone, Copy, Debug, Eq, PartialEq, Semantics)] +pub enum Semantics { + #[sem(name = "in_position", repr = "[i16; 3]", wrapper = "VertexPosition")] + Position, + + #[sem(name = "in_texcoord", repr = "[f32; 2]", wrapper = "VertexTexcoord")] + Texcoord, + + #[sem(name = "in_color", repr = "[u8; 4]", wrapper = "VertexColor")] + Color, +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, Vertex)] +#[vertex(sem = "Semantics")] +struct Vertex { + pos: VertexPosition, + uv: VertexTexcoord, + #[vertex(normalized = "true")] + rgba: VertexColor, +} + +#[derive(UniformInterface)] +struct ShaderInterface { + // the 'static lifetime acts as “anything” here + color_map: Uniform<&'static BoundTexture<'static, Flat, Dim2, NormUnsigned>>, + + #[uniform(name = "mvp")] + mvp: Uniform<[[f32; 4]; 4]>, +} + +const DEFAULT_VERTICES: [Vertex; 4] = [ + Vertex::new(VertexPosition::new([0, 0, 0]), VertexTexcoord::new([0., 0.]), VertexColor::new([255, 255, 255, 255])), + Vertex::new(VertexPosition::new([640, 0, 0]), VertexTexcoord::new([1., 0.]), VertexColor::new([255, 255, 255, 255])), + Vertex::new(VertexPosition::new([640, 480, 0]), VertexTexcoord::new([1., 1.]), VertexColor::new([255, 255, 255, 255])), + Vertex::new(VertexPosition::new([0, 480, 0]), VertexTexcoord::new([0., 1.]), VertexColor::new([255, 255, 255, 255])), +]; + +fn main() { + // Parse arguments. + let args: Vec<_> = env::args().collect(); + if args.len() != 2 { + eprintln!("Usage: {} ", args[0]); + return; + } + let directory = Path::new(&args[1]); + + let in_dat = directory.join("IN.DAT"); + // Since GLFW can be slow to create its window, let’s decode the splash screen in another + // thread in the meantime. + let jpeg_thread = std::thread::spawn(|| { + let mut in_pbg3 = pbg3::from_path_buffered(in_dat).expect("IN.DAT present"); + let jpeg = in_pbg3.get_file("th06logo.jpg", true).expect("th06logo.jpg in IN.DAT"); + let image = common::load_from_data(&jpeg).expect("th06logo.jpg decodable"); + image + }); + + let mut surface = GlfwSurface::new(WindowDim::Windowed(640, 480), "Touhou", WindowOpt::default()).expect("GLFW window"); + + let image = jpeg_thread.join().expect("image loading"); + let tex = common::upload_texture_from_rgb_image(&mut surface, image).expect("image loading"); + + // set the uniform interface to our type so that we can read textures from the shader + let program = + Program::::from_strings(None, VS, None, FS).expect("program creation").ignore_warnings(); + + let mut tess = TessBuilder::new(&mut surface) + .add_vertices(DEFAULT_VERTICES) + .set_mode(Mode::TriangleFan) + .build() + .unwrap(); + + let mut back_buffer = surface.back_buffer().unwrap(); + let mut resize = false; + + 'app: loop { + for event in surface.poll_events() { + match event { + WindowEvent::Close | WindowEvent::Key(Key::Escape, _, Action::Release, _) => break 'app, + + WindowEvent::FramebufferSize(..) => { + resize = true; + } + + _ => (), + } + } + + if resize { + back_buffer = surface.back_buffer().unwrap(); + resize = false; + } + + // here, we need to bind the pipeline variable; it will enable us to bind the texture to the GPU + // and use it in the shader + surface + .pipeline_builder() + .pipeline(&back_buffer, &PipelineState::default(), |pipeline, mut shd_gate| { + // bind our fancy texture to the GPU: it gives us a bound texture we can use with the shader + let bound_tex = match &tex { + LoadedTexture::Rgb(tex) => pipeline.bind_texture(tex), + LoadedTexture::Rgba(tex) => pipeline.bind_texture(tex), + }; + + shd_gate.shade(&program, |iface, mut rdr_gate| { + // update the texture; strictly speaking, this update doesn’t do much: it just tells the GPU + // to use the texture passed as argument (no allocation or copy is performed) + iface.color_map.update(&bound_tex); + let mvp = ortho_2d(0., 640., 480., 0.); + // TODO: check how to pass by reference. + iface.mvp.update(*mvp.borrow_inner()); + + let render_state = RenderState::default() + .set_blending((Equation::Additive, Factor::SrcAlpha, Factor::SrcAlphaComplement)); + + rdr_gate.render(&render_state, |mut tess_gate| { + tess_gate.render(&tess); + }); + }); + }); + + surface.swap_buffers(); + } +} diff --git a/src/th06/pbg3.rs b/src/th06/pbg3.rs --- a/src/th06/pbg3.rs +++ b/src/th06/pbg3.rs @@ -8,8 +8,10 @@ use crate::util::bitstream::BitStream; use crate::util::lzss; +use std::fs::File; use std::io; use std::collections::hash_map::{self, HashMap}; +use std::path::Path; /// Helper struct to handle strings and integers in PBG3 bitstreams. pub struct PBG3BitStream { @@ -132,9 +134,9 @@ impl PBG3 { } /// Read a single file from this PBG3 archive. - pub fn get_file(&mut self, filename: String, check: bool) -> io::Result> { + pub fn get_file(&mut self, filename: &str, check: bool) -> io::Result> { // XXX: no unwrap! - let (_unknown_1, _unknown_2, checksum, offset, size) = self.entries.get(&filename).unwrap(); + let (_unknown_1, _unknown_2, checksum, offset, size) = self.entries.get(filename).unwrap(); self.bitstream.seek(io::SeekFrom::Start(*offset as u64))?; let data = lzss::decompress(&mut self.bitstream.bitstream, *size as usize, 0x2000, 13, 4, 3)?; if check { @@ -154,6 +156,13 @@ impl PBG3 { } } +/// Open a PBG3 archive from its path. +pub fn from_path_buffered>(path: P) -> io::Result>> { + let file = File::open(path)?; + let buf_file = io::BufReader::new(file); + PBG3::from_file(buf_file) +} + #[cfg(test)] mod tests { use super::*;