Skip to main content

htl_mq/
lib.rs

1//! A macroquad window for an htl program.
2//!
3//! `htl new --target bin` writes a host whose script runs to completion. A game wants the
4//! other shape — a window, a frame loop, input, drawing — and the part of that which is
5//! the same for every project is this crate; `htl new --target window` writes a project
6//! on it. The project keeps its engine and its rules in Teal, and its own
7//! `#[host_module]` beside `mq` for whatever wants the GPU.
8//!
9//! [`Mq`] is a [`#[host_module]`](htl::host_module) that re-exports macroquad's drawing
10//! and input to Teal as `require("mq")`. [`run`] drives a Teal game table (with
11//! `load`, `update(dt): boolean`, and `draw` methods) through the frame loop; the
12//! declaration names its shape `mq.Game`, each field ending in `---@noyield`, because the
13//! loop calls them with `Function::call` and a suspension inside one cannot reach an
14//! executor.
15//! [`Hooks`] provides the two environment hooks a run without a person at the window
16//! needs. The declaration file `dts/mq.d.tl` is written by the `#[host_module]` macro
17//! at build time and shipped through `[package.metadata.htl] dts`. [`macroquad`] is
18//! re-exported, so a project that draws on its own side reaches it through this crate
19//! rather than naming a version of its own — which is also why a window is a crate and
20//! not a feature of `htl`: macroquad comes with it.
21//!
22//! Not here: textures and audio, which need asset paths, and that is a host decision;
23//! and the web target, since macroquad's wasm path and mlua's are different targets.
24//!
25//! # A window, end to end
26//!
27//! ```toml
28//! [dependencies]
29//! htl = "0.8"
30//! htl-mq = "0.8"          # macroquad comes with it
31//! ```
32//!
33//! ```rust,ignore
34//! use htl::bundle::Bundle;
35//! use htl::mlua::Table;
36//! use htl::{Htl, include_bundle};
37//!
38//! // `mq` is htl-mq's: its declaration is `types/htl-mq/mq.d.tl`, which `htl dts` writes.
39//! // `host` is this crate's `#[host_module]`, which the build knows without being told.
40//! const MAIN: &[u8] = include_bundle!("src/main.tl", host = ["game", "mq"], debug = true);
41//!
42//! fn main() -> anyhow::Result<()> {
43//!     let h = Htl::new()?;
44//!     game::preload(&h)?;                       // the project's own host module and Teal
45//!     htl_mq::Mq.htl_preload(&h)?;              // `require("mq")`
46//!     h.install_bundle(&Bundle::decode(MAIN)?)?;
47//!     let game: Table = h.lua().load("return require('main')").eval()?;
48//!     htl_mq::run(h, game, htl_mq::conf("game", 800, 600))
49//! }
50//! ```
51//!
52//! The entry script returns the game table, bound to `mq.Game` so that `htl check` knows
53//! what it is (under `[lang] async`, an `async function` given to `update` is reported by
54//! `async-as-sync-callback`; `{ .. } as mq.Game` is a cast the rule does not see through):
55//!
56//! ```lua
57//! local mq = require("mq")
58//! local x = 40.0
59//!
60//! local game: mq.Game = {
61//!    update = function(dt: number): boolean
62//!       x = x + 120 * dt
63//!       return not mq:is_key_pressed("Escape")
64//!    end,
65//!    draw = function()
66//!       mq:clear_background({r = 0.08, g = 0.08, b = 0.12, a = 1})
67//!       mq:draw_circle(x, 300, 24, {r = 1, g = 0.6, b = 0.2, a = 1})
68//!       mq:draw_text("fps " .. mq:fps(), 16, 32, 28, {r = 1, g = 1, b = 1, a = 1})
69//!    end,
70//! }
71//! return game
72//! ```
73
74use htl::mlua::{FromLua, Function, Table, Value};
75use htl::{Htl, TealRecord, host_module};
76use std::cell::RefCell;
77use std::rc::Rc;
78
79/// The macroquad this window was opened with. A project's own host module — `fx` in what
80/// `htl new --target window` writes — draws into the same frame as [`Mq`] does, and two
81/// macroquads in one binary are two sets of process-global state; taking it from here is
82/// what makes it the same one, and it costs the project no version of its own to keep in
83/// step with this crate's.
84pub use macroquad;
85
86/// Channels 0.0..=1.0, as macroquad's.
87#[derive(TealRecord, Clone, Copy, Debug, PartialEq)]
88pub struct Color {
89    pub r: f32,
90    pub g: f32,
91    pub b: f32,
92    pub a: f32,
93}
94
95impl From<Color> for macroquad::color::Color {
96    fn from(c: Color) -> Self {
97        macroquad::color::Color::new(c.r, c.g, c.b, c.a)
98    }
99}
100
101impl From<macroquad::color::Color> for Color {
102    fn from(c: macroquad::color::Color) -> Self {
103        Color {
104            r: c.r,
105            g: c.g,
106            b: c.b,
107            a: c.a,
108        }
109    }
110}
111
112/// A 2D vector.
113#[derive(TealRecord, Clone, Copy, Debug, PartialEq)]
114pub struct Vec2 {
115    pub x: f32,
116    pub y: f32,
117}
118
119impl From<Vec2> for macroquad::math::Vec2 {
120    fn from(v: Vec2) -> Self {
121        macroquad::math::Vec2::new(v.x, v.y)
122    }
123}
124
125impl From<macroquad::math::Vec2> for Vec2 {
126    fn from(v: macroquad::math::Vec2) -> Self {
127        Vec2 { x: v.x, y: v.y }
128    }
129}
130
131/// The subset of macroquad's `KeyCode` a game reaches for. On the Teal side it is an
132/// `enum`, so a string outside the set is an `htl check` error that lists the variants,
133/// and one that reaches the host at run time is refused by name.
134#[derive(TealRecord, Clone, Copy, Debug, PartialEq, Eq)]
135pub enum Key {
136    Space,
137    Escape,
138    Enter,
139    Tab,
140    Backspace,
141    Delete,
142    Insert,
143    Home,
144    End,
145    PageUp,
146    PageDown,
147    Up,
148    Down,
149    Left,
150    Right,
151    LeftShift,
152    RightShift,
153    LeftControl,
154    RightControl,
155    LeftAlt,
156    RightAlt,
157    A,
158    B,
159    C,
160    D,
161    E,
162    F,
163    G,
164    H,
165    I,
166    J,
167    K,
168    L,
169    M,
170    N,
171    O,
172    P,
173    Q,
174    R,
175    S,
176    T,
177    U,
178    V,
179    W,
180    X,
181    Y,
182    Z,
183    Key0,
184    Key1,
185    Key2,
186    Key3,
187    Key4,
188    Key5,
189    Key6,
190    Key7,
191    Key8,
192    Key9,
193    F1,
194    F2,
195    F3,
196    F4,
197    F5,
198    F6,
199    F7,
200    F8,
201    F9,
202    F10,
203    F11,
204    F12,
205}
206
207impl From<Key> for macroquad::input::KeyCode {
208    fn from(k: Key) -> Self {
209        match k {
210            Key::Space => macroquad::input::KeyCode::Space,
211            Key::Escape => macroquad::input::KeyCode::Escape,
212            Key::Enter => macroquad::input::KeyCode::Enter,
213            Key::Tab => macroquad::input::KeyCode::Tab,
214            Key::Backspace => macroquad::input::KeyCode::Backspace,
215            Key::Delete => macroquad::input::KeyCode::Delete,
216            Key::Insert => macroquad::input::KeyCode::Insert,
217            Key::Home => macroquad::input::KeyCode::Home,
218            Key::End => macroquad::input::KeyCode::End,
219            Key::PageUp => macroquad::input::KeyCode::PageUp,
220            Key::PageDown => macroquad::input::KeyCode::PageDown,
221            Key::Up => macroquad::input::KeyCode::Up,
222            Key::Down => macroquad::input::KeyCode::Down,
223            Key::Left => macroquad::input::KeyCode::Left,
224            Key::Right => macroquad::input::KeyCode::Right,
225            Key::LeftShift => macroquad::input::KeyCode::LeftShift,
226            Key::RightShift => macroquad::input::KeyCode::RightShift,
227            Key::LeftControl => macroquad::input::KeyCode::LeftControl,
228            Key::RightControl => macroquad::input::KeyCode::RightControl,
229            Key::LeftAlt => macroquad::input::KeyCode::LeftAlt,
230            Key::RightAlt => macroquad::input::KeyCode::RightAlt,
231            Key::A => macroquad::input::KeyCode::A,
232            Key::B => macroquad::input::KeyCode::B,
233            Key::C => macroquad::input::KeyCode::C,
234            Key::D => macroquad::input::KeyCode::D,
235            Key::E => macroquad::input::KeyCode::E,
236            Key::F => macroquad::input::KeyCode::F,
237            Key::G => macroquad::input::KeyCode::G,
238            Key::H => macroquad::input::KeyCode::H,
239            Key::I => macroquad::input::KeyCode::I,
240            Key::J => macroquad::input::KeyCode::J,
241            Key::K => macroquad::input::KeyCode::K,
242            Key::L => macroquad::input::KeyCode::L,
243            Key::M => macroquad::input::KeyCode::M,
244            Key::N => macroquad::input::KeyCode::N,
245            Key::O => macroquad::input::KeyCode::O,
246            Key::P => macroquad::input::KeyCode::P,
247            Key::Q => macroquad::input::KeyCode::Q,
248            Key::R => macroquad::input::KeyCode::R,
249            Key::S => macroquad::input::KeyCode::S,
250            Key::T => macroquad::input::KeyCode::T,
251            Key::U => macroquad::input::KeyCode::U,
252            Key::V => macroquad::input::KeyCode::V,
253            Key::W => macroquad::input::KeyCode::W,
254            Key::X => macroquad::input::KeyCode::X,
255            Key::Y => macroquad::input::KeyCode::Y,
256            Key::Z => macroquad::input::KeyCode::Z,
257            Key::Key0 => macroquad::input::KeyCode::Key0,
258            Key::Key1 => macroquad::input::KeyCode::Key1,
259            Key::Key2 => macroquad::input::KeyCode::Key2,
260            Key::Key3 => macroquad::input::KeyCode::Key3,
261            Key::Key4 => macroquad::input::KeyCode::Key4,
262            Key::Key5 => macroquad::input::KeyCode::Key5,
263            Key::Key6 => macroquad::input::KeyCode::Key6,
264            Key::Key7 => macroquad::input::KeyCode::Key7,
265            Key::Key8 => macroquad::input::KeyCode::Key8,
266            Key::Key9 => macroquad::input::KeyCode::Key9,
267            Key::F1 => macroquad::input::KeyCode::F1,
268            Key::F2 => macroquad::input::KeyCode::F2,
269            Key::F3 => macroquad::input::KeyCode::F3,
270            Key::F4 => macroquad::input::KeyCode::F4,
271            Key::F5 => macroquad::input::KeyCode::F5,
272            Key::F6 => macroquad::input::KeyCode::F6,
273            Key::F7 => macroquad::input::KeyCode::F7,
274            Key::F8 => macroquad::input::KeyCode::F8,
275            Key::F9 => macroquad::input::KeyCode::F9,
276            Key::F10 => macroquad::input::KeyCode::F10,
277            Key::F11 => macroquad::input::KeyCode::F11,
278            Key::F12 => macroquad::input::KeyCode::F12,
279        }
280    }
281}
282
283#[derive(TealRecord, Clone, Copy, Debug, PartialEq, Eq)]
284pub enum MouseButton {
285    Left,
286    Middle,
287    Right,
288}
289
290impl From<MouseButton> for macroquad::input::MouseButton {
291    fn from(b: MouseButton) -> Self {
292        match b {
293            MouseButton::Left => macroquad::input::MouseButton::Left,
294            MouseButton::Middle => macroquad::input::MouseButton::Middle,
295            MouseButton::Right => macroquad::input::MouseButton::Right,
296        }
297    }
298}
299
300/// Stateless, because macroquad keeps its state process-global; every method calls
301/// macroquad and panics when no window is open, which is why a Teal test never calls
302/// them — `htl test` sees only the declaration, which declares and does nothing. So an
303/// engine module that takes what it needs as arguments is testable headless, and
304/// `main.tl` — the one file that calls `mq` — is not what a test requires; that panic is
305/// the other reason to keep the loop out of the engine.
306pub struct Mq;
307
308#[host_module(
309    name = "mq",
310    dts = "dts/mq.d.tl",
311    records = [Color, Vec2, Key, MouseButton, Game]
312)]
313impl Mq {
314    /// Returns the current screen width.
315    pub fn screen_width(&self) -> f32 {
316        macroquad::window::screen_width()
317    }
318
319    /// Returns the current screen height.
320    pub fn screen_height(&self) -> f32 {
321        macroquad::window::screen_height()
322    }
323
324    /// Returns the time elapsed since the last frame.
325    pub fn frame_time(&self) -> f32 {
326        macroquad::time::get_frame_time()
327    }
328
329    /// Returns the time since application start.
330    pub fn time(&self) -> f64 {
331        macroquad::time::get_time()
332    }
333
334    /// Returns the current FPS.
335    pub fn fps(&self) -> i32 {
336        macroquad::time::get_fps()
337    }
338
339    /// Clears the background with the given color.
340    pub fn clear_background(&self, color: Color) {
341        macroquad::window::clear_background(color.into());
342    }
343
344    /// Draws a filled rectangle.
345    pub fn draw_rectangle(&self, x: f32, y: f32, w: f32, h: f32, color: Color) {
346        macroquad::shapes::draw_rectangle(x, y, w, h, color.into());
347    }
348
349    /// Draws a rectangle outline.
350    pub fn draw_rectangle_lines(
351        &self,
352        x: f32,
353        y: f32,
354        w: f32,
355        h: f32,
356        thickness: f32,
357        color: Color,
358    ) {
359        macroquad::shapes::draw_rectangle_lines(x, y, w, h, thickness, color.into());
360    }
361
362    /// Draws a filled circle.
363    pub fn draw_circle(&self, x: f32, y: f32, r: f32, color: Color) {
364        macroquad::shapes::draw_circle(x, y, r, color.into());
365    }
366
367    /// Draws a circle outline.
368    pub fn draw_circle_lines(&self, x: f32, y: f32, r: f32, thickness: f32, color: Color) {
369        macroquad::shapes::draw_circle_lines(x, y, r, thickness, color.into());
370    }
371
372    /// Draws a line.
373    pub fn draw_line(&self, x1: f32, y1: f32, x2: f32, y2: f32, thickness: f32, color: Color) {
374        macroquad::shapes::draw_line(x1, y1, x2, y2, thickness, color.into());
375    }
376
377    /// Draws text.
378    pub fn draw_text(&self, text: &str, x: f32, y: f32, font_size: f32, color: Color) {
379        macroquad::text::draw_text(text, x, y, font_size, color.into());
380    }
381
382    /// Returns whether the given key is currently held down.
383    pub fn is_key_down(&self, key: Key) -> bool {
384        macroquad::input::is_key_down(key.into())
385    }
386
387    /// Returns whether the given key was pressed this frame.
388    pub fn is_key_pressed(&self, key: Key) -> bool {
389        macroquad::input::is_key_pressed(key.into())
390    }
391
392    /// Returns whether the given key was released this frame.
393    pub fn is_key_released(&self, key: Key) -> bool {
394        macroquad::input::is_key_released(key.into())
395    }
396
397    /// Returns the current mouse position.
398    pub fn mouse_position(&self) -> Vec2 {
399        let (x, y) = macroquad::input::mouse_position();
400        Vec2 { x, y }
401    }
402
403    /// Returns whether the given mouse button is currently held down.
404    pub fn is_mouse_button_down(&self, button: MouseButton) -> bool {
405        macroquad::input::is_mouse_button_down(button.into())
406    }
407
408    /// Returns whether the given mouse button was pressed this frame.
409    pub fn is_mouse_button_pressed(&self, button: MouseButton) -> bool {
410        macroquad::input::is_mouse_button_pressed(button.into())
411    }
412}
413
414/// What a run without a person at the window needs: stop after `frames` frames, and
415/// write the last frame drawn to `shot` as a PNG. Read from `HTL_MQ_FRAMES` and
416/// `HTL_MQ_SHOT` by [`Hooks::from_env`], which [`run`] does; [`run_with`] takes them
417/// explicitly, and [`Hooks::NONE`] turns both off. A machine with no display fails before
418/// the first frame (`XOpenDisplay() failed!` on Linux); `xvfb-run` is enough to get the
419/// PNG out of one.
420#[derive(Debug, Clone, Default, PartialEq, Eq)]
421pub struct Hooks {
422    pub frames: Option<u64>,
423    pub shot: Option<String>,
424}
425
426impl Hooks {
427    pub const NONE: Hooks = Hooks {
428        frames: None,
429        shot: None,
430    };
431
432    /// `HTL_MQ_FRAMES` / `HTL_MQ_SHOT` from the environment, through [`Hooks::parse`].
433    pub fn from_env() -> anyhow::Result<Hooks> {
434        Self::parse(
435            std::env::var("HTL_MQ_FRAMES").ok().as_deref(),
436            std::env::var("HTL_MQ_SHOT").ok().as_deref(),
437        )
438    }
439
440    /// `frames` must be a `u64` of 1 or more; `shot` is taken as written. `None` or an
441    /// empty string is "unset" for either.
442    pub fn parse(frames: Option<&str>, shot: Option<&str>) -> anyhow::Result<Hooks> {
443        let frames = match frames {
444            None | Some("") => None,
445            Some(s) => {
446                let n: u64 = s.parse().map_err(|_| {
447                    anyhow::anyhow!("HTL_MQ_FRAMES: expected a frame count of 1 or more, got `{s}`")
448                })?;
449                if n == 0 {
450                    anyhow::bail!("HTL_MQ_FRAMES: expected a frame count of 1 or more, got `{s}`");
451                }
452                Some(n)
453            }
454        };
455        let shot = match shot {
456            None | Some("") => None,
457            Some(s) => Some(s.to_string()),
458        };
459        Ok(Hooks { frames, shot })
460    }
461}
462
463/// A window with a title and a size; everything else is macroquad's default.
464pub fn conf(title: &str, width: i32, height: i32) -> macroquad::conf::Conf {
465    macroquad::conf::Conf {
466        miniquad_conf: macroquad::miniquad::conf::Conf {
467            window_title: title.to_string(),
468            window_width: width,
469            window_height: height,
470            ..Default::default()
471        },
472        ..Default::default()
473    }
474}
475
476/// The functions a game table provides, declared to Teal as `mq.Game`. `load` may be
477/// absent; the other two may not, and a table without one is refused by the derived
478/// `FromLua` before a window opens (`Game.update: expected function, got nil`). [`frames`]
479/// calls every one of them with the sync `Function::call`, so each field is
480/// `#[teal(noyield)]`: the declaration says so, and an async function bound to one is
481/// reported by `htl check` rather than failing on the first frame with `attempt to yield
482/// across a C-call boundary`.
483#[derive(TealRecord)]
484struct Game {
485    #[teal(noyield)]
486    load: Option<Function>,
487    #[teal(noyield)]
488    update: Function,
489    #[teal(noyield)]
490    draw: Function,
491}
492
493/// Open the window described by `conf` and drive `game` until `update` returns false,
494/// the window is closed, or the `HTL_MQ_FRAMES` hook is reached. `h` is the state the
495/// table lives in; it is kept alive for the whole run. Hooks come from the
496/// environment; [`run_with`] is the same with them given.
497pub fn run(h: Htl, game: Table, conf: macroquad::conf::Conf) -> anyhow::Result<()> {
498    run_with(h, game, conf, Hooks::from_env()?)
499}
500
501/// [`run`] with the hooks given rather than read from the environment.
502pub fn run_with(
503    h: Htl,
504    game: Table,
505    conf: macroquad::conf::Conf,
506    hooks: Hooks,
507) -> anyhow::Result<()> {
508    let game = Game::from_lua(Value::Table(game), h.lua())?;
509    let failed: Rc<RefCell<Option<anyhow::Error>>> = Rc::new(RefCell::new(None));
510    macroquad::Window::from_config(conf, {
511        let failed = Rc::clone(&failed);
512        async move {
513            let _h = h;
514            if let Err(e) = frames(game, hooks).await {
515                *failed.borrow_mut() = Some(e);
516            }
517        }
518    });
519    match failed.borrow_mut().take() {
520        Some(e) => Err(e),
521        None => Ok(()),
522    }
523}
524
525/// One run of the game loop: `load` once, then `update(dt)` and `draw()` each frame
526/// around `next_frame().await`, until `update` returns false or the frame hook is
527/// reached; then the screenshot hook, if any.
528async fn frames(game: Game, hooks: Hooks) -> anyhow::Result<()> {
529    if let Some(f) = game.load {
530        f.call::<()>(())?;
531    }
532    let mut n: u64 = 0;
533    loop {
534        let dt = macroquad::time::get_frame_time();
535        let go: bool = game.update.call::<bool>(dt)?;
536        // the game says it is done; the PNG, if asked for, holds the previous frame
537        if !go {
538            break;
539        }
540        game.draw.call::<()>(())?;
541        n += 1;
542        if hooks.frames == Some(n) {
543            break;
544        }
545        macroquad::window::next_frame().await;
546    }
547    if let Some(path) = &hooks.shot {
548        macroquad::texture::get_screen_data().export_png(path);
549    }
550    Ok(())
551}