Une ombre est née..

5d3bc9f4f25cfdb8aaf998c7445cacd85a6c509d
Alexis Sellier committed ago
.cargo/config.toml added +2 -0
1 +
[alias]
2 +
y = "clippy --all-targets --all-features -- -D warnings"
.gitignore added +4 -0
1 +
/target
2 +
/notes
3 +
errors.err
4 +
.aider*
Cargo.lock added +335 -0
1 +
# This file is automatically @generated by Cargo.
2 +
# It is not intended for manual editing.
3 +
version = 4
4 +
5 +
[[package]]
6 +
name = "bitflags"
7 +
version = "1.3.2"
8 +
source = "registry+https://github.com/rust-lang/crates.io-index"
9 +
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
10 +
11 +
[[package]]
12 +
name = "bumpalo"
13 +
version = "3.14.0"
14 +
source = "registry+https://github.com/rust-lang/crates.io-index"
15 +
checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec"
16 +
17 +
[[package]]
18 +
name = "cc"
19 +
version = "1.0.83"
20 +
source = "registry+https://github.com/rust-lang/crates.io-index"
21 +
checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0"
22 +
dependencies = [
23 +
 "libc",
24 +
]
25 +
26 +
[[package]]
27 +
name = "cfg-if"
28 +
version = "1.0.0"
29 +
source = "registry+https://github.com/rust-lang/crates.io-index"
30 +
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
31 +
32 +
[[package]]
33 +
name = "cmake"
34 +
version = "0.1.50"
35 +
source = "registry+https://github.com/rust-lang/crates.io-index"
36 +
checksum = "a31c789563b815f77f4250caee12365734369f942439b7defd71e18a48197130"
37 +
dependencies = [
38 +
 "cc",
39 +
]
40 +
41 +
[[package]]
42 +
name = "glfw"
43 +
version = "0.58.0"
44 +
source = "registry+https://github.com/rust-lang/crates.io-index"
45 +
checksum = "d1cad81f99085cabd6a4a99403335bc3f3d00d6cf4467e478f13c393ced9259d"
46 +
dependencies = [
47 +
 "bitflags",
48 +
 "glfw-sys",
49 +
 "objc2",
50 +
 "raw-window-handle",
51 +
 "winapi",
52 +
]
53 +
54 +
[[package]]
55 +
name = "glfw-sys"
56 +
version = "5.0.0+3.3.9"
57 +
source = "registry+https://github.com/rust-lang/crates.io-index"
58 +
checksum = "1dfc32d45fb58ff38b112696907963a7d671e9cf742b16f882062169a053cf88"
59 +
dependencies = [
60 +
 "cmake",
61 +
]
62 +
63 +
[[package]]
64 +
name = "glow"
65 +
version = "0.14.0"
66 +
source = "registry+https://github.com/rust-lang/crates.io-index"
67 +
checksum = "f865cbd94bd355b89611211e49508da98a1fce0ad755c1e8448fb96711b24528"
68 +
dependencies = [
69 +
 "js-sys",
70 +
 "slotmap",
71 +
 "wasm-bindgen",
72 +
 "web-sys",
73 +
]
74 +
75 +
[[package]]
76 +
name = "js-sys"
77 +
version = "0.3.66"
78 +
source = "registry+https://github.com/rust-lang/crates.io-index"
79 +
checksum = "cee9c64da59eae3b50095c18d3e74f8b73c0b86d2792824ff01bbce68ba229ca"
80 +
dependencies = [
81 +
 "wasm-bindgen",
82 +
]
83 +
84 +
[[package]]
85 +
name = "libc"
86 +
version = "0.2.150"
87 +
source = "registry+https://github.com/rust-lang/crates.io-index"
88 +
checksum = "89d92a4743f9a61002fae18374ed11e7973f530cb3a3255fb354818118b2203c"
89 +
90 +
[[package]]
91 +
name = "log"
92 +
version = "0.4.20"
93 +
source = "registry+https://github.com/rust-lang/crates.io-index"
94 +
checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f"
95 +
96 +
[[package]]
97 +
name = "nonempty"
98 +
version = "0.10.0"
99 +
source = "registry+https://github.com/rust-lang/crates.io-index"
100 +
checksum = "303e8749c804ccd6ca3b428de7fe0d86cb86bc7606bc15291f100fd487960bb8"
101 +
102 +
[[package]]
103 +
name = "objc-sys"
104 +
version = "0.3.5"
105 +
source = "registry+https://github.com/rust-lang/crates.io-index"
106 +
checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"
107 +
108 +
[[package]]
109 +
name = "objc2"
110 +
version = "0.5.2"
111 +
source = "registry+https://github.com/rust-lang/crates.io-index"
112 +
checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804"
113 +
dependencies = [
114 +
 "objc-sys",
115 +
 "objc2-encode",
116 +
]
117 +
118 +
[[package]]
119 +
name = "objc2-encode"
120 +
version = "4.0.3"
121 +
source = "registry+https://github.com/rust-lang/crates.io-index"
122 +
checksum = "7891e71393cd1f227313c9379a26a584ff3d7e6e7159e988851f0934c993f0f8"
123 +
124 +
[[package]]
125 +
name = "ombre"
126 +
version = "0.6.6"
127 +
dependencies = [
128 +
 "glfw",
129 +
 "glow",
130 +
 "log",
131 +
 "nonempty",
132 +
 "ombre",
133 +
 "ombre-derive",
134 +
 "termcolor",
135 +
]
136 +
137 +
[[package]]
138 +
name = "ombre-derive"
139 +
version = "0.1.0"
140 +
dependencies = [
141 +
 "quote",
142 +
 "syn 1.0.109",
143 +
]
144 +
145 +
[[package]]
146 +
name = "once_cell"
147 +
version = "1.18.0"
148 +
source = "registry+https://github.com/rust-lang/crates.io-index"
149 +
checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
150 +
151 +
[[package]]
152 +
name = "proc-macro2"
153 +
version = "1.0.70"
154 +
source = "registry+https://github.com/rust-lang/crates.io-index"
155 +
checksum = "39278fbbf5fb4f646ce651690877f89d1c5811a3d4acb27700c1cb3cdb78fd3b"
156 +
dependencies = [
157 +
 "unicode-ident",
158 +
]
159 +
160 +
[[package]]
161 +
name = "quote"
162 +
version = "1.0.33"
163 +
source = "registry+https://github.com/rust-lang/crates.io-index"
164 +
checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae"
165 +
dependencies = [
166 +
 "proc-macro2",
167 +
]
168 +
169 +
[[package]]
170 +
name = "raw-window-handle"
171 +
version = "0.6.2"
172 +
source = "registry+https://github.com/rust-lang/crates.io-index"
173 +
checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
174 +
175 +
[[package]]
176 +
name = "reve"
177 +
version = "0.0.0"
178 +
dependencies = [
179 +
 "log",
180 +
 "ombre",
181 +
]
182 +
183 +
[[package]]
184 +
name = "slotmap"
185 +
version = "1.0.7"
186 +
source = "registry+https://github.com/rust-lang/crates.io-index"
187 +
checksum = "dbff4acf519f630b3a3ddcfaea6c06b42174d9a44bc70c620e9ed1649d58b82a"
188 +
dependencies = [
189 +
 "version_check",
190 +
]
191 +
192 +
[[package]]
193 +
name = "syn"
194 +
version = "1.0.109"
195 +
source = "registry+https://github.com/rust-lang/crates.io-index"
196 +
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
197 +
dependencies = [
198 +
 "proc-macro2",
199 +
 "quote",
200 +
 "unicode-ident",
201 +
]
202 +
203 +
[[package]]
204 +
name = "syn"
205 +
version = "2.0.39"
206 +
source = "registry+https://github.com/rust-lang/crates.io-index"
207 +
checksum = "23e78b90f2fcf45d3e842032ce32e3f2d1545ba6636271dcbf24fa306d87be7a"
208 +
dependencies = [
209 +
 "proc-macro2",
210 +
 "quote",
211 +
 "unicode-ident",
212 +
]
213 +
214 +
[[package]]
215 +
name = "syntaxe"
216 +
version = "0.1.0"
217 +
dependencies = [
218 +
 "ombre",
219 +
]
220 +
221 +
[[package]]
222 +
name = "termcolor"
223 +
version = "1.4.0"
224 +
source = "registry+https://github.com/rust-lang/crates.io-index"
225 +
checksum = "ff1bc3d3f05aff0403e8ac0d92ced918ec05b666a43f83297ccef5bea8a3d449"
226 +
dependencies = [
227 +
 "winapi-util",
228 +
]
229 +
230 +
[[package]]
231 +
name = "unicode-ident"
232 +
version = "1.0.12"
233 +
source = "registry+https://github.com/rust-lang/crates.io-index"
234 +
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
235 +
236 +
[[package]]
237 +
name = "version_check"
238 +
version = "0.9.4"
239 +
source = "registry+https://github.com/rust-lang/crates.io-index"
240 +
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
241 +
242 +
[[package]]
243 +
name = "wasm-bindgen"
244 +
version = "0.2.89"
245 +
source = "registry+https://github.com/rust-lang/crates.io-index"
246 +
checksum = "0ed0d4f68a3015cc185aff4db9506a015f4b96f95303897bfa23f846db54064e"
247 +
dependencies = [
248 +
 "cfg-if",
249 +
 "wasm-bindgen-macro",
250 +
]
251 +
252 +
[[package]]
253 +
name = "wasm-bindgen-backend"
254 +
version = "0.2.89"
255 +
source = "registry+https://github.com/rust-lang/crates.io-index"
256 +
checksum = "1b56f625e64f3a1084ded111c4d5f477df9f8c92df113852fa5a374dbda78826"
257 +
dependencies = [
258 +
 "bumpalo",
259 +
 "log",
260 +
 "once_cell",
261 +
 "proc-macro2",
262 +
 "quote",
263 +
 "syn 2.0.39",
264 +
 "wasm-bindgen-shared",
265 +
]
266 +
267 +
[[package]]
268 +
name = "wasm-bindgen-macro"
269 +
version = "0.2.89"
270 +
source = "registry+https://github.com/rust-lang/crates.io-index"
271 +
checksum = "0162dbf37223cd2afce98f3d0785506dcb8d266223983e4b5b525859e6e182b2"
272 +
dependencies = [
273 +
 "quote",
274 +
 "wasm-bindgen-macro-support",
275 +
]
276 +
277 +
[[package]]
278 +
name = "wasm-bindgen-macro-support"
279 +
version = "0.2.89"
280 +
source = "registry+https://github.com/rust-lang/crates.io-index"
281 +
checksum = "f0eb82fcb7930ae6219a7ecfd55b217f5f0893484b7a13022ebb2b2bf20b5283"
282 +
dependencies = [
283 +
 "proc-macro2",
284 +
 "quote",
285 +
 "syn 2.0.39",
286 +
 "wasm-bindgen-backend",
287 +
 "wasm-bindgen-shared",
288 +
]
289 +
290 +
[[package]]
291 +
name = "wasm-bindgen-shared"
292 +
version = "0.2.89"
293 +
source = "registry+https://github.com/rust-lang/crates.io-index"
294 +
checksum = "7ab9b36309365056cd639da3134bf87fa8f3d86008abf99e612384a6eecd459f"
295 +
296 +
[[package]]
297 +
name = "web-sys"
298 +
version = "0.3.66"
299 +
source = "registry+https://github.com/rust-lang/crates.io-index"
300 +
checksum = "50c24a44ec86bb68fbecd1b3efed7e85ea5621b39b35ef2766b66cd984f8010f"
301 +
dependencies = [
302 +
 "js-sys",
303 +
 "wasm-bindgen",
304 +
]
305 +
306 +
[[package]]
307 +
name = "winapi"
308 +
version = "0.3.9"
309 +
source = "registry+https://github.com/rust-lang/crates.io-index"
310 +
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
311 +
dependencies = [
312 +
 "winapi-i686-pc-windows-gnu",
313 +
 "winapi-x86_64-pc-windows-gnu",
314 +
]
315 +
316 +
[[package]]
317 +
name = "winapi-i686-pc-windows-gnu"
318 +
version = "0.4.0"
319 +
source = "registry+https://github.com/rust-lang/crates.io-index"
320 +
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
321 +
322 +
[[package]]
323 +
name = "winapi-util"
324 +
version = "0.1.6"
325 +
source = "registry+https://github.com/rust-lang/crates.io-index"
326 +
checksum = "f29e6f9198ba0d26b4c9f07dbe6f9ed633e1f3d5b8b414090084349e46a52596"
327 +
dependencies = [
328 +
 "winapi",
329 +
]
330 +
331 +
[[package]]
332 +
name = "winapi-x86_64-pc-windows-gnu"
333 +
version = "0.4.0"
334 +
source = "registry+https://github.com/rust-lang/crates.io-index"
335 +
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
Cargo.toml added +26 -0
1 +
[workspace]
2 +
members = [
3 +
  "reve",
4 +
  "ombre",
5 +
  "ombre-derive",
6 +
  "syntaxe",
7 +
]
8 +
default-members = [
9 +
  "reve",
10 +
  "ombre",
11 +
  "syntaxe",
12 +
]
13 +
resolver = "2"
14 +
15 +
[workspace.dependencies]
16 +
lexopt = { version = "0.3.0" }
17 +
18 +
[workspace.lints]
19 +
clippy.unwrap_used = "warn"
20 +
clippy.let_unit_value = "allow"
21 +
clippy.single_match = "allow"
22 +
clippy.type_complexity = "allow"
23 +
clippy.too_many_arguments = "allow"
24 +
clippy.bool_assert_comparison = "allow"
25 +
clippy.len_without_is_empty = "allow"
26 +
rust.rust_2018_idioms = "warn"
README added +25 -0
1 +
2 +
 .o88b.  .88b  d88. d&888b. d8&88b. d88&8b
3 +
 d8P  Y8 88 YbdP 88 88  `8D 88  `8D 88'
4 +
 8P    8 88  88  8& 88oooY' 88oobY' 88oooo
5 +
 8b    & 88  &8  88 88^^^b. 88`8b   88^^^^
6 +
 Y8b  d8 88  88  88 88   8D 8& `88. 88.
7 +
  `Y88P' YP  YP  YP Y8888P' 88   YD Y88&8P
8 +
9 +
     Une ombre est née.
10 +
11 +
       /ˈɒmbə/
12 +
13 +
       ombre       ░  core library
14 +
       ├─ platform ░  context creation and input
15 +
       ├─ runtime  ░  application runtime on top of platform
16 +
       ├─ gfx      ░  graphics abstraction around 3D APIs
17 +
       ├─ draw     ░  2D drawing library
18 +
       ├─ math     ░  linear algebra and trigonometry library
19 +
       ├─ rng      ░  random number generation
20 +
       ├─ bytes    ░  general byte manipulation
21 +
       ├─ ui       ░  user interface toolkit
22 +
       ├─ bench    ░  benchmarking library
23 +
       └─ lisp     ░  small shadowy lisp implementation
24 +
       arbre       ░  living documents
25 +
       rêve        ░  2D/3D art tools
ombre-derive/Cargo.toml added +11 -0
1 +
[package]
2 +
name = "ombre-derive"
3 +
version = "0.1.0"
4 +
edition = "2021"
5 +
6 +
[dependencies]
7 +
syn = { version = "1.0" }
8 +
quote = { version = "1.0" }
9 +
10 +
[lib]
11 +
proc-macro = true
ombre-derive/src/lib.rs added +259 -0
1 +
//! Derive macros for the ombre crate.
2 +
use proc_macro::TokenStream;
3 +
use quote::quote;
4 +
use syn::{parse_macro_input, Data, DeriveInput, Error, Fields};
5 +
6 +
/// Derives the `VertexAttributes` trait for structs.
7 +
///
8 +
/// Fields can be renamed in the shader using `#[attrib(name = "...")]`.
9 +
#[proc_macro_derive(VertexAttributes, attributes(attrib))]
10 +
pub fn derive_vertex_attributes(input: TokenStream) -> TokenStream {
11 +
    let ast = parse_macro_input!(input as DeriveInput);
12 +
    let name = &ast.ident;
13 +
14 +
    // Only allow structs with named fields
15 +
    let fields = match &ast.data {
16 +
        Data::Struct(data) => match &data.fields {
17 +
            Fields::Named(fields) => &fields.named,
18 +
            _ => {
19 +
                return syn::Error::new_spanned(
20 +
                    name,
21 +
                    "`VertexAttributes` can only be derived for structs with named fields",
22 +
                )
23 +
                .to_compile_error()
24 +
                .into()
25 +
            }
26 +
        },
27 +
        _ => {
28 +
            return syn::Error::new_spanned(
29 +
                name,
30 +
                "`VertexAttributes` can only be derived for structs",
31 +
            )
32 +
            .to_compile_error()
33 +
            .into()
34 +
        }
35 +
    };
36 +
37 +
    // Generate attribute descriptors for each field
38 +
    let attrs = fields.iter().map(|field| {
39 +
        let field_name = field.ident.as_ref().unwrap();
40 +
        let ty = &field.ty;
41 +
42 +
        // Check for shader name override.
43 +
        let shader_name = field
44 +
            .attrs
45 +
            .iter()
46 +
            .find(|attr| attr.path.is_ident("attrib"))
47 +
            .and_then(|attr| {
48 +
                attr.parse_args_with(|input: syn::parse::ParseStream| {
49 +
                    let key: syn::Ident = input.parse()?;
50 +
                    if key != "name" {
51 +
                        return Err(syn::Error::new(
52 +
                            key.span(),
53 +
                            "unknown attribute key, only `name` is valid",
54 +
                        ));
55 +
                    }
56 +
                    input.parse::<syn::Token![=]>()?;
57 +
                    input.parse::<syn::LitStr>()
58 +
                })
59 +
                .ok()
60 +
            })
61 +
            .map(|lit| lit.value())
62 +
            .unwrap_or_else(|| field_name.to_string());
63 +
64 +
        quote! {
65 +
            ombre::gfx::VertexAttribute {
66 +
                name: #shader_name,
67 +
                format: <#ty as ombre::gfx::ToVertexFormat>::FORMAT,
68 +
            }
69 +
        }
70 +
    });
71 +
72 +
    let expanded = quote! {
73 +
        impl ombre::gfx::VertexAttributes for #name {
74 +
            fn attributes() -> &'static [ombre::gfx::VertexAttribute] {
75 +
                static ATTRS: &[ombre::gfx::VertexAttribute] = &[#(#attrs),*];
76 +
                ATTRS
77 +
            }
78 +
        }
79 +
        unsafe impl ombre::bytes::Packed for #name {}
80 +
    };
81 +
    TokenStream::from(expanded)
82 +
}
83 +
84 +
/// Derive macro for implementing the `UniformBlock` trait.
85 +
#[proc_macro_derive(UniformBlock, attributes(uniform))]
86 +
pub fn derive_uniform_block(input: TokenStream) -> TokenStream {
87 +
    let ast = parse_macro_input!(input as DeriveInput);
88 +
    let name = &ast.ident;
89 +
90 +
    // Only allow structs with named fields
91 +
    let fields = match &ast.data {
92 +
        Data::Struct(data) => match &data.fields {
93 +
            Fields::Named(fields) => &fields.named,
94 +
            _ => {
95 +
                return Error::new_spanned(
96 +
                    name,
97 +
                    "`UniformBlock` can only be derived for structs with named fields",
98 +
                )
99 +
                .to_compile_error()
100 +
                .into()
101 +
            }
102 +
        },
103 +
        _ => {
104 +
            return Error::new_spanned(name, "`UniformBlock` can only be derived for structs")
105 +
                .to_compile_error()
106 +
                .into()
107 +
        }
108 +
    };
109 +
110 +
    // Generate uniform descriptors for each field.
111 +
    let descriptors = fields.iter().map(|field| {
112 +
        let field_ident = field.ident.as_ref().unwrap();
113 +
        let ty = &field.ty;
114 +
115 +
        // Check for shader name override
116 +
        let uniform_name = field
117 +
            .attrs
118 +
            .iter()
119 +
            .find(|attr| attr.path.is_ident("uniform"))
120 +
            .and_then(|attr| {
121 +
                attr.parse_args_with(|input: syn::parse::ParseStream| {
122 +
                    let key: syn::Ident = input.parse()?;
123 +
                    if key != "name" {
124 +
                        return Err(syn::Error::new(
125 +
                            key.span(),
126 +
                            "unknown uniform attribute key, only `name` is valid",
127 +
                        ));
128 +
                    }
129 +
                    input.parse::<syn::Token![=]>()?;
130 +
                    input.parse::<syn::LitStr>()
131 +
                })
132 +
                .ok()
133 +
            })
134 +
            .map(|lit| lit.value())
135 +
            .unwrap_or_else(|| field_ident.to_string());
136 +
137 +
        quote! {
138 +
            ombre::gfx::UniformDescriptor {
139 +
                name: #uniform_name,
140 +
                kind: <#ty as ombre::gfx::ToUniformKind>::KIND,
141 +
                arity: <#ty as ombre::gfx::ToUniformKind>::ARITY,
142 +
            }
143 +
        }
144 +
    });
145 +
146 +
    let (_, ty_generics, where_clause) = ast.generics.split_for_impl();
147 +
    let const_params = ast.generics.const_params().collect::<Vec<_>>();
148 +
    let lifetime_params = ast.generics.lifetimes().collect::<Vec<_>>();
149 +
150 +
    let expanded = quote! {
151 +
        impl<'block, #(#lifetime_params,)* #(#const_params,)*> ombre::gfx::UniformBlock<'block>
152 +
        for #name #ty_generics #where_clause {
153 +
            fn layout() -> ombre::gfx::UniformBlockLayout<'block> {
154 +
                let uniforms = &[#(#descriptors),*];
155 +
                ombre::gfx::UniformBlockLayout {
156 +
                    uniforms
157 +
                }
158 +
            }
159 +
        }
160 +
        unsafe impl<#(#lifetime_params,)* #(#const_params,)*> ombre::bytes::Packed
161 +
        for #name #ty_generics #where_clause {}
162 +
    };
163 +
164 +
    TokenStream::from(expanded)
165 +
}
166 +
167 +
/// Derive macro for generating lens types for struct fields.
168 +
#[proc_macro_derive(Lenses, attributes(lens))]
169 +
pub fn derive_lenses(input: TokenStream) -> TokenStream {
170 +
    let ast = parse_macro_input!(input as DeriveInput);
171 +
    let name = &ast.ident;
172 +
173 +
    // Only allow structs with named fields
174 +
    let fields = match &ast.data {
175 +
        Data::Struct(data) => match &data.fields {
176 +
            Fields::Named(fields) => &fields.named,
177 +
            _ => {
178 +
                return Error::new_spanned(
179 +
                    name,
180 +
                    "`Lenses` can only be derived for structs with named fields",
181 +
                )
182 +
                .to_compile_error()
183 +
                .into()
184 +
            }
185 +
        },
186 +
        _ => {
187 +
            return Error::new_spanned(name, "`Lenses` can only be derived for structs")
188 +
                .to_compile_error()
189 +
                .into()
190 +
        }
191 +
    };
192 +
193 +
    // Generate lens implementations for fields with #[lens] attribute
194 +
    let lens_impls = fields.iter().filter_map(|field| {
195 +
        if field.attrs.iter().any(|attr| attr.path.is_ident("lens")) {
196 +
            let field_name = &field.ident.as_ref().unwrap();
197 +
            let field_type = &field.ty;
198 +
            let lens_name = quote::format_ident!("{}Lens", field_name);
199 +
            let lens_doc = format!(
200 +
                "Lens for accessing the `{field_name}` field of [`{name}`].\n\n\
201 +
                This lens allows you to get and modify the `{field_name}` field.",
202 +
            );
203 +
            let const_doc = format!(
204 +
                "A lens for the `{field_name}` field of [`{name}`].\n\n\
205 +
                Use this constant to access or modify the `{field_name}` field.",
206 +
            );
207 +
208 +
            Some(quote! {
209 +
                #[doc = #lens_doc]
210 +
                #[allow(non_camel_case_types)]
211 +
                #[derive(Debug, Clone, Copy)]
212 +
                pub struct #lens_name;
213 +
214 +
                impl Lens<#name, #field_type> for #lens_name {
215 +
                    fn with<V, F: FnOnce(&#field_type) -> V>(&self, data: &#name, f: F) -> V {
216 +
                        f(&data.#field_name)
217 +
                    }
218 +
219 +
                    fn with_mut<V, F: FnOnce(&mut #field_type) -> V>(&self, data: &mut #name, f: F) -> V {
220 +
                        f(&mut data.#field_name)
221 +
                    }
222 +
                }
223 +
224 +
                impl #name {
225 +
                    #[doc = #const_doc]
226 +
                    #[allow(non_upper_case_globals)]
227 +
                    pub const #field_name: #lens_name = #lens_name;
228 +
                }
229 +
            })
230 +
        } else {
231 +
            None
232 +
        }
233 +
    });
234 +
235 +
    TokenStream::from(quote!(#(#lens_impls)*))
236 +
}
237 +
238 +
/// Derive macro for implementing the `Packed` trait.
239 +
#[proc_macro_derive(Packed)]
240 +
pub fn derive_packed(input: TokenStream) -> TokenStream {
241 +
    let ast = parse_macro_input!(input as DeriveInput);
242 +
    let name = &ast.ident;
243 +
    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
244 +
    let data = match ast.data {
245 +
        Data::Struct(data) => data,
246 +
        _ => {
247 +
            return Error::new_spanned(&ast, "`Packed` can only be derived for structs")
248 +
                .to_compile_error()
249 +
                .into()
250 +
        }
251 +
    };
252 +
    let field_types = data.fields.iter().map(|f| &f.ty);
253 +
254 +
    quote! {
255 +
        unsafe impl #impl_generics ombre::bytes::Packed for #name #ty_generics #where_clause
256 +
        where #(#field_types: ombre::bytes::Packed,)* {}
257 +
    }
258 +
    .into()
259 +
}
ombre/Cargo.toml added +29 -0
1 +
[package]
2 +
name = "ombre"
3 +
description = "Ombre context creation and graphics library"
4 +
version = "0.6.6"
5 +
edition = "2021"
6 +
keywords = ["graphics", "gamedev", "game"]
7 +
categories = ["graphics", "rendering", "game-development"]
8 +
authors = ["cloudhead <self@cloudhead.io>"]
9 +
10 +
[features]
11 +
default = ["glfw", "color-logging"]
12 +
color-logging = ["termcolor"]
13 +
derive = ["ombre-derive"]
14 +
draw = ["derive"]
15 +
ui = ["draw"]
16 +
17 +
[dependencies]
18 +
glfw = { version = "0.58.0", optional = true }
19 +
glow = { version = "0.14.0" }
20 +
log = { version = "0.4.20", features = ["std"] }
21 +
ombre-derive = { version = "0.1.0", path = "../ombre-derive", optional = true }
22 +
nonempty = { version = "0.10.0" }
23 +
termcolor = { version = "1.4.0", optional = true }
24 +
25 +
[lints]
26 +
workspace = true
27 +
28 +
[dev-dependencies]
29 +
ombre = { version = "0.6.6", features = ["derive", "ui"], path = "." }
ombre/README.md added +63 -0
1 +
# ombre
2 +
3 +
> Context creation, graphics and input library.
4 +
5 +
## Synopsis
6 +
7 +
Ombre is a "New Jersey" style[^0] library designed for games and graphics
8 +
programming on the desktop.
9 +
10 +
It provides a thin layer of abstraction over the underlying context creation
11 +
and graphics frameworks while keeping dependencies to a bare minimum, and
12 +
trying to do the few things it does *really well*.
13 +
Ombre also comes with support for various simple file formats that are designed
14 +
to be easy encode and decode. This is in contrast to more popular formats like
15 +
PNG and TTF which would likely call for external libraries.
16 +
17 +
Despite all of the above, Ombre is not meant as a "toy" library. Performance,
18 +
stability, flexibility and developer friendliness are not compromised. Though
19 +
certain defaults are chosen, such as the graphics backend, the user is able
20 +
to easily swap out backends for something more appropriate to their target
21 +
platform.
22 +
23 +
## Features
24 +
25 +
* Context creation and input handling using `glfw`[^1]
26 +
* Graphics API inspired by `sokol-gfx`[^2]
27 +
* Cross-platform using an OpenGL 3.3 backend with `glow`[^3]
28 +
* Bitmap font rendering support for UF1 and UF2 fonts[^4]
29 +
* Image encoding and decoding using the simple RGBA (`.rgba`) file format
30 +
* Computer graphics `math` module with 2D and 3D vectors and transforms
31 +
* Color types and functions
32 +
33 +
## Rationale
34 +
35 +
* Since all major platforms support OpenGL 3.3, and will do for the foreseable
36 +
future, there is no reason to target anything else. The `glow` crate is used
37 +
for its simplicity, portability, and bare-bones type safety.
38 +
* For context creation and input handling, GLFW is chosen for its maturity and
39 +
stability, while staying minimal and offering the most flexibility without
40 +
taking away control from the user.
41 +
* Popular font and image formats such as TTF and PNG are explicitly not
42 +
supported due to their complexity and low value-add.
43 +
* 3D math is implemented in-house, to avoid depending on yet another
44 +
abandonned math library, and to offer the best experience.
45 +
* Trying to support all platforms including web and mobile with a single
46 +
API is bound to leak platform details. We avoid that by focusing on OpenGL
47 +
and desktop graphics.
48 +
49 +
## Acknowledgments
50 +
51 +
Big chunks of this library were adapted from `miniquad` by Fedor Logachev,
52 +
which itself is adapted from `sokol`, by Andre Weissflog. Additionally, much
53 +
of the 3D math code was borrowed from `cgmath`, and `euclid` by the Servo
54 +
Project Developers. Finally it's worth mentioning that `druid`, by Raph
55 +
Levien has served as inspiration for the UI code, and some of the math code.
56 +
57 +
## References
58 +
59 +
[^0]: https://dreamsongs.com/WorseIsBetter.html
60 +
[^1]: https://www.glfw.org/
61 +
[^2]: https://floooh.github.io/2017/07/29/sokol-gfx-tour.html
62 +
[^3]: https://crates.io/crates/glow
63 +
[^4]: https://wiki.xxiivv.com/site/ufx_format.html
ombre/examples/button.rs added +49 -0
1 +
#![deny(clippy::all)]
2 +
#![allow(clippy::unwrap_used)]
3 +
#[path = "common/runtime.rs"]
4 +
mod runtime;
5 +
6 +
use ombre::prelude::*;
7 +
use ombre::ui as gui;
8 +
use ombre::ui::widgets::*;
9 +
10 +
pub struct Example<T> {
11 +
    ui: gui::Interface<Box<dyn Widget<()>>, ()>,
12 +
    backend: T,
13 +
}
14 +
15 +
impl<T: gfx::RenderBackend> Example<T> {
16 +
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, gui::Error<T>> {
17 +
        let root = button("Click me!", |_, _, _| println!("Clicked!")).center().boxed();
18 +
        let ui = gui::interface(win, &mut backend).scale(2.0).build(root)?;
19 +
20 +
        Ok(Self { backend, ui })
21 +
    }
22 +
}
23 +
24 +
impl<T: RenderBackend> Application for Example<T> {
25 +
    type Error = T::Error;
26 +
27 +
    fn event(
28 +
        &mut self,
29 +
        event: platform::WindowEvent,
30 +
        win: &mut platform::Window,
31 +
    ) -> Result<(), T::Error> {
32 +
        self.ui.event(event, &mut (), &mut self.backend, win)?;
33 +
34 +
        Ok(())
35 +
    }
36 +
37 +
    fn frame(&mut self) -> Result<(), Self::Error> {
38 +
        let mut frame = self.backend.frame();
39 +
        self.ui.frame(&(), &mut frame)?;
40 +
41 +
        frame.commit();
42 +
43 +
        Ok(())
44 +
    }
45 +
}
46 +
47 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
48 +
    runtime::run("button", Example::init)
49 +
}
ombre/examples/buttons.rs added +100 -0
1 +
#![deny(clippy::all)]
2 +
#![allow(clippy::unwrap_used)]
3 +
#[path = "common/runtime.rs"]
4 +
mod runtime;
5 +
6 +
use ombre::prelude::*;
7 +
use ombre::ui as gui;
8 +
use ombre::ui::widgets::*;
9 +
10 +
#[derive(Default)]
11 +
struct Data {
12 +
    red: (u64, bool),
13 +
    blue: (u64, bool),
14 +
    green: (u64, bool),
15 +
}
16 +
17 +
pub struct Example<T> {
18 +
    ui: gui::Interface<Box<dyn Widget<Data>>, Data>,
19 +
    data: Data,
20 +
    backend: T,
21 +
}
22 +
23 +
impl<T: gfx::RenderBackend> Example<T> {
24 +
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, gui::Error<T>> {
25 +
        let root = zstack((
26 +
            canvas(|data: &Data, bounds, mut p| {
27 +
                p.fill(bounds, Rgba8::BLUE.alpha(0x80));
28 +
                p.write(
29 +
                    format!("{} ({})", data.blue.0, data.blue.1),
30 +
                    Rgba::WHITE,
31 +
                    bounds,
32 +
                );
33 +
            })
34 +
            .sized((256., 256.))
35 +
            .on_click(|_, data, _| data.blue.0 += 1)
36 +
            .on_hover(|_, hovered, data, _| data.blue.1 = hovered)
37 +
            .center(),
38 +
            canvas(|data: &Data, bounds, mut p| {
39 +
                p.fill(bounds, Rgba8::RED.alpha(0x80));
40 +
                p.write(
41 +
                    format!("{} ({})", data.red.0, data.red.1),
42 +
                    Rgba::WHITE,
43 +
                    bounds,
44 +
                );
45 +
            })
46 +
            .sized((192., 192.))
47 +
            .on_click(|_, data, _| data.red.0 += 1)
48 +
            .on_hover(|_, hovered, data, _| data.red.1 = hovered)
49 +
            .center(),
50 +
            canvas(|data: &Data, bounds, mut p| {
51 +
                p.fill(bounds, Rgba8::GREEN.alpha(0x80));
52 +
                p.write(
53 +
                    format!("{} ({})", data.green.0, data.green.1),
54 +
                    Rgba::WHITE,
55 +
                    bounds,
56 +
                );
57 +
            })
58 +
            .sized((128., 128.))
59 +
            .on_click(|_, data, _| data.green.0 += 1)
60 +
            .on_hover(|_, hovered, data, _| data.green.1 = hovered)
61 +
            .center(),
62 +
        ))
63 +
        .boxed();
64 +
65 +
        let ui = gui::interface(win, &mut backend).scale(2.0).build(root)?;
66 +
67 +
        Ok(Self {
68 +
            backend,
69 +
            data: Data::default(),
70 +
            ui,
71 +
        })
72 +
    }
73 +
}
74 +
75 +
impl<T: RenderBackend> Application for Example<T> {
76 +
    type Error = T::Error;
77 +
78 +
    fn event(
79 +
        &mut self,
80 +
        event: platform::WindowEvent,
81 +
        win: &mut platform::Window,
82 +
    ) -> Result<(), T::Error> {
83 +
        self.ui.event(event, &mut self.data, &mut self.backend, win)?;
84 +
85 +
        Ok(())
86 +
    }
87 +
88 +
    fn frame(&mut self) -> Result<(), Self::Error> {
89 +
        let mut frame = self.backend.frame();
90 +
        self.ui.frame(&self.data, &mut frame)?;
91 +
92 +
        frame.commit();
93 +
94 +
        Ok(())
95 +
    }
96 +
}
97 +
98 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
99 +
    runtime::run("buttons", Example::init)
100 +
}
ombre/examples/canvas.rs added +60 -0
1 +
#![deny(clippy::all)]
2 +
#[path = "common/runtime.rs"]
3 +
mod runtime;
4 +
5 +
use ombre::prelude::*;
6 +
use ombre::ui as gui;
7 +
use ombre::ui::widgets::*;
8 +
9 +
type State = Vec<Point2D<f32, Local>>;
10 +
11 +
pub struct Example<T> {
12 +
    ui: gui::Interface<Click<Canvas<State>, State>, State>,
13 +
    state: State,
14 +
    backend: T,
15 +
}
16 +
17 +
impl<T: gfx::RenderBackend> Example<T> {
18 +
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, gui::Error<T>> {
19 +
        let root = gui::canvas(move |state: &State, view, mut g| {
20 +
            g.stroke(view, Rgba8::BLUE, 9.);
21 +
            for click in state.iter().copied() {
22 +
                g.fill(Rect::centered(click, Size::from(18.)), Rgba8::GREEN);
23 +
            }
24 +
        })
25 +
        .on_click(|_, state, ctx| state.push(ctx.cursor.convert()));
26 +
27 +
        let ui = gui::interface(win, &mut backend).scale(2.0).build(root)?;
28 +
29 +
        Ok(Self {
30 +
            backend,
31 +
            ui,
32 +
            state: Vec::new(),
33 +
        })
34 +
    }
35 +
}
36 +
37 +
impl<T: RenderBackend> Application for Example<T> {
38 +
    type Error = T::Error;
39 +
40 +
    fn event(
41 +
        &mut self,
42 +
        event: platform::WindowEvent,
43 +
        win: &mut platform::Window,
44 +
    ) -> Result<(), T::Error> {
45 +
        self.ui.event(event, &mut self.state, &mut self.backend, win)?;
46 +
47 +
        Ok(())
48 +
    }
49 +
50 +
    fn frame(&mut self) -> Result<(), Self::Error> {
51 +
        let mut frame = self.backend.frame();
52 +
        self.ui.frame(&self.state, &mut frame)?;
53 +
54 +
        Ok(())
55 +
    }
56 +
}
57 +
58 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
59 +
    runtime::run("canvas", Example::init)
60 +
}
ombre/examples/checkbox.rs added +64 -0
1 +
#![deny(clippy::all)]
2 +
#![allow(clippy::unwrap_used)]
3 +
#[path = "common/runtime.rs"]
4 +
mod runtime;
5 +
6 +
use ombre::prelude::*;
7 +
use ombre::ui as gui;
8 +
use ombre::ui::widgets::*;
9 +
10 +
pub struct Example<T> {
11 +
    ui: gui::Interface<Box<dyn Widget<bool>>, bool>,
12 +
    checked: bool,
13 +
    backend: T,
14 +
}
15 +
16 +
const POINTER: &[u8] = include_bytes!("common/pointer.rgba");
17 +
18 +
impl<T: gfx::RenderBackend> Example<T> {
19 +
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, gui::Error<T>> {
20 +
        let root = checkbox("Check me!").center().boxed();
21 +
        let pointer = gfx::Image::try_from(POINTER).unwrap();
22 +
        let ui = gui::interface(win, &mut backend)
23 +
            .scale(4.0)
24 +
            .cursor(gui::CursorDescriptor {
25 +
                name: "pointer",
26 +
                image: pointer,
27 +
                origin: Point2D::ORIGIN,
28 +
            })?
29 +
            .build(root)?;
30 +
31 +
        Ok(Self {
32 +
            backend,
33 +
            ui,
34 +
            checked: false,
35 +
        })
36 +
    }
37 +
}
38 +
39 +
impl<T: RenderBackend> Application for Example<T> {
40 +
    type Error = T::Error;
41 +
42 +
    fn event(
43 +
        &mut self,
44 +
        event: platform::WindowEvent,
45 +
        win: &mut platform::Window,
46 +
    ) -> Result<(), T::Error> {
47 +
        self.ui.event(event, &mut self.checked, &mut self.backend, win)?;
48 +
49 +
        Ok(())
50 +
    }
51 +
52 +
    fn frame(&mut self) -> Result<(), Self::Error> {
53 +
        let mut frame = self.backend.frame();
54 +
        self.ui.frame(&self.checked, &mut frame)?;
55 +
56 +
        frame.commit();
57 +
58 +
        Ok(())
59 +
    }
60 +
}
61 +
62 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
63 +
    runtime::run("checkbox", Example::init)
64 +
}
ombre/examples/circles.rs added +149 -0
1 +
#![deny(clippy::all)]
2 +
#[path = "common/runtime.rs"]
3 +
mod runtime;
4 +
5 +
use ombre::draw::{
6 +
    batch::{TextureInfo, VertexBatch},
7 +
    pipeline,
8 +
    pipeline::*,
9 +
    shape::Circle,
10 +
};
11 +
use ombre::prelude::*;
12 +
use ombre::ui as gui;
13 +
14 +
pub struct Example<T> {
15 +
    pipeline: gfx::PipelineId,
16 +
    bindings: gfx::Bindings<1, 1>,
17 +
    width: f64,
18 +
    height: f64,
19 +
    radius: f32,
20 +
    blank: TextureInfo,
21 +
    cursor: Point2D<f32, Screen>,
22 +
    backend: T,
23 +
}
24 +
25 +
impl<T: gfx::RenderBackend> Example<T> {
26 +
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, gui::Error<T>> {
27 +
        let size = win.size();
28 +
        let vbo = backend
29 +
            .buffer(
30 +
                gfx::BufferKind::Vertex,
31 +
                gfx::BufferUsage::Stream,
32 +
                gfx::BufferSource::<Vertex>::empty(2usize.pow(17)),
33 +
            )
34 +
            .map_err(gui::Error::Render)?;
35 +
        let blank = backend
36 +
            .texture(gfx::Texture::<[[u8; 4]; 1]>::WHITE)
37 +
            .map_err(gui::Error::Render)?;
38 +
        let bindings = gfx::Bindings {
39 +
            vertex: [vbo],
40 +
            index: None,
41 +
            textures: [blank],
42 +
        };
43 +
        let pipeline = pipeline::create::<_, 1>(&mut backend).map_err(gui::Error::Render)?;
44 +
45 +
        Ok(Self {
46 +
            backend,
47 +
            pipeline,
48 +
            bindings,
49 +
            blank: TextureInfo {
50 +
                id: blank,
51 +
                size: gfx::Texture::<[[u8; 4]; 1]>::WHITE.size,
52 +
            },
53 +
            radius: 32.,
54 +
            cursor: Point2D::ORIGIN,
55 +
            width: size.width,
56 +
            height: size.height,
57 +
        })
58 +
    }
59 +
}
60 +
61 +
impl<T: RenderBackend> Application for Example<T> {
62 +
    type Error = T::Error;
63 +
64 +
    fn event(
65 +
        &mut self,
66 +
        event: platform::WindowEvent,
67 +
        _win: &mut platform::Window,
68 +
    ) -> Result<(), Self::Error> {
69 +
        match event {
70 +
            platform::WindowEvent::Resized(size) => {
71 +
                self.width = size.width;
72 +
                self.height = size.height;
73 +
            }
74 +
            platform::WindowEvent::KeyboardInput(i) if i.is_pressed() => {
75 +
                if i.key == Some(platform::Key::Space) {
76 +
                    self.radius *= 2.;
77 +
                    if self.radius == 1024. {
78 +
                        self.radius = 32.;
79 +
                    }
80 +
                }
81 +
            }
82 +
            platform::WindowEvent::CursorMoved { position } => {
83 +
                self.cursor = Point2D::new(position.x as f32, position.y as f32);
84 +
            }
85 +
            _ => {}
86 +
        }
87 +
        Ok(())
88 +
    }
89 +
90 +
    fn frame(&mut self) -> Result<(), Self::Error> {
91 +
        let mut batch = VertexBatch::new(self.blank.clone());
92 +
        let radius = self.radius;
93 +
        let rows = (self.height as f32 / (radius * 2.)) as u32 + 1;
94 +
        let cols = (self.width as f32 / (radius * 2.)) as u32 + 1;
95 +
        let cursor: Vector2D<f32, Screen> = Vector2D::new(
96 +
            self.cursor.x / self.width as f32,
97 +
            self.cursor.y / self.height as f32,
98 +
        );
99 +
100 +
        for i in 0..rows {
101 +
            let y = i as f32 * radius * 2. + radius;
102 +
103 +
            for j in 0..cols {
104 +
                let x = j as f32 * radius * 2. + radius;
105 +
106 +
                // Color.
107 +
                let c1 = i as f32 / rows as f32;
108 +
                let c2 = j as f32 / cols as f32;
109 +
110 +
                let center = Vector2D::new(x / self.width as f32, y / self.height as f32);
111 +
                let delta = Vector2D::distance(center, cursor);
112 +
                let width = f32::max(1., delta * radius);
113 +
114 +
                batch.stroke(
115 +
                    Circle::new(Point2D::new(x, y), radius, 8),
116 +
                    Rgba::new(0.5, c2, c1, 0.75),
117 +
                    width,
118 +
                );
119 +
            }
120 +
        }
121 +
122 +
        let buffer = batch.vertices();
123 +
        self.backend
124 +
            .buffer_update(self.bindings.vertex[0], BufferKind::Vertex, 0, &buffer)?;
125 +
126 +
        let mut frame = self.backend.frame();
127 +
128 +
        frame.begin_default_pass(
129 +
            PassAction::default(),
130 +
            Size::new(self.width as u32, self.height as u32),
131 +
        );
132 +
        frame.apply_pipeline(&self.pipeline)?;
133 +
        frame.apply_bindings(&self.bindings)?;
134 +
        frame.apply_uniforms(&Uniforms::<1>::new(
135 +
            [self.width as f32, self.height as f32],
136 +
            Transform3D::identity(),
137 +
            Default::default(),
138 +
        ))?;
139 +
        frame.draw(0, buffer.len(), 1)?;
140 +
        frame.end_pass();
141 +
        frame.commit();
142 +
143 +
        Ok(())
144 +
    }
145 +
}
146 +
147 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
148 +
    runtime::run("circles", Example::init)
149 +
}
ombre/examples/common/grab.rgba added +0 -0

Binary file changed.

ombre/examples/common/hand.rgba added +0 -0

Binary file changed.

ombre/examples/common/pointer.rgba added +0 -0

Binary file changed.

ombre/examples/common/runtime.rs added +21 -0
1 +
use ombre::math::Size;
2 +
use ombre::ui as gui;
3 +
use ombre::{gfx, platform};
4 +
5 +
pub fn run<R: ombre::runtime::Application>(
6 +
    name: &str,
7 +
    example: fn(gfx::gl::Context, &platform::Window) -> Result<R, gui::Error<gfx::gl::Context>>,
8 +
) -> Result<(), Box<dyn std::error::Error>> {
9 +
    ombre::logger::init(log::Level::Debug)?;
10 +
11 +
    let size = Size::new(640, 480);
12 +
    let (mut win, events) =
13 +
        platform::init(name, size.w, size.h, &[], platform::GraphicsContext::Gl)?;
14 +
    let ctx = unsafe { ombre::glow::Context::from_loader_function(|p| win.get_proc_address(p)) };
15 +
    let backend = gfx::gl::Context::new(ctx, win.size())?;
16 +
    let example = example(backend, &win)?;
17 +
18 +
    ombre::runtime::default::run(win, events, example)?;
19 +
20 +
    Ok(())
21 +
}
ombre/examples/common/rx.rgba added +0 -0

Binary file changed.

ombre/examples/counter.rs added +61 -0
1 +
#![deny(clippy::all)]
2 +
#[path = "common/runtime.rs"]
3 +
mod runtime;
4 +
5 +
use gui::{Widget, WidgetExt as _, WidgetInteract as _};
6 +
use ombre::prelude::*;
7 +
use ombre::ui as gui;
8 +
9 +
type State = usize;
10 +
11 +
pub struct Example<R> {
12 +
    ui: gui::Interface<Box<dyn Widget<State>>, State>,
13 +
    state: State,
14 +
    backend: R,
15 +
}
16 +
17 +
impl<R: gfx::RenderBackend> Example<R> {
18 +
    pub fn init(mut backend: R, win: &platform::Window) -> Result<Self, gui::Error<R>> {
19 +
        let root = gui::label(|s: &State| s.to_string())
20 +
            .center()
21 +
            .sized([32., 48.])
22 +
            .stroke(Rgba::WHITE)
23 +
            .on_click(|_, state, _| *state += 1)
24 +
            .center()
25 +
            .boxed();
26 +
27 +
        let ui = gui::interface(win, &mut backend)
28 +
            .font(gui::fonts::uf2::VENICE)?
29 +
            .scale(4.0)
30 +
            .build(root)?;
31 +
32 +
        Ok(Self {
33 +
            ui,
34 +
            state: State::default(),
35 +
            backend,
36 +
        })
37 +
    }
38 +
}
39 +
40 +
impl<R: RenderBackend> Application for Example<R> {
41 +
    type Error = R::Error;
42 +
43 +
    fn event(
44 +
        &mut self,
45 +
        event: platform::WindowEvent,
46 +
        win: &mut platform::Window,
47 +
    ) -> Result<(), R::Error> {
48 +
        self.ui.event(event, &mut self.state, &mut self.backend, win)
49 +
    }
50 +
51 +
    fn frame(&mut self) -> Result<(), Self::Error> {
52 +
        let mut frame = self.backend.frame();
53 +
        self.ui.frame(&self.state, &mut frame)?;
54 +
55 +
        Ok(())
56 +
    }
57 +
}
58 +
59 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
60 +
    runtime::run("counter", Example::init)
61 +
}
ombre/examples/cursors.rs added +84 -0
1 +
#![deny(clippy::all)]
2 +
#![allow(clippy::unwrap_used)]
3 +
#[path = "common/runtime.rs"]
4 +
mod runtime;
5 +
6 +
use ombre::prelude::*;
7 +
use ombre::ui as gui;
8 +
use ombre::ui::{CursorDescriptor, Widget, WidgetExt as _};
9 +
10 +
type State = usize;
11 +
12 +
pub struct Example<R> {
13 +
    ui: gui::Interface<Box<dyn Widget<State>>, State>,
14 +
    state: State,
15 +
    backend: R,
16 +
}
17 +
18 +
const POINTER: &[u8] = include_bytes!("common/pointer.rgba");
19 +
const GRAB: &[u8] = include_bytes!("common/grab.rgba");
20 +
const HAND: &[u8] = include_bytes!("common/hand.rgba");
21 +
22 +
impl<R: gfx::RenderBackend> Example<R> {
23 +
    pub fn init(mut backend: R, window: &platform::Window) -> Result<Self, gui::Error<R>> {
24 +
        let root = gui::zstack([
25 +
            Rgba8::BLUE.cursor("grab").sized([128., 128.]).boxed(),
26 +
            Rgba8::GREEN.cursor("hand").sized([96., 96.]).boxed(),
27 +
            Rgba8::RED.cursor("pointer").sized([64., 64.]).boxed(),
28 +
        ])
29 +
        .center()
30 +
        .boxed();
31 +
        let pointer = Image::try_from(POINTER).unwrap();
32 +
        let grab = Image::try_from(GRAB).unwrap();
33 +
        let hand = Image::try_from(HAND).unwrap();
34 +
        let ui = gui::interface(window, &mut backend)
35 +
            .scale(2.0)
36 +
            .cursor(CursorDescriptor {
37 +
                name: "pointer",
38 +
                image: pointer,
39 +
                origin: Point2D::ORIGIN,
40 +
            })?
41 +
            .cursor(CursorDescriptor {
42 +
                name: "grab",
43 +
                image: grab,
44 +
                origin: Point2D::ORIGIN,
45 +
            })?
46 +
            .cursor(CursorDescriptor {
47 +
                name: "hand",
48 +
                image: hand,
49 +
                origin: Point2D::ORIGIN,
50 +
            })?
51 +
            .build(root)?;
52 +
53 +
        Ok(Self {
54 +
            ui,
55 +
            state: State::default(),
56 +
            backend,
57 +
        })
58 +
    }
59 +
}
60 +
61 +
impl<R: RenderBackend> Application for Example<R> {
62 +
    type Error = R::Error;
63 +
64 +
    fn event(
65 +
        &mut self,
66 +
        event: platform::WindowEvent,
67 +
        win: &mut platform::Window,
68 +
    ) -> Result<(), R::Error> {
69 +
        let cursor = win.get_cursor_pos();
70 +
        win.set_title(format!("{}, {}", cursor.x, cursor.y).as_str());
71 +
        self.ui.event(event, &mut self.state, &mut self.backend, win)
72 +
    }
73 +
74 +
    fn frame(&mut self) -> Result<(), Self::Error> {
75 +
        let mut frame = self.backend.frame();
76 +
        self.ui.frame(&self.state, &mut frame)?;
77 +
78 +
        Ok(())
79 +
    }
80 +
}
81 +
82 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
83 +
    runtime::run("cursors", Example::init)
84 +
}
ombre/examples/fonts.rs added +60 -0
1 +
#![deny(clippy::all)]
2 +
#![allow(clippy::unwrap_used)]
3 +
#[path = "common/runtime.rs"]
4 +
mod runtime;
5 +
6 +
use ombre::prelude::*;
7 +
use ombre::ui as gui;
8 +
use ombre::ui::widgets::*;
9 +
use ombre::ui::TextAlign;
10 +
11 +
pub struct Example<T> {
12 +
    ui: gui::Interface<Box<dyn Widget<()>>, ()>,
13 +
    backend: T,
14 +
}
15 +
16 +
impl<T: gfx::RenderBackend> Example<T> {
17 +
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, gui::Error<T>> {
18 +
        let venice = gui::fonts::uf2::VENICE;
19 +
        let default = gui::fonts::uf2::DEFAULT;
20 +
        let text = "Sphinx. $%/~_Jq!`,|";
21 +
        let ui = gui::interface(win, &mut backend).font(venice)?.scale(20.0).build(
22 +
            gui::label(text)
23 +
                .align(TextAlign::Center)
24 +
                .font(default.name)
25 +
                .sized([f32::MAX, 18.])
26 +
                .fill(Rgba8::RED.alpha(32))
27 +
                .center()
28 +
                .boxed(),
29 +
        )?;
30 +
31 +
        Ok(Self { backend, ui })
32 +
    }
33 +
}
34 +
35 +
impl<T: RenderBackend> Application for Example<T> {
36 +
    type Error = T::Error;
37 +
38 +
    fn event(
39 +
        &mut self,
40 +
        event: platform::WindowEvent,
41 +
        win: &mut platform::Window,
42 +
    ) -> Result<(), T::Error> {
43 +
        self.ui.event(event, &mut (), &mut self.backend, win)?;
44 +
45 +
        Ok(())
46 +
    }
47 +
48 +
    fn frame(&mut self) -> Result<(), Self::Error> {
49 +
        let mut frame = self.backend.frame();
50 +
        self.ui.frame(&(), &mut frame)?;
51 +
52 +
        frame.commit();
53 +
54 +
        Ok(())
55 +
    }
56 +
}
57 +
58 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
59 +
    runtime::run("fonts", Example::init)
60 +
}
ombre/examples/hover.rs added +63 -0
1 +
#![deny(clippy::all)]
2 +
#![allow(clippy::unwrap_used)]
3 +
#[path = "common/runtime.rs"]
4 +
mod runtime;
5 +
6 +
use ombre::prelude::*;
7 +
use ombre::ui as gui;
8 +
use ombre::ui::widgets::*;
9 +
10 +
pub struct Example<T> {
11 +
    ui: gui::Interface<Box<dyn Widget<()>>, ()>,
12 +
    backend: T,
13 +
}
14 +
15 +
impl<T: gfx::RenderBackend> Example<T> {
16 +
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, gui::Error<T>> {
17 +
        let items = vec![
18 +
            Rgba8::RED
19 +
                .on_hover(|s, _, _, _| *s = s.invert())
20 +
                .sized([32., 32.])
21 +
                .boxed(),
22 +
            Rgba8::GREEN
23 +
                .on_hover(|s, _, _, _| *s = s.invert())
24 +
                .sized([32., 32.])
25 +
                .boxed(),
26 +
            Rgba8::BLUE
27 +
                .on_hover(|s, _, _, _| *s = s.invert())
28 +
                .sized([32., 32.])
29 +
                .boxed(),
30 +
        ];
31 +
        let root = hstack(items).gap(16.).center().boxed();
32 +
        let ui = gui::interface(win, &mut backend).scale(4.0).build(root)?;
33 +
34 +
        Ok(Self { backend, ui })
35 +
    }
36 +
}
37 +
38 +
impl<T: RenderBackend> Application for Example<T> {
39 +
    type Error = T::Error;
40 +
41 +
    fn event(
42 +
        &mut self,
43 +
        event: platform::WindowEvent,
44 +
        win: &mut platform::Window,
45 +
    ) -> Result<(), T::Error> {
46 +
        self.ui.event(event, &mut (), &mut self.backend, win)?;
47 +
48 +
        Ok(())
49 +
    }
50 +
51 +
    fn frame(&mut self) -> Result<(), Self::Error> {
52 +
        let mut frame = self.backend.frame();
53 +
        self.ui.frame(&(), &mut frame)?;
54 +
55 +
        frame.commit();
56 +
57 +
        Ok(())
58 +
    }
59 +
}
60 +
61 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
62 +
    runtime::run("hover", Example::init)
63 +
}
ombre/examples/hstack.rs added +60 -0
1 +
#![deny(clippy::all)]
2 +
#![allow(clippy::unwrap_used)]
3 +
#[path = "common/runtime.rs"]
4 +
mod runtime;
5 +
6 +
use ombre::prelude::*;
7 +
use ombre::ui as gui;
8 +
use ombre::ui::widgets::*;
9 +
10 +
pub struct Example<T> {
11 +
    ui: gui::Interface<Box<dyn Widget<()>>, ()>,
12 +
    backend: T,
13 +
}
14 +
15 +
impl<T: gfx::RenderBackend> Example<T> {
16 +
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, gui::Error<T>> {
17 +
        let ui = gui::interface(win, &mut backend).scale(2.).build(
18 +
            gui::hstack([
19 +
                Rgba8::RED.sized([96., 96.]),
20 +
                Rgba8::GREEN.sized([64., 128.]),
21 +
                Rgba8::BLUE.sized([128., 64.]),
22 +
                Rgba8::YELLOW.sized([32., 160.]),
23 +
                Rgba8::PINK.sized([64., 32.]),
24 +
            ])
25 +
            .gap(24.)
26 +
            .align(gui::gfx::Align::End)
27 +
            .center()
28 +
            .boxed(),
29 +
        )?;
30 +
31 +
        Ok(Self { backend, ui })
32 +
    }
33 +
}
34 +
35 +
impl<T: RenderBackend> Application for Example<T> {
36 +
    type Error = T::Error;
37 +
38 +
    fn event(
39 +
        &mut self,
40 +
        event: platform::WindowEvent,
41 +
        win: &mut platform::Window,
42 +
    ) -> Result<(), T::Error> {
43 +
        self.ui.event(event, &mut (), &mut self.backend, win)?;
44 +
45 +
        Ok(())
46 +
    }
47 +
48 +
    fn frame(&mut self) -> Result<(), Self::Error> {
49 +
        let mut frame = self.backend.frame();
50 +
        self.ui.frame(&(), &mut frame)?;
51 +
52 +
        frame.commit();
53 +
54 +
        Ok(())
55 +
    }
56 +
}
57 +
58 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
59 +
    runtime::run("hstack", Example::init)
60 +
}
ombre/examples/image.rs added +50 -0
1 +
#![deny(clippy::all)]
2 +
#![allow(clippy::unwrap_used)]
3 +
#[path = "common/runtime.rs"]
4 +
mod runtime;
5 +
6 +
use ombre::prelude::*;
7 +
use ombre::ui as gui;
8 +
use ombre::ui::widgets;
9 +
10 +
pub struct Example<T> {
11 +
    ui: gui::Interface<widgets::Image, ()>,
12 +
    backend: T,
13 +
}
14 +
15 +
impl<T: gfx::RenderBackend> Example<T> {
16 +
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, gui::Error<T>> {
17 +
        let src = include_bytes!("common/rx.rgba");
18 +
        let img = gfx::Image::try_from(src.as_slice()).unwrap();
19 +
        let ui = gui::interface(win, &mut backend).build(gui::image(img))?;
20 +
21 +
        Ok(Self { backend, ui })
22 +
    }
23 +
}
24 +
25 +
impl<T: RenderBackend> Application for Example<T> {
26 +
    type Error = T::Error;
27 +
28 +
    fn event(
29 +
        &mut self,
30 +
        event: platform::WindowEvent,
31 +
        win: &mut platform::Window,
32 +
    ) -> Result<(), T::Error> {
33 +
        self.ui.event(event, &mut (), &mut self.backend, win)?;
34 +
35 +
        Ok(())
36 +
    }
37 +
38 +
    fn frame(&mut self) -> Result<(), Self::Error> {
39 +
        let mut frame = self.backend.frame();
40 +
        self.ui.frame(&(), &mut frame)?;
41 +
42 +
        frame.commit();
43 +
44 +
        Ok(())
45 +
    }
46 +
}
47 +
48 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
49 +
    runtime::run("image", Example::init)
50 +
}
ombre/examples/input.rs added +70 -0
1 +
#![deny(clippy::all)]
2 +
#![allow(clippy::unwrap_used)]
3 +
#[path = "common/runtime.rs"]
4 +
mod runtime;
5 +
6 +
use ombre::prelude::*;
7 +
use ombre::ui::widgets::*;
8 +
use ombre::ui::{self as gui, fonts};
9 +
10 +
pub struct Example<T> {
11 +
    ui: gui::Interface<Box<dyn Widget<String>>, String>,
12 +
    data: String,
13 +
    backend: T,
14 +
}
15 +
16 +
impl<T: gfx::RenderBackend> Example<T> {
17 +
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, gui::Error<T>> {
18 +
        let ui = gui::interface(win, &mut backend)
19 +
            .scale(10.0)
20 +
            .font(fonts::uf2::VENICE)?
21 +
            .build(
22 +
                gui::hstack((
23 +
                    gui::input(gui::Label::empty())
24 +
                        .font("Venice")
25 +
                        .padding([2., 2.])
26 +
                        .stroke(1.0)
27 +
                        .sized([64., 22.]),
28 +
                    gui::label(|data: &String| data.len().to_string())
29 +
                        .tint(Rgba8::greyscale(0x9f))
30 +
                        .font("Default"),
31 +
                ))
32 +
                .gap(4.)
33 +
                .center()
34 +
                .boxed(),
35 +
            )?;
36 +
37 +
        Ok(Self {
38 +
            backend,
39 +
            ui,
40 +
            data: String::new(),
41 +
        })
42 +
    }
43 +
}
44 +
45 +
impl<T: RenderBackend> Application for Example<T> {
46 +
    type Error = T::Error;
47 +
48 +
    fn event(
49 +
        &mut self,
50 +
        event: platform::WindowEvent,
51 +
        win: &mut platform::Window,
52 +
    ) -> Result<(), T::Error> {
53 +
        self.ui.event(event, &mut self.data, &mut self.backend, win)?;
54 +
55 +
        Ok(())
56 +
    }
57 +
58 +
    fn frame(&mut self) -> Result<(), Self::Error> {
59 +
        let mut frame = self.backend.frame();
60 +
        self.ui.frame(&self.data, &mut frame)?;
61 +
62 +
        frame.commit();
63 +
64 +
        Ok(())
65 +
    }
66 +
}
67 +
68 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
69 +
    runtime::run("input", Example::init)
70 +
}
ombre/examples/latency.rs added +181 -0
1 +
#![allow(clippy::unwrap_used)]
2 +
use ombre::derive::{UniformBlock, VertexAttributes};
3 +
use ombre::math::Origin;
4 +
use ombre::platform::Window;
5 +
use ombre::{
6 +
    math::{Vector2D, Vector4D, Zero},
7 +
    prelude::*,
8 +
};
9 +
10 +
struct Example<T> {
11 +
    pipeline: PipelineId,
12 +
    bindings: Bindings<1, 0>,
13 +
    delta: f64,
14 +
    size: Size<u32>,
15 +
    cursor: platform::LogicalPosition,
16 +
    backend: T,
17 +
}
18 +
19 +
impl<T: RenderBackend> ApplicationExt for Example<T> {
20 +
    type Error = T::Error;
21 +
22 +
    fn window_resized(&mut self, size: platform::LogicalSize) -> Result<(), Self::Error> {
23 +
        self.size = Size::new(size.width as u32, size.height as u32);
24 +
25 +
        Ok(())
26 +
    }
27 +
28 +
    fn update(
29 +
        &mut self,
30 +
        delta: runtime::time::Duration,
31 +
        win: &mut Window,
32 +
    ) -> Result<(), Self::Error> {
33 +
        let cursor = win.get_cursor_pos();
34 +
        if cursor != self.cursor {
35 +
            self.cursor = cursor;
36 +
            win.redraw();
37 +
        }
38 +
        self.delta += delta.as_secs_f64();
39 +
40 +
        Ok(())
41 +
    }
42 +
43 +
    fn present(&mut self) -> Result<(), Self::Error> {
44 +
        let mut frame = self.backend.frame();
45 +
        // Convert from screen coordinates to normalized device coordinates.
46 +
        let position = Transform3D::ortho(self.size, Origin::default())
47 +
            * Vector2D::new(self.cursor.x as f32, self.cursor.y as f32);
48 +
        let uniforms = shader::Uniforms {
49 +
            shape: 0,
50 +
            smoothing: 0.002,
51 +
            size: Vector2D::new(0.1, 0.1),
52 +
            color: Vector4D::new(1.0, 0.0, 1.0, 1.0),
53 +
            position,
54 +
            aspect: self.size.w as f32 / self.size.h as f32,
55 +
        };
56 +
        frame.begin_default_pass(Default::default(), self.size);
57 +
        frame.apply_pipeline(&self.pipeline)?;
58 +
        frame.apply_bindings(&self.bindings)?;
59 +
        frame.apply_uniforms(&uniforms)?;
60 +
        frame.draw(0, 6, 1)?;
61 +
        frame.end_pass();
62 +
        frame.commit();
63 +
64 +
        Ok(())
65 +
    }
66 +
}
67 +
68 +
impl<T: RenderBackend> Example<T> {
69 +
    pub fn init(mut backend: T, win: &Window) -> Result<Example<T>, T::Error> {
70 +
        let vertices: [shader::Vertex; 4] = [
71 +
            shader::Vertex {
72 +
                position: Vector2D::new(-1.0, -1.0),
73 +
            },
74 +
            shader::Vertex {
75 +
                position: Vector2D::new(1.0, -1.0),
76 +
            },
77 +
            shader::Vertex {
78 +
                position: Vector2D::new(1.0, 1.0),
79 +
            },
80 +
            shader::Vertex {
81 +
                position: Vector2D::new(-1.0, 1.0),
82 +
            },
83 +
        ];
84 +
        let vertex_buffer = backend.buffer(
85 +
            BufferKind::Vertex,
86 +
            BufferUsage::Immutable,
87 +
            BufferSource::slice(&vertices),
88 +
        )?;
89 +
90 +
        let indices: [u16; 6] = [0, 1, 2, 0, 2, 3];
91 +
        let index_buffer = backend.buffer(
92 +
            BufferKind::Index,
93 +
            BufferUsage::Immutable,
94 +
            BufferSource::slice(&indices),
95 +
        )?;
96 +
97 +
        let bindings = Bindings {
98 +
            vertex: [vertex_buffer],
99 +
            index: Some(index_buffer),
100 +
            textures: [],
101 +
        };
102 +
103 +
        let shader = backend
104 +
            .shader(
105 +
                ShaderSource {
106 +
                    vertex: shader::VERTEX,
107 +
                    fragment: shader::FRAGMENT,
108 +
                    geometry: None,
109 +
                },
110 +
                shader::description(),
111 +
            )
112 +
            .unwrap();
113 +
114 +
        let pipeline = backend.pipeline(
115 +
            shader,
116 +
            gfx::PipelineDescriptor {
117 +
                layout: &[gfx::BufferLayout {
118 +
                    attrs: shader::Vertex::attributes(),
119 +
                    ..gfx::BufferLayout::default()
120 +
                }],
121 +
                ..gfx::PipelineDescriptor::default()
122 +
            },
123 +
        )?;
124 +
125 +
        Ok(Self {
126 +
            pipeline,
127 +
            bindings,
128 +
            backend,
129 +
            delta: 0.,
130 +
            size: Size::ZERO,
131 +
            cursor: win.get_cursor_pos(),
132 +
        })
133 +
    }
134 +
}
135 +
136 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
137 +
    logger::init(log::Level::Debug)?;
138 +
139 +
    let (mut win, events) =
140 +
        platform::init("latency", 640, 480, &[], platform::GraphicsContext::Gl)?;
141 +
    let ctx = unsafe { glow::Context::from_loader_function(|p| win.get_proc_address(p)) };
142 +
    let backend = gfx::gl::Context::new(ctx, win.size())?;
143 +
    let app = Example::init(backend, &win)?;
144 +
145 +
    // TODO: Where to set tick interval, or request animation frame?
146 +
147 +
    ombre::runtime::default::run(win, events, app)?;
148 +
149 +
    Ok(())
150 +
}
151 +
152 +
mod shader {
153 +
    use super::*;
154 +
155 +
    #[repr(C)]
156 +
    #[derive(VertexAttributes)]
157 +
    pub struct Vertex {
158 +
        pub position: Vector2D,
159 +
    }
160 +
161 +
    pub const VERTEX: &str = include_str!("../src/gfx/sdf/vertex.glsl");
162 +
    pub const FRAGMENT: &str = include_str!("../src/gfx/sdf/fragment.glsl");
163 +
164 +
    pub fn description() -> ShaderDescriptor<'static> {
165 +
        ShaderDescriptor {
166 +
            textures: &[],
167 +
            uniforms: Uniforms::layout(),
168 +
        }
169 +
    }
170 +
171 +
    #[repr(C)]
172 +
    #[derive(UniformBlock)]
173 +
    pub struct Uniforms {
174 +
        pub shape: i32,
175 +
        pub smoothing: f32,
176 +
        pub size: Vector2D,
177 +
        pub color: Vector4D,
178 +
        pub position: Vector2D,
179 +
        pub aspect: f32,
180 +
    }
181 +
}
ombre/examples/offscreen.rs added +350 -0
1 +
#![allow(clippy::unwrap_used)]
2 +
use ombre::prelude::*;
3 +
4 +
struct Renderer<T> {
5 +
    display_pipeline: gfx::PipelineId,
6 +
    display_bind: gfx::Bindings<1, 1>,
7 +
    offscreen_pipeline: gfx::PipelineId,
8 +
    offscreen_bind: gfx::Bindings<1, 0>,
9 +
    offscreen_pass: gfx::PassId,
10 +
    rx: f32,
11 +
    ry: f32,
12 +
    width: f64,
13 +
    height: f64,
14 +
    backend: T,
15 +
}
16 +
17 +
impl<T: gfx::RenderBackend> ApplicationExt for Renderer<T> {
18 +
    type Error = T::Error;
19 +
20 +
    fn window_resized(&mut self, size: platform::LogicalSize) -> Result<(), Self::Error> {
21 +
        self.width = size.width;
22 +
        self.height = size.height;
23 +
        self.backend.window_resized(size);
24 +
25 +
        Ok(())
26 +
    }
27 +
28 +
    fn update(
29 +
        &mut self,
30 +
        _delta: runtime::time::Duration,
31 +
        win: &mut platform::Window,
32 +
    ) -> Result<(), Self::Error> {
33 +
        win.redraw();
34 +
35 +
        Ok(())
36 +
    }
37 +
38 +
    fn present(&mut self) -> Result<(), Self::Error> {
39 +
        let (width, height) = (self.width as f32, self.height as f32);
40 +
        let proj = Transform3D::perspective(60.0f32, width / height, 0.01, 100.);
41 +
        let view = Transform3D::<f32>::look_at(
42 +
            Vector3D::new(0.0, 1.5, 9.0),
43 +
            Vector3D::new(0.0, 0.0, 0.0),
44 +
            Vector3D::new(0.0, 1.0, 0.0),
45 +
        );
46 +
        let view_proj = proj * view;
47 +
48 +
        self.rx += 0.01;
49 +
        self.ry += 0.03;
50 +
51 +
        let model = Transform3D::rotation(self.ry, Vector3D::new(0., 1.0, 0.))
52 +
            * Transform3D::<f32>::rotation(self.rx, Vector3D::new(1.0, 0., 0.));
53 +
        let vs_params = display_shader::Uniforms {
54 +
            mvp: view_proj * model,
55 +
        };
56 +
        let mut frame = self.backend.frame();
57 +
58 +
        // Offscreen pass.
59 +
        frame.begin_pass(
60 +
            self.offscreen_pass,
61 +
            gfx::PassAction::clear(gfx::color::Rgba::WHITE),
62 +
        );
63 +
        frame.apply_pipeline(&self.offscreen_pipeline)?;
64 +
        frame.apply_bindings(&self.offscreen_bind)?;
65 +
        frame.apply_uniforms(&vs_params)?;
66 +
        frame.draw(0, 36, 1)?;
67 +
        frame.end_pass();
68 +
69 +
        // Display pass.
70 +
        frame.begin_default_pass(
71 +
            gfx::PassAction::clear(gfx::color::Rgba::new(0.0, 0., 0.45, 1.)),
72 +
            [self.width as u32, self.height as u32],
73 +
        );
74 +
        frame.apply_pipeline(&self.display_pipeline)?;
75 +
        frame.apply_bindings(&self.display_bind)?;
76 +
        frame.apply_uniforms(&vs_params)?;
77 +
        frame.draw(0, 36, 1)?;
78 +
        frame.end_pass();
79 +
        frame.commit();
80 +
81 +
        Ok(())
82 +
    }
83 +
}
84 +
85 +
impl<T: gfx::RenderBackend> Renderer<T> {
86 +
    pub fn init(mut backend: T) -> Result<Self, Box<dyn std::error::Error>> {
87 +
        let color_img = backend.texture(gfx::Texture {
88 +
            data: gfx::Empty,
89 +
            access: gfx::TextureAccess::RenderTarget,
90 +
            size: Size::new(1024, 1024),
91 +
            format: gfx::TextureFormat::Rgba8,
92 +
            ..gfx::Texture::default()
93 +
        })?;
94 +
        let depth_img = backend.texture(gfx::Texture {
95 +
            data: gfx::Empty,
96 +
            size: Size::new(1024, 1024),
97 +
            access: gfx::TextureAccess::RenderTarget,
98 +
            format: gfx::TextureFormat::Depth,
99 +
            ..gfx::Texture::default()
100 +
        })?;
101 +
        let offscreen_pass = backend.pass(gfx::PassDescriptor {
102 +
            color_attachments: &[color_img],
103 +
            depth_attachment: Some(depth_img),
104 +
        })?;
105 +
106 +
        #[rustfmt::skip]
107 +
        let vertices: &[f32] = &[
108 +
            // position          color                   uvs
109 +
            -1.0, -1.0, -1.0,    1.0, 0.5, 0.5, 1.0,     0.0, 0.0,
110 +
             1.0, -1.0, -1.0,    1.0, 0.5, 0.5, 1.0,     1.0, 0.0,
111 +
             1.0,  1.0, -1.0,    1.0, 0.5, 0.5, 1.0,     1.0, 1.0,
112 +
            -1.0,  1.0, -1.0,    1.0, 0.5, 0.5, 1.0,     0.0, 1.0,
113 +
114 +
            -1.0, -1.0,  1.0,    0.5, 1.0, 0.5, 1.0,     0.0, 0.0,
115 +
             1.0, -1.0,  1.0,    0.5, 1.0, 0.5, 1.0,     1.0, 0.0,
116 +
             1.0,  1.0,  1.0,    0.5, 1.0, 0.5, 1.0,     1.0, 1.0,
117 +
            -1.0,  1.0,  1.0,    0.5, 1.0, 0.5, 1.0,     0.0, 1.0,
118 +
119 +
            -1.0, -1.0, -1.0,    0.5, 0.5, 1.0, 1.0,     0.0, 0.0,
120 +
            -1.0,  1.0, -1.0,    0.5, 0.5, 1.0, 1.0,     1.0, 0.0,
121 +
            -1.0,  1.0,  1.0,    0.5, 0.5, 1.0, 1.0,     1.0, 1.0,
122 +
            -1.0, -1.0,  1.0,    0.5, 0.5, 1.0, 1.0,     0.0, 1.0,
123 +
124 +
             1.0, -1.0, -1.0,    1.0, 0.5, 0.0, 1.0,     0.0, 0.0,
125 +
             1.0,  1.0, -1.0,    1.0, 0.5, 0.0, 1.0,     1.0, 0.0,
126 +
             1.0,  1.0,  1.0,    1.0, 0.5, 0.0, 1.0,     1.0, 1.0,
127 +
             1.0, -1.0,  1.0,    1.0, 0.5, 0.0, 1.0,     0.0, 1.0,
128 +
129 +
            -1.0, -1.0, -1.0,    0.0, 0.5, 1.0, 1.0,     0.0, 0.0,
130 +
            -1.0, -1.0,  1.0,    0.0, 0.5, 1.0, 1.0,     1.0, 0.0,
131 +
             1.0, -1.0,  1.0,    0.0, 0.5, 1.0, 1.0,     1.0, 1.0,
132 +
             1.0, -1.0, -1.0,    0.0, 0.5, 1.0, 1.0,     0.0, 1.0,
133 +
134 +
            -1.0,  1.0, -1.0,    1.0, 0.0, 0.5, 1.0,     0.0, 0.0,
135 +
            -1.0,  1.0,  1.0,    1.0, 0.0, 0.5, 1.0,     1.0, 0.0,
136 +
             1.0,  1.0,  1.0,    1.0, 0.0, 0.5, 1.0,     1.0, 1.0,
137 +
             1.0,  1.0, -1.0,    1.0, 0.0, 0.5, 1.0,     0.0, 1.0
138 +
        ];
139 +
140 +
        let vertex_buffer = backend.buffer(
141 +
            gfx::BufferKind::Vertex,
142 +
            gfx::BufferUsage::Immutable,
143 +
            gfx::BufferSource::slice(vertices),
144 +
        )?;
145 +
146 +
        #[rustfmt::skip]
147 +
        let indices: &[u8] = &[
148 +
            0, 1, 2,  0, 2, 3,
149 +
            6, 5, 4,  7, 6, 4,
150 +
            8, 9, 10,  8, 10, 11,
151 +
            14, 13, 12,  15, 14, 12,
152 +
            16, 17, 18,  16, 18, 19,
153 +
            22, 21, 20,  23, 22, 20
154 +
        ];
155 +
156 +
        let index_buffer = backend.buffer(
157 +
            gfx::BufferKind::Index,
158 +
            gfx::BufferUsage::Immutable,
159 +
            gfx::BufferSource::slice(indices),
160 +
        )?;
161 +
162 +
        let offscreen_bind = gfx::Bindings {
163 +
            vertex: [vertex_buffer],
164 +
            index: Some(index_buffer),
165 +
            textures: [],
166 +
        };
167 +
168 +
        let display_bind = gfx::Bindings {
169 +
            vertex: [vertex_buffer],
170 +
            index: Some(index_buffer),
171 +
            textures: [color_img],
172 +
        };
173 +
174 +
        let source = gfx::ShaderSource {
175 +
            vertex: display_shader::VERTEX,
176 +
            fragment: display_shader::FRAGMENT,
177 +
            geometry: None,
178 +
        };
179 +
        let default_shader = backend.shader(source, display_shader::meta()).unwrap();
180 +
181 +
        let display_pipeline = backend.pipeline(
182 +
            default_shader,
183 +
            gfx::PipelineDescriptor {
184 +
                layout: &[gfx::BufferLayout {
185 +
                    attrs: &[
186 +
                        gfx::VertexAttribute::new("in_pos", gfx::VertexFormat::Float3),
187 +
                        gfx::VertexAttribute::new("in_color", gfx::VertexFormat::Float4),
188 +
                        gfx::VertexAttribute::new("in_uv", gfx::VertexFormat::Float2),
189 +
                    ],
190 +
                    ..gfx::BufferLayout::default()
191 +
                }],
192 +
                depth: Some(gfx::DepthState {
193 +
                    compare: gfx::Comparison::LessOrEqual,
194 +
                    offset: None,
195 +
                }),
196 +
                ..Default::default()
197 +
            },
198 +
        )?;
199 +
200 +
        let source = gfx::ShaderSource {
201 +
            vertex: offscreen_shader::VERTEX,
202 +
            fragment: offscreen_shader::FRAGMENT,
203 +
            geometry: None,
204 +
        };
205 +
        let offscreen_shader = backend.shader(source, offscreen_shader::meta()).unwrap();
206 +
        let offscreen_pipeline = backend.pipeline(
207 +
            offscreen_shader,
208 +
            gfx::PipelineDescriptor {
209 +
                layout: &[gfx::BufferLayout {
210 +
                    stride: Some(36),
211 +
                    attrs: &[
212 +
                        gfx::VertexAttribute::new("in_pos", gfx::VertexFormat::Float3),
213 +
                        gfx::VertexAttribute::new("in_color", gfx::VertexFormat::Float4),
214 +
                    ],
215 +
                    ..Default::default()
216 +
                }],
217 +
                depth: Some(gfx::DepthState {
218 +
                    compare: gfx::Comparison::LessOrEqual,
219 +
                    offset: None,
220 +
                }),
221 +
                ..Default::default()
222 +
            },
223 +
        )?;
224 +
225 +
        Ok(Self {
226 +
            display_pipeline,
227 +
            display_bind,
228 +
            offscreen_pipeline,
229 +
            offscreen_bind,
230 +
            offscreen_pass,
231 +
            height: 1.,
232 +
            width: 1.,
233 +
            rx: 0.,
234 +
            ry: 0.,
235 +
            backend,
236 +
        })
237 +
    }
238 +
}
239 +
240 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
241 +
    logger::init(log::Level::Debug)?;
242 +
243 +
    let (mut win, events) =
244 +
        platform::init("offscreen", 640, 480, &[], platform::GraphicsContext::Gl)?;
245 +
    let ctx = unsafe { glow::Context::from_loader_function(|p| win.get_proc_address(p)) };
246 +
    let backend = gfx::gl::Context::new(ctx, win.size())?;
247 +
    let renderer = Renderer::init(backend)?;
248 +
249 +
    ombre::runtime::default::run(win, events, renderer)?;
250 +
251 +
    Ok(())
252 +
}
253 +
254 +
mod display_shader {
255 +
    use super::*;
256 +
257 +
    pub const VERTEX: &str = r#"
258 +
    #version 100
259 +
260 +
    attribute vec3 in_pos;
261 +
    attribute vec4 in_color;
262 +
    attribute vec2 in_uv;
263 +
264 +
    varying lowp vec4 color;
265 +
    varying lowp vec2 uv;
266 +
267 +
    uniform mat4 mvp;
268 +
269 +
    void main() {
270 +
        gl_Position = mvp * vec4(in_pos, 1);
271 +
        color = in_color;
272 +
        uv = in_uv;
273 +
    }
274 +
    "#;
275 +
276 +
    pub const FRAGMENT: &str = r#"
277 +
    #version 100
278 +
279 +
    varying lowp vec4 color;
280 +
    varying lowp vec2 uv;
281 +
282 +
    uniform sampler2D tex;
283 +
284 +
    void main() {
285 +
        gl_FragColor = color * texture2D(tex, uv);
286 +
    }
287 +
    "#;
288 +
289 +
    pub fn meta<'a>() -> gfx::ShaderDescriptor<'a> {
290 +
        gfx::ShaderDescriptor {
291 +
            textures: &["tex"],
292 +
            uniforms: gfx::UniformBlockLayout {
293 +
                uniforms: &[gfx::UniformDescriptor {
294 +
                    name: "mvp",
295 +
                    kind: gfx::UniformKind::Mat4,
296 +
                    arity: 1,
297 +
                }],
298 +
            },
299 +
        }
300 +
    }
301 +
302 +
    #[repr(C)]
303 +
    pub struct Uniforms {
304 +
        pub mvp: Transform3D,
305 +
    }
306 +
    unsafe impl bytes::Packed for Uniforms {}
307 +
}
308 +
309 +
mod offscreen_shader {
310 +
    use super::*;
311 +
312 +
    pub const VERTEX: &str = r#"
313 +
    #version 100
314 +
315 +
    attribute vec3 in_pos;
316 +
    attribute vec4 in_color;
317 +
318 +
    varying lowp vec4 color;
319 +
320 +
    uniform mat4 mvp;
321 +
322 +
    void main() {
323 +
        gl_Position = mvp * vec4(in_pos, 1);
324 +
        color = in_color;
325 +
    }
326 +
    "#;
327 +
328 +
    pub const FRAGMENT: &str = r#"
329 +
    #version 100
330 +
331 +
    varying lowp vec4 color;
332 +
333 +
    void main() {
334 +
        gl_FragColor = color;
335 +
    }
336 +
    "#;
337 +
338 +
    pub fn meta() -> gfx::ShaderDescriptor<'static> {
339 +
        gfx::ShaderDescriptor {
340 +
            textures: &[],
341 +
            uniforms: gfx::UniformBlockLayout {
342 +
                uniforms: &[gfx::UniformDescriptor {
343 +
                    name: "mvp",
344 +
                    kind: gfx::UniformKind::Mat4,
345 +
                    arity: 1,
346 +
                }],
347 +
            },
348 +
        }
349 +
    }
350 +
}
ombre/examples/particles.rs added +315 -0
1 +
#![deny(clippy::all)]
2 +
#[path = "common/runtime.rs"]
3 +
mod runtime;
4 +
5 +
use ombre::math::Vector3D;
6 +
use ombre::prelude::*;
7 +
use ombre::rng::Rng;
8 +
use ombre::ui as gui;
9 +
use ombre::{
10 +
    derive::{UniformBlock, VertexAttributes},
11 +
    gfx::{
12 +
        self, BufferKind, BufferLayout, BufferSource, BufferUsage, PassAction, PipelineDescriptor,
13 +
        Primitive, ShaderDescriptor, ShaderSource, Transform3D, VertexStep,
14 +
    },
15 +
};
16 +
17 +
const MAX_PARTICLES: usize = 512 * 1024;
18 +
const PARTICLES_PER_FRAME: usize = 10;
19 +
20 +
#[repr(C)]
21 +
#[derive(Copy, Clone, Debug)]
22 +
struct Particle {
23 +
    pos: Vector3D<f32>,
24 +
    vel: Vector3D<f32>,
25 +
    age: f32,
26 +
}
27 +
28 +
pub struct Example<T> {
29 +
    pipeline: gfx::PipelineId,
30 +
    bindings: gfx::Bindings<2, 0>,
31 +
    particles: Vec<Particle>,
32 +
    width: f64,
33 +
    height: f64,
34 +
    paused: bool,
35 +
    backend: T,
36 +
}
37 +
38 +
impl<T: gfx::RenderBackend> Example<T> {
39 +
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, gui::Error<T>> {
40 +
        let size = win.size();
41 +
        let r: f32 = 0.008;
42 +
        let vertices = [
43 +
            [-r, -r, 0.0], // Bottom left
44 +
            [r, -r, 0.0],  // Bottom right
45 +
            [r, r, 0.0],   // Top right
46 +
        ];
47 +
        let indices: [u16; 4] = [0, 1, 2, 0];
48 +
49 +
        // Create vertex buffer for static geometry.
50 +
        let vbuf = backend
51 +
            .buffer(
52 +
                BufferKind::Vertex,
53 +
                BufferUsage::Immutable,
54 +
                BufferSource::slice(&vertices),
55 +
            )
56 +
            .map_err(gui::Error::Render)?;
57 +
58 +
        // Create instance buffer for particle positions.
59 +
        let instance_buf = backend
60 +
            .buffer(
61 +
                BufferKind::Vertex,
62 +
                BufferUsage::Stream,
63 +
                BufferSource::<Vector3D<f32>>::empty(MAX_PARTICLES),
64 +
            )
65 +
            .map_err(gui::Error::Render)?;
66 +
67 +
        // Create index buffer
68 +
        let ibuf = backend
69 +
            .buffer(
70 +
                BufferKind::Index,
71 +
                BufferUsage::Immutable,
72 +
                BufferSource::slice(&indices),
73 +
            )
74 +
            .map_err(gui::Error::Render)?;
75 +
76 +
        let bindings = gfx::Bindings {
77 +
            vertex: [vbuf, instance_buf],
78 +
            index: Some(ibuf),
79 +
            textures: [],
80 +
        };
81 +
        let pipeline = pipeline(&mut backend).map_err(gui::Error::Render)?;
82 +
83 +
        Ok(Self {
84 +
            backend,
85 +
            pipeline,
86 +
            bindings,
87 +
            particles: Vec::with_capacity(MAX_PARTICLES),
88 +
            width: size.width,
89 +
            height: size.height,
90 +
            paused: false,
91 +
        })
92 +
    }
93 +
94 +
    fn emit_particles(&mut self) {
95 +
        let mut rng = Rng::new();
96 +
97 +
        for _ in 0..PARTICLES_PER_FRAME {
98 +
            if self.particles.len() >= MAX_PARTICLES {
99 +
                break;
100 +
            }
101 +
            // Generate random angle and radius for circular distribution.
102 +
            let angle = rng.probability() as f32 * std::f32::consts::PI * 2.0;
103 +
            let spread = 1.4f32;
104 +
            let radius = rng.probability() as f32 * spread;
105 +
106 +
            // Convert polar coordinates to cartesian.
107 +
            let vx = radius * angle.cos();
108 +
            let vz = radius * angle.sin();
109 +
110 +
            self.particles.push(Particle {
111 +
                pos: Vector3D::new(0.0, 0.0, 0.0),
112 +
                vel: Vector3D::new(
113 +
                    vx,
114 +
                    rng.probability() as f32 * 2.0 + 1.5, // Upward velocity.
115 +
                    vz,
116 +
                ),
117 +
                age: 0.0,
118 +
            });
119 +
        }
120 +
    }
121 +
122 +
    fn update_particles(&mut self, dt: f32) {
123 +
        self.particles.retain(|p| p.age < 12.0); // Remove old particles.
124 +
        for particle in &mut self.particles {
125 +
            particle.vel.y -= 2.0 * dt; // Gravity scaled by delta time.
126 +
            particle.pos.x += particle.vel.x * dt;
127 +
            particle.pos.y += particle.vel.y * dt;
128 +
            particle.pos.z += particle.vel.z * dt;
129 +
            particle.age += dt;
130 +
131 +
            if particle.pos.y < -2.0 {
132 +
                particle.pos.y = -1.8;
133 +
                particle.vel.y = -particle.vel.y * 0.5; // Bouciness.
134 +
                particle.vel = particle.vel * 0.7; // Friction.
135 +
            }
136 +
        }
137 +
    }
138 +
}
139 +
140 +
impl<T: gfx::RenderBackend> Application for Example<T> {
141 +
    type Error = T::Error;
142 +
143 +
    fn event(
144 +
        &mut self,
145 +
        event: platform::WindowEvent,
146 +
        _win: &mut platform::Window,
147 +
    ) -> Result<(), Self::Error> {
148 +
        match event {
149 +
            platform::WindowEvent::Resized(size) => {
150 +
                self.width = size.width;
151 +
                self.height = size.height;
152 +
            }
153 +
            platform::WindowEvent::KeyboardInput(i) if i.is_pressed() => {
154 +
                if i.key == Some(platform::Key::Space) {
155 +
                    self.paused = !self.paused;
156 +
                }
157 +
            }
158 +
            _ => {}
159 +
        }
160 +
        Ok(())
161 +
    }
162 +
163 +
    fn tick(
164 +
        &mut self,
165 +
        delta: ombre::runtime::time::Duration,
166 +
        win: &mut platform::Window,
167 +
    ) -> Result<(), Self::Error> {
168 +
        if !self.paused {
169 +
            let dt = delta.as_secs_f32();
170 +
            self.emit_particles();
171 +
            self.update_particles(dt);
172 +
        }
173 +
        win.redraw();
174 +
175 +
        Ok(())
176 +
    }
177 +
178 +
    fn frame(&mut self) -> Result<(), Self::Error> {
179 +
        // Update instance buffer with particle positions.
180 +
        let instance_data: Vec<_> = self
181 +
            .particles
182 +
            .iter()
183 +
            .map(|p| [p.pos.x, p.pos.y, p.pos.z, p.age])
184 +
            .collect();
185 +
        self.backend.buffer_update(
186 +
            self.bindings.vertex[1],
187 +
            BufferKind::Vertex,
188 +
            0,
189 +
            &instance_data,
190 +
        )?;
191 +
192 +
        let mut frame = self.backend.frame();
193 +
194 +
        // Setup view and projection.
195 +
        let aspect = self.width as f32 / self.height as f32;
196 +
        let proj = Transform3D::<_, (), ()>::perspective(60.0_f32, aspect, 0.01, 50.0);
197 +
        let view = Transform3D::<_, (), ()>::look_at(
198 +
            Vector3D::new(0.0, 1.5, 12.0),
199 +
            Vector3D::new(0.0, 0.0, 0.0),
200 +
            Vector3D::new(0.0, 1.0, 0.0),
201 +
        );
202 +
        let model = Transform3D::rotation(45., Vector3D::new(0.0, 1.0, 0.0));
203 +
        let mvp = proj * view * model;
204 +
205 +
        frame.begin_default_pass(
206 +
            PassAction::default(),
207 +
            Size::new(self.width as u32, self.height as u32),
208 +
        );
209 +
        frame.apply_pipeline(&self.pipeline)?;
210 +
        frame.apply_bindings(&self.bindings)?;
211 +
        frame.apply_uniforms(&Uniforms { mvp })?;
212 +
        frame.draw(0, 4, self.particles.len())?;
213 +
        frame.end_pass();
214 +
        frame.commit();
215 +
216 +
        Ok(())
217 +
    }
218 +
}
219 +
220 +
#[repr(C)]
221 +
#[derive(UniformBlock)]
222 +
struct Uniforms {
223 +
    mvp: Transform3D,
224 +
}
225 +
226 +
#[repr(C)]
227 +
#[derive(VertexAttributes)]
228 +
struct Vertex {
229 +
    #[attrib(name = "position")]
230 +
    position: Vector3D<f32>,
231 +
}
232 +
233 +
#[repr(C)]
234 +
#[derive(VertexAttributes)]
235 +
struct Instance {
236 +
    #[attrib(name = "iPos")]
237 +
    position: Vector3D<f32>,
238 +
    #[attrib(name = "iAge")]
239 +
    age: f32,
240 +
}
241 +
242 +
fn pipeline<T: gfx::RenderBackend>(backend: &mut T) -> Result<gfx::PipelineId, T::Error> {
243 +
    const VS: &str = r#"
244 +
        #version 330 core
245 +
        uniform mat4 mvp;
246 +
247 +
        // Vertex attributes.
248 +
        layout(location = 0) in vec3 position;
249 +
250 +
        // Instance attributes.
251 +
        layout(location = 1) in vec3 iPos;
252 +
        layout(location = 2) in float iAge;
253 +
254 +
        out vec4 color;
255 +
256 +
        void main() {
257 +
            gl_Position = mvp * vec4(position + iPos, 1.0);
258 +
            float t = clamp(iAge / 2.0, 0.0, 1.0);
259 +
            color = mix(vec4(1.0), vec4(0.1, 0.1, 0.4, 0.0), t);
260 +
        }
261 +
    "#;
262 +
263 +
    const FS: &str = r#"
264 +
        #version 330 core
265 +
        in vec4 color;
266 +
        out vec4 fragColor;
267 +
268 +
        void main() {
269 +
            fragColor = color;
270 +
        }
271 +
    "#;
272 +
273 +
    let shader = backend.shader(
274 +
        ShaderSource {
275 +
            vertex: VS,
276 +
            fragment: FS,
277 +
            geometry: None,
278 +
        },
279 +
        ShaderDescriptor {
280 +
            uniforms: Uniforms::layout(),
281 +
            textures: &[],
282 +
        },
283 +
    )?;
284 +
285 +
    // Create pipeline
286 +
    let desc = PipelineDescriptor {
287 +
        primitive: Primitive::Triangles,
288 +
        depth: Some(gfx::DepthState {
289 +
            compare: gfx::Comparison::LessOrEqual,
290 +
            offset: None,
291 +
        }),
292 +
        color: None,
293 +
        layout: &[
294 +
            BufferLayout {
295 +
                stride: Some(std::mem::size_of::<Vertex>()),
296 +
                step: VertexStep::PerVertex,
297 +
                step_rate: 1,
298 +
                attrs: Vertex::attributes(),
299 +
            },
300 +
            BufferLayout {
301 +
                stride: Some(std::mem::size_of::<Instance>()),
302 +
                step: VertexStep::PerInstance,
303 +
                step_rate: 1,
304 +
                attrs: Instance::attributes(),
305 +
            },
306 +
        ],
307 +
        ..PipelineDescriptor::default()
308 +
    };
309 +
310 +
    backend.pipeline(shader, desc)
311 +
}
312 +
313 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
314 +
    runtime::run("particles", Example::init)
315 +
}
ombre/examples/picker.rs added +68 -0
1 +
#![deny(clippy::all)]
2 +
#![allow(clippy::unwrap_used)]
3 +
#[path = "common/runtime.rs"]
4 +
mod runtime;
5 +
6 +
use std::str::FromStr as _;
7 +
8 +
use ombre::prelude::*;
9 +
use ombre::ui as gui;
10 +
use ombre::ui::widgets::*;
11 +
12 +
type State = Rgba8;
13 +
14 +
pub struct Example<T> {
15 +
    ui: gui::Interface<Box<dyn Widget<State>>, State>,
16 +
    state: State,
17 +
    backend: T,
18 +
}
19 +
20 +
impl<T: gfx::RenderBackend> Example<T> {
21 +
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, gui::Error<T>> {
22 +
        let palette = [
23 +
            "#1a1c2c", "#5d275d", "#b13e53", "#ef7d57", "#ffcd75", "#a7f070", "#38b764", "#257179",
24 +
            "#29366f", "#3b5dc9", "#41a6f6", "#73eff7", "#f4f4f4", "#94b0c2", "#566c86", "#333c57",
25 +
        ];
26 +
        let swatches = palette
27 +
            .into_iter()
28 +
            .map(|s| Rgba8::from_str(s).unwrap())
29 +
            .map(|color| color.sized((16., 16.)).on_click(move |_, s, _| *s = color))
30 +
            .collect::<Vec<_>>();
31 +
        let root = gui::zstack((
32 +
            gui::canvas(|color, bounds, mut canvas| canvas.fill(bounds, *color)),
33 +
            gui::hstack(swatches).center(),
34 +
        ));
35 +
        let ui = gui::interface(win, &mut backend).scale(4.0).build(root.boxed())?;
36 +
37 +
        Ok(Self {
38 +
            backend,
39 +
            ui,
40 +
            state: Rgba8::RED,
41 +
        })
42 +
    }
43 +
}
44 +
45 +
impl<T: RenderBackend> Application for Example<T> {
46 +
    type Error = T::Error;
47 +
48 +
    fn event(
49 +
        &mut self,
50 +
        event: platform::WindowEvent,
51 +
        win: &mut platform::Window,
52 +
    ) -> Result<(), T::Error> {
53 +
        self.ui.event(event, &mut self.state, &mut self.backend, win)?;
54 +
55 +
        Ok(())
56 +
    }
57 +
58 +
    fn frame(&mut self) -> Result<(), Self::Error> {
59 +
        let mut frame = self.backend.frame();
60 +
        self.ui.frame(&self.state, &mut frame)?;
61 +
62 +
        Ok(())
63 +
    }
64 +
}
65 +
66 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
67 +
    runtime::run("picker", Example::init)
68 +
}
ombre/examples/screenshot.rs added +337 -0
1 +
#![allow(clippy::unwrap_used)]
2 +
use ombre::derive::Packed;
3 +
use ombre::prelude::*;
4 +
5 +
#[repr(C)]
6 +
#[derive(Packed)]
7 +
struct Vertex {
8 +
    position: [f32; 2],
9 +
    color: [f32; 4],
10 +
}
11 +
12 +
struct Renderer<T> {
13 +
    display_pipeline: gfx::PipelineId,
14 +
    display_bind: gfx::Bindings<0, 1>,
15 +
    offscreen_pipeline: gfx::PipelineId,
16 +
    offscreen_bind: gfx::Bindings<1, 0>,
17 +
    offscreen_pass: gfx::PassId,
18 +
    rx: f32,
19 +
    ry: f32,
20 +
    width: f64,
21 +
    height: f64,
22 +
    backend: T,
23 +
}
24 +
25 +
impl<T: gfx::RenderBackend> Renderer<T> {
26 +
    pub fn init(mut backend: T) -> Result<Self, T::Error> {
27 +
        let color_img = backend.texture(gfx::Texture {
28 +
            data: gfx::Empty,
29 +
            access: gfx::TextureAccess::RenderTarget,
30 +
            size: Size::new(512, 512),
31 +
            format: gfx::TextureFormat::Rgba8,
32 +
            min_filter: gfx::FilterMode::Nearest,
33 +
            mag_filter: gfx::FilterMode::Nearest,
34 +
            ..Default::default()
35 +
        })?;
36 +
        let depth_img = backend.texture(gfx::Texture {
37 +
            data: gfx::Empty,
38 +
            access: gfx::TextureAccess::RenderTarget,
39 +
            size: Size::new(512, 512),
40 +
            format: gfx::TextureFormat::Depth,
41 +
            ..Default::default()
42 +
        })?;
43 +
44 +
        let offscreen_pass = backend.pass(gfx::PassDescriptor {
45 +
            color_attachments: &[color_img],
46 +
            depth_attachment: Some(depth_img),
47 +
        })?;
48 +
49 +
        #[rustfmt::skip]
50 +
        let vertices: [Vertex; 3] = [
51 +
            Vertex { position: [-0.5, -0.5], color: [1., 0., 1., 1.] },
52 +
            Vertex { position: [ 0.5, -0.5], color: [0., 1., 1., 1.] },
53 +
            Vertex { position: [ 0.0,  0.5], color: [1., 1., 0., 1.] },
54 +
        ];
55 +
        let vertex_buffer = backend.buffer(
56 +
            gfx::BufferKind::Vertex,
57 +
            gfx::BufferUsage::Immutable,
58 +
            gfx::BufferSource::slice(&vertices),
59 +
        )?;
60 +
        let index_buffer = backend.buffer(
61 +
            gfx::BufferKind::Index,
62 +
            gfx::BufferUsage::Immutable,
63 +
            gfx::BufferSource::slice(&[0, 1, 2]),
64 +
        )?;
65 +
66 +
        let offscreen_bind = gfx::Bindings {
67 +
            vertex: [vertex_buffer],
68 +
            index: Some(index_buffer),
69 +
            textures: [],
70 +
        };
71 +
72 +
        let display_bind = gfx::Bindings {
73 +
            vertex: [],
74 +
            index: None,
75 +
            textures: [color_img],
76 +
        };
77 +
78 +
        let source = gfx::ShaderSource {
79 +
            vertex: display_shader::VERTEX,
80 +
            fragment: display_shader::FRAGMENT,
81 +
            geometry: None,
82 +
        };
83 +
        let display_shader = backend.shader(source, display_shader::meta()).unwrap();
84 +
        let display_pipeline = backend.pipeline(
85 +
            display_shader,
86 +
            gfx::PipelineDescriptor {
87 +
                depth: Some(gfx::DepthState {
88 +
                    compare: gfx::Comparison::LessOrEqual,
89 +
                    offset: None,
90 +
                }),
91 +
                ..Default::default()
92 +
            },
93 +
        )?;
94 +
95 +
        let source = gfx::ShaderSource {
96 +
            vertex: offscreen_shader::VERTEX,
97 +
            fragment: offscreen_shader::FRAGMENT,
98 +
            geometry: None,
99 +
        };
100 +
        let offscreen_shader = backend.shader(source, offscreen_shader::meta()).unwrap();
101 +
102 +
        let offscreen_pipeline = backend.pipeline(
103 +
            offscreen_shader,
104 +
            gfx::PipelineDescriptor {
105 +
                layout: &[gfx::BufferLayout {
106 +
                    stride: Some(std::mem::size_of::<Vertex>()),
107 +
                    attrs: &[
108 +
                        gfx::VertexAttribute::new("in_pos", gfx::VertexFormat::Float2),
109 +
                        gfx::VertexAttribute::new("in_color", gfx::VertexFormat::Float4),
110 +
                    ],
111 +
                    ..Default::default()
112 +
                }],
113 +
                depth: Some(gfx::DepthState {
114 +
                    compare: gfx::Comparison::LessOrEqual,
115 +
                    offset: None,
116 +
                }),
117 +
                ..Default::default()
118 +
            },
119 +
        )?;
120 +
121 +
        Ok(Self {
122 +
            display_pipeline,
123 +
            display_bind,
124 +
            offscreen_pipeline,
125 +
            offscreen_bind,
126 +
            offscreen_pass,
127 +
            height: 1.,
128 +
            width: 1.,
129 +
            rx: 0.,
130 +
            ry: 0.,
131 +
            backend,
132 +
        })
133 +
    }
134 +
135 +
    fn window_resized(&mut self, size: platform::LogicalSize) -> Result<(), T::Error> {
136 +
        self.width = size.width;
137 +
        self.height = size.height;
138 +
        self.backend.window_resized(size);
139 +
140 +
        self.backend.pass_resize_attachments(
141 +
            self.offscreen_pass,
142 +
            Size::new(self.width as u32, self.height as u32),
143 +
        )?;
144 +
145 +
        Ok(())
146 +
    }
147 +
148 +
    fn frame(&mut self) -> Result<(), T::Error> {
149 +
        let (width, height) = (self.width as f32, self.height as f32);
150 +
        let proj = Transform3D::perspective(60.0f32, width / height, 0.01, 30.0);
151 +
        let view = Transform3D::<f32>::look_at(
152 +
            Vector3D::new(0.0, 1.5, 9.0),
153 +
            Vector3D::new(0.0, 0.0, 0.0),
154 +
            Vector3D::new(0.0, 1.0, 0.0),
155 +
        );
156 +
        let view_proj = proj * view;
157 +
158 +
        self.rx += 0.01;
159 +
        self.ry += 0.03;
160 +
161 +
        let model = Transform3D::rotation(self.ry, Vector3D::new(0., 1.0, 0.))
162 +
            * Transform3D::<f32>::rotation(self.rx, Vector3D::new(1.0, 0., 0.));
163 +
164 +
        let vs_params = display_shader::Uniforms {
165 +
            mvp: view_proj * model,
166 +
        };
167 +
        let mut frame = self.backend.frame();
168 +
169 +
        frame.begin_pass(
170 +
            self.offscreen_pass,
171 +
            gfx::PassAction::clear(gfx::color::Rgba::BLACK),
172 +
        );
173 +
        frame.apply_pipeline(&self.offscreen_pipeline)?;
174 +
        frame.apply_bindings(&self.offscreen_bind)?;
175 +
        frame.apply_uniforms(&vs_params)?;
176 +
        frame.draw(0, 3, 1)?;
177 +
        frame.end_pass();
178 +
179 +
        frame.begin_default_pass(
180 +
            gfx::PassAction::clear(gfx::color::Rgba::BLACK),
181 +
            [self.width as u32, self.height as u32],
182 +
        );
183 +
        frame.apply_pipeline(&self.display_pipeline)?;
184 +
        frame.apply_bindings(&self.display_bind)?;
185 +
        frame.draw(0, 6, 1)?;
186 +
        frame.end_pass();
187 +
        frame.commit();
188 +
189 +
        Ok(())
190 +
    }
191 +
}
192 +
193 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
194 +
    logger::init(log::Level::Debug)?;
195 +
196 +
    let (mut win, mut events) =
197 +
        platform::init("screenshot", 640, 480, &[], platform::GraphicsContext::Gl)?;
198 +
    let ctx = unsafe { glow::Context::from_loader_function(|p| win.get_proc_address(p)) };
199 +
    let backend = gfx::gl::Context::new(ctx, win.size())?;
200 +
    let mut renderer = Renderer::init(backend)?;
201 +
202 +
    'main: while win.is_open() {
203 +
        events.poll();
204 +
205 +
        for event in events.flush() {
206 +
            match event {
207 +
                platform::WindowEvent::Resized(size) => {
208 +
                    renderer.window_resized(size)?;
209 +
                }
210 +
                platform::WindowEvent::KeyboardInput(platform::KeyboardInput {
211 +
                    key: Some(platform::Key::Escape),
212 +
                    state: platform::InputState::Pressed,
213 +
                    ..
214 +
                }) => break 'main,
215 +
                _ => {}
216 +
            }
217 +
        }
218 +
        renderer.frame()?;
219 +
        win.present();
220 +
    }
221 +
222 +
    let size = win.size();
223 +
    let mut pixels = vec![Rgba8::default(); size.width as usize * size.height as usize];
224 +
    renderer
225 +
        .backend
226 +
        .pass_read_color_attachment(renderer.offscreen_pass, 0, &mut pixels)?;
227 +
228 +
    let img = gfx::Image::new(pixels, Size::new(size.width as u32, size.height as u32));
229 +
    let mut file = std::fs::File::create("./screenshot.rgba")?;
230 +
    img.write(&mut file)?;
231 +
232 +
    Ok(())
233 +
}
234 +
235 +
mod display_shader {
236 +
    use super::*;
237 +
238 +
    pub const VERTEX: &str = r#"
239 +
    #version 330
240 +
241 +
    const vec2[6] POSITION = vec2[](
242 +
        vec2(-1.0, -1.0),
243 +
        vec2( 1.0, -1.0),
244 +
        vec2( 1.0,  1.0),
245 +
        vec2(-1.0, -1.0),
246 +
        vec2(-1.0,  1.0),
247 +
        vec2( 1.0,  1.0)
248 +
    );
249 +
    const vec2[6] UV = vec2[](
250 +
        vec2(0.0, 0.0),
251 +
        vec2(1.0, 0.0),
252 +
        vec2(1.0, 1.0),
253 +
        vec2(0.0, 0.0),
254 +
        vec2(0.0, 1.0),
255 +
        vec2(1.0, 1.0)
256 +
    );
257 +
258 +
    out vec2 f_uv;
259 +
260 +
    void main() {
261 +
        f_uv = UV[gl_VertexID];
262 +
        gl_Position = vec4(POSITION[gl_VertexID], 0.0, 1.0);
263 +
    }
264 +
    "#;
265 +
266 +
    pub const FRAGMENT: &str = r#"
267 +
    #version 330
268 +
269 +
    uniform sampler2D framebuffer;
270 +
271 +
    in  vec2 f_uv;
272 +
    out vec4 fragColor;
273 +
274 +
    void main() {
275 +
        fragColor = texture(
276 +
            framebuffer,
277 +
            vec2(f_uv.s, f_uv.t)
278 +
        );
279 +
    }
280 +
    "#;
281 +
282 +
    pub fn meta() -> gfx::ShaderDescriptor<'static> {
283 +
        gfx::ShaderDescriptor {
284 +
            textures: &["framebuffer"],
285 +
            uniforms: gfx::UniformBlockLayout { uniforms: &[] },
286 +
        }
287 +
    }
288 +
289 +
    #[repr(C)]
290 +
    pub struct Uniforms {
291 +
        pub mvp: Transform3D,
292 +
    }
293 +
    unsafe impl bytes::Packed for Uniforms {}
294 +
}
295 +
296 +
mod offscreen_shader {
297 +
    use super::*;
298 +
299 +
    pub const VERTEX: &str = r#"
300 +
    #version 100
301 +
302 +
    attribute vec2 in_pos;
303 +
    attribute vec4 in_color;
304 +
305 +
    varying lowp vec4 color;
306 +
307 +
    uniform mat4 mvp;
308 +
309 +
    void main() {
310 +
        gl_Position = mvp * vec4(in_pos, 0, 1);
311 +
        color = in_color;
312 +
    }
313 +
    "#;
314 +
315 +
    pub const FRAGMENT: &str = r#"
316 +
    #version 100
317 +
318 +
    varying lowp vec4 color;
319 +
320 +
    void main() {
321 +
        gl_FragColor = color;
322 +
    }
323 +
    "#;
324 +
325 +
    pub fn meta() -> gfx::ShaderDescriptor<'static> {
326 +
        gfx::ShaderDescriptor {
327 +
            textures: &[],
328 +
            uniforms: gfx::UniformBlockLayout {
329 +
                uniforms: &[gfx::UniformDescriptor {
330 +
                    name: "mvp",
331 +
                    kind: gfx::UniformKind::Mat4,
332 +
                    arity: 1,
333 +
                }],
334 +
            },
335 +
        }
336 +
    }
337 +
}
ombre/examples/sprite.rs added +128 -0
1 +
#![deny(clippy::all)]
2 +
#![allow(clippy::unwrap_used)]
3 +
#![allow(clippy::unreadable_literal)]
4 +
#![allow(clippy::single_match)]
5 +
#[path = "common/runtime.rs"]
6 +
mod runtime;
7 +
8 +
use std::time;
9 +
10 +
use ombre::prelude::*;
11 +
use ombre::ui as gui;
12 +
13 +
#[derive(Debug)]
14 +
pub struct State {
15 +
    width: f64,
16 +
    height: f64,
17 +
    scale: f32,
18 +
    started: time::Instant,
19 +
    image: Image,
20 +
}
21 +
22 +
pub struct Example<T> {
23 +
    ui: gui::Interface<gui::Canvas<State>, State>,
24 +
    state: State,
25 +
    backend: T,
26 +
}
27 +
28 +
impl<T: gfx::RenderBackend> Example<T> {
29 +
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, gui::Error<T>> {
30 +
        let bytes = include_bytes!("common/rx.rgba");
31 +
        let image = Image::try_from(bytes.as_slice()).unwrap();
32 +
        let root = gui::canvas(move |state: &State, _view, mut g| {
33 +
            let sw = image.size.w as f32 * state.scale;
34 +
            let sh = image.size.h as f32 * state.scale;
35 +
            let rows = (state.height as f32 / sh).ceil() as u32 + 1;
36 +
            let cols = (state.width as f32 / sw).ceil() as u32 + 1;
37 +
            let elapsed = time::Instant::now().duration_since(state.started).as_millis() as f32;
38 +
            let freq = 0.002;
39 +
40 +
            for i in 0..rows {
41 +
                let y = i as f32 * sh;
42 +
43 +
                for j in 0..cols {
44 +
                    let x = j as f32 * sw;
45 +
                    let offset = if j % 2 == 0 {
46 +
                        elapsed / 11.
47 +
                    } else {
48 +
                        elapsed / -12.
49 +
                    };
50 +
                    let src = Rect::new([0., offset], image.size);
51 +
                    let dst = Rect::new([x, y], [sw, sh]);
52 +
                    let tint = Rgba::new(
53 +
                        i as f32 / rows as f32,
54 +
                        j as f32 / cols as f32,
55 +
                        (f32::sin(freq * elapsed) + 1.0) / 2.0,
56 +
                        0.5,
57 +
                    );
58 +
                    g.blit(state.image.clone(), src, dst, tint);
59 +
                }
60 +
            }
61 +
        });
62 +
63 +
        let ui = gui::interface(win, &mut backend).build(root)?;
64 +
        let size = win.size();
65 +
66 +
        Ok(Self {
67 +
            backend,
68 +
            state: State {
69 +
                scale: 1.,
70 +
                width: size.width,
71 +
                height: size.height,
72 +
                started: time::Instant::now(),
73 +
                image: image.clone(),
74 +
            },
75 +
            ui,
76 +
        })
77 +
    }
78 +
}
79 +
80 +
impl<T: RenderBackend> Application for Example<T> {
81 +
    type Error = T::Error;
82 +
83 +
    fn tick(
84 +
        &mut self,
85 +
        _delta: ombre::runtime::time::Duration,
86 +
        win: &mut platform::Window,
87 +
    ) -> Result<(), Self::Error> {
88 +
        win.redraw();
89 +
90 +
        Ok(())
91 +
    }
92 +
93 +
    fn event(
94 +
        &mut self,
95 +
        event: platform::WindowEvent,
96 +
        win: &mut platform::Window,
97 +
    ) -> Result<(), Self::Error> {
98 +
        match event {
99 +
            platform::WindowEvent::Resized(size) => {
100 +
                self.state.width = size.width;
101 +
                self.state.height = size.height;
102 +
            }
103 +
            platform::WindowEvent::KeyboardInput(k)
104 +
                if k.state.is_pressed() && k.key == Some(platform::Key::Space) =>
105 +
            {
106 +
                self.state.scale += 1.;
107 +
                if self.state.scale == 5. {
108 +
                    self.state.scale = 1.;
109 +
                }
110 +
            }
111 +
            _ => {}
112 +
        }
113 +
        self.ui.event(event, &mut self.state, &mut self.backend, win)?;
114 +
115 +
        Ok(())
116 +
    }
117 +
118 +
    fn frame(&mut self) -> Result<(), Self::Error> {
119 +
        let mut frame = self.backend.frame();
120 +
        self.ui.frame(&self.state, &mut frame)?;
121 +
122 +
        Ok(())
123 +
    }
124 +
}
125 +
126 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
127 +
    runtime::run("sprite", Example::init)
128 +
}
ombre/examples/state.rs added +58 -0
1 +
#![deny(clippy::all)]
2 +
#![allow(clippy::unwrap_used)]
3 +
#[path = "common/runtime.rs"]
4 +
mod runtime;
5 +
6 +
use ombre::prelude::*;
7 +
use ombre::ui as gui;
8 +
use ombre::ui::{Widget, WidgetExt};
9 +
10 +
type State = usize;
11 +
12 +
pub struct Example<T> {
13 +
    ui: gui::Interface<Box<dyn Widget<State>>, usize>,
14 +
    state: State,
15 +
    backend: T,
16 +
}
17 +
18 +
impl<T: gfx::RenderBackend> Example<T> {
19 +
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, gui::Error<T>> {
20 +
        let ui = gui::interface(win, &mut backend)
21 +
            .scale(4.0)
22 +
            .build(gui::label(|s: &State| s.to_string()).center().boxed())?;
23 +
24 +
        Ok(Self {
25 +
            ui,
26 +
            state: 0,
27 +
            backend,
28 +
        })
29 +
    }
30 +
}
31 +
32 +
impl<T: RenderBackend> Application for Example<T> {
33 +
    type Error = T::Error;
34 +
35 +
    fn event(
36 +
        &mut self,
37 +
        event: platform::WindowEvent,
38 +
        win: &mut platform::Window,
39 +
    ) -> Result<(), T::Error> {
40 +
        self.state += 1;
41 +
        self.ui.event(event, &mut self.state, &mut self.backend, win)?;
42 +
43 +
        Ok(())
44 +
    }
45 +
46 +
    fn frame(&mut self) -> Result<(), Self::Error> {
47 +
        let mut frame = self.backend.frame();
48 +
        self.ui.frame(&self.state, &mut frame)?;
49 +
50 +
        frame.commit();
51 +
52 +
        Ok(())
53 +
    }
54 +
}
55 +
56 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
57 +
    runtime::run("state", Example::init)
58 +
}
ombre/examples/text.rs added +140 -0
1 +
#![deny(clippy::all)]
2 +
#![allow(clippy::unwrap_used)]
3 +
#[path = "common/runtime.rs"]
4 +
mod runtime;
5 +
6 +
use ombre::prelude::*;
7 +
use ombre::ui as gui;
8 +
use ombre::ui::gfx::FontStyle;
9 +
use ombre::ui::gfx::TextSpan;
10 +
use ombre::ui::widgets::*;
11 +
use ombre::ui::{RichTextStorage, TextAlign};
12 +
13 +
/// Rich text object with layout.
14 +
#[derive(Debug)]
15 +
pub struct RichText {
16 +
    /// The actual text.
17 +
    pub content: String,
18 +
    /// Spans of text with contiguous style.
19 +
    pub spans: Vec<TextSpan>,
20 +
}
21 +
22 +
impl RichText {
23 +
    pub fn new(content: String, spans: Vec<TextSpan>) -> Self {
24 +
        Self { content, spans }
25 +
    }
26 +
}
27 +
28 +
impl RichTextStorage for RichText {
29 +
    fn len(&self) -> usize {
30 +
        self.content.len()
31 +
    }
32 +
33 +
    fn spans(&self) -> impl Iterator<Item = &TextSpan> {
34 +
        self.spans.iter()
35 +
    }
36 +
}
37 +
38 +
impl AsRef<str> for RichText {
39 +
    fn as_ref(&self) -> &str {
40 +
        self.content.as_ref()
41 +
    }
42 +
}
43 +
44 +
pub struct Example<T> {
45 +
    ui: gui::Interface<Box<dyn Widget<RichText>>, RichText>,
46 +
    text: RichText,
47 +
    backend: T,
48 +
}
49 +
50 +
impl<T: gfx::RenderBackend> Example<T> {
51 +
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, gui::Error<T>> {
52 +
        let venice = gui::fonts::uf2::VENICE;
53 +
        let spans: Vec<TextSpan> = [
54 +
            TextSpan {
55 +
                range: 0..2,
56 +
                font: FontName::new("Venice"),
57 +
                tint: Rgba8::RED,
58 +
                style: FontStyle::default(),
59 +
            },
60 +
            TextSpan {
61 +
                range: 2..5,
62 +
                font: FontName::new("Default"),
63 +
                tint: Rgba8::GREEN,
64 +
                style: FontStyle::default(),
65 +
            },
66 +
            TextSpan {
67 +
                range: 5..8,
68 +
                font: FontName::new("Default"),
69 +
                tint: Rgba8::PINK,
70 +
                style: FontStyle::default(),
71 +
            },
72 +
            TextSpan {
73 +
                range: 8..17,
74 +
                font: FontName::new("Venice"),
75 +
                tint: Rgba8::BLUE,
76 +
                style: FontStyle::default(),
77 +
            },
78 +
        ]
79 +
        .into_iter()
80 +
        .cycle()
81 +
        .take(4 * 40)
82 +
        .collect();
83 +
84 +
        let text = RichText::new("A Shadow is Born ".to_owned(), spans);
85 +
        let root = gui::text()
86 +
            .align(TextAlign::Left)
87 +
            .on_event(|widget, e, _, _, _| {
88 +
                if let &WidgetEvent::KeyDown(platform::Key::Space) = e {
89 +
                    let align = match widget.style().align {
90 +
                        TextAlign::Left => TextAlign::Center,
91 +
                        TextAlign::Center => TextAlign::Right,
92 +
                        TextAlign::Right => TextAlign::Left,
93 +
                    };
94 +
                    widget.style_mut().align = align;
95 +
                    widget.refresh();
96 +
97 +
                    return true;
98 +
                }
99 +
                false
100 +
            })
101 +
            .boxed();
102 +
103 +
        let ui = gui::interface(win, &mut backend)
104 +
            .font(venice)?
105 +
            .scale(4.0)
106 +
            .build(root)?;
107 +
108 +
        // TODO: Have alignment toggle with key.
109 +
        // TODO: Have hyphernation toggle with key.
110 +
111 +
        Ok(Self { backend, text, ui })
112 +
    }
113 +
}
114 +
115 +
impl<T: RenderBackend> Application for Example<T> {
116 +
    type Error = T::Error;
117 +
118 +
    fn event(
119 +
        &mut self,
120 +
        event: platform::WindowEvent,
121 +
        win: &mut platform::Window,
122 +
    ) -> Result<(), T::Error> {
123 +
        self.ui.event(event, &mut self.text, &mut self.backend, win)?;
124 +
125 +
        Ok(())
126 +
    }
127 +
128 +
    fn frame(&mut self) -> Result<(), Self::Error> {
129 +
        let mut frame = self.backend.frame();
130 +
        self.ui.frame(&self.text, &mut frame)?;
131 +
132 +
        frame.commit();
133 +
134 +
        Ok(())
135 +
    }
136 +
}
137 +
138 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
139 +
    runtime::run("text", Example::init)
140 +
}
ombre/examples/texture.rs added +225 -0
1 +
#![allow(clippy::unwrap_used)]
2 +
use ombre::derive::VertexAttributes;
3 +
use ombre::platform::Window;
4 +
use ombre::{math::Zero, prelude::*};
5 +
6 +
const PIXELS: [Rgba8; 4 * 4] = [
7 +
    Rgba8::new(0xFF, 0xFF, 0xFF, 0xFF),
8 +
    Rgba8::new(0xFF, 0x00, 0x00, 0xFF),
9 +
    Rgba8::new(0xFF, 0xFF, 0xFF, 0xFF),
10 +
    Rgba8::new(0xFF, 0x00, 0x00, 0xFF),
11 +
    Rgba8::new(0xFF, 0x00, 0x00, 0xFF),
12 +
    Rgba8::new(0xFF, 0xFF, 0xFF, 0xFF),
13 +
    Rgba8::new(0xFF, 0x00, 0x00, 0xFF),
14 +
    Rgba8::new(0xFF, 0xFF, 0xFF, 0xFF),
15 +
    Rgba8::new(0xFF, 0xFF, 0xFF, 0xFF),
16 +
    Rgba8::new(0xFF, 0x00, 0x00, 0x00),
17 +
    Rgba8::new(0xFF, 0xFF, 0xFF, 0xFF),
18 +
    Rgba8::new(0xFF, 0x00, 0x00, 0xFF),
19 +
    Rgba8::new(0xFF, 0x00, 0x00, 0xFF),
20 +
    Rgba8::new(0xFF, 0xFF, 0xFF, 0xFF),
21 +
    Rgba8::new(0xFF, 0x00, 0x00, 0xFF),
22 +
    Rgba8::new(0xFF, 0xFF, 0xFF, 0xFF),
23 +
];
24 +
25 +
#[repr(C)]
26 +
#[derive(VertexAttributes)]
27 +
struct Vertex {
28 +
    #[attrib(name = "in_pos")]
29 +
    pos: Vector2D,
30 +
    #[attrib(name = "in_uv")]
31 +
    uv: Vector2D,
32 +
}
33 +
34 +
struct Example<T> {
35 +
    pipeline: PipelineId,
36 +
    bindings: Bindings<1, 1>,
37 +
    delta: f64,
38 +
    size: Size<u32>,
39 +
    texture: TextureId,
40 +
    pixels: [Rgba8; 4 * 4],
41 +
    backend: T,
42 +
}
43 +
44 +
impl<T: RenderBackend> ApplicationExt for Example<T> {
45 +
    type Error = T::Error;
46 +
47 +
    fn window_resized(&mut self, size: platform::LogicalSize) -> Result<(), Self::Error> {
48 +
        self.size = Size::new(size.width as u32, size.height as u32);
49 +
50 +
        Ok(())
51 +
    }
52 +
53 +
    fn key_down(&mut self, key: platform::Key) {
54 +
        if key == platform::Key::Space {
55 +
            for pixel in self.pixels.iter_mut() {
56 +
                *pixel = pixel.invert();
57 +
            }
58 +
            self.backend
59 +
                .texture_update(self.texture, Rect::origin(Size::new(4u32, 4)), &self.pixels)
60 +
                .unwrap();
61 +
        }
62 +
    }
63 +
64 +
    fn update(
65 +
        &mut self,
66 +
        delta: runtime::time::Duration,
67 +
        win: &mut Window,
68 +
    ) -> Result<(), Self::Error> {
69 +
        self.delta += delta.as_secs_f64();
70 +
        win.redraw();
71 +
72 +
        Ok(())
73 +
    }
74 +
75 +
    fn present(&mut self) -> Result<(), Self::Error> {
76 +
        let mut frame = self.backend.frame();
77 +
78 +
        frame.begin_default_pass(Default::default(), self.size);
79 +
        frame.apply_pipeline(&self.pipeline)?;
80 +
        frame.apply_bindings(&self.bindings)?;
81 +
82 +
        for i in 0..10 {
83 +
            let t = self.delta + i as f64 * 0.3;
84 +
85 +
            frame.apply_uniforms(&shader::Uniforms {
86 +
                offset: [t.sin() as f32 * 0.5, (t * 3.).cos() as f32 * 0.5],
87 +
            })?;
88 +
            frame.draw(0, 6, 1)?;
89 +
        }
90 +
        frame.end_pass();
91 +
        frame.commit();
92 +
93 +
        Ok(())
94 +
    }
95 +
}
96 +
97 +
impl<T: RenderBackend> Example<T> {
98 +
    pub fn init(mut backend: T) -> Result<Example<T>, T::Error> {
99 +
        #[rustfmt::skip]
100 +
        let vertices: [Vertex; 4] = [
101 +
            Vertex { pos : Vector2D::new(-0.5,-0.5), uv: Vector2D::new(0., 0. ) },
102 +
            Vertex { pos : Vector2D::new( 0.5,-0.5), uv: Vector2D::new(1., 0. ) },
103 +
            Vertex { pos : Vector2D::new( 0.5, 0.5), uv: Vector2D::new(1., 1. ) },
104 +
            Vertex { pos : Vector2D::new(-0.5, 0.5), uv: Vector2D::new(0., 1. ) },
105 +
        ];
106 +
        let vertex_buffer = backend.buffer(
107 +
            BufferKind::Vertex,
108 +
            BufferUsage::Immutable,
109 +
            BufferSource::slice(&vertices),
110 +
        )?;
111 +
112 +
        let indices: [u16; 6] = [0, 1, 2, 0, 2, 3];
113 +
        let index_buffer = backend.buffer(
114 +
            BufferKind::Index,
115 +
            BufferUsage::Immutable,
116 +
            BufferSource::slice(&indices),
117 +
        )?;
118 +
119 +
        let texture = backend.texture(gfx::Texture {
120 +
            data: PIXELS.as_slice(),
121 +
            size: Size::new(4, 4),
122 +
            min_filter: FilterMode::Nearest,
123 +
            mag_filter: FilterMode::Nearest,
124 +
            format: TextureFormat::Srgba8,
125 +
            ..gfx::Texture::default()
126 +
        })?;
127 +
128 +
        let bindings = Bindings {
129 +
            vertex: [vertex_buffer],
130 +
            index: Some(index_buffer),
131 +
            textures: [texture],
132 +
        };
133 +
134 +
        let shader = backend
135 +
            .shader(
136 +
                ShaderSource {
137 +
                    vertex: shader::VERTEX,
138 +
                    fragment: shader::FRAGMENT,
139 +
                    geometry: None,
140 +
                },
141 +
                shader::meta(),
142 +
            )
143 +
            .unwrap();
144 +
145 +
        let pipeline = backend.pipeline(
146 +
            shader,
147 +
            gfx::PipelineDescriptor {
148 +
                layout: &[gfx::BufferLayout {
149 +
                    attrs: Vertex::attributes(),
150 +
                    ..gfx::BufferLayout::default()
151 +
                }],
152 +
                ..gfx::PipelineDescriptor::default()
153 +
            },
154 +
        )?;
155 +
156 +
        Ok(Self {
157 +
            pipeline,
158 +
            bindings,
159 +
            backend,
160 +
            delta: 0.,
161 +
            size: Size::ZERO,
162 +
            pixels: PIXELS,
163 +
            texture,
164 +
        })
165 +
    }
166 +
}
167 +
168 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
169 +
    logger::init(log::Level::Debug)?;
170 +
171 +
    let (mut win, events) =
172 +
        platform::init("texture", 640, 480, &[], platform::GraphicsContext::Gl)?;
173 +
    let ctx = unsafe { glow::Context::from_loader_function(|p| win.get_proc_address(p)) };
174 +
    let backend = gfx::gl::Context::new(ctx, win.size())?;
175 +
    let app = Example::init(backend)?;
176 +
177 +
    ombre::runtime::default::run(win, events, app)?;
178 +
179 +
    Ok(())
180 +
}
181 +
182 +
mod shader {
183 +
    use super::*;
184 +
185 +
    pub const VERTEX: &str = r#"#version 100
186 +
    attribute vec2 in_pos;
187 +
    attribute vec2 in_uv;
188 +
189 +
    uniform vec2 offset;
190 +
191 +
    varying lowp vec2 texcoord;
192 +
193 +
    void main() {
194 +
        gl_Position = vec4(in_pos + offset, 0, 1);
195 +
        texcoord = in_uv;
196 +
    }"#;
197 +
198 +
    pub const FRAGMENT: &str = r#"#version 100
199 +
    varying lowp vec2 texcoord;
200 +
201 +
    uniform sampler2D tex;
202 +
203 +
    void main() {
204 +
        gl_FragColor = texture2D(tex, texcoord);
205 +
    }"#;
206 +
207 +
    pub fn meta() -> ShaderDescriptor<'static> {
208 +
        ShaderDescriptor {
209 +
            textures: &["tex"],
210 +
            uniforms: UniformBlockLayout {
211 +
                uniforms: &[UniformDescriptor {
212 +
                    name: "offset",
213 +
                    kind: UniformKind::Float2,
214 +
                    arity: 1,
215 +
                }],
216 +
            },
217 +
        }
218 +
    }
219 +
220 +
    #[repr(C)]
221 +
    pub struct Uniforms {
222 +
        pub offset: [f32; 2],
223 +
    }
224 +
    unsafe impl bytes::Packed for Uniforms {}
225 +
}
ombre/examples/triangle.rs added +145 -0
1 +
#![allow(clippy::unwrap_used)]
2 +
use ombre::derive::Packed;
3 +
use ombre::{math::Zero, prelude::*};
4 +
5 +
#[repr(C)]
6 +
#[derive(Packed)]
7 +
struct Vertex {
8 +
    position: [f32; 2],
9 +
    color: [f32; 4],
10 +
}
11 +
12 +
pub struct Renderer<T> {
13 +
    pipeline: gfx::PipelineId,
14 +
    bindings: gfx::Bindings<1, 0>,
15 +
    size: Size<u32>,
16 +
    backend: T,
17 +
}
18 +
19 +
impl<T: gfx::RenderBackend> ApplicationExt for Renderer<T> {
20 +
    type Error = T::Error;
21 +
22 +
    fn window_resized(&mut self, size: platform::LogicalSize) -> Result<(), Self::Error> {
23 +
        self.size = Size::new(size.width as u32, size.height as u32);
24 +
25 +
        Ok(())
26 +
    }
27 +
28 +
    fn present(&mut self) -> Result<(), Self::Error> {
29 +
        let mut frame = self.backend.frame();
30 +
31 +
        frame.begin_default_pass(Default::default(), self.size);
32 +
        frame.apply_pipeline(&self.pipeline)?;
33 +
        frame.apply_bindings(&self.bindings)?;
34 +
        frame.draw(0, 3, 1)?;
35 +
        frame.end_pass();
36 +
        frame.commit();
37 +
38 +
        Ok(())
39 +
    }
40 +
}
41 +
42 +
impl<T: gfx::RenderBackend> Renderer<T> {
43 +
    pub fn init(mut backend: T) -> Result<Self, T::Error> {
44 +
        #[rustfmt::skip]
45 +
        let vertices: [Vertex; 3] = [
46 +
            Vertex { position: [-0.5, -0.5], color: [1., 1., 0., 1.] },
47 +
            Vertex { position: [ 0.5, -0.5], color: [0., 1., 1., 1.] },
48 +
            Vertex { position: [ 0.0,  0.5], color: [1., 0., 1., 1.] },
49 +
        ];
50 +
        let vertex_buffer = backend.buffer(
51 +
            gfx::BufferKind::Vertex,
52 +
            gfx::BufferUsage::Immutable,
53 +
            gfx::BufferSource::slice(&vertices),
54 +
        )?;
55 +
        let index_buffer = backend.buffer(
56 +
            gfx::BufferKind::Index,
57 +
            gfx::BufferUsage::Immutable,
58 +
            gfx::BufferSource::slice(&[0, 1, 2]),
59 +
        )?;
60 +
        let bindings = gfx::Bindings {
61 +
            vertex: [vertex_buffer],
62 +
            index: Some(index_buffer),
63 +
            textures: [],
64 +
        };
65 +
        let shader = backend
66 +
            .shader(
67 +
                gfx::ShaderSource {
68 +
                    vertex: shader::VERTEX,
69 +
                    fragment: shader::FRAGMENT,
70 +
                    geometry: None,
71 +
                },
72 +
                shader::descriptor(),
73 +
            )
74 +
            .unwrap();
75 +
        let pipeline = backend.pipeline(
76 +
            shader,
77 +
            gfx::PipelineDescriptor {
78 +
                layout: &[gfx::BufferLayout {
79 +
                    attrs: &[
80 +
                        gfx::VertexAttribute::new("position", gfx::VertexFormat::Float2),
81 +
                        gfx::VertexAttribute::new("color", gfx::VertexFormat::Float4),
82 +
                    ],
83 +
                    ..gfx::BufferLayout::default()
84 +
                }],
85 +
                ..gfx::PipelineDescriptor::default()
86 +
            },
87 +
        )?;
88 +
89 +
        Ok(Self {
90 +
            backend,
91 +
            pipeline,
92 +
            bindings,
93 +
            size: Size::ZERO,
94 +
        })
95 +
    }
96 +
}
97 +
98 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
99 +
    logger::init(log::Level::Debug)?;
100 +
101 +
    let (mut win, events) =
102 +
        platform::init("triangle", 640, 480, &[], platform::GraphicsContext::Gl)?;
103 +
    let ctx = unsafe { glow::Context::from_loader_function(|p| win.get_proc_address(p)) };
104 +
    let backend = gfx::gl::Context::new(ctx, win.size())?;
105 +
    let renderer = Renderer::init(backend)?;
106 +
107 +
    ombre::runtime::default::run(win, events, renderer)?;
108 +
109 +
    Ok(())
110 +
}
111 +
112 +
mod shader {
113 +
    use super::*;
114 +
115 +
    pub const VERTEX: &str = r#"
116 +
    #version 100
117 +
118 +
    attribute vec2 position;
119 +
    attribute vec4 color;
120 +
121 +
    varying lowp vec4 f_color;
122 +
123 +
    void main() {
124 +
        gl_Position = vec4(position, 0, 1);
125 +
        f_color = color;
126 +
    }
127 +
    "#;
128 +
129 +
    pub const FRAGMENT: &str = r#"
130 +
    #version 100
131 +
132 +
    varying lowp vec4 f_color;
133 +
134 +
    void main() {
135 +
        gl_FragColor = f_color;
136 +
    }
137 +
    "#;
138 +
139 +
    pub fn descriptor() -> gfx::ShaderDescriptor<'static> {
140 +
        gfx::ShaderDescriptor {
141 +
            textures: &[],
142 +
            uniforms: gfx::UniformBlockLayout { uniforms: &[] },
143 +
        }
144 +
    }
145 +
}
ombre/examples/vstack.rs added +59 -0
1 +
#![deny(clippy::all)]
2 +
#![allow(clippy::unwrap_used)]
3 +
#[path = "common/runtime.rs"]
4 +
mod runtime;
5 +
6 +
use ombre::prelude::*;
7 +
use ombre::ui as gui;
8 +
use ombre::ui::widgets::*;
9 +
10 +
pub struct Example<T> {
11 +
    ui: gui::Interface<Box<dyn Widget<()>>, ()>,
12 +
    backend: T,
13 +
}
14 +
15 +
impl<T: gfx::RenderBackend> Example<T> {
16 +
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, gui::Error<T>> {
17 +
        let ui = gui::interface(win, &mut backend).build(
18 +
            gui::vstack([
19 +
                Rgba8::RED.sized([96., 96.]),
20 +
                Rgba8::GREEN.sized([96., 96.]),
21 +
                Rgba8::BLUE.sized([96., 96.]),
22 +
                Rgba8::YELLOW.sized([96., 96.]),
23 +
                Rgba8::PINK.sized([96., 96.]),
24 +
            ])
25 +
            .stroke(4.)
26 +
            .center()
27 +
            .boxed(),
28 +
        )?;
29 +
30 +
        Ok(Self { backend, ui })
31 +
    }
32 +
}
33 +
34 +
impl<T: RenderBackend> Application for Example<T> {
35 +
    type Error = T::Error;
36 +
37 +
    fn event(
38 +
        &mut self,
39 +
        event: platform::WindowEvent,
40 +
        win: &mut platform::Window,
41 +
    ) -> Result<(), T::Error> {
42 +
        self.ui.event(event, &mut (), &mut self.backend, win)?;
43 +
44 +
        Ok(())
45 +
    }
46 +
47 +
    fn frame(&mut self) -> Result<(), Self::Error> {
48 +
        let mut frame = self.backend.frame();
49 +
        self.ui.frame(&(), &mut frame)?;
50 +
51 +
        frame.commit();
52 +
53 +
        Ok(())
54 +
    }
55 +
}
56 +
57 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
58 +
    runtime::run("vstack", Example::init)
59 +
}
ombre/examples/zstack.rs added +57 -0
1 +
#![deny(clippy::all)]
2 +
#![allow(clippy::unwrap_used)]
3 +
#[path = "common/runtime.rs"]
4 +
mod runtime;
5 +
6 +
use ombre::prelude::*;
7 +
use ombre::ui as gui;
8 +
use ombre::ui::widgets::*;
9 +
10 +
pub struct Example<T> {
11 +
    ui: gui::Interface<Box<dyn Widget<()>>, ()>,
12 +
    backend: T,
13 +
}
14 +
15 +
impl<T: gfx::RenderBackend> Example<T> {
16 +
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, gui::Error<T>> {
17 +
        let ui = gui::interface(win, &mut backend).scale(4.).build(
18 +
            gui::zstack([
19 +
                Rgba8::RED.sized([96., 96.]),
20 +
                Rgba8::GREEN.sized([64., 64.]),
21 +
                Rgba8::BLUE.sized([32., 32.]),
22 +
            ])
23 +
            .stroke(4.)
24 +
            .center()
25 +
            .boxed(),
26 +
        )?;
27 +
28 +
        Ok(Self { backend, ui })
29 +
    }
30 +
}
31 +
32 +
impl<T: RenderBackend> Application for Example<T> {
33 +
    type Error = T::Error;
34 +
35 +
    fn event(
36 +
        &mut self,
37 +
        event: platform::WindowEvent,
38 +
        win: &mut platform::Window,
39 +
    ) -> Result<(), T::Error> {
40 +
        self.ui.event(event, &mut (), &mut self.backend, win)?;
41 +
42 +
        Ok(())
43 +
    }
44 +
45 +
    fn frame(&mut self) -> Result<(), Self::Error> {
46 +
        let mut frame = self.backend.frame();
47 +
        self.ui.frame(&(), &mut frame)?;
48 +
49 +
        frame.commit();
50 +
51 +
        Ok(())
52 +
    }
53 +
}
54 +
55 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
56 +
    runtime::run("vstack", Example::init)
57 +
}
ombre/src/bench.rs added +266 -0
1 +
//! Simple benchmarking library.
2 +
//!
3 +
//! Copyright (c) Frank Denis, code adapted from `benchmark-simple`.
4 +
use std::cmp::max;
5 +
use std::fmt::{self, Debug, Display, Formatter};
6 +
use std::rc::Rc;
7 +
use std::time::{Duration, Instant};
8 +
9 +
use nonempty::NonEmpty;
10 +
11 +
/// Configuration options for running benchmarks.
12 +
#[derive(Clone, Debug)]
13 +
pub struct Options {
14 +
    /// Number of iterations to perform for each sample.
15 +
    pub iterations: u64,
16 +
    /// Number of warm-up iterations to perform before timing.
17 +
    pub warmup_iterations: u64,
18 +
    /// Minimum number of samples to collect before checking convergence.
19 +
    pub min_samples: usize,
20 +
    /// Maximum number of samples to collect before stopping.
21 +
    pub max_samples: usize,
22 +
    /// Maximum relative standard deviation to tolerate (in 0...100).
23 +
    pub max_rsd: f64,
24 +
    /// Maximum total duration to run the benchmark for.
25 +
    pub max_duration: Option<Duration>,
26 +
}
27 +
28 +
impl Default for Options {
29 +
    fn default() -> Self {
30 +
        Self {
31 +
            iterations: 1,
32 +
            warmup_iterations: 1,
33 +
            min_samples: 3,
34 +
            max_samples: 6,
35 +
            max_rsd: 5.0,
36 +
            max_duration: None,
37 +
        }
38 +
    }
39 +
}
40 +
41 +
/// A benchmark result.
42 +
#[derive(Clone)]
43 +
pub struct BenchResult {
44 +
    elapsed: Duration,
45 +
    options: Rc<Options>,
46 +
}
47 +
48 +
impl BenchResult {
49 +
    /// Returns the elapsed time in seconds.
50 +
    pub fn as_secs(&self) -> u64 {
51 +
        self.elapsed.as_secs()
52 +
    }
53 +
54 +
    /// Returns the elapsed time in seconds (floating point).
55 +
    pub fn as_secs_f64(&self) -> f64 {
56 +
        self.elapsed.as_secs_f64()
57 +
    }
58 +
59 +
    /// Returns the elapsed time in milliseconds.
60 +
    pub fn as_millis(&self) -> u128 {
61 +
        self.elapsed.as_millis()
62 +
    }
63 +
64 +
    /// Returns the elapsed time in microseconds.
65 +
    pub fn as_micros(&self) -> u128 {
66 +
        self.elapsed.as_micros()
67 +
    }
68 +
69 +
    /// Compute the throughput for a given volume of data.
70 +
    /// The volume is the amount of bytes processed in a single iteration.
71 +
    pub fn throughput(self, mut volume: u128) -> Throughput {
72 +
        volume *= self.options.iterations as u128;
73 +
        Throughput {
74 +
            volume: volume as f64,
75 +
            result: self,
76 +
            unit: Unit::Unknown,
77 +
        }
78 +
    }
79 +
80 +
    /// Compute the throughput in bits for a given volume of data.
81 +
    /// The volume is the amount of bytes processed in a single iteration.
82 +
    pub fn throughput_bits(self, mut volume: u128) -> Throughput {
83 +
        volume *= self.options.iterations as u128;
84 +
        volume *= 8;
85 +
        Throughput {
86 +
            volume: volume as f64,
87 +
            result: self,
88 +
            unit: Unit::Bits,
89 +
        }
90 +
    }
91 +
92 +
    /// Compute the throughput in bytes for a given volume of data.
93 +
    /// The volume is the amount of bytes processed in a single iteration.
94 +
    pub fn throughput_bytes(self, mut volume: u128) -> Throughput {
95 +
        volume *= self.options.iterations as u128;
96 +
        // volume *= 8;
97 +
        Throughput {
98 +
            volume: volume as f64,
99 +
            result: self,
100 +
            unit: Unit::Bytes,
101 +
        }
102 +
    }
103 +
}
104 +
105 +
impl Display for BenchResult {
106 +
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
107 +
        write!(f, "{:.2}s", self.as_secs_f64())
108 +
    }
109 +
}
110 +
111 +
impl Debug for BenchResult {
112 +
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
113 +
        write!(f, "{}", self)
114 +
    }
115 +
}
116 +
117 +
/// Unit of volume.
118 +
#[derive(Clone, Copy, Debug, Eq, PartialEq, Default)]
119 +
pub enum Unit {
120 +
    /// No unit.
121 +
    #[default]
122 +
    Unknown,
123 +
    /// Bytes.
124 +
    Bytes,
125 +
    /// Bits.
126 +
    Bits,
127 +
}
128 +
129 +
impl Display for Unit {
130 +
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
131 +
        match self {
132 +
            Unit::Unknown => write!(f, ""),
133 +
            Unit::Bytes => write!(f, "B"),
134 +
            Unit::Bits => write!(f, "b"),
135 +
        }
136 +
    }
137 +
}
138 +
139 +
/// The result of a benchmark, as a throughput.
140 +
#[derive(Clone)]
141 +
pub struct Throughput {
142 +
    volume: f64,
143 +
    result: BenchResult,
144 +
    unit: Unit,
145 +
}
146 +
147 +
impl Throughput {
148 +
    /// The throughput as a floating point number.
149 +
    pub fn as_f64(&self) -> f64 {
150 +
        self.volume * 1_000_000f64 / (max(1, self.result.as_micros()) as f64)
151 +
    }
152 +
153 +
    /// The throughput as an integer.
154 +
    pub fn as_u128(&self) -> u128 {
155 +
        self.volume as u128 * 1_000_000 / (max(1, self.result.as_micros()) as u128)
156 +
    }
157 +
158 +
    /// The throughput in kilobytes.
159 +
    pub fn as_kb(&self) -> f64 {
160 +
        self.volume * 1_000_000f64 / (max(1, self.result.as_micros()) as f64) / 1024.0
161 +
    }
162 +
163 +
    /// The throughput in megabytes.
164 +
    pub fn as_mb(&self) -> f64 {
165 +
        self.volume * 1_000_000f64 / (max(1, self.result.as_micros()) as f64) / (1024.0 * 1024.0)
166 +
    }
167 +
168 +
    /// The throughput in gigabytes.
169 +
    pub fn as_gb(&self) -> f64 {
170 +
        self.volume * 1_000_000f64
171 +
            / (max(1, self.result.as_micros()) as f64)
172 +
            / (1024.0 * 1024.0 * 1024.0)
173 +
    }
174 +
}
175 +
176 +
impl Display for Throughput {
177 +
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
178 +
        match self.unit {
179 +
            Unit::Unknown => match self.as_u128() {
180 +
                0..=999 => write!(f, "{:.2} /s", self.as_f64()),
181 +
                1_000..=999_999 => write!(f, "{:.2} K/s", self.as_kb()),
182 +
                1_000_000..=999_999_999 => write!(f, "{:.2} M/s", self.as_mb()),
183 +
                _ => write!(f, "{:.2} G/s", self.as_gb()),
184 +
            },
185 +
            Unit::Bytes => match self.as_u128() {
186 +
                0..=999 => write!(f, "{:.2} B/s", self.as_f64()),
187 +
                1_000..=999_999 => write!(f, "{:.2} KB/s", self.as_kb()),
188 +
                1_000_000..=999_999_999 => write!(f, "{:.2} MB/s", self.as_mb()),
189 +
                _ => write!(f, "{:.2} GB/s", self.as_gb()),
190 +
            },
191 +
            Unit::Bits => match self.as_u128() {
192 +
                0..=999 => write!(f, "{:.2} b/s", self.as_f64()),
193 +
                1_000..=999_999 => write!(f, "{:.2} Kb/s", self.as_kb()),
194 +
                1_000_000..=999_999_999 => write!(f, "{:.2} Mb/s", self.as_mb()),
195 +
                _ => write!(f, "{:.2} Gb/s", self.as_gb()),
196 +
            },
197 +
        }
198 +
    }
199 +
}
200 +
201 +
impl Debug for Throughput {
202 +
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
203 +
        write!(f, "{}", self)
204 +
    }
205 +
}
206 +
207 +
/// Executes a function repeatedly and measures the total duration.
208 +
/// Used internally by the benchmarking system.
209 +
fn call<F, G>(f: &mut F, iterations: u64) -> Duration
210 +
where
211 +
    F: FnMut() -> G,
212 +
{
213 +
    let start = Instant::now();
214 +
    for _ in 0..iterations {
215 +
        black_box(f());
216 +
    }
217 +
    start.elapsed()
218 +
}
219 +
220 +
/// Run a benchmark.
221 +
pub fn run<F, G>(options: &Options, mut f: F) -> BenchResult
222 +
where
223 +
    F: FnMut() -> G,
224 +
{
225 +
    let max_samples = max(options.max_samples, 1);
226 +
    for _ in 0..options.warmup_iterations {
227 +
        black_box(f());
228 +
    }
229 +
230 +
    let start = Instant::now();
231 +
    let mut results = NonEmpty::new(call(&mut f, options.iterations)); // First sample.
232 +
233 +
    // Remaining samples.
234 +
    for _ in 0..max_samples - 1 {
235 +
        results.push(call(&mut f, options.iterations));
236 +
237 +
        if results.len() >= 2 {
238 +
            let mean = results.iter().map(|r| r.as_secs_f64()).sum::<f64>() / results.len() as f64;
239 +
            let std_dev = (results.iter().map(|r| (r.as_secs_f64() - mean).powi(2)).sum::<f64>()
240 +
                / (results.len() - 1) as f64)
241 +
                .sqrt();
242 +
            let rsd = std_dev * 100.0 / mean;
243 +
244 +
            if results.len() >= options.min_samples && rsd < options.max_rsd {
245 +
                break;
246 +
            }
247 +
            if let Some(max_duration) = options.max_duration {
248 +
                let elapsed = start.elapsed();
249 +
                if elapsed >= max_duration {
250 +
                    break;
251 +
                }
252 +
            }
253 +
        }
254 +
    }
255 +
    let elapsed = *results.minimum_by_key(|r| r.as_micros());
256 +
    let options = Rc::new(options.clone());
257 +
258 +
    BenchResult { elapsed, options }
259 +
}
260 +
261 +
/// Force the compiler to avoid optimizing away a value that is computed
262 +
/// for benchmarking purposes, but not used afterwards.
263 +
#[inline(never)]
264 +
pub fn black_box<T>(dummy: T) -> T {
265 +
    std::hint::black_box(dummy)
266 +
}
ombre/src/bytes.rs added +135 -0
1 +
//! Byte slices.
2 +
use std::{any, mem, slice};
3 +
4 +
pub mod encoding;
5 +
pub mod rle;
6 +
7 +
/// Used when an empty [`AsBytes`] instance is needed.
8 +
#[derive(Debug, Clone, Copy, Default)]
9 +
pub struct Empty;
10 +
11 +
/// Marker trait for types that are packed and can be safely
12 +
/// converted to a byte slice.
13 +
///
14 +
/// # Safety
15 +
///
16 +
/// Types which derive `repr(C)` and do not have any pointers or references can safely implement
17 +
/// this trait.
18 +
pub unsafe trait Packed {}
19 +
20 +
unsafe impl<T, const N: usize> Packed for [T; N] where T: Packed {}
21 +
unsafe impl Packed for u8 {}
22 +
unsafe impl Packed for u16 {}
23 +
unsafe impl Packed for u32 {}
24 +
unsafe impl Packed for u64 {}
25 +
unsafe impl Packed for i8 {}
26 +
unsafe impl Packed for i16 {}
27 +
unsafe impl Packed for i32 {}
28 +
unsafe impl Packed for i64 {}
29 +
unsafe impl Packed for f32 {}
30 +
unsafe impl Packed for f64 {}
31 +
unsafe impl Packed for crate::gfx::Rgba8 {}
32 +
unsafe impl Packed for crate::gfx::Rgb8 {}
33 +
unsafe impl Packed for crate::gfx::Rgba<f32> {}
34 +
unsafe impl<T> Packed for crate::gfx::Size<T> where T: Packed {}
35 +
unsafe impl<T> Packed for crate::gfx::Point2D<T> where T: Packed {}
36 +
unsafe impl<T> Packed for crate::gfx::Vector2D<T> where T: Packed {}
37 +
unsafe impl<T> Packed for crate::gfx::Vector3D<T> where T: Packed {}
38 +
unsafe impl<T> Packed for crate::gfx::Vector4D<T> where T: Packed {}
39 +
unsafe impl<S, D> Packed for crate::gfx::Transform2D<S, D> {}
40 +
unsafe impl<S, D> Packed for crate::gfx::Transform3D<S, D> {}
41 +
42 +
/// Types that can be represented as a `u8` slice.
43 +
///
44 +
/// # Safety
45 +
///
46 +
/// This trait should only be implemented if the type can be safely
47 +
/// converted to a slice.
48 +
pub trait AsBytes {
49 +
    /// Return a byte slice representation.
50 +
    fn as_bytes(&self) -> &[u8];
51 +
}
52 +
53 +
impl AsBytes for () {
54 +
    fn as_bytes(&self) -> &[u8] {
55 +
        &[]
56 +
    }
57 +
}
58 +
59 +
impl AsBytes for Empty {
60 +
    fn as_bytes(&self) -> &[u8] {
61 +
        &[]
62 +
    }
63 +
}
64 +
65 +
impl<T> AsBytes for T
66 +
where
67 +
    T: Packed,
68 +
{
69 +
    fn as_bytes(&self) -> &[u8] {
70 +
        unsafe { slice::from_raw_parts(self as *const Self as *const u8, mem::size_of::<Self>()) }
71 +
    }
72 +
}
73 +
74 +
impl<T: Packed> AsBytes for &[T] {
75 +
    fn as_bytes(&self) -> &[u8] {
76 +
        unsafe { slice::from_raw_parts(self.as_ptr() as *const u8, std::mem::size_of_val(*self)) }
77 +
    }
78 +
}
79 +
80 +
impl<T: Packed> AsBytes for [T] {
81 +
    fn as_bytes(&self) -> &[u8] {
82 +
        unsafe { slice::from_raw_parts(self.as_ptr() as *const u8, std::mem::size_of_val(self)) }
83 +
    }
84 +
}
85 +
86 +
/// Types that can be represented as a mutable `u8` slice.
87 +
pub trait AsBytesMut {
88 +
    /// Return a mutable byte slice representation.
89 +
    fn as_bytes_mut(&mut self) -> &mut [u8];
90 +
}
91 +
92 +
impl<T> AsBytesMut for &mut [T] {
93 +
    fn as_bytes_mut(&mut self) -> &mut [u8] {
94 +
        let (head, aligned, tail) = unsafe { self.align_to_mut::<u8>() };
95 +
96 +
        assert!(head.is_empty());
97 +
        assert!(tail.is_empty());
98 +
99 +
        aligned
100 +
    }
101 +
}
102 +
103 +
/// Align a byte slice to any slice type.
104 +
///
105 +
/// # Panics
106 +
///
107 +
/// If the byte slice length is not a multiple of the size of a `T`.
108 +
pub fn align_to<T>(bytes: &[u8]) -> &[T] {
109 +
    if bytes.len() % mem::size_of::<T>() != 0 {
110 +
        panic!(
111 +
            "{}::align_to: byte slice length {} is not a multiple of the size of a {}",
112 +
            module_path!(),
113 +
            bytes.len(),
114 +
            any::type_name::<T>()
115 +
        );
116 +
    }
117 +
    let ptr = bytes.as_ptr() as *const T;
118 +
    let len = bytes.len() / mem::size_of::<T>();
119 +
120 +
    unsafe { slice::from_raw_parts(ptr, len) }
121 +
}
122 +
123 +
#[cfg(test)]
124 +
mod tests {
125 +
    use super::*;
126 +
127 +
    #[test]
128 +
    fn test_as_bytes() {
129 +
        let data: [u16; 4] = [0, 1, 2, 0];
130 +
131 +
        assert_eq!(data.as_bytes().len(), 8);
132 +
        assert_eq!(data.as_bytes().len(), 8);
133 +
        assert_eq!(data.as_slice().as_bytes().len(), 8);
134 +
    }
135 +
}
ombre/src/bytes/encoding.rs added +255 -0
1 +
//! Binary encoding of `ombre` and `std` types. Useful for implementing file formats.
2 +
use std::{io, mem};
3 +
4 +
/// Things that can be encoded as binary.
5 +
pub trait Encode {
6 +
    /// Encode an object into a writer.
7 +
    fn encode<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error>;
8 +
}
9 +
10 +
/// Things that can be decoded from binary.
11 +
pub trait Decode: Sized {
12 +
    /// Decode an object from a reader.
13 +
    fn decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error>;
14 +
}
15 +
16 +
/// Encode an object into a byte vector.
17 +
pub fn serialize<T: Encode + ?Sized>(data: &T) -> Result<Vec<u8>, io::Error> {
18 +
    let mut buffer = Vec::new();
19 +
    let len = data.encode(&mut buffer)?;
20 +
21 +
    debug_assert_eq!(len, buffer.len());
22 +
23 +
    Ok(buffer)
24 +
}
25 +
26 +
/// Decode an object from a vector.
27 +
pub fn deserialize<T: Decode>(data: &[u8]) -> Result<T, io::Error> {
28 +
    let mut cursor = io::Cursor::new(data);
29 +
    let obj = T::decode(&mut cursor)?;
30 +
31 +
    if cursor.position() as usize != cursor.get_ref().len() {
32 +
        return Err(io::ErrorKind::InvalidData.into());
33 +
    }
34 +
    Ok(obj)
35 +
}
36 +
37 +
impl Encode for &[u8] {
38 +
    fn encode<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error> {
39 +
        writer.write_all(self)?;
40 +
        Ok(mem::size_of_val(*self))
41 +
    }
42 +
}
43 +
44 +
impl<const N: usize> Encode for [u8; N] {
45 +
    fn encode<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error> {
46 +
        writer.write_all(self.as_slice())?;
47 +
        Ok(mem::size_of::<Self>())
48 +
    }
49 +
}
50 +
51 +
impl<const N: usize> Decode for [u8; N] {
52 +
    fn decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> {
53 +
        let mut array = [0; N];
54 +
        reader.read_exact(&mut array)?;
55 +
        Ok(array)
56 +
    }
57 +
}
58 +
59 +
impl Encode for u8 {
60 +
    fn encode<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error> {
61 +
        writer.write_all(&[*self])?;
62 +
        Ok(mem::size_of::<Self>())
63 +
    }
64 +
}
65 +
66 +
impl Encode for u16 {
67 +
    fn encode<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error> {
68 +
        writer.write_all(&self.to_be_bytes())?;
69 +
        Ok(mem::size_of::<Self>())
70 +
    }
71 +
}
72 +
73 +
impl Encode for u32 {
74 +
    fn encode<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error> {
75 +
        writer.write_all(&self.to_be_bytes())?;
76 +
        Ok(mem::size_of::<Self>())
77 +
    }
78 +
}
79 +
80 +
impl Encode for u64 {
81 +
    fn encode<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error> {
82 +
        writer.write_all(&self.to_be_bytes())?;
83 +
        Ok(mem::size_of::<Self>())
84 +
    }
85 +
}
86 +
87 +
impl Encode for f64 {
88 +
    fn encode<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error> {
89 +
        writer.write_all(&self.to_be_bytes())?;
90 +
        Ok(mem::size_of::<Self>())
91 +
    }
92 +
}
93 +
94 +
impl Encode for f32 {
95 +
    fn encode<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error> {
96 +
        writer.write_all(&self.to_be_bytes())?;
97 +
        Ok(mem::size_of::<Self>())
98 +
    }
99 +
}
100 +
101 +
impl Decode for u8 {
102 +
    fn decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> {
103 +
        let buf: [u8; 1] = Decode::decode(reader)?;
104 +
        Ok(u8::from_be_bytes(buf))
105 +
    }
106 +
}
107 +
108 +
impl Decode for u16 {
109 +
    fn decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> {
110 +
        let buf: [u8; 2] = Decode::decode(reader)?;
111 +
        Ok(u16::from_be_bytes(buf))
112 +
    }
113 +
}
114 +
115 +
impl Decode for u32 {
116 +
    fn decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> {
117 +
        let buf: [u8; 4] = Decode::decode(reader)?;
118 +
        Ok(u32::from_be_bytes(buf))
119 +
    }
120 +
}
121 +
122 +
impl Decode for u64 {
123 +
    fn decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> {
124 +
        let buf: [u8; 8] = Decode::decode(reader)?;
125 +
        Ok(u64::from_be_bytes(buf))
126 +
    }
127 +
}
128 +
129 +
impl Decode for f32 {
130 +
    fn decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> {
131 +
        let buf: [u8; 4] = Decode::decode(reader)?;
132 +
        Ok(f32::from_be_bytes(buf))
133 +
    }
134 +
}
135 +
136 +
impl Decode for f64 {
137 +
    fn decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> {
138 +
        let buf: [u8; 8] = Decode::decode(reader)?;
139 +
        Ok(f64::from_be_bytes(buf))
140 +
    }
141 +
}
142 +
143 +
impl Encode for crate::gfx::Rgba8 {
144 +
    fn encode<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error> {
145 +
        writer.write_all(&[self.r, self.g, self.b, self.a])?;
146 +
        Ok(mem::size_of::<Self>())
147 +
    }
148 +
}
149 +
150 +
impl Decode for crate::gfx::Rgba8 {
151 +
    fn decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> {
152 +
        let buf: [u8; 4] = Decode::decode(reader)?;
153 +
        Ok(crate::gfx::Rgba8::new(buf[0], buf[1], buf[2], buf[3]))
154 +
    }
155 +
}
156 +
157 +
impl<S: Encode> Encode for crate::gfx::Rgba<S> {
158 +
    fn encode<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error> {
159 +
        self.r.encode(writer)?;
160 +
        self.g.encode(writer)?;
161 +
        self.b.encode(writer)?;
162 +
        self.a.encode(writer)?;
163 +
164 +
        Ok(mem::size_of::<Self>())
165 +
    }
166 +
}
167 +
168 +
impl<S: Decode> Decode for crate::gfx::Rgba<S> {
169 +
    fn decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> {
170 +
        let r: S = S::decode(reader)?;
171 +
        let g: S = S::decode(reader)?;
172 +
        let b: S = S::decode(reader)?;
173 +
        let a: S = S::decode(reader)?;
174 +
175 +
        Ok(crate::gfx::Rgba::new(r, g, b, a))
176 +
    }
177 +
}
178 +
179 +
impl<S: Encode> Encode for crate::math::Vector2D<S> {
180 +
    fn encode<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error> {
181 +
        self.x.encode(writer)?;
182 +
        self.y.encode(writer)?;
183 +
184 +
        Ok(mem::size_of::<Self>())
185 +
    }
186 +
}
187 +
188 +
impl<S: Decode> Decode for crate::math::Vector2D<S> {
189 +
    fn decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> {
190 +
        let x: S = S::decode(reader)?;
191 +
        let y: S = S::decode(reader)?;
192 +
193 +
        Ok(crate::math::Vector2D::new(x, y))
194 +
    }
195 +
}
196 +
197 +
impl<S: Encode> Encode for crate::math::Vector3D<S> {
198 +
    fn encode<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error> {
199 +
        self.x.encode(writer)?;
200 +
        self.y.encode(writer)?;
201 +
        self.z.encode(writer)?;
202 +
203 +
        Ok(mem::size_of::<Self>())
204 +
    }
205 +
}
206 +
207 +
impl<S: Decode> Decode for crate::math::Vector3D<S> {
208 +
    fn decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> {
209 +
        let x: S = S::decode(reader)?;
210 +
        let y: S = S::decode(reader)?;
211 +
        let z: S = S::decode(reader)?;
212 +
213 +
        Ok(crate::math::Vector3D::new(x, y, z))
214 +
    }
215 +
}
216 +
217 +
impl<S: Encode> Encode for crate::math::Vector4D<S> {
218 +
    fn encode<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error> {
219 +
        self.x.encode(writer)?;
220 +
        self.y.encode(writer)?;
221 +
        self.z.encode(writer)?;
222 +
        self.w.encode(writer)?;
223 +
224 +
        Ok(mem::size_of::<Self>())
225 +
    }
226 +
}
227 +
228 +
impl<S: Decode> Decode for crate::math::Vector4D<S> {
229 +
    fn decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> {
230 +
        let x: S = S::decode(reader)?;
231 +
        let y: S = S::decode(reader)?;
232 +
        let z: S = S::decode(reader)?;
233 +
        let w: S = S::decode(reader)?;
234 +
235 +
        Ok(crate::math::Vector4D::new(x, y, z, w))
236 +
    }
237 +
}
238 +
239 +
impl<S: Encode> Encode for crate::math::Point2D<S> {
240 +
    fn encode<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error> {
241 +
        self.x.encode(writer)?;
242 +
        self.y.encode(writer)?;
243 +
244 +
        Ok(mem::size_of::<Self>())
245 +
    }
246 +
}
247 +
248 +
impl<S: Decode> Decode for crate::math::Point2D<S> {
249 +
    fn decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> {
250 +
        let x: S = S::decode(reader)?;
251 +
        let y: S = S::decode(reader)?;
252 +
253 +
        Ok(crate::math::Point2D::new(x, y))
254 +
    }
255 +
}
ombre/src/bytes/rle.rs added +90 -0
1 +
//! Run-length encoding (RLE).
2 +
3 +
#[derive(Debug)]
4 +
pub enum Error {
5 +
    /// Supplied chunk size doesn't match input data.
6 +
    InvalidChunkSize,
7 +
}
8 +
9 +
/// Encode (compress) data in RLE format.
10 +
pub fn encode(input: &[u8], cs: usize) -> Result<Vec<u8>, Error> {
11 +
    if input.len() % cs != 0 {
12 +
        return Err(Error::InvalidChunkSize);
13 +
    }
14 +
    let mut compressed: Vec<u8> = Vec::new();
15 +
    let mut iter = input.chunks_exact(cs).peekable();
16 +
17 +
    while let Some(chunk) = iter.next() {
18 +
        let mut count = 1u8;
19 +
20 +
        while iter.peek() == Some(&chunk) && count < u8::MAX {
21 +
            count += 1;
22 +
            iter.next();
23 +
        }
24 +
        compressed.extend_from_slice(chunk);
25 +
        compressed.push(count);
26 +
    }
27 +
    Ok(compressed)
28 +
}
29 +
30 +
/// Decode (decompress) data from RLE format.
31 +
pub fn decode(input: &[u8], cs: usize) -> Result<Vec<u8>, Error> {
32 +
    if input.len() % (cs + 1) != 0 {
33 +
        return Err(Error::InvalidChunkSize);
34 +
    }
35 +
    let mut decompressed: Vec<u8> = Vec::new();
36 +
37 +
    for chunk in input.chunks_exact(cs + 1) {
38 +
        let data = &chunk[..cs];
39 +
        let count = chunk[cs];
40 +
41 +
        for _ in 0..count {
42 +
            decompressed.extend_from_slice(data);
43 +
        }
44 +
    }
45 +
    Ok(decompressed)
46 +
}
47 +
48 +
#[cfg(test)]
49 +
#[allow(clippy::unwrap_used)]
50 +
mod tests {
51 +
    use super::*;
52 +
53 +
    #[test]
54 +
    fn test_rle() {
55 +
        let input: Vec<u8> = vec![1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 7, 8];
56 +
57 +
        let compressed = encode(&input, 1).unwrap();
58 +
        let decompressed = decode(&compressed, 1).unwrap();
59 +
60 +
        assert_eq!(input, decompressed);
61 +
62 +
        let compressed = encode(&input, 2).unwrap();
63 +
        let decompressed = decode(&compressed, 2).unwrap();
64 +
65 +
        assert_eq!(input, decompressed);
66 +
67 +
        let compressed = encode(&input, 4).unwrap();
68 +
        let decompressed = decode(&compressed, 4).unwrap();
69 +
70 +
        assert_eq!(input, decompressed);
71 +
        assert_eq!(compressed, vec![1, 2, 3, 4, 3, 5, 6, 7, 8, 1]);
72 +
    }
73 +
74 +
    #[test]
75 +
    fn test_rle_limits() {
76 +
        let input: Vec<u8> = vec![9; 512];
77 +
78 +
        let compressed = encode(&input, 1).unwrap();
79 +
        let decompressed = decode(&compressed, 1).unwrap();
80 +
81 +
        assert_eq!(input, decompressed);
82 +
        assert_eq!(compressed, vec![9, 255, 9, 255, 9, 2]);
83 +
84 +
        let compressed = encode(&input, 2).unwrap();
85 +
        let decompressed = decode(&compressed, 2).unwrap();
86 +
87 +
        assert_eq!(input, decompressed);
88 +
        assert_eq!(compressed, vec![9, 9, 255, 9, 9, 1]);
89 +
    }
90 +
}
ombre/src/collections.rs added +69 -0
1 +
//! Data containers used throughout the crate.
2 +
3 +
/// Hashet state used for collections.
4 +
pub type RandomState = std::hash::BuildHasherDefault<IntHasher>;
5 +
/// An integer map.
6 +
pub type IntMap<K, V> = std::collections::HashMap<K, V, RandomState>;
7 +
/// An integer set.
8 +
pub type IntSet<K> = std::collections::HashSet<K, RandomState>;
9 +
10 +
/// Collection types.
11 +
pub mod int_map {
12 +
    pub use std::collections::hash_map::*;
13 +
}
14 +
15 +
/// Integer hasher that doesn't do any hashing.
16 +
#[derive(Default, Copy, Clone)]
17 +
pub struct IntHasher {
18 +
    data: u64,
19 +
}
20 +
21 +
impl std::hash::Hasher for IntHasher {
22 +
    fn write(&mut self, _bytes: &[u8]) {
23 +
        panic!("IntHasher::write: invalid use: only integers are supported");
24 +
    }
25 +
26 +
    fn write_u8(&mut self, n: u8) {
27 +
        self.data = u64::from(n)
28 +
    }
29 +
30 +
    fn write_u16(&mut self, n: u16) {
31 +
        self.data = u64::from(n)
32 +
    }
33 +
34 +
    fn write_u32(&mut self, n: u32) {
35 +
        self.data = u64::from(n)
36 +
    }
37 +
38 +
    fn write_u64(&mut self, n: u64) {
39 +
        self.data = n
40 +
    }
41 +
42 +
    fn write_usize(&mut self, n: usize) {
43 +
        self.data = n as u64
44 +
    }
45 +
46 +
    fn write_i8(&mut self, n: i8) {
47 +
        self.data = n as u64
48 +
    }
49 +
50 +
    fn write_i16(&mut self, n: i16) {
51 +
        self.data = n as u64
52 +
    }
53 +
54 +
    fn write_i32(&mut self, n: i32) {
55 +
        self.data = n as u64
56 +
    }
57 +
58 +
    fn write_i64(&mut self, n: i64) {
59 +
        self.data = n as u64
60 +
    }
61 +
62 +
    fn write_isize(&mut self, n: isize) {
63 +
        self.data = n as u64
64 +
    }
65 +
66 +
    fn finish(&self) -> u64 {
67 +
        self.data
68 +
    }
69 +
}
ombre/src/derive.rs added +127 -0
1 +
pub use ombre_derive::*;
2 +
3 +
#[cfg(test)]
4 +
mod tests {
5 +
    use super::*;
6 +
    use crate::bytes::Packed;
7 +
    use crate::gfx;
8 +
    use crate::gfx::UniformBlock as _;
9 +
    use crate::lenses::Lens;
10 +
    use crate::prelude::*;
11 +
12 +
    #[derive(Lenses)]
13 +
    struct Fnord {
14 +
        #[lens]
15 +
        name: String,
16 +
        #[lens]
17 +
        number: i32,
18 +
        #[allow(dead_code)]
19 +
        dead: bool, // This field should not have a lens.
20 +
    }
21 +
22 +
    #[test]
23 +
    fn test_lens_derive() {
24 +
        let mut obj = Fnord {
25 +
            name: "Hello".to_string(),
26 +
            number: 42,
27 +
            dead: true,
28 +
        };
29 +
30 +
        Fnord::name.with(&obj, |value| {
31 +
            assert_eq!(value, "Hello");
32 +
        });
33 +
        Fnord::number.with(&obj, |value| {
34 +
            assert_eq!(*value, 42);
35 +
        });
36 +
        Fnord::name.with_mut(&mut obj, |value| {
37 +
            *value = "World".to_string();
38 +
        });
39 +
        Fnord::number.with_mut(&mut obj, |value| {
40 +
            *value += 1;
41 +
        });
42 +
43 +
        // Verify modifications.
44 +
        assert_eq!(obj.name, "World");
45 +
        assert_eq!(obj.number, 43);
46 +
    }
47 +
48 +
    #[derive(UniformBlock)]
49 +
    #[allow(dead_code)]
50 +
    struct TestUniforms {
51 +
        projection: [[f32; 4]; 4],
52 +
        color: gfx::Rgba<f32>,
53 +
        position: Vector3D<f32>,
54 +
        scale: f32,
55 +
        setting: u32,
56 +
    }
57 +
58 +
    #[test]
59 +
    fn test_uniform_layout() {
60 +
        let layout = TestUniforms::layout();
61 +
62 +
        assert_eq!(layout.uniforms.len(), 5);
63 +
64 +
        assert_eq!(layout.uniforms[0].name, "projection");
65 +
        assert_eq!(layout.uniforms[0].kind, UniformKind::Mat4);
66 +
67 +
        assert_eq!(layout.uniforms[1].name, "color");
68 +
        assert_eq!(layout.uniforms[1].kind, UniformKind::Float4);
69 +
70 +
        assert_eq!(layout.uniforms[2].name, "position");
71 +
        assert_eq!(layout.uniforms[2].kind, UniformKind::Float3);
72 +
73 +
        assert_eq!(layout.uniforms[3].name, "scale");
74 +
        assert_eq!(layout.uniforms[3].kind, UniformKind::Float1);
75 +
76 +
        assert_eq!(layout.uniforms[4].name, "setting");
77 +
        assert_eq!(layout.uniforms[4].kind, UniformKind::UInt1);
78 +
    }
79 +
80 +
    #[test]
81 +
    fn test_vertex_attributes() {
82 +
        #[allow(dead_code)]
83 +
        #[derive(VertexAttributes)]
84 +
        struct TestVertex {
85 +
            position: Vector3D<f32>,
86 +
            #[attrib(name = "vertexColor")]
87 +
            color: Vector4D<f32>,
88 +
            #[attrib(name = "texCoord")]
89 +
            uv: Vector2D<f32>,
90 +
        }
91 +
92 +
        let attrs = TestVertex::attributes();
93 +
        assert_eq!(attrs.len(), 3);
94 +
95 +
        assert_eq!(attrs[0].name, "position");
96 +
        assert_eq!(attrs[0].format, VertexFormat::Float3);
97 +
98 +
        assert_eq!(attrs[1].name, "vertexColor");
99 +
        assert_eq!(attrs[1].format, VertexFormat::Float4);
100 +
101 +
        assert_eq!(attrs[2].name, "texCoord");
102 +
        assert_eq!(attrs[2].format, VertexFormat::Float2);
103 +
    }
104 +
105 +
    #[test]
106 +
    // Test compilation is sufficient as the derive macro
107 +
    // will fail to compile if bounds aren't satisfied.
108 +
    fn test_packed_derive() {
109 +
        #[derive(Packed)]
110 +
        struct Test<T: Packed> {
111 +
            #[allow(dead_code)]
112 +
            x: u32,
113 +
            #[allow(dead_code)]
114 +
            y: T,
115 +
        }
116 +
117 +
        #[derive(Packed)]
118 +
        #[allow(dead_code)]
119 +
        struct Wrapper(u64);
120 +
121 +
        let _ = Wrapper;
122 +
        let _ = Test {
123 +
            x: 1,
124 +
            y: Wrapper(42),
125 +
        };
126 +
    }
127 +
}
ombre/src/draw.rs added +5 -0
1 +
pub mod batch;
2 +
pub mod blit;
3 +
pub mod pipeline;
4 +
pub mod shape;
5 +
pub mod traits;
ombre/src/draw/batch.rs added +91 -0
1 +
use crate::draw::{blit::Blit, pipeline::Vertex, shape::Shape};
2 +
use crate::gfx::TextureId;
3 +
use crate::math::*;
4 +
5 +
use super::traits::Brush;
6 +
7 +
/// Information about a texture used in a render batch.
8 +
///
9 +
/// Contains the metadata needed to properly render a texture.
10 +
/// This information is shared across all sprites in a batch that use
11 +
/// the same source texture.
12 +
#[derive(Debug, Clone, PartialEq, Eq)]
13 +
pub struct TextureInfo {
14 +
    /// Texture ID for binding the correct texture.
15 +
    pub id: TextureId,
16 +
    /// Dimensions in pixels for calculating proper UV coordinates and scaling.
17 +
    pub size: Size<u32>,
18 +
}
19 +
20 +
/// Vertex render batch.
21 +
/// Represents a list of vertices that is associated with a texture and
22 +
/// can be rendered in one draw call.
23 +
#[derive(Debug)]
24 +
pub struct VertexBatch {
25 +
    /// The texture array we are using as source for blitting.
26 +
    pub texture: TextureInfo,
27 +
    /// Vertices to render.
28 +
    vertices: Vec<Vertex>,
29 +
}
30 +
31 +
impl VertexBatch {
32 +
    /// Creates a new empty vertex batch for collecting vertices to render.
33 +
    ///
34 +
    /// The batch can be populated with shapes and blits that share the same texture.
35 +
    /// All vertices in a batch will be rendered in a single draw call for efficiency.
36 +
    pub fn new(texture: TextureInfo) -> Self {
37 +
        Self {
38 +
            vertices: Vec::new(),
39 +
            texture,
40 +
        }
41 +
    }
42 +
43 +
    /// Fill a shape into the batch.
44 +
    pub fn fill(&mut self, shape: impl Shape, brush: impl Into<Brush>) -> &mut Self {
45 +
        self.vertices.extend(shape.fill(brush));
46 +
        self
47 +
    }
48 +
49 +
    /// Stroke a shape into the batch.
50 +
    pub fn stroke(&mut self, shape: impl Shape, brush: impl Into<Brush>, width: f32) -> &mut Self {
51 +
        self.vertices.extend(shape.stroke(brush, width));
52 +
        self
53 +
    }
54 +
55 +
    /// Add a sprite blit to the batch.
56 +
    pub fn blit(&mut self, blit: Blit<Screen>, layer: u8) -> &mut Self {
57 +
        self.vertices.extend(blit.vertices(&self.texture, layer));
58 +
        self
59 +
    }
60 +
61 +
    /// Takes ownership of and returns the batch's vertices, leaving an empty vector in its place.
62 +
    /// This is used when submitting the batch for rendering.
63 +
    pub fn vertices(&mut self) -> Box<[Vertex]> {
64 +
        std::mem::take(&mut self.vertices).into_boxed_slice()
65 +
    }
66 +
}
67 +
68 +
#[cfg(test)]
69 +
mod test {
70 +
    use super::*;
71 +
    use crate::ui::gfx::{Color, Rgba, TextureId};
72 +
73 +
    #[test]
74 +
    fn test() {
75 +
        let mut batch = VertexBatch::new(TextureInfo {
76 +
            id: TextureId::next(),
77 +
            size: Size::new(32, 32),
78 +
        });
79 +
        batch.blit(
80 +
            Blit::new(
81 +
                Rect::origin(Size::new(32., 32.)),
82 +
                Rect::new(Point2D::new(32., 32.), Size::new(64., 64.)),
83 +
            )
84 +
            .tint(Rgba::BLACK)
85 +
            .opacity(0.5)
86 +
            .zdepth(0.1)
87 +
            .repeat(8., 8.),
88 +
            0,
89 +
        );
90 +
    }
91 +
}
ombre/src/draw/blit.rs added +141 -0
1 +
//! Blitting.
2 +
//! Renders a portion of a texture onto a portion of the screen.
3 +
use crate::gfx::{Rgb, Rgba};
4 +
use crate::math::rect::{Box2D, Rect};
5 +
use crate::math::*;
6 +
7 +
use super::batch::TextureInfo;
8 +
use super::pipeline::Vertex;
9 +
10 +
/// Constructs a vertex with the given position, texture coordinates and color attributes.
11 +
/// Used internally to generate vertices for sprite blitting.
12 +
const fn vertex(
13 +
    x: f32,
14 +
    y: f32,
15 +
    z: f32,
16 +
    u: f32,
17 +
    v: f32,
18 +
    tint: Rgb<f32>,
19 +
    opacity: f32,
20 +
    mix: f32,
21 +
    texture: u8,
22 +
) -> Vertex {
23 +
    Vertex {
24 +
        position: Vector3D::new(x, y, z),
25 +
        center: Vector2D::ZERO,
26 +
        rotation: 0.,
27 +
        uv: Vector2D::new(u, v),
28 +
        color: Rgba::new(tint.r, tint.g, tint.b, opacity),
29 +
        mix,
30 +
        texture: texture as f32,
31 +
    }
32 +
}
33 +
34 +
/// Specifies how to render a portion of a texture to the screen.
35 +
/// Controls source/destination rectangles, color tinting, opacity and other
36 +
/// rendering parameters.
37 +
#[derive(Clone, Debug, PartialEq)]
38 +
pub struct Blit<U> {
39 +
    /// Source (texture) rectangle.
40 +
    pub src: Rect<f32, Screen>,
41 +
    /// Destination rectangle.
42 +
    pub dst: Rect<f32, U>,
43 +
    /// Z-depth to render at.
44 +
    pub zdepth: ZDepth,
45 +
    /// Tint color.
46 +
    pub tint: Rgb<f32>,
47 +
    /// Tint mix strength.
48 +
    pub mix: f32,
49 +
    /// Transparency.
50 +
    pub opacity: f32,
51 +
    /// Texture repeat.
52 +
    pub repeat: Repeat,
53 +
}
54 +
55 +
impl<U: Default> Blit<U> {
56 +
    /// Create a new blit.
57 +
    pub fn new(src: Rect<f32, Screen>, dst: Rect<f32, U>) -> Self {
58 +
        Self {
59 +
            src,
60 +
            dst,
61 +
            opacity: 1.,
62 +
            zdepth: ZDepth::default(),
63 +
            tint: Rgb::default(),
64 +
            mix: 0.,
65 +
            repeat: Repeat::default(),
66 +
        }
67 +
    }
68 +
69 +
    /// Set the tint.
70 +
    pub fn tint<T: Into<Rgba<f32>>>(mut self, tint: T) -> Self {
71 +
        let tint = tint.into();
72 +
73 +
        self.tint = Rgb::new(tint.r, tint.g, tint.b);
74 +
        self.mix = tint.a;
75 +
        self
76 +
    }
77 +
78 +
    /// Set the opacity.
79 +
    pub fn opacity(mut self, opacity: f32) -> Self {
80 +
        self.opacity = opacity;
81 +
        self
82 +
    }
83 +
84 +
    /// Set the z-depth.
85 +
    pub fn zdepth<T: Into<ZDepth>>(mut self, zdepth: T) -> Self {
86 +
        self.zdepth = zdepth.into();
87 +
        self
88 +
    }
89 +
90 +
    /// Set the tetxure repeat.
91 +
    pub fn repeat(mut self, x: f32, y: f32) -> Self {
92 +
        self.repeat = Repeat::new(x, y);
93 +
        self
94 +
    }
95 +
96 +
    /// Transform this image's destination rectangle.
97 +
    pub fn transform<V>(self, t: Transform2D<U, V>) -> Blit<V> {
98 +
        Blit {
99 +
            src: self.src,
100 +
            dst: self.dst.transform(t),
101 +
            zdepth: self.zdepth,
102 +
            tint: self.tint,
103 +
            mix: self.mix,
104 +
            opacity: self.opacity,
105 +
            repeat: self.repeat,
106 +
        }
107 +
    }
108 +
109 +
    /// Get the vertices for this [`Blit`].
110 +
    #[rustfmt::skip]
111 +
    pub fn vertices(self, texture: &TextureInfo, layer: u8) -> [Vertex; 6] {
112 +
        let Blit {
113 +
            src,
114 +
            dst,
115 +
            zdepth,
116 +
            tint: t,
117 +
            mix,
118 +
            opacity: o,
119 +
            repeat: re,
120 +
        } = self;
121 +
122 +
        let src = Box2D::from(src);
123 +
        let dst = Box2D::from(dst);
124 +
        let z = *zdepth;
125 +
126 +
        // Relative texture coordinates
127 +
        let rx1: f32 = src.min.x / texture.size.w as f32;
128 +
        let ry1: f32 = src.min.y / texture.size.h as f32;
129 +
        let rx2: f32 = src.max.x / texture.size.w as f32;
130 +
        let ry2: f32 = src.max.y / texture.size.h as f32;
131 +
132 +
        [
133 +
            vertex(dst.min.x, dst.min.y, z, rx1 * re.x, ry1 * re.y, t, o, mix, layer),
134 +
            vertex(dst.max.x, dst.max.y, z, rx2 * re.x, ry2 * re.y, t, o, mix, layer),
135 +
            vertex(dst.max.x, dst.min.y, z, rx2 * re.x, ry1 * re.y, t, o, mix, layer),
136 +
            vertex(dst.min.x, dst.min.y, z, rx1 * re.x, ry1 * re.y, t, o, mix, layer),
137 +
            vertex(dst.max.x, dst.max.y, z, rx2 * re.x, ry2 * re.y, t, o, mix, layer),
138 +
            vertex(dst.min.x, dst.max.y, z, rx1 * re.x, ry2 * re.y, t, o, mix, layer),
139 +
        ]
140 +
    }
141 +
}
ombre/src/draw/pipeline.rs added +120 -0
1 +
//! Pipeline for rendering sprites and shapes.
2 +
//!
3 +
//! This module provides the core rendering pipeline implementation for 2D graphics.
4 +
//! It handles vertex attribute management, shader uniforms, and the overall rendering
5 +
//! state needed to efficiently draw sprites and shapes with proper blending,
6 +
//! transformations, and depth testing.
7 +
8 +
use ombre_derive::UniformBlock;
9 +
10 +
use crate::derive::VertexAttributes;
11 +
use crate::gfx;
12 +
use crate::gfx::*;
13 +
use crate::math::{Origin, Size, Transform3D};
14 +
15 +
/// A vertex in the rendering pipeline.
16 +
/// Contains all the attributes needed for rendering sprites and shapes.
17 +
#[repr(C)]
18 +
#[derive(Copy, Clone, Debug, VertexAttributes)]
19 +
pub struct Vertex {
20 +
    ///  3D vertex position in world space.
21 +
    pub position: Vector3D<f32>,
22 +
    /// Center of rotation.
23 +
    pub center: Vector2D<f32>,
24 +
    /// Angle of rotation around center.
25 +
    #[attrib(name = "angle")]
26 +
    pub rotation: f32,
27 +
    /// UV coordinate.
28 +
    pub uv: Vector2D<f32>,
29 +
    /// Vertex color for tinting.
30 +
    pub color: Rgba<f32>,
31 +
    /// Mix factor for blending between texture and vertex color.
32 +
    #[attrib(name = "colorMix")]
33 +
    pub mix: f32,
34 +
    /// Texture layer index to use.
35 +
    #[attrib(name = "textureLayer")]
36 +
    pub texture: f32,
37 +
}
38 +
39 +
/// Creates a new rendering pipeline for sprites and shapes.
40 +
///
41 +
/// Sets up the shader programs and pipeline state for rendering
42 +
/// textured and colored vertices.
43 +
pub fn create<T: gfx::RenderBackend, const N: usize>(
44 +
    backend: &mut T,
45 +
) -> Result<gfx::PipelineId, T::Error> {
46 +
    let shader = backend.shader(
47 +
        gfx::ShaderSource {
48 +
            vertex: include_str!("shaders/vertex.glsl"),
49 +
            fragment: include_str!("shaders/fragment.glsl"),
50 +
            geometry: None,
51 +
        },
52 +
        ShaderDescriptor {
53 +
            textures: &["textures"],
54 +
            uniforms: Uniforms::<N>::layout(),
55 +
        },
56 +
    )?;
57 +
58 +
    backend.pipeline(
59 +
        shader,
60 +
        gfx::PipelineDescriptor {
61 +
            layout: &[gfx::BufferLayout {
62 +
                stride: Some(std::mem::size_of::<Vertex>()),
63 +
                attrs: Vertex::attributes(),
64 +
                ..gfx::BufferLayout::default()
65 +
            }],
66 +
            color: Some(gfx::ColorState {
67 +
                mask: Rgba::new(true, true, true, true),
68 +
                blend: BlendState {
69 +
                    rgb: Some(gfx::BlendEquation {
70 +
                        op: BlendOp::Add,
71 +
                        sfactor: BlendFactor::Value(BlendValue::SourceAlpha),
72 +
                        dfactor: BlendFactor::OneMinusValue(BlendValue::SourceAlpha),
73 +
                    }),
74 +
                    alpha: Some(gfx::BlendEquation {
75 +
                        op: BlendOp::Add,
76 +
                        sfactor: BlendFactor::Value(BlendValue::SourceAlpha),
77 +
                        dfactor: BlendFactor::Value(BlendValue::DestinationAlpha),
78 +
                    }),
79 +
                },
80 +
            }),
81 +
            depth: Some(gfx::DepthState {
82 +
                compare: gfx::Comparison::LessOrEqual,
83 +
                offset: None,
84 +
            }),
85 +
            ..gfx::PipelineDescriptor::default()
86 +
        },
87 +
    )
88 +
}
89 +
90 +
/// Uniform block for the sprite shader pipeline.
91 +
/// Contains transformation matrices and texture array information.
92 +
#[repr(C)]
93 +
#[derive(UniformBlock)]
94 +
pub struct Uniforms<const N: usize> {
95 +
    /// Orthographic transform.
96 +
    pub ortho: Transform3D,
97 +
    /// Local transform.
98 +
    pub transform: Transform3D,
99 +
    #[uniform(name = "imageSizes")]
100 +
    pub images: [Size<u32>; N],
101 +
}
102 +
103 +
impl<const N: usize> Uniforms<N> {
104 +
    /// Creates a new uniform block for the sprite shader pipeline.
105 +
    ///
106 +
    /// * `viewport` - The size of the viewport to create the orthographic projection for
107 +
    /// * `transform` - The local transform to apply to vertices
108 +
    /// * `images` - Array of texture sizes used for UV coordinate calculations
109 +
    pub fn new(
110 +
        viewport: impl Into<Size<f32>>,
111 +
        transform: Transform3D,
112 +
        images: [Size<u32>; N],
113 +
    ) -> Self {
114 +
        Self {
115 +
            ortho: Transform3D::ortho(viewport.into(), Origin::default()),
116 +
            transform,
117 +
            images,
118 +
        }
119 +
    }
120 +
}
ombre/src/draw/shaders/fragment.glsl added +29 -0
1 +
#version 330 core
2 +
3 +
uniform sampler2DArray textures;
4 +
uniform uvec2 imageSizes[16];
5 +
6 +
in  vec2  vertexUV;
7 +
in  vec4  vertexColor;
8 +
in  float vertexColorMix;
9 +
in  float vertexTextureLayer;
10 +
11 +
out vec4  fragColor;
12 +
13 +
// Main fragment shader entry point.
14 +
// Samples the texture array using corrected UV coordinates,
15 +
// then blends the sampled texel with the vertex color using the mix factor.
16 +
// The alpha channel is handled separately to maintain proper transparency.
17 +
void main() {
18 +
	vec2 scale = textureSize(textures, 0).xy / vec2(imageSizes[uint(vertexTextureLayer)]);
19 +
	vec2 imageUV = vec2(
20 +
		fract(vertexUV.x * scale.x) / scale.x,
21 +
		fract(vertexUV.y * scale.y) / scale.y
22 +
	);
23 +
	vec4 texel = texture(textures, vec3(imageUV, vertexTextureLayer));
24 +
25 +
	fragColor = vec4(
26 +
		mix(texel.rgb, vertexColor.rgb, vertexColorMix),
27 +
		texel.a * vertexColor.a
28 +
	);
29 +
}
ombre/src/draw/shaders/vertex.glsl added +66 -0
1 +
#version 330 core
2 +
3 +
uniform mat4 ortho;
4 +
uniform mat4 transform;
5 +
6 +
in vec3  position;
7 +
in vec2  center;
8 +
in float angle;
9 +
in vec2  uv;
10 +
in vec4  color;
11 +
in float colorMix;
12 +
in float textureLayer;
13 +
14 +
out vec2  vertexUV;
15 +
out vec4  vertexColor;
16 +
out float vertexColorMix;
17 +
out float vertexTextureLayer;
18 +
19 +
// Creates a 2D rotation matrix for the given angle in radians.
20 +
//
21 +
// The matrix is constructed using sine and cosine of the angle to create
22 +
// a standard 2D rotation transformation matrix:
23 +
// [cos θ  -sin θ]
24 +
// [sin θ   cos θ]
25 +
//
26 +
// This allows rotating vertices around the origin by multiplying with this matrix.
27 +
mat2 rotation2d(float angle) {
28 +
	float s = sin(angle);
29 +
	float c = cos(angle);
30 +
	return mat2(c, -s, s, c);
31 +
}
32 +
33 +
// Rotates a 2D point around a pivot point by the given angle in radians.
34 +
//
35 +
// The rotation is performed in these steps:
36 +
// 1. Translate point to origin relative to pivot point (position - around)
37 +
// 2. Apply rotation matrix multiplication (m * translated)
38 +
// 3. Translate back to original space (rotated + around)
39 +
//
40 +
// This allows rotating any point around an arbitrary pivot point rather than just the origin.
41 +
vec2 rotate(vec2 position, vec2 around, float angle) {
42 +
	mat2 m = rotation2d(angle);
43 +
	vec2 rotated = m * (position - around);
44 +
	return rotated + around;
45 +
}
46 +
47 +
// Convert an sRGB color to linear space by applying the standard sRGB transfer function.
48 +
// This ensures correct color blending in the linear color space used by the GPU.
49 +
vec3 linearize(vec3 srgb) {
50 +
	bvec3 cutoff = lessThan(srgb, vec3(0.04045));
51 +
	vec3 higher = pow((srgb + vec3(0.055)) / vec3(1.055), vec3(2.4));
52 +
	vec3 lower = srgb / vec3(12.92);
53 +
54 +
	return mix(higher, lower, cutoff);
55 +
}
56 +
57 +
void main() {
58 +
	vec2 rotated = rotate(position.xy, center, angle);
59 +
60 +
	vertexUV = uv;
61 +
	vertexColor = vec4(linearize(color.rgb), color.a);
62 +
	vertexColorMix = colorMix;
63 +
	vertexTextureLayer = textureLayer;
64 +
65 +
	gl_Position = ortho * transform * vec4(rotated, position.z, 1.0);
66 +
}
ombre/src/draw/shape.rs added +421 -0
1 +
//! Shape rendering.
2 +
use std::f32;
3 +
use std::fmt;
4 +
5 +
use crate::gfx::Rgba;
6 +
use crate::math::rect::{Box2D, Rect};
7 +
use crate::math::*;
8 +
9 +
use super::pipeline::Vertex;
10 +
use super::traits::Brush;
11 +
12 +
/// Creates a vertex with the given position, rotation and color attributes.
13 +
#[inline]
14 +
const fn vertex(
15 +
    x: f32,
16 +
    y: f32,
17 +
    z: f32,
18 +
    angle: f32,
19 +
    center: Point2D<f32>,
20 +
    color: Rgba<f32>,
21 +
) -> Vertex {
22 +
    Vertex {
23 +
        position: Vector3D::new(x, y, z),
24 +
        rotation: angle,
25 +
        center: Vector2D::new(center.x, center.y),
26 +
        uv: Vector2D::ZERO,
27 +
        color,
28 +
        mix: 1.,
29 +
        texture: 0., // Layer `0` is the blank texture.
30 +
    }
31 +
}
32 +
33 +
/// Controls how a texture is repeated when rendered.
34 +
#[derive(Copy, Clone, Debug, Default)]
35 +
pub struct Repeat {
36 +
    /// Horizontal repeat factor.
37 +
    pub x: f32,
38 +
    /// Vertical repeat factor.
39 +
    pub y: f32,
40 +
}
41 +
42 +
impl Repeat {
43 +
    /// Creates a new repeat configuration.
44 +
    /// * `x` - Number of times to repeat horizontally
45 +
    /// * `y` - Number of times to repeat vertically
46 +
    pub fn new(x: f32, y: f32) -> Self {
47 +
        Self { x, y }
48 +
    }
49 +
}
50 +
51 +
/// Defines rotation of a shape around an arbitrary point.
52 +
#[derive(Clone, Debug)]
53 +
pub struct Rotation {
54 +
    /// Angle of rotation in radians.
55 +
    pub angle: f32,
56 +
    /// Center of rotation.
57 +
    pub center: Point2D<f32>,
58 +
}
59 +
60 +
impl Rotation {
61 +
    /// No rotation.
62 +
    pub const ZERO: Rotation = Rotation {
63 +
        angle: 0.0,
64 +
        center: Point2D::ZERO,
65 +
    };
66 +
67 +
    /// Create a new rotation.
68 +
    pub fn new(angle: f32, center: Point2D<f32>) -> Self {
69 +
        Self { angle, center }
70 +
    }
71 +
}
72 +
73 +
impl Default for Rotation {
74 +
    fn default() -> Self {
75 +
        Rotation::ZERO
76 +
    }
77 +
}
78 +
79 +
/// A rectangular shape that can be rendered.
80 +
#[derive(Debug, Clone)]
81 +
pub struct Rectangle {
82 +
    /// Position and size in screen space.
83 +
    rect: Rect<f32, Screen>,
84 +
    /// Z-depth for controlling render order.
85 +
    zdepth: ZDepth,
86 +
    /// Rotation around a point.
87 +
    rotation: Rotation,
88 +
}
89 +
90 +
impl From<Rect<f32, Screen>> for Rectangle {
91 +
    /// Creates a rectangle from a screen-space rect.
92 +
    fn from(rect: Rect<f32, Screen>) -> Self {
93 +
        Self::new(rect.origin, rect.size)
94 +
    }
95 +
}
96 +
97 +
impl Rectangle {
98 +
    /// Create a new rectangle.
99 +
    pub fn new(origin: impl Into<Point2D<f32, Screen>>, size: impl Into<Size>) -> Self {
100 +
        Self {
101 +
            rect: Rect::new(origin, size),
102 +
            zdepth: ZDepth::default(),
103 +
            rotation: Rotation::default(),
104 +
        }
105 +
    }
106 +
107 +
    /// Set the z-depth.
108 +
    pub fn zdepth(self, zdepth: impl Into<ZDepth>) -> Self {
109 +
        Self {
110 +
            zdepth: zdepth.into(),
111 +
            ..self
112 +
        }
113 +
    }
114 +
115 +
    /// Set the rotation.
116 +
    pub fn rotation(self, angle: f32, center: impl Into<Point2D>) -> Self {
117 +
        let center = center.into();
118 +
        let rotation = Rotation::new(angle, center);
119 +
        Self { rotation, ..self }
120 +
    }
121 +
}
122 +
123 +
/// A shape is any object that can be converted into renderable vertices.
124 +
///
125 +
/// This trait allows different geometric shapes to be rendered by converting
126 +
/// them into a sequence of vertices that define their visual representation.
127 +
/// Implementations should generate the appropriate vertex data for the shape,
128 +
/// including position, color, texture coordinates and other attributes needed
129 +
/// for rendering.
130 +
pub trait Shape: fmt::Debug {
131 +
    /// Return the vertices for this shape's fill.
132 +
    fn fill<'a>(&self, brush: impl Into<Brush>) -> impl Iterator<Item = Vertex> + 'a;
133 +
    /// Return the vertices for this shape's stroke.
134 +
    fn stroke<'a>(&self, brush: impl Into<Brush>, width: f32) -> impl Iterator<Item = Vertex> + 'a;
135 +
}
136 +
137 +
impl Shape for Rectangle {
138 +
    fn fill<'a>(&self, brush: impl Into<Brush>) -> impl Iterator<Item = Vertex> + 'a {
139 +
        let outer = Box2D::from(self.rect);
140 +
        let z = *self.zdepth;
141 +
        let Rotation { angle, center } = self.rotation;
142 +
143 +
        match brush.into() {
144 +
            Brush::Color(color) => [
145 +
                (outer.min.x, outer.min.y),
146 +
                (outer.max.x, outer.min.y),
147 +
                (outer.max.x, outer.max.y),
148 +
                (outer.min.x, outer.min.y),
149 +
                (outer.min.x, outer.max.y),
150 +
                (outer.max.x, outer.max.y),
151 +
            ]
152 +
            .into_iter()
153 +
            .map(move |(x, y)| vertex(x, y, z, angle, center, color)),
154 +
155 +
            Brush::LinearGradient(_) => unimplemented!(),
156 +
        }
157 +
    }
158 +
159 +
    fn stroke<'a>(&self, brush: impl Into<Brush>, width: f32) -> impl Iterator<Item = Vertex> + 'a {
160 +
        let outer = Box2D::from(self.rect);
161 +
        let inner = Box2D::<_, Screen>::new(
162 +
            Point2D::new(outer.min.x + width, outer.min.y + width),
163 +
            Point2D::new(outer.max.x - width, outer.max.y - width),
164 +
        );
165 +
        let z = *self.zdepth;
166 +
        let Rotation { angle, center } = self.rotation;
167 +
168 +
        match brush.into() {
169 +
            Brush::Color(color) => [
170 +
                // Bottom
171 +
                (outer.min.x, outer.min.y),
172 +
                (outer.max.x, outer.min.y),
173 +
                (inner.min.x, inner.min.y),
174 +
                (inner.min.x, inner.min.y),
175 +
                (outer.max.x, outer.min.y),
176 +
                (inner.max.x, inner.min.y),
177 +
                // Left
178 +
                (outer.min.x, outer.min.y),
179 +
                (inner.min.x, inner.min.y),
180 +
                (outer.min.x, outer.max.y),
181 +
                (outer.min.x, outer.max.y),
182 +
                (inner.min.x, inner.min.y),
183 +
                (inner.min.x, inner.max.y),
184 +
                // Right
185 +
                (inner.max.x, inner.min.y),
186 +
                (outer.max.x, outer.min.y),
187 +
                (outer.max.x, outer.max.y),
188 +
                (inner.max.x, inner.min.y),
189 +
                (inner.max.x, inner.max.y),
190 +
                (outer.max.x, outer.max.y),
191 +
                // Top
192 +
                (outer.min.x, outer.max.y),
193 +
                (outer.max.x, outer.max.y),
194 +
                (inner.min.x, inner.max.y),
195 +
                (inner.min.x, inner.max.y),
196 +
                (outer.max.x, outer.max.y),
197 +
                (inner.max.x, inner.max.y),
198 +
            ]
199 +
            .into_iter()
200 +
            .map(move |(x, y)| vertex(x, y, z, angle, center, color)),
201 +
202 +
            Brush::LinearGradient(_) => unimplemented!(),
203 +
        }
204 +
    }
205 +
}
206 +
207 +
/// A circular shape that can be rendered.
208 +
#[derive(Clone, Debug)]
209 +
pub struct Circle {
210 +
    /// Origin point (center).
211 +
    origin: Point2D,
212 +
    /// Radius.
213 +
    radius: f32,
214 +
    /// Number of sides (for approximating the circle).
215 +
    sides: u32,
216 +
    /// Z-depth for controlling render order.
217 +
    zdepth: ZDepth,
218 +
}
219 +
220 +
impl Circle {
221 +
    /// Create a circle.
222 +
    pub fn new(origin: impl Into<Point2D>, radius: f32, sides: u32) -> Self {
223 +
        let origin = origin.into();
224 +
225 +
        Self {
226 +
            origin,
227 +
            radius,
228 +
            sides,
229 +
            zdepth: ZDepth::default(),
230 +
        }
231 +
    }
232 +
}
233 +
234 +
impl Shape for Circle {
235 +
    fn fill<'a>(&self, brush: impl Into<Brush>) -> impl Iterator<Item = Vertex> + 'a {
236 +
        let brush = brush.into();
237 +
        let z = *self.zdepth;
238 +
        let sides = self.sides as usize;
239 +
240 +
        match brush {
241 +
            Brush::Color(color) => {
242 +
                let center = vertex(self.origin.x, self.origin.y, z, 0.0, Point2D::ZERO, color);
243 +
                let radius = self.radius;
244 +
                let origin = self.origin;
245 +
246 +
                (0..sides).flat_map(move |i| {
247 +
                    let angle1 = (i as f32) * ((2. * f32::consts::PI) / sides as f32);
248 +
                    let angle2 = ((i + 1) as f32) * ((2. * f32::consts::PI) / sides as f32);
249 +
250 +
                    let p1 = Point2D::<_, ()>::new(
251 +
                        origin.x + radius * angle1.cos(),
252 +
                        origin.y + radius * angle1.sin(),
253 +
                    );
254 +
                    let p2 = Point2D::<_, ()>::new(
255 +
                        origin.x + radius * angle2.cos(),
256 +
                        origin.y + radius * angle2.sin(),
257 +
                    );
258 +
259 +
                    [
260 +
                        center,
261 +
                        vertex(p1.x, p1.y, z, 0., Point2D::ZERO, color),
262 +
                        vertex(p2.x, p2.y, z, 0., Point2D::ZERO, color),
263 +
                    ]
264 +
                })
265 +
            }
266 +
            Brush::LinearGradient(_) => unimplemented!(),
267 +
        }
268 +
    }
269 +
270 +
    fn stroke<'a>(&self, brush: impl Into<Brush>, width: f32) -> impl Iterator<Item = Vertex> + 'a {
271 +
        let z = *self.zdepth;
272 +
        let sides = self.sides as usize;
273 +
274 +
        match brush.into() {
275 +
            Brush::Color(color) => {
276 +
                let inner_radius = self.radius - width;
277 +
                let outer_radius = self.radius;
278 +
                let origin = self.origin;
279 +
280 +
                (0..sides).flat_map(move |i| {
281 +
                    let angle1 = (i as f32) * ((2. * f32::consts::PI) / sides as f32);
282 +
                    let angle2 = ((i + 1) as f32) * ((2. * f32::consts::PI) / sides as f32);
283 +
284 +
                    let i0 = Point2D::<_, ()>::new(
285 +
                        origin.x + inner_radius * angle1.cos(),
286 +
                        origin.y + inner_radius * angle1.sin(),
287 +
                    );
288 +
                    let i1 = Point2D::<_, ()>::new(
289 +
                        origin.x + inner_radius * angle2.cos(),
290 +
                        origin.y + inner_radius * angle2.sin(),
291 +
                    );
292 +
                    let o0 = Point2D::<_, ()>::new(
293 +
                        origin.x + outer_radius * angle1.cos(),
294 +
                        origin.y + outer_radius * angle1.sin(),
295 +
                    );
296 +
                    let o1 = Point2D::<_, ()>::new(
297 +
                        origin.x + outer_radius * angle2.cos(),
298 +
                        origin.y + outer_radius * angle2.sin(),
299 +
                    );
300 +
301 +
                    [
302 +
                        (i0.x, i0.y),
303 +
                        (o0.x, o0.y),
304 +
                        (o1.x, o1.y),
305 +
                        (i0.x, i0.y),
306 +
                        (o1.x, o1.y),
307 +
                        (i1.x, i1.y),
308 +
                    ]
309 +
                    .into_iter()
310 +
                    .map(move |(x, y)| vertex(x, y, z, 0.0, Point2D::ZERO, color))
311 +
                })
312 +
            }
313 +
            Brush::LinearGradient(_) => unimplemented!(),
314 +
        }
315 +
    }
316 +
}
317 +
318 +
/// A line segment that can be rendered.
319 +
#[derive(Clone, Debug)]
320 +
pub struct Line {
321 +
    /// Start point in screen space.
322 +
    from: Point2D<f32, Screen>,
323 +
    /// End point in screen space.
324 +
    to: Point2D<f32, Screen>,
325 +
    /// Z-depth for controlling render order.
326 +
    zdepth: ZDepth,
327 +
    /// Rotation.
328 +
    rotation: Rotation,
329 +
}
330 +
331 +
impl Line {
332 +
    /// Creates a new line between two points in screen space.
333 +
    /// The line can be styled with color and width.
334 +
    pub fn new<P: Into<Point2D<f32, Screen>>>(from: P, to: P) -> Self {
335 +
        Self {
336 +
            from: from.into(),
337 +
            to: to.into(),
338 +
            zdepth: ZDepth::default(),
339 +
            rotation: Rotation::default(),
340 +
        }
341 +
    }
342 +
343 +
    /// Transform a line.
344 +
    pub fn transform(self, m: impl Into<Transform2D<Screen, Screen>>) -> Self {
345 +
        let t = m.into();
346 +
347 +
        Self {
348 +
            from: t * self.from,
349 +
            to: t * self.to,
350 +
            ..self
351 +
        }
352 +
    }
353 +
}
354 +
355 +
impl Shape for Line {
356 +
    fn fill<'a>(&self, brush: impl Into<Brush>) -> impl Iterator<Item = Vertex> + 'a {
357 +
        self.stroke(brush, 1.0)
358 +
    }
359 +
360 +
    fn stroke<'a>(&self, brush: impl Into<Brush>, width: f32) -> impl Iterator<Item = Vertex> + 'a {
361 +
        let (from, to) = (self.from, self.to);
362 +
        let z = *self.zdepth;
363 +
        let Rotation { angle, center } = self.rotation;
364 +
        let v = (to - from).normalize();
365 +
        let wx = width / 2. * v.y;
366 +
        let wy = width / 2. * v.x;
367 +
368 +
        match brush.into() {
369 +
            Brush::Color(color) => [
370 +
                vertex(from.x - wx, from.y + wy, z, angle, center, color),
371 +
                vertex(from.x + wx, from.y - wy, z, angle, center, color),
372 +
                vertex(to.x - wx, to.y + wy, z, angle, center, color),
373 +
                vertex(to.x - wx, to.y + wy, z, angle, center, color),
374 +
                vertex(from.x + wx, from.y - wy, z, angle, center, color),
375 +
                vertex(to.x + wx, to.y - wy, z, angle, center, color),
376 +
            ]
377 +
            .into_iter(),
378 +
379 +
            Brush::LinearGradient(_) => unimplemented!(),
380 +
        }
381 +
    }
382 +
}
383 +
384 +
impl std::ops::Mul<f32> for Line {
385 +
    type Output = Self;
386 +
387 +
    fn mul(self, n: f32) -> Self {
388 +
        Self {
389 +
            from: self.from * n,
390 +
            to: self.to * n,
391 +
            ..self
392 +
        }
393 +
    }
394 +
}
395 +
396 +
impl std::ops::Add<Vector2D<f32, Screen>> for Line {
397 +
    type Output = Self;
398 +
399 +
    fn add(self, vec: Vector2D<f32, Screen>) -> Self {
400 +
        Self {
401 +
            from: self.from + vec,
402 +
            to: self.to + vec,
403 +
            ..self
404 +
        }
405 +
    }
406 +
}
407 +
408 +
/// Create a line.
409 +
pub fn line<P: Into<Point2D<f32, Screen>>>(from: P, to: P) -> Line {
410 +
    Line::new(from, to)
411 +
}
412 +
413 +
/// Create a rectangle.
414 +
pub fn rectangle(origin: impl Into<Point2D<f32, Screen>>, size: impl Into<Size>) -> Rectangle {
415 +
    Rectangle::new(origin, size)
416 +
}
417 +
418 +
/// Create a circle.
419 +
pub fn circle(origin: impl Into<Point2D>, radius: f32, sides: u32) -> Circle {
420 +
    Circle::new(origin, radius, sides)
421 +
}
ombre/src/draw/traits.rs added +17 -0
1 +
use crate::gfx::Rgba;
2 +
3 +
/// Defines how a shape should be colored.
4 +
/// Can be either a solid color or a gradient between multiple colors.
5 +
#[derive(Debug, Clone)]
6 +
pub enum Brush {
7 +
    /// A [`Rgba`] color.
8 +
    Color(Rgba<f32>),
9 +
    /// A gradient between a set of colors.
10 +
    LinearGradient([Rgba<f32>; 8]),
11 +
}
12 +
13 +
impl From<Rgba<f32>> for Brush {
14 +
    fn from(src: Rgba<f32>) -> Brush {
15 +
        Brush::Color(src)
16 +
    }
17 +
}
ombre/src/gfx.rs added +40 -0
1 +
//! Graphics rendering.
2 +
pub mod color;
3 +
pub mod font;
4 +
pub mod gl;
5 +
pub mod limits;
6 +
pub mod pixels;
7 +
pub mod traits;
8 +
9 +
mod blending;
10 +
mod buffer;
11 +
mod id;
12 +
mod image;
13 +
mod pass;
14 +
mod pipeline;
15 +
mod shader;
16 +
mod stencil;
17 +
mod texture;
18 +
mod uniform;
19 +
20 +
pub use crate::bytes;
21 +
pub use crate::bytes::{AsBytes, AsBytesMut};
22 +
pub use crate::math::{
23 +
    Point2D, Rect, Size, Transform2D, Transform3D, Vector2D, Vector3D, Vector4D,
24 +
};
25 +
pub use crate::platform;
26 +
27 +
pub use blending::*;
28 +
pub use buffer::*;
29 +
pub use bytes::Empty;
30 +
pub use color::{Color, Rgb, Rgb8, Rgba, Rgba8};
31 +
pub use font::*;
32 +
pub use id::Id;
33 +
pub use image::*;
34 +
pub use pass::*;
35 +
pub use pipeline::*;
36 +
pub use shader::*;
37 +
pub use stencil::*;
38 +
pub use texture::*;
39 +
pub use traits::*;
40 +
pub use uniform::*;
ombre/src/gfx/blending.rs added +75 -0
1 +
//! Color blending.
2 +
3 +
/// A pixel-wise comparison function.
4 +
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
5 +
pub enum Comparison {
6 +
    #[default]
7 +
    Always,
8 +
    Never,
9 +
    Less,
10 +
    LessOrEqual,
11 +
    Greater,
12 +
    GreaterOrEqual,
13 +
    Equal,
14 +
    NotEqual,
15 +
}
16 +
17 +
/// Specifies how incoming RGBA values (source) and RGBA values
18 +
/// in a framebuffer (destination) are combined.
19 +
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
20 +
pub enum BlendOp {
21 +
    /// Adds source to destination. Source and destination are multiplied
22 +
    /// by the blending parameters before addition.
23 +
    #[default]
24 +
    Add,
25 +
    /// Subtracts destination from source. Source and destination are
26 +
    /// multiplied by the blending parameters before subtraction.
27 +
    Subtract,
28 +
    /// Subtracts source from destination. Source and destination are
29 +
    /// multiplied by the blending parameters before subtraction.
30 +
    SubtractReverse,
31 +
}
32 +
33 +
/// Blend values.
34 +
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
35 +
pub enum BlendValue {
36 +
    SourceColor,
37 +
    SourceAlpha,
38 +
    DestinationColor,
39 +
    DestinationAlpha,
40 +
}
41 +
42 +
/// Blend factors.
43 +
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
44 +
pub enum BlendFactor {
45 +
    Zero,
46 +
    One,
47 +
    Value(BlendValue),
48 +
    OneMinusValue(BlendValue),
49 +
    SourceAlphaSaturate,
50 +
}
51 +
52 +
/// A blending equation.
53 +
///
54 +
/// Can be described as `op(sfactor * source, dfactor * destination)`
55 +
/// The default is pre-multiplied alpha blending, ie. `destination.rgb = source.rgb * source.a +
56 +
/// destination.rgb * (1 - source.a)`
57 +
#[derive(Debug, Copy, Clone, PartialEq)]
58 +
pub struct BlendEquation {
59 +
    /// Blend operation.
60 +
    pub op: BlendOp,
61 +
    /// Source factor.
62 +
    pub sfactor: BlendFactor,
63 +
    /// Destination factor.
64 +
    pub dfactor: BlendFactor,
65 +
}
66 +
67 +
impl Default for BlendEquation {
68 +
    fn default() -> Self {
69 +
        BlendEquation {
70 +
            op: BlendOp::Add,
71 +
            sfactor: BlendFactor::Value(BlendValue::SourceAlpha),
72 +
            dfactor: BlendFactor::OneMinusValue(BlendValue::SourceAlpha),
73 +
        }
74 +
    }
75 +
}
ombre/src/gfx/buffer.rs added +77 -0
1 +
//! Vertex and index buffers.
2 +
use std::mem;
3 +
4 +
use super::id;
5 +
6 +
/// Identifier for an index or vertex buffer.
7 +
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
8 +
pub struct BufferId(id::Id);
9 +
10 +
impl BufferId {
11 +
    /// Get the next id.
12 +
    pub(crate) fn next() -> Self {
13 +
        Self(id::next())
14 +
    }
15 +
}
16 +
17 +
impl std::fmt::Display for BufferId {
18 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19 +
        self.0.fmt(f)
20 +
    }
21 +
}
22 +
23 +
/// Buffer source.
24 +
#[derive(Debug)]
25 +
pub enum BufferSource<'a, T> {
26 +
    /// A slice of data.
27 +
    Slice(&'a [T]),
28 +
    /// An empty pre-allocated buffer.
29 +
    Empty {
30 +
        /// Size in bytes of buffer.
31 +
        size: usize,
32 +
    },
33 +
    /// A zero-initialized buffer.
34 +
    Zero {
35 +
        /// Size in bytes of buffer.
36 +
        size: usize,
37 +
    },
38 +
}
39 +
40 +
impl<'a, T> BufferSource<'a, T> {
41 +
    /// Empty buffer of `elements * size_of::<T>` bytes.
42 +
    pub fn empty(elements: usize) -> BufferSource<'a, T> {
43 +
        BufferSource::Empty {
44 +
            size: elements * mem::size_of::<T>(),
45 +
        }
46 +
    }
47 +
48 +
    /// Zero-initialized buffer of `elements * size_of::<T>` bytes.
49 +
    pub fn zero(elements: usize) -> BufferSource<'a, T> {
50 +
        BufferSource::Zero {
51 +
            size: elements * mem::size_of::<T>(),
52 +
        }
53 +
    }
54 +
55 +
    /// Buffer from a slice of `T`.
56 +
    pub fn slice(data: &'a [T]) -> BufferSource<'a, T> {
57 +
        BufferSource::Slice(data)
58 +
    }
59 +
}
60 +
61 +
/// Type of object the buffer holds.
62 +
#[derive(Clone, Copy, Debug, PartialEq)]
63 +
pub enum BufferKind {
64 +
    Vertex,
65 +
    Index,
66 +
}
67 +
68 +
/// How the buffer will be used.
69 +
#[derive(Clone, Copy, Debug, PartialEq)]
70 +
pub enum BufferUsage {
71 +
    /// Buffer will never be updated.
72 +
    Immutable,
73 +
    /// Buffer will be updated occasionally.
74 +
    Dynamic,
75 +
    /// Buffer will be updated often.
76 +
    Stream,
77 +
}
ombre/src/gfx/color.rs added +335 -0
1 +
//! Color types.
2 +
use std::fmt;
3 +
use std::mem;
4 +
use std::mem::ManuallyDrop;
5 +
use std::str::FromStr;
6 +
7 +
use crate::math::Zero;
8 +
9 +
///////////////////////////////////////////////////////////////////////////
10 +
// Rgba8
11 +
///////////////////////////////////////////////////////////////////////////
12 +
13 +
/// RGBA color with 8-bit channels.
14 +
#[repr(C)]
15 +
#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Debug, Default, Hash)]
16 +
pub struct Rgba8 {
17 +
    /// Red channel.
18 +
    pub r: u8,
19 +
    /// Green channel.
20 +
    pub g: u8,
21 +
    /// Blue channel.
22 +
    pub b: u8,
23 +
    /// Alpha channel.
24 +
    pub a: u8,
25 +
}
26 +
27 +
impl Rgba8 {
28 +
    /// Create a new [`Rgba8`] color from individual channels.
29 +
    pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
30 +
        Self { r, g, b, a }
31 +
    }
32 +
33 +
    /// Create a greyscale color.
34 +
    pub const fn greyscale(value: u8) -> Self {
35 +
        Self::new(value, value, value, u8::MAX)
36 +
    }
37 +
38 +
    /// Invert the color.
39 +
    pub fn invert(self) -> Self {
40 +
        Self::new(0xff - self.r, 0xff - self.g, 0xff - self.b, self.a)
41 +
    }
42 +
43 +
    /// Return the color with a changed alpha.
44 +
    ///
45 +
    /// ```
46 +
    /// use ombre::gfx::{Rgba8, Color as _};
47 +
    ///
48 +
    /// let c = Rgba8::WHITE;
49 +
    /// assert_eq!(c.alpha(0x88), Rgba8::new(c.r, c.g, c.b, 0x88))
50 +
    /// ```
51 +
    pub const fn alpha(self, a: u8) -> Self {
52 +
        Self::new(self.r, self.g, self.b, a)
53 +
    }
54 +
55 +
    /// Given a byte slice, returns a slice of [`Rgba8`] values.
56 +
    pub fn align<'a, S: 'a, T: AsRef<[S]> + ?Sized>(bytes: &'a T) -> &'a [Rgba8] {
57 +
        let bytes = bytes.as_ref();
58 +
        let (head, body, tail) = unsafe { bytes.align_to::<Rgba8>() };
59 +
60 +
        if !(head.is_empty() && tail.is_empty()) {
61 +
            panic!("Rgba8::align: input is not a valid `Rgba8` buffer");
62 +
        }
63 +
        body
64 +
    }
65 +
66 +
    /// Given a byte vector, returns a vector of [`Rgba8`] values.
67 +
    pub fn into_vec(bytes: Vec<u8>) -> Vec<Self> {
68 +
        if bytes.len() % mem::size_of::<Rgba8>() != 0 {
69 +
            panic!("Rgba8::into_vec: input is not a valid `Rgba8` buffer");
70 +
        }
71 +
        assert_eq!(bytes.capacity() % 4, 0);
72 +
73 +
        let bytes = ManuallyDrop::new(bytes);
74 +
        let ptr = bytes.as_ptr();
75 +
        let length = bytes.len() / 4;
76 +
        let capacity = bytes.capacity() / 4;
77 +
78 +
        unsafe { Vec::from_raw_parts(ptr as *mut Rgba8, length, capacity) }
79 +
    }
80 +
}
81 +
82 +
impl Zero for Rgba8 {
83 +
    const ZERO: Self = Rgba8::TRANSPARENT;
84 +
85 +
    fn is_zero(&self) -> bool {
86 +
        self == &Self::ZERO
87 +
    }
88 +
}
89 +
90 +
/// ```
91 +
/// use ombre::gfx::Rgba8;
92 +
///
93 +
/// assert_eq!(format!("{}", Rgba8::new(0xff, 0x0, 0xa, 0xff)), "#ff000a");
94 +
/// ```
95 +
impl fmt::Display for Rgba8 {
96 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 +
        write!(f, "#{:02x}{:02x}{:02x}", self.r, self.g, self.b)?;
98 +
        if self.a != 0xff {
99 +
            write!(f, "{:02x}", self.a)?;
100 +
        }
101 +
        Ok(())
102 +
    }
103 +
}
104 +
105 +
/// ```
106 +
/// use ombre::gfx::{Rgba8, Rgba, Color as _};
107 +
///
108 +
/// assert_eq!(Rgba8::from(Rgba::RED), Rgba8::RED);
109 +
/// ```
110 +
impl From<Rgba<f32>> for Rgba8 {
111 +
    fn from(rgba: Rgba<f32>) -> Self {
112 +
        Self {
113 +
            r: (rgba.r * 255.0).round() as u8,
114 +
            g: (rgba.g * 255.0).round() as u8,
115 +
            b: (rgba.b * 255.0).round() as u8,
116 +
            a: (rgba.a * 255.0).round() as u8,
117 +
        }
118 +
    }
119 +
}
120 +
121 +
impl From<u32> for Rgba8 {
122 +
    fn from(rgba: u32) -> Self {
123 +
        unsafe { std::mem::transmute(rgba) }
124 +
    }
125 +
}
126 +
127 +
impl From<Rgba8> for u32 {
128 +
    fn from(rgba: Rgba8) -> Self {
129 +
        unsafe { std::mem::transmute(rgba) }
130 +
    }
131 +
}
132 +
133 +
/// Error returned by [`Rgba8::from_str`].
134 +
#[derive(Debug, Clone, PartialEq, Eq)]
135 +
pub enum ParseRgba8Error {
136 +
    ParseInt(std::num::ParseIntError),
137 +
    Length,
138 +
}
139 +
140 +
impl fmt::Display for ParseRgba8Error {
141 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 +
        match self {
143 +
            Self::ParseInt(e) => e.fmt(f),
144 +
            Self::Length => write!(f, "invalid length for RGBA8 color"),
145 +
        }
146 +
    }
147 +
}
148 +
149 +
impl From<std::num::ParseIntError> for ParseRgba8Error {
150 +
    fn from(value: std::num::ParseIntError) -> Self {
151 +
        Self::ParseInt(value)
152 +
    }
153 +
}
154 +
155 +
impl FromStr for Rgba8 {
156 +
    type Err = ParseRgba8Error;
157 +
158 +
    /// Parse a color code of the form `#ffffff` into an
159 +
    /// instance of `Rgba8`. The alpha is set to `0xff` if the
160 +
    /// string does not contain an alpha channel.
161 +
    fn from_str(hex_code: &str) -> Result<Self, Self::Err> {
162 +
        if hex_code.len() < 7 || hex_code.len() > 9 {
163 +
            return Err(ParseRgba8Error::Length);
164 +
        }
165 +
        let r: u8 = u8::from_str_radix(&hex_code[1..3], 16)?;
166 +
        let g: u8 = u8::from_str_radix(&hex_code[3..5], 16)?;
167 +
        let b: u8 = u8::from_str_radix(&hex_code[5..7], 16)?;
168 +
        let a: u8 = if hex_code.len() == 9 {
169 +
            u8::from_str_radix(&hex_code[7..9], 16)?
170 +
        } else {
171 +
            0xff
172 +
        };
173 +
        Ok(Rgba8 { r, g, b, a })
174 +
    }
175 +
}
176 +
177 +
//////////////////////////////////////////////////////////////////////////////
178 +
// Rgb8
179 +
//////////////////////////////////////////////////////////////////////////////
180 +
181 +
/// An RGB 8-bit color. Used when the alpha value isn't used.
182 +
#[repr(C)]
183 +
#[derive(Copy, Clone, Default, Debug)]
184 +
pub struct Rgb8 {
185 +
    pub r: u8,
186 +
    pub g: u8,
187 +
    pub b: u8,
188 +
}
189 +
190 +
impl From<Rgba8> for Rgb8 {
191 +
    fn from(rgba: Rgba8) -> Self {
192 +
        Self {
193 +
            r: rgba.r,
194 +
            g: rgba.g,
195 +
            b: rgba.b,
196 +
        }
197 +
    }
198 +
}
199 +
200 +
impl fmt::Display for Rgb8 {
201 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202 +
        write!(f, "#{:02X}{:02X}{:02X}", self.r, self.g, self.b)
203 +
    }
204 +
}
205 +
206 +
//////////////////////////////////////////////////////////////////////////////
207 +
// Rgb
208 +
//////////////////////////////////////////////////////////////////////////////
209 +
210 +
/// A generic RGB color.
211 +
#[repr(C)]
212 +
#[derive(Copy, Clone, PartialEq, Debug, Default)]
213 +
pub struct Rgb<T> {
214 +
    /// Red channel.
215 +
    pub r: T,
216 +
    /// Green channel.
217 +
    pub g: T,
218 +
    /// Blue channel.
219 +
    pub b: T,
220 +
}
221 +
222 +
impl<T> Rgb<T> {
223 +
    /// Create a new `Rgb` color.
224 +
    pub const fn new(r: T, g: T, b: T) -> Self {
225 +
        Self { r, g, b }
226 +
    }
227 +
}
228 +
229 +
//////////////////////////////////////////////////////////////////////////////
230 +
// Rgba
231 +
//////////////////////////////////////////////////////////////////////////////
232 +
233 +
/// A generic RGBA color.
234 +
#[repr(C)]
235 +
#[derive(Copy, Clone, PartialEq, Debug, Default)]
236 +
pub struct Rgba<T> {
237 +
    /// Red channel.
238 +
    pub r: T,
239 +
    /// Green channel.
240 +
    pub g: T,
241 +
    /// Blue channel.
242 +
    pub b: T,
243 +
    /// Alpha channel.
244 +
    pub a: T,
245 +
}
246 +
247 +
impl<T> Rgba<T> {
248 +
    /// Create a new `Rgba` color.
249 +
    pub const fn new(r: T, g: T, b: T, a: T) -> Self {
250 +
        Self { r, g, b, a }
251 +
    }
252 +
}
253 +
254 +
impl Rgba<f32> {
255 +
    /// Invert the color.
256 +
    pub fn invert(self) -> Self {
257 +
        Self::new(1.0 - self.r, 1.0 - self.g, 1.0 - self.b, self.a)
258 +
    }
259 +
}
260 +
261 +
impl From<Rgba8> for Rgba<f32> {
262 +
    fn from(rgba8: Rgba8) -> Self {
263 +
        Self {
264 +
            r: (rgba8.r as f32 / 255.0),
265 +
            g: (rgba8.g as f32 / 255.0),
266 +
            b: (rgba8.b as f32 / 255.0),
267 +
            a: (rgba8.a as f32 / 255.0),
268 +
        }
269 +
    }
270 +
}
271 +
272 +
impl<T> From<Rgba<T>> for [T; 4] {
273 +
    fn from(rgba: Rgba<T>) -> Self {
274 +
        [rgba.r, rgba.g, rgba.b, rgba.a]
275 +
    }
276 +
}
277 +
278 +
/// Implemented by most color types.
279 +
pub trait Color {
280 +
    /// Pure white.
281 +
    const WHITE: Self;
282 +
    /// Pute black.
283 +
    const BLACK: Self;
284 +
    /// Transparent.
285 +
    const TRANSPARENT: Self;
286 +
    /// Pure red.
287 +
    const RED: Self;
288 +
    /// Pure green.
289 +
    const GREEN: Self;
290 +
    /// Pure blue.
291 +
    const BLUE: Self;
292 +
    /// Yellow.
293 +
    const YELLOW: Self;
294 +
    /// Pink.
295 +
    const PINK: Self;
296 +
}
297 +
298 +
impl Color for Rgba8 {
299 +
    const WHITE: Self = Self::new(0xff, 0xff, 0xff, 0xff);
300 +
    const BLACK: Self = Self::new(0, 0, 0, 0xff);
301 +
    const TRANSPARENT: Self = Self::new(0, 0, 0, 0);
302 +
    const RED: Self = Self::new(0xff, 0x55, 0x55, 0xff);
303 +
    const GREEN: Self = Self::new(0x55, 0xff, 0x55, 0xff);
304 +
    const BLUE: Self = Self::new(0x55, 0x55, 0xff, 0xff);
305 +
    const YELLOW: Self = Self::new(0xff, 0xff, 0x55, 0xff);
306 +
    const PINK: Self = Self::new(0xff, 0x55, 0xff, 0xff);
307 +
}
308 +
309 +
impl Color for Rgba<f32> {
310 +
    const WHITE: Self = Rgba::new(1., 1., 1., 1.);
311 +
    const BLACK: Self = Rgba::new(0., 0., 0., 1.);
312 +
    const TRANSPARENT: Self = Rgba::new(0., 0., 0., 0.);
313 +
    const RED: Self = Rgba::new(1., 1. / 3., 1. / 3., 1.);
314 +
    const GREEN: Self = Rgba::new(1. / 3., 1.0, 1. / 3., 1.);
315 +
    const BLUE: Self = Rgba::new(1. / 3., 1. / 3., 1., 1.);
316 +
    const YELLOW: Self = Self::new(1., 1., 1. / 3., 1.);
317 +
    const PINK: Self = Self::new(1., 1. / 3., 1.0, 1.);
318 +
}
319 +
320 +
#[cfg(test)]
321 +
mod tests {
322 +
    use super::*;
323 +
324 +
    #[test]
325 +
    fn test_conversion() {
326 +
        assert_eq!(
327 +
            Rgba::<f32>::from(Rgba8::BLUE.alpha(0x80)),
328 +
            Rgba::new(1. / 3., 1. / 3., 1., 0.5019608)
329 +
        );
330 +
        assert_eq!(
331 +
            Rgba8::from(Rgba::<f32>::new(1. / 3., 1. / 3., 1., 0.5)),
332 +
            Rgba8::BLUE.alpha(0x80)
333 +
        );
334 +
    }
335 +
}
ombre/src/gfx/font.rs added +228 -0
1 +
//! Bitmap font encodings.
2 +
use std::array::TryFromSliceError;
3 +
use std::fmt;
4 +
use std::ops::Deref;
5 +
6 +
use crate::gfx::pixels::PixelsMut;
7 +
use crate::gfx::*;
8 +
use crate::math::*;
9 +
use crate::string::Str;
10 +
11 +
/// Font error.
12 +
#[derive(Debug, Clone)]
13 +
pub enum FontError {
14 +
    TryFromSlice(TryFromSliceError),
15 +
    TileCount(usize, usize),
16 +
    ByteLength(usize),
17 +
}
18 +
19 +
impl std::error::Error for FontError {}
20 +
21 +
impl std::fmt::Display for FontError {
22 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23 +
        match self {
24 +
            Self::TryFromSlice(e) => write!(f, "invalid font: {e}"),
25 +
            Self::TileCount(a, e) => write!(f, "invalid tile count `{a}`, expected `{e}`"),
26 +
            Self::ByteLength(l) => write!(f, "invalid font byte length '{l}'"),
27 +
        }
28 +
    }
29 +
}
30 +
31 +
/// Font format.
32 +
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33 +
pub enum FontFormat {
34 +
    UF1,
35 +
    UF2,
36 +
}
37 +
38 +
impl FontFormat {
39 +
    /// Glyph tile.
40 +
    pub fn tile_size(&self) -> Size<f32> {
41 +
        match self {
42 +
            Self::UF1 => Size::new(8., 8.),
43 +
            Self::UF2 => Size::new(16., 16.),
44 +
        }
45 +
    }
46 +
}
47 +
48 +
/// Bitmap font.
49 +
#[derive(Debug, Clone, Copy)]
50 +
pub struct Font<T> {
51 +
    /// Glyph widths.
52 +
    pub widths: [u8; 256],
53 +
    /// Font texture or image.
54 +
    pub image: T,
55 +
    /// Font glyph size.
56 +
    pub format: FontFormat,
57 +
    /// Font metrics.
58 +
    pub metrics: FontMetrics,
59 +
}
60 +
61 +
impl Font<Image> {
62 +
    /// Decode a font from a byte slice.
63 +
    pub fn decode(
64 +
        bytes: &[u8],
65 +
        format: FontFormat,
66 +
        metrics: FontMetrics,
67 +
    ) -> Result<Font<Image>, FontError> {
68 +
        // Tile width and height. For UF2 fonts, each glyph is represented by four tiles.
69 +
        const T: usize = 8;
70 +
        // Glyph count. Represents the ASCII range.
71 +
        const N: usize = 256;
72 +
        // Number of tiles per glyph.
73 +
        const G: usize = 2 * 2;
74 +
75 +
        assert!(
76 +
            matches!(format, FontFormat::UF2),
77 +
            "Only UF2 fonts are currently supported"
78 +
        );
79 +
80 +
        let (widths, glyphs) = bytes.split_at(N);
81 +
        let (head, tiles, tail) = unsafe { glyphs.align_to::<[u8; T]>() };
82 +
83 +
        if !head.is_empty() || !tail.is_empty() {
84 +
            return Err(FontError::ByteLength(glyphs.len()));
85 +
        }
86 +
        if tiles.len() != N * G {
87 +
            return Err(FontError::TileCount(tiles.len(), N * G));
88 +
        }
89 +
90 +
        // Rasterize the font into a 256x256 texture.
91 +
        let size = Size::new(N, N);
92 +
        let widths: [u8; N] = widths.try_into().map_err(FontError::TryFromSlice)?;
93 +
        let mut texels = vec![Rgba8::ZERO; size.area()];
94 +
        let mut pixels = PixelsMut::new(&mut texels, size.w, size.h);
95 +
96 +
        // Each glyph is a 2x2 grid of tiles encoded in the following order:
97 +
        //
98 +
        //   0 2
99 +
        //   1 3
100 +
        //
101 +
        // We loop through the tiles in chunks of 2, where each iteration renders half a glyph
102 +
        // into the texture.
103 +
        //
104 +
        let v = Rgba8::WHITE;
105 +
        let (mut x, mut y) = (0, 0);
106 +
107 +
        for window in tiles.chunks(G / 2) {
108 +
            if let &[a, b] = window {
109 +
                pixels.icn(a, x, y, v);
110 +
                pixels.icn(b, x, y + T, v);
111 +
112 +
                x += T;
113 +
114 +
                if x == size.w {
115 +
                    x = 0;
116 +
                    y += T + T;
117 +
                }
118 +
            }
119 +
        }
120 +
121 +
        Ok(Font {
122 +
            widths,
123 +
            metrics,
124 +
            format,
125 +
            image: Image::new(texels, size),
126 +
        })
127 +
    }
128 +
}
129 +
130 +
impl<T> Font<T> {
131 +
    /// Tile size.
132 +
    pub fn tile_size(&self) -> Size<f32> {
133 +
        self.format.tile_size()
134 +
    }
135 +
136 +
    /// Glyph width of given character.
137 +
    pub fn glyph_width(&self, c: u8) -> f32 {
138 +
        self.widths[c as usize] as f32
139 +
    }
140 +
141 +
    /// Width of the given text string.
142 +
    pub fn text_width(&self, text: &str) -> f32 {
143 +
        text.bytes().map(|c| self.glyph_width(c)).sum()
144 +
    }
145 +
}
146 +
147 +
/// Identifies a font.
148 +
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
149 +
pub struct FontName(Str);
150 +
151 +
impl FontName {
152 +
    /// Create a new font name from a string.
153 +
    pub const fn new(name: &str) -> Self {
154 +
        Self(Str::new(name))
155 +
    }
156 +
157 +
    /// Return a reference to the font name string.
158 +
    pub fn as_str(&self) -> &str {
159 +
        self.0.as_str()
160 +
    }
161 +
}
162 +
163 +
impl From<String> for FontName {
164 +
    fn from(value: String) -> Self {
165 +
        Self(value.into())
166 +
    }
167 +
}
168 +
169 +
impl From<&str> for FontName {
170 +
    fn from(value: &str) -> Self {
171 +
        Self(value.into())
172 +
    }
173 +
}
174 +
175 +
impl Deref for FontName {
176 +
    type Target = str;
177 +
178 +
    fn deref(&self) -> &Self::Target {
179 +
        self.0.as_ref()
180 +
    }
181 +
}
182 +
183 +
/// A font that hasn't been loaded yet.
184 +
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
185 +
pub struct FontDescriptor<'f> {
186 +
    /// The font format.
187 +
    pub format: FontFormat,
188 +
    /// Font metrics.
189 +
    pub metrics: FontMetrics,
190 +
    /// The font name.
191 +
    pub name: FontName,
192 +
    /// The raw font bytes.
193 +
    pub data: &'f [u8],
194 +
}
195 +
196 +
impl FontDescriptor<'_> {
197 +
    /// Decode a font descriptor into a [`Font<Image>`].
198 +
    pub fn decode(&self) -> Result<Font<Image>, font::FontError> {
199 +
        Font::decode(self.data, self.format, self.metrics)
200 +
    }
201 +
}
202 +
203 +
impl std::fmt::Display for FontDescriptor<'_> {
204 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
205 +
        write!(f, "{}", self.name.as_str())
206 +
    }
207 +
}
208 +
209 +
/// Font metrics, eg. baseline, cap height etc.
210 +
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
211 +
pub struct FontMetrics {
212 +
    /// Glyph height, in pixels.
213 +
    pub glyph_height: u8,
214 +
    /// Height of capital letters, ie. "cap height", in pixels.
215 +
    pub cap_height: u8,
216 +
    /// Descender height.
217 +
    pub desc_height: u8,
218 +
    /// Vertical offset of baseline, from top of glyph.
219 +
    pub baseline: u8,
220 +
}
221 +
222 +
impl FontMetrics {
223 +
    /// Line height is calculated based on centering the "cap height" vertically,
224 +
    /// such that there is equal space above and below.
225 +
    pub fn line_height(&self) -> u8 {
226 +
        self.cap_height + self.desc_height * 2
227 +
    }
228 +
}
ombre/src/gfx/gl.rs added +1390 -0
1 +
//! OpenGL backend.
2 +
mod error;
3 +
mod types;
4 +
5 +
use std::mem;
6 +
7 +
use glow::HasContext as _;
8 +
9 +
use super::*;
10 +
use crate::bytes::Packed;
11 +
use crate::collections::IntMap;
12 +
use types::ToGl as _;
13 +
14 +
pub use error::Error;
15 +
16 +
/// OpenGL context information.
17 +
#[derive(Clone, Debug)]
18 +
pub struct ContextInfo {
19 +
    /// OpenGL version information.
20 +
    pub version: glow::Version,
21 +
}
22 +
23 +
/// Converts from [`TextureFormat`] to `(internal_format, format, pixel_type)`.
24 +
impl From<TextureFormat> for (u32, u32, u32) {
25 +
    fn from(format: TextureFormat) -> Self {
26 +
        match format {
27 +
            TextureFormat::Rgb8 => (glow::RGB, glow::RGB, glow::UNSIGNED_BYTE),
28 +
            TextureFormat::Rgba8 => (glow::RGBA, glow::RGBA, glow::UNSIGNED_BYTE),
29 +
            TextureFormat::Srgb8 => (glow::SRGB8, glow::RGB, glow::UNSIGNED_BYTE),
30 +
            TextureFormat::Srgba8 => (glow::SRGB8_ALPHA8, glow::RGBA, glow::UNSIGNED_BYTE),
31 +
            TextureFormat::Depth => (glow::DEPTH_COMPONENT32F, glow::DEPTH_COMPONENT, glow::FLOAT),
32 +
            TextureFormat::Alpha => (glow::ALPHA, glow::ALPHA, glow::UNSIGNED_BYTE),
33 +
            TextureFormat::Signed => (glow::R32I, glow::RED_INTEGER, glow::INT),
34 +
            TextureFormat::Unsigned => (glow::R32UI, glow::RED_INTEGER, glow::UNSIGNED_INT),
35 +
        }
36 +
    }
37 +
}
38 +
39 +
/// An OpenGL vertex buffer.
40 +
#[derive(Clone, Copy, Debug)]
41 +
struct VertexBuffer {
42 +
    /// OpenGL handle.
43 +
    handle: glow::Buffer,
44 +
    /// Size in bytes.
45 +
    size: usize,
46 +
}
47 +
48 +
/// An OpenGL index buffer.
49 +
#[derive(Clone, Copy, Debug)]
50 +
struct IndexBuffer {
51 +
    /// OpenGL handle.
52 +
    handle: glow::Buffer,
53 +
    /// Size of individual indices.
54 +
    elem: ElementSize,
55 +
    /// Size in bytes.
56 +
    size: usize,
57 +
}
58 +
59 +
/// Size of elements in index buffer.
60 +
#[derive(Clone, Copy, Debug, PartialEq)]
61 +
struct ElementSize(usize);
62 +
63 +
impl ElementSize {
64 +
    fn size(&self) -> usize {
65 +
        self.0
66 +
    }
67 +
}
68 +
69 +
impl TryFrom<usize> for ElementSize {
70 +
    type Error = usize;
71 +
72 +
    fn try_from(size: usize) -> Result<Self, Self::Error> {
73 +
        match size {
74 +
            1 | 2 | 4 => Ok(Self(size)),
75 +
            _ => Err(size),
76 +
        }
77 +
    }
78 +
}
79 +
80 +
#[derive(Debug)]
81 +
struct ShaderUniform {
82 +
    /// Location in vertex shader binding.
83 +
    location: Option<glow::UniformLocation>,
84 +
    /// Uniform type.
85 +
    kind: UniformKind,
86 +
    /// Number of elements.
87 +
    arity: usize,
88 +
}
89 +
90 +
impl ShaderUniform {
91 +
    fn size(&self) -> usize {
92 +
        self.kind.size() * self.arity
93 +
    }
94 +
}
95 +
96 +
#[derive(Debug)]
97 +
struct ShaderTexture {
98 +
    location: glow::UniformLocation,
99 +
}
100 +
101 +
#[derive(Debug)]
102 +
struct Shader {
103 +
    program: glow::Program,
104 +
    textures: Vec<ShaderTexture>,
105 +
    uniforms: Vec<ShaderUniform>,
106 +
}
107 +
108 +
#[derive(Clone, Copy, Debug, PartialEq)]
109 +
struct VertexAttributeInternal {
110 +
    location: u32,
111 +
    size: i32,
112 +
    format: VertexFormat,
113 +
    offset: i64,
114 +
    stride: i32,
115 +
    buffer: usize,
116 +
    divisor: i32,
117 +
}
118 +
119 +
#[derive(Debug, Clone)]
120 +
struct Pipeline {
121 +
    shader: ShaderId,
122 +
    layout: Vec<VertexAttributeInternal>,
123 +
    culling: CullMode,
124 +
    winding: FaceWinding,
125 +
    depth: Option<DepthState>,
126 +
    stencil: Option<StencilState>,
127 +
    color: Option<ColorState>,
128 +
    primitive: Primitive,
129 +
}
130 +
131 +
#[derive(Debug, Clone)]
132 +
struct Pass {
133 +
    fb: glow::Framebuffer,
134 +
    colors: Vec<TextureId>,
135 +
    depth: Option<TextureId>,
136 +
    size: Size<u32>,
137 +
}
138 +
139 +
/// Active objects in a frame.
140 +
#[derive(Default)]
141 +
struct Active {
142 +
    pipeline: Option<PipelineId>,
143 +
    pass: Option<PassId>,
144 +
    vertices: Vec<BufferId>,
145 +
    indices: Option<BufferId>,
146 +
}
147 +
148 +
impl Active {
149 +
    fn pipeline(&self) -> Result<PipelineId, Error> {
150 +
        self.pipeline.ok_or(Error::NoActivePipeline)
151 +
    }
152 +
}
153 +
154 +
/// OpenGL context.
155 +
#[derive(Debug)]
156 +
pub struct Context {
157 +
    gl: glow::Context,
158 +
    shaders: IntMap<ShaderId, Shader>,
159 +
    pipelines: IntMap<PipelineId, Pipeline>,
160 +
    passes: IntMap<PassId, Pass>,
161 +
    index_buffers: IntMap<BufferId, IndexBuffer>,
162 +
    vertex_buffers: IntMap<BufferId, VertexBuffer>,
163 +
    textures: IntMap<TextureId, Texture<glow::Texture>>,
164 +
    window: platform::LogicalSize,
165 +
}
166 +
167 +
impl Context {
168 +
    /// Load the default OpenGL context from a window.
169 +
    pub fn load(window: &mut platform::Window) -> Result<Context, Error> {
170 +
        let gl = unsafe { glow::Context::from_loader_function(|p| window.get_proc_address(p)) };
171 +
        Self::new(gl, window.size())
172 +
    }
173 +
174 +
    /// Create a new OpenGL context from a `glow` context.
175 +
    // TODO: Should be physical size.
176 +
    pub fn new(mut gl: glow::Context, window: platform::LogicalSize) -> Result<Context, Error> {
177 +
        unsafe {
178 +
            gl.enable(glow::DEBUG_OUTPUT);
179 +
            gl.enable(glow::FRAMEBUFFER_SRGB);
180 +
            gl.debug_message_callback(|_source, _etype, id, severity, message| {
181 +
                let lvl = match severity {
182 +
                    glow::DEBUG_SEVERITY_LOW => log::Level::Debug,
183 +
                    glow::DEBUG_SEVERITY_MEDIUM => log::Level::Warn,
184 +
                    glow::DEBUG_SEVERITY_HIGH => log::Level::Error,
185 +
                    glow::DEBUG_SEVERITY_NOTIFICATION => log::Level::Trace,
186 +
                    _ => log::Level::Debug,
187 +
                };
188 +
                log::log!(target: "gl", lvl,"(id {id}): {message}");
189 +
            });
190 +
            log::info!(target: "gl", "OpenGL {:?}", gl.version());
191 +
192 +
            let vao = gl.create_vertex_array().map_err(Error::Internal)?;
193 +
            gl.bind_vertex_array(Some(vao));
194 +
195 +
            Ok(Context {
196 +
                gl,
197 +
                window,
198 +
                shaders: IntMap::default(),
199 +
                pipelines: IntMap::default(),
200 +
                passes: IntMap::default(),
201 +
                index_buffers: IntMap::default(),
202 +
                vertex_buffers: IntMap::default(),
203 +
                textures: IntMap::default(),
204 +
            })
205 +
        }
206 +
    }
207 +
208 +
    unsafe fn set_blend(&mut self, blend: BlendState) -> Result<(), Error> {
209 +
        if blend.rgb.is_none() && blend.alpha.is_some() {
210 +
            return Err(Error::AlphaBlendWithoutColor);
211 +
        }
212 +
        if let Some(rgb) = blend.rgb {
213 +
            self.gl.enable(glow::BLEND);
214 +
215 +
            let BlendEquation {
216 +
                op: eq_rgb,
217 +
                sfactor: src_rgb,
218 +
                dfactor: dst_rgb,
219 +
            } = rgb;
220 +
221 +
            if let Some(BlendEquation {
222 +
                op: eq_alpha,
223 +
                sfactor: src_alpha,
224 +
                dfactor: dst_alpha,
225 +
            }) = blend.alpha
226 +
            {
227 +
                self.gl.blend_func_separate(
228 +
                    src_rgb.to_gl(),
229 +
                    dst_rgb.to_gl(),
230 +
                    src_alpha.to_gl(),
231 +
                    dst_alpha.to_gl(),
232 +
                );
233 +
                self.gl.blend_equation_separate(eq_rgb.to_gl(), eq_alpha.to_gl());
234 +
            } else {
235 +
                self.gl.blend_func(src_rgb.to_gl(), dst_rgb.to_gl());
236 +
                self.gl.blend_equation_separate(eq_rgb.to_gl(), eq_rgb.to_gl());
237 +
            }
238 +
        } else {
239 +
            self.gl.disable(glow::BLEND);
240 +
        }
241 +
        Ok(())
242 +
    }
243 +
244 +
    unsafe fn set_stencil(&mut self, stencil: Option<StencilState>) {
245 +
        if let Some(stencil) = stencil {
246 +
            let front = &stencil.front;
247 +
            let back = &stencil.back;
248 +
249 +
            self.gl.enable(glow::STENCIL_TEST);
250 +
            self.gl.stencil_op_separate(
251 +
                glow::FRONT,
252 +
                front.fail_op.to_gl(),
253 +
                front.depth_fail_op.to_gl(),
254 +
                front.pass_op.to_gl(),
255 +
            );
256 +
            self.gl.stencil_func_separate(
257 +
                glow::FRONT,
258 +
                front.compare.to_gl(),
259 +
                stencil.reference,
260 +
                stencil.read_mask,
261 +
            );
262 +
            self.gl.stencil_mask_separate(glow::FRONT, stencil.write_mask);
263 +
            self.gl.stencil_op_separate(
264 +
                glow::BACK,
265 +
                back.fail_op.to_gl(),
266 +
                back.depth_fail_op.to_gl(),
267 +
                back.pass_op.to_gl(),
268 +
            );
269 +
            self.gl.stencil_func_separate(
270 +
                glow::BACK,
271 +
                back.compare.to_gl(),
272 +
                stencil.reference,
273 +
                stencil.read_mask,
274 +
            );
275 +
            self.gl.stencil_mask_separate(glow::BACK, stencil.write_mask);
276 +
        } else {
277 +
            self.gl.disable(glow::STENCIL_TEST);
278 +
        }
279 +
    }
280 +
281 +
    unsafe fn set_cull_face(&mut self, cull_face: CullMode) {
282 +
        match cull_face {
283 +
            CullMode::Nothing => {
284 +
                self.gl.disable(glow::CULL_FACE);
285 +
            }
286 +
            CullMode::Front => {
287 +
                self.gl.enable(glow::CULL_FACE);
288 +
                self.gl.cull_face(glow::FRONT);
289 +
            }
290 +
            CullMode::Back => {
291 +
                self.gl.enable(glow::CULL_FACE);
292 +
                self.gl.cull_face(glow::BACK);
293 +
            }
294 +
        }
295 +
    }
296 +
297 +
    unsafe fn set_color_mask(&mut self, mask: Rgba<bool>) {
298 +
        self.gl.color_mask(mask.r, mask.g, mask.b, mask.a);
299 +
    }
300 +
301 +
    unsafe fn load_shader(
302 +
        &self,
303 +
        kind: ShaderKind,
304 +
        source: &str,
305 +
    ) -> Result<glow::Shader, ShaderError> {
306 +
        let shader = self.gl.create_shader(kind.to_gl()).map_err(ShaderError::Internal)?;
307 +
308 +
        self.gl.shader_source(shader, source);
309 +
        self.gl.compile_shader(shader);
310 +
311 +
        if !self.gl.get_shader_compile_status(shader) {
312 +
            let message = self.gl.get_shader_info_log(shader);
313 +
314 +
            return Err(ShaderError::CompilationError { kind, message });
315 +
        }
316 +
        Ok(shader)
317 +
    }
318 +
319 +
    unsafe fn bind_framebuffer(&mut self, framebuffer: Option<glow::Framebuffer>, size: Size<u32>) {
320 +
        self.gl.bind_framebuffer(glow::FRAMEBUFFER, framebuffer);
321 +
        self.gl.viewport(0, 0, size.w as i32, size.h as i32);
322 +
        self.gl.scissor(0, 0, size.w as i32, size.h as i32);
323 +
    }
324 +
}
325 +
326 +
pub struct FrameBuilder<'a> {
327 +
    ctx: &'a mut Context,
328 +
    active: Active,
329 +
}
330 +
331 +
impl Drop for FrameBuilder<'_> {
332 +
    fn drop(&mut self) {
333 +
        unsafe {
334 +
            self.ctx.gl.bind_buffer(BufferKind::Vertex.to_gl(), None);
335 +
            self.ctx.gl.bind_buffer(BufferKind::Index.to_gl(), None);
336 +
        }
337 +
    }
338 +
}
339 +
340 +
impl<'a> RenderFrame<'a> for FrameBuilder<'a> {
341 +
    type Error = Error;
342 +
    type Backend = Context;
343 +
344 +
    fn backend(&self) -> &Self::Backend {
345 +
        self.ctx
346 +
    }
347 +
348 +
    fn backend_mut(&mut self) -> &mut Self::Backend {
349 +
        self.ctx
350 +
    }
351 +
352 +
    fn apply_viewport(&mut self, rect: Rect<i32>) -> Result<(), Error> {
353 +
        unsafe {
354 +
            self.ctx
355 +
                .gl
356 +
                .viewport(rect.origin.x, rect.origin.y, rect.size.w, rect.size.h);
357 +
        }
358 +
        Ok(())
359 +
    }
360 +
361 +
    fn apply_scissor(&mut self, rect: Rect<i32>) -> Result<(), Error> {
362 +
        unsafe {
363 +
            self.ctx
364 +
                .gl
365 +
                .scissor(rect.origin.x, rect.origin.y, rect.size.w, rect.size.h);
366 +
        }
367 +
        Ok(())
368 +
    }
369 +
370 +
    fn apply_pipeline(&mut self, pipeline: &PipelineId) -> Result<(), Error> {
371 +
        let desc = &self.ctx.pipelines[pipeline].clone();
372 +
        let shader = &desc.shader;
373 +
        let shader = &self.ctx.shaders[shader];
374 +
375 +
        unsafe {
376 +
            self.ctx.gl.use_program(Some(shader.program));
377 +
            self.ctx.gl.enable(glow::SCISSOR_TEST);
378 +
379 +
            if let Some(depth) = &desc.depth {
380 +
                self.ctx.gl.enable(glow::DEPTH_TEST);
381 +
                self.ctx.gl.depth_func(depth.compare.to_gl());
382 +
            } else {
383 +
                self.ctx.gl.disable(glow::DEPTH_TEST);
384 +
            }
385 +
        }
386 +
387 +
        unsafe {
388 +
            self.ctx.gl.front_face(desc.winding.to_gl());
389 +
            self.ctx.set_cull_face(desc.culling);
390 +
            self.ctx.set_stencil(desc.stencil);
391 +
392 +
            if let Some(color) = desc.color {
393 +
                self.ctx.set_blend(color.blend)?;
394 +
                self.ctx.set_color_mask(color.mask);
395 +
            }
396 +
        }
397 +
        self.active.pipeline = Some(*pipeline);
398 +
399 +
        Ok(())
400 +
    }
401 +
402 +
    fn apply_bindings<const V: usize, const N: usize>(
403 +
        &mut self,
404 +
        bindings: &Bindings<V, N>,
405 +
    ) -> Result<(), Error> {
406 +
        let pip = self.active.pipeline()?;
407 +
        let pip = &self.ctx.pipelines[&pip];
408 +
        let shader = &self.ctx.shaders[&pip.shader];
409 +
410 +
        // Bind the textures.
411 +
        for (n, img) in shader.textures.iter().enumerate() {
412 +
            let tex = bindings.textures.get(n).ok_or(Error::TextureLayoutMismatch(
413 +
                shader.textures.len(),
414 +
                bindings.textures.len(),
415 +
            ))?;
416 +
417 +
            let tex = &self.ctx.textures[tex];
418 +
            let target = tex.target.to_gl();
419 +
420 +
            unsafe {
421 +
                self.ctx.gl.active_texture(glow::TEXTURE0 + n as u32);
422 +
                self.ctx.gl.bind_texture(target, Some(tex.data));
423 +
                self.ctx.gl.uniform_1_i32(Some(&img.location), n as i32);
424 +
            }
425 +
        }
426 +
        self.active.vertices.clear();
427 +
428 +
        // Bind the vertex buffers.
429 +
        for (attr_index, attribute) in pip.layout.iter().enumerate() {
430 +
            let attr_index = attr_index as u32;
431 +
432 +
            let id = bindings.vertex[attribute.buffer];
433 +
            let vb = self.ctx.vertex_buffers[&id];
434 +
435 +
            unsafe {
436 +
                self.ctx.gl.bind_buffer(BufferKind::Vertex.to_gl(), Some(vb.handle));
437 +
                if attribute.format.is_integer() {
438 +
                    self.ctx.gl.vertex_attrib_pointer_i32(
439 +
                        attribute.location,
440 +
                        attribute.size,
441 +
                        attribute.format.to_gl(),
442 +
                        attribute.stride,
443 +
                        attribute.offset as i32,
444 +
                    );
445 +
                } else {
446 +
                    self.ctx.gl.vertex_attrib_pointer_f32(
447 +
                        attribute.location,
448 +
                        attribute.size,
449 +
                        attribute.format.to_gl(),
450 +
                        false,
451 +
                        attribute.stride,
452 +
                        attribute.offset as i32,
453 +
                    );
454 +
                }
455 +
                self.ctx
456 +
                    .gl
457 +
                    .vertex_attrib_divisor(attr_index, attribute.divisor as u32);
458 +
                self.ctx.gl.enable_vertex_attrib_array(attr_index);
459 +
            }
460 +
            self.active.vertices.push(id);
461 +
            // TODO: Do we need to disable vertex attributes that aren't in use?
462 +
        }
463 +
464 +
        // Bind the index buffer, if any.
465 +
        if let Some(index) = bindings.index {
466 +
            let indices = self.ctx.index_buffers[&index];
467 +
            unsafe {
468 +
                self.ctx
469 +
                    .gl
470 +
                    .bind_buffer(BufferKind::Index.to_gl(), Some(indices.handle))
471 +
            };
472 +
            self.active.indices = Some(index);
473 +
        } else {
474 +
            unsafe { self.ctx.gl.bind_buffer(BufferKind::Index.to_gl(), None) };
475 +
            self.active.indices = None;
476 +
        }
477 +
478 +
        Ok(())
479 +
    }
480 +
481 +
    fn apply_uniforms<T: AsBytes>(&mut self, uniforms: &T) -> Result<(), Error> {
482 +
        let pip = self.pipeline()?;
483 +
        let shader = &self.ctx.shaders[&pip.shader];
484 +
485 +
        {
486 +
            let expected = shader.uniforms.iter().map(|u| u.size()).sum::<usize>();
487 +
            let actual = mem::size_of_val(uniforms);
488 +
            if expected != actual {
489 +
                return Err(Error::UniformSizeMismatch(actual, expected));
490 +
            }
491 +
        }
492 +
        let mut offset = 0;
493 +
494 +
        for uniform in shader.uniforms.iter() {
495 +
            let size = uniform.size();
496 +
            let data = &uniforms.as_bytes()[offset..offset + size];
497 +
498 +
            offset += size;
499 +
500 +
            unsafe {
501 +
                if let Some(loc) = &uniform.location {
502 +
                    use bytes::align_to;
503 +
                    use UniformKind::*;
504 +
505 +
                    match uniform.kind {
506 +
                        Float1 => self.ctx.gl.uniform_1_f32_slice(Some(loc), align_to::<f32>(data)),
507 +
                        Float2 => self.ctx.gl.uniform_2_f32_slice(Some(loc), align_to::<f32>(data)),
508 +
                        Float3 => self.ctx.gl.uniform_3_f32_slice(Some(loc), align_to::<f32>(data)),
509 +
                        Float4 => self.ctx.gl.uniform_4_f32_slice(Some(loc), align_to::<f32>(data)),
510 +
                        Int1 => self.ctx.gl.uniform_1_i32_slice(Some(loc), align_to::<i32>(data)),
511 +
                        Int2 => self.ctx.gl.uniform_2_i32_slice(Some(loc), align_to::<i32>(data)),
512 +
                        Int3 => self.ctx.gl.uniform_3_i32_slice(Some(loc), align_to::<i32>(data)),
513 +
                        Int4 => self.ctx.gl.uniform_4_i32_slice(Some(loc), align_to::<i32>(data)),
514 +
                        UInt1 => self.ctx.gl.uniform_1_u32_slice(Some(loc), align_to::<u32>(data)),
515 +
                        UInt2 => self.ctx.gl.uniform_2_u32_slice(Some(loc), align_to::<u32>(data)),
516 +
                        UInt3 => self.ctx.gl.uniform_3_u32_slice(Some(loc), align_to::<u32>(data)),
517 +
                        UInt4 => self.ctx.gl.uniform_4_u32_slice(Some(loc), align_to::<u32>(data)),
518 +
                        Mat4 => self.ctx.gl.uniform_matrix_4_f32_slice(
519 +
                            Some(loc),
520 +
                            false,
521 +
                            align_to::<f32>(data),
522 +
                        ),
523 +
                    }
524 +
                }
525 +
            }
526 +
        }
527 +
528 +
        Ok(())
529 +
    }
530 +
531 +
    fn clear(&mut self, color: Option<Rgba<f32>>, depth: Option<f32>, stencil: Option<i32>) {
532 +
        let mut bits = 0;
533 +
        if let Some(color) = color {
534 +
            bits |= glow::COLOR_BUFFER_BIT;
535 +
            unsafe {
536 +
                self.ctx.gl.clear_color(color.r, color.g, color.b, color.a);
537 +
            }
538 +
        }
539 +
540 +
        if let Some(v) = depth {
541 +
            bits |= glow::DEPTH_BUFFER_BIT;
542 +
            unsafe {
543 +
                self.ctx.gl.clear_depth_f32(v);
544 +
            }
545 +
        }
546 +
547 +
        if let Some(v) = stencil {
548 +
            bits |= glow::STENCIL_BUFFER_BIT;
549 +
            unsafe {
550 +
                self.ctx.gl.clear_stencil(v);
551 +
            }
552 +
        }
553 +
554 +
        if bits != 0 {
555 +
            unsafe {
556 +
                self.ctx.gl.clear(bits);
557 +
            }
558 +
        }
559 +
    }
560 +
561 +
    fn buffer_update<T: Packed>(
562 +
        &mut self,
563 +
        buffer: BufferId,
564 +
        kind: BufferKind,
565 +
        offset: usize,
566 +
        data: &[T],
567 +
    ) -> Result<(), Self::Error> {
568 +
        self.ctx.buffer_update(buffer, kind, offset, data)
569 +
    }
570 +
571 +
    fn begin_default_pass(&mut self, action: PassAction, size: impl Into<Size<u32>>) {
572 +
        unsafe { self.ctx.bind_framebuffer(None, size.into()) }
573 +
        match action {
574 +
            PassAction::Nothing => {}
575 +
            PassAction::Clear {
576 +
                color,
577 +
                depth,
578 +
                stencil,
579 +
            } => {
580 +
                self.clear(color, depth, stencil);
581 +
            }
582 +
        }
583 +
    }
584 +
585 +
    fn begin_pass(&mut self, pass: PassId, action: PassAction) {
586 +
        let p = &self.ctx.passes[&pass];
587 +
588 +
        unsafe { self.ctx.bind_framebuffer(Some(p.fb), p.size) }
589 +
        match action {
590 +
            PassAction::Nothing => {}
591 +
            PassAction::Clear {
592 +
                color,
593 +
                depth,
594 +
                stencil,
595 +
            } => {
596 +
                self.clear(color, depth, stencil);
597 +
            }
598 +
        }
599 +
        self.active.pass = Some(pass);
600 +
    }
601 +
602 +
    fn end_pass(&mut self) {
603 +
        unsafe {
604 +
            self.ctx.gl.bind_framebuffer(glow::FRAMEBUFFER, None);
605 +
            self.ctx.gl.bind_buffer(BufferKind::Vertex.to_gl(), None);
606 +
            self.ctx.gl.bind_buffer(BufferKind::Index.to_gl(), None);
607 +
        }
608 +
        self.active.vertices.clear();
609 +
        self.active.indices = None;
610 +
        self.active.pass = None;
611 +
    }
612 +
613 +
    fn draw(&self, offset: usize, elements: usize, instances: usize) -> Result<(), Error> {
614 +
        let pip = self.pipeline()?;
615 +
        let pass = self.pass();
616 +
        let primitive_type = pip.primitive.to_gl();
617 +
618 +
        if let Ok(p) = pass {
619 +
            let buffers = (0..p.colors.len())
620 +
                .map(|i| glow::COLOR_ATTACHMENT0 + i as u32)
621 +
                .collect::<Vec<_>>();
622 +
            unsafe { self.ctx.gl.draw_buffers(&buffers) };
623 +
        } else {
624 +
            unsafe { self.ctx.gl.draw_buffers(&[glow::BACK]) };
625 +
        }
626 +
627 +
        if let Some(idx) = self.active.indices {
628 +
            let indices = self.ctx.index_buffers[&idx];
629 +
            if elements > indices.size {
630 +
                return Err(Error::InvalidIndexElementCount(elements));
631 +
            }
632 +
            unsafe {
633 +
                self.ctx.gl.draw_elements_instanced(
634 +
                    primitive_type,
635 +
                    elements as i32,
636 +
                    indices.elem.to_gl(),
637 +
                    indices.elem.size() as i32 * offset as i32,
638 +
                    instances as i32,
639 +
                );
640 +
            }
641 +
        } else {
642 +
            unsafe {
643 +
                self.ctx.gl.draw_arrays(primitive_type, 0, elements as i32);
644 +
            }
645 +
        }
646 +
        Ok(())
647 +
    }
648 +
649 +
    fn commit(self) {
650 +
        drop(self)
651 +
    }
652 +
}
653 +
654 +
impl FrameBuilder<'_> {
655 +
    fn pipeline(&self) -> Result<&Pipeline, Error> {
656 +
        let id = self.active.pipeline.ok_or(Error::NoActivePipeline)?;
657 +
        Ok(&self.ctx.pipelines[&id])
658 +
    }
659 +
660 +
    fn pass(&self) -> Result<&Pass, Error> {
661 +
        let id = self.active.pass.ok_or(Error::NoActivePass)?;
662 +
        Ok(&self.ctx.passes[&id])
663 +
    }
664 +
}
665 +
666 +
impl RenderBackend for Context {
667 +
    type Info = ContextInfo;
668 +
    type Frame<'a> = FrameBuilder<'a>;
669 +
    type Error = Error;
670 +
    type TextureHandle = glow::Texture;
671 +
672 +
    fn info(&self) -> ContextInfo {
673 +
        let version = self.gl.version().clone();
674 +
        ContextInfo { version }
675 +
    }
676 +
677 +
    fn frame(&mut self) -> FrameBuilder<'_> {
678 +
        FrameBuilder {
679 +
            ctx: self,
680 +
            active: Active::default(),
681 +
        }
682 +
    }
683 +
684 +
    fn shader(
685 +
        &mut self,
686 +
        shader: ShaderSource<'_>,
687 +
        meta: ShaderDescriptor<'_>,
688 +
    ) -> Result<ShaderId, Error> {
689 +
        let vertex_shader = shader.vertex;
690 +
        let fragment_shader = shader.fragment;
691 +
        let geometry_shader = shader.geometry;
692 +
        let shader = unsafe {
693 +
            let program = self.gl.create_program().map_err(ShaderError::Internal)?;
694 +
            let vertex_shader = self.load_shader(ShaderKind::Vertex, vertex_shader)?;
695 +
            self.gl.attach_shader(program, vertex_shader);
696 +
697 +
            let fragment_shader = self.load_shader(ShaderKind::Fragment, fragment_shader)?;
698 +
            self.gl.attach_shader(program, fragment_shader);
699 +
700 +
            if let Some(shader) = geometry_shader {
701 +
                let shader = self.load_shader(ShaderKind::Geometry, shader)?;
702 +
                self.gl.attach_shader(program, shader);
703 +
            }
704 +
            self.gl.link_program(program);
705 +
706 +
            if !self.gl.get_program_link_status(program) {
707 +
                let error = self.gl.get_program_info_log(program);
708 +
                return Err(Error::from(ShaderError::LinkError(error)));
709 +
            }
710 +
            self.gl.use_program(Some(program));
711 +
712 +
            let textures = meta
713 +
                .textures
714 +
                .iter()
715 +
                .map(|name| {
716 +
                    self.gl
717 +
                        .get_uniform_location(program, name)
718 +
                        .ok_or_else(|| Error::MissingUniform((*name).to_owned()))
719 +
                        .map(|location| ShaderTexture { location })
720 +
                })
721 +
                .collect::<Result<Vec<_>, Error>>()?;
722 +
723 +
            let uniforms = meta
724 +
                .uniforms
725 +
                .uniforms
726 +
                .iter()
727 +
                .scan(0, |offset, uniform| {
728 +
                    let res = ShaderUniform {
729 +
                        location: self.gl.get_uniform_location(program, uniform.name),
730 +
                        kind: uniform.kind,
731 +
                        arity: uniform.arity as _,
732 +
                    };
733 +
                    *offset += uniform.kind.size() * uniform.arity;
734 +
                    Some(res)
735 +
                })
736 +
                .collect();
737 +
738 +
            Ok::<_, Error>(Shader {
739 +
                program,
740 +
                textures,
741 +
                uniforms,
742 +
            })
743 +
        }?;
744 +
        let id = ShaderId::next();
745 +
746 +
        log::debug!(
747 +
            target: "gl",
748 +
            "created shader program {id}, handle {:?}",
749 +
            shader.program
750 +
        );
751 +
        self.shaders.insert(id, shader);
752 +
753 +
        Ok(id)
754 +
    }
755 +
756 +
    fn texture<T: TextureData>(&mut self, texture: Texture<T>) -> Result<TextureId, Error> {
757 +
        let Texture {
758 +
            data,
759 +
            size,
760 +
            access,
761 +
            target,
762 +
            format,
763 +
            wrap,
764 +
            min_filter,
765 +
            mag_filter,
766 +
        } = texture;
767 +
768 +
        let source = data.as_bytes();
769 +
        let source = if source.is_empty() {
770 +
            None
771 +
        } else {
772 +
            Some(source)
773 +
        };
774 +
        let length = format.size(size) as usize;
775 +
776 +
        match target {
777 +
            TextureKind::Texture2D => {
778 +
                if let Some(source) = source {
779 +
                    if length != source.len() {
780 +
                        return Err(Error::TextureSizeMismatch(length, source.len()));
781 +
                    }
782 +
                }
783 +
            }
784 +
            TextureKind::Texture2DArray { arity: _arity } => {
785 +
                // TODO: Check here.
786 +
            }
787 +
        }
788 +
789 +
        // TODO: Switch to bindless `glTextureParameteri`.
790 +
        let (internal_format, gl_format, pixel_type) = format.into();
791 +
        let wrap = wrap.to_gl() as i32;
792 +
        let min_filter = min_filter.to_gl() as i32;
793 +
        let mag_filter = mag_filter.to_gl() as i32;
794 +
        let handle = unsafe {
795 +
            let texture = self.gl.create_texture().map_err(Error::Internal)?;
796 +
797 +
            self.gl.active_texture(glow::TEXTURE0);
798 +
            self.gl.bind_texture(target.to_gl(), Some(texture));
799 +
800 +
            assert!(self.gl.is_texture(texture));
801 +
802 +
            // Allow any type of alignment for texture buffers.
803 +
            self.gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, 1);
804 +
805 +
            match target {
806 +
                TextureKind::Texture2D => {
807 +
                    self.gl.tex_image_2d(
808 +
                        target.to_gl(),
809 +
                        0,
810 +
                        internal_format as i32,
811 +
                        size.w as i32,
812 +
                        size.h as i32,
813 +
                        0,
814 +
                        gl_format,
815 +
                        pixel_type,
816 +
                        source,
817 +
                    );
818 +
                }
819 +
                TextureKind::Texture2DArray { arity } => {
820 +
                    self.gl.tex_image_3d(
821 +
                        target.to_gl(),
822 +
                        0,
823 +
                        internal_format as i32,
824 +
                        size.w as i32,
825 +
                        size.h as i32,
826 +
                        arity as i32,
827 +
                        0,
828 +
                        gl_format,
829 +
                        pixel_type,
830 +
                        source,
831 +
                    );
832 +
                }
833 +
            }
834 +
            self.gl.tex_parameter_i32(target.to_gl(), glow::TEXTURE_WRAP_S, wrap);
835 +
            self.gl.tex_parameter_i32(target.to_gl(), glow::TEXTURE_WRAP_T, wrap);
836 +
            self.gl
837 +
                .tex_parameter_i32(target.to_gl(), glow::TEXTURE_MIN_FILTER, min_filter);
838 +
            self.gl
839 +
                .tex_parameter_i32(target.to_gl(), glow::TEXTURE_MAG_FILTER, mag_filter);
840 +
841 +
            texture
842 +
        };
843 +
        let id = TextureId::next();
844 +
845 +
        log::debug!(
846 +
            target: "gl",
847 +
            "created texture {id} with size {size}, format {format:?}, target {target:?}, handle {handle:?}",
848 +
        );
849 +
        self.textures.insert(
850 +
            id,
851 +
            Texture {
852 +
                data: handle,
853 +
                size,
854 +
                access,
855 +
                target,
856 +
                format: texture.format,
857 +
                wrap: texture.wrap,
858 +
                min_filter: texture.min_filter,
859 +
                mag_filter: texture.mag_filter,
860 +
            },
861 +
        );
862 +
        Ok(id)
863 +
    }
864 +
865 +
    fn texture_delete(&mut self, id: TextureId) {
866 +
        if let Some(t) = self.textures.remove(&id) {
867 +
            unsafe { self.gl.delete_texture(t.data) };
868 +
        }
869 +
    }
870 +
871 +
    fn texture_set_wrap(&mut self, texture: TextureId, wrap: TextureWrap) {
872 +
        let t = &self.textures[&texture];
873 +
        let target = t.target.to_gl();
874 +
        let wrap = wrap.to_gl() as i32;
875 +
876 +
        unsafe {
877 +
            self.gl.bind_texture(target, Some(t.data));
878 +
            self.gl.tex_parameter_i32(target, glow::TEXTURE_WRAP_S, wrap);
879 +
            self.gl.tex_parameter_i32(target, glow::TEXTURE_WRAP_T, wrap);
880 +
            self.gl.bind_texture(target, None);
881 +
        }
882 +
    }
883 +
884 +
    fn texture_set_min_filter(&mut self, texture: TextureId, filter: FilterMode) {
885 +
        let t = &self.textures[&texture];
886 +
        let filter = filter.to_gl();
887 +
        let target = t.target.to_gl();
888 +
889 +
        unsafe {
890 +
            self.gl.bind_texture(target, Some(t.data));
891 +
            self.gl
892 +
                .tex_parameter_i32(target, glow::TEXTURE_MIN_FILTER, filter as i32);
893 +
            self.gl.bind_texture(target, None);
894 +
        }
895 +
    }
896 +
897 +
    fn texture_set_mag_filter(&mut self, texture: TextureId, filter: FilterMode) {
898 +
        let t = &self.textures[&texture];
899 +
        let filter = filter.to_gl();
900 +
        let target = t.target.to_gl();
901 +
902 +
        unsafe {
903 +
            self.gl.bind_texture(target, Some(t.data));
904 +
            self.gl
905 +
                .tex_parameter_i32(target, glow::TEXTURE_MAG_FILTER, filter as i32);
906 +
            self.gl.bind_texture(target, None);
907 +
        }
908 +
    }
909 +
910 +
    fn texture_resize(
911 +
        &mut self,
912 +
        texture: TextureId,
913 +
        size: Size<u32>,
914 +
        source: &[color::Rgba8],
915 +
    ) -> Result<(), Error> {
916 +
        let t = self
917 +
            .textures
918 +
            .get_mut(&texture)
919 +
            .ok_or(Error::TextureNotFound(texture))?;
920 +
        let target = t.target.to_gl();
921 +
922 +
        assert!(
923 +
            t.target == TextureKind::Texture2D,
924 +
            "RenderBackend::texture_resize: can only be used with textures of kind `Texture2D`"
925 +
        );
926 +
        t.size = size;
927 +
928 +
        let (internal_format, format, pixel_type) = t.format.into();
929 +
        log::debug!(target: "gl", "resizing texture {texture} to {size} with target {:?}", t.target);
930 +
931 +
        unsafe {
932 +
            self.gl.bind_texture(target, Some(t.data));
933 +
            self.gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, 1);
934 +
            self.gl.tex_image_2d(
935 +
                target,
936 +
                0,
937 +
                internal_format as i32,
938 +
                t.size.w as i32,
939 +
                t.size.h as i32,
940 +
                0,
941 +
                format,
942 +
                pixel_type,
943 +
                if source.is_empty() {
944 +
                    None
945 +
                } else {
946 +
                    Some(source.as_bytes())
947 +
                },
948 +
            );
949 +
            self.gl.bind_texture(target, None);
950 +
        }
951 +
        Ok(())
952 +
    }
953 +
954 +
    fn texture_update(
955 +
        &mut self,
956 +
        texture: TextureId,
957 +
        area: Rect<u32>,
958 +
        source: &[color::Rgba8],
959 +
    ) -> Result<(), Error> {
960 +
        let t = &self.textures[&texture];
961 +
        let bytes = t.format.size(area.size);
962 +
        let (_, format, pixel_type) = t.format.into();
963 +
        let target = t.target.to_gl();
964 +
965 +
        // TODO: Convert to errors.
966 +
        assert!(
967 +
            t.target == TextureKind::Texture2D,
968 +
            "RenderBackend::texture_update: can only be used with textures of kind `Texture2D`"
969 +
        );
970 +
        assert_eq!(bytes as usize, mem::size_of_val(source));
971 +
        assert!(area.origin.x + area.width() <= t.size.w as _);
972 +
        assert!(area.origin.y + area.height() <= t.size.h as _);
973 +
974 +
        unsafe {
975 +
            self.gl.bind_texture(target, Some(t.data));
976 +
            self.gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, 1);
977 +
            self.gl.tex_sub_image_2d(
978 +
                target,
979 +
                0,
980 +
                area.origin.x as _,
981 +
                area.origin.y as _,
982 +
                area.width() as _,
983 +
                area.height() as _,
984 +
                format,
985 +
                pixel_type,
986 +
                glow::PixelUnpackData::Slice(source.as_bytes()),
987 +
            );
988 +
            self.gl.bind_texture(target, None);
989 +
        }
990 +
        Ok(())
991 +
    }
992 +
993 +
    fn texture_update_layer(
994 +
        &mut self,
995 +
        texture: TextureId,
996 +
        layer: u8,
997 +
        area: Rect<u32>,
998 +
        source: &[color::Rgba8],
999 +
    ) -> Result<(), Error> {
1000 +
        let t = &self.textures[&texture];
1001 +
        let bytes = t.format.size(area.size);
1002 +
        let (_, format, pixel_type) = t.format.into();
1003 +
1004 +
        assert!(
1005 +
            matches!(t.target, TextureKind::Texture2DArray { .. }),
1006 +
            "RenderBackend::texture_update_layer: can only be used with textures of kind `Texture2DArray`"
1007 +
        );
1008 +
        assert_eq!(bytes as usize, mem::size_of_val(source));
1009 +
        assert!(
1010 +
            area.origin.x + area.width() <= t.size.w as _,
1011 +
            "rect {area} is not contained in {}",
1012 +
            t.size
1013 +
        );
1014 +
        assert!(area.origin.y + area.height() <= t.size.h as _);
1015 +
1016 +
        unsafe {
1017 +
            self.gl.bind_texture(glow::TEXTURE_2D_ARRAY, Some(t.data));
1018 +
            self.gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, 1);
1019 +
            self.gl.tex_sub_image_3d(
1020 +
                glow::TEXTURE_2D_ARRAY,
1021 +
                0,                  // mipmap level
1022 +
                area.origin.x as _, // xoffset
1023 +
                area.origin.y as _, // yoffset
1024 +
                layer as _,         // zoffset (layer)
1025 +
                area.width() as _,  // width
1026 +
                area.height() as _, // height
1027 +
                1,                  // depth (number of layers to update)
1028 +
                format,
1029 +
                pixel_type,
1030 +
                glow::PixelUnpackData::Slice(source.as_bytes()),
1031 +
            );
1032 +
            self.gl.bind_texture(glow::TEXTURE_2D_ARRAY, None);
1033 +
1034 +
            log::debug!(
1035 +
                target: "gl",
1036 +
                "updated layer {layer} of texture {texture}, area: {area}",
1037 +
            );
1038 +
        }
1039 +
        Ok(())
1040 +
    }
1041 +
1042 +
    fn textures(&self) -> &IntMap<TextureId, Texture<Self::TextureHandle>> {
1043 +
        &self.textures
1044 +
    }
1045 +
1046 +
    fn pass(&mut self, desc: PassDescriptor<'_>) -> Result<PassId, Error> {
1047 +
        let colors = desc.color_attachments.iter().map(|t| &self.textures[t]);
1048 +
        let depth = desc.depth_attachment.map(|t| &self.textures[&t]);
1049 +
1050 +
        let mut sizes = colors.clone().map(|t| t.size).chain(depth.map(|t| t.size));
1051 +
        let size = match sizes.next() {
1052 +
            None => return Err(Error::MissingAttachment),
1053 +
            Some(size) => {
1054 +
                if !sizes.all(|s| s == size) {
1055 +
                    return Err(Error::AttachmentSizeMismatch);
1056 +
                } else {
1057 +
                    size
1058 +
                }
1059 +
            }
1060 +
        };
1061 +
1062 +
        let (fb, status) = unsafe {
1063 +
            let fb = self.gl.create_framebuffer().map_err(Error::Internal)?;
1064 +
            self.gl.bind_framebuffer(glow::FRAMEBUFFER, Some(fb));
1065 +
            self.gl.viewport(0, 0, size.w as i32, size.h as i32);
1066 +
1067 +
            for (ix, texture) in colors.enumerate() {
1068 +
                self.gl.framebuffer_texture_2d(
1069 +
                    glow::FRAMEBUFFER,
1070 +
                    glow::COLOR_ATTACHMENT0 + ix as u32,
1071 +
                    glow::TEXTURE_2D,
1072 +
                    Some(texture.data),
1073 +
                    0,
1074 +
                );
1075 +
            }
1076 +
            if let Some(t) = depth {
1077 +
                self.gl.framebuffer_texture_2d(
1078 +
                    glow::FRAMEBUFFER,
1079 +
                    glow::DEPTH_ATTACHMENT,
1080 +
                    glow::TEXTURE_2D,
1081 +
                    Some(t.data),
1082 +
                    0,
1083 +
                );
1084 +
            }
1085 +
            (fb, self.gl.check_framebuffer_status(glow::FRAMEBUFFER))
1086 +
        };
1087 +
1088 +
        if status != glow::FRAMEBUFFER_COMPLETE {
1089 +
            return Err(Error::IncompleteFramebuffer(status));
1090 +
        }
1091 +
        unsafe { self.gl.bind_framebuffer(glow::FRAMEBUFFER, None) };
1092 +
1093 +
        let id = PassId::next();
1094 +
        let pass = Pass {
1095 +
            fb,
1096 +
            colors: desc.color_attachments.to_owned(),
1097 +
            depth: desc.depth_attachment,
1098 +
            size,
1099 +
        };
1100 +
        self.passes.insert(id, pass);
1101 +
1102 +
        Ok(id)
1103 +
    }
1104 +
1105 +
    fn pass_resize_attachments(
1106 +
        &mut self,
1107 +
        pass: PassId,
1108 +
        size: Size<u32>,
1109 +
    ) -> Result<(), Self::Error> {
1110 +
        let p = self.passes.get(&pass).ok_or(Error::PassNotFound(pass))?.clone();
1111 +
1112 +
        for texture in &p.colors {
1113 +
            self.texture_resize(*texture, size, &[])?;
1114 +
        }
1115 +
        if let Some(texture) = p.depth {
1116 +
            self.texture_resize(texture, size, &[])?;
1117 +
        }
1118 +
1119 +
        // TODO: Unify with pass creation code.
1120 +
        unsafe {
1121 +
            self.gl.bind_framebuffer(glow::FRAMEBUFFER, Some(p.fb));
1122 +
            self.gl.viewport(0, 0, size.w as i32, size.h as i32);
1123 +
1124 +
            for (ix, texture) in p.colors.iter().enumerate() {
1125 +
                let t = &self.textures[texture];
1126 +
                self.gl.framebuffer_texture_2d(
1127 +
                    glow::FRAMEBUFFER,
1128 +
                    glow::COLOR_ATTACHMENT0 + ix as u32,
1129 +
                    glow::TEXTURE_2D,
1130 +
                    Some(t.data),
1131 +
                    0,
1132 +
                );
1133 +
            }
1134 +
            if let Some(texture) = p.depth {
1135 +
                let t = &self.textures[&texture];
1136 +
                self.gl.framebuffer_texture_2d(
1137 +
                    glow::FRAMEBUFFER,
1138 +
                    glow::DEPTH_ATTACHMENT,
1139 +
                    glow::TEXTURE_2D,
1140 +
                    Some(t.data),
1141 +
                    0,
1142 +
                );
1143 +
            }
1144 +
1145 +
            let status = self.gl.check_framebuffer_status(glow::FRAMEBUFFER);
1146 +
            if status != glow::FRAMEBUFFER_COMPLETE {
1147 +
                return Err(Error::IncompleteFramebuffer(status));
1148 +
            }
1149 +
            self.gl.bind_framebuffer(glow::FRAMEBUFFER, None);
1150 +
        }
1151 +
        self.passes.get_mut(&pass).ok_or(Error::PassNotFound(pass))?.size = size;
1152 +
1153 +
        Ok(())
1154 +
    }
1155 +
1156 +
    fn pass_delete(&mut self, pass: PassId) {
1157 +
        if let Some(pass) = &self.passes.remove(&pass) {
1158 +
            unsafe { self.gl.delete_framebuffer(pass.fb) };
1159 +
1160 +
            for color_texture in &pass.colors {
1161 +
                if let Some(t) = self.textures.remove(color_texture) {
1162 +
                    unsafe { self.gl.delete_texture(t.data) };
1163 +
                }
1164 +
            }
1165 +
            if let Some(depth_texture) = pass.depth {
1166 +
                if let Some(t) = self.textures.remove(&depth_texture) {
1167 +
                    unsafe { self.gl.delete_texture(t.data) };
1168 +
                }
1169 +
            }
1170 +
        }
1171 +
    }
1172 +
1173 +
    fn pipeline(
1174 +
        &mut self,
1175 +
        shader: ShaderId,
1176 +
        desc: PipelineDescriptor<'_>,
1177 +
    ) -> Result<PipelineId, Error> {
1178 +
        let program = self.shaders[&shader].program;
1179 +
        let mut internal: Vec<VertexAttributeInternal> = Vec::new();
1180 +
1181 +
        for (buffer, layout) in desc.layout.iter().enumerate() {
1182 +
            let stride = layout.attrs.iter().map(|a| a.format.size()).sum::<usize>();
1183 +
            let mut offset: i64 = 0;
1184 +
1185 +
            for VertexAttribute { name, format } in layout.attrs {
1186 +
                let location = unsafe { self.gl.get_attrib_location(program, name) }
1187 +
                    .ok_or_else(|| Error::MissingShaderAttribute((*name).to_owned()))?;
1188 +
                let stride = layout.stride.unwrap_or(stride) as i32;
1189 +
                let divisor = if layout.step == VertexStep::PerVertex {
1190 +
                    0
1191 +
                } else {
1192 +
                    layout.step_rate
1193 +
                };
1194 +
1195 +
                internal.push(VertexAttributeInternal {
1196 +
                    location,
1197 +
                    size: format.components() as i32,
1198 +
                    format: *format,
1199 +
                    offset,
1200 +
                    stride,
1201 +
                    divisor,
1202 +
                    buffer,
1203 +
                });
1204 +
                offset += format.size() as i64
1205 +
            }
1206 +
        }
1207 +
1208 +
        let id = PipelineId::next();
1209 +
        let pipeline = Pipeline {
1210 +
            layout: internal,
1211 +
            shader,
1212 +
            culling: desc.culling,
1213 +
            winding: desc.winding,
1214 +
            depth: desc.depth,
1215 +
            color: desc.color,
1216 +
            stencil: desc.stencil,
1217 +
            primitive: desc.primitive,
1218 +
        };
1219 +
        self.pipelines.insert(id, pipeline);
1220 +
1221 +
        Ok(id)
1222 +
    }
1223 +
1224 +
    fn pass_read_color_attachment<T>(
1225 +
        &self,
1226 +
        pass: PassId,
1227 +
        attachment: usize,
1228 +
        mut colors: &mut [T],
1229 +
    ) -> Result<(), Error> {
1230 +
        let pass = &self.passes[&pass];
1231 +
        let Some(a) = pass.colors.get(attachment) else {
1232 +
            return Err(Error::MissingColorAttachment);
1233 +
        };
1234 +
        let tex = &self.textures[a];
1235 +
        let (_, format, pixel_type) = tex.format.into();
1236 +
1237 +
        unsafe {
1238 +
            self.gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(pass.fb));
1239 +
            self.gl.viewport(0, 0, pass.size.w as i32, pass.size.h as i32);
1240 +
            self.gl.read_buffer(glow::COLOR_ATTACHMENT0 + attachment as u32);
1241 +
            self.gl.read_pixels(
1242 +
                0,
1243 +
                0,
1244 +
                tex.size.w as _,
1245 +
                tex.size.h as _,
1246 +
                format,
1247 +
                pixel_type,
1248 +
                glow::PixelPackData::Slice(colors.as_bytes_mut()),
1249 +
            );
1250 +
            self.gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None);
1251 +
        }
1252 +
        Ok(())
1253 +
    }
1254 +
1255 +
    fn pass_read_depth_attachment(
1256 +
        &self,
1257 +
        pass: PassId,
1258 +
        mut colors: &mut [f32],
1259 +
    ) -> Result<(), Error> {
1260 +
        let pass = &self.passes[&pass];
1261 +
        let Some(a) = pass.depth else {
1262 +
            return Err(Error::MissingDepthAttachment);
1263 +
        };
1264 +
        let tex = &self.textures[&a];
1265 +
        let (_, format, pixel_type) = tex.format.into();
1266 +
1267 +
        unsafe {
1268 +
            self.gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(pass.fb));
1269 +
            self.gl.viewport(0, 0, pass.size.w as i32, pass.size.h as i32);
1270 +
            self.gl.read_pixels(
1271 +
                0,
1272 +
                0,
1273 +
                tex.size.w as _,
1274 +
                tex.size.h as _,
1275 +
                format,
1276 +
                pixel_type,
1277 +
                glow::PixelPackData::Slice(colors.as_bytes_mut()),
1278 +
            );
1279 +
            self.gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None);
1280 +
        }
1281 +
        Ok(())
1282 +
    }
1283 +
1284 +
    fn buffer<T: Packed>(
1285 +
        &mut self,
1286 +
        kind: BufferKind,
1287 +
        usage: BufferUsage,
1288 +
        data: BufferSource<'_, T>,
1289 +
    ) -> Result<BufferId, Error> {
1290 +
        let size = match &data {
1291 +
            BufferSource::Slice(data) => mem::size_of_val(*data),
1292 +
            BufferSource::Empty { size, .. } => *size,
1293 +
            BufferSource::Zero { size, .. } => *size,
1294 +
        };
1295 +
        let handle = unsafe {
1296 +
            let target = kind.to_gl();
1297 +
            let handle = self.gl.create_buffer().map_err(Error::Internal)?;
1298 +
1299 +
            self.gl.bind_buffer(target, Some(handle));
1300 +
1301 +
            match data {
1302 +
                BufferSource::Slice(data) => {
1303 +
                    self.gl.buffer_data_size(target, size as _, usage.to_gl());
1304 +
                    self.gl.buffer_sub_data_u8_slice(target, 0, data.as_bytes());
1305 +
                }
1306 +
                BufferSource::Empty { .. } => {
1307 +
                    self.gl.buffer_data_size(target, size as _, usage.to_gl());
1308 +
                }
1309 +
                BufferSource::Zero { .. } => {
1310 +
                    self.gl
1311 +
                        .buffer_data_u8_slice(target, vec![0u8; size].as_slice(), usage.to_gl());
1312 +
                }
1313 +
            }
1314 +
            handle
1315 +
        };
1316 +
        let id = BufferId::next();
1317 +
        match kind {
1318 +
            BufferKind::Vertex => {
1319 +
                self.vertex_buffers.insert(id, VertexBuffer { handle, size });
1320 +
            }
1321 +
            BufferKind::Index => {
1322 +
                let elem = ElementSize::try_from(mem::size_of::<T>())
1323 +
                    .map_err(Error::InvalidIndexElementSize)?;
1324 +
                self.index_buffers.insert(id, IndexBuffer { handle, size, elem });
1325 +
            }
1326 +
        }
1327 +
        log::debug!(
1328 +
            target: "gl",
1329 +
            "created buffer {id} of size {size}, kind {kind:?}, usage {usage:?}, handle {handle:?}",
1330 +
        );
1331 +
1332 +
        Ok(id)
1333 +
    }
1334 +
1335 +
    fn buffer_update<T: Packed>(
1336 +
        &mut self,
1337 +
        buffer: BufferId,
1338 +
        kind: BufferKind,
1339 +
        offset: usize,
1340 +
        data: &[T],
1341 +
    ) -> Result<(), Error> {
1342 +
        let offset = offset * mem::size_of::<T>();
1343 +
        let (handle, size) = match kind {
1344 +
            BufferKind::Index => {
1345 +
                let b = self.index_buffers[&buffer];
1346 +
                (b.handle, b.size)
1347 +
            }
1348 +
            BufferKind::Vertex => {
1349 +
                let b = self.vertex_buffers[&buffer];
1350 +
                (b.handle, b.size)
1351 +
            }
1352 +
        };
1353 +
        if offset >= size {
1354 +
            return Err(Error::InvalidBufferOffset(offset));
1355 +
        }
1356 +
        if offset + mem::size_of_val(data) > size {
1357 +
            return Err(Error::InvalidBufferDataSize(mem::size_of_val(data), size));
1358 +
        }
1359 +
1360 +
        let target = kind.to_gl();
1361 +
        unsafe {
1362 +
            self.gl.bind_buffer(target, Some(handle));
1363 +
            self.gl
1364 +
                .buffer_sub_data_u8_slice(target, offset as i32, data.as_bytes());
1365 +
            self.gl.bind_buffer(target, None);
1366 +
        }
1367 +
        Ok(())
1368 +
    }
1369 +
1370 +
    fn buffer_delete(&mut self, id: BufferId, kind: BufferKind) {
1371 +
        match kind {
1372 +
            BufferKind::Index => {
1373 +
                if let Some(buf) = self.index_buffers.remove(&id) {
1374 +
                    unsafe { self.gl.delete_buffer(buf.handle) };
1375 +
                }
1376 +
            }
1377 +
            BufferKind::Vertex => {
1378 +
                if let Some(buf) = self.vertex_buffers.remove(&id) {
1379 +
                    unsafe { self.gl.delete_buffer(buf.handle) };
1380 +
                }
1381 +
            }
1382 +
        }
1383 +
    }
1384 +
}
1385 +
1386 +
impl EventHandlerBackend for Context {
1387 +
    fn window_resized(&mut self, size: platform::LogicalSize) {
1388 +
        self.window = size;
1389 +
    }
1390 +
}
ombre/src/gfx/gl/error.rs added +112 -0
1 +
//! OpenGL backend errors.
2 +
use crate::gfx::{PassId, ShaderError, TextureId};
3 +
4 +
/// OpenGL backend error.
5 +
#[derive(Debug)]
6 +
pub enum Error {
7 +
    NoActivePipeline,
8 +
    NoActivePass,
9 +
    IncompleteFramebuffer(u32),
10 +
    InvalidIndexElementSize(usize),
11 +
    InvalidIndexElementCount(usize),
12 +
    InvalidBufferDataSize(usize, usize),
13 +
    InvalidBufferOffset(usize),
14 +
    MissingShaderAttribute(String),
15 +
    MissingColorAttachment,
16 +
    MissingDepthAttachment,
17 +
    MissingAttachment,
18 +
    MissingUniform(String),
19 +
    AttachmentSizeMismatch,
20 +
    AlphaBlendWithoutColor,
21 +
    TextureLayoutMismatch(usize, usize),
22 +
    TextureSizeMismatch(usize, usize),
23 +
    TextureNotFound(TextureId),
24 +
    PassNotFound(PassId),
25 +
    Shader(ShaderError),
26 +
    UniformSizeMismatch(usize, usize),
27 +
    Internal(String),
28 +
}
29 +
30 +
impl From<ShaderError> for Error {
31 +
    fn from(e: ShaderError) -> Self {
32 +
        Self::Shader(e)
33 +
    }
34 +
}
35 +
36 +
impl std::fmt::Display for Error {
37 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38 +
        match self {
39 +
            Self::NoActivePipeline => {
40 +
                write!(f, "this operation requires an active pipeline")
41 +
            }
42 +
            Self::NoActivePass => {
43 +
                write!(f, "this operation requires an active pass")
44 +
            }
45 +
            Self::MissingAttachment => {
46 +
                write!(
47 +
                    f,
48 +
                    "render pass should have at least one render target specified"
49 +
                )
50 +
            }
51 +
            Self::MissingShaderAttribute(name) => {
52 +
                write!(f, "shader is missing attribute '{name}'")
53 +
            }
54 +
            Self::MissingColorAttachment => {
55 +
                write!(f, "render pass color attachment is missing")
56 +
            }
57 +
            Self::MissingDepthAttachment => {
58 +
                write!(f, "render pass depth attachment is missing")
59 +
            }
60 +
            Self::MissingUniform(name) => {
61 +
                write!(f, "missing uniform '{name}' in shader")
62 +
            }
63 +
            Self::AttachmentSizeMismatch => {
64 +
                write!(f, "render pass attachment size mismatch")
65 +
            }
66 +
            Self::AlphaBlendWithoutColor => {
67 +
                write!(f, "alpha blend specified without color blend")
68 +
            }
69 +
            Self::TextureNotFound(id) => {
70 +
                write!(f, "texture {id} not found")
71 +
            }
72 +
            Self::TextureLayoutMismatch(l, r) => {
73 +
                write!(f, "texture binding doesn't match shader layout: {l} != {r}")
74 +
            }
75 +
            Self::TextureSizeMismatch(l, r) => {
76 +
                write!(f, "texture size doesn't match data: {l} != {r}")
77 +
            }
78 +
            Self::PassNotFound(id) => {
79 +
                write!(f, "pass {id} not found")
80 +
            }
81 +
            Self::UniformSizeMismatch(l, r) => {
82 +
                write!(
83 +
                    f,
84 +
                    "uniform data size doesn't match shader layout: {l} != {r}"
85 +
                )
86 +
            }
87 +
            Self::IncompleteFramebuffer(status) => {
88 +
                write!(f, "framebuffer is incomplete (status {status:x})")
89 +
            }
90 +
            Self::InvalidIndexElementSize(s) => {
91 +
                write!(f, "index buffer element size `{s}` is invalid")
92 +
            }
93 +
            Self::InvalidIndexElementCount(s) => {
94 +
                write!(f, "element count `{s}` is not within index buffer range")
95 +
            }
96 +
            Self::InvalidBufferDataSize(s, max) => {
97 +
                write!(f, "buffer data size `{s}` is invalid (max={max})")
98 +
            }
99 +
            Self::InvalidBufferOffset(o) => {
100 +
                write!(f, "buffer data offset `{o}` is invalid")
101 +
            }
102 +
            Self::Shader(e) => {
103 +
                write!(f, "{e}")
104 +
            }
105 +
            Self::Internal(e) => {
106 +
                write!(f, "{e}")
107 +
            }
108 +
        }
109 +
    }
110 +
}
111 +
112 +
impl std::error::Error for Error {}
ombre/src/gfx/gl/types.rs added +175 -0
1 +
//! OpenGL types.
2 +
use crate::gfx::gl::*;
3 +
use crate::gfx::*;
4 +
5 +
/// Types that can be converted to OpenGL format.
6 +
pub trait ToGl {
7 +
    /// Convert type to an OpenGL type, eg. `GLenum` or `GLuint`.
8 +
    fn to_gl(&self) -> u32;
9 +
}
10 +
11 +
impl ToGl for BufferUsage {
12 +
    fn to_gl(&self) -> u32 {
13 +
        match self {
14 +
            Self::Immutable => glow::STATIC_DRAW,
15 +
            Self::Dynamic => glow::DYNAMIC_DRAW,
16 +
            Self::Stream => glow::STREAM_DRAW,
17 +
        }
18 +
    }
19 +
}
20 +
21 +
impl ToGl for Comparison {
22 +
    fn to_gl(&self) -> u32 {
23 +
        match self {
24 +
            Self::Never => glow::NEVER,
25 +
            Self::Less => glow::LESS,
26 +
            Self::LessOrEqual => glow::LEQUAL,
27 +
            Self::Greater => glow::GREATER,
28 +
            Self::GreaterOrEqual => glow::GEQUAL,
29 +
            Self::Equal => glow::EQUAL,
30 +
            Self::NotEqual => glow::NOTEQUAL,
31 +
            Self::Always => glow::ALWAYS,
32 +
        }
33 +
    }
34 +
}
35 +
36 +
impl ToGl for Primitive {
37 +
    fn to_gl(&self) -> u32 {
38 +
        match self {
39 +
            Self::Triangles => glow::TRIANGLES,
40 +
            Self::Lines => glow::LINES,
41 +
        }
42 +
    }
43 +
}
44 +
45 +
impl ToGl for VertexFormat {
46 +
    fn to_gl(&self) -> u32 {
47 +
        match self {
48 +
            VertexFormat::Float1 => glow::FLOAT,
49 +
            VertexFormat::Float2 => glow::FLOAT,
50 +
            VertexFormat::Float3 => glow::FLOAT,
51 +
            VertexFormat::Float4 => glow::FLOAT,
52 +
            VertexFormat::Byte1 => glow::UNSIGNED_BYTE,
53 +
            VertexFormat::Byte2 => glow::UNSIGNED_BYTE,
54 +
            VertexFormat::Byte3 => glow::UNSIGNED_BYTE,
55 +
            VertexFormat::Byte4 => glow::UNSIGNED_BYTE,
56 +
            VertexFormat::Short1 => glow::UNSIGNED_SHORT,
57 +
            VertexFormat::Short2 => glow::UNSIGNED_SHORT,
58 +
            VertexFormat::Short3 => glow::UNSIGNED_SHORT,
59 +
            VertexFormat::Short4 => glow::UNSIGNED_SHORT,
60 +
            VertexFormat::Int1 => glow::UNSIGNED_INT,
61 +
            VertexFormat::Int2 => glow::UNSIGNED_INT,
62 +
            VertexFormat::Int3 => glow::UNSIGNED_INT,
63 +
            VertexFormat::Int4 => glow::UNSIGNED_INT,
64 +
        }
65 +
    }
66 +
}
67 +
68 +
impl ToGl for TextureKind {
69 +
    fn to_gl(&self) -> u32 {
70 +
        match self {
71 +
            TextureKind::Texture2D => glow::TEXTURE_2D,
72 +
            TextureKind::Texture2DArray { .. } => glow::TEXTURE_2D_ARRAY,
73 +
        }
74 +
    }
75 +
}
76 +
77 +
impl ToGl for TextureWrap {
78 +
    fn to_gl(&self) -> u32 {
79 +
        match self {
80 +
            TextureWrap::Repeat => glow::REPEAT,
81 +
            TextureWrap::Mirror => glow::MIRRORED_REPEAT,
82 +
            TextureWrap::Clamp => glow::CLAMP_TO_EDGE,
83 +
        }
84 +
    }
85 +
}
86 +
87 +
impl ToGl for ElementSize {
88 +
    fn to_gl(&self) -> u32 {
89 +
        match self.0 {
90 +
            1 => glow::UNSIGNED_BYTE,
91 +
            2 => glow::UNSIGNED_SHORT,
92 +
            4 => glow::UNSIGNED_INT,
93 +
            _ => unreachable! {},
94 +
        }
95 +
    }
96 +
}
97 +
98 +
impl ToGl for FaceWinding {
99 +
    fn to_gl(&self) -> u32 {
100 +
        match self {
101 +
            Self::Clockwise => glow::CW,
102 +
            Self::CounterClockwise => glow::CCW,
103 +
        }
104 +
    }
105 +
}
106 +
107 +
impl ToGl for BufferKind {
108 +
    fn to_gl(&self) -> u32 {
109 +
        match self {
110 +
            BufferKind::Vertex => glow::ARRAY_BUFFER,
111 +
            BufferKind::Index => glow::ELEMENT_ARRAY_BUFFER,
112 +
        }
113 +
    }
114 +
}
115 +
116 +
impl ToGl for FilterMode {
117 +
    fn to_gl(&self) -> u32 {
118 +
        match self {
119 +
            Self::Linear => glow::LINEAR,
120 +
            Self::Nearest => glow::NEAREST,
121 +
        }
122 +
    }
123 +
}
124 +
125 +
impl ToGl for BlendOp {
126 +
    fn to_gl(&self) -> u32 {
127 +
        match self {
128 +
            BlendOp::Add => glow::FUNC_ADD,
129 +
            BlendOp::Subtract => glow::FUNC_SUBTRACT,
130 +
            BlendOp::SubtractReverse => glow::FUNC_REVERSE_SUBTRACT,
131 +
        }
132 +
    }
133 +
}
134 +
135 +
impl ToGl for BlendFactor {
136 +
    fn to_gl(&self) -> u32 {
137 +
        match self {
138 +
            Self::Zero => glow::ZERO,
139 +
            Self::One => glow::ONE,
140 +
            Self::Value(BlendValue::SourceColor) => glow::SRC_COLOR,
141 +
            Self::Value(BlendValue::SourceAlpha) => glow::SRC_ALPHA,
142 +
            Self::Value(BlendValue::DestinationColor) => glow::DST_COLOR,
143 +
            Self::Value(BlendValue::DestinationAlpha) => glow::DST_ALPHA,
144 +
            Self::OneMinusValue(BlendValue::SourceColor) => glow::ONE_MINUS_SRC_COLOR,
145 +
            Self::OneMinusValue(BlendValue::SourceAlpha) => glow::ONE_MINUS_SRC_ALPHA,
146 +
            Self::OneMinusValue(BlendValue::DestinationColor) => glow::ONE_MINUS_DST_COLOR,
147 +
            Self::OneMinusValue(BlendValue::DestinationAlpha) => glow::ONE_MINUS_DST_ALPHA,
148 +
            Self::SourceAlphaSaturate => glow::SRC_ALPHA_SATURATE,
149 +
        }
150 +
    }
151 +
}
152 +
153 +
impl ToGl for ShaderKind {
154 +
    fn to_gl(&self) -> u32 {
155 +
        match self {
156 +
            ShaderKind::Vertex => glow::VERTEX_SHADER,
157 +
            ShaderKind::Fragment => glow::FRAGMENT_SHADER,
158 +
            ShaderKind::Geometry => glow::GEOMETRY_SHADER,
159 +
        }
160 +
    }
161 +
}
162 +
impl ToGl for StencilOp {
163 +
    fn to_gl(&self) -> u32 {
164 +
        match self {
165 +
            Self::Keep => glow::KEEP,
166 +
            Self::Zero => glow::ZERO,
167 +
            Self::Replace => glow::REPLACE,
168 +
            Self::IncrementClamp => glow::INCR,
169 +
            Self::DecrementClamp => glow::DECR,
170 +
            Self::Invert => glow::INVERT,
171 +
            Self::IncrementWrap => glow::INCR_WRAP,
172 +
            Self::DecrementWrap => glow::DECR_WRAP,
173 +
        }
174 +
    }
175 +
}
ombre/src/gfx/id.rs added +13 -0
1 +
//! Internal identifiers.
2 +
use std::{num::NonZeroU64, sync::atomic::*};
3 +
4 +
/// Type for all identifiers.
5 +
pub type Id = NonZeroU64;
6 +
7 +
/// Get the next unique identifier.
8 +
pub fn next() -> Id {
9 +
    static NEXT: AtomicU64 = AtomicU64::new(1);
10 +
11 +
    let next = NEXT.fetch_add(1, Ordering::SeqCst);
12 +
    unsafe { NonZeroU64::new_unchecked(next) }
13 +
}
ombre/src/gfx/image.rs added +169 -0
1 +
//! Image encoding and decoding.
2 +
use std::io;
3 +
use std::sync::Arc;
4 +
5 +
use super::{pixels, Color as _, Point2D, Rect, Rgba8, Size};
6 +
use crate::{
7 +
    bytes::encoding::{Decode, Encode},
8 +
    math::Zero,
9 +
};
10 +
11 +
/// File extension for RGBA images.
12 +
pub const FILE_EXTENSION: &str = "rgba";
13 +
/// File header magic.
14 +
pub const MAGIC: [u8; 4] = [b'R', b'G', b'B', b'A'];
15 +
16 +
/// Uniquely identifies an [`Image`].
17 +
pub type ImageId = u64;
18 +
19 +
///////////////////////////////////////////////////////////////////////////
20 +
// Image
21 +
///////////////////////////////////////////////////////////////////////////
22 +
23 +
/// An RGBA image. Can be created from an `.rgba` file buffer using the `TryFrom`
24 +
/// instance.
25 +
///
26 +
/// .---------.
27 +
/// |  MAGIC  | "RGBA" (4 bytes)
28 +
/// +---------+
29 +
/// |  WIDTH  |        (4 bytes) (Big Endian)
30 +
/// +---------+
31 +
/// |  HEIGHT |        (4 bytes) (Big Endian)
32 +
/// +---------+
33 +
/// |  DATA   |        (WIDTH * HEIGHT * 4 bytes)
34 +
/// |  ....   |        (RGBA format)
35 +
/// |  ....   |
36 +
/// |  ....   |
37 +
/// '---------'
38 +
///
39 +
#[derive(Clone)]
40 +
pub struct Image {
41 +
    pub size: Size<u32>,
42 +
    pub pixels: Arc<[Rgba8]>,
43 +
}
44 +
45 +
impl std::fmt::Debug for Image {
46 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 +
        f.debug_struct("Image")
48 +
            .field("size", &self.size)
49 +
            .finish_non_exhaustive()
50 +
    }
51 +
}
52 +
53 +
impl Eq for Image {}
54 +
55 +
impl PartialEq for Image {
56 +
    fn eq(&self, other: &Self) -> bool {
57 +
        (Arc::ptr_eq(&self.pixels, &other.pixels) && self.size == other.size)
58 +
            || self.pixels == other.pixels
59 +
    }
60 +
}
61 +
62 +
impl Image {
63 +
    /// Create a new image from pixels and dimensions.
64 +
    pub fn new(pixels: impl Into<Arc<[Rgba8]>>, size: impl Into<Size<u32>>) -> Self {
65 +
        let size = size.into();
66 +
        let pixels = pixels.into();
67 +
68 +
        assert_eq!(size.area() as usize, pixels.len());
69 +
70 +
        Self { size, pixels }
71 +
    }
72 +
73 +
    /// An empty image.
74 +
    pub fn empty() -> Self {
75 +
        Self {
76 +
            size: Size::ZERO,
77 +
            pixels: Arc::new([]),
78 +
        }
79 +
    }
80 +
81 +
    /// Return a new scaled image.
82 +
    pub fn scaled(&self, factor: u32) -> Self {
83 +
        let scaled = pixels::scale(&self.pixels, self.size.w, self.size.h, factor);
84 +
85 +
        Self {
86 +
            size: self.size * factor,
87 +
            pixels: scaled.into(),
88 +
        }
89 +
    }
90 +
91 +
    /// Get the image area rectangle.
92 +
    pub fn rect(&self) -> Rect<u32> {
93 +
        Rect::origin(self.size)
94 +
    }
95 +
96 +
    /// Create a blank image of the given size.
97 +
    pub fn blank(size: impl Into<Size<u32>>) -> Self {
98 +
        let size = size.into();
99 +
100 +
        Self::new(vec![Rgba8::TRANSPARENT; size.area() as usize], size)
101 +
    }
102 +
103 +
    /// Write the image to the writer in `.rgba` format.
104 +
    pub fn write(&self, writer: &mut impl io::Write) -> Result<usize, io::Error> {
105 +
        let mut n = 0;
106 +
107 +
        n += MAGIC.encode(writer)?;
108 +
        n += self.size.w.encode(writer)?;
109 +
        n += self.size.h.encode(writer)?;
110 +
111 +
        for p in self.pixels.iter() {
112 +
            n += p.encode(writer)?;
113 +
        }
114 +
        Ok(n)
115 +
    }
116 +
117 +
    /// Get the texel color at the given position in the image.
118 +
    pub fn sample(&self, point: Point2D<u32>) -> Option<&Rgba8> {
119 +
        let offset = self.size.w * point.y + point.x;
120 +
        self.pixels.get(offset as usize)
121 +
    }
122 +
123 +
    /// Return the image identifier of this image.
124 +
    /// This is the address in memory of the pixels.
125 +
    pub fn id(&self) -> ImageId {
126 +
        self.pixels.as_ptr() as ImageId
127 +
    }
128 +
129 +
    /// Return the image pixels as a [`u32`] slice.
130 +
    pub fn as_u32_slice(&self) -> &[u32] {
131 +
        let (head, aligned, tail) = unsafe { self.pixels.align_to::<u32>() };
132 +
133 +
        assert!(head.is_empty());
134 +
        assert!(tail.is_empty());
135 +
136 +
        aligned
137 +
    }
138 +
}
139 +
140 +
impl Decode for Image {
141 +
    fn decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> {
142 +
        let magic: [u8; 4] = Decode::decode(reader)?;
143 +
        if magic != MAGIC {
144 +
            return Err(io::ErrorKind::InvalidData.into());
145 +
        }
146 +
        let w = u32::decode(reader)? as usize;
147 +
        let h = u32::decode(reader)? as usize;
148 +
        let s = Size::new(w, h);
149 +
        let n = s.area();
150 +
151 +
        let mut pixels = Vec::with_capacity(n);
152 +
        while pixels.len() < n {
153 +
            let pixel = Rgba8::decode(reader)?;
154 +
            pixels.push(pixel);
155 +
        }
156 +
        Ok(Self::new(pixels, s))
157 +
    }
158 +
}
159 +
160 +
impl TryFrom<&[u8]> for Image {
161 +
    type Error = io::Error;
162 +
163 +
    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
164 +
        let mut cursor = io::Cursor::new(bytes);
165 +
        let image = Image::decode(&mut cursor)?;
166 +
167 +
        Ok(image)
168 +
    }
169 +
}
ombre/src/gfx/limits.rs added +43 -0
1 +
/// Graphics backend limits.
2 +
///
3 +
/// The [`Default`] instance should almost always be used, as the values are safe
4 +
/// across all backends.
5 +
pub struct Limits {
6 +
    pub max_bind_groups: usize,
7 +
    pub max_dynamic_uniform_buffers_per_pipeline_layout: usize,
8 +
    pub max_dynamic_storage_buffers_per_pipeline_layout: usize,
9 +
    pub max_sampled_textures_per_shader_stage: usize,
10 +
    pub max_samplers_per_shader_stage: usize,
11 +
    pub max_storage_buffers_per_shader_stage: usize,
12 +
    pub max_storage_textures_per_shader_stage: usize,
13 +
    pub max_uniform_buffers_per_shader_stage: usize,
14 +
    pub max_vertex_buffers: usize,
15 +
    pub max_vertex_attributes: usize,
16 +
    pub max_vertex_array_stride: usize,
17 +
    pub max_texture_dimension_1d: usize,
18 +
    pub max_texture_dimension_2d: usize,
19 +
    pub max_texture_dimension_3d: usize,
20 +
    pub max_texture_array_layers: usize,
21 +
}
22 +
23 +
impl Default for Limits {
24 +
    fn default() -> Self {
25 +
        Self {
26 +
            max_bind_groups: 4,
27 +
            max_dynamic_uniform_buffers_per_pipeline_layout: 8,
28 +
            max_dynamic_storage_buffers_per_pipeline_layout: 4,
29 +
            max_sampled_textures_per_shader_stage: 16,
30 +
            max_samplers_per_shader_stage: 16,
31 +
            max_storage_buffers_per_shader_stage: 4,
32 +
            max_storage_textures_per_shader_stage: 4,
33 +
            max_uniform_buffers_per_shader_stage: 12,
34 +
            max_vertex_buffers: 8,
35 +
            max_vertex_attributes: 16,
36 +
            max_vertex_array_stride: 2048,
37 +
            max_texture_dimension_1d: 8192,
38 +
            max_texture_dimension_2d: 8192,
39 +
            max_texture_dimension_3d: 2048,
40 +
            max_texture_array_layers: 2048,
41 +
        }
42 +
    }
43 +
}
ombre/src/gfx/pass.rs added +56 -0
1 +
use super::*;
2 +
3 +
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4 +
pub struct PassId(id::Id);
5 +
6 +
impl std::fmt::Display for PassId {
7 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8 +
        self.0.fmt(f)
9 +
    }
10 +
}
11 +
12 +
impl PassId {
13 +
    /// Get the next pipeline id.
14 +
    pub fn next() -> Self {
15 +
        Self(id::next())
16 +
    }
17 +
}
18 +
19 +
#[derive(Debug, Clone)]
20 +
pub enum PassAction {
21 +
    Nothing,
22 +
    Clear {
23 +
        color: Option<color::Rgba<f32>>,
24 +
        depth: Option<f32>,
25 +
        stencil: Option<i32>,
26 +
    },
27 +
}
28 +
29 +
impl PassAction {
30 +
    pub fn clear(color: impl Into<Rgba<f32>>) -> PassAction {
31 +
        PassAction::Clear {
32 +
            color: Some(color.into()),
33 +
            depth: Some(1.),
34 +
            stencil: None,
35 +
        }
36 +
    }
37 +
}
38 +
39 +
impl Default for PassAction {
40 +
    fn default() -> PassAction {
41 +
        PassAction::Clear {
42 +
            color: Some(Rgba::TRANSPARENT),
43 +
            depth: Some(1.),
44 +
            stencil: None,
45 +
        }
46 +
    }
47 +
}
48 +
49 +
/// Describes a render pass.
50 +
#[derive(Debug, Clone)]
51 +
pub struct PassDescriptor<'a> {
52 +
    /// Textures in which to render color.
53 +
    pub color_attachments: &'a [TextureId],
54 +
    /// Texture in which to render depth.
55 +
    pub depth_attachment: Option<TextureId>,
56 +
}
ombre/src/gfx/pipeline.rs added +315 -0
1 +
//! Graphics pipeline types.
2 +
use super::*;
3 +
4 +
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
5 +
pub struct PipelineId(id::Id);
6 +
7 +
impl PipelineId {
8 +
    /// Get the next pipeline id.
9 +
    pub fn next() -> Self {
10 +
        Self(id::next())
11 +
    }
12 +
}
13 +
14 +
#[derive(Debug, Clone, Copy, Default)]
15 +
pub struct BlendState {
16 +
    /// Color blending.
17 +
    pub rgb: Option<BlendEquation>,
18 +
    /// Alpha blending.
19 +
    pub alpha: Option<BlendEquation>,
20 +
}
21 +
22 +
#[derive(Debug, Clone, Copy)]
23 +
pub struct ColorState {
24 +
    pub mask: Rgba<bool>,
25 +
    pub blend: BlendState,
26 +
}
27 +
28 +
impl Default for ColorState {
29 +
    fn default() -> Self {
30 +
        Self {
31 +
            mask: Rgba::new(true, true, true, true),
32 +
            blend: BlendState::default(),
33 +
        }
34 +
    }
35 +
}
36 +
37 +
#[derive(Debug, Clone, Copy, Default)]
38 +
pub struct DepthState {
39 +
    pub compare: Comparison,
40 +
    pub offset: Option<(f32, f32)>,
41 +
}
42 +
43 +
#[derive(Debug, Clone, Default)]
44 +
pub struct PipelineDescriptor<'a> {
45 +
    pub layout: &'a [BufferLayout<'a>],
46 +
    pub depth: Option<DepthState>,
47 +
    pub stencil: Option<StencilState>,
48 +
    pub color: Option<ColorState>,
49 +
    pub culling: CullMode,
50 +
    pub winding: FaceWinding,
51 +
    pub primitive: Primitive,
52 +
}
53 +
54 +
#[derive(Clone, Debug)]
55 +
pub struct BufferLayout<'a> {
56 +
    pub stride: Option<usize>,
57 +
    pub step: VertexStep,
58 +
    pub step_rate: i32,
59 +
    pub attrs: &'a [VertexAttribute],
60 +
}
61 +
62 +
impl<'a> Default for BufferLayout<'a> {
63 +
    fn default() -> BufferLayout<'a> {
64 +
        BufferLayout {
65 +
            stride: None,
66 +
            step: VertexStep::default(),
67 +
            step_rate: 1,
68 +
            attrs: &[],
69 +
        }
70 +
    }
71 +
}
72 +
73 +
#[derive(Clone, Copy, PartialEq, Debug, Default)]
74 +
pub enum VertexStep {
75 +
    #[default]
76 +
    PerVertex,
77 +
    PerInstance,
78 +
}
79 +
80 +
#[derive(Clone, Debug)]
81 +
pub struct VertexAttribute {
82 +
    pub name: &'static str,
83 +
    pub format: VertexFormat,
84 +
}
85 +
86 +
impl VertexAttribute {
87 +
    pub const fn new(name: &'static str, format: VertexFormat) -> VertexAttribute {
88 +
        VertexAttribute { name, format }
89 +
    }
90 +
}
91 +
92 +
#[derive(Clone, Copy, PartialEq, Debug)]
93 +
pub enum VertexFormat {
94 +
    /// One 32-bit wide float (equivalent to `f32`)
95 +
    Float1,
96 +
    /// Two 32-bit wide floats (equivalent to `[f32; 2]`)
97 +
    Float2,
98 +
    /// Three 32-bit wide floats (equivalent to `[f32; 3]`)
99 +
    Float3,
100 +
    /// Four 32-bit wide floats (equivalent to `[f32; 4]`)
101 +
    Float4,
102 +
    /// One unsigned 8-bit integer (equivalent to `u8`)
103 +
    Byte1,
104 +
    /// Two unsigned 8-bit integers (equivalent to `[u8; 2]`)
105 +
    Byte2,
106 +
    /// Three unsigned 8-bit integers (equivalent to `[u8; 3]`)
107 +
    Byte3,
108 +
    /// Four unsigned 8-bit integers (equivalent to `[u8; 4]`)
109 +
    Byte4,
110 +
    /// One unsigned 16-bit integer (equivalent to `u16`)
111 +
    Short1,
112 +
    /// Two unsigned 16-bit integers (equivalent to `[u16; 2]`)
113 +
    Short2,
114 +
    /// Tree unsigned 16-bit integers (equivalent to `[u16; 3]`)
115 +
    Short3,
116 +
    /// Four unsigned 16-bit integers (equivalent to `[u16; 4]`)
117 +
    Short4,
118 +
    /// One unsigned 32-bit integers (equivalent to `[u32; 1]`)
119 +
    Int1,
120 +
    /// Two unsigned 32-bit integers (equivalent to `[u32; 2]`)
121 +
    Int2,
122 +
    /// Three unsigned 32-bit integers (equivalent to `[u32; 3]`)
123 +
    Int3,
124 +
    /// Four unsigned 32-bit integers (equivalent to `[u32; 4]`)
125 +
    Int4,
126 +
}
127 +
128 +
/// Trait for types that can be used as vertex attributes.
129 +
pub trait ToVertexFormat {
130 +
    /// The corresponding VertexFormat for this type.
131 +
    const FORMAT: VertexFormat;
132 +
}
133 +
134 +
impl ToVertexFormat for f32 {
135 +
    const FORMAT: VertexFormat = VertexFormat::Float1;
136 +
}
137 +
138 +
impl ToVertexFormat for [f32; 2] {
139 +
    const FORMAT: VertexFormat = VertexFormat::Float2;
140 +
}
141 +
142 +
impl ToVertexFormat for [f32; 3] {
143 +
    const FORMAT: VertexFormat = VertexFormat::Float3;
144 +
}
145 +
146 +
impl ToVertexFormat for [f32; 4] {
147 +
    const FORMAT: VertexFormat = VertexFormat::Float4;
148 +
}
149 +
150 +
impl ToVertexFormat for u8 {
151 +
    const FORMAT: VertexFormat = VertexFormat::Byte1;
152 +
}
153 +
154 +
impl ToVertexFormat for [u8; 2] {
155 +
    const FORMAT: VertexFormat = VertexFormat::Byte2;
156 +
}
157 +
158 +
impl ToVertexFormat for [u8; 3] {
159 +
    const FORMAT: VertexFormat = VertexFormat::Byte3;
160 +
}
161 +
162 +
impl ToVertexFormat for [u8; 4] {
163 +
    const FORMAT: VertexFormat = VertexFormat::Byte4;
164 +
}
165 +
166 +
impl ToVertexFormat for u16 {
167 +
    const FORMAT: VertexFormat = VertexFormat::Short1;
168 +
}
169 +
170 +
impl ToVertexFormat for [u16; 2] {
171 +
    const FORMAT: VertexFormat = VertexFormat::Short2;
172 +
}
173 +
174 +
impl ToVertexFormat for [u16; 3] {
175 +
    const FORMAT: VertexFormat = VertexFormat::Short3;
176 +
}
177 +
178 +
impl ToVertexFormat for [u16; 4] {
179 +
    const FORMAT: VertexFormat = VertexFormat::Short4;
180 +
}
181 +
182 +
impl ToVertexFormat for u32 {
183 +
    const FORMAT: VertexFormat = VertexFormat::Int1;
184 +
}
185 +
186 +
impl ToVertexFormat for [u32; 2] {
187 +
    const FORMAT: VertexFormat = VertexFormat::Int2;
188 +
}
189 +
190 +
impl ToVertexFormat for [u32; 3] {
191 +
    const FORMAT: VertexFormat = VertexFormat::Int3;
192 +
}
193 +
194 +
impl ToVertexFormat for [u32; 4] {
195 +
    const FORMAT: VertexFormat = VertexFormat::Int4;
196 +
}
197 +
198 +
impl<U> ToVertexFormat for Vector2D<f32, U> {
199 +
    const FORMAT: VertexFormat = VertexFormat::Float2;
200 +
}
201 +
202 +
impl<U> ToVertexFormat for Vector3D<f32, U> {
203 +
    const FORMAT: VertexFormat = VertexFormat::Float3;
204 +
}
205 +
206 +
impl<U> ToVertexFormat for Vector4D<f32, U> {
207 +
    const FORMAT: VertexFormat = VertexFormat::Float4;
208 +
}
209 +
210 +
impl<U> ToVertexFormat for Point2D<f32, U> {
211 +
    const FORMAT: VertexFormat = VertexFormat::Float2;
212 +
}
213 +
214 +
impl ToVertexFormat for Rgba<f32> {
215 +
    const FORMAT: VertexFormat = VertexFormat::Float4;
216 +
}
217 +
218 +
impl VertexFormat {
219 +
    /// Number of components in this vertex format.
220 +
    pub const fn components(&self) -> usize {
221 +
        match self {
222 +
            VertexFormat::Float1 => 1,
223 +
            VertexFormat::Float2 => 2,
224 +
            VertexFormat::Float3 => 3,
225 +
            VertexFormat::Float4 => 4,
226 +
            VertexFormat::Byte1 => 1,
227 +
            VertexFormat::Byte2 => 2,
228 +
            VertexFormat::Byte3 => 3,
229 +
            VertexFormat::Byte4 => 4,
230 +
            VertexFormat::Short1 => 1,
231 +
            VertexFormat::Short2 => 2,
232 +
            VertexFormat::Short3 => 3,
233 +
            VertexFormat::Short4 => 4,
234 +
            VertexFormat::Int1 => 1,
235 +
            VertexFormat::Int2 => 2,
236 +
            VertexFormat::Int3 => 3,
237 +
            VertexFormat::Int4 => 4,
238 +
        }
239 +
    }
240 +
241 +
    /// Size in bytes.
242 +
    pub const fn size(&self) -> usize {
243 +
        self.components()
244 +
            * match self {
245 +
                VertexFormat::Float1
246 +
                | VertexFormat::Float2
247 +
                | VertexFormat::Float3
248 +
                | VertexFormat::Float4 => 4,
249 +
                VertexFormat::Byte1
250 +
                | VertexFormat::Byte2
251 +
                | VertexFormat::Byte3
252 +
                | VertexFormat::Byte4 => 1,
253 +
                VertexFormat::Short1
254 +
                | VertexFormat::Short2
255 +
                | VertexFormat::Short3
256 +
                | VertexFormat::Short4 => 2,
257 +
                VertexFormat::Int1
258 +
                | VertexFormat::Int2
259 +
                | VertexFormat::Int3
260 +
                | VertexFormat::Int4 => 4,
261 +
            }
262 +
    }
263 +
264 +
    /// Check whether this format is of an integer type.
265 +
    pub const fn is_integer(&self) -> bool {
266 +
        match self {
267 +
            VertexFormat::Int1
268 +
            | VertexFormat::Int2
269 +
            | VertexFormat::Int3
270 +
            | VertexFormat::Int4
271 +
            | VertexFormat::Byte1
272 +
            | VertexFormat::Byte2
273 +
            | VertexFormat::Byte3
274 +
            | VertexFormat::Byte4
275 +
            | VertexFormat::Short1
276 +
            | VertexFormat::Short2
277 +
            | VertexFormat::Short3
278 +
            | VertexFormat::Short4 => true,
279 +
            VertexFormat::Float1
280 +
            | VertexFormat::Float2
281 +
            | VertexFormat::Float3
282 +
            | VertexFormat::Float4 => false,
283 +
        }
284 +
    }
285 +
}
286 +
287 +
/// Specify whether front- or back-facing polygons can be culled.
288 +
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
289 +
pub enum CullMode {
290 +
    #[default]
291 +
    Nothing,
292 +
    Front,
293 +
    Back,
294 +
}
295 +
296 +
/// Define front- and back-facing polygons.
297 +
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
298 +
pub enum FaceWinding {
299 +
    #[default]
300 +
    CounterClockwise,
301 +
    Clockwise,
302 +
}
303 +
304 +
#[derive(Debug, PartialEq, Clone, Copy, Default)]
305 +
pub enum Primitive {
306 +
    #[default]
307 +
    Triangles,
308 +
    Lines,
309 +
}
310 +
311 +
/// Trait for types that can provide their vertex attribute layout.
312 +
pub trait VertexAttributes {
313 +
    /// Get the vertex attributes for this type.
314 +
    fn attributes() -> &'static [VertexAttribute];
315 +
}
ombre/src/gfx/pixels.rs added +151 -0
1 +
use crate::math::Rect;
2 +
3 +
/// `icn` format tile width and height.
4 +
pub const ICN_TILE: usize = 8;
5 +
6 +
/// A view into a pixel buffer.
7 +
pub struct Pixels<'a, T> {
8 +
    width: usize,
9 +
    height: usize,
10 +
    pixels: &'a [T],
11 +
}
12 +
13 +
impl<'a, T: Copy> Pixels<'a, T> {
14 +
    pub fn new(pixels: &'a [T], width: usize, height: usize) -> Self {
15 +
        Self {
16 +
            width,
17 +
            height,
18 +
            pixels,
19 +
        }
20 +
    }
21 +
22 +
    pub fn get(&self, x: usize, y: usize) -> Option<&T> {
23 +
        if x < self.width && y < self.height {
24 +
            self.pixels.get(self.width * y + x)
25 +
        } else {
26 +
            None
27 +
        }
28 +
    }
29 +
30 +
    pub fn rect(&self, rect: Rect<usize>) -> Vec<T> {
31 +
        let mut pixels = Vec::with_capacity(rect.area());
32 +
33 +
        for y in rect.origin.y..rect.origin.y + rect.size.h {
34 +
            for x in rect.origin.x..rect.origin.x + rect.size.w {
35 +
                if let Some(pixel) = self.get(x, y) {
36 +
                    pixels.push(*pixel);
37 +
                }
38 +
            }
39 +
        }
40 +
        pixels
41 +
    }
42 +
}
43 +
44 +
/// A mutable view into a pixel buffer.
45 +
pub struct PixelsMut<'a, T> {
46 +
    pub width: usize,
47 +
    pub height: usize,
48 +
49 +
    pixels: &'a mut [T],
50 +
}
51 +
52 +
impl<'a, T: Copy> PixelsMut<'a, T> {
53 +
    pub fn new(pixels: &'a mut [T], width: usize, height: usize) -> Self {
54 +
        assert_eq!(pixels.len(), width * height);
55 +
56 +
        Self {
57 +
            width,
58 +
            height,
59 +
            pixels,
60 +
        }
61 +
    }
62 +
63 +
    pub fn get(&self, x: usize, y: usize) -> Option<&T> {
64 +
        if x < self.width && y < self.height {
65 +
            self.pixels.get(x + y * self.width)
66 +
        } else {
67 +
            None
68 +
        }
69 +
    }
70 +
71 +
    pub fn get_mut(&mut self, x: usize, y: usize) -> Option<&mut T> {
72 +
        if x < self.width && y < self.height {
73 +
            self.pixels.get_mut(x + y * self.width)
74 +
        } else {
75 +
            None
76 +
        }
77 +
    }
78 +
79 +
    pub fn set(&mut self, x: usize, y: usize, value: T) {
80 +
        if x < self.width && y < self.height {
81 +
            self.pixels[self.width * y + x] = value;
82 +
        }
83 +
    }
84 +
85 +
    pub fn iter_mut(&'a mut self) -> impl Iterator<Item = (usize, usize, &'a mut T)> {
86 +
        let width = self.width;
87 +
88 +
        self.pixels
89 +
            .as_mut()
90 +
            .iter_mut()
91 +
            .enumerate()
92 +
            .map(move |(i, c)| (i % width, i / width, c))
93 +
    }
94 +
95 +
    #[allow(clippy::needless_range_loop)]
96 +
    pub fn icn(&mut self, tile: [u8; ICN_TILE], x: usize, y: usize, color: T) {
97 +
        for v in 0..ICN_TILE {
98 +
            for h in 0..ICN_TILE {
99 +
                let value = (tile[v] >> (7 - h)) & 0x1;
100 +
                if value == 1 {
101 +
                    self.set(x + h, y + v, color);
102 +
                };
103 +
            }
104 +
        }
105 +
    }
106 +
}
107 +
108 +
/// Scale an image using the nearest-neighbor algorithm, by a given factor.
109 +
pub fn scale<T: Default + Clone + Copy>(
110 +
    image: &[T],
111 +
    width: u32,
112 +
    height: u32,
113 +
    factor: u32,
114 +
) -> Vec<T> {
115 +
    assert_eq!(image.len(), (width * height) as usize);
116 +
117 +
    let input = Pixels::new(image, width as usize, height as usize);
118 +
    let width = (width * factor) as usize;
119 +
    let height = (height * factor) as usize;
120 +
121 +
    let mut output_buf = vec![T::default(); width * height];
122 +
    let mut output = PixelsMut::new(&mut output_buf, width, height);
123 +
124 +
    #[allow(clippy::unwrap_used)]
125 +
    for (x, y, pixel) in output.iter_mut() {
126 +
        let x = x / factor as usize;
127 +
        let y = y / factor as usize;
128 +
129 +
        // SAFETY: This is safe assuming `x` and `y` are computed correctly.
130 +
        *pixel = *input.get(x, y).unwrap();
131 +
    }
132 +
    output_buf
133 +
}
134 +
135 +
/// Stitch frames together so that they form a single contiguous strip.
136 +
pub fn stitch_frames<T: Clone>(frames: Vec<Vec<T>>, fw: usize, fh: usize, default: T) -> Vec<T> {
137 +
    let nframes = frames.len();
138 +
    let width = fw * nframes;
139 +
    let mut buffer: Vec<T> = vec![default; fw * fh * nframes];
140 +
141 +
    for (i, frame) in frames.iter().enumerate() {
142 +
        for y in 0..fh {
143 +
            let offset = i * fw + y * width;
144 +
            buffer.splice(
145 +
                offset..offset + fw,
146 +
                frame[fw * y..fw * y + fw].iter().cloned(),
147 +
            );
148 +
        }
149 +
    }
150 +
    buffer
151 +
}
ombre/src/gfx/sdf/fragment.glsl added +71 -0
1 +
// Signed distance function (SDF) shader.
2 +
#version 330 core
3 +
4 +
// Vertex position in NDC space.
5 +
in vec2 vertexPos;
6 +
// Output color for this fragment.
7 +
out vec4 fragColor;
8 +
9 +
// Shape to render (0=circle, 1=box, 2=triangle).
10 +
uniform int shape;
11 +
// Amount of smoothing to apply to shape edges.
12 +
uniform float smoothing;
13 +
// Screen aspect ratio for maintaining correct shapes.
14 +
uniform float aspect;
15 +
// Size of shape (`x`,`y` for box, `x` only for circle/triangle)
16 +
uniform vec2 size;
17 +
// Color and alpha of the shape.
18 +
uniform vec4 color;
19 +
// Center position of shape in NDC space.
20 +
uniform vec2 position;
21 +
22 +
// Circle SDF.
23 +
float circle(vec2 p, float radius) {
24 +
    return length(p) - radius;
25 +
}
26 +
27 +
// Box SDF.
28 +
// `p` is the point to test, `h` is the half-width and half-height.
29 +
float box(vec2 p, vec2 h) {
30 +
    vec2 d = abs(p) - h; // Transform to first quadrant and offset by size
31 +
    return length(max(d, 0.0)) + min(max(d.x, d.y), 0.0); // Distance to edge
32 +
}
33 +
34 +
// Triangle SDF.
35 +
float triangle(vec2 p, float size) {
36 +
    const float k = sqrt(3.0); // Constant for 60° angles
37 +
38 +
    // Scale and center the triangle.
39 +
    p /= size;
40 +
    p.x = abs(p.x) - 0.5; // Mirror across y-axis and offset
41 +
    p.y = p.y + 0.5 / k;  // Move triangle up to center
42 +
43 +
    // Fold the space to create the triangle shape.
44 +
    if (p.x + k * p.y > 0.0) {
45 +
		p = vec2(
46 +
			p.x - k * p.y,
47 +
			-k * p.x - p.y
48 +
		) / 2.0;
49 +
	}
50 +
    p.x -= clamp(p.x, -2.0, 0.0);
51 +
52 +
    return -length(p) * sign(p.y) * size;
53 +
}
54 +
55 +
void main() {
56 +
    // Calculate point relative to shape center, correcting for aspect ratio.
57 +
    vec2 p = vertexPos * vec2(aspect, 1.0) - position * vec2(aspect, 1.0);
58 +
59 +
    // Get signed distance for selected shape.
60 +
    float d = shape == 0 ? circle(p, size.x)
61 +
            : shape == 1 ? box(p, size)
62 +
            : triangle(p, size.x * 2.0);
63 +
64 +
    // Discard fragments far outside the shape
65 +
    if (d > smoothing) discard;
66 +
67 +
    // Calculate smooth edge transition
68 +
    float edge = smoothstep(-smoothing, smoothing, d);
69 +
    // Mix between shape color and transparent based on edge distance.
70 +
	fragColor = vec4(mix(color.rgb, vec3(0.0), edge), color.a * (1.0 - edge));
71 +
}
ombre/src/gfx/sdf/vertex.glsl added +10 -0
1 +
#version 330 core
2 +
3 +
layout(location = 0) in vec2 position;
4 +
5 +
out vec2 vertexPos;
6 +
7 +
void main() {
8 +
    vertexPos = position;
9 +
    gl_Position = vec4(position, 0.0, 1.0);
10 +
}
ombre/src/gfx/shader.rs added +79 -0
1 +
use super::*;
2 +
3 +
/// Shader identifier.
4 +
#[derive(Clone, Debug, Copy, PartialEq, Eq, Hash)]
5 +
pub struct ShaderId(id::Id);
6 +
7 +
impl std::fmt::Display for ShaderId {
8 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9 +
        self.0.fmt(f)
10 +
    }
11 +
}
12 +
13 +
#[derive(Clone, Debug)]
14 +
pub enum ShaderError {
15 +
    CompilationError { kind: ShaderKind, message: String },
16 +
    LinkError(String),
17 +
    Internal(String),
18 +
}
19 +
20 +
impl std::fmt::Display for ShaderError {
21 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22 +
        match self {
23 +
            Self::CompilationError { kind, message } => {
24 +
                write!(f, "{kind} shader compilation: {message}")
25 +
            }
26 +
            Self::LinkError(msg) => write!(f, "shader linking: {msg}"),
27 +
            Self::Internal(msg) => write!(f, "shader internal error: {msg}"),
28 +
        }
29 +
    }
30 +
}
31 +
32 +
impl ShaderId {
33 +
    /// Get the next shader id.
34 +
    pub fn next() -> Self {
35 +
        Self(id::next())
36 +
    }
37 +
}
38 +
39 +
#[derive(Clone, Debug, Copy, PartialEq, Eq)]
40 +
pub enum ShaderKind {
41 +
    Vertex,
42 +
    Fragment,
43 +
    Geometry,
44 +
}
45 +
46 +
impl std::fmt::Display for ShaderKind {
47 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48 +
        match self {
49 +
            Self::Vertex => write!(f, "vertex"),
50 +
            Self::Fragment => write!(f, "fragment"),
51 +
            Self::Geometry => write!(f, "geometry"),
52 +
        }
53 +
    }
54 +
}
55 +
56 +
#[derive(Debug)]
57 +
pub struct ShaderSource<'a> {
58 +
    pub vertex: &'a str,
59 +
    pub fragment: &'a str,
60 +
    pub geometry: Option<&'a str>,
61 +
}
62 +
63 +
#[derive(Debug, Clone)]
64 +
pub struct ShaderDescriptor<'a> {
65 +
    pub uniforms: UniformBlockLayout<'a>,
66 +
    pub textures: &'a [&'a str],
67 +
}
68 +
69 +
/// Shader bindings
70 +
#[derive(Clone, Debug)]
71 +
pub struct Bindings<const V: usize = 1, const N: usize = 0> {
72 +
    /// Vertex buffers. Data contained in the buffer must match layout
73 +
    /// specified in the [`PipelineDescriptor`].
74 +
    pub vertex: [BufferId; V],
75 +
    /// Index buffer.
76 +
    pub index: Option<BufferId>,
77 +
    /// Textures that can be sampled from the fragment shader.
78 +
    pub textures: [TextureId; N],
79 +
}
ombre/src/gfx/stencil.rs added +44 -0
1 +
use super::*;
2 +
3 +
#[derive(Debug, Copy, Clone, PartialEq)]
4 +
pub struct StencilState {
5 +
    /// Front-facing fragment tests.
6 +
    pub front: StencilFaceState,
7 +
    /// Back-facing fragment tests.
8 +
    pub back: StencilFaceState,
9 +
    /// Specifies the reference value for the stencil test. Default is 0.
10 +
    pub reference: i32,
11 +
    /// Specifies a mask that is `&`ed with both the reference value and the stored stencil value
12 +
    /// when the test is done. The initial value is all 1's.
13 +
    pub read_mask: u32,
14 +
    /// Specifies a bit mask to enable and disable writing of individual bits in the stencil planes.
15 +
    /// Initially, the mask is all 1's.
16 +
    pub write_mask: u32,
17 +
}
18 +
19 +
#[derive(Debug, Copy, Clone, PartialEq)]
20 +
pub struct StencilFaceState {
21 +
    /// Used to determine if the stencil test passes or fails.
22 +
    pub compare: Comparison,
23 +
    /// Operation to use when stencil test fails.
24 +
    pub fail_op: StencilOp,
25 +
    /// Operation to use when stencil test passes, but depth test fails.
26 +
    pub depth_fail_op: StencilOp,
27 +
    /// Operation to use when both stencil and depth test pass,
28 +
    /// or when stencil pass and no depth or depth is disabled.
29 +
    pub pass_op: StencilOp,
30 +
}
31 +
32 +
/// Stencil operations performed on value after comparison.
33 +
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
34 +
pub enum StencilOp {
35 +
    #[default]
36 +
    Keep,
37 +
    Zero,
38 +
    Replace,
39 +
    IncrementClamp,
40 +
    DecrementClamp,
41 +
    Invert,
42 +
    IncrementWrap,
43 +
    DecrementWrap,
44 +
}
ombre/src/gfx/texture.rs added +152 -0
1 +
use super::*;
2 +
3 +
#[derive(Clone, Debug, Copy, PartialEq, Eq, Hash)]
4 +
pub struct TextureId(id::Id);
5 +
6 +
impl std::fmt::Display for TextureId {
7 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8 +
        self.0.fmt(f)
9 +
    }
10 +
}
11 +
12 +
impl TextureId {
13 +
    /// Get the next texture id.
14 +
    pub fn next() -> Self {
15 +
        Self(id::next())
16 +
    }
17 +
}
18 +
19 +
#[derive(Clone, Copy, Debug, PartialEq, Hash, Default)]
20 +
pub enum FilterMode {
21 +
    Linear,
22 +
    #[default]
23 +
    Nearest,
24 +
}
25 +
26 +
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
27 +
pub enum TextureAccess {
28 +
    /// A regular read-only texture.
29 +
    #[default]
30 +
    Static,
31 +
    /// Can be used as the output of a render pass.
32 +
    RenderTarget,
33 +
}
34 +
35 +
#[derive(Debug, Copy, Clone, PartialEq, Default)]
36 +
pub enum TextureKind {
37 +
    #[default]
38 +
    Texture2D,
39 +
    Texture2DArray {
40 +
        arity: u8,
41 +
    },
42 +
}
43 +
44 +
/// Supported texture formats.
45 +
#[repr(u8)]
46 +
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Default)]
47 +
pub enum TextureFormat {
48 +
    /// 32-bit RGB color with alpha.
49 +
    #[default]
50 +
    Rgba8,
51 +
    /// 24-bit RGB color.
52 +
    Rgb8,
53 +
    /// 24-bit sRGB color. Used for color textures that need gamma correction.
54 +
    Srgb8,
55 +
    /// 32-bit sRGB color with alpha. Used for color textures that need gamma correction.
56 +
    Srgba8,
57 +
    /// 32-bit floating point depth.
58 +
    Depth,
59 +
    /// 8-bit alpha.
60 +
    Alpha,
61 +
    /// 32-bit single-channel signed integers.
62 +
    /// Useful for storing object IDs, for example.
63 +
    Signed,
64 +
    /// 32-bit single-channel unsigned integers.
65 +
    /// Useful for storing object IDs, for example.
66 +
    Unsigned,
67 +
}
68 +
69 +
impl TextureFormat {
70 +
    /// Returns the size in bytes of a texture with the given dimensions.
71 +
    pub fn size<T: From<u32> + std::ops::Mul<Output = T>>(self, dimensions: Size<T>) -> T {
72 +
        let area = dimensions.area();
73 +
        match self {
74 +
            TextureFormat::Rgb8 => T::from(3) * area,
75 +
            TextureFormat::Rgba8 => T::from(4) * area,
76 +
            TextureFormat::Srgb8 => T::from(3) * area,
77 +
            TextureFormat::Srgba8 => T::from(4) * area,
78 +
            TextureFormat::Depth => T::from(4) * area,
79 +
            TextureFormat::Alpha => T::from(1) * area,
80 +
            TextureFormat::Signed => T::from(4) * area,
81 +
            TextureFormat::Unsigned => T::from(4) * area,
82 +
        }
83 +
    }
84 +
}
85 +
86 +
/// How texture sampling should wrap.
87 +
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
88 +
pub enum TextureWrap {
89 +
    /// Samples at coordinate `x + 1` map to `1`.
90 +
    #[default]
91 +
    Clamp,
92 +
    /// Samples at coordinate `x + 1` map to `x`.
93 +
    Repeat,
94 +
    /// Samples at coordinate `x + 1` map to `1 - x`.
95 +
    Mirror,
96 +
}
97 +
98 +
/// Describes a texture.
99 +
#[derive(Debug, Clone)]
100 +
pub struct Texture<T> {
101 +
    pub data: T,
102 +
    pub size: Size<u32>,
103 +
    pub access: TextureAccess,
104 +
    pub target: TextureKind,
105 +
    pub format: TextureFormat,
106 +
    pub wrap: TextureWrap,
107 +
    pub min_filter: FilterMode,
108 +
    pub mag_filter: FilterMode,
109 +
}
110 +
111 +
impl Texture<[u8; 4]> {
112 +
    /// A white, 1x1 texture.
113 +
    pub const WHITE: Self = Self {
114 +
        data: [0xff, 0xff, 0xff, 0xff],
115 +
        size: Size::new(1, 1),
116 +
        access: TextureAccess::Static,
117 +
        target: TextureKind::Texture2D,
118 +
        format: TextureFormat::Rgba8,
119 +
        wrap: TextureWrap::Clamp,
120 +
        min_filter: FilterMode::Nearest,
121 +
        mag_filter: FilterMode::Nearest,
122 +
    };
123 +
}
124 +
125 +
impl Texture<[[u8; 4]; 1]> {
126 +
    /// A white, 1x1 texture.
127 +
    pub const WHITE: Self = Self {
128 +
        data: [[0xff, 0xff, 0xff, 0xff]],
129 +
        size: Size::new(1, 1),
130 +
        access: TextureAccess::Static,
131 +
        target: TextureKind::Texture2D,
132 +
        format: TextureFormat::Rgba8,
133 +
        wrap: TextureWrap::Clamp,
134 +
        min_filter: FilterMode::Nearest,
135 +
        mag_filter: FilterMode::Nearest,
136 +
    };
137 +
}
138 +
139 +
impl<T: Default> Default for Texture<T> {
140 +
    fn default() -> Self {
141 +
        Texture {
142 +
            data: T::default(),
143 +
            access: TextureAccess::default(),
144 +
            target: TextureKind::default(),
145 +
            format: TextureFormat::default(),
146 +
            wrap: TextureWrap::default(),
147 +
            min_filter: FilterMode::default(),
148 +
            mag_filter: FilterMode::default(),
149 +
            size: Size::default(),
150 +
        }
151 +
    }
152 +
}
ombre/src/gfx/traits.rs added +184 -0
1 +
//! Graphics rendering traits, implemented by backends.
2 +
use crate::bytes::Packed;
3 +
use crate::collections::IntMap;
4 +
5 +
use super::*;
6 +
7 +
/// Graphics rendering backend.
8 +
/// This trait is implemented by compatible backends, eg. OpenGL, Vulkan etc.
9 +
pub trait RenderBackend: EventHandlerBackend {
10 +
    /// Information returned by the backend.
11 +
    type Info: std::fmt::Debug;
12 +
    /// The frame builder, created and dropped every frame.
13 +
    type Frame<'a>: RenderFrame<'a, Backend = Self, Error = Self::Error>
14 +
    where
15 +
        Self: 'a;
16 +
    /// Error returned by trait methods.
17 +
    type Error: std::error::Error + 'static;
18 +
    /// Texture handle.
19 +
    type TextureHandle;
20 +
21 +
    /// Return information about the backend.
22 +
    fn info(&self) -> Self::Info;
23 +
    /// Create a [`Self::Frame`] object.
24 +
    fn frame(&mut self) -> Self::Frame<'_>;
25 +
    /// Create a new shader program.
26 +
    fn shader(
27 +
        &mut self,
28 +
        shader: ShaderSource<'_>,
29 +
        meta: ShaderDescriptor<'_>,
30 +
    ) -> Result<ShaderId, Self::Error>;
31 +
32 +
    /// Create a new texture. Can be used for render targets as well.
33 +
    fn texture<T: TextureData>(&mut self, texture: Texture<T>) -> Result<TextureId, Self::Error>;
34 +
    /// Set the texture filter mode.
35 +
    fn texture_set_filter(&mut self, texture: TextureId, filter: FilterMode) {
36 +
        self.texture_set_min_filter(texture, filter);
37 +
        self.texture_set_mag_filter(texture, filter);
38 +
    }
39 +
    /// Set the texture *min* filter mode.
40 +
    fn texture_set_min_filter(&mut self, texture: TextureId, filter: FilterMode);
41 +
    /// Set the texture *mag* filter mode.
42 +
    fn texture_set_mag_filter(&mut self, texture: TextureId, filter: FilterMode);
43 +
    /// Set the texture wrap mode.
44 +
    fn texture_set_wrap(&mut self, texture: TextureId, wrap: TextureWrap);
45 +
    /// Resize texture.
46 +
    fn texture_resize(
47 +
        &mut self,
48 +
        texture: TextureId,
49 +
        size: Size<u32>,
50 +
        bytes: &[color::Rgba8],
51 +
    ) -> Result<(), Self::Error>;
52 +
    /// Update texture area.
53 +
    fn texture_update(
54 +
        &mut self,
55 +
        texture: TextureId,
56 +
        area: Rect<u32>,
57 +
        pixels: &[color::Rgba8],
58 +
    ) -> Result<(), Self::Error>;
59 +
    /// Update texture layer area.
60 +
    fn texture_update_layer(
61 +
        &mut self,
62 +
        texture: TextureId,
63 +
        layer: u8,
64 +
        area: Rect<u32>,
65 +
        pixels: &[color::Rgba8],
66 +
    ) -> Result<(), Self::Error>;
67 +
    /// Delete texture.
68 +
    fn texture_delete(&mut self, texture: TextureId);
69 +
    /// Textures map.
70 +
    fn textures(&self) -> &IntMap<TextureId, Texture<Self::TextureHandle>>;
71 +
72 +
    /// Create a buffer resource object.
73 +
    fn buffer<T: Packed>(
74 +
        &mut self,
75 +
        kind: BufferKind,
76 +
        usage: BufferUsage,
77 +
        data: BufferSource<'_, T>,
78 +
    ) -> Result<BufferId, Self::Error>;
79 +
    /// Update a buffer object.
80 +
    fn buffer_update<T: Packed>(
81 +
        &mut self,
82 +
        buffer: BufferId,
83 +
        kind: BufferKind,
84 +
        offset: usize,
85 +
        data: &[T],
86 +
    ) -> Result<(), Self::Error>;
87 +
    /// Delete buffer object.
88 +
    fn buffer_delete(&mut self, buffer: BufferId, kind: BufferKind);
89 +
90 +
    /// Create a new render pass.
91 +
    fn pass(&mut self, desc: PassDescriptor<'_>) -> Result<PassId, Self::Error>;
92 +
    /// Resize all pass attachments.
93 +
    fn pass_resize_attachments(&mut self, pass: PassId, size: Size<u32>)
94 +
        -> Result<(), Self::Error>;
95 +
    /// Read pass color attachment into slice.
96 +
    fn pass_read_color_attachment<T>(
97 +
        &self,
98 +
        pass: PassId,
99 +
        attachment: usize,
100 +
        output: &mut [T],
101 +
    ) -> Result<(), Self::Error>;
102 +
    /// Read pass depth attachment into slice.
103 +
    fn pass_read_depth_attachment(
104 +
        &self,
105 +
        pass: PassId,
106 +
        output: &mut [f32],
107 +
    ) -> Result<(), Self::Error>;
108 +
    /// Delete a pass.
109 +
    fn pass_delete(&mut self, pass: PassId);
110 +
111 +
    /// Create a new render pipeline using the given shader.
112 +
    fn pipeline(
113 +
        &mut self,
114 +
        shader: ShaderId,
115 +
        desc: PipelineDescriptor<'_>,
116 +
    ) -> Result<PipelineId, Self::Error>;
117 +
}
118 +
119 +
/// Methods relating to event handling.
120 +
pub trait EventHandlerBackend {
121 +
    /// Handle a window resized event.
122 +
    /// This can be used to resize textures, for example.
123 +
    fn window_resized(&mut self, size: platform::LogicalSize);
124 +
}
125 +
126 +
/// A render frame. Created by calling [`RenderBackend::frame`] and finalized with
127 +
/// [`RenderFrame::commit`].
128 +
pub trait RenderFrame<'a> {
129 +
    /// Error returned by trait methods.
130 +
    type Error: std::error::Error + 'static;
131 +
    /// The render backend.
132 +
    type Backend: RenderBackend;
133 +
134 +
    /// Get a reference to the render backend.
135 +
    fn backend(&self) -> &Self::Backend;
136 +
    /// Get a mutable reference to the render backend.
137 +
    fn backend_mut(&mut self) -> &mut Self::Backend;
138 +
    /// Apply a render pipeline.
139 +
    fn apply_pipeline(&mut self, pipeline: &PipelineId) -> Result<(), Self::Error>;
140 +
    /// Set a new viewport rectangle.
141 +
    /// Should be applied after [`RenderFrame::begin_pass`].
142 +
    fn apply_viewport(&mut self, rect: Rect<i32>) -> Result<(), Self::Error>;
143 +
    /// Set a new scissor rectangle.
144 +
    /// Should be applied after [`RenderFrame::begin_pass`].
145 +
    fn apply_scissor(&mut self, rect: Rect<i32>) -> Result<(), Self::Error>;
146 +
    /// Apply shader bindings.
147 +
    fn apply_bindings<const V: usize, const N: usize>(
148 +
        &mut self,
149 +
        bindings: &Bindings<V, N>,
150 +
    ) -> Result<(), Self::Error>;
151 +
    /// Apply shader uniforms.
152 +
    fn apply_uniforms<T: AsBytes>(&mut self, uniforms: &T) -> Result<(), Self::Error>;
153 +
    /// Clear the view.
154 +
    fn clear(&mut self, color: Option<Rgba<f32>>, depth: Option<f32>, stencil: Option<i32>);
155 +
    /// Update a buffer. Same as [`RenderBackend::buffer_update`].
156 +
    fn buffer_update<T: Packed>(
157 +
        &mut self,
158 +
        buffer: BufferId,
159 +
        kind: BufferKind,
160 +
        offset: usize,
161 +
        data: &[T],
162 +
    ) -> Result<(), Self::Error>;
163 +
    /// Begin the final presentation pass. Drawing while this pass is active draws to the screen.
164 +
    fn begin_default_pass(&mut self, action: PassAction, size: impl Into<Size<u32>>);
165 +
    /// Begin an off-screen pass.
166 +
    fn begin_pass(&mut self, pass: PassId, action: PassAction);
167 +
    /// End the current pass.
168 +
    fn end_pass(&mut self);
169 +
    /// Draw elements using the currently applied bindings and pipeline.
170 +
    /// * `offset` specifies the starting offset in the index buffer.
171 +
    /// * `elements` specifies how many elements to draw from the index buffer.
172 +
    /// * `instances` specifies how many instances should be rendered.
173 +
    fn draw(&self, offset: usize, elements: usize, instances: usize) -> Result<(), Self::Error>;
174 +
    /// Finalize the frame, presenting it to the screen.
175 +
    fn commit(self);
176 +
}
177 +
178 +
/// Valid tetxure data must implement this trait.
179 +
pub trait TextureData: AsBytes {}
180 +
181 +
impl TextureData for &[Rgba8] {}
182 +
impl TextureData for Empty {}
183 +
impl<const N: usize> TextureData for [Rgba8; N] {}
184 +
impl<T, const N: usize, const M: usize> TextureData for [[T; N]; M] where T: Packed {}
ombre/src/gfx/uniform.rs added +215 -0
1 +
//! Shader uniforms.
2 +
use crate::color::Rgba;
3 +
use crate::math::{Point2D, Size, Transform3D, Vector2D, Vector3D, Vector4D};
4 +
5 +
/// Trait for types that can be used as uniforms
6 +
pub trait ToUniformKind {
7 +
    /// The corresponding UniformKind for this type
8 +
    const KIND: UniformKind;
9 +
    /// Distinct elements in the uniform. Use values greater than `1` for uniform arrays.
10 +
    const ARITY: usize = 1;
11 +
}
12 +
13 +
impl ToUniformKind for u32 {
14 +
    const KIND: UniformKind = UniformKind::UInt1;
15 +
}
16 +
17 +
impl ToUniformKind for [u32; 2] {
18 +
    const KIND: UniformKind = UniformKind::UInt2;
19 +
}
20 +
21 +
impl ToUniformKind for [u32; 3] {
22 +
    const KIND: UniformKind = UniformKind::UInt3;
23 +
}
24 +
25 +
impl ToUniformKind for [u32; 4] {
26 +
    const KIND: UniformKind = UniformKind::UInt4;
27 +
}
28 +
29 +
impl ToUniformKind for i32 {
30 +
    const KIND: UniformKind = UniformKind::Int1;
31 +
}
32 +
33 +
impl ToUniformKind for [i32; 2] {
34 +
    const KIND: UniformKind = UniformKind::Int2;
35 +
}
36 +
37 +
impl ToUniformKind for [i32; 3] {
38 +
    const KIND: UniformKind = UniformKind::Int3;
39 +
}
40 +
41 +
impl ToUniformKind for [i32; 4] {
42 +
    const KIND: UniformKind = UniformKind::Int4;
43 +
}
44 +
45 +
impl ToUniformKind for Vector2D<i32> {
46 +
    const KIND: UniformKind = UniformKind::Int2;
47 +
}
48 +
49 +
impl ToUniformKind for Vector3D<i32> {
50 +
    const KIND: UniformKind = UniformKind::Int3;
51 +
}
52 +
53 +
impl ToUniformKind for Vector4D<i32> {
54 +
    const KIND: UniformKind = UniformKind::Int4;
55 +
}
56 +
57 +
impl ToUniformKind for f32 {
58 +
    const KIND: UniformKind = UniformKind::Float1;
59 +
}
60 +
61 +
impl ToUniformKind for [f32; 2] {
62 +
    const KIND: UniformKind = UniformKind::Float2;
63 +
}
64 +
65 +
impl ToUniformKind for [f32; 3] {
66 +
    const KIND: UniformKind = UniformKind::Float3;
67 +
}
68 +
69 +
impl ToUniformKind for [f32; 4] {
70 +
    const KIND: UniformKind = UniformKind::Float4;
71 +
}
72 +
73 +
impl ToUniformKind for [[f32; 4]; 4] {
74 +
    const KIND: UniformKind = UniformKind::Mat4;
75 +
}
76 +
77 +
impl ToUniformKind for Rgba<f32> {
78 +
    const KIND: UniformKind = UniformKind::Float4;
79 +
}
80 +
81 +
impl ToUniformKind for Vector2D<f32> {
82 +
    const KIND: UniformKind = UniformKind::Float2;
83 +
}
84 +
85 +
impl ToUniformKind for Vector3D<f32> {
86 +
    const KIND: UniformKind = UniformKind::Float3;
87 +
}
88 +
89 +
impl ToUniformKind for Vector4D<f32> {
90 +
    const KIND: UniformKind = UniformKind::Float4;
91 +
}
92 +
93 +
impl ToUniformKind for Transform3D {
94 +
    const KIND: UniformKind = UniformKind::Mat4;
95 +
}
96 +
97 +
impl ToUniformKind for Point2D {
98 +
    const KIND: UniformKind = UniformKind::Float2;
99 +
}
100 +
101 +
impl ToUniformKind for Size<f32> {
102 +
    const KIND: UniformKind = UniformKind::Float2;
103 +
}
104 +
105 +
impl<T: ToUniformKind> ToUniformKind for &T {
106 +
    const KIND: UniformKind = T::KIND;
107 +
    const ARITY: usize = T::ARITY;
108 +
}
109 +
110 +
impl<const N: usize> ToUniformKind for [Size<u32>; N] {
111 +
    const KIND: UniformKind = UniformKind::UInt2;
112 +
    const ARITY: usize = N;
113 +
}
114 +
115 +
impl<const N: usize> ToUniformKind for [Size<f32>; N] {
116 +
    const KIND: UniformKind = UniformKind::Float2;
117 +
    const ARITY: usize = N;
118 +
}
119 +
120 +
impl<const N: usize> ToUniformKind for [Point2D<f32>; N] {
121 +
    const KIND: UniformKind = UniformKind::Float2;
122 +
    const ARITY: usize = N;
123 +
}
124 +
125 +
impl<const N: usize> ToUniformKind for [Vector2D<f32>; N] {
126 +
    const KIND: UniformKind = UniformKind::Float2;
127 +
    const ARITY: usize = N;
128 +
}
129 +
130 +
impl<const N: usize> ToUniformKind for [Vector3D<f32>; N] {
131 +
    const KIND: UniformKind = UniformKind::Float3;
132 +
    const ARITY: usize = N;
133 +
}
134 +
135 +
impl<const N: usize> ToUniformKind for [Vector4D<f32>; N] {
136 +
    const KIND: UniformKind = UniformKind::Float4;
137 +
    const ARITY: usize = N;
138 +
}
139 +
140 +
impl<const N: usize> ToUniformKind for [Transform3D; N] {
141 +
    const KIND: UniformKind = UniformKind::Mat4;
142 +
    const ARITY: usize = N;
143 +
}
144 +
145 +
/// Uniform type.
146 +
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
147 +
pub enum UniformKind {
148 +
    /// One 32-bit wide float (equivalent to `f32`).
149 +
    Float1,
150 +
    /// Two 32-bit wide floats (equivalent to `[f32; 2]`).
151 +
    Float2,
152 +
    /// Three 32-bit wide floats (equivalent to `[f32; 3]`).
153 +
    Float3,
154 +
    /// Four 32-bit wide floats (equivalent to `[f32; 4]`).
155 +
    Float4,
156 +
    /// One unsigned 32-bit integer (equivalent to `[u32; 1]`).
157 +
    UInt1,
158 +
    /// Two unsigned 32-bit integers (equivalent to `[u32; 2]`).
159 +
    UInt2,
160 +
    /// Three unsigned 32-bit integers (equivalent to `[u32; 3]`).
161 +
    UInt3,
162 +
    /// Four unsigned 32-bit integers (equivalent to `[u32; 4]`).
163 +
    UInt4,
164 +
    /// One signed 32-bit integer (equivalent to `[i32; 1]`).
165 +
    Int1,
166 +
    /// Two signed 32-bit integers (equivalent to `[i32; 2]`).
167 +
    Int2,
168 +
    /// Three signed 32-bit integers (equivalent to `[i32; 3]`).
169 +
    Int3,
170 +
    /// Four signed 32-bit integers (equivalent to `[i32; 4]`).
171 +
    Int4,
172 +
    /// Four by four matrix of 32-bit floats.
173 +
    Mat4,
174 +
}
175 +
176 +
impl UniformKind {
177 +
    /// Byte size for a given uniform type.
178 +
    pub fn size(&self) -> usize {
179 +
        match self {
180 +
            UniformKind::Float1 => 4,
181 +
            UniformKind::Float2 => 8,
182 +
            UniformKind::Float3 => 12,
183 +
            UniformKind::Float4 => 16,
184 +
            UniformKind::UInt1 | UniformKind::Int1 => 4,
185 +
            UniformKind::UInt2 | UniformKind::Int2 => 8,
186 +
            UniformKind::UInt3 | UniformKind::Int3 => 12,
187 +
            UniformKind::UInt4 | UniformKind::Int4 => 16,
188 +
            UniformKind::Mat4 => 64,
189 +
        }
190 +
    }
191 +
}
192 +
193 +
/// Describes a shader uniform.
194 +
#[derive(Debug, Clone)]
195 +
pub struct UniformDescriptor<'a> {
196 +
    /// Uniform name.
197 +
    pub name: &'a str,
198 +
    /// Uniform type.
199 +
    pub kind: UniformKind,
200 +
    /// Array length, for arrays.
201 +
    pub arity: usize,
202 +
}
203 +
204 +
/// A uniform block layout descriptor.
205 +
#[derive(Debug, Clone)]
206 +
pub struct UniformBlockLayout<'a> {
207 +
    /// The uniforms in the block.
208 +
    pub uniforms: &'a [UniformDescriptor<'a>],
209 +
}
210 +
211 +
/// Trait for types that can provide their uniform block layout.
212 +
pub trait UniformBlock<'a> {
213 +
    /// Get the uniform block layout for this type.
214 +
    fn layout() -> UniformBlockLayout<'a>;
215 +
}
ombre/src/lenses.rs added +24 -0
1 +
//! Functional lenses.
2 +
3 +
/// Functional lens.
4 +
pub trait Lens<T: ?Sized, U: ?Sized> {
5 +
    /// Focus immutably.
6 +
    fn with<V, F: FnOnce(&U) -> V>(&self, data: &T, f: F) -> V;
7 +
    /// Focus mutably.
8 +
    fn with_mut<V, F: FnOnce(&mut U) -> V>(&self, data: &mut T, f: F) -> V;
9 +
}
10 +
11 +
/// A lens that always gives the same value and discards changes.
12 +
#[derive(Debug, Copy, Clone)]
13 +
pub struct Constant<T>(pub T);
14 +
15 +
impl<A, B: Clone> Lens<A, B> for Constant<B> {
16 +
    fn with<V, F: FnOnce(&B) -> V>(&self, _: &A, f: F) -> V {
17 +
        f(&self.0)
18 +
    }
19 +
20 +
    fn with_mut<V, F: FnOnce(&mut B) -> V>(&self, _: &mut A, f: F) -> V {
21 +
        let mut tmp = self.0.clone();
22 +
        f(&mut tmp)
23 +
    }
24 +
}
ombre/src/lib.rs added +46 -0
1 +
#![allow(clippy::collapsible_else_if)]
2 +
#![allow(clippy::too_many_arguments)]
3 +
#![allow(clippy::single_match)]
4 +
#![allow(clippy::collapsible_match)]
5 +
#![allow(clippy::identity_op)]
6 +
#![warn(clippy::unwrap_used)]
7 +
8 +
#[cfg(feature = "draw")]
9 +
extern crate self as ombre;
10 +
11 +
pub mod bench;
12 +
pub mod bytes;
13 +
pub mod collections;
14 +
#[cfg(feature = "draw")]
15 +
pub mod draw;
16 +
pub mod gfx;
17 +
pub mod lenses;
18 +
pub mod lisp;
19 +
pub mod logger;
20 +
pub mod math;
21 +
pub mod platform;
22 +
pub mod rng;
23 +
pub mod runtime;
24 +
pub mod string;
25 +
#[cfg(feature = "ui")]
26 +
pub mod ui;
27 +
28 +
#[cfg(feature = "derive")]
29 +
pub mod derive;
30 +
#[cfg(feature = "derive")]
31 +
pub use derive::*;
32 +
33 +
pub use gfx::color;
34 +
pub use glow;
35 +
36 +
/// Crate prelude.
37 +
pub mod prelude {
38 +
    pub use super::bytes;
39 +
    pub use super::gfx;
40 +
    pub use super::gfx::*;
41 +
    pub use super::math::{
42 +
        coord::*, Point2D, Rect, Size, Transform3D, Vector2D, Vector3D, Zero as _,
43 +
    };
44 +
    pub use super::runtime::{Application, ApplicationExt, Simulation, SimulationCtx};
45 +
    pub use super::{logger, platform, runtime};
46 +
}
ombre/src/lisp.rs added +39 -0
1 +
#![warn(missing_docs)]
2 +
//! An interpreter for a lisp dialect.
3 +
//!
4 +
//! There are three phases through which code is transformed:
5 +
//!
6 +
//! 1. Scanner: transforms the input string into tokens
7 +
//! 2. Parser: transforms the tokens into an abstract syntax tree (AST) made of expressions
8 +
//! 3. Evaluator: Evaluates the program represented by the AST
9 +
//!
10 +
//! Each phase is an iterator which feeds into the next.
11 +
pub mod dynamic;
12 +
pub mod evaluator;
13 +
pub mod list;
14 +
pub mod parser;
15 +
pub mod scanner;
16 +
17 +
use std::error::Error;
18 +
19 +
pub use evaluator::{Env, Evaluator, Expr};
20 +
pub use parser::Parser;
21 +
pub use scanner::Scanner;
22 +
23 +
/// Build a syntax tree from the input string.
24 +
pub fn parse(input: &str) -> impl Iterator<Item = parser::Result<Expr>> + '_ {
25 +
    Parser::new(Scanner::new(input))
26 +
}
27 +
28 +
/// Evaluate expressions returned by a parser. Returns the result and modified environment.
29 +
pub fn evaluate<E: Error + 'static>(
30 +
    exprs: impl Iterator<Item = Result<Expr, E>>,
31 +
    env: &mut evaluator::Env<'_>,
32 +
) -> evaluator::Result<Expr> {
33 +
    Evaluator::new(exprs).eval(env)
34 +
}
35 +
36 +
/// Execute a program as a string, returning the result.
37 +
pub fn execute(input: &str, env: &mut evaluator::Env<'_>) -> evaluator::Result<Expr> {
38 +
    evaluate(parse(input), env)
39 +
}
ombre/src/lisp/dynamic.rs added +87 -0
1 +
//! Dynamic type support. Extends the language with user-defined types.
2 +
use std::any::Any;
3 +
use std::fmt;
4 +
use std::rc::Rc;
5 +
6 +
use crate::lisp::evaluator::Expr;
7 +
8 +
/// Dynamic type.
9 +
#[derive(Clone)]
10 +
pub struct Dynamic(Rc<dyn IsDynamic>);
11 +
12 +
impl Dynamic {
13 +
    /// Create a new dynamic object.
14 +
    pub fn new<T: IsDynamic>(value: T) -> Self {
15 +
        Self(Rc::new(value))
16 +
    }
17 +
18 +
    /// Try to cast to a concrete type.
19 +
    pub fn downcast_ref<T: 'static>(&self) -> Option<&T> {
20 +
        self.0.as_any().downcast_ref()
21 +
    }
22 +
23 +
    /// Try to cast to a concrete type, giving ownership.
24 +
    /// Returns `None` if there are other references to the inner type.
25 +
    pub fn downcast<T: 'static>(self) -> Option<T> {
26 +
        let concrete = Rc::downcast::<T>(self.0.as_any_rc()).ok()?;
27 +
        let inner = Rc::try_unwrap(concrete).ok()?;
28 +
29 +
        Some(inner)
30 +
    }
31 +
}
32 +
33 +
impl From<Dynamic> for Expr {
34 +
    fn from(value: Dynamic) -> Self {
35 +
        Expr::Dynamic(value)
36 +
    }
37 +
}
38 +
39 +
impl PartialEq for Dynamic {
40 +
    fn eq(&self, other: &Self) -> bool {
41 +
        self.0.eq(&*other.0)
42 +
    }
43 +
}
44 +
45 +
impl fmt::Debug for Dynamic {
46 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 +
        self.0.fmt(f)
48 +
    }
49 +
}
50 +
51 +
/// Helper trait to faciliate downcasting of [`IsDynamic`].
52 +
pub trait AsAny: Any {
53 +
    /// Convert to [`Any`].
54 +
    fn as_any(&self) -> &dyn Any;
55 +
    /// Convert to mutable [`Any`].
56 +
    #[allow(dead_code)]
57 +
    fn as_any_mut(&mut self) -> &mut dyn Any;
58 +
    /// Convert to a [`Box<dyn Any>`].
59 +
    #[allow(dead_code)]
60 +
    fn as_any_box(self: Box<Self>) -> Box<dyn Any>;
61 +
    /// Convert to a [`Rc<dyn Any>`].
62 +
    fn as_any_rc(self: Rc<Self>) -> Rc<dyn Any>;
63 +
}
64 +
65 +
impl<T: Any> AsAny for T {
66 +
    fn as_any_box(self: Box<Self>) -> Box<dyn Any> {
67 +
        self
68 +
    }
69 +
70 +
    fn as_any_rc(self: Rc<Self>) -> Rc<dyn Any> {
71 +
        self
72 +
    }
73 +
74 +
    fn as_any(&self) -> &dyn Any {
75 +
        self
76 +
    }
77 +
78 +
    fn as_any_mut(&mut self) -> &mut dyn Any {
79 +
        self
80 +
    }
81 +
}
82 +
83 +
/// Any dynamic type.
84 +
pub trait IsDynamic: fmt::Debug + AsAny {
85 +
    /// Check equality with another dynamic type.
86 +
    fn eq(&self, other: &dyn IsDynamic) -> bool;
87 +
}
ombre/src/lisp/evaluator.rs added +2106 -0
1 +
//! Expression evaluator.
2 +
use std::cell::RefCell;
3 +
use std::fmt;
4 +
use std::ops::{Deref, DerefMut};
5 +
use std::rc::Rc;
6 +
use std::result;
7 +
use std::{collections::HashMap, iter::Peekable};
8 +
9 +
use crate::gfx::Rgba8;
10 +
11 +
use crate::lisp::dynamic::Dynamic;
12 +
use crate::lisp::list::List;
13 +
14 +
/// Result type for all functions.
15 +
pub type Result<T, E = Error> = result::Result<T, E>;
16 +
17 +
/// Evaluation error.
18 +
#[derive(Debug)]
19 +
pub enum Error {
20 +
    /// Error coming from parsing stage.
21 +
    Parser(Box<dyn std::error::Error>),
22 +
    /// Undefined symbol.
23 +
    UndefinedSymbol(Symbol),
24 +
    /// Expected value of a certain type.
25 +
    ExpectedValue(&'static str),
26 +
    /// Expected value for named argument.
27 +
    ExpectedNamedValue(Symbol),
28 +
    /// Unexpected value.
29 +
    UnexpectedValue(Expr),
30 +
    /// Unexpected named argument.
31 +
    UnexpectedNamedArgument(Symbol),
32 +
    /// Wrong number of arguments supplied.
33 +
    WrongArgumentCount {
34 +
        /// Expected count.
35 +
        expected: usize,
36 +
        /// Actual count.
37 +
        actual: usize,
38 +
    },
39 +
    /// Invalid function argument.
40 +
    InvalidArgument,
41 +
    /// Error raised by user.
42 +
    User(Expr),
43 +
}
44 +
45 +
impl fmt::Display for Error {
46 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 +
        match self {
48 +
            Error::Parser(e) => write!(f, "parser: {e}"),
49 +
            Error::UndefinedSymbol(s) => write!(f, "undefined symbol: {s}"),
50 +
            Error::ExpectedValue(s) => write!(f, "expected value: {s}"),
51 +
            Error::ExpectedNamedValue(s) => write!(f, "expected named value: {s}"),
52 +
            Error::UnexpectedValue(e) => write!(f, "unexpected value: {e:?}"),
53 +
            Error::UnexpectedNamedArgument(s) => write!(f, "unexpected named argument: {s}"),
54 +
            Error::WrongArgumentCount { expected, actual } => {
55 +
                write!(f, "expected {expected} arguments, got {actual}")
56 +
            }
57 +
            Error::InvalidArgument => write!(f, "invalid argument"),
58 +
            Error::User(e) => write!(f, "user error: {e:?}"),
59 +
        }
60 +
    }
61 +
}
62 +
63 +
/// A symbol is an immutable string.
64 +
pub type Symbol = Rc<str>;
65 +
66 +
/// Values that can be used as dictionary keys.
67 +
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
68 +
pub enum Key {
69 +
    /// Eg. :true
70 +
    Bool(bool),
71 +
    /// Eg. :yikes
72 +
    Atom(Rc<str>),
73 +
    /// Eg. "fnord"
74 +
    Str(String),
75 +
    /// Eg. 42
76 +
    Integer(i64),
77 +
    /// Eg. `z`
78 +
    Char(char),
79 +
    /// Eg. #44ff88
80 +
    Color(Rgba8),
81 +
}
82 +
83 +
impl TryFrom<Expr> for Key {
84 +
    type Error = Expr;
85 +
86 +
    fn try_from(e: Expr) -> result::Result<Self, Self::Error> {
87 +
        let key = match e {
88 +
            Expr::Bool(k) => Key::Bool(k),
89 +
            Expr::Atom(k) => Key::Atom(k),
90 +
            Expr::Str(k) => Key::Str(k),
91 +
            Expr::Integer(k) => Key::Integer(k),
92 +
            Expr::Char(k) => Key::Char(k),
93 +
            Expr::Color(k) => Key::Color(k),
94 +
            _ => return Err(e),
95 +
        };
96 +
        Ok(key)
97 +
    }
98 +
}
99 +
100 +
/// Expression in the language.
101 +
#[derive(Debug, Clone, PartialEq)]
102 +
pub enum Expr {
103 +
    /// Eg. (1 2 3)
104 +
    List(List<Expr>),
105 +
    /// Eg. :true
106 +
    Bool(bool),
107 +
    /// Eg. 'fnord
108 +
    Quoted(Box<Expr>),
109 +
    /// Eg. [1 2 3]
110 +
    Vector(Vec<Expr>),
111 +
    /// Eg. (dict {:a 1 :b 2 :c 3})
112 +
    Dict(HashMap<Key, Expr>),
113 +
    /// Eg. fnord
114 +
    Symbol(Symbol),
115 +
    /// Eg. :yikes
116 +
    Atom(Rc<str>),
117 +
    /// Eg. "fnord"
118 +
    Str(String),
119 +
    /// Eg. 42.194
120 +
    Float(f64),
121 +
    /// Eg. 42
122 +
    Integer(i64),
123 +
    /// Eg. `z`
124 +
    Char(char),
125 +
    /// Eg. #44ff88
126 +
    Color(Rgba8),
127 +
    /// Eg. (fn [x y] (+ x y))
128 +
    Function(Function),
129 +
    /// Mutable reference.
130 +
    Ref(Rc<RefCell<Expr>>),
131 +
    /// Dynamic type. Can be any Rust type.
132 +
    Dynamic(Dynamic),
133 +
}
134 +
135 +
impl Expr {
136 +
    /// The empty list, or "nil".
137 +
    pub fn nil() -> Self {
138 +
        Self::List(List::default())
139 +
    }
140 +
141 +
    /// Check if this expression is the empty list.
142 +
    pub fn is_nil(&self) -> bool {
143 +
        matches!(self, Self::List(l) if l.is_empty())
144 +
    }
145 +
146 +
    /// Construct a list.
147 +
    pub fn list(items: impl Into<List<Expr>>) -> Self {
148 +
        Expr::List(items.into())
149 +
    }
150 +
151 +
    /// Construct a vector.
152 +
    pub fn vector(items: impl IntoIterator<Item = Expr>) -> Self {
153 +
        Expr::Vector(items.into_iter().collect())
154 +
    }
155 +
156 +
    /// Construct a symbol.
157 +
    pub fn symbol(name: impl Into<Rc<str>>) -> Self {
158 +
        Expr::Symbol(name.into())
159 +
    }
160 +
161 +
    /// Quote an expression.
162 +
    pub fn quoted(self) -> Self {
163 +
        Expr::Quoted(Box::new(self))
164 +
    }
165 +
}
166 +
167 +
impl From<f64> for Expr {
168 +
    fn from(value: f64) -> Self {
169 +
        Expr::Float(value)
170 +
    }
171 +
}
172 +
173 +
impl From<i64> for Expr {
174 +
    fn from(value: i64) -> Self {
175 +
        Expr::Integer(value)
176 +
    }
177 +
}
178 +
179 +
impl From<bool> for Expr {
180 +
    fn from(value: bool) -> Self {
181 +
        Expr::Bool(value)
182 +
    }
183 +
}
184 +
185 +
impl From<Intrinsic> for Expr {
186 +
    fn from(value: Intrinsic) -> Self {
187 +
        Expr::Function(Function::Intrinsic(Rc::new(value)))
188 +
    }
189 +
}
190 +
191 +
impl From<Closure> for Expr {
192 +
    fn from(value: Closure) -> Self {
193 +
        Expr::Function(Function::Closure(Rc::new(value)))
194 +
    }
195 +
}
196 +
197 +
impl TryFrom<Expr> for f64 {
198 +
    type Error = Expr;
199 +
200 +
    fn try_from(expr: Expr) -> std::result::Result<Self, Self::Error> {
201 +
        match expr {
202 +
            Expr::Float(n) => Ok(n),
203 +
            _ => Err(expr),
204 +
        }
205 +
    }
206 +
}
207 +
208 +
impl TryFrom<Expr> for i64 {
209 +
    type Error = Expr;
210 +
211 +
    fn try_from(expr: Expr) -> std::result::Result<Self, Self::Error> {
212 +
        match expr {
213 +
            Expr::Integer(n) => Ok(n),
214 +
            _ => Err(expr),
215 +
        }
216 +
    }
217 +
}
218 +
219 +
impl TryFrom<Expr> for bool {
220 +
    type Error = Expr;
221 +
222 +
    fn try_from(expr: Expr) -> std::result::Result<Self, Self::Error> {
223 +
        match expr {
224 +
            Expr::Bool(b) => Ok(b),
225 +
            _ => Err(expr),
226 +
        }
227 +
    }
228 +
}
229 +
230 +
/// Built-in or user-defined function.
231 +
#[derive(Debug, Clone)]
232 +
pub enum Function {
233 +
    /// A function that closes over some environment.
234 +
    Closure(Rc<Closure>),
235 +
    /// A built-in function implemented natively.
236 +
    Intrinsic(Rc<Intrinsic>),
237 +
}
238 +
239 +
impl Function {
240 +
    /// Apply the function.
241 +
    fn apply(&self, args: impl Iterator<Item = Expr>, env: &mut Env<'_>) -> Result<Expr> {
242 +
        let args = args.map(|a| eval(a, env)).collect::<Result<Vec<_>>>()?;
243 +
244 +
        match self {
245 +
            Self::Closure(f) => {
246 +
                let env = Env {
247 +
                    local: if let Some(name) = &f.name {
248 +
                        HashMap::from_iter([(
249 +
                            name.to_owned(),
250 +
                            Expr::Function(Function::Closure(f.clone())),
251 +
                        )])
252 +
                    } else {
253 +
                        HashMap::new()
254 +
                    },
255 +
                    docs: HashMap::new(),
256 +
                    parent: None,
257 +
                };
258 +
                let result = f.call(args, &env)?;
259 +
260 +
                Ok(result)
261 +
            }
262 +
            Self::Intrinsic(f) => {
263 +
                let result = f.call(args, env)?;
264 +
265 +
                Ok(result)
266 +
            }
267 +
        }
268 +
    }
269 +
}
270 +
271 +
impl PartialEq for Function {
272 +
    fn eq(&self, other: &Self) -> bool {
273 +
        match (self, other) {
274 +
            (Self::Closure(ref a), Self::Closure(ref b)) => Rc::ptr_eq(a, b),
275 +
            (Self::Intrinsic(ref a), Self::Intrinsic(ref b)) => Rc::ptr_eq(a, b),
276 +
            _ => false,
277 +
        }
278 +
    }
279 +
}
280 +
281 +
/// User-defined function that closes over an environment.
282 +
#[derive(Debug, PartialEq)]
283 +
pub struct Closure {
284 +
    /// Binding name, if bound. This is used for recursive calls.
285 +
    name: Option<Symbol>,
286 +
    /// Positional parameters.
287 +
    positional: Vec<Symbol>,
288 +
    /// Named parameters with default values.
289 +
    named: HashMap<Symbol, Expr>,
290 +
    /// Expressions to be evaluated on call.
291 +
    body: Vec<Expr>,
292 +
    /// Closure static environment.
293 +
    env: Env<'static>,
294 +
}
295 +
296 +
impl Closure {
297 +
    /// Evaluate the function body.
298 +
    fn call(&self, args: Vec<Expr>, env: &Env<'_>) -> Result<Expr> {
299 +
        let mut local = self.env.local.clone();
300 +
        let mut args = args.into_iter();
301 +
302 +
        // Handle positional arguments.
303 +
        for formal in &self.positional {
304 +
            if let Some(arg) = args.next() {
305 +
                local.insert(formal.clone(), arg);
306 +
            } else {
307 +
                return Err(Error::WrongArgumentCount {
308 +
                    expected: self.positional.len(),
309 +
                    actual: local.len(),
310 +
                });
311 +
            }
312 +
        }
313 +
314 +
        // Handle named arguments.
315 +
        let mut named_args = HashMap::new();
316 +
        while let Some(arg) = args.next() {
317 +
            if let Expr::Atom(name) = arg {
318 +
                if let Some(value) = args.next() {
319 +
                    named_args.insert(name, value);
320 +
                } else {
321 +
                    return Err(Error::ExpectedNamedValue(name));
322 +
                }
323 +
            } else {
324 +
                return Err(Error::InvalidArgument);
325 +
            }
326 +
        }
327 +
        for (name, default) in &self.named {
328 +
            local.insert(
329 +
                name.clone(),
330 +
                named_args.remove(name).unwrap_or_else(|| default.clone()),
331 +
            );
332 +
        }
333 +
334 +
        // Extra arguments passed that are not recognized.
335 +
        if let Some((name, _)) = named_args.into_iter().next() {
336 +
            return Err(Error::UnexpectedNamedArgument(name));
337 +
        }
338 +
339 +
        let mut env = Env {
340 +
            local,
341 +
            docs: HashMap::new(),
342 +
            parent: Some(env),
343 +
        };
344 +
        eval_iter(self.body.clone(), &mut env)
345 +
    }
346 +
}
347 +
348 +
/// Built-in function intrinsic to the language.
349 +
pub struct Intrinsic(Rc<dyn Fn(Vec<Expr>, &Env<'_>) -> Result<Expr>>);
350 +
351 +
impl PartialEq for Intrinsic {
352 +
    fn eq(&self, other: &Self) -> bool {
353 +
        Rc::ptr_eq(&self.0, &other.0)
354 +
    }
355 +
}
356 +
357 +
impl std::fmt::Debug for Intrinsic {
358 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
359 +
        f.debug_tuple("Intrinsic")
360 +
            .field(&format!("{:p}", Rc::as_ptr(&self.0)))
361 +
            .finish()
362 +
    }
363 +
}
364 +
365 +
impl Intrinsic {
366 +
    /// Call the intrinsic function.
367 +
    fn call(&self, args: Vec<Expr>, env: &Env<'_>) -> Result<Expr> {
368 +
        (self.0)(args, env)
369 +
    }
370 +
}
371 +
372 +
/// Lexical environment.
373 +
#[derive(Debug, Clone, PartialEq)]
374 +
pub struct Env<'a> {
375 +
    /// This environment's bindings.
376 +
    local: HashMap<Symbol, Expr>,
377 +
    /// Docstrings for bindings.
378 +
    docs: HashMap<Symbol, String>,
379 +
    /// Parent environment.
380 +
    parent: Option<&'a Env<'a>>,
381 +
}
382 +
383 +
impl<'a> Env<'a> {
384 +
    /// Add intrinsics to this evaluator. Returns a new evaluator with the specified
385 +
    /// intrinsics.
386 +
    pub fn intrinsics<'b, 'c, F>(
387 +
        mut self,
388 +
        fns: impl IntoIterator<Item = (&'b str, &'c str, F)>,
389 +
    ) -> Self
390 +
    where
391 +
        F: Fn(Vec<Expr>, &Env<'_>) -> Result<Expr> + 'static,
392 +
    {
393 +
        for (name, docs, f) in fns.into_iter() {
394 +
            self.intrinsic(name, docs, f);
395 +
        }
396 +
        self
397 +
    }
398 +
399 +
    /// Lookup a symbol.
400 +
    pub fn lookup(&self, name: &str) -> Option<&Expr> {
401 +
        if let Some(expr) = self.local.get(name) {
402 +
            return Some(expr);
403 +
        }
404 +
        if let Some(parent) = self.parent {
405 +
            return parent.lookup(name);
406 +
        }
407 +
        None
408 +
    }
409 +
410 +
    /// Get the docstring for a symbol.
411 +
    #[allow(dead_code)]
412 +
    pub fn lookup_doc(&self, name: &str) -> Option<&str> {
413 +
        self.docs
414 +
            .get(name)
415 +
            .map(String::as_str)
416 +
            .or_else(|| self.parent.and_then(|p| p.lookup_doc(name)))
417 +
    }
418 +
419 +
    /// Flatten the environemnt into a single [`HashMap`].
420 +
    pub fn flatten(&self) -> HashMap<Symbol, Expr> {
421 +
        let mut env = self.local.clone();
422 +
        if let Some(p) = self.parent {
423 +
            env.extend(p.flatten());
424 +
        }
425 +
        env
426 +
    }
427 +
428 +
    /// Define an intrinsic.
429 +
    pub fn intrinsic(
430 +
        &mut self,
431 +
        name: &str,
432 +
        docstr: &str,
433 +
        f: impl Fn(Vec<Expr>, &Env<'_>) -> Result<Expr> + 'static,
434 +
    ) {
435 +
        self.binding(name, Some(docstr), Intrinsic(Rc::new(f)).into());
436 +
    }
437 +
438 +
    /// Define a binding.
439 +
    pub fn binding(&mut self, name: &str, docstr: Option<&str>, expr: Expr) {
440 +
        self.insert(name.into(), expr);
441 +
442 +
        if let Some(doc) = docstr {
443 +
            self.docs.insert(name.into(), doc.to_string());
444 +
        }
445 +
    }
446 +
447 +
    /// Create a new env from a parent environemnt.
448 +
    pub fn from_parent(parent: &'a Env<'_>) -> Env<'a> {
449 +
        Env {
450 +
            parent: Some(parent),
451 +
            local: HashMap::new(),
452 +
            docs: HashMap::new(),
453 +
        }
454 +
    }
455 +
456 +
    /// Return a new env with the given bindings.
457 +
    pub fn with(&'a self, kvs: impl IntoIterator<Item = (Symbol, Expr)>) -> Env<'a> {
458 +
        Env {
459 +
            local: kvs.into_iter().collect(),
460 +
            docs: HashMap::new(),
461 +
            parent: Some(self),
462 +
        }
463 +
    }
464 +
}
465 +
466 +
impl Deref for Env<'_> {
467 +
    type Target = HashMap<Symbol, Expr>;
468 +
469 +
    fn deref(&self) -> &Self::Target {
470 +
        &self.local
471 +
    }
472 +
}
473 +
474 +
impl DerefMut for Env<'_> {
475 +
    fn deref_mut(&mut self) -> &mut Self::Target {
476 +
        &mut self.local
477 +
    }
478 +
}
479 +
480 +
impl Default for Env<'_> {
481 +
    fn default() -> Self {
482 +
        let mut env = Env {
483 +
            local: HashMap::default(),
484 +
            docs: HashMap::default(),
485 +
            parent: None,
486 +
        };
487 +
        env.intrinsic("+", "Add two or more numbers", intrinsic::add);
488 +
        env.intrinsic(
489 +
            "-",
490 +
            "Subtract numbers or negate a single number",
491 +
            intrinsic::sub,
492 +
        );
493 +
        env.intrinsic("*", "Multiply two or more numbers", intrinsic::mul);
494 +
        env.intrinsic(
495 +
            "/",
496 +
            "Divide numbers or calculate reciprocal of a single number",
497 +
            intrinsic::div,
498 +
        );
499 +
        env.intrinsic(
500 +
            "mod",
501 +
            "Calculate the modulo of two numbers",
502 +
            intrinsic::modulo,
503 +
        );
504 +
        env.intrinsic(
505 +
            "pow",
506 +
            "Raise a number to the power of another",
507 +
            intrinsic::pow,
508 +
        );
509 +
        env.intrinsic("eq?", "Check if all arguments are equal", intrinsic::eq);
510 +
        env.intrinsic(
511 +
            "and",
512 +
            "Logical *and* of two or more boolean values",
513 +
            intrinsic::and,
514 +
        );
515 +
        env.intrinsic(
516 +
            "or",
517 +
            "Logical *or* of two or more boolean values",
518 +
            intrinsic::or,
519 +
        );
520 +
        env.intrinsic(
521 +
            ">",
522 +
            "Check if the first argument is greater than the second",
523 +
            intrinsic::gt,
524 +
        );
525 +
        env.intrinsic(
526 +
            "<",
527 +
            "Check if the first argument is lesser than the second",
528 +
            intrinsic::lt,
529 +
        );
530 +
        env.intrinsic(
531 +
            ">=",
532 +
            "Check if the first argument is greater or equal than the second",
533 +
            intrinsic::gte,
534 +
        );
535 +
        env.intrinsic(
536 +
            "<=",
537 +
            "Check if the first argument is lesser or equal than the second",
538 +
            intrinsic::lte,
539 +
        );
540 +
        env.intrinsic(
541 +
            "max",
542 +
            "Find the maximum value among the arguments",
543 +
            intrinsic::max,
544 +
        );
545 +
        env.intrinsic(
546 +
            "min",
547 +
            "Find the minimum value among the arguments",
548 +
            intrinsic::min,
549 +
        );
550 +
        env.intrinsic("not", "Logical *not* of a boolean value", intrinsic::not);
551 +
        env.intrinsic(
552 +
            "first",
553 +
            "Get the first element of a list or vector",
554 +
            intrinsic::first,
555 +
        );
556 +
        env.intrinsic(
557 +
            "last",
558 +
            "Get the last element of a list or vector",
559 +
            intrinsic::last,
560 +
        );
561 +
        env.intrinsic(
562 +
            "nth",
563 +
            "Get the *nth* element of a list or vector",
564 +
            intrinsic::nth,
565 +
        );
566 +
        env.intrinsic(
567 +
            "list",
568 +
            "Create a new list from the given arguments",
569 +
            intrinsic::list,
570 +
        );
571 +
        env.intrinsic(
572 +
            "dict",
573 +
            "Create a new dictionary from the given list",
574 +
            intrinsic::dict,
575 +
        );
576 +
        env.intrinsic(
577 +
            "lookup",
578 +
            "Lookup a value in a dictionary, under the given key",
579 +
            intrinsic::lookup,
580 +
        );
581 +
        env.intrinsic(
582 +
            "cons",
583 +
            "Construct a new list from a value and an existing list",
584 +
            intrinsic::cons,
585 +
        );
586 +
        env.intrinsic(
587 +
            "map",
588 +
            "Apply a function to each element of a list or vector",
589 +
            intrinsic::map,
590 +
        );
591 +
        env.intrinsic("error", "Raise a user-defined error", intrinsic::error);
592 +
        env.intrinsic(
593 +
            "length",
594 +
            "Get the length of a list, vector, dictionary or string",
595 +
            intrinsic::length,
596 +
        );
597 +
        env.intrinsic(
598 +
            "contains?",
599 +
            "Check if a collection contains the given key",
600 +
            intrinsic::contains,
601 +
        );
602 +
        env.intrinsic("empty?", "Check if a collection is empty", intrinsic::empty);
603 +
        env.intrinsic("append", "Append elements to a vector", intrinsic::append);
604 +
        env.intrinsic("reverse", "Reverse a list or vector", intrinsic::reverse);
605 +
        env.intrinsic(
606 +
            "range",
607 +
            "Create a vector of numbers in a specified range",
608 +
            intrinsic::range,
609 +
        );
610 +
        env.intrinsic("ref", "Create a mutable reference", intrinsic::create_ref);
611 +
        env.intrinsic("deref", "Dereference a mutable reference", intrinsic::deref);
612 +
        env.intrinsic(
613 +
            "set!",
614 +
            "Set the value of a mutable reference",
615 +
            intrinsic::set_ref,
616 +
        );
617 +
        env.intrinsic(
618 +
            "modify!",
619 +
            "Modify a mutable reference in-place using a lambda",
620 +
            intrinsic::modify,
621 +
        );
622 +
        env
623 +
    }
624 +
}
625 +
626 +
/// Iterator over syntax tree which returns evaluated expressions.
627 +
pub struct Evaluator<T, E>
628 +
where
629 +
    T: IntoIterator<Item = Result<Expr, E>>,
630 +
    E: std::error::Error + 'static,
631 +
{
632 +
    exprs: Peekable<T::IntoIter>,
633 +
}
634 +
635 +
impl<T, E> Evaluator<T, E>
636 +
where
637 +
    T: Iterator<Item = Result<Expr, E>>,
638 +
    E: std::error::Error + 'static,
639 +
{
640 +
    /// Create a new evaluator.
641 +
    pub fn new(exprs: T) -> Self {
642 +
        Self {
643 +
            exprs: exprs.into_iter().peekable(),
644 +
        }
645 +
    }
646 +
647 +
    /// Evaluate expressions one by one and return the result of the last one.
648 +
    pub fn eval(self, env: &mut Env<'_>) -> Result<Expr, Error> {
649 +
        let mut result = Expr::nil();
650 +
651 +
        for expr in self.exprs {
652 +
            let expr = expr.map_err(|e| Error::Parser(Box::new(e)))?;
653 +
            result = eval(expr, env)?;
654 +
        }
655 +
        Ok(result)
656 +
    }
657 +
}
658 +
659 +
/// Evaluate a "let" expression.
660 +
fn eval_let(assignments: Vec<Expr>, body: Vec<Expr>, env: &mut Env<'_>) -> Result<Expr> {
661 +
    let mut kvs = Vec::new();
662 +
    for (k, v) in pairs(assignments)? {
663 +
        let Expr::Symbol(k) = k else {
664 +
            return Err(Error::ExpectedValue("symbol"));
665 +
        };
666 +
        let v = eval(v, env)?;
667 +
        kvs.push((k, v));
668 +
    }
669 +
    eval_iter(body, &mut env.with(kvs))
670 +
}
671 +
672 +
/// Evaluate a lambda expression, returning a closure object.
673 +
fn eval_lambda(formals: Vec<Expr>, body: Vec<Expr>, env: &Env<'_>) -> Result<Expr> {
674 +
    let local = env.flatten();
675 +
    let mut positional = Vec::new();
676 +
    let mut named = HashMap::new();
677 +
    let mut formals = formals.into_iter();
678 +
679 +
    while let Some(expr) = formals.next() {
680 +
        match expr {
681 +
            Expr::Symbol(param) => positional.push(param),
682 +
            Expr::Atom(name) => {
683 +
                let Some(default) = formals.next() else {
684 +
                    return Err(Error::ExpectedNamedValue(name));
685 +
                };
686 +
                named.insert(name, default);
687 +
            }
688 +
            _ => return Err(Error::ExpectedValue("symbol or atom")),
689 +
        }
690 +
    }
691 +
692 +
    Ok(Closure {
693 +
        name: None,
694 +
        positional,
695 +
        named,
696 +
        body,
697 +
        env: Env {
698 +
            local,
699 +
            docs: HashMap::new(),
700 +
            parent: None,
701 +
        },
702 +
    }
703 +
    .into())
704 +
}
705 +
706 +
/// Evaluate an iterator and return the last value.
707 +
fn eval_iter(iter: impl IntoIterator<Item = Expr>, env: &mut Env<'_>) -> Result<Expr> {
708 +
    Ok(iter
709 +
        .into_iter()
710 +
        .map(|e| eval(e, env))
711 +
        .collect::<Result<Vec<_>>>()?
712 +
        .pop()
713 +
        .unwrap_or(Expr::nil()))
714 +
}
715 +
716 +
/// Evaluate special forms and function application.
717 +
fn eval_list(sexpr: List<Expr>, env: &mut Env<'_>) -> Result<Expr> {
718 +
    let mut items = sexpr.iter().cloned(); // TODO: Can we avoid cloning here?
719 +
    let Some(head) = items.next() else {
720 +
        return Ok(Expr::nil());
721 +
    };
722 +
    if let Expr::Symbol(ref name) = head {
723 +
        match name.deref() {
724 +
            "def" => {
725 +
                let sym = items.next().ok_or(Error::ExpectedValue("symbol"))?;
726 +
                let Expr::Symbol(name) = sym else {
727 +
                    return Err(Error::UnexpectedValue(sym));
728 +
                };
729 +
                let (docstr, value) = match (items.next(), items.next()) {
730 +
                    (Some(Expr::Str(docstr)), Some(value)) => (Some(docstr), value),
731 +
                    (Some(value), None) => (None, value),
732 +
733 +
                    _ => return Err(Error::ExpectedValue("expression")),
734 +
                };
735 +
736 +
                match eval(value, env)? {
737 +
                    Expr::Function(Function::Closure(mut closure)) => {
738 +
                        if closure.name.is_none() {
739 +
                            if let Some(closure) = Rc::get_mut(&mut closure) {
740 +
                                closure.name = Some(Rc::clone(&name));
741 +
                            }
742 +
                        }
743 +
                        env.binding(
744 +
                            &name,
745 +
                            docstr.as_deref(),
746 +
                            Expr::Function(Function::Closure(closure)),
747 +
                        );
748 +
                    }
749 +
                    other => {
750 +
                        env.binding(&name, docstr.as_deref(), other);
751 +
                    }
752 +
                }
753 +
                Ok(Expr::nil())
754 +
            }
755 +
            "do" => eval_iter(items, env),
756 +
            "eval" => {
757 +
                let Some(expr) = items.next() else {
758 +
                    return Err(Error::ExpectedValue("expression"));
759 +
                };
760 +
                if let Some(e) = items.next() {
761 +
                    return Err(Error::UnexpectedValue(e));
762 +
                }
763 +
                eval(eval(expr, env)?, env)
764 +
            }
765 +
            "let" => {
766 +
                let assignments = items.next().ok_or(Error::ExpectedValue("vector"))?;
767 +
                let body = items.collect::<Vec<_>>();
768 +
769 +
                let Expr::Vector(assignments) = assignments else {
770 +
                    return Err(Error::UnexpectedValue(assignments));
771 +
                };
772 +
                if body.is_empty() {
773 +
                    return Err(Error::ExpectedValue("expression"));
774 +
                }
775 +
                eval_let(assignments, body, env)
776 +
            }
777 +
            "fn" => {
778 +
                let formals = items.next().ok_or(Error::ExpectedValue("vector"))?;
779 +
                let body = items.collect::<Vec<_>>();
780 +
781 +
                let Expr::Vector(formals) = formals else {
782 +
                    return Err(Error::UnexpectedValue(formals));
783 +
                };
784 +
                if body.is_empty() {
785 +
                    return Err(Error::ExpectedValue("expression"));
786 +
                }
787 +
                eval_lambda(formals, body, env)
788 +
            }
789 +
            "if" => {
790 +
                let cond = items.next().ok_or(Error::ExpectedValue("bool"))?;
791 +
                let left = items.next().ok_or(Error::ExpectedValue("expression"))?;
792 +
                let right = items.next().ok_or(Error::ExpectedValue("expression"))?;
793 +
794 +
                match eval(cond, env)?.try_into() {
795 +
                    Ok(true) => eval(left, env),
796 +
                    Ok(false) => eval(right, env),
797 +
                    Err(e) => Err(Error::UnexpectedValue(e)),
798 +
                }
799 +
            }
800 +
            _ => apply(head, items, env),
801 +
        }
802 +
    } else {
803 +
        apply(head, items, env)
804 +
    }
805 +
}
806 +
807 +
/// The top-level recursive evaluation function.
808 +
fn eval(expr: Expr, env: &mut Env<'_>) -> Result<Expr> {
809 +
    match expr {
810 +
        Expr::Char(c) => Ok(Expr::Char(c)),
811 +
        Expr::Float(n) => Ok(Expr::Float(n)),
812 +
        Expr::Integer(n) => Ok(Expr::Integer(n)),
813 +
        Expr::Function(f) => Ok(Expr::Function(f)),
814 +
        Expr::Color(c) => Ok(Expr::Color(c)),
815 +
        Expr::Str(s) => Ok(Expr::Str(s)),
816 +
        Expr::Bool(b) => Ok(Expr::Bool(b)),
817 +
        Expr::List(l) => eval_list(l, env),
818 +
        Expr::Quoted(e) => Ok(*e),
819 +
        Expr::Symbol(s) => {
820 +
            if let Some(val) = env.lookup(&s) {
821 +
                Ok(val.clone())
822 +
            } else {
823 +
                Err(Error::UndefinedSymbol(s))
824 +
            }
825 +
        }
826 +
        Expr::Atom(s) => Ok(match s.deref() {
827 +
            "true" => Expr::Bool(true),
828 +
            "false" => Expr::Bool(false),
829 +
            _ => Expr::Atom(s),
830 +
        }),
831 +
        Expr::Vector(v) => v
832 +
            .into_iter()
833 +
            .map(|e| eval(e, env))
834 +
            .collect::<Result<Vec<_>>>()
835 +
            .map(Expr::Vector),
836 +
        Expr::Dict(d) => d
837 +
            .into_iter()
838 +
            .map(|(k, v)| eval(v, env).map(|v| (k, v)))
839 +
            .collect::<Result<HashMap<_, _>>>()
840 +
            .map(Expr::Dict),
841 +
        Expr::Ref(r) => Ok(Expr::Ref(r)),
842 +
        Expr::Dynamic(d) => Ok(Expr::Dynamic(d)),
843 +
    }
844 +
}
845 +
846 +
/// Function application.
847 +
fn apply(f: Expr, args: impl Iterator<Item = Expr>, env: &mut Env<'_>) -> Result<Expr> {
848 +
    match eval(f, env)? {
849 +
        Expr::Function(f) => f.apply(args, env),
850 +
        _ => Err(Error::ExpectedValue("function")),
851 +
    }
852 +
}
853 +
854 +
/// Return pairs from a list of expressions.
855 +
fn pairs(exprs: Vec<Expr>) -> Result<Vec<(Expr, Expr)>> {
856 +
    if exprs.len() % 2 != 0 {
857 +
        return Err(Error::WrongArgumentCount {
858 +
            actual: exprs.len(),
859 +
            expected: exprs.len() + 1,
860 +
        });
861 +
    }
862 +
    let mut iter = exprs.into_iter();
863 +
    let mut pairs = Vec::new();
864 +
865 +
    while let Some(l) = iter.next() {
866 +
        if let Some(r) = iter.next() {
867 +
            pairs.push((l, r));
868 +
        }
869 +
    }
870 +
    Ok(pairs)
871 +
}
872 +
873 +
/// Intrinsic functions.
874 +
mod intrinsic {
875 +
    use super::*;
876 +
877 +
    /// Raise an error.
878 +
    pub fn error(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
879 +
        let arity = args.len();
880 +
        let err = args.into_iter().next().ok_or(Error::WrongArgumentCount {
881 +
            expected: 1,
882 +
            actual: arity,
883 +
        })?;
884 +
        Err(Error::User(err))
885 +
    }
886 +
887 +
    /// Get the first item of a list.
888 +
    pub fn first(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
889 +
        let arity = args.len();
890 +
        let Ok([expr]) = <[_; 1]>::try_from(args) else {
891 +
            return Err(Error::WrongArgumentCount {
892 +
                expected: 1,
893 +
                actual: arity,
894 +
            });
895 +
        };
896 +
        if let Expr::List(l) = expr {
897 +
            return Ok(l.head().cloned().unwrap_or(Expr::nil()));
898 +
        }
899 +
        if let Expr::Vector(v) = expr {
900 +
            return Ok(v.into_iter().next().unwrap_or(Expr::nil()));
901 +
        }
902 +
        Err(Error::ExpectedValue("list"))
903 +
    }
904 +
905 +
    /// Get the last item of a vector.
906 +
    pub fn last(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
907 +
        if args.len() != 1 {
908 +
            return Err(Error::WrongArgumentCount {
909 +
                expected: 1,
910 +
                actual: args.len(),
911 +
            });
912 +
        }
913 +
        if let Some(Expr::Vector(l)) = args.into_iter().next() {
914 +
            return Ok(l.into_iter().next_back().unwrap_or(Expr::nil()));
915 +
        }
916 +
        Err(Error::ExpectedValue("vector"))
917 +
    }
918 +
919 +
    /// Get the nth item of a vector.
920 +
    pub fn nth(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
921 +
        if args.len() != 2 {
922 +
            return Err(Error::WrongArgumentCount {
923 +
                expected: 2,
924 +
                actual: args.len(),
925 +
            });
926 +
        }
927 +
        let mut args = args.into_iter();
928 +
        let Some(Expr::Vector(l)) = args.next() else {
929 +
            return Err(Error::ExpectedValue("vector"));
930 +
        };
931 +
        let Some(Expr::Integer(idx)) = args.next() else {
932 +
            return Err(Error::ExpectedValue("integer"));
933 +
        };
934 +
        Ok(l.into_iter().nth(idx as usize).unwrap_or(Expr::nil()))
935 +
    }
936 +
937 +
    /// Map function.
938 +
    pub fn map(args: Vec<Expr>, env: &Env<'_>) -> Result<Expr> {
939 +
        if args.len() != 2 {
940 +
            return Err(Error::WrongArgumentCount {
941 +
                expected: 2,
942 +
                actual: args.len(),
943 +
            });
944 +
        }
945 +
        let mut args = args.into_iter();
946 +
        let Some(Expr::Function(f)) = args.next() else {
947 +
            return Err(Error::ExpectedValue("function"));
948 +
        };
949 +
        let mut env = Env::from_parent(env);
950 +
951 +
        match args.next() {
952 +
            Some(Expr::List(l)) => l
953 +
                .iter()
954 +
                .cloned()
955 +
                .map(|i| f.apply([i].into_iter(), &mut env))
956 +
                .collect::<Result<Vec<_>>>()
957 +
                .map(List::from)
958 +
                .map(Expr::List),
959 +
            Some(Expr::Vector(l)) => l
960 +
                .into_iter()
961 +
                .map(|i| f.apply([i].into_iter(), &mut env))
962 +
                .collect::<Result<Vec<_>>>()
963 +
                .map(Expr::Vector),
964 +
            _ => Err(Error::ExpectedValue("list or vector")),
965 +
        }
966 +
    }
967 +
968 +
    /// Return the length of a value.
969 +
    pub fn length(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
970 +
        let arity = args.len();
971 +
        let Ok([value]) = <[_; 1]>::try_from(args) else {
972 +
            return Err(Error::WrongArgumentCount {
973 +
                expected: 1,
974 +
                actual: arity,
975 +
            });
976 +
        };
977 +
978 +
        let length = match value {
979 +
            Expr::Vector(l) => l.len(),
980 +
            Expr::List(l) => l.len(),
981 +
            Expr::Dict(d) => d.len(),
982 +
            Expr::Str(s) => s.chars().count(),
983 +
            _ => return Err(Error::UnexpectedValue(value)),
984 +
        };
985 +
        Ok(Expr::Integer(length.try_into().expect(
986 +
            "intrinsic::length: integer overflow on length calculation",
987 +
        )))
988 +
    }
989 +
990 +
    /// Check if the collection is empty.
991 +
    pub fn empty(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
992 +
        let arity = args.len();
993 +
        let Ok([expr]) = <[_; 1]>::try_from(args) else {
994 +
            return Err(Error::WrongArgumentCount {
995 +
                expected: 1,
996 +
                actual: arity,
997 +
            });
998 +
        };
999 +
1000 +
        let is_empty = match expr {
1001 +
            Expr::Vector(l) => l.is_empty(),
1002 +
            Expr::List(l) => l.is_empty(),
1003 +
            Expr::Str(s) => s.is_empty(),
1004 +
            Expr::Dict(d) => d.is_empty(),
1005 +
            _ => return Err(Error::UnexpectedValue(expr)),
1006 +
        };
1007 +
        Ok(Expr::Bool(is_empty))
1008 +
    }
1009 +
1010 +
    /// Create a list.
1011 +
    pub fn list(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1012 +
        Ok(Expr::List(args.into()))
1013 +
    }
1014 +
1015 +
    /// Create a dictionary.
1016 +
    pub fn dict(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1017 +
        if args.is_empty() {
1018 +
            return Ok(Expr::Dict(HashMap::new()));
1019 +
        }
1020 +
        let arity = args.len();
1021 +
        let Ok([expr]) = <[_; 1]>::try_from(args) else {
1022 +
            return Err(Error::WrongArgumentCount {
1023 +
                expected: 1,
1024 +
                actual: arity,
1025 +
            });
1026 +
        };
1027 +
        if let Expr::Vector(v) = expr {
1028 +
            let mut iter = v.into_iter();
1029 +
            let mut dict = HashMap::new();
1030 +
1031 +
            loop {
1032 +
                let Some(k) = iter.next() else {
1033 +
                    break;
1034 +
                };
1035 +
                let Some(v) = iter.next() else {
1036 +
                    return Err(Error::ExpectedValue("any"));
1037 +
                };
1038 +
                let k = match Key::try_from(k) {
1039 +
                    Ok(key) => key,
1040 +
                    Err(e) => return Err(Error::UnexpectedValue(e)),
1041 +
                };
1042 +
                dict.insert(k, v);
1043 +
            }
1044 +
            Ok(Expr::Dict(dict))
1045 +
        } else {
1046 +
            Err(Error::ExpectedValue("vector"))
1047 +
        }
1048 +
    }
1049 +
1050 +
    /// Lookup a value in a dictionary.
1051 +
    pub fn lookup(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1052 +
        if args.len() != 2 {
1053 +
            return Err(Error::WrongArgumentCount {
1054 +
                expected: 2,
1055 +
                actual: args.len(),
1056 +
            });
1057 +
        }
1058 +
        let mut args = args.into_iter();
1059 +
        let Some(e) = args.next() else {
1060 +
            return Err(Error::ExpectedValue("key"));
1061 +
        };
1062 +
        let Some(Expr::Dict(d)) = args.next() else {
1063 +
            return Err(Error::ExpectedValue("dictionary"));
1064 +
        };
1065 +
        let k = match Key::try_from(e) {
1066 +
            Ok(key) => key,
1067 +
            Err(e) => return Err(Error::UnexpectedValue(e)),
1068 +
        };
1069 +
        if let Some(v) = d.get(&k) {
1070 +
            Ok(v.clone())
1071 +
        } else {
1072 +
            Ok(Expr::nil())
1073 +
        }
1074 +
    }
1075 +
1076 +
    /// Check if a collection contains a key.
1077 +
    pub fn contains(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1078 +
        if args.len() != 2 {
1079 +
            return Err(Error::WrongArgumentCount {
1080 +
                expected: 2,
1081 +
                actual: args.len(),
1082 +
            });
1083 +
        }
1084 +
        let mut args = args.into_iter();
1085 +
        let Some(key) = args.next() else {
1086 +
            return Err(Error::ExpectedValue("key or value"));
1087 +
        };
1088 +
        let is_contained = match args.next() {
1089 +
            Some(Expr::Vector(l)) => l.contains(&key),
1090 +
            Some(Expr::List(l)) => l.contains(&key),
1091 +
            Some(Expr::Str(s)) => match key {
1092 +
                Expr::Str(k) => s.contains(&k),
1093 +
                Expr::Char(c) => s.contains(c),
1094 +
                _ => return Err(Error::ExpectedValue("string or character")),
1095 +
            },
1096 +
            Some(Expr::Dict(d)) => {
1097 +
                let k = match Key::try_from(key) {
1098 +
                    Ok(key) => key,
1099 +
                    Err(e) => return Err(Error::UnexpectedValue(e)),
1100 +
                };
1101 +
                d.contains_key(&k)
1102 +
            }
1103 +
            _ => return Err(Error::ExpectedValue("collection")),
1104 +
        };
1105 +
        Ok(Expr::Bool(is_contained))
1106 +
    }
1107 +
1108 +
    /// Push elements to the end of a vector.
1109 +
    pub fn append(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1110 +
        if args.is_empty() {
1111 +
            return Ok(Expr::nil());
1112 +
        }
1113 +
        let mut args = args.into_iter();
1114 +
1115 +
        match args.next() {
1116 +
            Some(Expr::Vector(mut v)) => {
1117 +
                v.extend(args);
1118 +
                Ok(Expr::Vector(v))
1119 +
            }
1120 +
            _ => Err(Error::ExpectedValue("vector")),
1121 +
        }
1122 +
    }
1123 +
1124 +
    /// Push elements to the front of a list.
1125 +
    pub fn cons(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1126 +
        if args.is_empty() {
1127 +
            return Ok(Expr::nil());
1128 +
        }
1129 +
        if args.len() != 2 {
1130 +
            return Err(Error::WrongArgumentCount {
1131 +
                expected: 2,
1132 +
                actual: args.len(),
1133 +
            });
1134 +
        }
1135 +
        let mut args = args.into_iter();
1136 +
        let Some(val) = args.next() else {
1137 +
            return Err(Error::ExpectedValue("expr"));
1138 +
        };
1139 +
        let Some(Expr::List(l)) = args.next() else {
1140 +
            return Err(Error::ExpectedValue("list"));
1141 +
        };
1142 +
        Ok(Expr::List(l.prepend(val)))
1143 +
    }
1144 +
1145 +
    /// Reverse a vector.
1146 +
    pub fn reverse(mut args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1147 +
        match args.pop() {
1148 +
            Some(Expr::Vector(mut v)) => {
1149 +
                v.reverse();
1150 +
                Ok(Expr::Vector(v))
1151 +
            }
1152 +
            Some(_) => Err(Error::ExpectedValue("vector")),
1153 +
            None => Err(Error::WrongArgumentCount {
1154 +
                expected: 1,
1155 +
                actual: args.len(),
1156 +
            }),
1157 +
        }
1158 +
    }
1159 +
1160 +
    /// Create a list of numbers in a specified range.
1161 +
    pub fn range(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1162 +
        match args.as_slice() {
1163 +
            [Expr::Integer(end)] => Ok(Expr::Vector((0..*end).map(Expr::Integer).collect())),
1164 +
            [Expr::Integer(start), Expr::Integer(end)] => {
1165 +
                Ok(Expr::Vector((*start..*end).map(Expr::Integer).collect()))
1166 +
            }
1167 +
            [Expr::Integer(start), Expr::Integer(end), Expr::Integer(step)] => Ok(Expr::Vector(
1168 +
                (0..)
1169 +
                    .map(|n| *start + n * *step)
1170 +
                    .take_while(|&x| x < *end)
1171 +
                    .map(Expr::Integer)
1172 +
                    .collect(),
1173 +
            )),
1174 +
            _ => Err(Error::WrongArgumentCount {
1175 +
                expected: 3,
1176 +
                actual: args.len(),
1177 +
            }),
1178 +
        }
1179 +
    }
1180 +
1181 +
    /// Greater than.
1182 +
    pub fn gt(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1183 +
        let result = binop(args, |a, b| a > b, |a, b| a > b)?;
1184 +
        Ok(Expr::Bool(result))
1185 +
    }
1186 +
1187 +
    /// Greater than or equal.
1188 +
    pub fn gte(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1189 +
        let result = binop(args, |a, b| a >= b, |a, b| a >= b)?;
1190 +
        Ok(Expr::Bool(result))
1191 +
    }
1192 +
1193 +
    /// Lesser than.
1194 +
    pub fn lt(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1195 +
        let result = binop(args, |a, b| a < b, |a, b| a < b)?;
1196 +
        Ok(Expr::Bool(result))
1197 +
    }
1198 +
1199 +
    /// Lesser than or equal.
1200 +
    pub fn lte(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1201 +
        let result = binop(args, |a, b| a <= b, |a, b| a <= b)?;
1202 +
        Ok(Expr::Bool(result))
1203 +
    }
1204 +
1205 +
    /// Not (!).
1206 +
    pub fn not(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1207 +
        if args.len() != 1 {
1208 +
            return Err(Error::WrongArgumentCount {
1209 +
                expected: 1,
1210 +
                actual: args.len(),
1211 +
            });
1212 +
        }
1213 +
        let Some(Expr::Bool(b)) = args.into_iter().next() else {
1214 +
            return Err(Error::ExpectedValue("bool"));
1215 +
        };
1216 +
        Ok(Expr::Bool(!b))
1217 +
    }
1218 +
1219 +
    /// And (&&).
1220 +
    pub fn and(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1221 +
        fold(args, true, |a, b| a && b)
1222 +
    }
1223 +
1224 +
    /// Or (||).
1225 +
    pub fn or(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1226 +
        fold(args, false, |a, b| a || b)
1227 +
    }
1228 +
1229 +
    /// Equals (==).
1230 +
    pub fn eq(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1231 +
        let mut args = args.into_iter();
1232 +
        let Some(head) = args.next() else {
1233 +
            return Err(Error::ExpectedValue("expression"));
1234 +
        };
1235 +
        Ok(Expr::Bool(args.all(|a| a == head)))
1236 +
    }
1237 +
1238 +
    /// Addition (+).
1239 +
    pub fn add(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1240 +
        fold(args, 0, |acc, n| acc + n)
1241 +
    }
1242 +
1243 +
    /// Multiplication (*).
1244 +
    pub fn mul(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1245 +
        fold(args, 1, |acc, n| acc * n)
1246 +
    }
1247 +
1248 +
    /// Division (/).
1249 +
    pub fn div(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1250 +
        let mut args = args.into_iter().peekable();
1251 +
        match args.next() {
1252 +
            Some(Expr::Float(n)) => {
1253 +
                if args.peek().is_none() {
1254 +
                    return Ok(Expr::Float(n.recip()));
1255 +
                }
1256 +
                fold(args, n, |acc, n| acc / n)
1257 +
            }
1258 +
            Some(Expr::Integer(n)) => {
1259 +
                if args.peek().is_none() {
1260 +
                    return Err(Error::ExpectedValue("float"));
1261 +
                }
1262 +
                fold(args, n, |acc, n| acc / n)
1263 +
            }
1264 +
            Some(v) => Err(Error::UnexpectedValue(v)),
1265 +
            None => Err(Error::WrongArgumentCount {
1266 +
                expected: 1,
1267 +
                actual: args.len(),
1268 +
            }),
1269 +
        }
1270 +
    }
1271 +
1272 +
    /// Subtraction (-).
1273 +
    pub fn sub(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1274 +
        let mut args = args.into_iter().peekable();
1275 +
        match args.next() {
1276 +
            Some(Expr::Float(n)) => {
1277 +
                if args.peek().is_none() {
1278 +
                    return Ok(Expr::Float(-n));
1279 +
                }
1280 +
                fold(args, n, |acc, n| acc - n)
1281 +
            }
1282 +
            Some(Expr::Integer(n)) => {
1283 +
                if args.peek().is_none() {
1284 +
                    return Ok(Expr::Integer(-n));
1285 +
                }
1286 +
                fold(args, n, |acc, n| acc - n)
1287 +
            }
1288 +
            Some(v) => Err(Error::UnexpectedValue(v)),
1289 +
            None => Err(Error::WrongArgumentCount {
1290 +
                expected: 1,
1291 +
                actual: args.len(),
1292 +
            }),
1293 +
        }
1294 +
    }
1295 +
1296 +
    /// Modulo (%).
1297 +
    pub fn modulo(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1298 +
        binop(args, |a, b| Expr::Integer(a % b), |a, b| Expr::Float(a % b))
1299 +
    }
1300 +
1301 +
    /// Power (^).
1302 +
    pub fn pow(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1303 +
        binop(
1304 +
            args,
1305 +
            |a, b| Expr::Integer(a.pow(b as u32)),
1306 +
            |a, b| Expr::Float(a.powf(b)),
1307 +
        )
1308 +
    }
1309 +
1310 +
    /// Minimum.
1311 +
    pub fn min(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1312 +
        let Some(e) = args.first() else {
1313 +
            return Err(Error::WrongArgumentCount {
1314 +
                expected: 1,
1315 +
                actual: args.len(),
1316 +
            });
1317 +
        };
1318 +
        match e {
1319 +
            Expr::Float(_) => fold(args, f64::MAX, f64::min),
1320 +
            Expr::Integer(_) => fold(args, i64::MAX, i64::min),
1321 +
            _ => Err(Error::ExpectedValue("number")),
1322 +
        }
1323 +
    }
1324 +
1325 +
    /// Maximum.
1326 +
    pub fn max(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1327 +
        let Some(e) = args.first() else {
1328 +
            return Err(Error::WrongArgumentCount {
1329 +
                expected: 1,
1330 +
                actual: args.len(),
1331 +
            });
1332 +
        };
1333 +
        match e {
1334 +
            Expr::Float(_) => fold(args, f64::MIN, f64::max),
1335 +
            Expr::Integer(_) => fold(args, i64::MIN, i64::max),
1336 +
            _ => Err(Error::ExpectedValue("number")),
1337 +
        }
1338 +
    }
1339 +
1340 +
    /// Create a mutable reference.
1341 +
    pub fn create_ref(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1342 +
        let arity = args.len();
1343 +
        let Ok([value]) = <[_; 1]>::try_from(args) else {
1344 +
            return Err(Error::WrongArgumentCount {
1345 +
                expected: 1,
1346 +
                actual: arity,
1347 +
            });
1348 +
        };
1349 +
        Ok(Expr::Ref(Rc::new(RefCell::new(value))))
1350 +
    }
1351 +
1352 +
    /// Dereference a mutable reference.
1353 +
    pub fn deref(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1354 +
        let arity = args.len();
1355 +
        let Ok([value]) = <[_; 1]>::try_from(args) else {
1356 +
            return Err(Error::WrongArgumentCount {
1357 +
                expected: 1,
1358 +
                actual: arity,
1359 +
            });
1360 +
        };
1361 +
        match value {
1362 +
            Expr::Ref(r) => Ok(r.borrow().clone()),
1363 +
            _ => Err(Error::ExpectedValue("ref")),
1364 +
        }
1365 +
    }
1366 +
1367 +
    /// Set the value of a mutable reference.
1368 +
    pub fn set_ref(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1369 +
        let arity = args.len();
1370 +
        let Ok([r, v]) = <[_; 2]>::try_from(args) else {
1371 +
            return Err(Error::WrongArgumentCount {
1372 +
                expected: 2,
1373 +
                actual: arity,
1374 +
            });
1375 +
        };
1376 +
        match r {
1377 +
            Expr::Ref(r) => {
1378 +
                *r.borrow_mut() = v;
1379 +
                Ok(Expr::nil())
1380 +
            }
1381 +
            _ => Err(Error::ExpectedValue("ref")),
1382 +
        }
1383 +
    }
1384 +
1385 +
    /// Modify a mutable reference in-place using a lambda.
1386 +
    pub fn modify(args: Vec<Expr>, env: &Env<'_>) -> Result<Expr> {
1387 +
        let arity = args.len();
1388 +
        let Ok([r, f]) = <[_; 2]>::try_from(args) else {
1389 +
            return Err(Error::WrongArgumentCount {
1390 +
                expected: 2,
1391 +
                actual: arity,
1392 +
            });
1393 +
        };
1394 +
        let mut env = Env::from_parent(env);
1395 +
1396 +
        match (r, f) {
1397 +
            (Expr::Ref(r), Expr::Function(f)) => {
1398 +
                let mut old = r.borrow_mut();
1399 +
                let new = f.apply([old.clone()].into_iter(), &mut env)?;
1400 +
1401 +
                *old = new;
1402 +
1403 +
                Ok(Expr::nil())
1404 +
            }
1405 +
            (_, _) => Err(Error::ExpectedValue("ref and function")),
1406 +
        }
1407 +
    }
1408 +
1409 +
    fn fold<T: TryFrom<Expr, Error = Expr> + Into<Expr>>(
1410 +
        args: impl IntoIterator<Item = Expr>,
1411 +
        init: T,
1412 +
        op: impl Fn(T, T) -> T,
1413 +
    ) -> Result<Expr> {
1414 +
        args.into_iter()
1415 +
            .map(|v| v.try_into().map_err(Error::UnexpectedValue))
1416 +
            .try_fold(init, |acc, item| item.map(|i| op(acc, i)))
1417 +
            .map(Into::into)
1418 +
    }
1419 +
1420 +
    fn binop<T>(
1421 +
        args: Vec<Expr>,
1422 +
        op: impl Fn(i64, i64) -> T,
1423 +
        opf: impl Fn(f64, f64) -> T,
1424 +
    ) -> Result<T> {
1425 +
        if args.is_empty() {
1426 +
            return Err(Error::WrongArgumentCount {
1427 +
                expected: 2,
1428 +
                actual: 0,
1429 +
            });
1430 +
        }
1431 +
        let mut args = args.into_iter();
1432 +
        match args.next() {
1433 +
            Some(Expr::Integer(a)) => {
1434 +
                let Some(Expr::Integer(b)) = args.next() else {
1435 +
                    return Err(Error::ExpectedValue("integer"));
1436 +
                };
1437 +
                Ok(op(a, b))
1438 +
            }
1439 +
            Some(Expr::Float(a)) => {
1440 +
                let Some(Expr::Float(b)) = args.next() else {
1441 +
                    return Err(Error::ExpectedValue("float"));
1442 +
                };
1443 +
                Ok(opf(a, b))
1444 +
            }
1445 +
            _ => Err(Error::ExpectedValue("number")),
1446 +
        }
1447 +
    }
1448 +
}
1449 +
1450 +
#[cfg(test)]
1451 +
#[allow(clippy::unwrap_used)]
1452 +
mod tests {
1453 +
    use crate::gfx::Rgba8;
1454 +
1455 +
    use super::*;
1456 +
    use crate::lisp::parser::Parser;
1457 +
    use crate::lisp::scanner::Scanner;
1458 +
1459 +
    #[track_caller]
1460 +
    fn expect(input: &[&str], expected: Expr) {
1461 +
        let input = input.join("\n");
1462 +
        let tokens = Scanner::new(input.as_str());
1463 +
        let parser = Parser::new(tokens);
1464 +
        let eval = Evaluator::new(parser);
1465 +
        let result = eval.eval(&mut Env::default()).unwrap();
1466 +
1467 +
        assert_eq!(result, expected);
1468 +
    }
1469 +
1470 +
    #[track_caller]
1471 +
    fn expect_err(input: &[&str], err: Error) {
1472 +
        let input = input.join("\n");
1473 +
        let tokens = Scanner::new(input.as_str());
1474 +
        let parser = Parser::new(tokens);
1475 +
        let eval = Evaluator::new(parser);
1476 +
1477 +
        assert_eq!(
1478 +
            eval.eval(&mut Env::default()).unwrap_err().to_string(),
1479 +
            err.to_string()
1480 +
        );
1481 +
    }
1482 +
1483 +
    #[test]
1484 +
    fn test_def() {
1485 +
        expect(&["(def fnord 42)", "fnord"], Expr::Integer(42));
1486 +
        expect(
1487 +
            &["(def fnord 'answer)", "fnord"],
1488 +
            Expr::Symbol("answer".into()),
1489 +
        );
1490 +
        expect(
1491 +
            &["(def fnord {* 2 21})", "fnord"],
1492 +
            Expr::list([Expr::symbol("*"), Expr::Integer(2), Expr::Integer(21)]),
1493 +
        );
1494 +
        expect(&["(def fnord (* 2 21))", "fnord"], Expr::Integer(42));
1495 +
        expect(&["(def fnord {* 2 21})", "(eval fnord)"], Expr::Integer(42));
1496 +
        expect(
1497 +
            &["(def f (fn [x] (* x x)))", "((first [f ()]) 3)"],
1498 +
            Expr::Integer(9),
1499 +
        );
1500 +
    }
1501 +
1502 +
    #[test]
1503 +
    fn test_higher_order() {
1504 +
        expect(
1505 +
            &[
1506 +
                "(def apply-func (fn [f a b] (f a b)))",
1507 +
                "(apply-func (fn [x y] (* x y)) 6 7)",
1508 +
            ],
1509 +
            Expr::Integer(42),
1510 +
        );
1511 +
    }
1512 +
1513 +
    #[test]
1514 +
    fn test_closure() {
1515 +
        expect(
1516 +
            &[
1517 +
                "(def fnord 42)",
1518 +
                "(def f (fn [] fnord))",
1519 +
                "(def fnord 0)",
1520 +
                "(def g (fn [] fnord))",
1521 +
                "(list (f) (g))",
1522 +
            ],
1523 +
            Expr::list([Expr::Integer(42), Expr::Integer(0)]),
1524 +
        );
1525 +
    }
1526 +
1527 +
    #[test]
1528 +
    fn test_scoping() {
1529 +
        expect(
1530 +
            &["(def x 0)", "(def f (fn [] (def x 42) x))", "(f)"],
1531 +
            Expr::Integer(42),
1532 +
        );
1533 +
    }
1534 +
1535 +
    #[test]
1536 +
    fn test_recursive_fn() {
1537 +
        expect(
1538 +
            &[
1539 +
                "(def fib (fn [n] (if (< n 2) 1 (+ (fib (- n 1)) (fib (- n 2))))))",
1540 +
                "(fib 13)",
1541 +
            ],
1542 +
            Expr::Integer(377),
1543 +
        );
1544 +
        expect(
1545 +
            &[
1546 +
                "(def fact (fn [n] (if (<= n 1) 1 (* n (fact (- n 1))))))",
1547 +
                "(fact 10)",
1548 +
            ],
1549 +
            Expr::Integer(3628800),
1550 +
        );
1551 +
    }
1552 +
1553 +
    #[test]
1554 +
    fn test_add() {
1555 +
        expect(&["(+)"], Expr::Integer(0));
1556 +
        expect(&["(+ 1)"], Expr::Integer(1));
1557 +
        expect(&["(+ 1 2)"], Expr::Integer(3));
1558 +
        expect(&["(+ 1 (+ 3 (+ 7 2)))"], Expr::Integer(13));
1559 +
        expect(&["(+ 1 3 7 2)"], Expr::Integer(13));
1560 +
        expect(&["(+ (+ 1 3) (+ 7 2))"], Expr::Integer(13));
1561 +
    }
1562 +
1563 +
    #[test]
1564 +
    fn test_mul() {
1565 +
        expect(&["(*)"], Expr::Integer(1));
1566 +
        expect(&["(* 3)"], Expr::Integer(3));
1567 +
        expect(&["(* 3 2)"], Expr::Integer(6));
1568 +
        expect(&["(* 3 2 2)"], Expr::Integer(12));
1569 +
    }
1570 +
1571 +
    #[test]
1572 +
    fn test_div() {
1573 +
        expect(&["(/ 2.0)"], Expr::Float(1. / 2.));
1574 +
        expect(&["(/ 7.0 2.0)"], Expr::Float(3.5));
1575 +
        expect(&["(/ 7 2)"], Expr::Integer(3));
1576 +
        expect(&["(/ 8 2 2)"], Expr::Integer(2));
1577 +
    }
1578 +
1579 +
    #[test]
1580 +
    fn test_sub() {
1581 +
        expect(&["(- 4)"], Expr::Integer(-4));
1582 +
        expect(&["(- 4 3)"], Expr::Integer(1));
1583 +
        expect(&["(- 5 3 2)"], Expr::Integer(0));
1584 +
    }
1585 +
1586 +
    #[test]
1587 +
    fn test_min() {
1588 +
        expect(&["(min 4 1 3)"], Expr::Integer(1));
1589 +
        expect(&["(min 3)"], Expr::Integer(3));
1590 +
    }
1591 +
1592 +
    #[test]
1593 +
    fn test_max() {
1594 +
        expect(&["(max 3 1 4)"], Expr::Integer(4));
1595 +
        expect(&["(max 3)"], Expr::Integer(3));
1596 +
    }
1597 +
1598 +
    #[test]
1599 +
    fn test_mod() {
1600 +
        expect(&["(mod 4 3)"], Expr::Integer(1));
1601 +
        expect(&["(mod 4 2)"], Expr::Integer(0));
1602 +
        expect(&["(mod 7 5)"], Expr::Integer(2));
1603 +
        expect(&["(mod 5 7)"], Expr::Integer(5));
1604 +
    }
1605 +
1606 +
    #[test]
1607 +
    fn test_pow() {
1608 +
        expect(&["(pow 3 3)"], Expr::Integer(27));
1609 +
        expect(&["(pow 4 0)"], Expr::Integer(1));
1610 +
    }
1611 +
1612 +
    #[test]
1613 +
    fn test_bool() {
1614 +
        expect(&[":true"], Expr::Bool(true));
1615 +
        expect(&[":false"], Expr::Bool(false));
1616 +
    }
1617 +
1618 +
    #[test]
1619 +
    fn test_not() {
1620 +
        expect(&["(not :true)"], Expr::Bool(false));
1621 +
        expect(&["(not (not :false))"], Expr::Bool(false));
1622 +
    }
1623 +
1624 +
    #[test]
1625 +
    fn test_and() {
1626 +
        expect(&["(and :true :true :true)"], Expr::Bool(true));
1627 +
        expect(&["(and :true :false :true)"], Expr::Bool(false));
1628 +
    }
1629 +
1630 +
    #[test]
1631 +
    fn test_or() {
1632 +
        expect(&["(or :false :true :false)"], Expr::Bool(true));
1633 +
        expect(&["(or :false :false :false)"], Expr::Bool(false));
1634 +
    }
1635 +
1636 +
    #[test]
1637 +
    fn test_eval() {
1638 +
        expect(&["(eval 5)"], Expr::Integer(5));
1639 +
        expect(&["(eval (+ 3 2))"], Expr::Integer(5));
1640 +
        expect(&["(eval '(+ 3 2))"], Expr::Integer(5));
1641 +
        expect(&["(eval {+ 3 2})"], Expr::Integer(5));
1642 +
        expect(&["(eval ''symbol)"], Expr::Symbol("symbol".into()));
1643 +
        expect(
1644 +
            &["(eval ''(+ 3 2))"],
1645 +
            Expr::list([Expr::Symbol("+".into()), Expr::Integer(3), Expr::Integer(2)]),
1646 +
        );
1647 +
        expect(&["(eval (eval ''(+ 3 2)))"], Expr::Integer(5));
1648 +
        expect(
1649 +
            &["(eq? (eval '(+ 1 2)) (eval ''(+ 1 2)))"],
1650 +
            Expr::Bool(false),
1651 +
        );
1652 +
        expect(&["(eval '(eq? :true :false))"], Expr::Bool(false));
1653 +
        expect(&["(eval ':true)"], Expr::Bool(true));
1654 +
    }
1655 +
1656 +
    #[test]
1657 +
    fn test_color() {
1658 +
        expect(
1659 +
            &["#443311"],
1660 +
            Expr::Color(Rgba8::new(0x44, 0x33, 0x11, 0xff)),
1661 +
        );
1662 +
        expect(
1663 +
            &["{#111111 #ff00ff}"],
1664 +
            Expr::list([
1665 +
                Expr::Color(Rgba8::new(0x11, 0x11, 0x11, 0xff)),
1666 +
                Expr::Color(Rgba8::new(0xff, 0x00, 0xff, 0xff)),
1667 +
            ]),
1668 +
        );
1669 +
    }
1670 +
1671 +
    #[test]
1672 +
    fn test_eq() {
1673 +
        expect(&["(eq? 1 2)"], Expr::Bool(false));
1674 +
        expect(&["(eq? 1 1)"], Expr::Bool(true));
1675 +
        expect(&["(eq? 1 1 1)"], Expr::Bool(true));
1676 +
        expect(&["(eq? 1 1 2)"], Expr::Bool(false));
1677 +
        expect(&["(eq? :true :true)"], Expr::Bool(true));
1678 +
        expect(&["(eq? :true :false)"], Expr::Bool(false));
1679 +
        expect(&["(eq? {4 2} {4 2})"], Expr::Bool(true));
1680 +
        expect(&["(eq? {4 2} {4 3})"], Expr::Bool(false));
1681 +
    }
1682 +
1683 +
    #[test]
1684 +
    fn test_if() {
1685 +
        expect(&["(if (> 4 3) `l` `r`)"], Expr::Char('l'));
1686 +
        expect(&["(if (< 4 3) `l` `r`)"], Expr::Char('r'));
1687 +
        expect(&["(if :true (+ 2 3) 0)"], Expr::Integer(5));
1688 +
        expect(&["(if :false (+ 2 3) 0)"], Expr::Integer(0));
1689 +
        expect(&["(if :false 0 (if :true 1 2))"], Expr::Integer(1));
1690 +
        expect(&["(if :true 'symbol {})"], Expr::Symbol("symbol".into()));
1691 +
        expect(
1692 +
            &["(def symbol 42)", "(if :true symbol {})"],
1693 +
            Expr::Integer(42),
1694 +
        );
1695 +
    }
1696 +
1697 +
    #[test]
1698 +
    fn test_fn() {
1699 +
        expect(
1700 +
            &["(def incr (fn [a] (+ a 1)))", "(incr (incr 3))"],
1701 +
            Expr::Integer(5),
1702 +
        );
1703 +
        expect(
1704 +
            &["(def decr (fn [a] (- a 1)))", "(def d decr)", "(d 3)"],
1705 +
            Expr::Integer(2),
1706 +
        );
1707 +
        expect(&["(def answer (fn [] 42))", "(answer)"], Expr::Integer(42));
1708 +
    }
1709 +
1710 +
    #[test]
1711 +
    fn test_fn_optional_args() {
1712 +
        expect(
1713 +
            &[
1714 +
                "(def greet (fn [x y :name \"greyface\" :age 103] (list x y name age)))",
1715 +
                "(greet 1 2)",
1716 +
            ],
1717 +
            Expr::list([
1718 +
                Expr::Integer(1),
1719 +
                Expr::Integer(2),
1720 +
                Expr::Str("greyface".to_owned()),
1721 +
                Expr::Integer(103),
1722 +
            ]),
1723 +
        );
1724 +
        expect(
1725 +
            &[
1726 +
                "(def greet (fn [x y :name \"greyface\" :age 103] (list x y name age)))",
1727 +
                "(greet 1 2 :name \"alice\" :age 31)",
1728 +
            ],
1729 +
            Expr::list([
1730 +
                Expr::Integer(1),
1731 +
                Expr::Integer(2),
1732 +
                Expr::Str("alice".to_owned()),
1733 +
                Expr::Integer(31),
1734 +
            ]),
1735 +
        );
1736 +
        expect(
1737 +
            &[
1738 +
                "(def greet (fn [x y :name \"greyface\" :age 103] (list x y name age)))",
1739 +
                "(greet 1 2 :age 33)",
1740 +
            ],
1741 +
            Expr::list([
1742 +
                Expr::Integer(1),
1743 +
                Expr::Integer(2),
1744 +
                Expr::Str("greyface".to_owned()),
1745 +
                Expr::Integer(33),
1746 +
            ]),
1747 +
        );
1748 +
        expect(
1749 +
            &[
1750 +
                "(def greet (fn [:name \"greyface\" :eyes :brown] (list name eyes)))",
1751 +
                "(greet :eyes :blue)",
1752 +
            ],
1753 +
            Expr::list([Expr::Str("greyface".to_owned()), Expr::Atom("blue".into())]),
1754 +
        );
1755 +
        expect(
1756 +
            &[
1757 +
                "(def greet (fn [:name \"greyface\" :eyes :brown] (list name eyes)))",
1758 +
                "(greet)",
1759 +
            ],
1760 +
            Expr::list([Expr::Str("greyface".to_owned()), Expr::Atom("brown".into())]),
1761 +
        );
1762 +
    }
1763 +
1764 +
    #[test]
1765 +
    fn test_first() {
1766 +
        expect(&["(first (list 4 3 1))"], Expr::Integer(4));
1767 +
        expect(
1768 +
            &["(first (list (list 4 2) 3 1))"],
1769 +
            Expr::list([Expr::Integer(4), Expr::Integer(2)]),
1770 +
        );
1771 +
        expect(&["(first ())"], Expr::nil());
1772 +
    }
1773 +
1774 +
    #[test]
1775 +
    fn test_last() {
1776 +
        expect(&["(last [4 3 1])"], Expr::Integer(1));
1777 +
        expect(&["(last [])"], Expr::nil());
1778 +
    }
1779 +
1780 +
    #[test]
1781 +
    fn test_nth() {
1782 +
        expect(&["(nth [4 3 1] 1)"], Expr::Integer(3));
1783 +
        expect(&["(nth [4 3 1] 0)"], Expr::Integer(4));
1784 +
        expect_err(&["(nth [4 3 1] 1.2)"], Error::ExpectedValue("integer"));
1785 +
    }
1786 +
1787 +
    #[test]
1788 +
    fn test_do() {
1789 +
        expect(&["(do (def x 1) (def y 2) (+ x y))"], Expr::Integer(3));
1790 +
    }
1791 +
1792 +
    #[test]
1793 +
    fn test_let() {
1794 +
        expect(&["(let [x 1 y 2 z 3] (+ x y z))"], Expr::Integer(6));
1795 +
        expect(
1796 +
            &["(let [x 1 y 2] (let [z (+ x y)] (+ z 1)))"],
1797 +
            Expr::Integer(4),
1798 +
        );
1799 +
    }
1800 +
1801 +
    #[test]
1802 +
    fn test_dict() {
1803 +
        expect(
1804 +
            &["(dict [:x 1 :y 2 :z (+ 2 1)])"],
1805 +
            Expr::Dict(HashMap::from_iter([
1806 +
                (Key::Atom("x".into()), Expr::Integer(1)),
1807 +
                (Key::Atom("y".into()), Expr::Integer(2)),
1808 +
                (Key::Atom("z".into()), Expr::Integer(3)),
1809 +
            ])),
1810 +
        );
1811 +
        expect(
1812 +
            &["(let [d (dict [1 :x 2 :y 3 :z])] (lookup 2 d))"],
1813 +
            Expr::Atom("y".into()),
1814 +
        );
1815 +
        expect(
1816 +
            &["(dict [`x` 1 #ff0000 2 41 :a])"],
1817 +
            Expr::Dict(HashMap::from_iter([
1818 +
                (Key::Char('x'), Expr::Integer(1)),
1819 +
                (Key::Color(Rgba8::new(0xff, 0, 0, 0xff)), Expr::Integer(2)),
1820 +
                (Key::Integer(41), Expr::Atom("a".into())),
1821 +
            ])),
1822 +
        );
1823 +
        expect(&["(dict)"], Expr::Dict(HashMap::new()));
1824 +
        expect(&["(dict [])"], Expr::Dict(HashMap::new()));
1825 +
        expect_err(&["(dict [:x])"], Error::ExpectedValue("any"));
1826 +
        expect_err(&["(dict {:x 1})"], Error::ExpectedValue("vector"));
1827 +
    }
1828 +
1829 +
    #[test]
1830 +
    fn test_map() {
1831 +
        expect(
1832 +
            &["(map (fn [x] (+ x 1)) (list 1 2 3))"],
1833 +
            Expr::list([Expr::Integer(2), Expr::Integer(3), Expr::Integer(4)]),
1834 +
        );
1835 +
        expect(
1836 +
            &["(map (fn [x] (+ x x)) [1 2 3])"],
1837 +
            Expr::vector([Expr::Integer(2), Expr::Integer(4), Expr::Integer(6)]),
1838 +
        );
1839 +
        expect(
1840 +
            &["(map (fn [x] (+ x x)) (map - [1 2 3]))"],
1841 +
            Expr::vector([Expr::Integer(-2), Expr::Integer(-4), Expr::Integer(-6)]),
1842 +
        );
1843 +
    }
1844 +
1845 +
    #[test]
1846 +
    fn test_list() {
1847 +
        expect(
1848 +
            &["(list 1 2 3)"],
1849 +
            Expr::list([Expr::Integer(1), Expr::Integer(2), Expr::Integer(3)]),
1850 +
        );
1851 +
        expect(&["(list)"], Expr::nil());
1852 +
        expect(
1853 +
            &["(list {+ 1})"],
1854 +
            Expr::list([Expr::list([Expr::Symbol("+".into()), Expr::Integer(1)])]),
1855 +
        );
1856 +
        expect(&["{symbol}"], Expr::list([Expr::Symbol("symbol".into())]));
1857 +
        expect(
1858 +
            &["{(symbol)}"],
1859 +
            Expr::list([Expr::list([Expr::Symbol("symbol".into())])]),
1860 +
        );
1861 +
        expect(
1862 +
            &["{{symbol}}"],
1863 +
            Expr::list([Expr::Quoted(Box::new(Expr::list([Expr::Symbol(
1864 +
                "symbol".into(),
1865 +
            )])))]),
1866 +
        );
1867 +
        expect(
1868 +
            &["{+ 1 2}"],
1869 +
            Expr::list([Expr::Symbol("+".into()), Expr::Integer(1), Expr::Integer(2)]),
1870 +
        );
1871 +
        expect(&["(eq? {} ())"], Expr::Bool(true));
1872 +
        expect_err(&["(list (4 2))"], Error::ExpectedValue("function"));
1873 +
    }
1874 +
1875 +
    #[test]
1876 +
    fn test_cons() {
1877 +
        expect(&["(cons)"], Expr::list([]));
1878 +
        expect(&["(cons 1 ())"], Expr::list([Expr::Integer(1)]));
1879 +
        expect(
1880 +
            &["(cons 3 (cons 2 (cons 1 ())))"],
1881 +
            Expr::list([Expr::Integer(3), Expr::Integer(2), Expr::Integer(1)]),
1882 +
        );
1883 +
        expect(
1884 +
            &["(cons 3 '(2 1))"],
1885 +
            Expr::list([Expr::Integer(3), Expr::Integer(2), Expr::Integer(1)]),
1886 +
        );
1887 +
    }
1888 +
1889 +
    #[test]
1890 +
    fn test_length() {
1891 +
        expect(&["(length '(1 2 3))"], Expr::Integer(3));
1892 +
        expect(&["(length [1 2 3 4])"], Expr::Integer(4));
1893 +
        expect(&["(length \"hello\")"], Expr::Integer(5));
1894 +
        expect(&["(length (dict [:x 1 :y 2]))"], Expr::Integer(2));
1895 +
    }
1896 +
1897 +
    #[test]
1898 +
    fn test_empty() {
1899 +
        expect(&["(empty? '(1 2 3))"], Expr::Bool(false));
1900 +
        expect(&["(empty? '())"], Expr::Bool(true));
1901 +
        expect(&["(empty? [1 2 3])"], Expr::Bool(false));
1902 +
        expect(&["(empty? [])"], Expr::Bool(true));
1903 +
        expect(&["(empty? \"hello\")"], Expr::Bool(false));
1904 +
        expect(&["(empty? \"\")"], Expr::Bool(true));
1905 +
        expect(&["(empty? (dict [:x 1]))"], Expr::Bool(false));
1906 +
        expect(&["(empty? (dict))"], Expr::Bool(true));
1907 +
    }
1908 +
1909 +
    #[test]
1910 +
    fn test_contains() {
1911 +
        expect(&["(contains? 2 '(1 2 3))"], Expr::Bool(true));
1912 +
        expect(&["(contains? 4 '(1 2 3))"], Expr::Bool(false));
1913 +
        expect(&["(contains? 2 [1 2 3])"], Expr::Bool(true));
1914 +
        expect(&["(contains? 4 [1 2 3])"], Expr::Bool(false));
1915 +
        expect(&["(contains? `e` \"hello\")"], Expr::Bool(true));
1916 +
        expect(&["(contains? \"lo\" \"hello\")"], Expr::Bool(true));
1917 +
        expect(&["(contains? `z` \"hello\")"], Expr::Bool(false));
1918 +
        expect(&["(contains? :x (dict [:x 1]))"], Expr::Bool(true));
1919 +
        expect(&["(contains? :y (dict [:x 1]))"], Expr::Bool(false));
1920 +
    }
1921 +
1922 +
    #[test]
1923 +
    fn test_append() {
1924 +
        expect(
1925 +
            &["(append [1 2] 3 4)"],
1926 +
            Expr::vector([
1927 +
                Expr::Integer(1),
1928 +
                Expr::Integer(2),
1929 +
                Expr::Integer(3),
1930 +
                Expr::Integer(4),
1931 +
            ]),
1932 +
        );
1933 +
        expect(&["(append [] 1)"], Expr::vector([Expr::Integer(1)]));
1934 +
    }
1935 +
1936 +
    #[test]
1937 +
    fn test_reverse() {
1938 +
        expect(
1939 +
            &["(reverse [1 2 3])"],
1940 +
            Expr::vector([Expr::Integer(3), Expr::Integer(2), Expr::Integer(1)]),
1941 +
        );
1942 +
        expect(&["(reverse [])"], Expr::vector([]));
1943 +
    }
1944 +
1945 +
    #[test]
1946 +
    fn test_range() {
1947 +
        expect(
1948 +
            &["(range 5)"],
1949 +
            Expr::vector([
1950 +
                Expr::Integer(0),
1951 +
                Expr::Integer(1),
1952 +
                Expr::Integer(2),
1953 +
                Expr::Integer(3),
1954 +
                Expr::Integer(4),
1955 +
            ]),
1956 +
        );
1957 +
        expect(
1958 +
            &["(range 2 5)"],
1959 +
            Expr::vector([Expr::Integer(2), Expr::Integer(3), Expr::Integer(4)]),
1960 +
        );
1961 +
        expect(
1962 +
            &["(range 0 10 2)"],
1963 +
            Expr::vector([
1964 +
                Expr::Integer(0),
1965 +
                Expr::Integer(2),
1966 +
                Expr::Integer(4),
1967 +
                Expr::Integer(6),
1968 +
                Expr::Integer(8),
1969 +
            ]),
1970 +
        );
1971 +
        expect(&["(range 0)"], Expr::vector([]));
1972 +
    }
1973 +
1974 +
    #[test]
1975 +
    fn test_quote() {
1976 +
        expect(&["'symbol"], Expr::Symbol("symbol".into()));
1977 +
        expect(&["'(symbol)"], Expr::list([Expr::Symbol("symbol".into())]));
1978 +
        expect(
1979 +
            &["''(symbol)"],
1980 +
            Expr::Quoted(Box::new(Expr::list([Expr::Symbol("symbol".into())]))),
1981 +
        );
1982 +
    }
1983 +
1984 +
    #[test]
1985 +
    fn test_error() {
1986 +
        expect_err(
1987 +
            &["(error 'other)"],
1988 +
            Error::User(Expr::Symbol("other".into())),
1989 +
        );
1990 +
    }
1991 +
1992 +
    #[test]
1993 +
    fn test_docs() {
1994 +
        let input = "
1995 +
            (def nord \"Nord nord nord.\" 42)
1996 +
            (def fnord \"Fnord fnord fnord.\" (fn [] 42))";
1997 +
        let tokens = Scanner::new(input);
1998 +
        let parser = Parser::new(tokens);
1999 +
        let eval = Evaluator::new(parser);
2000 +
2001 +
        let mut env = Env::default();
2002 +
        let _ = eval.eval(&mut env).unwrap();
2003 +
2004 +
        assert_eq!(env.lookup_doc("nord"), Some("Nord nord nord."));
2005 +
        assert_eq!(env.lookup_doc("fnord"), Some("Fnord fnord fnord."));
2006 +
    }
2007 +
2008 +
    #[test]
2009 +
    fn test_mutable_refs() {
2010 +
        expect(
2011 +
            &["(ref 42)"],
2012 +
            Expr::Ref(Rc::new(RefCell::new(Expr::Integer(42)))),
2013 +
        );
2014 +
        expect(&["(def r (ref 42))", "(deref r)"], Expr::Integer(42));
2015 +
        expect(
2016 +
            &["(def r (ref 1))", "(set! r 2)", "(deref r)"],
2017 +
            Expr::Integer(2),
2018 +
        );
2019 +
        expect(
2020 +
            &["(def r (ref 1))", "(def s r)", "(set! s 3)", "(deref r)"],
2021 +
            Expr::Integer(3),
2022 +
        );
2023 +
        // Test mutations to refs are persisted beyond a lambda's scope.
2024 +
        expect(
2025 +
            &[
2026 +
                "(def inc-ref",
2027 +
                "  (fn [r]",
2028 +
                "    (def temp (deref r))",
2029 +
                "    (set! r (+ temp 1))))",
2030 +
                "(def a (ref 0))",
2031 +
                "(inc-ref a)",
2032 +
                "(deref a)",
2033 +
            ],
2034 +
            Expr::Integer(1),
2035 +
        );
2036 +
        expect(
2037 +
            &[
2038 +
                "(def ref-mapper",
2039 +
                "  (fn [f]",
2040 +
                "    (fn [r]",
2041 +
                "      (def temp (deref r))",
2042 +
                "      (set! r (f temp)))))",
2043 +
                "(def ref-incer (ref-mapper (fn [x] (+ x 1))))",
2044 +
                "(def foo (ref 0))",
2045 +
                "(ref-incer foo)",
2046 +
                "(deref foo)",
2047 +
            ],
2048 +
            Expr::Integer(1),
2049 +
        );
2050 +
        // Test multiple refs mutated in multiple lambdas.
2051 +
        expect(
2052 +
            &[
2053 +
                "(def make-counter",
2054 +
                "  (fn []",
2055 +
                "    (def current (ref 0))",
2056 +
                "    (fn []",
2057 +
                "      (def temp (deref current))",
2058 +
                "      (set! current (+ temp 1))",
2059 +
                "      temp)))",
2060 +
                "(def c1 (make-counter))",
2061 +
                "(c1)",
2062 +
                "(c1)",
2063 +
                "(def c2 (make-counter))",
2064 +
                "(c2)",
2065 +
                "(c1)",
2066 +
                "(list (c1) (c2))",
2067 +
            ],
2068 +
            Expr::list([Expr::Integer(3), Expr::Integer(1)]),
2069 +
        );
2070 +
        // Test modify! function.
2071 +
        expect(
2072 +
            &[
2073 +
                "(def r (ref 5))",
2074 +
                "(modify! r (fn [x] (* x 2)))",
2075 +
                "(deref r)",
2076 +
            ],
2077 +
            Expr::Integer(10),
2078 +
        );
2079 +
    }
2080 +
2081 +
    #[test]
2082 +
    fn test_foreign_function() {
2083 +
        let input = "(rust-reverse \"alice\")";
2084 +
        let tokens = Scanner::new(input);
2085 +
        let parser = Parser::new(tokens);
2086 +
        let mut env = Env::default().intrinsics([(
2087 +
            "rust-reverse",
2088 +
            "Reverse a string",
2089 +
            |args: Vec<Expr>, _: &Env<'_>| {
2090 +
                if args.len() != 1 {
2091 +
                    return Err(Error::WrongArgumentCount {
2092 +
                        expected: 1,
2093 +
                        actual: args.len(),
2094 +
                    });
2095 +
                }
2096 +
                match &args[0] {
2097 +
                    Expr::Str(s) => Ok(Expr::Str(s.chars().rev().collect())),
2098 +
                    _ => Err(Error::ExpectedValue("string")),
2099 +
                }
2100 +
            },
2101 +
        )]);
2102 +
2103 +
        let result = Evaluator::new(parser).eval(&mut env).unwrap();
2104 +
        assert_eq!(result, Expr::Str("ecila".to_owned()));
2105 +
    }
2106 +
}
ombre/src/lisp/list.rs added +190 -0
1 +
//! Defines the [`List`] type.
2 +
use std::{ops::Deref, rc::Rc};
3 +
4 +
/// Traditional persistent "cons" list.
5 +
#[derive(Debug, Clone, PartialEq, Eq)]
6 +
pub struct List<T> {
7 +
    head: Link<T>,
8 +
}
9 +
10 +
impl<T> Default for List<T> {
11 +
    fn default() -> Self {
12 +
        Self { head: None }
13 +
    }
14 +
}
15 +
16 +
/// Link to the next list node.
17 +
type Link<T> = Option<Rc<Node<T>>>;
18 +
19 +
/// List node.
20 +
#[derive(Debug, Clone, PartialEq, Eq)]
21 +
struct Node<T> {
22 +
    elem: T,
23 +
    next: Link<T>,
24 +
}
25 +
26 +
impl<T> Deref for Node<T> {
27 +
    type Target = T;
28 +
29 +
    fn deref(&self) -> &Self::Target {
30 +
        &self.elem
31 +
    }
32 +
}
33 +
34 +
impl<T> Drop for List<T> {
35 +
    fn drop(&mut self) {
36 +
        let mut head = self.head.take();
37 +
        while let Some(node) = head {
38 +
            if let Ok(mut node) = Rc::try_unwrap(node) {
39 +
                head = node.next.take();
40 +
            } else {
41 +
                break;
42 +
            }
43 +
        }
44 +
    }
45 +
}
46 +
47 +
impl<T, const N: usize> From<[T; N]> for List<T> {
48 +
    fn from(value: [T; N]) -> Self {
49 +
        List::build(value.into_iter())
50 +
    }
51 +
}
52 +
53 +
impl<T> From<Vec<T>> for List<T> {
54 +
    fn from(value: Vec<T>) -> Self {
55 +
        List::build(value.into_iter())
56 +
    }
57 +
}
58 +
59 +
impl<T> List<T> {
60 +
    /// Create a new list from a value.
61 +
    pub fn new(head: T) -> Self {
62 +
        Self {
63 +
            head: Some(Rc::new(Node {
64 +
                elem: head,
65 +
                next: None,
66 +
            })),
67 +
        }
68 +
    }
69 +
70 +
    /// Take the head of the list.
71 +
    pub fn head(&self) -> Option<&T> {
72 +
        self.head.as_ref().map(|node| &node.elem)
73 +
    }
74 +
75 +
    /// Take the tail of the list.
76 +
    pub fn tail(&self) -> List<T> {
77 +
        List {
78 +
            head: self.head.as_ref().and_then(|node| node.next.clone()),
79 +
        }
80 +
    }
81 +
82 +
    /// Return a list with the value added to its head.
83 +
    pub fn prepend(&self, elem: T) -> List<T> {
84 +
        List {
85 +
            head: Some(Rc::new(Node {
86 +
                elem,
87 +
                next: self.head.clone(),
88 +
            })),
89 +
        }
90 +
    }
91 +
92 +
    /// Get the length of the list.
93 +
    pub fn len(&self) -> usize {
94 +
        let mut len = 0;
95 +
        let mut current = &self.head;
96 +
97 +
        while let Some(node) = current {
98 +
            len += 1;
99 +
            current = &node.next;
100 +
        }
101 +
        len
102 +
    }
103 +
104 +
    /// Return an iterator over the list.
105 +
    pub fn iter(&self) -> Iter<'_, T> {
106 +
        Iter {
107 +
            next: self.head.as_deref(),
108 +
        }
109 +
    }
110 +
111 +
    /// Check if the list is empty.
112 +
    pub fn is_empty(&self) -> bool {
113 +
        self.head.is_none()
114 +
    }
115 +
116 +
    /// Build a list in-order from an iterator.
117 +
    pub fn build(iter: impl DoubleEndedIterator<Item = T>) -> Self {
118 +
        let mut list = Self::default();
119 +
        for item in iter.rev() {
120 +
            list = list.prepend(item);
121 +
        }
122 +
        list
123 +
    }
124 +
}
125 +
126 +
impl<T: PartialEq> List<T> {
127 +
    /// Check if the list contains an item.
128 +
    pub fn contains(&self, item: &T) -> bool {
129 +
        self.iter().any(|i| i == item)
130 +
    }
131 +
}
132 +
133 +
/// List iterator.
134 +
pub struct Iter<'a, T> {
135 +
    next: Option<&'a Node<T>>,
136 +
}
137 +
138 +
impl<'a, T> Iterator for Iter<'a, T> {
139 +
    type Item = &'a T;
140 +
141 +
    fn next(&mut self) -> Option<Self::Item> {
142 +
        self.next.map(|node| {
143 +
            self.next = node.next.as_deref();
144 +
            &node.elem
145 +
        })
146 +
    }
147 +
}
148 +
149 +
/// Nb. This function creates a list in reverse order.
150 +
impl<T> FromIterator<T> for List<T> {
151 +
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
152 +
        let mut list = List::default();
153 +
        for item in iter {
154 +
            list = list.prepend(item);
155 +
        }
156 +
        list
157 +
    }
158 +
}
159 +
160 +
#[cfg(test)]
161 +
#[allow(clippy::unwrap_used)]
162 +
mod tests {
163 +
    use super::*;
164 +
165 +
    #[test]
166 +
    fn test_list_type() {
167 +
        let list = List::new('o').prepend('l').prepend('l').prepend('e').prepend('h');
168 +
        let result = list.iter().collect::<String>();
169 +
        assert_eq!(result.as_str(), "hello");
170 +
        assert_eq!(list.len(), 5);
171 +
        assert_eq!(list.is_empty(), false);
172 +
        assert_eq!(list.head(), Some(&'h'));
173 +
        assert_eq!(list.tail().tail(), List::new('o').prepend('l').prepend('l'));
174 +
        assert_eq!(list.tail().tail().tail(), List::new('o').prepend('l'));
175 +
176 +
        let list = List::build(result.chars());
177 +
        assert_eq!(
178 +
            list,
179 +
            List::new('o').prepend('l').prepend('l').prepend('e').prepend('h')
180 +
        );
181 +
182 +
        let list = List::from_iter(result.chars());
183 +
        assert_eq!(
184 +
            list,
185 +
            List::new('h').prepend('e').prepend('l').prepend('l').prepend('o')
186 +
        );
187 +
        assert_eq!(List::<()>::default().is_empty(), true);
188 +
        assert_eq!(List::<()>::default().head(), None);
189 +
    }
190 +
}
ombre/src/lisp/parser.rs added +324 -0
1 +
//! Parser.
2 +
use std::fmt;
3 +
use std::iter::Peekable;
4 +
use std::result;
5 +
6 +
use crate::lisp::evaluator::Expr;
7 +
use crate::lisp::scanner;
8 +
use crate::lisp::scanner::Token;
9 +
10 +
/// Result type for all functions.
11 +
pub type Result<T> = result::Result<T, Error>;
12 +
13 +
/// Parse error.
14 +
#[derive(Debug, Clone, PartialEq)]
15 +
pub enum Error {
16 +
    /// Scanning error.
17 +
    Scanner(scanner::Error),
18 +
    /// An unexpected token was encountered.
19 +
    UnexpectedToken(Token<'static>),
20 +
    /// An unexpected end of input was reached.
21 +
    EndOfInput,
22 +
}
23 +
24 +
impl fmt::Display for Error {
25 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26 +
        match self {
27 +
            Error::Scanner(e) => write!(f, "scanner: {e}"),
28 +
            Error::UnexpectedToken(token) => write!(f, "unexpected token: {token:?}"),
29 +
            Error::EndOfInput => write!(f, "unexpected end of input"),
30 +
        }
31 +
    }
32 +
}
33 +
34 +
impl std::error::Error for Error {}
35 +
36 +
/// Parse a stream of tokens into a syntax tree.
37 +
#[derive(Debug)]
38 +
pub struct Parser<'a, T>
39 +
where
40 +
    T: Iterator<Item = scanner::Result<Token<'a>>>,
41 +
{
42 +
    tokens: Peekable<T>,
43 +
}
44 +
45 +
impl<'a, T> Parser<'a, T>
46 +
where
47 +
    T: Iterator<Item = scanner::Result<Token<'a>>>,
48 +
{
49 +
    /// Create a new parser from a token stream.
50 +
    pub fn new(tokens: T) -> Self {
51 +
        Parser {
52 +
            tokens: tokens.peekable(),
53 +
        }
54 +
    }
55 +
56 +
    /// Parse all the input into a vector of expressions.
57 +
    pub fn parse(self) -> Result<Vec<Expr>> {
58 +
        self.collect()
59 +
    }
60 +
61 +
    fn peek(&mut self) -> Result<Token<'a>> {
62 +
        self.tokens
63 +
            .peek()
64 +
            .cloned()
65 +
            .ok_or(Error::EndOfInput)?
66 +
            .map_err(Error::Scanner)
67 +
    }
68 +
69 +
    fn parse_expr(&mut self) -> Result<Expr> {
70 +
        let token = self.peek()?;
71 +
        let expr = match token {
72 +
            Token::LParen => self.parse_sexpr()?,
73 +
            Token::RParen => return Err(Error::UnexpectedToken(token.owned())),
74 +
            Token::LBrace => self.parse_qexpr()?,
75 +
            Token::RBrace => return Err(Error::UnexpectedToken(token.owned())),
76 +
            Token::LBracket => self.parse_vector()?,
77 +
            Token::RBracket => return Err(Error::UnexpectedToken(token.owned())),
78 +
            Token::Quote => self.parse_quoted()?,
79 +
            Token::Symbol(s) => {
80 +
                self.tokens.next();
81 +
                Expr::Symbol(s.into())
82 +
            }
83 +
            Token::Atom(s) => {
84 +
                self.tokens.next();
85 +
                Expr::Atom(s.into())
86 +
            }
87 +
            Token::Float(n) => {
88 +
                self.tokens.next();
89 +
                Expr::Float(n)
90 +
            }
91 +
            Token::Integer(n) => {
92 +
                self.tokens.next();
93 +
                Expr::Integer(n)
94 +
            }
95 +
            Token::Char(c) => {
96 +
                self.tokens.next();
97 +
                Expr::Char(c)
98 +
            }
99 +
            Token::Color(c) => {
100 +
                self.tokens.next();
101 +
                Expr::Color(c)
102 +
            }
103 +
            Token::Str(s) => {
104 +
                self.tokens.next();
105 +
                Expr::Str(s.into_owned())
106 +
            }
107 +
        };
108 +
        Ok(expr)
109 +
    }
110 +
111 +
    fn parse_sexpr(&mut self) -> Result<Expr> {
112 +
        self.next_if(|t| t == &Token::LParen)?;
113 +
        let exprs = self.parse_until(|t| t == &Token::RParen)?;
114 +
        self.next_if(|t| t == &Token::RParen)?;
115 +
116 +
        Ok(Expr::list(exprs))
117 +
    }
118 +
119 +
    fn parse_qexpr(&mut self) -> Result<Expr> {
120 +
        self.next_if(|t| t == &Token::LBrace)?;
121 +
        let exprs = self.parse_until(|t| t == &Token::RBrace)?;
122 +
        self.next_if(|t| t == &Token::RBrace)?;
123 +
124 +
        Ok(Expr::Quoted(Expr::list(exprs).into()))
125 +
    }
126 +
127 +
    fn parse_vector(&mut self) -> Result<Expr> {
128 +
        self.next_if(|t| t == &Token::LBracket)?;
129 +
        let exprs = self.parse_until(|t| t == &Token::RBracket)?;
130 +
        self.next_if(|t| t == &Token::RBracket)?;
131 +
132 +
        Ok(Expr::vector(exprs))
133 +
    }
134 +
135 +
    fn parse_quoted(&mut self) -> Result<Expr> {
136 +
        self.next_if(|t| t == &Token::Quote)?;
137 +
        let expr = self.parse_expr()?;
138 +
139 +
        Ok(Expr::Quoted(expr.into()))
140 +
    }
141 +
142 +
    fn next_if(&mut self, condition: impl FnOnce(&Token<'_>) -> bool) -> Result<Token<'a>> {
143 +
        let tok = self.tokens.next().ok_or(Error::EndOfInput)?.map_err(Error::Scanner)?;
144 +
145 +
        if condition(&tok) {
146 +
            return Ok(tok);
147 +
        }
148 +
        Err(Error::UnexpectedToken(tok.owned()))
149 +
    }
150 +
151 +
    fn parse_until(&mut self, until: impl Fn(&Token<'a>) -> bool) -> Result<Vec<Expr>> {
152 +
        let mut exprs = Vec::new();
153 +
154 +
        while let Some(Ok(t)) = self.tokens.peek() {
155 +
            if until(t) {
156 +
                break;
157 +
            }
158 +
            let expr = self.parse_expr()?;
159 +
            exprs.push(expr);
160 +
        }
161 +
        Ok(exprs)
162 +
    }
163 +
}
164 +
165 +
impl<'a, T> Iterator for Parser<'a, T>
166 +
where
167 +
    T: Iterator<Item = scanner::Result<Token<'a>>>,
168 +
{
169 +
    type Item = Result<Expr>;
170 +
171 +
    fn next(&mut self) -> Option<Self::Item> {
172 +
        if self.tokens.peek().is_some() {
173 +
            Some(self.parse_expr())
174 +
        } else {
175 +
            None
176 +
        }
177 +
    }
178 +
}
179 +
180 +
#[cfg(test)]
181 +
#[allow(clippy::unwrap_used)]
182 +
mod tests {
183 +
    use super::*;
184 +
185 +
    use crate::lisp::scanner::Scanner;
186 +
187 +
    #[track_caller]
188 +
    fn ok(input: &str, expected: &[Expr]) {
189 +
        let exprs = Parser::new(Scanner::new(input)).parse().unwrap();
190 +
        assert_eq!(exprs, expected);
191 +
    }
192 +
193 +
    #[track_caller]
194 +
    fn err(input: &str) {
195 +
        Parser::new(Scanner::new(input)).parse().unwrap_err();
196 +
    }
197 +
198 +
    #[test]
199 +
    fn test_parse_err() {
200 +
        err("(");
201 +
        err(")");
202 +
        err("{");
203 +
        err("}");
204 +
        err("(cons 1 (cons 2 nil)");
205 +
        err(")(");
206 +
        err("(}");
207 +
        err("(const 1 nil}");
208 +
        err("{const 1 nil)");
209 +
    }
210 +
211 +
    #[test]
212 +
    fn test_parse_sexpr() {
213 +
        ok("()", &[Expr::nil()]);
214 +
        ok("(cons)", &[Expr::list([Expr::Symbol("cons".into())])]);
215 +
        ok(
216 +
            "(+ 4 2)",
217 +
            &[Expr::list([
218 +
                Expr::Symbol("+".into()),
219 +
                Expr::Integer(4),
220 +
                Expr::Integer(2),
221 +
            ])],
222 +
        );
223 +
    }
224 +
225 +
    #[test]
226 +
    fn test_parse_sexpr_nested() {
227 +
        ok(
228 +
            "(cons 1 (cons 2 (cons 3 nil)))",
229 +
            &[Expr::list([
230 +
                Expr::Symbol("cons".into()),
231 +
                Expr::Integer(1),
232 +
                Expr::list([
233 +
                    Expr::Symbol("cons".into()),
234 +
                    Expr::Integer(2),
235 +
                    Expr::list([
236 +
                        Expr::Symbol("cons".into()),
237 +
                        Expr::Integer(3),
238 +
                        Expr::Symbol("nil".into()),
239 +
                    ]),
240 +
                ]),
241 +
            ])],
242 +
        );
243 +
    }
244 +
245 +
    #[test]
246 +
    fn test_parse_qexpr() {
247 +
        ok("{}", &[Expr::Quoted(Box::new(Expr::nil()))]);
248 +
        ok(
249 +
            "{+ 4 2}",
250 +
            &[Expr::Quoted(Box::new(Expr::list([
251 +
                Expr::Symbol("+".into()),
252 +
                Expr::Integer(4),
253 +
                Expr::Integer(2),
254 +
            ])))],
255 +
        );
256 +
        ok(
257 +
            "{sym}",
258 +
            &[Expr::Quoted(Box::new(Expr::list([Expr::Symbol(
259 +
                "sym".into(),
260 +
            )])))],
261 +
        );
262 +
        ok(
263 +
            "{{sym}}",
264 +
            &[Expr::Quoted(
265 +
                Expr::list([Expr::Quoted(
266 +
                    Expr::list([Expr::Symbol("sym".into())]).into(),
267 +
                )])
268 +
                .into(),
269 +
            )],
270 +
        );
271 +
        ok(
272 +
            "{(sym)}",
273 +
            &[Expr::Quoted(
274 +
                Expr::list([Expr::list([Expr::Symbol("sym".into())])]).into(),
275 +
            )],
276 +
        );
277 +
    }
278 +
279 +
    #[test]
280 +
    fn test_parse_vector() {
281 +
        ok("[]", &[Expr::Vector(vec![])]);
282 +
        ok(
283 +
            "[1 2 3]",
284 +
            &[Expr::vector([
285 +
                Expr::Integer(1),
286 +
                Expr::Integer(2),
287 +
                Expr::Integer(3),
288 +
            ])],
289 +
        );
290 +
    }
291 +
292 +
    #[test]
293 +
    fn test_parse_quoted() {
294 +
        ok(
295 +
            "'(sym)",
296 +
            &[Expr::Quoted(Box::new(Expr::list([Expr::Symbol(
297 +
                "sym".into(),
298 +
            )])))],
299 +
        );
300 +
        ok(
301 +
            "''(sym)",
302 +
            &[Expr::Quoted(Box::new(Expr::Quoted(Box::new(Expr::list(
303 +
                [Expr::Symbol("sym".into())],
304 +
            )))))],
305 +
        );
306 +
    }
307 +
308 +
    #[test]
309 +
    fn test_parse_if() {
310 +
        ok(
311 +
            "(if (eq? a b) 0 1)",
312 +
            &[Expr::list([
313 +
                Expr::Symbol("if".into()),
314 +
                Expr::list([
315 +
                    Expr::Symbol("eq?".into()),
316 +
                    Expr::Symbol("a".into()),
317 +
                    Expr::Symbol("b".into()),
318 +
                ]),
319 +
                Expr::Integer(0),
320 +
                Expr::Integer(1),
321 +
            ])],
322 +
        );
323 +
    }
324 +
}
ombre/src/lisp/scanner.rs added +508 -0
1 +
//! Token scanner or "lexer".
2 +
use std::borrow::Cow;
3 +
use std::fmt;
4 +
use std::iter::Peekable;
5 +
use std::result;
6 +
use std::str::CharIndices;
7 +
8 +
use crate::gfx::color::Rgba8;
9 +
use crate::*;
10 +
11 +
/// Result type for all functions.
12 +
pub type Result<T> = result::Result<T, Error>;
13 +
14 +
/// Lexical error.
15 +
#[derive(Debug, Clone, PartialEq, Eq)]
16 +
pub enum Error {
17 +
    /// An unexpected character was encountered in the input.
18 +
    UnexpectedChar {
19 +
        /// The unexpected character.
20 +
        ch: char,
21 +
        /// Its index in the input string.
22 +
        ix: usize,
23 +
    },
24 +
    /// The end of the input was reached unexpectedly.
25 +
    EndOfInput,
26 +
    /// Error parsing a float.
27 +
    ParseFloat(std::num::ParseFloatError),
28 +
    /// Error parsing an integer.
29 +
    ParseInteger(std::num::ParseIntError),
30 +
    /// Error parsing a color.
31 +
    ParseColor(color::ParseRgba8Error),
32 +
}
33 +
34 +
impl fmt::Display for Error {
35 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 +
        match self {
37 +
            Error::UnexpectedChar { ch, ix } => {
38 +
                write!(f, "unexpected character '{ch}' at index {ix}")
39 +
            }
40 +
            Error::EndOfInput => write!(f, "unexpected end of input"),
41 +
            Error::ParseFloat(e) => write!(f, "parsing float: {e}"),
42 +
            Error::ParseInteger(e) => write!(f, "parsing integer: {e}"),
43 +
            Error::ParseColor(e) => write!(f, "parsing color: {e}"),
44 +
        }
45 +
    }
46 +
}
47 +
48 +
impl std::error::Error for Error {}
49 +
50 +
/// A token representing some piece of source code.
51 +
#[derive(Debug, Clone, PartialEq)]
52 +
pub enum Token<'a> {
53 +
    /// Eg. `{`
54 +
    LBrace,
55 +
    /// Eg. `}`
56 +
    RBrace,
57 +
    /// Eg. `(`
58 +
    LParen,
59 +
    /// Eg. `)`
60 +
    RParen,
61 +
    /// Eg. `[`
62 +
    LBracket,
63 +
    /// Eg. `]`
64 +
    RBracket,
65 +
    /// Eg. '
66 +
    Quote,
67 +
    /// Eg. fnord
68 +
    Symbol(Cow<'a, str>),
69 +
    /// Eg. :fnord
70 +
    Atom(Cow<'a, str>),
71 +
    /// Eg. `z`
72 +
    Char(char),
73 +
    /// Eg. "xyz"
74 +
    Str(Cow<'a, str>),
75 +
    /// Eg. `42`, `0.1`
76 +
    Float(f64),
77 +
    /// Eg. `-42`
78 +
    Integer(i64),
79 +
    /// Eg. `#ff0033`
80 +
    Color(Rgba8),
81 +
}
82 +
83 +
impl Token<'_> {
84 +
    /// Returns an owned token with a static lifetime.
85 +
    pub fn owned(self) -> Token<'static> {
86 +
        use Token::*;
87 +
88 +
        match self {
89 +
            LBrace => LBrace,
90 +
            RBrace => RBrace,
91 +
            LParen => LParen,
92 +
            RParen => RParen,
93 +
            LBracket => LBracket,
94 +
            RBracket => RBracket,
95 +
            Quote => Quote,
96 +
            Symbol(s) => Symbol(Cow::Owned(s.into_owned())),
97 +
            Atom(s) => Atom(Cow::Owned(s.into_owned())),
98 +
            Char(c) => Char(c),
99 +
            Str(s) => Str(Cow::Owned(s.into_owned())),
100 +
            Float(n) => Float(n),
101 +
            Integer(n) => Integer(n),
102 +
            Color(c) => Color(c),
103 +
        }
104 +
    }
105 +
}
106 +
107 +
/// Generates a stream of [`Token`] values given an input string.
108 +
#[derive(Debug, Clone)]
109 +
pub struct Scanner<'a> {
110 +
    chars: Peekable<CharIndices<'a>>,
111 +
    input: &'a str,
112 +
}
113 +
114 +
impl<'a> Scanner<'a> {
115 +
    /// Create a new scanner for the given input.
116 +
    pub fn new(input: &'a str) -> Self {
117 +
        Self {
118 +
            chars: input.char_indices().peekable(),
119 +
            input,
120 +
        }
121 +
    }
122 +
}
123 +
124 +
impl<'a> Scanner<'a> {
125 +
    fn scan_color(&mut self) -> Result<Token<'a>> {
126 +
        let (start, _) = self.skip_char('#')?;
127 +
        let digits = self.skip_while(|c| c.is_ascii_hexdigit());
128 +
129 +
        if digits.is_empty() {
130 +
            return Err(Error::EndOfInput);
131 +
        }
132 +
        self.input[start..=start + digits.len()]
133 +
            .parse()
134 +
            .map(Token::Color)
135 +
            .map_err(Error::ParseColor)
136 +
    }
137 +
138 +
    fn scan_atom(&mut self) -> Result<Token<'a>> {
139 +
        let (_, _) = self.skip_char(':')?;
140 +
        let sym = self.scan_ident()?;
141 +
142 +
        Ok(Token::Atom(sym.into()))
143 +
    }
144 +
145 +
    fn scan_symbol(&mut self) -> Result<Token<'a>> {
146 +
        let sym = self.scan_ident()?;
147 +
148 +
        Ok(Token::Symbol(sym.into()))
149 +
    }
150 +
151 +
    fn scan_ident(&mut self) -> Result<&'a str> {
152 +
        let valid = "!@#$%^&*/-+=<>?~_";
153 +
        let ident = self.skip_while(|c| c.is_ascii_alphanumeric() || valid.contains(c));
154 +
155 +
        if ident.is_empty() {
156 +
            Err(self.error())
157 +
        } else {
158 +
            Ok(ident)
159 +
        }
160 +
    }
161 +
162 +
    fn scan_number(&mut self) -> Result<Token<'a>> {
163 +
        let (start, _) = self.skip_if(|c| c.is_ascii_digit())?;
164 +
        let mut floating = false;
165 +
166 +
        while let Some((_, ch)) = self.peek() {
167 +
            if ch.is_ascii_digit() {
168 +
                self.skip_next()?;
169 +
            } else if ch == '.' && !floating {
170 +
                floating = true;
171 +
                self.skip_next()?;
172 +
            } else {
173 +
                break;
174 +
            }
175 +
        }
176 +
        let string = &self.input[start..self.index()];
177 +
178 +
        if floating {
179 +
            string.parse::<f64>().map(Token::Float).map_err(Error::ParseFloat)
180 +
        } else {
181 +
            string.parse::<i64>().map(Token::Integer).map_err(Error::ParseInteger)
182 +
        }
183 +
    }
184 +
185 +
    fn scan_char(&mut self) -> Result<Token<'a>> {
186 +
        self.skip_char('`')?;
187 +
        let (_, ch) = self.skip_next()?;
188 +
189 +
        let ch = if ch == '\\' {
190 +
            let (_, escaped) = self.skip_next()?;
191 +
            escaped
192 +
        } else {
193 +
            ch
194 +
        };
195 +
        self.skip_char('`')?;
196 +
197 +
        Ok(Token::Char(ch))
198 +
    }
199 +
200 +
    fn scan_str(&mut self) -> Result<Token<'a>> {
201 +
        let (start, _) = self.skip_char('"')?;
202 +
        loop {
203 +
            let (ix, ch) = self.skip_next()?;
204 +
205 +
            match ch {
206 +
                '"' => {
207 +
                    return Ok(Token::Str(self.input[start + 1..ix].into()));
208 +
                }
209 +
                '\\' => {
210 +
                    self.skip_next()?;
211 +
                }
212 +
                _ => {}
213 +
            }
214 +
        }
215 +
    }
216 +
217 +
    fn skip_char(&mut self, ch: char) -> Result<(usize, char)> {
218 +
        self.skip_if(|c| c == ch)
219 +
    }
220 +
221 +
    fn skip_if(&mut self, condition: impl FnOnce(char) -> bool) -> Result<(usize, char)> {
222 +
        let (i, c) = self.peek().ok_or(Error::EndOfInput)?;
223 +
224 +
        if condition(c) {
225 +
            self.chars.next();
226 +
            Ok((i, c))
227 +
        } else {
228 +
            Err(self.error())
229 +
        }
230 +
    }
231 +
232 +
    fn skip_while(&mut self, condition: impl Fn(char) -> bool) -> &'a str {
233 +
        let Some((start, _)) = self.peek() else {
234 +
            return "";
235 +
        };
236 +
        while let Some((ix, c)) = self.peek() {
237 +
            if condition(c) {
238 +
                self.chars.next();
239 +
            } else {
240 +
                return &self.input[start..ix];
241 +
            }
242 +
        }
243 +
        &self.input[start..]
244 +
    }
245 +
246 +
    fn skip_next(&mut self) -> Result<(usize, char)> {
247 +
        self.chars.next().ok_or(Error::EndOfInput)
248 +
    }
249 +
250 +
    fn index(&mut self) -> usize {
251 +
        if let Some((ix, _)) = self.chars.peek() {
252 +
            *ix
253 +
        } else {
254 +
            self.input.len()
255 +
        }
256 +
    }
257 +
258 +
    fn peek(&mut self) -> Option<(usize, char)> {
259 +
        self.chars.peek().cloned()
260 +
    }
261 +
262 +
    fn error(&mut self) -> Error {
263 +
        if let Some((index, input)) = self.peek() {
264 +
            Error::UnexpectedChar {
265 +
                ch: input,
266 +
                ix: index,
267 +
            }
268 +
        } else {
269 +
            Error::EndOfInput
270 +
        }
271 +
    }
272 +
}
273 +
274 +
impl<'a> Iterator for Scanner<'a> {
275 +
    type Item = Result<Token<'a>>;
276 +
277 +
    fn next(&mut self) -> Option<Result<Token<'a>>> {
278 +
        while let Some((_, c)) = self.peek() {
279 +
            match c {
280 +
                '(' => {
281 +
                    self.chars.next();
282 +
                    return Some(Ok(Token::LParen));
283 +
                }
284 +
                ')' => {
285 +
                    self.chars.next();
286 +
                    return Some(Ok(Token::RParen));
287 +
                }
288 +
                '{' => {
289 +
                    self.chars.next();
290 +
                    return Some(Ok(Token::LBrace));
291 +
                }
292 +
                '}' => {
293 +
                    self.chars.next();
294 +
                    return Some(Ok(Token::RBrace));
295 +
                }
296 +
                '[' => {
297 +
                    self.chars.next();
298 +
                    return Some(Ok(Token::LBracket));
299 +
                }
300 +
                ']' => {
301 +
                    self.chars.next();
302 +
                    return Some(Ok(Token::RBracket));
303 +
                }
304 +
                ';' => {
305 +
                    // Comment.
306 +
                    self.skip_while(|c| c != '\n');
307 +
                }
308 +
                '#' => {
309 +
                    return Some(self.scan_color());
310 +
                }
311 +
                '`' => {
312 +
                    return Some(self.scan_char());
313 +
                }
314 +
                '"' => {
315 +
                    return Some(self.scan_str());
316 +
                }
317 +
                ':' => {
318 +
                    return Some(self.scan_atom());
319 +
                }
320 +
                '\'' => {
321 +
                    self.chars.next();
322 +
                    return Some(Ok(Token::Quote));
323 +
                }
324 +
                c if c.is_ascii_whitespace() => {
325 +
                    self.chars.next();
326 +
                }
327 +
                c if c.is_ascii_digit() => {
328 +
                    return Some(self.scan_number());
329 +
                }
330 +
                _ => {
331 +
                    return Some(self.scan_symbol());
332 +
                }
333 +
            }
334 +
        }
335 +
        None
336 +
    }
337 +
}
338 +
339 +
#[cfg(test)]
340 +
#[allow(clippy::unwrap_used)]
341 +
mod tests {
342 +
    use super::Rgba8;
343 +
    use super::Token;
344 +
345 +
    #[track_caller]
346 +
    fn ok(input: &str, expected: &[Token<'_>]) {
347 +
        let mut scanner = super::Scanner::new(input);
348 +
        let tokens = scanner.by_ref().collect::<Result<Vec<_>, _>>().unwrap();
349 +
        let next = scanner.peek();
350 +
351 +
        assert_eq!(tokens.as_slice(), expected, "Next character {next:?}");
352 +
        assert!(scanner.peek().is_none(), "Unexpected character {next:?}");
353 +
    }
354 +
355 +
    #[track_caller]
356 +
    fn err(input: &str) {
357 +
        let mut scanner = super::Scanner::new(input);
358 +
        scanner.by_ref().collect::<Result<Vec<_>, _>>().unwrap_err();
359 +
    }
360 +
361 +
    #[test]
362 +
    fn test_invalid() {
363 +
        err(",");
364 +
        err("\"");
365 +
        err("`");
366 +
        err("\\");
367 +
        err(".");
368 +
    }
369 +
370 +
    #[test]
371 +
    fn test_symbol() {
372 +
        ok("const", &[Token::Symbol("const".into())]);
373 +
        ok("_c_o_n_s_", &[Token::Symbol("_c_o_n_s_".into())]);
374 +
        ok("_", &[Token::Symbol("_".into())]);
375 +
        ok("one/two/three", &[Token::Symbol("one/two/three".into())]);
376 +
        ok("fNord_42!", &[Token::Symbol("fNord_42!".into())]);
377 +
        ok("-42", &[Token::Symbol("-42".into())]);
378 +
        ok("+", &[Token::Symbol("+".into())]);
379 +
        ok("-", &[Token::Symbol("-".into())]);
380 +
        ok("*", &[Token::Symbol("*".into())]);
381 +
    }
382 +
383 +
    #[test]
384 +
    fn test_quote() {
385 +
        ok("'fnord", &[Token::Quote, Token::Symbol("fnord".into())]);
386 +
    }
387 +
388 +
    #[test]
389 +
    fn test_char() {
390 +
        ok("`a`", &[Token::Char('a')]);
391 +
        ok("`\"`", &[Token::Char('"')]);
392 +
        ok("` `", &[Token::Char(' ')]);
393 +
        ok("`\\``", &[Token::Char('`')]);
394 +
        ok("`\\\\`", &[Token::Char('\\')]);
395 +
        err("`");
396 +
    }
397 +
398 +
    #[test]
399 +
    fn test_str() {
400 +
        ok(
401 +
            "\"Hello World!\"\"Bonjour Terre!\"",
402 +
            &[
403 +
                Token::Str("Hello World!".into()),
404 +
                Token::Str("Bonjour Terre!".into()),
405 +
            ],
406 +
        );
407 +
        ok(
408 +
            r#""String with \"escapes\"""#,
409 +
            &[Token::Str("String with \\\"escapes\\\"".into())],
410 +
        );
411 +
        err("\"\\");
412 +
        err("\"");
413 +
    }
414 +
415 +
    #[test]
416 +
    fn test_number() {
417 +
        ok("48192", &[Token::Integer(48192)]);
418 +
        ok("10", &[Token::Integer(10)]);
419 +
        ok("0", &[Token::Integer(0)]);
420 +
        ok("000", &[Token::Integer(0)]);
421 +
        ok("481.92", &[Token::Float(481.92)]);
422 +
        ok("1.0", &[Token::Float(1.0)]);
423 +
        ok("0.0", &[Token::Float(0.0)]);
424 +
        ok("0.0001", &[Token::Float(0.0001)]);
425 +
        ok("41.", &[Token::Float(41.0)]);
426 +
        ok("41.0", &[Token::Float(41.0)]);
427 +
    }
428 +
429 +
    #[test]
430 +
    fn test_comment() {
431 +
        ok("; Some comment", &[]);
432 +
        ok(";", &[]);
433 +
        ok(";\n()", &[Token::LParen, Token::RParen]);
434 +
        ok(
435 +
            "(expr) ;; Some comment.",
436 +
            &[Token::LParen, Token::Symbol("expr".into()), Token::RParen],
437 +
        );
438 +
        ok(
439 +
            "; Some comment.\n; Some other comment\n;Some other comment",
440 +
            &[],
441 +
        );
442 +
        ok(
443 +
            "command ; Some comment\n",
444 +
            &[Token::Symbol("command".into())],
445 +
        );
446 +
    }
447 +
448 +
    #[test]
449 +
    fn test_sexpr() {
450 +
        ok("()", &[Token::LParen, Token::RParen]);
451 +
        ok(
452 +
            "(one two)",
453 +
            &[
454 +
                Token::LParen,
455 +
                Token::Symbol("one".into()),
456 +
                Token::Symbol("two".into()),
457 +
                Token::RParen,
458 +
            ],
459 +
        );
460 +
        ok("(", &[Token::LParen]);
461 +
        ok(")", &[Token::RParen]);
462 +
        ok("{", &[Token::LBrace]);
463 +
        ok("}", &[Token::RBrace]);
464 +
    }
465 +
466 +
    #[test]
467 +
    fn test_qexpr() {
468 +
        ok("{}", &[Token::LBrace, Token::RBrace]);
469 +
        ok(
470 +
            "{one two}",
471 +
            &[
472 +
                Token::LBrace,
473 +
                Token::Symbol("one".into()),
474 +
                Token::Symbol("two".into()),
475 +
                Token::RBrace,
476 +
            ],
477 +
        );
478 +
    }
479 +
480 +
    #[test]
481 +
    fn test_vector() {
482 +
        ok("[]", &[Token::LBracket, Token::RBracket]);
483 +
        ok(
484 +
            "[one two]",
485 +
            &[
486 +
                Token::LBracket,
487 +
                Token::Symbol("one".into()),
488 +
                Token::Symbol("two".into()),
489 +
                Token::RBracket,
490 +
            ],
491 +
        );
492 +
    }
493 +
494 +
    #[test]
495 +
    fn test_color() {
496 +
        ok(
497 +
            "#ff0011",
498 +
            &[Token::Color(Rgba8::new(0xff, 0x00, 0x11, 0xff))],
499 +
        );
500 +
        ok(
501 +
            "#ff001133",
502 +
            &[Token::Color(Rgba8::new(0xff, 0x00, 0x11, 0x33))],
503 +
        );
504 +
        err("#");
505 +
        err("#ff00");
506 +
        err("#ff00113399");
507 +
    }
508 +
}
ombre/src/logger.rs added +100 -0
1 +
//! Logging module.
2 +
use std::io::Write;
3 +
use std::time::SystemTime;
4 +
5 +
use log::{Level, Log, Metadata, Record, SetLoggerError};
6 +
7 +
struct Logger {
8 +
    level: Level,
9 +
    start: SystemTime,
10 +
}
11 +
12 +
impl Log for Logger {
13 +
    fn enabled(&self, metadata: &Metadata<'_>) -> bool {
14 +
        metadata.level() <= self.level
15 +
    }
16 +
17 +
    #[cfg(feature = "color-logging")]
18 +
    fn log(&self, record: &Record<'_>) {
19 +
        use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
20 +
21 +
        if self.enabled(record.metadata()) {
22 +
            if record.level() == Level::Error {
23 +
                write(
24 +
                    record,
25 +
                    StandardStream::stderr(ColorChoice::Always),
26 +
                    self.start,
27 +
                );
28 +
            } else {
29 +
                write(
30 +
                    record,
31 +
                    StandardStream::stdout(ColorChoice::Always),
32 +
                    self.start,
33 +
                );
34 +
            }
35 +
36 +
            fn write(record: &log::Record<'_>, mut stream: StandardStream, start: SystemTime) {
37 +
                // SAFETY: `start` is the start time, therefore should be in the past.
38 +
                #[allow(clippy::unwrap_used)]
39 +
                let now = SystemTime::now().duration_since(start).unwrap();
40 +
                let message = format!(
41 +
                    "{:5} {:012} {:6} {}",
42 +
                    record.level(),
43 +
                    now.as_millis(),
44 +
                    record.target(),
45 +
                    record.args()
46 +
                );
47 +
                match record.level() {
48 +
                    Level::Info => stream.set_color(ColorSpec::new().set_fg(Some(Color::Cyan))),
49 +
                    Level::Error => stream
50 +
                        .set_color(ColorSpec::new().set_fg(Some(Color::Red)).set_intense(true)),
51 +
                    Level::Warn => stream.set_color(ColorSpec::new().set_fg(Some(Color::Yellow))),
52 +
                    Level::Debug => stream.set_color(ColorSpec::new().set_fg(None)),
53 +
                    Level::Trace => stream
54 +
                        .set_color(ColorSpec::new().set_fg(Some(Color::White)).set_dimmed(true)),
55 +
                }
56 +
                .ok();
57 +
58 +
                writeln!(stream, "{message}").ok();
59 +
            }
60 +
        }
61 +
    }
62 +
63 +
    #[cfg(not(feature = "color-logging"))]
64 +
    fn log(&self, record: &Record<'_>) {
65 +
        use std::io;
66 +
67 +
        if self.enabled(record.metadata()) {
68 +
            if record.level() == Level::Error {
69 +
                write(record, io::stderr(), self.start);
70 +
            } else {
71 +
                write(record, io::stdout(), self.start);
72 +
            }
73 +
74 +
            fn write(record: &log::Record<'_>, mut stream: impl io::Write, start: SystemTime) {
75 +
                let now = SystemTime::now().duration_since(start).unwrap();
76 +
                let message = format!(
77 +
                    "{:5} {:012} {}",
78 +
                    record.level(),
79 +
                    now.as_millis(),
80 +
                    record.args()
81 +
                );
82 +
                writeln!(stream, "{message}").ok();
83 +
            }
84 +
        }
85 +
    }
86 +
87 +
    fn flush(&self) {}
88 +
}
89 +
90 +
/// Initialize a new logger.
91 +
pub fn init(level: Level) -> Result<(), SetLoggerError> {
92 +
    let logger = Logger {
93 +
        level,
94 +
        start: SystemTime::now(),
95 +
    };
96 +
    log::set_boxed_logger(Box::new(logger))?;
97 +
    log::set_max_level(level.to_level_filter());
98 +
99 +
    Ok(())
100 +
}
ombre/src/math.rs added +17 -0
1 +
//! Math-related functions and types.
2 +
pub mod algebra;
3 +
pub mod macros;
4 +
pub mod misc;
5 +
pub mod rect;
6 +
pub mod size;
7 +
pub mod traits;
8 +
pub mod transform;
9 +
10 +
pub use algebra::*;
11 +
pub use macros::*;
12 +
pub use misc::*;
13 +
pub use rect::*;
14 +
pub use size::*;
15 +
pub use traits::*;
16 +
pub use transform::coord::*;
17 +
pub use transform::*;
ombre/src/math/algebra.rs added +963 -0
1 +
// (c) 2013-2014 The CGMath Developers
2 +
// (c) 2012-2013 Mozilla Foundation
3 +
// (c) 2021-2022 Alexis Sellier
4 +
//
5 +
// Most of the code in this module was borrowed from the `cgmath` crate.
6 +
7 +
//! Linear algebra types and functions.
8 +
use std::fmt;
9 +
use std::marker::PhantomData;
10 +
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
11 +
12 +
use super::rect::Rect;
13 +
use super::size::Size;
14 +
use super::transform::{coord::Spherical, Transform2D};
15 +
use super::{traits::*, World};
16 +
17 +
/// View origin.
18 +
#[derive(PartialEq, Eq, Copy, Clone, Debug, Default)]
19 +
pub enum Origin {
20 +
    #[default]
21 +
    TopLeft,
22 +
    BottomLeft,
23 +
}
24 +
25 +
/// An N-dimensional vector.
26 +
#[repr(C)]
27 +
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
28 +
pub struct Vector<const N: usize, S = f32, Unit = ()> {
29 +
    /// Vector elements.
30 +
    elems: [S; N],
31 +
    #[doc(hidden)]
32 +
    unit: PhantomData<Unit>,
33 +
}
34 +
35 +
impl<const N: usize, S, U> Vector<N, S, U> {
36 +
    /// Dot product of two vectors.
37 +
    ///
38 +
    /// ```
39 +
    /// use ombre::math::*;
40 +
    ///
41 +
    /// let v1 = Vector::<4, i32, ()>::from([1, 3, -5, 4]);
42 +
    /// let v2 = Vector::<4, i32, ()>::from([4, -2, -1, 3]);
43 +
    ///
44 +
    /// assert_eq!(Vector::dot(v1, v2), 15);
45 +
    /// ```
46 +
    #[inline]
47 +
    pub fn dot(a: Self, b: Self) -> <S as Add>::Output
48 +
    where
49 +
        S: Mul<Output = S> + Add<Output = S> + Zero,
50 +
    {
51 +
        a.elems
52 +
            .into_iter()
53 +
            .zip(b.elems)
54 +
            .fold(S::ZERO, |acc, (a, b)| acc + a * b)
55 +
    }
56 +
}
57 +
58 +
impl<const N: usize, S, U> From<[S; N]> for Vector<N, S, U> {
59 +
    fn from(elems: [S; N]) -> Self {
60 +
        Self {
61 +
            elems,
62 +
            unit: PhantomData,
63 +
        }
64 +
    }
65 +
}
66 +
67 +
impl<const N: usize, S, U> Add<Vector<N, S, U>> for Vector<N, S, U>
68 +
where
69 +
    S: AddAssign<S> + Copy,
70 +
{
71 +
    type Output = Self;
72 +
73 +
    fn add(mut self, other: Vector<N, S, U>) -> Self {
74 +
        for i in 0..N {
75 +
            self.elems[i] += other.elems[i];
76 +
        }
77 +
        self
78 +
    }
79 +
}
80 +
81 +
impl<const N: usize, S, U> Sub<Vector<N, S, U>> for Vector<N, S, U>
82 +
where
83 +
    S: SubAssign<S> + Copy,
84 +
{
85 +
    type Output = Self;
86 +
87 +
    fn sub(mut self, other: Vector<N, S, U>) -> Self {
88 +
        for i in 0..N {
89 +
            self.elems[i] -= other.elems[i];
90 +
        }
91 +
        self
92 +
    }
93 +
}
94 +
95 +
impl<const N: usize, S, U> Mul<S> for Vector<N, S, U>
96 +
where
97 +
    S: MulAssign<S> + Copy,
98 +
{
99 +
    type Output = Self;
100 +
101 +
    fn mul(mut self, value: S) -> Self {
102 +
        for e in self.elems.iter_mut() {
103 +
            *e *= value;
104 +
        }
105 +
        self
106 +
    }
107 +
}
108 +
109 +
impl<const N: usize, S, U> Div<S> for Vector<N, S, U>
110 +
where
111 +
    S: DivAssign<S> + Copy,
112 +
{
113 +
    type Output = Self;
114 +
115 +
    fn div(mut self, value: S) -> Self {
116 +
        for e in self.elems.iter_mut() {
117 +
            *e /= value;
118 +
        }
119 +
        self
120 +
    }
121 +
}
122 +
123 +
/// 2D vector.
124 +
#[repr(C)]
125 +
#[derive(Debug, Hash, Default)]
126 +
pub struct Vector2D<S = f32, Unit = ()> {
127 +
    pub x: S,
128 +
    pub y: S,
129 +
    #[doc(hidden)]
130 +
    unit: PhantomData<Unit>,
131 +
}
132 +
133 +
impl<S: Copy, U> Copy for Vector2D<S, U> {}
134 +
135 +
impl<S: Clone, U> Clone for Vector2D<S, U> {
136 +
    fn clone(&self) -> Self {
137 +
        Vector2D {
138 +
            x: self.x.clone(),
139 +
            y: self.y.clone(),
140 +
            unit: PhantomData,
141 +
        }
142 +
    }
143 +
}
144 +
145 +
impl<S: PartialEq, U> PartialEq for Vector2D<S, U> {
146 +
    fn eq(&self, other: &Self) -> bool {
147 +
        self.x == other.x && self.y == other.y
148 +
    }
149 +
}
150 +
151 +
impl<S: Eq, U> Eq for Vector2D<S, U> {}
152 +
153 +
impl<T: ApproxEq + PartialOrd, U> ApproxEq for Vector2D<T, U> {
154 +
    type Epsilon = <T as ApproxEq>::Epsilon;
155 +
156 +
    fn approx_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
157 +
        self.x.approx_eq(&other.x, epsilon) && self.y.approx_eq(&other.y, epsilon)
158 +
    }
159 +
}
160 +
161 +
impl<S: Copy + PartialEq + Zero, U> Vector2D<S, U> {
162 +
    pub fn zero() -> Self {
163 +
        Self::ZERO
164 +
    }
165 +
}
166 +
167 +
impl<U> Vector2D<f32, U> {
168 +
    /// Returns the angle between two vectors, in radians.
169 +
    pub fn angle(&self, other: &Vector2D<f32>) -> f32 {
170 +
        (self.x - other.x).atan2(other.y - self.y)
171 +
    }
172 +
173 +
    pub fn transform<V>(self, t: impl Into<Transform2D<U, V>>) -> Vector2D<f32, V> {
174 +
        t.into() * self
175 +
    }
176 +
}
177 +
178 +
impl<S: Sized, U> Vector2D<S, U> {
179 +
    pub const fn new(x: S, y: S) -> Self {
180 +
        Vector2D {
181 +
            x,
182 +
            y,
183 +
            unit: PhantomData,
184 +
        }
185 +
    }
186 +
}
187 +
188 +
impl<S: Copy, U> Vector2D<S, U> {
189 +
    /// Creates a vector with all elements set to `v`.
190 +
    pub fn splat(n: S) -> Self {
191 +
        Self::new(n, n)
192 +
    }
193 +
194 +
    /// Returns a vector with the same direction and a given magnitude.
195 +
    #[inline]
196 +
    pub fn normalize(self) -> Self
197 +
    where
198 +
        S: One + Float + Div + Mul,
199 +
    {
200 +
        self * (S::ONE / self.magnitude())
201 +
    }
202 +
203 +
    /// Performs [`FloatExt::expand`] on the coordinates.
204 +
    #[inline]
205 +
    pub fn expand(self) -> Self
206 +
    where
207 +
        S: FloatExt<S>,
208 +
    {
209 +
        Self::new(self.x.expand(), self.y.expand())
210 +
    }
211 +
212 +
    /// The distance from the tail to the tip of the vector.
213 +
    #[inline]
214 +
    pub fn magnitude(self) -> S
215 +
    where
216 +
        S: Float,
217 +
    {
218 +
        Float::sqrt(Self::dot(self, self))
219 +
    }
220 +
221 +
    /// Dot product of two vectors.
222 +
    ///
223 +
    /// ```
224 +
    /// use ombre::math::*;
225 +
    ///
226 +
    /// let v1 = Vector4D::<i32, ()>::new(1, 3, -5, 4);
227 +
    /// let v2 = Vector4D::<i32, ()>::new(4, -2, -1, 3);
228 +
    ///
229 +
    /// assert_eq!(v1 * v2, 15);
230 +
    /// ```
231 +
    #[inline]
232 +
    pub fn dot(a: Self, b: Self) -> <S as Add>::Output
233 +
    where
234 +
        S: Mul<Output = S> + Add,
235 +
    {
236 +
        a.x * b.x + a.y * b.y
237 +
    }
238 +
239 +
    /// Distance between two vectors.
240 +
    #[inline]
241 +
    pub fn distance(self, other: Self) -> S
242 +
    where
243 +
        S: Float,
244 +
    {
245 +
        (other - self).magnitude()
246 +
    }
247 +
248 +
    /// Extend vector to three dimensions.
249 +
    pub fn extend(self, z: S) -> Vector3D<S, U> {
250 +
        Vector3D::new(self.x, self.y, z)
251 +
    }
252 +
253 +
    pub fn map<F, T>(self, mut f: F) -> Vector2D<T>
254 +
    where
255 +
        T: Copy,
256 +
        F: FnMut(S) -> T,
257 +
    {
258 +
        Vector2D::new(f(self.x), f(self.y))
259 +
    }
260 +
}
261 +
262 +
impl<S: Zero + Copy + PartialEq, U> Zero for Vector2D<S, U> {
263 +
    const ZERO: Self = Vector2D::new(S::ZERO, S::ZERO);
264 +
265 +
    #[inline]
266 +
    fn is_zero(&self) -> bool {
267 +
        self == &Vector2D::ZERO
268 +
    }
269 +
}
270 +
271 +
impl<S, T, U> From<[T; 2]> for Vector2D<S, U>
272 +
where
273 +
    T: Into<S>,
274 +
{
275 +
    #[inline]
276 +
    fn from([x, y]: [T; 2]) -> Self {
277 +
        Vector2D::new(x.into(), y.into())
278 +
    }
279 +
}
280 +
281 +
impl<S, T, U> From<(T, T)> for Vector2D<S, U>
282 +
where
283 +
    T: Into<S>,
284 +
{
285 +
    #[inline]
286 +
    fn from(tuple: (T, T)) -> Self {
287 +
        Vector2D::new(tuple.0.into(), tuple.1.into())
288 +
    }
289 +
}
290 +
291 +
impl<T> From<Vector2D<T>> for [T; 2] {
292 +
    fn from(vec: Vector2D<T>) -> Self {
293 +
        [vec.x, vec.y]
294 +
    }
295 +
}
296 +
297 +
impl<S: Copy, U> From<Vector3D<S, U>> for Vector2D<S, U> {
298 +
    #[inline]
299 +
    fn from(other: Vector3D<S, U>) -> Self {
300 +
        Vector2D::new(other.x, other.y)
301 +
    }
302 +
}
303 +
304 +
impl<S, U> Add for Vector2D<S, U>
305 +
where
306 +
    S: Add<Output = S>,
307 +
{
308 +
    type Output = Self;
309 +
310 +
    fn add(self, other: Vector2D<S, U>) -> Self {
311 +
        Self {
312 +
            x: self.x + other.x,
313 +
            y: self.y + other.y,
314 +
            unit: PhantomData,
315 +
        }
316 +
    }
317 +
}
318 +
319 +
impl<S, U> Sub<Vector2D<S, U>> for Vector2D<S, U>
320 +
where
321 +
    S: Sub<Output = S> + Copy,
322 +
{
323 +
    type Output = Self;
324 +
325 +
    fn sub(self, other: Vector2D<S, U>) -> Self {
326 +
        Self {
327 +
            x: self.x - other.x,
328 +
            y: self.y - other.y,
329 +
            unit: PhantomData,
330 +
        }
331 +
    }
332 +
}
333 +
334 +
impl<S, U> Mul<S> for Vector2D<S, U>
335 +
where
336 +
    S: Mul<Output = S> + Copy,
337 +
{
338 +
    type Output = Self;
339 +
340 +
    fn mul(self, s: S) -> Self {
341 +
        Self {
342 +
            x: self.x * s,
343 +
            y: self.y * s,
344 +
            unit: PhantomData,
345 +
        }
346 +
    }
347 +
}
348 +
349 +
impl<S, U> Div<S> for Vector2D<S, U>
350 +
where
351 +
    S: Div<Output = S> + Copy,
352 +
{
353 +
    type Output = Self;
354 +
355 +
    fn div(self, s: S) -> Self {
356 +
        Self {
357 +
            x: self.x / s,
358 +
            y: self.y / s,
359 +
            unit: PhantomData,
360 +
        }
361 +
    }
362 +
}
363 +
364 +
impl<S: Copy, U> From<Point2D<S, U>> for Vector2D<S, U> {
365 +
    fn from(p: Point2D<S, U>) -> Self {
366 +
        Self::new(p.x, p.y)
367 +
    }
368 +
}
369 +
370 +
impl<S: Copy, U> From<Size<S>> for Vector2D<S, U> {
371 +
    fn from(s: Size<S>) -> Self {
372 +
        Self::new(s.w, s.h)
373 +
    }
374 +
}
375 +
376 +
impl<S, U> fmt::Display for Vector2D<S, U>
377 +
where
378 +
    S: fmt::Display,
379 +
{
380 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381 +
        write!(f, "({}, {})", self.x, self.y)
382 +
    }
383 +
}
384 +
385 +
/// 3D vector.
386 +
#[repr(C)]
387 +
#[derive(Debug, Default)]
388 +
pub struct Vector3D<S = f32, U = ()> {
389 +
    pub x: S,
390 +
    pub y: S,
391 +
    pub z: S,
392 +
    pub unit: PhantomData<U>,
393 +
}
394 +
395 +
impl<S: Copy, U> Copy for Vector3D<S, U> {}
396 +
397 +
impl<S: Clone, U> Clone for Vector3D<S, U> {
398 +
    fn clone(&self) -> Self {
399 +
        Vector3D {
400 +
            x: self.x.clone(),
401 +
            y: self.y.clone(),
402 +
            z: self.z.clone(),
403 +
            unit: PhantomData,
404 +
        }
405 +
    }
406 +
}
407 +
408 +
impl<S, U> Vector3D<S, U> {
409 +
    #[inline]
410 +
    pub const fn new(x: S, y: S, z: S) -> Self {
411 +
        Vector3D {
412 +
            x,
413 +
            y,
414 +
            z,
415 +
            unit: PhantomData,
416 +
        }
417 +
    }
418 +
419 +
    /// Extend vector to four dimensions.
420 +
    pub fn extend(self, w: S) -> Vector4D<S, U> {
421 +
        Vector4D::new(self.x, self.y, self.z, w)
422 +
    }
423 +
424 +
    /// Dot product of two vectors.
425 +
    #[inline]
426 +
    pub fn dot(a: Self, b: Self) -> <S as Add>::Output
427 +
    where
428 +
        S: Mul<Output = S>,
429 +
        S: Add<Output = S>,
430 +
    {
431 +
        a.x * b.x + a.y * b.y + a.z * b.z
432 +
    }
433 +
434 +
    /// Vector cross product.
435 +
    #[inline]
436 +
    pub fn cross(a: Self, b: Self) -> Self
437 +
    where
438 +
        S: Mul<Output = S>,
439 +
        S: Sub<Output = S>,
440 +
        S: Copy,
441 +
    {
442 +
        Self::new(
443 +
            (a.y * b.z) - (a.z * b.y),
444 +
            (a.z * b.x) - (a.x * b.z),
445 +
            (a.x * b.y) - (a.y * b.x),
446 +
        )
447 +
    }
448 +
}
449 +
450 +
impl<S, U> fmt::Display for Vector3D<S, U>
451 +
where
452 +
    S: fmt::Display,
453 +
{
454 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
455 +
        write!(f, "{{{}, {}, {}}}", self.x, self.y, self.z)
456 +
    }
457 +
}
458 +
459 +
impl<S: PartialEq, U> PartialEq for Vector3D<S, U> {
460 +
    fn eq(&self, other: &Self) -> bool {
461 +
        self.x == other.x && self.y == other.y && self.z == other.z
462 +
    }
463 +
}
464 +
465 +
impl<S: Eq, U> Eq for Vector3D<S, U> {}
466 +
467 +
impl<S: Zero + PartialEq, U: PartialEq> Vector3D<S, U> {
468 +
    pub const fn zero() -> Self {
469 +
        Self::ZERO
470 +
    }
471 +
}
472 +
473 +
impl<S: Copy, U> Vector3D<S, U> {
474 +
    /// The distance from the tail to the tip of the vector.
475 +
    #[inline]
476 +
    pub fn magnitude(self) -> S
477 +
    where
478 +
        S: Float,
479 +
    {
480 +
        Float::sqrt(Self::dot(self, self))
481 +
    }
482 +
483 +
    /// Returns a vector with the same direction and a given magnitude.
484 +
    #[inline]
485 +
    pub fn normalize(self) -> Self
486 +
    where
487 +
        S: One + Float + Div + Mul,
488 +
    {
489 +
        self * (S::ONE / self.magnitude())
490 +
    }
491 +
}
492 +
493 +
impl<S: Copy> Vector3D<S, Spherical> {
494 +
    /// Radius or 'r'.
495 +
    pub const fn radius(&self) -> S {
496 +
        self.x
497 +
    }
498 +
499 +
    /// Theta or azimuth.
500 +
    pub const fn theta(&self) -> S {
501 +
        self.y
502 +
    }
503 +
504 +
    /// Phi or polar angle.
505 +
    pub const fn phi(&self) -> S {
506 +
        self.z
507 +
    }
508 +
}
509 +
510 +
impl Vector3D<f32, Spherical> {
511 +
    pub fn to_world(self) -> Vector3D<f32, World> {
512 +
        Vector3D::new(
513 +
            self.radius() * self.phi().sin() * self.theta().cos(),
514 +
            self.radius() * self.phi().cos(),
515 +
            self.radius() * self.phi().sin() * self.theta().sin(),
516 +
        )
517 +
    }
518 +
}
519 +
520 +
impl Vector3D<f32, World> {
521 +
    pub fn to_spherical(self, center: Vector3D<f32, World>) -> Vector3D<f32, Spherical> {
522 +
        let delta = self - center;
523 +
        let radius = delta.magnitude();
524 +
        let theta = delta.z.atan2(delta.x); // Azimuth
525 +
        let phi = (delta.y / radius).clamp(-1., 1.).acos(); // Polar angle
526 +
527 +
        Vector3D::<_, Spherical>::new(radius, theta, phi)
528 +
    }
529 +
}
530 +
531 +
impl<T: ApproxEq + PartialOrd, U> ApproxEq for Vector3D<T, U> {
532 +
    type Epsilon = <T as ApproxEq>::Epsilon;
533 +
534 +
    fn approx_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
535 +
        self.x.approx_eq(&other.x, epsilon)
536 +
            && self.y.approx_eq(&other.y, epsilon)
537 +
            && self.z.approx_eq(&other.z, epsilon)
538 +
    }
539 +
}
540 +
541 +
impl From<Vector3D<f32, Spherical>> for Vector3D<f32, World> {
542 +
    fn from(s: Vector3D<f32, Spherical>) -> Self {
543 +
        s.to_world()
544 +
    }
545 +
}
546 +
547 +
impl<S: Zero + PartialEq, U> Zero for Vector3D<S, U> {
548 +
    const ZERO: Self = Vector3D::new(S::ZERO, S::ZERO, S::ZERO);
549 +
550 +
    fn is_zero(&self) -> bool {
551 +
        self == &Self::ZERO
552 +
    }
553 +
}
554 +
555 +
impl<S: Copy + Zero, U> From<Vector2D<S, U>> for Vector3D<S, U> {
556 +
    fn from(other: Vector2D<S, U>) -> Self {
557 +
        other.extend(S::ZERO)
558 +
    }
559 +
}
560 +
561 +
impl<T: Copy> From<[T; 3]> for Vector3D<T> {
562 +
    #[inline]
563 +
    fn from(array: [T; 3]) -> Self {
564 +
        Vector3D::new(array[0], array[1], array[2])
565 +
    }
566 +
}
567 +
568 +
impl<S, U> Add<Vector3D<S, U>> for Vector3D<S, U>
569 +
where
570 +
    S: Add<Output = S> + Copy,
571 +
{
572 +
    type Output = Self;
573 +
574 +
    fn add(self, other: Vector3D<S, U>) -> Self {
575 +
        Self {
576 +
            x: self.x + other.x,
577 +
            y: self.y + other.y,
578 +
            z: self.z + other.z,
579 +
            unit: PhantomData,
580 +
        }
581 +
    }
582 +
}
583 +
584 +
impl<S, U> Sub<Vector3D<S, U>> for Vector3D<S, U>
585 +
where
586 +
    S: Sub<Output = S> + Copy,
587 +
{
588 +
    type Output = Self;
589 +
590 +
    fn sub(self, other: Vector3D<S, U>) -> Self {
591 +
        Self {
592 +
            x: self.x - other.x,
593 +
            y: self.y - other.y,
594 +
            z: self.z - other.z,
595 +
            unit: PhantomData,
596 +
        }
597 +
    }
598 +
}
599 +
600 +
impl<S, U> Mul<S> for Vector3D<S, U>
601 +
where
602 +
    S: Mul<Output = S> + Copy,
603 +
{
604 +
    type Output = Self;
605 +
606 +
    fn mul(self, s: S) -> Self {
607 +
        Self {
608 +
            x: self.x * s,
609 +
            y: self.y * s,
610 +
            z: self.z * s,
611 +
            unit: PhantomData,
612 +
        }
613 +
    }
614 +
}
615 +
616 +
/// 4D vector.
617 +
#[repr(C)]
618 +
#[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, Default)]
619 +
pub struct Vector4D<S = f32, U = ()> {
620 +
    pub x: S,
621 +
    pub y: S,
622 +
    pub z: S,
623 +
    pub w: S,
624 +
625 +
    unit: PhantomData<U>,
626 +
}
627 +
628 +
impl From<Vector4D<f32>> for [f32; 4] {
629 +
    fn from(mat: Vector4D<f32>) -> Self {
630 +
        unsafe { std::mem::transmute(mat) }
631 +
    }
632 +
}
633 +
634 +
impl<T: Copy> From<[T; 4]> for Vector4D<T> {
635 +
    #[inline]
636 +
    fn from(array: [T; 4]) -> Self {
637 +
        Vector4D::new(array[0], array[1], array[2], array[3])
638 +
    }
639 +
}
640 +
641 +
impl<S, U> Vector4D<S, U> {
642 +
    #[inline]
643 +
    pub const fn new(x: S, y: S, z: S, w: S) -> Self {
644 +
        Vector4D {
645 +
            x,
646 +
            y,
647 +
            z,
648 +
            w,
649 +
            unit: PhantomData,
650 +
        }
651 +
    }
652 +
}
653 +
654 +
impl<S, U> Mul<S> for Vector4D<S, U>
655 +
where
656 +
    S: Mul<Output = S> + Copy,
657 +
{
658 +
    type Output = Self;
659 +
660 +
    fn mul(self, s: S) -> Self {
661 +
        Self {
662 +
            x: self.x * s,
663 +
            y: self.y * s,
664 +
            z: self.z * s,
665 +
            w: self.w * s,
666 +
            unit: PhantomData,
667 +
        }
668 +
    }
669 +
}
670 +
671 +
impl<S, U> Mul<Vector4D<S, U>> for Vector4D<S, U>
672 +
where
673 +
    S: Mul<Output = S> + Add<Output = S> + Copy,
674 +
{
675 +
    type Output = S;
676 +
677 +
    fn mul(self, other: Vector4D<S, U>) -> S {
678 +
        other.x * self.x + other.y * self.y + other.z * self.z + other.w * self.w
679 +
    }
680 +
}
681 +
682 +
impl<S, U> Add<Vector4D<S, U>> for Vector4D<S, U>
683 +
where
684 +
    S: Add<Output = S>,
685 +
{
686 +
    type Output = Self;
687 +
688 +
    fn add(self, other: Vector4D<S, U>) -> Self {
689 +
        Self {
690 +
            x: self.x + other.x,
691 +
            y: self.y + other.y,
692 +
            z: self.z + other.z,
693 +
            w: self.w + other.w,
694 +
            unit: PhantomData,
695 +
        }
696 +
    }
697 +
}
698 +
699 +
impl<S, U> Sub<Vector4D<S, U>> for Vector4D<S, U>
700 +
where
701 +
    S: Sub<Output = S> + Copy,
702 +
{
703 +
    type Output = Self;
704 +
705 +
    fn sub(self, other: Vector4D<S, U>) -> Self {
706 +
        Self {
707 +
            x: self.x - other.x,
708 +
            y: self.y - other.y,
709 +
            z: self.z - other.z,
710 +
            w: self.w - other.w,
711 +
            unit: PhantomData,
712 +
        }
713 +
    }
714 +
}
715 +
716 +
impl From<Vector3D<f32>> for Vector4D<f32> {
717 +
    fn from(other: Vector3D<f32>) -> Self {
718 +
        other.extend(1.)
719 +
    }
720 +
}
721 +
722 +
impl From<Vector2D<f32>> for Vector4D<f32> {
723 +
    fn from(other: Vector2D<f32>) -> Self {
724 +
        other.extend(0.).extend(1.)
725 +
    }
726 +
}
727 +
728 +
impl From<Point2D<f32>> for Vector4D<f32> {
729 +
    fn from(other: Point2D<f32>) -> Self {
730 +
        Self::new(other.x, other.y, 0., 1.)
731 +
    }
732 +
}
733 +
734 +
/// 2D point.
735 +
#[repr(C)]
736 +
#[derive(Debug, Default)]
737 +
pub struct Point2D<S = f32, U = ()> {
738 +
    pub x: S,
739 +
    pub y: S,
740 +
741 +
    unit: PhantomData<U>,
742 +
}
743 +
744 +
impl<S: Copy, U> Copy for Point2D<S, U> {}
745 +
746 +
impl<S: Clone, U> Clone for Point2D<S, U> {
747 +
    fn clone(&self) -> Self {
748 +
        Point2D {
749 +
            x: self.x.clone(),
750 +
            y: self.y.clone(),
751 +
            unit: PhantomData,
752 +
        }
753 +
    }
754 +
}
755 +
756 +
impl<S, U> fmt::Display for Point2D<S, U>
757 +
where
758 +
    S: fmt::Display,
759 +
{
760 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
761 +
        write!(f, "{{{}, {}}}", self.x, self.y)
762 +
    }
763 +
}
764 +
765 +
impl<T: Zero + PartialEq, U> Point2D<T, U> {
766 +
    pub const ORIGIN: Self = Point2D::ZERO;
767 +
}
768 +
769 +
impl<S: PartialEq, U> PartialEq for Point2D<S, U> {
770 +
    fn eq(&self, other: &Self) -> bool {
771 +
        self.x == other.x && self.y == other.y
772 +
    }
773 +
}
774 +
775 +
impl<S: Eq, U> Eq for Point2D<S, U> {}
776 +
777 +
impl<S, U> Point2D<S, U> {
778 +
    pub const fn new(x: S, y: S) -> Self {
779 +
        Point2D {
780 +
            x,
781 +
            y,
782 +
            unit: PhantomData,
783 +
        }
784 +
    }
785 +
786 +
    pub fn map<F, T>(self, mut f: F) -> Point2D<T, U>
787 +
    where
788 +
        F: FnMut(S) -> T,
789 +
    {
790 +
        Point2D::new(f(self.x), f(self.y))
791 +
    }
792 +
793 +
    pub fn convert<V>(self) -> Point2D<S, V> {
794 +
        Point2D {
795 +
            x: self.x,
796 +
            y: self.y,
797 +
            unit: PhantomData,
798 +
        }
799 +
    }
800 +
}
801 +
802 +
impl Point2D<i32> {
803 +
    pub fn clamp(&mut self, rect: Rect<i32>) {
804 +
        if self.x < rect.min().x {
805 +
            self.x = rect.min().x;
806 +
        }
807 +
        if self.y < rect.min().y {
808 +
            self.y = rect.min().y;
809 +
        }
810 +
        if self.x > rect.max().x {
811 +
            self.x = rect.max().x;
812 +
        }
813 +
        if self.y > rect.max().y {
814 +
            self.y = rect.max().y;
815 +
        }
816 +
    }
817 +
}
818 +
819 +
impl<U> Point2D<f32, U> {
820 +
    pub fn transform<V>(self, t: impl Into<Transform2D<U, V>>) -> Point2D<f32, V> {
821 +
        t.into() * self
822 +
    }
823 +
}
824 +
825 +
impl<T: Zero + PartialEq, U> Zero for Point2D<T, U> {
826 +
    const ZERO: Self = Point2D::new(T::ZERO, T::ZERO);
827 +
828 +
    fn is_zero(&self) -> bool {
829 +
        self == &Self::ZERO
830 +
    }
831 +
}
832 +
833 +
impl<T: Copy, U> From<[T; 2]> for Point2D<T, U> {
834 +
    #[inline]
835 +
    fn from(array: [T; 2]) -> Self {
836 +
        Point2D::new(array[0], array[1])
837 +
    }
838 +
}
839 +
840 +
impl<T: Copy, C> From<(T, T)> for Point2D<T, C> {
841 +
    #[inline]
842 +
    fn from((x, y): (T, T)) -> Self {
843 +
        Point2D::new(x, y)
844 +
    }
845 +
}
846 +
847 +
impl From<Point2D<f64>> for Point2D<f32> {
848 +
    #[inline]
849 +
    fn from(other: Point2D<f64>) -> Self {
850 +
        Point2D::new(other.x as f32, other.y as f32)
851 +
    }
852 +
}
853 +
854 +
impl From<Point2D<f32>> for Point2D<i32> {
855 +
    #[inline]
856 +
    fn from(other: Point2D<f32>) -> Self {
857 +
        Point2D::new(other.x as i32, other.y as i32)
858 +
    }
859 +
}
860 +
861 +
impl<S, U> From<Vector2D<S, U>> for Point2D<S, U> {
862 +
    fn from(v: Vector2D<S, U>) -> Self {
863 +
        Self::new(v.x, v.y)
864 +
    }
865 +
}
866 +
867 +
impl<S, U> Div<S> for Point2D<S, U>
868 +
where
869 +
    S: Div<Output = S> + Copy,
870 +
{
871 +
    type Output = Self;
872 +
873 +
    fn div(self, s: S) -> Self {
874 +
        Self {
875 +
            x: self.x / s,
876 +
            y: self.y / s,
877 +
            unit: PhantomData,
878 +
        }
879 +
    }
880 +
}
881 +
882 +
impl<S, U> Mul<S> for Point2D<S, U>
883 +
where
884 +
    S: Mul<Output = S> + Copy,
885 +
{
886 +
    type Output = Self;
887 +
888 +
    fn mul(self, s: S) -> Self {
889 +
        Self {
890 +
            x: self.x * s,
891 +
            y: self.y * s,
892 +
            unit: PhantomData,
893 +
        }
894 +
    }
895 +
}
896 +
897 +
impl<S, T, U> Add<T> for Point2D<S, U>
898 +
where
899 +
    S: Add<Output = S> + Copy,
900 +
    T: Into<Vector2D<S, U>>,
901 +
{
902 +
    type Output = Self;
903 +
904 +
    fn add(self, other: T) -> Self {
905 +
        let other: Vector2D<S, U> = other.into();
906 +
907 +
        Self {
908 +
            x: self.x + other.x,
909 +
            y: self.y + other.y,
910 +
            unit: PhantomData,
911 +
        }
912 +
    }
913 +
}
914 +
915 +
impl<S, U> Sub<Vector2D<S, U>> for Point2D<S, U>
916 +
where
917 +
    S: Sub<Output = S> + Copy,
918 +
{
919 +
    type Output = Self;
920 +
921 +
    fn sub(self, other: Vector2D<S, U>) -> Self {
922 +
        Self {
923 +
            x: self.x - other.x,
924 +
            y: self.y - other.y,
925 +
            unit: PhantomData,
926 +
        }
927 +
    }
928 +
}
929 +
930 +
impl<S, U> Sub<Point2D<S, U>> for Point2D<S, U>
931 +
where
932 +
    S: Sub<Output = S> + Copy,
933 +
{
934 +
    type Output = Vector2D<S, U>;
935 +
936 +
    fn sub(self, other: Point2D<S, U>) -> Vector2D<S, U> {
937 +
        Vector2D {
938 +
            x: self.x - other.x,
939 +
            y: self.y - other.y,
940 +
            unit: PhantomData,
941 +
        }
942 +
    }
943 +
}
944 +
945 +
#[cfg(test)]
946 +
mod test {
947 +
    use super::*;
948 +
    use crate::math::assert_approx_eq;
949 +
950 +
    #[test]
951 +
    fn test_spherical_coordinates() {
952 +
        let world = Vector3D::<f32, World>::new(12., 19., 64.);
953 +
        let spherical = world.to_spherical(Vector3D::zero());
954 +
955 +
        assert_approx_eq!(spherical.to_world(), world, 0.00001);
956 +
957 +
        let world = Vector3D::<f32, World>::new(12., 19., 64.);
958 +
        let center = Vector3D::new(3., 7., 1.);
959 +
        let spherical = world.to_spherical(center);
960 +
961 +
        assert_approx_eq!(spherical.to_world() + center, world, 0.00001);
962 +
    }
963 +
}
ombre/src/math/macros.rs added +33 -0
1 +
//! Some useful macros.
2 +
3 +
/// Assertion macro for [`crate::math::traits::ApproxEq::approx_eq`].
4 +
#[macro_export]
5 +
macro_rules! assert_approx_eq {
6 +
    ($a:expr, $b:expr, $epsilon:expr) => {{
7 +
        let (a, b, eps) = ($a, $b, $epsilon);
8 +
        assert!(
9 +
            $crate::math::traits::ApproxEq::approx_eq(&a, &b, eps),
10 +
            "\
11 +
assertion `|left - right| <= {eps}` failed
12 +
  left: {a}
13 +
 right: {b}"
14 +
        );
15 +
    }};
16 +
}
17 +
pub use assert_approx_eq;
18 +
19 +
/// Assertion macro for [`crate::math::traits::ApproxEq::approx_neq`].
20 +
#[macro_export]
21 +
macro_rules! assert_approx_neq {
22 +
    ($a:expr, $b:expr, $epsilon:expr) => {{
23 +
        let (a, b, eps) = ($a, $b, $epsilon);
24 +
        assert!(
25 +
            $crate::math::traits::ApproxEq::approx_neq(&a, &b, eps),
26 +
            "\
27 +
assertion `|left - right| > {eps}` failed
28 +
  left: {a}
29 +
 right: {b}"
30 +
        );
31 +
    }};
32 +
}
33 +
pub use assert_approx_neq;
ombre/src/math/misc.rs added +61 -0
1 +
//! Miscellaneous math types.
2 +
3 +
/// Some axis.
4 +
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
5 +
pub enum Axis {
6 +
    /// X-axis.
7 +
    Horizontal,
8 +
    /// Y-axis.
9 +
    Vertical,
10 +
}
11 +
12 +
/// Texture repeat.
13 +
#[derive(PartialEq, Clone, Debug)]
14 +
pub struct Repeat {
15 +
    /// Horizontal repeat.
16 +
    pub x: f32,
17 +
    /// Vertical repeat.
18 +
    pub y: f32,
19 +
}
20 +
21 +
impl Repeat {
22 +
    /// Create a new [`Repeat`].
23 +
    pub fn new(x: f32, y: f32) -> Self {
24 +
        Repeat { x, y }
25 +
    }
26 +
}
27 +
28 +
impl Default for Repeat {
29 +
    fn default() -> Self {
30 +
        Repeat { x: 1.0, y: 1.0 }
31 +
    }
32 +
}
33 +
34 +
/// Z-Depth.
35 +
#[derive(Clone, Copy, PartialEq, PartialOrd, Debug)]
36 +
pub struct ZDepth(f32);
37 +
38 +
impl ZDepth {
39 +
    /// ZDepth of zero.
40 +
    pub const ZERO: Self = ZDepth(0.0);
41 +
}
42 +
43 +
impl From<f32> for ZDepth {
44 +
    fn from(other: f32) -> Self {
45 +
        ZDepth(other)
46 +
    }
47 +
}
48 +
49 +
impl Default for ZDepth {
50 +
    fn default() -> Self {
51 +
        Self::ZERO
52 +
    }
53 +
}
54 +
55 +
impl std::ops::Deref for ZDepth {
56 +
    type Target = f32;
57 +
58 +
    fn deref(&self) -> &Self::Target {
59 +
        &self.0
60 +
    }
61 +
}
ombre/src/math/rect.rs added +456 -0
1 +
//! Rectangle-like types.
2 +
use std::fmt;
3 +
use std::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
4 +
5 +
use crate::math;
6 +
use crate::math::{Point2D, Size, Transform2D, Vector2D, Zero};
7 +
8 +
use super::Float;
9 +
10 +
/// Alias for a visual region.
11 +
pub type Region = Rect<f32>;
12 +
13 +
/// A generic rectangle with an origin and size.
14 +
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
15 +
pub struct Rect<T, U = ()> {
16 +
    /// Rectangle origin.
17 +
    pub origin: Point2D<T, U>,
18 +
    /// Rectangle size.
19 +
    pub size: Size<T>,
20 +
}
21 +
22 +
impl<T, U> fmt::Display for Rect<T, U>
23 +
where
24 +
    T: fmt::Display,
25 +
{
26 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27 +
        write!(f, "[{}, {}]", self.origin, self.size)
28 +
    }
29 +
}
30 +
31 +
impl<T: Copy, U> Rect<T, U> {
32 +
    /// Create a new rectangle.
33 +
    pub fn new(origin: impl Into<Point2D<T, U>>, size: impl Into<Size<T>>) -> Self {
34 +
        Self {
35 +
            origin: origin.into(),
36 +
            size: size.into(),
37 +
        }
38 +
    }
39 +
40 +
    /// Create a rectangle from a bottom-left and top-right point.
41 +
    pub fn points(min: impl Into<Point2D<T, U>>, max: impl Into<Point2D<T, U>>) -> Self
42 +
    where
43 +
        T: Sub<Output = T>,
44 +
    {
45 +
        let min = min.into();
46 +
        let max = max.into();
47 +
48 +
        Self {
49 +
            origin: min,
50 +
            size: Size::from(max - min),
51 +
        }
52 +
    }
53 +
54 +
    /// Map the origin and size of a rectangle.
55 +
    pub fn map<S, F>(self, f: F) -> Rect<S>
56 +
    where
57 +
        F: Fn(T) -> S,
58 +
    {
59 +
        Rect {
60 +
            origin: Point2D::new(f(self.origin.x), f(self.origin.y)),
61 +
            size: Size::new(f(self.size.w), f(self.size.h)),
62 +
        }
63 +
    }
64 +
}
65 +
66 +
impl<T: Copy + std::fmt::Display + Sub<Output = T> + Add<Output = T> + Neg<Output = T>, U>
67 +
    Rect<T, U>
68 +
{
69 +
    /// Inset a rectangle's area.
70 +
    pub fn inset(&self, inset: impl Into<Vector2D<T>>) -> Self {
71 +
        let inset = inset.into();
72 +
73 +
        self.expand(inset.x.neg(), inset.y.neg())
74 +
    }
75 +
76 +
    /// Expand a rectangle's area.
77 +
    pub fn expand(&self, x: T, y: T) -> Self
78 +
    where
79 +
        T: Add<Output = T> + Sub<Output = T>,
80 +
    {
81 +
        let offset = Vector2D::<_, U>::new(x, y);
82 +
83 +
        Self {
84 +
            origin: self.origin - offset,
85 +
            size: Size::new(self.size.w + x + x, self.size.h + y + y),
86 +
        }
87 +
    }
88 +
}
89 +
90 +
impl<U> Rect<f32, U> {
91 +
    pub fn transform<V>(self, t: Transform2D<U, V>) -> Rect<f32, V> {
92 +
        Rect {
93 +
            origin: t * self.origin,
94 +
            size: self.size,
95 +
        }
96 +
    }
97 +
}
98 +
99 +
impl<T: Zero> Zero for Rect<T> {
100 +
    const ZERO: Self = Self {
101 +
        origin: Point2D::ZERO,
102 +
        size: Size::ZERO,
103 +
    };
104 +
105 +
    fn is_zero(&self) -> bool {
106 +
        self == &Self::ZERO
107 +
    }
108 +
}
109 +
110 +
impl<T: Copy, U> Rect<T, U> {
111 +
    /// Create a rectangle with a zero origin.
112 +
    pub fn origin(size: impl Into<Size<T>>) -> Self
113 +
    where
114 +
        T: math::Zero,
115 +
    {
116 +
        Self::new(Point2D::ORIGIN, size.into())
117 +
    }
118 +
119 +
    /// Create a rectangle centered on the given point.
120 +
    pub fn centered(center: impl Into<Point2D<T, U>>, size: impl Into<Size<T>>) -> Self
121 +
    where
122 +
        T: Float + Div,
123 +
    {
124 +
        let center = center.into();
125 +
        let size = size.into();
126 +
127 +
        Self {
128 +
            origin: Point2D::new(center.x - size.w / T::TWO, center.y - size.h / T::TWO),
129 +
            size,
130 +
        }
131 +
    }
132 +
133 +
    /// Scale a rectangle's size.
134 +
    pub fn scale(&self, s: T) -> Self
135 +
    where
136 +
        T: Mul<Output = T> + Copy,
137 +
    {
138 +
        Self {
139 +
            origin: self.origin,
140 +
            size: self.size * s,
141 +
        }
142 +
    }
143 +
144 +
    /// Return the rectangle with a different origin.
145 +
    ///
146 +
    /// # Examples
147 +
    ///
148 +
    /// ```
149 +
    /// use ombre::math::Rect;
150 +
    ///
151 +
    /// let r = Rect::<_, ()>::new([1, 1], [4, 4]);
152 +
    /// assert_eq!(r.with_origin([0, 0]), Rect::new([0, 0], [4, 4]));
153 +
    /// ```
154 +
    pub fn with_origin(&self, origin: impl Into<Point2D<T, U>>) -> Self
155 +
    where
156 +
        T: Add<Output = T> + Sub<Output = T> + Copy,
157 +
    {
158 +
        Self {
159 +
            origin: origin.into(),
160 +
            size: self.size,
161 +
        }
162 +
    }
163 +
164 +
    /// Return the rectangle with a different size.
165 +
    ///
166 +
    /// # Examples
167 +
    ///
168 +
    /// ```
169 +
    /// use ombre::math::Rect;
170 +
    ///
171 +
    /// let r = Rect::<_, ()>::new([1, 1], [4, 4]);
172 +
    /// assert_eq!(r.with_size([9, 9]), Rect::new([1, 1], [9, 9]));
173 +
    /// ```
174 +
    pub fn with_size(&self, size: impl Into<Size<T>>) -> Self
175 +
    where
176 +
        T: Add<Output = T> + Sub<Output = T> + Copy,
177 +
    {
178 +
        Self {
179 +
            origin: self.origin,
180 +
            size: size.into(),
181 +
        }
182 +
    }
183 +
184 +
    /// Return the area of a rectangle.
185 +
    pub fn area(&self) -> T
186 +
    where
187 +
        T: Copy + Sub<Output = T> + std::cmp::PartialOrd + Mul<Output = T>,
188 +
    {
189 +
        self.width() * self.height()
190 +
    }
191 +
192 +
    /// Check whether the rectangle has a zero size.
193 +
    pub fn is_empty(&self) -> bool
194 +
    where
195 +
        T: Zero,
196 +
    {
197 +
        self.size.is_zero()
198 +
    }
199 +
200 +
    /// Check whether the rectangle has a zero size and its origin is zero.
201 +
    pub fn is_zero(&self) -> bool
202 +
    where
203 +
        T: math::Zero,
204 +
    {
205 +
        self.origin.is_zero() && self.size.is_zero()
206 +
    }
207 +
208 +
    /// Return the width of the rectangle.
209 +
    ///
210 +
    /// # Examples
211 +
    ///
212 +
    /// ```
213 +
    /// use ombre::math::Rect;
214 +
    ///
215 +
    /// let r = Rect::<_, ()>::new([0, 0], [3, 3]);
216 +
    /// assert_eq!(r.width(), 3);
217 +
    /// ```
218 +
    pub fn width(&self) -> T {
219 +
        self.size.w
220 +
    }
221 +
222 +
    /// Return the height of the rectangle.
223 +
    ///
224 +
    /// # Examples
225 +
    ///
226 +
    /// ```
227 +
    /// use ombre::math::Rect;
228 +
    ///
229 +
    /// let r: Rect<u64> = Rect::<_, ()>::origin([6, 6]);
230 +
    /// assert_eq!(r.height(), 6);
231 +
    /// ```
232 +
    pub fn height(&self) -> T {
233 +
        self.size.h
234 +
    }
235 +
236 +
    /// Return the center of the rectangle.
237 +
    ///
238 +
    /// # Examples
239 +
    ///
240 +
    /// ```
241 +
    /// use ombre::math::Rect;
242 +
    /// use ombre::math::Point2D;
243 +
    ///
244 +
    /// let r = Rect::<_, ()>::origin([8, 8]);
245 +
    /// assert_eq!(r.center(), Point2D::new(4, 4));
246 +
    ///
247 +
    /// let r = Rect::<_, ()>::new([0, 0], [-8, -8]);
248 +
    /// assert_eq!(r.center(), Point2D::new(-4, -4));
249 +
    /// ```
250 +
    pub fn center(&self) -> Point2D<T>
251 +
    where
252 +
        T: math::Two + Div<Output = T> + Add<Output = T>,
253 +
    {
254 +
        Point2D::new(
255 +
            self.origin.x + self.width() / T::TWO,
256 +
            self.origin.y + self.height() / T::TWO,
257 +
        )
258 +
    }
259 +
260 +
    /// Return the radius of the rectangle.
261 +
    pub fn radius(&self) -> T
262 +
    where
263 +
        T: math::Two + Div<Output = T> + PartialOrd + Sub<Output = T>,
264 +
    {
265 +
        let w = self.width();
266 +
        let h = self.height();
267 +
268 +
        if w > h {
269 +
            w / T::TWO
270 +
        } else {
271 +
            h / T::TWO
272 +
        }
273 +
    }
274 +
275 +
    /// Check whether the given point is contained in the rectangle.
276 +
    ///
277 +
    /// ```
278 +
    /// use ombre::math::{Point2D, Rect};
279 +
    ///
280 +
    /// let r = Rect::<_, ()>::origin([6, 6]);
281 +
    /// assert!(r.contains([0, 0]));
282 +
    /// assert!(r.contains([3, 3]));
283 +
    /// assert!(!r.contains([6, 6]));
284 +
    ///
285 +
    /// let r = Rect::<_, ()>::new([-6, -6], [6, 6]);
286 +
    /// assert!(r.contains([-3, -3]));
287 +
    /// ```
288 +
    pub fn contains(&self, point: impl Into<Point2D<T, U>>) -> bool
289 +
    where
290 +
        T: PartialOrd + Add<Output = T>,
291 +
    {
292 +
        let min = self.min();
293 +
        let max = self.max();
294 +
        let p = point.into();
295 +
296 +
        p.x >= min.x && p.x < max.x && p.y >= min.y && p.y < max.y
297 +
    }
298 +
299 +
    /// Get the minimum point.
300 +
    #[inline]
301 +
    pub fn min(&self) -> Point2D<T, U> {
302 +
        self.origin
303 +
    }
304 +
305 +
    /// Get the maximum point.
306 +
    #[inline]
307 +
    pub fn max(&self) -> Point2D<T, U>
308 +
    where
309 +
        T: Add<Output = T>,
310 +
    {
311 +
        self.origin + self.size
312 +
    }
313 +
314 +
    /// Check whether this rectangle intersects with another.
315 +
    pub fn intersects(&self, other: Rect<T>) -> bool
316 +
    where
317 +
        T: PartialOrd + Add<Output = T>,
318 +
    {
319 +
        self.max().y > other.origin.y
320 +
            && self.origin.y < other.max().y
321 +
            && self.origin.x < other.max().x
322 +
            && self.max().x > other.origin.x
323 +
    }
324 +
325 +
    /// Return the intersection between two rectangles.
326 +
    ///
327 +
    /// # Examples
328 +
    ///
329 +
    /// ```
330 +
    /// use ombre::math::Rect;
331 +
    ///
332 +
    /// let other = Rect::<_, ()>::points([0, 0], [3, 3]);
333 +
    ///
334 +
    /// let r = Rect::points([1, 1], [6, 6]);
335 +
    /// assert_eq!(r.intersection(other), Some(Rect::points([1, 1], [3, 3])));
336 +
    ///
337 +
    /// let r = Rect::points([1, 1], [2, 2]);
338 +
    /// assert_eq!(r.intersection(other), Some(Rect::points([1, 1], [2, 2])));
339 +
    ///
340 +
    /// let r = Rect::points([-1, -1], [3, 3]);
341 +
    /// assert_eq!(r.intersection(other), Some(Rect::points([0, 0], [3, 3])));
342 +
    ///
343 +
    /// let r = Rect::points([-1, -1], [4, 4]);
344 +
    /// assert_eq!(r.intersection(other), Some(other));
345 +
    ///
346 +
    /// let r = Rect::points([4, 4], [5, 5]);
347 +
    /// assert_eq!(r.intersection(other), None);
348 +
    /// assert_eq!(other.intersection(r), None);
349 +
    /// ```
350 +
    pub fn intersection(&self, other: Rect<T, U>) -> Option<Self>
351 +
    where
352 +
        T: Ord + Add<Output = T> + Sub<Output = T>,
353 +
    {
354 +
        let x1 = T::max(self.origin.x, other.origin.x);
355 +
        let y1 = T::max(self.origin.y, other.origin.y);
356 +
        let x2 = T::min(self.max().x, other.max().x);
357 +
        let y2 = T::min(self.max().y, other.max().y);
358 +
359 +
        if x2 < x1 || y2 < y1 {
360 +
            None
361 +
        } else {
362 +
            Some(Rect::points(Point2D::new(x1, y1), Point2D::new(x2, y2)))
363 +
        }
364 +
    }
365 +
}
366 +
367 +
impl<T> Mul<T> for Rect<T>
368 +
where
369 +
    T: Mul<Output = T> + Copy,
370 +
{
371 +
    type Output = Self;
372 +
373 +
    fn mul(self, s: T) -> Self {
374 +
        self.scale(s)
375 +
    }
376 +
}
377 +
378 +
impl<T, U> Add<Vector2D<T, U>> for Rect<T, U>
379 +
where
380 +
    T: Add<Output = T> + Copy,
381 +
{
382 +
    type Output = Self;
383 +
384 +
    fn add(self, vec: Vector2D<T, U>) -> Self {
385 +
        Self {
386 +
            origin: self.origin + vec,
387 +
            size: self.size,
388 +
        }
389 +
    }
390 +
}
391 +
392 +
impl<T, U> AddAssign<Vector2D<T, U>> for Rect<T, U>
393 +
where
394 +
    T: Add<Output = T> + Copy,
395 +
{
396 +
    fn add_assign(&mut self, vec: Vector2D<T, U>) {
397 +
        self.origin = self.origin + vec;
398 +
    }
399 +
}
400 +
401 +
impl<T> Sub<Vector2D<T>> for Rect<T>
402 +
where
403 +
    T: Sub<Output = T> + Copy,
404 +
{
405 +
    type Output = Self;
406 +
407 +
    fn sub(self, vec: Vector2D<T>) -> Self {
408 +
        Self {
409 +
            origin: self.origin - vec,
410 +
            size: self.size,
411 +
        }
412 +
    }
413 +
}
414 +
415 +
impl<T> SubAssign<Vector2D<T>> for Rect<T>
416 +
where
417 +
    T: Sub<Output = T> + Copy,
418 +
{
419 +
    fn sub_assign(&mut self, vec: Vector2D<T>) {
420 +
        self.origin = self.origin - vec;
421 +
    }
422 +
}
423 +
424 +
/// A 2D box. Like a rectangle, but has a minimum and maximum point instead of an origin and size.
425 +
#[derive(Debug, Clone, PartialEq, Eq)]
426 +
pub struct Box2D<T, U = ()> {
427 +
    /// Minimum point.
428 +
    pub min: Point2D<T, U>,
429 +
    /// Maximum point.
430 +
    pub max: Point2D<T, U>,
431 +
}
432 +
433 +
impl<T, U> Box2D<T, U> {
434 +
    /// Create a new box.
435 +
    pub fn new(min: Point2D<T, U>, max: Point2D<T, U>) -> Self {
436 +
        Self { min, max }
437 +
    }
438 +
}
439 +
440 +
impl<T: Copy + Add<Output = T>, U> From<Rect<T, U>> for Box2D<T, U> {
441 +
    fn from(rect: Rect<T, U>) -> Self {
442 +
        Self {
443 +
            min: rect.origin,
444 +
            max: rect.max(),
445 +
        }
446 +
    }
447 +
}
448 +
449 +
impl<T: Copy + Add<Output = T>, U> From<&Rect<T, U>> for Box2D<T, U> {
450 +
    fn from(rect: &Rect<T, U>) -> Self {
451 +
        Self {
452 +
            min: rect.origin,
453 +
            max: rect.max(),
454 +
        }
455 +
    }
456 +
}
ombre/src/math/size.rs added +198 -0
1 +
use std::fmt;
2 +
use std::ops::{Div, Mul, Sub};
3 +
4 +
use super::{traits::FloatExt as _, Vector2D, Zero};
5 +
6 +
/// Size.
7 +
#[derive(Debug, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Default)]
8 +
pub struct Size<T = f32> {
9 +
    /// Width.
10 +
    pub w: T,
11 +
    /// Height.
12 +
    pub h: T,
13 +
}
14 +
15 +
impl<T> Size<T> {
16 +
    /// Map a size to another size.
17 +
    pub fn map<S>(self, f: impl Fn(T) -> S) -> Size<S> {
18 +
        Size::new(f(self.w), f(self.h))
19 +
    }
20 +
}
21 +
22 +
impl<T: Sized> Size<T> {
23 +
    /// Create a new size.
24 +
    pub const fn new(width: T, height: T) -> Self {
25 +
        Self {
26 +
            w: width,
27 +
            h: height,
28 +
        }
29 +
    }
30 +
}
31 +
32 +
impl Size<f32> {
33 +
    /// Returns a new `Size`, with `width` and `height` rounded away from zero to the nearest
34 +
    /// integer, unless they are already an integer.
35 +
    ///
36 +
    /// # Examples
37 +
    ///
38 +
    /// ```
39 +
    /// use ombre::math::Size;
40 +
    ///
41 +
    /// let size_pos = Size::new(3.3, 3.6).expand();
42 +
    /// assert_eq!(size_pos.w, 4.0);
43 +
    /// assert_eq!(size_pos.h, 4.0);
44 +
    ///
45 +
    /// let size_neg = Size::new(-3.3, -3.6).expand();
46 +
    /// assert_eq!(size_neg.w, -4.0);
47 +
    /// assert_eq!(size_neg.h, -4.0);
48 +
    /// ```
49 +
    #[inline]
50 +
    pub fn expand(self) -> Size {
51 +
        Size::new(self.w.expand(), self.h.expand())
52 +
    }
53 +
54 +
    /// Whether this size has zero area.
55 +
    ///
56 +
    /// Note: a size with negative area is not considered empty.
57 +
    #[inline]
58 +
    pub fn is_empty(self) -> bool {
59 +
        self.area() == 0.0
60 +
    }
61 +
62 +
    /// Returns a new size bounded by `min` and `max.`
63 +
    ///
64 +
    /// # Examples
65 +
    ///
66 +
    /// ```
67 +
    /// use ombre::math::Size;
68 +
    ///
69 +
    /// let this = Size::new(0., 100.);
70 +
    /// let min = Size::new(10., 10.,);
71 +
    /// let max = Size::new(50., 50.);
72 +
    ///
73 +
    /// assert_eq!(this.clamp(min, max), Size::new(10., 50.))
74 +
    /// ```
75 +
    pub fn clamp(self, min: Size, max: Size) -> Self {
76 +
        let width = self.w.max(min.w).min(max.w);
77 +
        let height = self.h.max(min.h).min(max.h);
78 +
79 +
        Size {
80 +
            w: width,
81 +
            h: height,
82 +
        }
83 +
    }
84 +
85 +
    /// Returns a new size constrained by another size.
86 +
    pub fn constrain(self, other: Size) -> Self {
87 +
        let w = self.w.min(other.w);
88 +
        let h = self.h.min(other.h);
89 +
90 +
        Size { w, h }
91 +
    }
92 +
}
93 +
94 +
impl<T: Mul<Output = T>> Size<T> {
95 +
    /// The area covered by this size.
96 +
    #[inline]
97 +
    pub fn area(self) -> T {
98 +
        self.w * self.h
99 +
    }
100 +
}
101 +
102 +
impl<T: Div<T, Output = T> + Copy> Div<T> for Size<T> {
103 +
    type Output = Size<T>;
104 +
105 +
    fn div(self, rhs: T) -> Self::Output {
106 +
        Size {
107 +
            w: self.w / rhs,
108 +
            h: self.h / rhs,
109 +
        }
110 +
    }
111 +
}
112 +
113 +
impl<T: Mul<Output = T> + Copy> Mul<T> for Size<T> {
114 +
    type Output = Size<T>;
115 +
116 +
    fn mul(self, rhs: T) -> Self::Output {
117 +
        Size {
118 +
            w: self.w * rhs,
119 +
            h: self.h * rhs,
120 +
        }
121 +
    }
122 +
}
123 +
124 +
impl<T: Sub<Output = T> + Copy> Sub<Size<T>> for Size<T> {
125 +
    type Output = Size<T>;
126 +
127 +
    fn sub(self, rhs: Size<T>) -> Self::Output {
128 +
        Size {
129 +
            w: self.w - rhs.w,
130 +
            h: self.h - rhs.h,
131 +
        }
132 +
    }
133 +
}
134 +
135 +
impl<T> From<(T, T)> for Size<T> {
136 +
    fn from((w, h): (T, T)) -> Self {
137 +
        Self::new(w, h)
138 +
    }
139 +
}
140 +
141 +
impl<T: Copy> From<T> for Size<T> {
142 +
    fn from(n: T) -> Self {
143 +
        Self::new(n, n)
144 +
    }
145 +
}
146 +
147 +
impl<T> From<[T; 2]> for Size<T> {
148 +
    fn from([w, h]: [T; 2]) -> Self {
149 +
        Self::new(w, h)
150 +
    }
151 +
}
152 +
153 +
impl From<Size<u32>> for Size<f32> {
154 +
    fn from(other: Size<u32>) -> Self {
155 +
        Self::new(other.w as f32, other.h as f32)
156 +
    }
157 +
}
158 +
159 +
impl From<Size<usize>> for Size<u32> {
160 +
    fn from(other: Size<usize>) -> Self {
161 +
        Self::new(other.w as u32, other.h as u32)
162 +
    }
163 +
}
164 +
165 +
impl<T, U> From<Vector2D<T, U>> for Size<T> {
166 +
    fn from(other: Vector2D<T, U>) -> Self {
167 +
        Self::new(other.x, other.y)
168 +
    }
169 +
}
170 +
171 +
impl<T: Zero + PartialEq> Zero for Size<T> {
172 +
    const ZERO: Self = Size::new(T::ZERO, T::ZERO);
173 +
174 +
    fn is_zero(&self) -> bool {
175 +
        self == &Self::ZERO
176 +
    }
177 +
}
178 +
179 +
impl From<crate::platform::LogicalSize> for Size {
180 +
    fn from(other: crate::platform::LogicalSize) -> Self {
181 +
        Size {
182 +
            w: other.width as f32,
183 +
            h: other.height as f32,
184 +
        }
185 +
    }
186 +
}
187 +
188 +
impl<T> From<Size<T>> for [T; 2] {
189 +
    fn from(size: Size<T>) -> Self {
190 +
        [size.w, size.h]
191 +
    }
192 +
}
193 +
194 +
impl<T: fmt::Display> fmt::Display for Size<T> {
195 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196 +
        write!(f, "({} x {})", self.w, self.h)
197 +
    }
198 +
}
ombre/src/math/traits.rs added +411 -0
1 +
//! Numerical traits.
2 +
use std::num::NonZeroU8;
3 +
use std::ops::{Add, Div, Mul, Neg, Shl, Sub};
4 +
5 +
/// A type that has a "zero".
6 +
pub trait Zero: PartialEq + Sized {
7 +
    const ZERO: Self;
8 +
9 +
    fn is_zero(&self) -> bool;
10 +
}
11 +
12 +
impl Zero for f32 {
13 +
    const ZERO: f32 = 0.;
14 +
15 +
    fn is_zero(&self) -> bool {
16 +
        self == &Self::ZERO
17 +
    }
18 +
}
19 +
20 +
impl Zero for f64 {
21 +
    const ZERO: f64 = 0.;
22 +
23 +
    fn is_zero(&self) -> bool {
24 +
        self == &Self::ZERO
25 +
    }
26 +
}
27 +
28 +
impl Zero for usize {
29 +
    const ZERO: usize = 0;
30 +
31 +
    fn is_zero(&self) -> bool {
32 +
        self == &Self::ZERO
33 +
    }
34 +
}
35 +
36 +
impl Zero for i32 {
37 +
    const ZERO: i32 = 0;
38 +
39 +
    fn is_zero(&self) -> bool {
40 +
        self == &Self::ZERO
41 +
    }
42 +
}
43 +
44 +
impl Zero for u8 {
45 +
    const ZERO: u8 = 0;
46 +
47 +
    fn is_zero(&self) -> bool {
48 +
        self == &Self::ZERO
49 +
    }
50 +
}
51 +
52 +
impl Zero for u16 {
53 +
    const ZERO: u16 = 0;
54 +
55 +
    fn is_zero(&self) -> bool {
56 +
        self == &Self::ZERO
57 +
    }
58 +
}
59 +
60 +
impl Zero for u32 {
61 +
    const ZERO: u32 = 0;
62 +
63 +
    fn is_zero(&self) -> bool {
64 +
        self == &Self::ZERO
65 +
    }
66 +
}
67 +
68 +
impl Zero for u64 {
69 +
    const ZERO: u64 = 0;
70 +
71 +
    fn is_zero(&self) -> bool {
72 +
        self == &Self::ZERO
73 +
    }
74 +
}
75 +
76 +
impl Zero for i64 {
77 +
    const ZERO: i64 = 0;
78 +
79 +
    fn is_zero(&self) -> bool {
80 +
        self == &Self::ZERO
81 +
    }
82 +
}
83 +
84 +
////////////////////////////////////////////////////////////////////////////////
85 +
86 +
/// A type that has a "one".
87 +
pub trait One: Sized {
88 +
    const ONE: Self;
89 +
90 +
    fn is_one(&self) -> bool;
91 +
}
92 +
93 +
impl One for f32 {
94 +
    const ONE: f32 = 1.;
95 +
96 +
    fn is_one(&self) -> bool {
97 +
        self == &Self::ONE
98 +
    }
99 +
}
100 +
101 +
impl One for f64 {
102 +
    const ONE: f64 = 1.;
103 +
104 +
    fn is_one(&self) -> bool {
105 +
        self == &Self::ONE
106 +
    }
107 +
}
108 +
109 +
impl One for usize {
110 +
    const ONE: usize = 1;
111 +
112 +
    fn is_one(&self) -> bool {
113 +
        self == &Self::ONE
114 +
    }
115 +
}
116 +
117 +
impl One for u8 {
118 +
    const ONE: u8 = 1;
119 +
120 +
    fn is_one(&self) -> bool {
121 +
        self == &Self::ONE
122 +
    }
123 +
}
124 +
125 +
impl One for u64 {
126 +
    const ONE: u64 = 1;
127 +
128 +
    fn is_one(&self) -> bool {
129 +
        self == &Self::ONE
130 +
    }
131 +
}
132 +
133 +
impl One for NonZeroU8 {
134 +
    const ONE: NonZeroU8 = unsafe { NonZeroU8::new_unchecked(u8::ONE) };
135 +
136 +
    fn is_one(&self) -> bool {
137 +
        self == &Self::ONE
138 +
    }
139 +
}
140 +
141 +
////////////////////////////////////////////////////////////////////////////////
142 +
143 +
/// A type that has a "two".
144 +
pub trait Two {
145 +
    const TWO: Self;
146 +
}
147 +
148 +
impl Two for f32 {
149 +
    const TWO: f32 = 2.;
150 +
}
151 +
152 +
impl Two for f64 {
153 +
    const TWO: f64 = 2.;
154 +
}
155 +
156 +
impl Two for i32 {
157 +
    const TWO: i32 = 2;
158 +
}
159 +
160 +
////////////////////////////////////////////////////////////////////////////////
161 +
162 +
/// Trait for types with defined minimum and maximum bounds.
163 +
pub trait Bounded {
164 +
    /// Minimum value for this type.
165 +
    const MIN: Self;
166 +
    /// Maximum value for this type.
167 +
    const MAX: Self;
168 +
}
169 +
170 +
impl Bounded for u8 {
171 +
    const MIN: Self = u8::MIN;
172 +
    const MAX: Self = u8::MAX;
173 +
}
174 +
175 +
impl Bounded for u16 {
176 +
    const MIN: Self = u16::MIN;
177 +
    const MAX: Self = u16::MAX;
178 +
}
179 +
180 +
impl Bounded for u32 {
181 +
    const MIN: Self = u32::MIN;
182 +
    const MAX: Self = u32::MAX;
183 +
}
184 +
185 +
impl Bounded for u64 {
186 +
    const MIN: Self = u64::MIN;
187 +
    const MAX: Self = u64::MAX;
188 +
}
189 +
190 +
impl Bounded for i8 {
191 +
    const MIN: Self = i8::MIN;
192 +
    const MAX: Self = i8::MAX;
193 +
}
194 +
195 +
impl Bounded for i16 {
196 +
    const MIN: Self = i16::MIN;
197 +
    const MAX: Self = i16::MAX;
198 +
}
199 +
200 +
impl Bounded for i32 {
201 +
    const MIN: Self = i32::MIN;
202 +
    const MAX: Self = i32::MAX;
203 +
}
204 +
205 +
impl Bounded for i64 {
206 +
    const MIN: Self = i64::MIN;
207 +
    const MAX: Self = i64::MAX;
208 +
}
209 +
210 +
impl Bounded for usize {
211 +
    const MIN: Self = usize::MIN;
212 +
    const MAX: Self = usize::MAX;
213 +
}
214 +
215 +
////////////////////////////////////////////////////////////////////////////////
216 +
217 +
/// Trait defining operations and properties required for integer types.
218 +
pub trait Integer:
219 +
    Copy
220 +
    + Ord
221 +
    + One
222 +
    + Zero
223 +
    + Bounded
224 +
    + Add<Output = Self>
225 +
    + Sub<Output = Self>
226 +
    + Shl<u32, Output = Self>
227 +
{
228 +
    /// Number of bits in this integer type.
229 +
    const BITS: u32;
230 +
231 +
    /// Calculates remainder when divided by other.
232 +
    fn rem(&self, other: Self) -> Self;
233 +
    /// Converts a u64 to this integer type.
234 +
    fn from_u64(other: u64) -> Self;
235 +
    /// Converts this integer to f64.
236 +
    fn as_f64(&self) -> f64;
237 +
}
238 +
239 +
impl Integer for u64 {
240 +
    const BITS: u32 = u64::BITS;
241 +
242 +
    fn rem(&self, other: Self) -> Self {
243 +
        self % other
244 +
    }
245 +
246 +
    fn from_u64(other: u64) -> Self {
247 +
        other
248 +
    }
249 +
250 +
    fn as_f64(&self) -> f64 {
251 +
        *self as f64
252 +
    }
253 +
}
254 +
255 +
impl Integer for usize {
256 +
    const BITS: u32 = usize::BITS;
257 +
258 +
    fn rem(&self, other: Self) -> Self {
259 +
        self % other
260 +
    }
261 +
262 +
    fn from_u64(other: u64) -> Self {
263 +
        other as usize
264 +
    }
265 +
266 +
    fn as_f64(&self) -> f64 {
267 +
        *self as f64
268 +
    }
269 +
}
270 +
271 +
////////////////////////////////////////////////////////////////////////////////
272 +
273 +
/// Floating point numbers.
274 +
pub trait Float:
275 +
    Copy
276 +
    + PartialOrd
277 +
    + Zero
278 +
    + One
279 +
    + Two
280 +
    + Neg<Output = Self>
281 +
    + Add<Output = Self>
282 +
    + Sub<Output = Self>
283 +
    + Div<Output = Self>
284 +
    + Mul<Output = Self>
285 +
{
286 +
    /// Get the square root.
287 +
    fn sqrt(self) -> Self;
288 +
}
289 +
290 +
impl Float for f32 {
291 +
    fn sqrt(self) -> Self {
292 +
        f32::sqrt(self)
293 +
    }
294 +
}
295 +
296 +
impl Float for f64 {
297 +
    fn sqrt(self) -> Self {
298 +
        f64::sqrt(self)
299 +
    }
300 +
}
301 +
302 +
/// Adds convenience methods to `f32` and `f64`.
303 +
pub trait FloatExt<T> {
304 +
    /// Rounds to the nearest integer towards zero,
305 +
    /// unless the provided value is already an integer.
306 +
    ///
307 +
    /// It is to `floor` what `expand` is to `ceil`.
308 +
    ///
309 +
    /// # Examples
310 +
    ///
311 +
    /// ```
312 +
    /// use ombre::math::traits::FloatExt;
313 +
    ///
314 +
    /// let f = 3.7_f64;
315 +
    /// let g = 3.0_f64;
316 +
    /// let h = -3.7_f64;
317 +
    /// let i = -5.9_f32;
318 +
    ///
319 +
    /// assert_eq!(f.truncate(), 3.0);
320 +
    /// assert_eq!(g.truncate(), 3.0);
321 +
    /// assert_eq!(h.truncate(), -3.0);
322 +
    /// assert_eq!(i.truncate(), -5.0);
323 +
    /// ```
324 +
    fn truncate(&self) -> T;
325 +
326 +
    /// Rounds to the nearest integer away from zero,
327 +
    /// unless the provided value is already an integer.
328 +
    ///
329 +
    /// It is to `ceil` what `truncate` is to `floor`.
330 +
    ///
331 +
    /// # Examples
332 +
    ///
333 +
    /// ```
334 +
    /// use ombre::math::traits::FloatExt;
335 +
    ///
336 +
    /// let f = 3.7_f64;
337 +
    /// let g = 3.0_f64;
338 +
    /// let h = -3.7_f64;
339 +
    /// let i = -5.1_f32;
340 +
    ///
341 +
    /// assert_eq!(f.expand(), 4.0);
342 +
    /// assert_eq!(g.expand(), 3.0);
343 +
    /// assert_eq!(h.expand(), -4.0);
344 +
    /// assert_eq!(i.expand(), -6.0);
345 +
    /// ```
346 +
    fn expand(&self) -> T;
347 +
}
348 +
349 +
impl FloatExt<f64> for f64 {
350 +
    #[inline]
351 +
    fn expand(&self) -> f64 {
352 +
        self.abs().ceil().copysign(*self)
353 +
    }
354 +
355 +
    #[inline]
356 +
    fn truncate(&self) -> Self {
357 +
        self.abs().floor().copysign(*self)
358 +
    }
359 +
}
360 +
361 +
impl FloatExt<f32> for f32 {
362 +
    #[inline]
363 +
    fn expand(&self) -> f32 {
364 +
        self.abs().ceil().copysign(*self)
365 +
    }
366 +
367 +
    #[inline]
368 +
    fn truncate(&self) -> Self {
369 +
        self.abs().floor().copysign(*self)
370 +
    }
371 +
}
372 +
373 +
/// Approximate equality.
374 +
pub trait ApproxEq {
375 +
    type Epsilon: Copy + PartialOrd;
376 +
377 +
    /// Checks if `|x - y| <= epsilon`.
378 +
    fn approx_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool;
379 +
    /// Checks if `|x - y| > epsilon`.
380 +
    fn approx_neq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
381 +
        !self.approx_eq(other, epsilon)
382 +
    }
383 +
}
384 +
385 +
impl ApproxEq for f32 {
386 +
    type Epsilon = f32;
387 +
388 +
    fn approx_eq(&self, other: &Self, epsilon: f32) -> bool {
389 +
        (self - other).abs() <= epsilon
390 +
    }
391 +
}
392 +
393 +
impl ApproxEq for f64 {
394 +
    type Epsilon = f64;
395 +
396 +
    fn approx_eq(&self, other: &Self, epsilon: f64) -> bool {
397 +
        (self - other).abs() <= epsilon
398 +
    }
399 +
}
400 +
401 +
#[cfg(test)]
402 +
mod test {
403 +
    use crate::math::macros::*;
404 +
405 +
    #[test]
406 +
    fn test_approx_eq() {
407 +
        assert_approx_eq!(1.0, 1.0, 0.0001);
408 +
        assert_approx_eq!(1.0, 1.001, 0.01);
409 +
        assert_approx_neq!(1.0, 1.001, 0.00000001);
410 +
    }
411 +
}
ombre/src/math/transform.rs added +783 -0
1 +
// (c) 2013-2014 The CGMath Developers
2 +
// (c) 2012-2013 Mozilla Foundation
3 +
// (c) 2021-2022 Alexis Sellier
4 +
//
5 +
// Code in this module was borrowed from the excellent `euler` crate.
6 +
7 +
//! Matrix transforms.
8 +
use std::marker::PhantomData;
9 +
use std::ops::{Add, Div, Mul, Sub};
10 +
11 +
use super::algebra::*;
12 +
use super::traits::*;
13 +
use super::Size;
14 +
15 +
/// Coordinate systems.
16 +
pub mod coord {
17 +
    /// Used as a marker for screen space coordinates.
18 +
    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
19 +
    pub struct Screen;
20 +
    /// Used as a marker for local space coordinates.
21 +
    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
22 +
    pub struct Local;
23 +
    /// Used as a marker for world space coordinates.
24 +
    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
25 +
    pub struct World;
26 +
    /// Used for spherical coordinates.
27 +
    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
28 +
    pub struct Spherical;
29 +
}
30 +
31 +
/// A 2D affine transform.
32 +
///
33 +
/// Transforms can be parametrized over the source and destination units, to describe a
34 +
/// transformation from a space to another.
35 +
///
36 +
/// For example, `Transform2D<f32, WorldSpace, ScreenSpace>::transform_point4d`
37 +
/// takes a `Point2D<f32, WorldSpace>` and returns a `Point2D<f32, ScreenSpace>`.
38 +
///
39 +
/// The matrix representation is conceptually equivalent to a 3 by 3 matrix transformation
40 +
/// compressed to 3 by 2 with the components that aren't needed to describe the set of 2d
41 +
/// transformations we are interested in implicitly defined:
42 +
///
43 +
/// ```text
44 +
///  | m11 m12 0 |   |x|   |x'|
45 +
///  | m21 m22 0 | x |y| = |y'|
46 +
///  | m31 m32 1 |   |1|   |w |
47 +
/// ```
48 +
///
49 +
/// When translating Transform2D into general matrix representations, consider that the
50 +
/// representation follows the column-major notation with column vectors.
51 +
///
52 +
/// The translation terms are m31 and m32.
53 +
#[repr(C)]
54 +
#[rustfmt::skip]
55 +
#[derive(Debug, Copy, Clone, PartialEq)]
56 +
pub struct Transform2D<Src = (), Dst = Src> {
57 +
    pub m11: f32, pub m12: f32,
58 +
    pub m21: f32, pub m22: f32,
59 +
    pub m31: f32, pub m32: f32,
60 +
    #[doc(hidden)]
61 +
    pub unit: PhantomData<(Src, Dst)>,
62 +
}
63 +
64 +
impl<Src: Copy, Dst: Copy> Transform2D<Src, Dst> {
65 +
    /// Identity matrix.
66 +
    pub const IDENTITY: Self = Self::identity();
67 +
68 +
    /// Create a transform specifying its components in using the column-major-column-vector
69 +
    /// matrix notation.
70 +
    ///
71 +
    /// For example, the translation terms m31 and m32 are the last two parameters parameters.
72 +
    ///
73 +
    /// ```
74 +
    /// use ombre::math::Transform2D;
75 +
    ///
76 +
    /// let tx = 1.0;
77 +
    /// let ty = 2.0;
78 +
    ///
79 +
    /// let translation: Transform2D<(), ()> = Transform2D::new(
80 +
    ///   1.0, 0.0,
81 +
    ///   0.0, 1.0,
82 +
    ///   tx,  ty,
83 +
    /// );
84 +
    /// ```
85 +
    #[rustfmt::skip]
86 +
    pub const fn new(m11: f32, m12: f32, m21: f32, m22: f32, m31: f32, m32: f32) -> Self {
87 +
        Transform2D {
88 +
            m11, m12,
89 +
            m21, m22,
90 +
            m31, m32,
91 +
            unit: PhantomData,
92 +
        }
93 +
    }
94 +
95 +
    /// Create an identity matrix:
96 +
    ///
97 +
    /// ```text
98 +
    /// 1 0
99 +
    /// 0 1
100 +
    /// 0 0
101 +
    /// ```
102 +
    #[inline]
103 +
    pub const fn identity() -> Self {
104 +
        Self::translate(Vector2D::ZERO)
105 +
    }
106 +
107 +
    /// Create a 2d translation transform:
108 +
    ///
109 +
    /// ```text
110 +
    /// 1 0
111 +
    /// 0 1
112 +
    /// x y
113 +
    /// ```
114 +
    #[inline]
115 +
    pub const fn translate(v: Vector2D<f32, Src>) -> Self {
116 +
        Self::new(1., 0., 0., 1., v.x, v.y)
117 +
    }
118 +
119 +
    /// Get the translation component.
120 +
    #[inline]
121 +
    pub const fn translation(&self) -> Vector2D<f32, Src> {
122 +
        Vector2D::new(self.m31, self.m32)
123 +
    }
124 +
125 +
    /// Create a 2d scale transform:
126 +
    ///
127 +
    /// ```text
128 +
    /// s 0
129 +
    /// 0 s
130 +
    /// 0 0
131 +
    /// ```
132 +
    #[inline]
133 +
    pub const fn scale(s: f32) -> Self {
134 +
        Self::new(s, 0., 0., s, 0., 0.)
135 +
    }
136 +
137 +
    /// Computes and returns the determinant of this transform.
138 +
    pub fn determinant(&self) -> f32 {
139 +
        self.m11 * self.m22 - self.m12 * self.m21
140 +
    }
141 +
142 +
    /// Returns whether it is possible to compute the inverse transform.
143 +
    #[inline]
144 +
    pub fn is_invertible(&self) -> bool {
145 +
        self.determinant() != 0.
146 +
    }
147 +
148 +
    /// Returns the inverse transform if possible.
149 +
    pub fn inverse(self) -> Transform2D<Dst, Src> {
150 +
        let idet = self.determinant().recip();
151 +
152 +
        Transform2D::new(
153 +
            idet * self.m22,
154 +
            idet * (0. - self.m12),
155 +
            idet * (0. - self.m21),
156 +
            idet * self.m11,
157 +
            idet * (self.m21 * self.m32 - self.m22 * self.m31),
158 +
            idet * (self.m31 * self.m12 - self.m11 * self.m32),
159 +
        )
160 +
    }
161 +
162 +
    /// Returns the multiplication of the two matrices such that mat's transformation
163 +
    /// applies after self's transformation.
164 +
    pub fn then<Final: Copy>(self, mat: Transform2D<Dst, Final>) -> Transform2D<Src, Final> {
165 +
        self.multiply(mat)
166 +
    }
167 +
168 +
    pub fn convert<S, T>(self) -> Transform2D<S, T> {
169 +
        Transform2D {
170 +
            m11: self.m11,
171 +
            m12: self.m12,
172 +
            m21: self.m21,
173 +
            m22: self.m22,
174 +
            m31: self.m31,
175 +
            m32: self.m32,
176 +
            unit: PhantomData,
177 +
        }
178 +
    }
179 +
}
180 +
181 +
impl<Src: Copy, Dst: Copy> Mul<Transform2D<Src, Dst>> for Transform2D<Src, Dst> {
182 +
    type Output = Transform2D<Src, Dst>;
183 +
184 +
    /// Multiply without changing the original coordinate system.
185 +
    fn mul(self, mat: Transform2D<Src, Dst>) -> Transform2D<Src, Dst> {
186 +
        self.multiply(mat)
187 +
    }
188 +
}
189 +
190 +
impl<Src: Copy, Dst: Copy> Transform2D<Src, Dst> {
191 +
    /// Low-level multiply function which is coordinate-system agnostic.
192 +
    fn multiply<S, T, U: Copy, V: Copy>(self, mat: Transform2D<S, T>) -> Transform2D<U, V> {
193 +
        Transform2D::new(
194 +
            self.m11 * mat.m11 + self.m12 * mat.m21,
195 +
            self.m11 * mat.m12 + self.m12 * mat.m22,
196 +
            self.m21 * mat.m11 + self.m22 * mat.m21,
197 +
            self.m21 * mat.m12 + self.m22 * mat.m22,
198 +
            self.m31 * mat.m11 + self.m32 * mat.m21 + mat.m31,
199 +
            self.m31 * mat.m12 + self.m32 * mat.m22 + mat.m32,
200 +
        )
201 +
    }
202 +
}
203 +
204 +
impl<U, V> Mul<Point2D<f32, U>> for Transform2D<U, V> {
205 +
    type Output = Point2D<f32, V>;
206 +
207 +
    #[inline]
208 +
    fn mul(self, point: Point2D<f32, U>) -> Point2D<f32, V> {
209 +
        Point2D::new(
210 +
            point.x * self.m11 + point.y * self.m21 + self.m31,
211 +
            point.x * self.m12 + point.y * self.m22 + self.m32,
212 +
        )
213 +
    }
214 +
}
215 +
216 +
impl<U, V> Mul<Vector2D<f32, U>> for Transform2D<U, V> {
217 +
    type Output = Vector2D<f32, V>;
218 +
219 +
    #[inline]
220 +
    fn mul(self, v: Vector2D<f32, U>) -> Vector2D<f32, V> {
221 +
        Vector2D::new(
222 +
            v.x * self.m11 + v.y * self.m21 + self.m31,
223 +
            v.x * self.m12 + v.y * self.m22 + self.m32,
224 +
        )
225 +
    }
226 +
}
227 +
228 +
/// A 4 x 4, column major matrix
229 +
///
230 +
/// This type is marked as `#[repr(C)]`.
231 +
#[repr(C)]
232 +
#[derive(Debug, Copy, Clone, PartialEq, Default)]
233 +
pub struct Transform3D<S = f32, Src = (), Dst = Src> {
234 +
    /// The first column of the matrix.
235 +
    pub x: Vector4D<S>,
236 +
    /// The second column of the matrix.
237 +
    pub y: Vector4D<S>,
238 +
    /// The third column of the matrix.
239 +
    pub z: Vector4D<S>,
240 +
    /// The fourth column of the matrix.
241 +
    pub w: Vector4D<S>,
242 +
    #[doc(hidden)]
243 +
    pub unit: PhantomData<(Src, Dst)>,
244 +
}
245 +
246 +
impl From<Transform3D<f32>> for [[f32; 4]; 4] {
247 +
    fn from(mat: Transform3D<f32>) -> Self {
248 +
        unsafe { std::mem::transmute(mat) }
249 +
    }
250 +
}
251 +
252 +
impl<S: Zero + One, Src, Dst> Transform3D<S, Src, Dst> {
253 +
    /// The zero matrix.
254 +
    #[rustfmt::skip]
255 +
    const fn zero() -> Self {
256 +
        Self::new(
257 +
            S::ZERO, S::ZERO, S::ZERO, S::ZERO,
258 +
            S::ZERO, S::ZERO, S::ZERO, S::ZERO,
259 +
            S::ZERO, S::ZERO, S::ZERO, S::ZERO,
260 +
            S::ZERO, S::ZERO, S::ZERO, S::ZERO,
261 +
        )
262 +
    }
263 +
264 +
    /// Create a new matrix, providing values for each index.
265 +
    #[inline]
266 +
    #[rustfmt::skip]
267 +
    pub const fn new(
268 +
        m11: S, m12: S, m13: S, m14: S,
269 +
        m21: S, m22: S, m23: S, m24: S,
270 +
        m31: S, m32: S, m33: S, m34: S,
271 +
        m41: S, m42: S, m43: S, m44: S,
272 +
    ) -> Self {
273 +
        Self {
274 +
            x: Vector4D::new(m11, m12, m13, m14),
275 +
            y: Vector4D::new(m21, m22, m23, m24),
276 +
            z: Vector4D::new(m31, m32, m33, m34),
277 +
            w: Vector4D::new(m41, m42, m43, m44),
278 +
279 +
            unit: PhantomData,
280 +
        }
281 +
    }
282 +
283 +
    /// Create a transform representing a 2d transformation from the components
284 +
    /// of a 2 by 3 matrix transformation.
285 +
    ///
286 +
    /// Components follow the column-major-column-vector notation (m41 and m42
287 +
    /// representating the translation terms).
288 +
    ///
289 +
    /// ```text
290 +
    /// m11  m12   0   0
291 +
    /// m21  m22   0   0
292 +
    ///   0    0   1   0
293 +
    /// m41  m42   0   1
294 +
    /// ```
295 +
    #[inline]
296 +
    #[rustfmt::skip]
297 +
    pub const fn new_2d(m11: S, m12: S, m21: S, m22: S, m41: S, m42: S) -> Self
298 +
    where
299 +
        S: Zero + One,
300 +
    {
301 +
        Self::new(
302 +
            m11,     m12,     S::ZERO, S::ZERO,
303 +
            m21,     m22,     S::ZERO, S::ZERO,
304 +
            S::ZERO, S::ZERO, S::ONE,  S::ZERO,
305 +
            m41,     m42,     S::ZERO, S::ONE
306 +
       )
307 +
    }
308 +
309 +
310 +
    #[inline]
311 +
    #[rustfmt::skip]
312 +
    pub const fn identity() -> Self {
313 +
        Transform3D::new(
314 +
            S::ONE,  S::ZERO, S::ZERO, S::ZERO,
315 +
            S::ZERO, S::ONE,  S::ZERO, S::ZERO,
316 +
            S::ZERO, S::ZERO, S::ONE,  S::ZERO,
317 +
            S::ZERO, S::ZERO, S::ZERO, S::ONE,
318 +
        )
319 +
    }
320 +
321 +
    /// Create a homogeneous transformation matrix from a set of scale values.
322 +
    #[inline]
323 +
    #[rustfmt::skip]
324 +
    pub const fn from_nonuniform_scale(x: S, y: S, z: S) -> Transform3D<S, Src, Dst> {
325 +
        Transform3D::new(
326 +
            x,       S::ZERO, S::ZERO, S::ZERO,
327 +
            S::ZERO, y,       S::ZERO, S::ZERO,
328 +
            S::ZERO, S::ZERO, z,       S::ZERO,
329 +
            S::ZERO, S::ZERO, S::ZERO, S::ONE,
330 +
        )
331 +
    }
332 +
}
333 +
334 +
impl<S: Copy + Zero + One, Src, Dst> Transform3D<S, Src, Dst> {
335 +
    #[inline]
336 +
    pub fn row(&self, n: usize) -> Vector4D<S> {
337 +
        match n {
338 +
            0 => Vector4D::new(self.x.x, self.y.x, self.z.x, self.w.x),
339 +
            1 => Vector4D::new(self.x.y, self.y.y, self.z.y, self.w.y),
340 +
            2 => Vector4D::new(self.x.z, self.y.z, self.z.z, self.w.z),
341 +
            3 => Vector4D::new(self.x.w, self.y.w, self.z.w, self.w.w),
342 +
            _ => panic!("Transform3D::row: invalid row number: {n}"),
343 +
        }
344 +
    }
345 +
346 +
    #[inline]
347 +
    pub fn translation(&self) -> Vector3D<S> {
348 +
        Vector3D::new(self.w.x, self.w.y, self.w.z)
349 +
    }
350 +
351 +
    /// Create a homogeneous transformation matrix from a translation vector.
352 +
    #[inline]
353 +
    #[rustfmt::skip]
354 +
    pub fn from_translation(v: impl Into<Vector3D<S, Src>>) -> Transform3D<S, Src, Dst> {
355 +
        let v = v.into();
356 +
357 +
        Transform3D::new(
358 +
            S::ONE,  S::ZERO, S::ZERO, S::ZERO,
359 +
            S::ZERO, S::ONE,  S::ZERO, S::ZERO,
360 +
            S::ZERO, S::ZERO, S::ONE,  S::ZERO,
361 +
            v.x,     v.y,     v.z,     S::ONE,
362 +
        )
363 +
    }
364 +
365 +
    #[inline]
366 +
    pub fn scale(&self) -> Vector3D<S> {
367 +
        Vector3D::new(self.x.x, self.y.y, self.z.z)
368 +
    }
369 +
370 +
    /// Create a homogeneous transformation matrix from a scale value.
371 +
    #[inline]
372 +
    pub fn from_scale(value: S) -> Transform3D<S, Src, Dst> {
373 +
        Transform3D::from_nonuniform_scale(value, value, value)
374 +
    }
375 +
}
376 +
377 +
impl<Src, Dst> Transform3D<f32, Src, Dst> {
378 +
    /// Create orthographic matrix.
379 +
    pub fn ortho(size: impl Into<Size<f32>>, origin: Origin) -> Self {
380 +
        let size = size.into();
381 +
        let (top, bottom) = match origin {
382 +
            Origin::BottomLeft => (size.h, 0.),
383 +
            Origin::TopLeft => (0., size.h),
384 +
        };
385 +
        Ortho::<f32> {
386 +
            left: 0.0,
387 +
            right: size.w,
388 +
            bottom,
389 +
            top,
390 +
            near: -1.0,
391 +
            far: 1.0,
392 +
        }
393 +
        .into()
394 +
    }
395 +
396 +
    #[inline]
397 +
    pub fn offset(&self) -> Vector2D {
398 +
        Vector2D::new(self.w.x, self.w.y)
399 +
    }
400 +
}
401 +
402 +
impl<T, Src, Dst> Transform3D<T, Src, Dst>
403 +
where
404 +
    T: Copy
405 +
        + Add<T, Output = T>
406 +
        + Sub<T, Output = T>
407 +
        + Mul<T, Output = T>
408 +
        + Div<T, Output = T>
409 +
        + One
410 +
        + Zero,
411 +
    Src: Copy,
412 +
    Dst: Copy,
413 +
{
414 +
    /// Returns whether it is possible to compute the inverse transform.
415 +
    #[inline]
416 +
    pub fn is_invertible(&self) -> bool {
417 +
        self.determinant() != Zero::ZERO
418 +
    }
419 +
420 +
    /// Return the inverse transform.
421 +
    ///
422 +
    /// Panics if the transform is not invertible.
423 +
    #[inline]
424 +
    pub fn inverse(&self) -> Transform3D<T, Dst, Src> {
425 +
        self.try_inverse()
426 +
            .expect("Transform3d::inverse: matrix is not invertible")
427 +
    }
428 +
429 +
    /// Returns the inverse transform if possible.
430 +
    #[rustfmt::skip]
431 +
    pub fn try_inverse(&self) -> Option<Transform3D<T, Dst, Src>> {
432 +
        let det = self.determinant();
433 +
434 +
        if det == Zero::ZERO {
435 +
            return None;
436 +
        }
437 +
438 +
        let m = Transform3D::new(
439 +
            self.y.z * self.z.w * self.w.y - self.y.w * self.z.z * self.w.y +
440 +
            self.y.w * self.z.y * self.w.z - self.y.y * self.z.w * self.w.z -
441 +
            self.y.z * self.z.y * self.w.w + self.y.y * self.z.z * self.w.w,
442 +
443 +
            self.x.w * self.z.z * self.w.y - self.x.z * self.z.w * self.w.y -
444 +
            self.x.w * self.z.y * self.w.z + self.x.y * self.z.w * self.w.z +
445 +
            self.x.z * self.z.y * self.w.w - self.x.y * self.z.z * self.w.w,
446 +
447 +
            self.x.z * self.y.w * self.w.y - self.x.w * self.y.z * self.w.y +
448 +
            self.x.w * self.y.y * self.w.z - self.x.y * self.y.w * self.w.z -
449 +
            self.x.z * self.y.y * self.w.w + self.x.y * self.y.z * self.w.w,
450 +
451 +
            self.x.w * self.y.z * self.z.y - self.x.z * self.y.w * self.z.y -
452 +
            self.x.w * self.y.y * self.z.z + self.x.y * self.y.w * self.z.z +
453 +
            self.x.z * self.y.y * self.z.w - self.x.y * self.y.z * self.z.w,
454 +
455 +
            self.y.w * self.z.z * self.w.x - self.y.z * self.z.w * self.w.x -
456 +
            self.y.w * self.z.x * self.w.z + self.y.x * self.z.w * self.w.z +
457 +
            self.y.z * self.z.x * self.w.w - self.y.x * self.z.z * self.w.w,
458 +
459 +
            self.x.z * self.z.w * self.w.x - self.x.w * self.z.z * self.w.x +
460 +
            self.x.w * self.z.x * self.w.z - self.x.x * self.z.w * self.w.z -
461 +
            self.x.z * self.z.x * self.w.w + self.x.x * self.z.z * self.w.w,
462 +
463 +
            self.x.w * self.y.z * self.w.x - self.x.z * self.y.w * self.w.x -
464 +
            self.x.w * self.y.x * self.w.z + self.x.x * self.y.w * self.w.z +
465 +
            self.x.z * self.y.x * self.w.w - self.x.x * self.y.z * self.w.w,
466 +
467 +
            self.x.z * self.y.w * self.z.x - self.x.w * self.y.z * self.z.x +
468 +
            self.x.w * self.y.x * self.z.z - self.x.x * self.y.w * self.z.z -
469 +
            self.x.z * self.y.x * self.z.w + self.x.x * self.y.z * self.z.w,
470 +
471 +
            self.y.y * self.z.w * self.w.x - self.y.w * self.z.y * self.w.x +
472 +
            self.y.w * self.z.x * self.w.y - self.y.x * self.z.w * self.w.y -
473 +
            self.y.y * self.z.x * self.w.w + self.y.x * self.z.y * self.w.w,
474 +
475 +
            self.x.w * self.z.y * self.w.x - self.x.y * self.z.w * self.w.x -
476 +
            self.x.w * self.z.x * self.w.y + self.x.x * self.z.w * self.w.y +
477 +
            self.x.y * self.z.x * self.w.w - self.x.x * self.z.y * self.w.w,
478 +
479 +
            self.x.y * self.y.w * self.w.x - self.x.w * self.y.y * self.w.x +
480 +
            self.x.w * self.y.x * self.w.y - self.x.x * self.y.w * self.w.y -
481 +
            self.x.y * self.y.x * self.w.w + self.x.x * self.y.y * self.w.w,
482 +
483 +
            self.x.w * self.y.y * self.z.x - self.x.y * self.y.w * self.z.x -
484 +
            self.x.w * self.y.x * self.z.y + self.x.x * self.y.w * self.z.y +
485 +
            self.x.y * self.y.x * self.z.w - self.x.x * self.y.y * self.z.w,
486 +
487 +
            self.y.z * self.z.y * self.w.x - self.y.y * self.z.z * self.w.x -
488 +
            self.y.z * self.z.x * self.w.y + self.y.x * self.z.z * self.w.y +
489 +
            self.y.y * self.z.x * self.w.z - self.y.x * self.z.y * self.w.z,
490 +
491 +
            self.x.y * self.z.z * self.w.x - self.x.z * self.z.y * self.w.x +
492 +
            self.x.z * self.z.x * self.w.y - self.x.x * self.z.z * self.w.y -
493 +
            self.x.y * self.z.x * self.w.z + self.x.x * self.z.y * self.w.z,
494 +
495 +
            self.x.z * self.y.y * self.w.x - self.x.y * self.y.z * self.w.x -
496 +
            self.x.z * self.y.x * self.w.y + self.x.x * self.y.z * self.w.y +
497 +
            self.x.y * self.y.x * self.w.z - self.x.x * self.y.y * self.w.z,
498 +
499 +
            self.x.y * self.y.z * self.z.x - self.x.z * self.y.y * self.z.x +
500 +
            self.x.z * self.y.x * self.z.y - self.x.x * self.y.z * self.z.y -
501 +
            self.x.y * self.y.x * self.z.z + self.x.x * self.y.y * self.z.z
502 +
        );
503 +
504 +
        Some(m * (T::ONE / det))
505 +
    }
506 +
507 +
    /// Compute the determinant of the transform.
508 +
    #[rustfmt::skip]
509 +
    pub fn determinant(&self) -> T {
510 +
        self.x.w * self.y.z * self.z.y * self.w.x -
511 +
        self.x.z * self.y.w * self.z.y * self.w.x -
512 +
        self.x.w * self.y.y * self.z.z * self.w.x +
513 +
        self.x.y * self.y.w * self.z.z * self.w.x +
514 +
        self.x.z * self.y.y * self.z.w * self.w.x -
515 +
        self.x.y * self.y.z * self.z.w * self.w.x -
516 +
        self.x.w * self.y.z * self.z.x * self.w.y +
517 +
        self.x.z * self.y.w * self.z.x * self.w.y +
518 +
        self.x.w * self.y.x * self.z.z * self.w.y -
519 +
        self.x.x * self.y.w * self.z.z * self.w.y -
520 +
        self.x.z * self.y.x * self.z.w * self.w.y +
521 +
        self.x.x * self.y.z * self.z.w * self.w.y +
522 +
        self.x.w * self.y.y * self.z.x * self.w.z -
523 +
        self.x.y * self.y.w * self.z.x * self.w.z -
524 +
        self.x.w * self.y.x * self.z.y * self.w.z +
525 +
        self.x.x * self.y.w * self.z.y * self.w.z +
526 +
        self.x.y * self.y.x * self.z.w * self.w.z -
527 +
        self.x.x * self.y.y * self.z.w * self.w.z -
528 +
        self.x.z * self.y.y * self.z.x * self.w.w +
529 +
        self.x.y * self.y.z * self.z.x * self.w.w +
530 +
        self.x.z * self.y.x * self.z.y * self.w.w -
531 +
        self.x.x * self.y.z * self.z.y * self.w.w -
532 +
        self.x.y * self.y.x * self.z.z * self.w.w +
533 +
        self.x.x * self.y.y * self.z.z * self.w.w
534 +
    }
535 +
536 +
    /// *Look at* transform.
537 +
    pub fn look_at(eye: Vector3D<T, Src>, center: Vector3D<T, Src>, up: Vector3D<T, Src>) -> Self
538 +
    where
539 +
        T: Float,
540 +
    {
541 +
        let mut res = Transform3D::<T, Src, Dst>::zero();
542 +
543 +
        let f = (center - eye).normalize();
544 +
        let s = Vector3D::cross(f, up).normalize();
545 +
        let u = Vector3D::cross(s, f);
546 +
547 +
        res.x.x = s.x;
548 +
        res.x.y = u.x;
549 +
        res.x.z = -f.x;
550 +
551 +
        res.y.x = s.y;
552 +
        res.y.y = u.y;
553 +
        res.y.z = -f.y;
554 +
555 +
        res.z.x = s.z;
556 +
        res.z.y = u.z;
557 +
        res.z.z = -f.z;
558 +
559 +
        res.w.x = -Vector3D::dot(s, eye);
560 +
        res.w.y = -Vector3D::dot(u, eye);
561 +
        res.w.z = Vector3D::dot(f, eye);
562 +
        res.w.w = T::ONE;
563 +
564 +
        res
565 +
    }
566 +
}
567 +
568 +
impl<Src, Dst> Transform3D<f32, Src, Dst> {
569 +
    /// Perspective projection.
570 +
    pub fn perspective(fov: f32, aspect: f32, near: f32, far: f32) -> Self {
571 +
        let mut res = Self::identity();
572 +
        let t = f32::tan(fov * (std::f32::consts::PI / 360.0));
573 +
574 +
        res.x.x = t.recip();
575 +
        res.y.y = aspect / t;
576 +
        res.z.w = -1.0;
577 +
        res.z.z = (near + far) / (near - far);
578 +
        res.w.z = (2.0 * near * far) / (near - far);
579 +
        res.w.w = 0.0;
580 +
581 +
        res
582 +
    }
583 +
584 +
    /// A rotation transform. The axis can be unnormalized.
585 +
    pub fn rotation(angle: f32, axis: Vector3D<f32>) -> Self {
586 +
        let mut res = Self::identity();
587 +
        let axis = axis.normalize();
588 +
        let sin_theta = f32::sin(angle.to_radians());
589 +
        let cos_theta = f32::cos(angle.to_radians());
590 +
        let cos = 1.0 - cos_theta;
591 +
592 +
        res.x.x = (axis.x * axis.x * cos) + cos_theta;
593 +
        res.x.y = (axis.x * axis.y * cos) + (axis.z * sin_theta);
594 +
        res.x.z = (axis.x * axis.z * cos) - (axis.y * sin_theta);
595 +
        res.y.x = (axis.y * axis.x * cos) - (axis.z * sin_theta);
596 +
        res.y.y = (axis.y * axis.y * cos) + cos_theta;
597 +
        res.y.z = (axis.y * axis.z * cos) + (axis.x * sin_theta);
598 +
        res.z.x = (axis.z * axis.x * cos) + (axis.y * sin_theta);
599 +
        res.z.y = (axis.z * axis.y * cos) - (axis.x * sin_theta);
600 +
        res.z.z = (axis.z * axis.z * cos) + cos_theta;
601 +
602 +
        res
603 +
    }
604 +
}
605 +
606 +
impl<S, Src, Dst, NewDst> Mul<Transform3D<S, Dst, NewDst>> for Transform3D<S, Src, Dst>
607 +
where
608 +
    S: Mul<Output = S> + Add<Output = S> + Copy,
609 +
{
610 +
    type Output = Transform3D<S, Src, NewDst>;
611 +
612 +
    #[rustfmt::skip]
613 +
    fn mul(self, rhs: Transform3D<S, Dst, NewDst>) -> Self::Output {
614 +
        let a = self.x;
615 +
        let b = self.y;
616 +
        let c = self.z;
617 +
        let d = self.w;
618 +
619 +
        Transform3D {
620 +
            x: a * rhs.x.x + b * rhs.x.y + c * rhs.x.z + d * rhs.x.w,
621 +
            y: a * rhs.y.x + b * rhs.y.y + c * rhs.y.z + d * rhs.y.w,
622 +
            z: a * rhs.z.x + b * rhs.z.y + c * rhs.z.z + d * rhs.z.w,
623 +
            w: a * rhs.w.x + b * rhs.w.y + c * rhs.w.z + d * rhs.w.w,
624 +
625 +
            unit: PhantomData,
626 +
        }
627 +
    }
628 +
}
629 +
630 +
/// Transform a [`Vector2D`] with a [`Transform3D`].
631 +
///
632 +
/// ```
633 +
/// use ombre::math::*;
634 +
/// let m = Transform3D::from_translation(Vector3D::new(8., 8., 0.));
635 +
/// let v = Vector2D::new(1., 1.);
636 +
///
637 +
/// assert_eq!(m * v, Vector2D::new(9., 9.));
638 +
/// ```
639 +
impl Mul<Vector2D<f32>> for Transform3D<f32> {
640 +
    type Output = Vector2D<f32>;
641 +
642 +
    fn mul(self, vec: Vector2D<f32>) -> Vector2D<f32> {
643 +
        let vec = Vector4D::from(vec);
644 +
        Vector2D::new(self.row(0) * vec, self.row(1) * vec)
645 +
    }
646 +
}
647 +
648 +
/// Transform a [`Vector3D`] with a [`Transform3D`].
649 +
///
650 +
/// ```
651 +
/// use ombre::math::*;
652 +
/// let m = Transform3D::from_translation(Vector3D::new(8., 8., 0.));
653 +
/// let v = Vector3D::new(1., 1., 0.);
654 +
///
655 +
/// assert_eq!(m * v, Vector3D::new(9., 9., 0.));
656 +
/// ```
657 +
impl Mul<Vector3D<f32>> for Transform3D<f32> {
658 +
    type Output = Vector3D<f32>;
659 +
660 +
    fn mul(self, vec: Vector3D<f32>) -> Vector3D<f32> {
661 +
        let vec = Vector4D::from(vec);
662 +
        Vector3D::new(self.row(0) * vec, self.row(1) * vec, self.row(2) * vec)
663 +
    }
664 +
}
665 +
666 +
/// Transform a [`Vector4D`] with a [`Transform3D`].
667 +
///
668 +
/// ```
669 +
/// use ombre::math::*;
670 +
/// let m = Transform3D::from_translation(Vector3D::new(8., 8., 0.));
671 +
/// let v = Vector4D::new(1., 1., 0., 1.);
672 +
///
673 +
/// assert_eq!(m * v, Vector4D::new(9., 9., 0., 1.));
674 +
/// ```
675 +
impl Mul<Vector4D<f32>> for Transform3D<f32> {
676 +
    type Output = Vector4D<f32>;
677 +
678 +
    fn mul(self, vec: Vector4D<f32>) -> Vector4D<f32> {
679 +
        Vector4D::new(
680 +
            self.row(0) * vec,
681 +
            self.row(1) * vec,
682 +
            self.row(2) * vec,
683 +
            self.row(3) * vec,
684 +
        )
685 +
    }
686 +
}
687 +
688 +
/// Transform a [`Point2D`] with a [`Transform3D`].
689 +
///
690 +
/// ```
691 +
/// use ombre::math::*;
692 +
/// let m = Transform3D::from_translation(Vector3D::new(8., 8., 0.));
693 +
/// let p = Point2D::new(1., 1.);
694 +
///
695 +
/// assert_eq!(m * p, Point2D::new(9., 9.));
696 +
/// ```
697 +
impl Mul<Point2D<f32>> for Transform3D<f32> {
698 +
    type Output = Point2D<f32>;
699 +
700 +
    fn mul(self, p: Point2D<f32>) -> Point2D<f32> {
701 +
        let vec = Vector4D::new(p.x, p.y, 0., 1.);
702 +
        Point2D::new(self.row(0) * vec, self.row(1) * vec)
703 +
    }
704 +
}
705 +
706 +
/// Multiplies all of the transform's component by a scalar and returns the result.
707 +
impl<S: Copy + Zero + One + Mul<Output = S>, Src, Dst> Mul<S> for Transform3D<S, Src, Dst> {
708 +
    type Output = Self;
709 +
710 +
    #[rustfmt::skip]
711 +
    fn mul(self, x: S) -> Self {
712 +
        Transform3D::new(
713 +
            self.x.x * x, self.x.y * x, self.x.z * x, self.x.w * x,
714 +
            self.y.x * x, self.y.y * x, self.y.z * x, self.y.w * x,
715 +
            self.z.x * x, self.z.y * x, self.z.z * x, self.z.w * x,
716 +
            self.w.x * x, self.w.y * x, self.w.z * x, self.w.w * x
717 +
        )
718 +
    }
719 +
}
720 +
721 +
/// An orthographic projection with arbitrary left/right/bottom/top distances
722 +
#[derive(Copy, Clone, Debug, PartialEq)]
723 +
pub struct Ortho<S> {
724 +
    pub left: S,
725 +
    pub right: S,
726 +
    pub bottom: S,
727 +
    pub top: S,
728 +
    pub near: S,
729 +
    pub far: S,
730 +
}
731 +
732 +
impl<S: Float, Src, Dst> From<Ortho<S>> for Transform3D<S, Src, Dst> {
733 +
    #[rustfmt::skip]
734 +
    fn from(ortho: Ortho<S>) -> Self {
735 +
        let m11 = S::TWO / (ortho.right - ortho.left);
736 +
        let m12 = S::ZERO;
737 +
        let m13 = S::ZERO;
738 +
        let m14 = S::ZERO;
739 +
740 +
        let m21 = S::ZERO;
741 +
        let m22 = S::TWO / (ortho.top - ortho.bottom);
742 +
        let m23 = S::ZERO;
743 +
        let m24 = S::ZERO;
744 +
745 +
        let m31 = S::ZERO;
746 +
        let m32 = S::ZERO;
747 +
        let m33 = -S::TWO / (ortho.far - ortho.near);
748 +
        let m34 = S::ZERO;
749 +
750 +
        let m41 = -(ortho.right + ortho.left) / (ortho.right - ortho.left);
751 +
        let m42 = -(ortho.top + ortho.bottom) / (ortho.top - ortho.bottom);
752 +
        let m43 = -(ortho.far + ortho.near) / (ortho.far - ortho.near);
753 +
        let m44 = S::ONE;
754 +
755 +
        Transform3D::new(
756 +
            m11, m12, m13, m14,
757 +
            m21, m22, m23, m24,
758 +
            m31, m32, m33, m34,
759 +
            m41, m42, m43, m44,
760 +
        )
761 +
    }
762 +
}
763 +
764 +
impl<S: One + Zero + Copy> From<Point2D<S>> for Transform3D<S> {
765 +
    #[inline]
766 +
    fn from(other: Point2D<S>) -> Self {
767 +
        Transform3D::from_translation(Vector3D::new(other.x, other.y, S::ZERO))
768 +
    }
769 +
}
770 +
771 +
impl<S: One + Zero + Copy> From<Vector2D<S>> for Transform3D<S> {
772 +
    #[inline]
773 +
    fn from(other: Vector2D<S>) -> Self {
774 +
        Transform3D::from_translation(Vector3D::new(other.x, other.y, S::ZERO))
775 +
    }
776 +
}
777 +
778 +
impl<Src, Dst> From<Transform2D<Src, Dst>> for Transform3D<f32, Src, Dst> {
779 +
    /// Create a 3D transform from the current transform
780 +
    fn from(m: Transform2D<Src, Dst>) -> Self {
781 +
        Transform3D::new_2d(m.m11, m.m12, m.m21, m.m22, m.m31, m.m32)
782 +
    }
783 +
}
ombre/src/platform.rs added +546 -0
1 +
use std::{fmt, io};
2 +
3 +
#[cfg(not(feature = "glfw"))]
4 +
#[path = "platform/dummy.rs"]
5 +
pub mod backend;
6 +
7 +
#[cfg(feature = "glfw")]
8 +
#[path = "platform/glfw.rs"]
9 +
pub mod backend;
10 +
11 +
pub use backend::{Cursor, Events, Window};
12 +
13 +
use crate::gfx::Size;
14 +
15 +
/// Initialize the platform.
16 +
pub fn init(
17 +
    title: &str,
18 +
    w: u32,
19 +
    h: u32,
20 +
    hints: &[WindowHint],
21 +
    context: GraphicsContext,
22 +
) -> io::Result<(backend::Window, backend::Events)> {
23 +
    backend::init(title, w, h, hints, context)
24 +
}
25 +
26 +
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
27 +
pub enum GraphicsContext {
28 +
    None,
29 +
    Gl,
30 +
}
31 +
32 +
/// Window creation hint.
33 +
#[derive(Debug, Copy, Clone)]
34 +
pub enum WindowHint {
35 +
    Resizable(bool),
36 +
    Visible(bool),
37 +
}
38 +
39 +
/// Describes an event from a `Window`.
40 +
#[derive(Clone, Debug, PartialEq)]
41 +
pub enum WindowEvent {
42 +
    /// The size of the window has changed. Contains the client area's new dimensions.
43 +
    Resized(LogicalSize),
44 +
    /// The position of the window has changed. Contains the window's new position.
45 +
    Moved(LogicalPosition),
46 +
    /// The window was minimized.
47 +
    Minimized,
48 +
    /// The window was restored after having been minimized.
49 +
    Restored,
50 +
    /// The window has been requested to close.
51 +
    CloseRequested,
52 +
    /// The window has been destroyed.
53 +
    Destroyed,
54 +
    /// The window received a unicode character.
55 +
    ReceivedCharacter(char, ModifiersState),
56 +
    /// The window gained or lost focus.
57 +
    Focused(bool),
58 +
    /// An event from the keyboard has been received.
59 +
    KeyboardInput(KeyboardInput),
60 +
    /// The cursor has moved on the window.
61 +
    CursorMoved {
62 +
        /// Coords in pixels relative to the top-left corner of the window.
63 +
        position: LogicalPosition,
64 +
    },
65 +
    /// The cursor has entered the window.
66 +
    CursorEntered,
67 +
    /// The cursor has left the window.
68 +
    CursorLeft,
69 +
    /// A mouse button press has been received.
70 +
    MouseInput {
71 +
        state: InputState,
72 +
        button: MouseButton,
73 +
        modifiers: ModifiersState,
74 +
    },
75 +
    /// The mouse wheel or trackpad has been used.
76 +
    Scroll { delta: LogicalDelta },
77 +
    /// The OS or application has requested that the window be redrawn.
78 +
    RedrawRequested,
79 +
    /// There are no more inputs to process, the application can do work.
80 +
    Ready,
81 +
    /// The content scale factor of the window has changed.  For example,
82 +
    /// the window was moved to a higher DPI screen.
83 +
    ScaleFactorChanged(f64),
84 +
    /// No-op event, for events we don't handle.
85 +
    Noop,
86 +
}
87 +
88 +
impl WindowEvent {
89 +
    /// Events that are triggered by user input.
90 +
    pub fn is_input(&self) -> bool {
91 +
        matches!(
92 +
            self,
93 +
            Self::Resized(_)
94 +
                | Self::Moved(_)
95 +
                | Self::Minimized
96 +
                | Self::Restored
97 +
                | Self::CloseRequested
98 +
                | Self::Destroyed
99 +
                | Self::ReceivedCharacter(_, _)
100 +
                | Self::Focused(_)
101 +
                | Self::KeyboardInput(_)
102 +
                | Self::CursorMoved { .. }
103 +
                | Self::CursorEntered
104 +
                | Self::CursorLeft
105 +
                | Self::MouseInput { .. }
106 +
                | Self::ScaleFactorChanged(_)
107 +
        )
108 +
    }
109 +
}
110 +
111 +
/// Describes a keyboard input event.
112 +
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
113 +
pub struct KeyboardInput {
114 +
    pub state: InputState,
115 +
    pub key: Option<Key>,
116 +
    pub modifiers: ModifiersState,
117 +
}
118 +
119 +
impl KeyboardInput {
120 +
    pub fn is_pressed(&self) -> bool {
121 +
        self.state.is_pressed()
122 +
    }
123 +
124 +
    pub fn is_released(&self) -> bool {
125 +
        self.state.is_released()
126 +
    }
127 +
}
128 +
129 +
/// Describes the input state of a key.
130 +
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)]
131 +
pub enum InputState {
132 +
    Pressed,
133 +
    Released,
134 +
    Repeated,
135 +
}
136 +
137 +
impl InputState {
138 +
    pub const fn is_released(&self) -> bool {
139 +
        matches!(self, Self::Released)
140 +
    }
141 +
142 +
    pub const fn is_pressed(&self) -> bool {
143 +
        matches!(self, Self::Pressed)
144 +
    }
145 +
}
146 +
147 +
/// State of all inputs.
148 +
#[derive(Debug)]
149 +
pub struct Inputs {
150 +
    /// Keyboard state.
151 +
    keys: [bool; 256],
152 +
    /// Mouse buttons.
153 +
    mouse: [bool; 256],
154 +
    /// Cursor position.
155 +
    cursor: LogicalPosition,
156 +
}
157 +
158 +
impl Inputs {
159 +
    /// Check if a key is down.
160 +
    pub fn is_key_down(&self, key: Key) -> bool {
161 +
        self.keys[key as usize]
162 +
    }
163 +
164 +
    /// Check if a mouse button is down.
165 +
    pub fn is_mouse_down(&self, button: MouseButton) -> bool {
166 +
        self.mouse[button.to_u8() as usize]
167 +
    }
168 +
169 +
    /// Get logical cursor position.
170 +
    pub fn cursor(&self) -> LogicalPosition {
171 +
        self.cursor
172 +
    }
173 +
}
174 +
175 +
impl Default for Inputs {
176 +
    fn default() -> Self {
177 +
        Self {
178 +
            keys: [false; 256],
179 +
            mouse: [false; 256],
180 +
            cursor: LogicalPosition::new(0., 0.),
181 +
        }
182 +
    }
183 +
}
184 +
185 +
/// Describes a mouse button.
186 +
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)]
187 +
pub enum MouseButton {
188 +
    Left,
189 +
    Right,
190 +
    Middle,
191 +
    Other(u8),
192 +
}
193 +
194 +
impl MouseButton {
195 +
    pub fn to_u8(&self) -> u8 {
196 +
        match self {
197 +
            Self::Left => 0,
198 +
            Self::Right => 1,
199 +
            Self::Middle => 2,
200 +
            Self::Other(n) => *n,
201 +
        }
202 +
    }
203 +
}
204 +
205 +
/// Symbolic name for a keyboard key.
206 +
#[derive(Debug, Hash, Ord, PartialOrd, PartialEq, Eq, Clone, Copy)]
207 +
#[repr(u32)]
208 +
#[rustfmt::skip]
209 +
pub enum Key {
210 +
    // Number keys.
211 +
    Num1, Num2, Num3, Num4, Num5, Num6, Num7, Num8, Num9, Num0,
212 +
213 +
    // Alpha keys.
214 +
    A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
215 +
216 +
    // Arrow keys.
217 +
    Left, Up, Right, Down,
218 +
219 +
    // Control characters.
220 +
    Backspace, Return, Space, Tab,
221 +
    Escape, Insert, Home, Delete, End, PageDown, PageUp,
222 +
223 +
    // Punctuation.
224 +
    Apostrophe, Grave, Caret, Comma, Period, Colon, Semicolon,
225 +
    LBracket, RBracket,
226 +
    Slash, Backslash,
227 +
228 +
    // Modifiers.
229 +
    Alt, Control, Shift,
230 +
231 +
    // Math keys.
232 +
    Equal, Minus,
233 +
234 +
    // Function keys.
235 +
    F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12,
236 +
237 +
    // Key is unknown/unsupported.
238 +
    Unknown,
239 +
}
240 +
241 +
impl From<char> for Key {
242 +
    #[rustfmt::skip]
243 +
    fn from(c: char) -> Self {
244 +
        match c {
245 +
            '0' => Key::Num0, '1' => Key::Num1, '2' => Key::Num2,
246 +
            '3' => Key::Num3, '4' => Key::Num4, '5' => Key::Num5,
247 +
            '6' => Key::Num6, '7' => Key::Num7, '8' => Key::Num8,
248 +
            '9' => Key::Num9,
249 +
250 +
            'a' => Key::A, 'b' => Key::B, 'c' => Key::C, 'd' => Key::D,
251 +
            'e' => Key::E, 'f' => Key::F, 'g' => Key::G, 'h' => Key::H,
252 +
            'i' => Key::I, 'j' => Key::J, 'k' => Key::K, 'l' => Key::L,
253 +
            'm' => Key::M, 'n' => Key::N, 'o' => Key::O, 'p' => Key::P,
254 +
            'q' => Key::Q, 'r' => Key::R, 's' => Key::S, 't' => Key::T,
255 +
            'u' => Key::U, 'v' => Key::V, 'w' => Key::W, 'x' => Key::X,
256 +
            'y' => Key::Y, 'z' => Key::Z,
257 +
258 +
            '/' => Key::Slash, '[' => Key::LBracket, ']' => Key::RBracket,
259 +
            '`' => Key::Grave, ',' => Key::Comma, '.' => Key::Period,
260 +
            '=' => Key::Equal, '-' => Key::Minus, '\'' => Key::Apostrophe,
261 +
            ';' => Key::Semicolon, ':' => Key::Colon, ' ' => Key::Space,
262 +
            '\\' => Key::Backslash,
263 +
            _ => Key::Unknown,
264 +
        }
265 +
    }
266 +
}
267 +
268 +
impl fmt::Display for Key {
269 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270 +
        match self {
271 +
            Key::A => "a".fmt(f),
272 +
            Key::B => "b".fmt(f),
273 +
            Key::C => "c".fmt(f),
274 +
            Key::D => "d".fmt(f),
275 +
            Key::E => "e".fmt(f),
276 +
            Key::F => "f".fmt(f),
277 +
            Key::G => "g".fmt(f),
278 +
            Key::H => "h".fmt(f),
279 +
            Key::I => "i".fmt(f),
280 +
            Key::J => "j".fmt(f),
281 +
            Key::K => "k".fmt(f),
282 +
            Key::L => "l".fmt(f),
283 +
            Key::M => "m".fmt(f),
284 +
            Key::N => "n".fmt(f),
285 +
            Key::O => "o".fmt(f),
286 +
            Key::P => "p".fmt(f),
287 +
            Key::Q => "q".fmt(f),
288 +
            Key::R => "r".fmt(f),
289 +
            Key::S => "s".fmt(f),
290 +
            Key::T => "t".fmt(f),
291 +
            Key::U => "u".fmt(f),
292 +
            Key::V => "v".fmt(f),
293 +
            Key::W => "w".fmt(f),
294 +
            Key::X => "x".fmt(f),
295 +
            Key::Y => "y".fmt(f),
296 +
            Key::Z => "z".fmt(f),
297 +
            Key::Num0 => "0".fmt(f),
298 +
            Key::Num1 => "1".fmt(f),
299 +
            Key::Num2 => "2".fmt(f),
300 +
            Key::Num3 => "3".fmt(f),
301 +
            Key::Num4 => "4".fmt(f),
302 +
            Key::Num5 => "5".fmt(f),
303 +
            Key::Num6 => "6".fmt(f),
304 +
            Key::Num7 => "7".fmt(f),
305 +
            Key::Num8 => "8".fmt(f),
306 +
            Key::Num9 => "9".fmt(f),
307 +
            Key::LBracket => "[".fmt(f),
308 +
            Key::RBracket => "]".fmt(f),
309 +
            Key::Comma => ",".fmt(f),
310 +
            Key::Period => ".".fmt(f),
311 +
            Key::Slash => "/".fmt(f),
312 +
            Key::Backslash => "\\".fmt(f),
313 +
            Key::Apostrophe => "'".fmt(f),
314 +
            Key::Control => "<ctrl>".fmt(f),
315 +
            Key::Shift => "<shift>".fmt(f),
316 +
            Key::Alt => "<alt>".fmt(f),
317 +
            Key::Up => "<up>".fmt(f),
318 +
            Key::Down => "<down>".fmt(f),
319 +
            Key::Left => "<left>".fmt(f),
320 +
            Key::Right => "<right>".fmt(f),
321 +
            Key::Return => "<return>".fmt(f),
322 +
            Key::Backspace => "<backspace>".fmt(f),
323 +
            Key::Space => "<space>".fmt(f),
324 +
            Key::Tab => "<tab>".fmt(f),
325 +
            Key::Escape => "<esc>".fmt(f),
326 +
            Key::Insert => "<insert>".fmt(f),
327 +
            Key::Delete => "<delete>".fmt(f),
328 +
            Key::Home => "<home>".fmt(f),
329 +
            Key::PageUp => "<pgup>".fmt(f),
330 +
            Key::PageDown => "<pgdown>".fmt(f),
331 +
            Key::Grave => "`".fmt(f),
332 +
            Key::Caret => "^".fmt(f),
333 +
            Key::End => "<end>".fmt(f),
334 +
            Key::Colon => ":".fmt(f),
335 +
            Key::Semicolon => ";".fmt(f),
336 +
            Key::Equal => "=".fmt(f),
337 +
            Key::Minus => "-".fmt(f),
338 +
            _ => "???".fmt(f),
339 +
        }
340 +
    }
341 +
}
342 +
343 +
impl Key {
344 +
    pub fn is_modifier(self) -> bool {
345 +
        matches!(self, Key::Alt | Key::Control | Key::Shift)
346 +
    }
347 +
}
348 +
349 +
/// Represents the current state of the keyboard modifiers
350 +
#[derive(Default, Debug, Hash, PartialEq, Eq, Clone, Copy)]
351 +
pub struct ModifiersState {
352 +
    /// The "shift" key
353 +
    pub shift: bool,
354 +
    /// The "control" key
355 +
    pub ctrl: bool,
356 +
    /// The "alt" key
357 +
    pub alt: bool,
358 +
    /// The "meta" key. This is the "windows" key on PC and "command" key on Mac.
359 +
    pub meta: bool,
360 +
}
361 +
362 +
impl fmt::Display for ModifiersState {
363 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
364 +
        let mut s = String::new();
365 +
        if self.ctrl {
366 +
            s.push_str("<ctrl>");
367 +
        }
368 +
        if self.alt {
369 +
            s.push_str("<alt>");
370 +
        }
371 +
        if self.meta {
372 +
            s.push_str("<meta>");
373 +
        }
374 +
        if self.shift {
375 +
            s.push_str("<shift>");
376 +
        }
377 +
        s.fmt(f)
378 +
    }
379 +
}
380 +
381 +
/// A delta represented in logical pixels.
382 +
#[derive(Debug, Copy, Clone, PartialEq)]
383 +
pub struct LogicalDelta {
384 +
    pub x: f64,
385 +
    pub y: f64,
386 +
}
387 +
388 +
impl From<(f64, f64)> for LogicalDelta {
389 +
    fn from((x, y): (f64, f64)) -> Self {
390 +
        Self { x, y }
391 +
    }
392 +
}
393 +
/// A position represented in logical pixels.
394 +
#[derive(Debug, Copy, Clone, PartialEq)]
395 +
pub struct LogicalPosition {
396 +
    pub x: f64,
397 +
    pub y: f64,
398 +
}
399 +
400 +
impl LogicalPosition {
401 +
    pub fn new(x: f64, y: f64) -> Self {
402 +
        LogicalPosition { x, y }
403 +
    }
404 +
405 +
    pub fn from_physical<T: Into<PhysicalPosition>>(physical: T, scale_factor: f64) -> Self {
406 +
        physical.into().to_logical(self::pixel_ratio(scale_factor))
407 +
    }
408 +
409 +
    pub fn to_physical(self, scale_factor: f64) -> PhysicalPosition {
410 +
        let x = self.x * self::pixel_ratio(scale_factor);
411 +
        let y = self.y * self::pixel_ratio(scale_factor);
412 +
413 +
        PhysicalPosition::new(x, y)
414 +
    }
415 +
}
416 +
417 +
impl From<(f64, f64)> for LogicalPosition {
418 +
    fn from((x, y): (f64, f64)) -> Self {
419 +
        Self::new(x, y)
420 +
    }
421 +
}
422 +
423 +
/// A position represented in physical pixels.
424 +
#[derive(Debug, Copy, Clone, PartialEq)]
425 +
pub struct PhysicalPosition {
426 +
    pub x: f64,
427 +
    pub y: f64,
428 +
}
429 +
430 +
impl PhysicalPosition {
431 +
    pub fn new(x: f64, y: f64) -> Self {
432 +
        PhysicalPosition { x, y }
433 +
    }
434 +
435 +
    pub fn from_logical<T: Into<LogicalPosition>>(logical: T, scale_factor: f64) -> Self {
436 +
        logical.into().to_physical(self::pixel_ratio(scale_factor))
437 +
    }
438 +
439 +
    pub fn to_logical(self, scale_factor: f64) -> LogicalPosition {
440 +
        let x = self.x / self::pixel_ratio(scale_factor);
441 +
        let y = self.y / self::pixel_ratio(scale_factor);
442 +
        LogicalPosition::new(x, y)
443 +
    }
444 +
}
445 +
446 +
/// A size represented in logical pixels.
447 +
#[derive(Debug, Copy, Clone, PartialEq)]
448 +
pub struct LogicalSize {
449 +
    pub width: f64,
450 +
    pub height: f64,
451 +
}
452 +
453 +
impl LogicalSize {
454 +
    pub const fn new(width: f64, height: f64) -> Self {
455 +
        LogicalSize { width, height }
456 +
    }
457 +
458 +
    pub fn from_physical<T: Into<PhysicalSize>>(physical: T, scale_factor: f64) -> Self {
459 +
        physical.into().to_logical(self::pixel_ratio(scale_factor))
460 +
    }
461 +
462 +
    pub fn to_physical(self, scale_factor: f64) -> PhysicalSize {
463 +
        let width = self.width * self::pixel_ratio(scale_factor);
464 +
        let height = self.height * self::pixel_ratio(scale_factor);
465 +
        PhysicalSize::new(width, height)
466 +
    }
467 +
468 +
    pub fn is_zero(&self) -> bool {
469 +
        self.width < 1. || self.height < 1.
470 +
    }
471 +
}
472 +
473 +
impl fmt::Display for LogicalSize {
474 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
475 +
        Size::new(self.width, self.height).fmt(f)
476 +
    }
477 +
}
478 +
479 +
impl From<(u32, u32)> for LogicalSize {
480 +
    fn from((width, height): (u32, u32)) -> Self {
481 +
        Self::new(width as f64, height as f64)
482 +
    }
483 +
}
484 +
485 +
impl From<LogicalSize> for (u32, u32) {
486 +
    /// Note that this rounds instead of truncating.
487 +
    fn from(other: LogicalSize) -> (u32, u32) {
488 +
        (other.width.round() as _, other.height.round() as _)
489 +
    }
490 +
}
491 +
492 +
/// A size represented in physical pixels.
493 +
#[derive(Debug, Copy, Clone, PartialEq)]
494 +
pub struct PhysicalSize {
495 +
    pub width: f64,
496 +
    pub height: f64,
497 +
}
498 +
499 +
impl PhysicalSize {
500 +
    pub fn new(width: f64, height: f64) -> Self {
501 +
        PhysicalSize { width, height }
502 +
    }
503 +
504 +
    pub fn from_logical<T: Into<LogicalSize>>(logical: T, scale_factor: f64) -> Self {
505 +
        logical.into().to_physical(self::pixel_ratio(scale_factor))
506 +
    }
507 +
508 +
    pub fn to_logical(self, scale_factor: f64) -> LogicalSize {
509 +
        let width = self.width / self::pixel_ratio(scale_factor);
510 +
        let height = self.height / self::pixel_ratio(scale_factor);
511 +
        LogicalSize::new(width, height)
512 +
    }
513 +
}
514 +
515 +
impl From<(u32, u32)> for PhysicalSize {
516 +
    fn from((width, height): (u32, u32)) -> Self {
517 +
        Self::new(width as f64, height as f64)
518 +
    }
519 +
}
520 +
521 +
impl From<PhysicalSize> for (u32, u32) {
522 +
    /// Note that this rounds instead of truncating.
523 +
    fn from(other: PhysicalSize) -> (u32, u32) {
524 +
        (other.width.round() as _, other.height.round() as _)
525 +
    }
526 +
}
527 +
528 +
/// The ratio between screen coordinates and pixels, given the
529 +
/// content scale.
530 +
/// On macOS, screen coordinates don't map 1:1 with pixels. Hence,
531 +
/// our ratio between screen coordinates and pixels is whatever
532 +
/// the scaling factor is, which is always `2.0` on modern hardware.
533 +
#[cfg(target_os = "macos")]
534 +
pub fn pixel_ratio(scale_factor: f64) -> f64 {
535 +
    scale_factor
536 +
}
537 +
538 +
/// The ratio between screen coordinates and pixels, given the
539 +
/// content scale.
540 +
/// On Linux and Windows, screen coordinates always map 1:1 with pixels.
541 +
/// No matter the DPI settings and display, we always want to map a screen
542 +
/// coordinate with a single pixel.
543 +
#[cfg(not(target_os = "macos"))]
544 +
pub fn pixel_ratio(_scale_factor: f64) -> f64 {
545 +
    1.0
546 +
}
ombre/src/platform/dummy.rs added +101 -0
1 +
use std::io;
2 +
3 +
use crate::bytes::AsBytes;
4 +
use crate::math::{Point2D, Size};
5 +
use crate::platform::{GraphicsContext, Inputs, LogicalSize, WindowEvent, WindowHint};
6 +
7 +
pub struct DummyWindow;
8 +
9 +
#[derive(Debug)]
10 +
pub struct Cursor {}
11 +
12 +
impl Cursor {
13 +
    pub fn create<T: AsBytes>(_pixels: &T, _size: Size<u32>, _origin: Point2D<u32>) -> Self {
14 +
        unreachable!()
15 +
    }
16 +
}
17 +
18 +
pub struct Events {
19 +
    #[allow(dead_code)]
20 +
    handle: (),
21 +
}
22 +
23 +
impl Events {
24 +
    pub fn wait(&mut self) {}
25 +
26 +
    pub fn wait_timeout(&mut self, _timeout: std::time::Duration) {}
27 +
28 +
    pub fn poll(&mut self) {}
29 +
30 +
    pub fn flush(&self) -> impl Iterator<Item = WindowEvent> {
31 +
        std::iter::empty::<WindowEvent>()
32 +
    }
33 +
}
34 +
35 +
pub struct Window {
36 +
    handle: DummyWindow,
37 +
}
38 +
39 +
impl Window {
40 +
    pub fn handle(&self) -> &DummyWindow {
41 +
        &self.handle
42 +
    }
43 +
44 +
    pub fn get_proc_address(&mut self, _s: &str) -> *const std::ffi::c_void {
45 +
        unreachable!()
46 +
    }
47 +
48 +
    pub fn get_cursor_pos(&self) -> (f64, f64) {
49 +
        unreachable!()
50 +
    }
51 +
52 +
    pub fn inputs(&self) -> Inputs {
53 +
        Inputs::default()
54 +
    }
55 +
56 +
    pub fn set_cursor(&mut self, _cursor: Option<Cursor>) -> Option<Cursor> {
57 +
        unreachable!()
58 +
    }
59 +
60 +
    pub fn set_cursor_visible(&mut self, _visible: bool) {
61 +
        unreachable!()
62 +
    }
63 +
64 +
    pub fn scale_factor(&self) -> f64 {
65 +
        unreachable!()
66 +
    }
67 +
68 +
    pub fn size(&self) -> LogicalSize {
69 +
        unreachable!()
70 +
    }
71 +
72 +
    pub fn is_focused(&self) -> bool {
73 +
        true
74 +
    }
75 +
76 +
    pub fn is_open(&self) -> bool {
77 +
        true
78 +
    }
79 +
80 +
    pub fn present(&self) {}
81 +
82 +
    pub fn redraw(&mut self) {}
83 +
84 +
    pub fn clipboard(&self) -> Option<String> {
85 +
        None
86 +
    }
87 +
88 +
    pub(crate) fn is_ready(&self) -> bool {
89 +
        true
90 +
    }
91 +
}
92 +
93 +
pub fn init(
94 +
    _title: &str,
95 +
    _w: u32,
96 +
    _h: u32,
97 +
    _hints: &[WindowHint],
98 +
    _context: GraphicsContext,
99 +
) -> io::Result<(Window, Events)> {
100 +
    panic!("`dummy` platform initialized");
101 +
}
ombre/src/platform/glfw.rs added +368 -0
1 +
//! GLFW platform backend.
2 +
use std::{io, time};
3 +
4 +
use glfw::Context;
5 +
use log::*;
6 +
7 +
use crate::{
8 +
    math::{Point2D, Size},
9 +
    platform::{
10 +
        GraphicsContext, InputState, Inputs, Key, KeyboardInput, LogicalDelta, LogicalPosition,
11 +
        LogicalSize, ModifiersState, MouseButton, WindowEvent, WindowHint,
12 +
    },
13 +
};
14 +
15 +
/// Initialize a context with GLFW.
16 +
pub fn init(
17 +
    title: &str,
18 +
    w: u32,
19 +
    h: u32,
20 +
    hints: &[WindowHint],
21 +
    context: GraphicsContext,
22 +
) -> io::Result<(Window, Events)> {
23 +
    let mut glfw = glfw::init(|_, desc| {
24 +
        error!("glfw: {desc}");
25 +
    })
26 +
    .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
27 +
28 +
    glfw.window_hint(glfw::WindowHint::Resizable(true));
29 +
    glfw.window_hint(glfw::WindowHint::Visible(true));
30 +
    glfw.window_hint(glfw::WindowHint::Focused(true));
31 +
    glfw.window_hint(glfw::WindowHint::RefreshRate(None));
32 +
    glfw.window_hint(glfw::WindowHint::ScaleToMonitor(true));
33 +
    glfw.window_hint(glfw::WindowHint::DoubleBuffer(true));
34 +
35 +
    match context {
36 +
        GraphicsContext::None => {
37 +
            glfw.window_hint(glfw::WindowHint::ClientApi(glfw::ClientApiHint::NoApi));
38 +
        }
39 +
        GraphicsContext::Gl => {
40 +
            glfw.window_hint(glfw::WindowHint::ClientApi(glfw::ClientApiHint::OpenGl));
41 +
            glfw.window_hint(glfw::WindowHint::ContextVersion(3, 3));
42 +
            glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true));
43 +
            glfw.window_hint(glfw::WindowHint::OpenGlProfile(
44 +
                glfw::OpenGlProfileHint::Core,
45 +
            ));
46 +
        }
47 +
    }
48 +
49 +
    for hint in hints {
50 +
        glfw.window_hint((*hint).into());
51 +
    }
52 +
53 +
    let (mut window, events) = glfw
54 +
        .create_window(w, h, title, glfw::WindowMode::Windowed)
55 +
        .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "glfw: error creating window"))?;
56 +
57 +
    window.make_current();
58 +
    window.set_all_polling(true);
59 +
60 +
    glfw.set_swap_interval(glfw::SwapInterval::None);
61 +
62 +
    Ok((
63 +
        Window {
64 +
            title: title.to_owned(),
65 +
            handle: window,
66 +
            context,
67 +
            redraw: true,
68 +
        },
69 +
        Events {
70 +
            handle: events,
71 +
            glfw,
72 +
        },
73 +
    ))
74 +
}
75 +
76 +
/// Hardware cursor.
77 +
#[derive(Debug)]
78 +
pub struct Cursor {
79 +
    raw: glfw::Cursor,
80 +
}
81 +
82 +
impl Cursor {
83 +
    /// Create a new cursor from an image, size and origin.
84 +
    pub fn create<T: AsRef<[u32]>, U>(pixels: T, size: Size<u32>, origin: Point2D<u32, U>) -> Self {
85 +
        let bytes = pixels.as_ref();
86 +
        let raw = glfw::Cursor::create_from_pixels(
87 +
            glfw::PixelImage {
88 +
                width: size.w,
89 +
                height: size.h,
90 +
                pixels: bytes.to_vec(),
91 +
            },
92 +
            origin.x,
93 +
            origin.y,
94 +
        );
95 +
        Self { raw }
96 +
    }
97 +
}
98 +
99 +
/// Platform events.
100 +
pub struct Events {
101 +
    handle: glfw::GlfwReceiver<(f64, glfw::WindowEvent)>,
102 +
    glfw: glfw::Glfw,
103 +
}
104 +
105 +
impl Events {
106 +
    pub fn wait(&mut self) {
107 +
        self.glfw.wait_events();
108 +
    }
109 +
110 +
    pub fn wait_timeout(&mut self, timeout: time::Duration) {
111 +
        self.glfw.wait_events_timeout(timeout.as_secs_f64());
112 +
    }
113 +
114 +
    pub fn poll(&mut self) {
115 +
        self.glfw.poll_events();
116 +
    }
117 +
118 +
    pub fn flush(&self) -> impl Iterator<Item = WindowEvent> + '_ {
119 +
        glfw::flush_messages(&self.handle).map(|(_, e)| e.into())
120 +
    }
121 +
}
122 +
123 +
/// Window state.
124 +
pub struct Window {
125 +
    title: String,
126 +
    handle: glfw::PWindow,
127 +
    context: GraphicsContext,
128 +
    redraw: bool,
129 +
}
130 +
131 +
impl Window {
132 +
    pub fn handle(&self) -> &glfw::Window {
133 +
        &self.handle
134 +
    }
135 +
136 +
    pub fn get_proc_address(&mut self, s: &str) -> *const std::ffi::c_void {
137 +
        self.handle.get_proc_address(s)
138 +
    }
139 +
140 +
    pub fn set_cursor_visible(&mut self, visible: bool) {
141 +
        self.handle.set_cursor_mode(if visible {
142 +
            glfw::CursorMode::Normal
143 +
        } else {
144 +
            glfw::CursorMode::Hidden
145 +
        });
146 +
    }
147 +
148 +
    pub fn set_cursor(&mut self, cursor: Option<Cursor>) -> Option<Cursor> {
149 +
        self.handle
150 +
            .set_cursor(cursor.map(|c| c.raw))
151 +
            .map(|raw| Cursor { raw })
152 +
    }
153 +
154 +
    pub fn set_title(&mut self, title: &str) {
155 +
        self.handle.set_title(title)
156 +
    }
157 +
158 +
    pub fn get_title(&self) -> &str {
159 +
        &self.title
160 +
    }
161 +
162 +
    pub fn get_cursor_pos(&self) -> LogicalPosition {
163 +
        self.handle.get_cursor_pos().into()
164 +
    }
165 +
166 +
    /// Get input state.
167 +
    pub fn inputs(&self) -> Inputs {
168 +
        let mut state = Inputs::default();
169 +
170 +
        // Poll all keyboard keys.
171 +
        for key in 0..=glfw::ffi::KEY_LAST {
172 +
            let glfw_key = unsafe { std::mem::transmute::<i32, glfw::Key>(key) };
173 +
            let index = Key::from(glfw_key) as usize;
174 +
175 +
            state.keys[index] = self.handle.get_key(glfw_key) == glfw::Action::Press;
176 +
        }
177 +
        // Poll all mouse buttons.
178 +
        for button in 0..=glfw::ffi::MOUSE_BUTTON_LAST {
179 +
            let glfw_button = unsafe { std::mem::transmute::<i32, glfw::MouseButton>(button) };
180 +
            let index = MouseButton::from(glfw_button).to_u8() as usize;
181 +
182 +
            state.mouse[index] = self.handle.get_mouse_button(glfw_button) == glfw::Action::Press;
183 +
        }
184 +
        state.cursor = LogicalPosition::from(self.handle.get_cursor_pos());
185 +
        state
186 +
    }
187 +
188 +
    pub fn scale_factor(&self) -> f64 {
189 +
        let (x, _) = self.handle.get_content_scale();
190 +
        x as f64
191 +
    }
192 +
193 +
    pub fn size(&self) -> LogicalSize {
194 +
        let (w, h) = self.handle.get_size();
195 +
        LogicalSize::new(w as f64, h as f64)
196 +
    }
197 +
198 +
    pub fn present(&mut self) {
199 +
        if self.context == GraphicsContext::Gl {
200 +
            self.handle.swap_buffers();
201 +
        }
202 +
        self.redraw = false;
203 +
    }
204 +
205 +
    pub fn is_open(&self) -> bool {
206 +
        !self.handle.should_close()
207 +
    }
208 +
209 +
    pub fn is_focused(&self) -> bool {
210 +
        self.handle.is_focused()
211 +
    }
212 +
213 +
    pub fn redraw(&mut self) {
214 +
        self.redraw = true;
215 +
        self.handle.post_empty_event();
216 +
    }
217 +
218 +
    pub fn clipboard(&self) -> Option<String> {
219 +
        self.handle.get_clipboard_string()
220 +
    }
221 +
222 +
    pub(crate) fn is_ready(&self) -> bool {
223 +
        self.redraw
224 +
    }
225 +
}
226 +
227 +
impl From<WindowHint> for glfw::WindowHint {
228 +
    fn from(other: WindowHint) -> glfw::WindowHint {
229 +
        match other {
230 +
            WindowHint::Resizable(b) => glfw::WindowHint::Resizable(b),
231 +
            WindowHint::Visible(b) => glfw::WindowHint::Visible(b),
232 +
        }
233 +
    }
234 +
}
235 +
236 +
impl From<glfw::MouseButton> for MouseButton {
237 +
    fn from(button: glfw::MouseButton) -> Self {
238 +
        match button {
239 +
            glfw::MouseButton::Button1 => MouseButton::Left,
240 +
            glfw::MouseButton::Button2 => MouseButton::Right,
241 +
            glfw::MouseButton::Button3 => MouseButton::Middle,
242 +
            glfw::MouseButton::Button4 => MouseButton::Other(3),
243 +
            glfw::MouseButton::Button5 => MouseButton::Other(4),
244 +
            glfw::MouseButton::Button6 => MouseButton::Other(5),
245 +
            glfw::MouseButton::Button7 => MouseButton::Other(6),
246 +
            glfw::MouseButton::Button8 => MouseButton::Other(7),
247 +
        }
248 +
    }
249 +
}
250 +
251 +
impl From<glfw::Action> for InputState {
252 +
    fn from(state: glfw::Action) -> Self {
253 +
        match state {
254 +
            glfw::Action::Press => InputState::Pressed,
255 +
            glfw::Action::Release => InputState::Released,
256 +
            glfw::Action::Repeat => InputState::Repeated,
257 +
        }
258 +
    }
259 +
}
260 +
261 +
impl From<glfw::WindowEvent> for WindowEvent {
262 +
    fn from(event: glfw::WindowEvent) -> Self {
263 +
        use glfw::WindowEvent as Glfw;
264 +
265 +
        match event {
266 +
            // We care about logical ("screen") coordinates, so we
267 +
            // use this event instead of the framebuffer size event.
268 +
            Glfw::Size(w, h) => WindowEvent::Resized(LogicalSize::new(w as f64, h as f64)),
269 +
            Glfw::FramebufferSize(_, _) => WindowEvent::Noop,
270 +
            Glfw::Iconify(true) => WindowEvent::Minimized,
271 +
            Glfw::Iconify(false) => WindowEvent::Restored,
272 +
            Glfw::Close => WindowEvent::CloseRequested,
273 +
            Glfw::Refresh => WindowEvent::RedrawRequested,
274 +
            Glfw::Pos(x, y) => WindowEvent::Moved(LogicalPosition::new(x as f64, y as f64)),
275 +
            Glfw::MouseButton(button, action, modifiers) => WindowEvent::MouseInput {
276 +
                state: action.into(),
277 +
                button: button.into(),
278 +
                modifiers: modifiers.into(),
279 +
            },
280 +
            Glfw::Scroll(x, y) => WindowEvent::Scroll {
281 +
                delta: LogicalDelta { x, y },
282 +
            },
283 +
            Glfw::CursorEnter(true) => WindowEvent::CursorEntered,
284 +
            Glfw::CursorEnter(false) => WindowEvent::CursorLeft,
285 +
            Glfw::CursorPos(x, y) => WindowEvent::CursorMoved {
286 +
                position: LogicalPosition::new(x, y),
287 +
            },
288 +
            Glfw::CharModifiers(c, mods) => WindowEvent::ReceivedCharacter(c, mods.into()),
289 +
            Glfw::Key(key, _, action, modifiers) => WindowEvent::KeyboardInput(KeyboardInput {
290 +
                key: Some(key.into()),
291 +
                state: action.into(),
292 +
                modifiers: modifiers.into(),
293 +
            }),
294 +
            Glfw::Focus(b) => WindowEvent::Focused(b),
295 +
            Glfw::ContentScale(x, y) => {
296 +
                if (x - y).abs() > 0.1 {
297 +
                    warn!("glfw: content scale isn't uniform: {} x {}", x, y);
298 +
                }
299 +
                WindowEvent::ScaleFactorChanged(x as f64)
300 +
            }
301 +
            _ => WindowEvent::Noop,
302 +
        }
303 +
    }
304 +
}
305 +
306 +
impl From<glfw::Key> for Key {
307 +
    fn from(k: glfw::Key) -> Self {
308 +
        use glfw::Key as Glfw;
309 +
310 +
        match k {
311 +
            Glfw::Escape => Key::Escape,
312 +
            Glfw::Insert => Key::Insert,
313 +
            Glfw::Home => Key::Home,
314 +
            Glfw::Delete => Key::Delete,
315 +
            Glfw::End => Key::End,
316 +
            Glfw::PageDown => Key::PageDown,
317 +
            Glfw::PageUp => Key::PageUp,
318 +
            Glfw::Left => Key::Left,
319 +
            Glfw::Up => Key::Up,
320 +
            Glfw::Right => Key::Right,
321 +
            Glfw::Down => Key::Down,
322 +
            Glfw::Backspace => Key::Backspace,
323 +
            Glfw::Enter => Key::Return,
324 +
            Glfw::Space => Key::Space,
325 +
            Glfw::LeftAlt => Key::Alt,
326 +
            Glfw::LeftBracket => Key::LBracket,
327 +
            Glfw::LeftControl => Key::Control,
328 +
            Glfw::LeftShift => Key::Shift,
329 +
            Glfw::RightAlt => Key::Alt,
330 +
            Glfw::RightBracket => Key::RBracket,
331 +
            Glfw::RightControl => Key::Control,
332 +
            Glfw::RightShift => Key::Shift,
333 +
            Glfw::Tab => Key::Tab,
334 +
            Glfw::F1 => Key::F1,
335 +
            Glfw::F2 => Key::F2,
336 +
            Glfw::F3 => Key::F3,
337 +
            Glfw::F4 => Key::F4,
338 +
            Glfw::F5 => Key::F5,
339 +
            Glfw::F6 => Key::F6,
340 +
            Glfw::F7 => Key::F7,
341 +
            Glfw::F8 => Key::F8,
342 +
            Glfw::F9 => Key::F9,
343 +
            Glfw::F10 => Key::F10,
344 +
            Glfw::F11 => Key::F11,
345 +
            Glfw::F12 => Key::F12,
346 +
347 +
            _ => {
348 +
                if let Some(sym) = k.get_name() {
349 +
                    if let Some(c) = sym.chars().next() {
350 +
                        return Key::from(c);
351 +
                    }
352 +
                }
353 +
                Key::Unknown
354 +
            }
355 +
        }
356 +
    }
357 +
}
358 +
359 +
impl From<glfw::Modifiers> for ModifiersState {
360 +
    fn from(mods: glfw::Modifiers) -> Self {
361 +
        Self {
362 +
            shift: mods.contains(glfw::Modifiers::Shift),
363 +
            ctrl: mods.contains(glfw::Modifiers::Control),
364 +
            alt: mods.contains(glfw::Modifiers::Alt),
365 +
            meta: mods.contains(glfw::Modifiers::Super),
366 +
        }
367 +
    }
368 +
}
ombre/src/rng.rs added +402 -0
1 +
//! Copyright (c) Simon Heath, some quality nuggets from their `oorandom` crate
2 +
//! Copyright (c) Wang Yi, WyRand algorithm
3 +
//! Copyright (c) The `fastrand` authors, various tidbits
4 +
use std::collections::hash_map::DefaultHasher;
5 +
use std::hash::{Hash, Hasher};
6 +
use std::ops::{Add, Bound, RangeBounds, Sub};
7 +
use std::time::Instant;
8 +
use std::{fmt, thread};
9 +
10 +
use crate::math::traits::Integer;
11 +
use crate::math::{Bounded, One};
12 +
13 +
/// Trait for sources of entropy.
14 +
pub trait Entropy {
15 +
    fn gen_u64(&mut self) -> u64;
16 +
17 +
    #[inline]
18 +
    fn gen_u32(&mut self) -> u32 {
19 +
        self.gen_u64() as u32
20 +
    }
21 +
}
22 +
23 +
/// A type that can be randomly generated
24 +
/// A probability distribution that can generate random values.
25 +
/// Implementations define how to sample values of type T from a random source.
26 +
pub trait Distribution<T> {
27 +
    /// Generates a random value from this distribution using the given entropy source.
28 +
    fn sample<R: Entropy>(&self, rng: &mut R) -> T;
29 +
}
30 +
31 +
extern "C" {
32 +
    fn getrandom(buf: *mut u8, buflen: usize, flags: u32) -> isize;
33 +
}
34 +
35 +
/// Wrapper around the C `getrandom` function.
36 +
/// Returns `true` if the supplied buffer was filled with random bytes.
37 +
fn random(out: &mut [u8]) -> bool {
38 +
    let flags = 0x0001; // GRND_NONBLOCK.
39 +
    unsafe { getrandom(out.as_mut_ptr(), out.len(), flags) as usize == out.len() }
40 +
}
41 +
42 +
/// The main RNG using WyRand algorithm
43 +
#[derive(Debug, Clone)]
44 +
pub struct Rng {
45 +
    state: u64,
46 +
}
47 +
48 +
impl Default for Rng {
49 +
    fn default() -> Self {
50 +
        Self::new()
51 +
    }
52 +
}
53 +
54 +
impl Rng {
55 +
    #[inline]
56 +
    pub fn new() -> Self {
57 +
        let mut bytes = [0u8; 8];
58 +
        let seed = if random(&mut bytes) {
59 +
            u64::from_ne_bytes(bytes)
60 +
        } else {
61 +
            let mut hasher = DefaultHasher::new();
62 +
            Instant::now().hash(&mut hasher);
63 +
            thread::current().id().hash(&mut hasher);
64 +
65 +
            hasher.finish()
66 +
        };
67 +
        Self::with_seed(seed)
68 +
    }
69 +
70 +
    pub fn sample<T>(&mut self, dist: &impl Distribution<T>) -> T {
71 +
        dist.sample(self)
72 +
    }
73 +
74 +
    #[inline]
75 +
    pub fn with_seed(seed: u64) -> Self {
76 +
        Self { state: seed }
77 +
    }
78 +
79 +
    pub fn probability(&mut self) -> f64 {
80 +
        const PRECISION: u32 = f64::MANTISSA_DIGITS + 1;
81 +
        const MANTISSA_SCALE: f64 = 1.0 / ((1u64 << PRECISION) as f64);
82 +
83 +
        let mut r = self.gen_u64();
84 +
85 +
        r >>= 64 - PRECISION;
86 +
        r as f64 * MANTISSA_SCALE
87 +
    }
88 +
89 +
    #[inline]
90 +
    pub fn gen<T, R>(&mut self, range: R) -> T
91 +
    where
92 +
        T: Copy + PartialOrd + Sub<Output = T> + Add<Output = T> + Bounded + One + fmt::Debug,
93 +
        R: RangeBounds<T>,
94 +
        Uniform<T>: Distribution<T>,
95 +
    {
96 +
        Uniform::from_range(range).sample(self)
97 +
    }
98 +
99 +
    #[inline]
100 +
    pub fn flip(&mut self) -> bool {
101 +
        self.gen_u32() & 1 == 1
102 +
    }
103 +
104 +
    /// Clones the generator by deterministically deriving a new generator based on the initial
105 +
    /// seed.
106 +
    ///
107 +
    /// This function can be used to create a new generator that is a "spinoff" of the old
108 +
    /// generator. The new generator will not produce the same sequence of values as the
109 +
    /// old generator.
110 +
    #[inline]
111 +
    #[must_use]
112 +
    pub fn fork(&mut self) -> Self {
113 +
        Rng::with_seed(self.gen_u64())
114 +
    }
115 +
116 +
    #[inline]
117 +
    pub fn shuffle<T>(&mut self, slice: &mut [T]) {
118 +
        for i in 1..slice.len() {
119 +
            slice.swap(i, self.gen(..=i));
120 +
        }
121 +
    }
122 +
123 +
    pub fn fill(&mut self, slice: &mut [u8]) {
124 +
        // We fill the slice by chunks of 8 bytes, or one block of
125 +
        // WyRand output per new state.
126 +
        let mut chunks = slice.chunks_exact_mut(core::mem::size_of::<u64>());
127 +
        for chunk in chunks.by_ref() {
128 +
            let n = self.gen_u64().to_ne_bytes();
129 +
            // Safe because the chunks are always 8 bytes exactly.
130 +
            chunk.copy_from_slice(&n);
131 +
        }
132 +
133 +
        // Any remainder will always be less than 8 bytes.
134 +
        let remainder = chunks.into_remainder();
135 +
        if !remainder.is_empty() {
136 +
            // Generate one last block of 8 bytes of entropy
137 +
            let n = self.gen_u64().to_ne_bytes();
138 +
            // Use the remaining length to copy from block
139 +
            remainder.copy_from_slice(&n[..remainder.len()]);
140 +
        }
141 +
    }
142 +
143 +
    /// Select a random element from a slice
144 +
    #[inline]
145 +
    pub fn choose<'a, T>(&mut self, slice: &'a [T]) -> Option<&'a T> {
146 +
        if slice.is_empty() {
147 +
            None
148 +
        } else {
149 +
            Some(&slice[self.gen(..slice.len())])
150 +
        }
151 +
    }
152 +
153 +
    /// Select a random mutable element from a slice
154 +
    #[inline]
155 +
    pub fn choose_mut<'a, T>(&mut self, slice: &'a mut [T]) -> Option<&'a mut T> {
156 +
        if slice.is_empty() {
157 +
            None
158 +
        } else {
159 +
            let idx = self.gen(0..slice.len());
160 +
            Some(&mut slice[idx])
161 +
        }
162 +
    }
163 +
}
164 +
165 +
impl Entropy for Rng {
166 +
    #[inline(always)]
167 +
    fn gen_u64(&mut self) -> u64 {
168 +
        self.state = self.state.wrapping_add(0x2d35_8dcc_aa6c_78a5);
169 +
        let t = u128::from(self.state) * u128::from(self.state ^ 0x8bb8_4b93_962e_acc9);
170 +
        (t as u64) ^ (t >> 64) as u64
171 +
    }
172 +
}
173 +
174 +
/// Uniform distribution over a range
175 +
#[derive(Debug, Clone, Copy)]
176 +
pub struct Uniform<T> {
177 +
    low: T,
178 +
    high: T,
179 +
}
180 +
181 +
impl<T> Uniform<T> {
182 +
    #[inline]
183 +
    pub const fn new(low: T, high: T) -> Self {
184 +
        Self { low, high }
185 +
    }
186 +
}
187 +
188 +
impl<T: Bounded> Uniform<T> {
189 +
    #[inline]
190 +
    pub const fn full() -> Self {
191 +
        Self::new(T::MIN, T::MAX)
192 +
    }
193 +
194 +
    #[inline]
195 +
    pub fn from_range<R: RangeBounds<T>>(range: R) -> Self
196 +
    where
197 +
        T: Copy + PartialOrd + Add<Output = T> + Sub<Output = T> + fmt::Debug + One,
198 +
    {
199 +
        let low = match range.start_bound() {
200 +
            Bound::Unbounded => T::MIN,
201 +
            Bound::Included(&x) => x,
202 +
            Bound::Excluded(&x) if x < T::MAX => x + T::ONE,
203 +
            Bound::Excluded(_) => panic!(
204 +
                "Uniform::from_range: empty range {:?}..{:?}",
205 +
                range.start_bound(),
206 +
                range.end_bound()
207 +
            ),
208 +
        };
209 +
        let high = match range.end_bound() {
210 +
            Bound::Unbounded => T::MAX,
211 +
            Bound::Included(&x) => x,
212 +
            Bound::Excluded(&x) if x > T::MIN => x - T::ONE,
213 +
            Bound::Excluded(_) => panic!(
214 +
                "Uniform::from_range: empty range {:?}..{:?}",
215 +
                range.start_bound(),
216 +
                range.end_bound()
217 +
            ),
218 +
        };
219 +
        assert!(
220 +
            low <= high,
221 +
            "Uniform::from_range: empty range {:?}..{:?}",
222 +
            range.start_bound(),
223 +
            range.end_bound()
224 +
        );
225 +
        Self { low, high }
226 +
    }
227 +
}
228 +
229 +
impl<T> Distribution<T> for Uniform<T>
230 +
where
231 +
    T: Copy + PartialOrd + Integer,
232 +
{
233 +
    fn sample<R: Entropy>(&self, rng: &mut R) -> T {
234 +
        let low = self.low;
235 +
        let high = self.high;
236 +
        let len = high - low;
237 +
238 +
        if low == T::MIN && high == T::MAX {
239 +
            T::from_u64(rng.gen_u64())
240 +
        } else {
241 +
            low + T::from_u64(rng.gen_u64()).rem(len)
242 +
        }
243 +
    }
244 +
}
245 +
246 +
#[cfg(test)]
247 +
mod tests {
248 +
    use super::*;
249 +
    use crate::math::traits::Integer;
250 +
251 +
    #[allow(dead_code)]
252 +
    fn distribution<T: Integer + std::fmt::Debug>(
253 +
        rng: &mut Rng,
254 +
        range: std::ops::Range<T>,
255 +
        samples: usize,
256 +
        buckets: usize,
257 +
    ) {
258 +
        let mut counts = vec![0; buckets];
259 +
        let bucket_size = (range.end - range.start).as_f64() / buckets as f64;
260 +
261 +
        for _ in 0..samples {
262 +
            let value = rng.gen(range.clone());
263 +
            let bucket = ((value - range.start).as_f64() / bucket_size) as usize;
264 +
            counts[bucket.min(buckets - 1)] += 1;
265 +
        }
266 +
267 +
        let expected = samples as f64 / buckets as f64;
268 +
        for (i, &count) in counts.iter().enumerate() {
269 +
            let deviation = (count as f64 - expected).abs() / expected * 100.0;
270 +
            println!("Bucket {}: {} ({:.1}% deviation)", i, count, deviation);
271 +
        }
272 +
    }
273 +
274 +
    fn distribution_f64(rng: &mut Rng, samples: usize, buckets: usize) {
275 +
        let mut counts = vec![0; buckets];
276 +
        let bucket_size = 1.0 / buckets as f64;
277 +
278 +
        for _ in 0..samples {
279 +
            let value = rng.probability();
280 +
            let bucket = (value / bucket_size) as usize;
281 +
            counts[bucket.min(buckets - 1)] += 1;
282 +
        }
283 +
284 +
        let expected = samples as f64 / buckets as f64;
285 +
        for (i, &count) in counts.iter().enumerate() {
286 +
            let deviation = (count as f64 - expected).abs() / expected * 100.0;
287 +
            println!("Bucket {}: {} ({:.1}% deviation)", i, count, deviation);
288 +
        }
289 +
    }
290 +
291 +
    #[test]
292 +
    fn test_distribution() {
293 +
        let mut rng = Rng::new();
294 +
295 +
        distribution_f64(&mut rng, 100000, 10);
296 +
    }
297 +
298 +
    #[test]
299 +
    fn test_basic_generation() {
300 +
        let mut rng = Rng::new();
301 +
302 +
        // Using gen
303 +
        let _: u64 = rng.gen(..);
304 +
        let _: bool = rng.flip();
305 +
306 +
        // Using gen_range
307 +
        let n = rng.gen(1u64..=100);
308 +
        assert!((1..=100).contains(&n));
309 +
    }
310 +
311 +
    #[test]
312 +
    fn test_fill_bytes() {
313 +
        let mut rng = Rng::new();
314 +
315 +
        // Test different buffer sizes
316 +
        let sizes = [1, 7, 8, 9, 16, 32, 64];
317 +
        for size in sizes {
318 +
            let mut buffer = vec![0u8; size];
319 +
            rng.fill(&mut buffer);
320 +
321 +
            // Ensure we actually wrote some non-zero bytes
322 +
            assert!(
323 +
                buffer.iter().any(|&x| x != 0),
324 +
                "Buffer of size {} contains only zeros",
325 +
                size
326 +
            );
327 +
        }
328 +
329 +
        // Test alignment handling
330 +
        let mut buffer = [0u8; 32];
331 +
        rng.fill(&mut buffer[1..31]); // Unaligned slice
332 +
    }
333 +
334 +
    #[test]
335 +
    fn test_seeded_sequences() {
336 +
        let mut rng1 = Rng::with_seed(12345);
337 +
        let mut rng2 = Rng::with_seed(12345);
338 +
339 +
        // Same seed should produce same sequence
340 +
        for _ in 0..100 {
341 +
            assert_eq!(rng1.gen_u64(), rng2.gen_u64());
342 +
        }
343 +
344 +
        // Different seeds should produce different sequences
345 +
        let mut rng3 = Rng::with_seed(12346);
346 +
        let val1 = rng1.gen_u64();
347 +
        let val2 = rng3.gen_u64();
348 +
        assert_ne!(val1, val2);
349 +
    }
350 +
351 +
    #[test]
352 +
    fn test_shuffle() {
353 +
        let mut rng = Rng::new();
354 +
355 +
        // Test with different sizes
356 +
        for len in [2, 3, 10, 100] {
357 +
            let mut v: Vec<i32> = (0..len).collect();
358 +
            let original = v.clone();
359 +
360 +
            rng.shuffle(&mut v);
361 +
362 +
            // Length should remain the same
363 +
            assert_eq!(v.len(), original.len());
364 +
365 +
            // All elements should still be present
366 +
            assert!(v.iter().all(|x| original.contains(x)));
367 +
368 +
            // Order should be different (for large enough arrays)
369 +
            if len > 10 {
370 +
                assert_ne!(v, original);
371 +
            }
372 +
        }
373 +
374 +
        // Test empty and single-element slices
375 +
        let mut empty: Vec<i32> = vec![];
376 +
        rng.shuffle(&mut empty);
377 +
        assert!(empty.is_empty());
378 +
379 +
        let mut single = vec![1];
380 +
        rng.shuffle(&mut single);
381 +
        assert_eq!(single, vec![1]);
382 +
    }
383 +
384 +
    #[test]
385 +
    fn test_consecutive_values() {
386 +
        let mut rng = Rng::new();
387 +
        let mut prev = rng.gen_u64();
388 +
        let mut repeats = 0;
389 +
390 +
        // Test for obvious patterns in consecutive values
391 +
        for _ in 0..1000 {
392 +
            let curr = rng.gen_u64();
393 +
            if curr == prev {
394 +
                repeats += 1;
395 +
            }
396 +
            prev = curr;
397 +
        }
398 +
399 +
        // Shouldn't have too many repeats
400 +
        assert!(repeats < 3, "Too many repeated consecutive values");
401 +
    }
402 +
}
ombre/src/runtime.rs added +196 -0
1 +
pub mod default;
2 +
pub mod sim;
3 +
pub mod time;
4 +
5 +
use crate::platform::*;
6 +
use crate::prelude::*;
7 +
8 +
/// Default UI scale.
9 +
pub const DEFAULT_SCALE: f32 = 2.;
10 +
/// Default target frames per second.
11 +
pub const DEFAULT_TARGET_FPS: f64 = 60.;
12 +
13 +
/// Simulation context.
14 +
pub struct SimulationCtx<'a> {
15 +
    /// Target/maximum frames per second.
16 +
    target_fps: f64,
17 +
    /// Ticks per second.
18 +
    tick_rate: f64,
19 +
    /// Reference to the platform window.
20 +
    window: &'a mut platform::Window,
21 +
}
22 +
23 +
impl std::ops::Deref for SimulationCtx<'_> {
24 +
    type Target = platform::Window;
25 +
26 +
    fn deref(&self) -> &Self::Target {
27 +
        self.window
28 +
    }
29 +
}
30 +
31 +
impl std::ops::DerefMut for SimulationCtx<'_> {
32 +
    fn deref_mut(&mut self) -> &mut Self::Target {
33 +
        self.window
34 +
    }
35 +
}
36 +
37 +
impl SimulationCtx<'_> {
38 +
    /// The target frames per second to render. This only affects
39 +
    /// how many frames are rendered to the screen, and not the tick rate
40 +
    /// of the simulation. Set to [`f64::INFINITY`] to make unlimited.
41 +
    /// This affects how often the simulations's [`Simulation::frame`] function is called.
42 +
    pub fn set_target_fps(&mut self, fps: f64) {
43 +
        self.target_fps = fps;
44 +
    }
45 +
46 +
    /// How fast the simulation progresses, in ticks per second.
47 +
    /// This affects how often the simulations's [`Simulation::tick`] function is called.
48 +
    pub fn set_tick_rate(&mut self, tick: f64) {
49 +
        self.tick_rate = tick;
50 +
    }
51 +
52 +
    /// Get the application window.
53 +
    pub fn window(&mut self) -> &'_ mut Window {
54 +
        self.window
55 +
    }
56 +
}
57 +
58 +
impl<'a> SimulationCtx<'a> {
59 +
    fn new(window: &'a mut platform::Window) -> Self {
60 +
        Self {
61 +
            target_fps: f64::INFINITY,
62 +
            tick_rate: 60.,
63 +
            window,
64 +
        }
65 +
    }
66 +
}
67 +
68 +
/// Application interface for runtime.
69 +
#[allow(unused_variables)]
70 +
pub trait Application {
71 +
    /// Error type returned by methods.
72 +
    /// Returning this error stops the application.
73 +
    type Error: std::error::Error + 'static;
74 +
75 +
    /// Called when there are changes that haven't been rendered.
76 +
    fn frame(&mut self) -> Result<(), Self::Error>;
77 +
    /// Called on every event.
78 +
    fn event(&mut self, event: WindowEvent, win: &mut Window) -> Result<(), Self::Error>;
79 +
    /// Called periodically to update the application state. Use this to implement animations.
80 +
    fn tick(&mut self, delta: time::Duration, win: &mut Window) -> Result<(), Self::Error> {
81 +
        Ok(())
82 +
    }
83 +
}
84 +
85 +
/// Simulation interface for runtime.
86 +
pub trait Simulation {
87 +
    /// Error type returned by methods.
88 +
    /// Returning this error stops the application.
89 +
    type Error: std::error::Error + 'static;
90 +
91 +
    /// Called whenever inputs are polled. Use [`Window::inputs`] via [`SimulationCtx`] to retrieve
92 +
    /// inputs.
93 +
    fn poll(&mut self, ctx: &mut SimulationCtx<'_>) -> Result<(), Self::Error>;
94 +
    /// Called for every fixed simulation tick.
95 +
    /// Change when this is called with [`SimulationCtx::set_tick_rate`].
96 +
    fn tick(&mut self, ctx: &mut SimulationCtx<'_>) -> Result<(), Self::Error>;
97 +
    /// Called when there is a window even, for example when the window is resized or the cursor
98 +
    /// is moved.
99 +
    fn event(&mut self, event: WindowEvent, ctx: &mut SimulationCtx<'_>)
100 +
        -> Result<(), Self::Error>;
101 +
    /// Called when the runtime is ready to render a frame to the
102 +
    /// screen. Change when this is called with [`SimulationCtx::set_target_fps`].
103 +
    fn frame(&mut self) -> Result<(), Self::Error>;
104 +
}
105 +
106 +
#[allow(unused_variables)]
107 +
pub trait ApplicationExt {
108 +
    type Error: std::error::Error + 'static;
109 +
110 +
    /// Called on every frame, after events have been processed. Drawing code goes here.
111 +
    fn present(&mut self) -> Result<(), Self::Error>;
112 +
    /// Called periodically to update the application state. Use this to implement animations.
113 +
    fn update(&mut self, delta: time::Duration, win: &mut Window) -> Result<(), Self::Error> {
114 +
        Ok(())
115 +
    }
116 +
    /// Called when the window size changes.
117 +
    fn window_resized(&mut self, size: LogicalSize) -> Result<(), Self::Error>;
118 +
    /// Called when the window moved.
119 +
    fn window_moved(&mut self, position: Point2D<f32, Screen>) {}
120 +
    /// Mouse cursor moved.
121 +
    fn mouse_moved(&mut self, position: Point2D<f32, Screen>) {}
122 +
    /// Mouse button pressed.
123 +
    fn mouse_down(&mut self, button: platform::MouseButton) {}
124 +
    /// Mouse button released.
125 +
    fn mouse_up(&mut self, button: platform::MouseButton) {}
126 +
    /// Mouse entered the window.
127 +
    fn mouse_entered(&mut self) {}
128 +
    /// Mouse left the window.
129 +
    fn mouse_left(&mut self) {}
130 +
    /// Mouse scrolled.
131 +
    fn mouse_scroll(&mut self, delta: Vector2D<f32, Screen>) {}
132 +
    /// Key pressed.
133 +
    fn key_down(&mut self, key: platform::Key) {}
134 +
    /// Key released.
135 +
    fn key_up(&mut self, key: platform::Key) {}
136 +
}
137 +
138 +
impl<A> Application for A
139 +
where
140 +
    A: ApplicationExt,
141 +
{
142 +
    type Error = A::Error;
143 +
144 +
    fn event(&mut self, event: WindowEvent, _window: &mut Window) -> Result<(), Self::Error> {
145 +
        match event {
146 +
            WindowEvent::CursorEntered => {
147 +
                self.mouse_entered();
148 +
            }
149 +
            WindowEvent::CursorLeft => {
150 +
                self.mouse_left();
151 +
            }
152 +
            WindowEvent::MouseInput { state, button, .. } => match state {
153 +
                InputState::Pressed => self.mouse_down(button),
154 +
                InputState::Released => self.mouse_up(button),
155 +
                InputState::Repeated => {}
156 +
            },
157 +
            WindowEvent::KeyboardInput(platform::KeyboardInput {
158 +
                key: Some(key),
159 +
                state,
160 +
                ..
161 +
            }) => match state {
162 +
                platform::InputState::Pressed => {
163 +
                    self.key_down(key);
164 +
                }
165 +
                platform::InputState::Released => {
166 +
                    self.key_up(key);
167 +
                }
168 +
                platform::InputState::Repeated => {}
169 +
            },
170 +
            WindowEvent::Scroll { delta } => {
171 +
                self.mouse_scroll(Vector2D::new(
172 +
                    delta.x.floor() as f32,
173 +
                    delta.y.floor() as f32,
174 +
                ));
175 +
            }
176 +
            WindowEvent::CursorMoved { position, .. } => {
177 +
                let cursor = Point2D::<f64, Screen>::from((position.x, position.y));
178 +
                let cursor = cursor.map(|n| n.floor() as f32);
179 +
180 +
                self.mouse_moved(cursor);
181 +
            }
182 +
            WindowEvent::Resized(size) => self.window_resized(size)?,
183 +
            WindowEvent::Moved(pos) => self.window_moved(Point2D::new(pos.x as f32, pos.y as f32)),
184 +
            _ => {}
185 +
        }
186 +
        Ok(())
187 +
    }
188 +
189 +
    fn frame(&mut self) -> Result<(), <A as ApplicationExt>::Error> {
190 +
        self.present()
191 +
    }
192 +
193 +
    fn tick(&mut self, delta: time::Duration, win: &mut Window) -> Result<(), Self::Error> {
194 +
        self.update(delta, win)
195 +
    }
196 +
}
ombre/src/runtime/default.rs added +105 -0
1 +
//! Runtime best used for GUIs.
2 +
use core::time;
3 +
use std::time::Instant;
4 +
5 +
use crate::platform;
6 +
use crate::platform::*;
7 +
use crate::runtime::time::MovingAverageTimer;
8 +
use crate::runtime::Application;
9 +
10 +
/// Run the given application.
11 +
pub fn run<A: Application>(
12 +
    mut win: platform::Window,
13 +
    mut events: platform::Events,
14 +
    mut app: A,
15 +
) -> Result<(), A::Error> {
16 +
    let mut resized = None;
17 +
    let mut minimized = false;
18 +
    let mut render_timer = MovingAverageTimer::default();
19 +
    let mut last = Instant::now();
20 +
    let mut delta;
21 +
22 +
    log::info!(target: "run", "starting runtime, window size is {}", win.size());
23 +
24 +
    'main: while win.is_open() {
25 +
        events.wait_timeout(time::Duration::from_millis(8));
26 +
27 +
        // The redraw flag is set by the "request redraw" function on `Window`.
28 +
        let mut redraw = win.is_ready();
29 +
        for event in events.flush() {
30 +
            log::debug!(target: "run", "event: {event:?}");
31 +
            if event.is_input() {
32 +
                // Input events force a redraw.
33 +
                redraw = true;
34 +
            }
35 +
36 +
            match &event {
37 +
                WindowEvent::Resized(size) => {
38 +
                    if size.is_zero() {
39 +
                        // On certain operating systems, the window size will be set to
40 +
                        // zero when the window is minimized. Since a zero-sized framebuffer
41 +
                        // is not valid, we don't render anything in this case.
42 +
                        minimized = true;
43 +
                    } else {
44 +
                        minimized = false;
45 +
                        resized = Some(*size);
46 +
                    }
47 +
                }
48 +
                WindowEvent::RedrawRequested => {
49 +
                    redraw = true;
50 +
                }
51 +
                WindowEvent::Moved(_) => {
52 +
                    app.event(
53 +
                        WindowEvent::CursorMoved {
54 +
                            position: win.get_cursor_pos(),
55 +
                        },
56 +
                        &mut win,
57 +
                    )?;
58 +
                }
59 +
                WindowEvent::Minimized => {
60 +
                    minimized = true;
61 +
                }
62 +
                WindowEvent::Restored => {
63 +
                    minimized = false;
64 +
                }
65 +
                WindowEvent::KeyboardInput(platform::KeyboardInput {
66 +
                    key: Some(platform::Key::Escape),
67 +
                    state: platform::InputState::Pressed,
68 +
                    ..
69 +
                }) => {
70 +
                    break 'main;
71 +
                }
72 +
                _ => {
73 +
                    app.event(event, &mut win)?;
74 +
                }
75 +
            };
76 +
        }
77 +
78 +
        // If minimized, don't update or render.
79 +
        if minimized {
80 +
            continue;
81 +
        }
82 +
        // Time delta.
83 +
        delta = last.elapsed();
84 +
        last += delta;
85 +
        app.tick(delta, &mut win)?;
86 +
87 +
        // Since we may receive multiple resize events at once, instead of responding to each
88 +
        // resize event, we handle the resize only once.
89 +
        if let Some(size) = resized.take() {
90 +
            let position = win.get_cursor_pos();
91 +
92 +
            app.event(WindowEvent::Resized(size), &mut win)?;
93 +
            app.event(WindowEvent::CursorMoved { position }, &mut win)?;
94 +
        }
95 +
        if redraw {
96 +
            render_timer.measure(|_| {
97 +
                app.frame()?;
98 +
                win.present();
99 +
100 +
                Ok(())
101 +
            })?;
102 +
        }
103 +
    }
104 +
    Ok(())
105 +
}
ombre/src/runtime/sim.rs added +122 -0
1 +
//! This runtime is used for real-time simulations, such as games.
2 +
//!
3 +
//! In this mode, the runtime will maintain a specified framerate,
4 +
//! never exceeding it.
5 +
use std::time::Instant;
6 +
7 +
use crate::platform;
8 +
use crate::platform::*;
9 +
use crate::runtime::time::MovingAverageTimer;
10 +
use crate::runtime::{Simulation, SimulationCtx};
11 +
12 +
/// Run the given application.
13 +
pub fn run<A: Simulation>(
14 +
    mut win: platform::Window,
15 +
    mut events: platform::Events,
16 +
    mut app: A,
17 +
) -> Result<(), A::Error> {
18 +
    let mut resized = None;
19 +
    let mut minimized = false;
20 +
    let mut render_timer = MovingAverageTimer::default();
21 +
    let mut win_size = win.size();
22 +
    let mut ctx = SimulationCtx::new(&mut win);
23 +
24 +
    // Keep track of when the last frame was entered.
25 +
    let mut last = Instant::now();
26 +
    // Tick accumulator.
27 +
    let mut acc_t = 0f64;
28 +
    // Render accumulator.
29 +
    let mut acc_r = 0f64;
30 +
31 +
    log::info!(
32 +
        target: "run",
33 +
        "starting runtime loop, window size is {} x {}",
34 +
        win_size.width, win_size.height
35 +
    );
36 +
37 +
    'main: while ctx.window.is_open() {
38 +
        let now = Instant::now();
39 +
        let delta = now - last;
40 +
41 +
        last = now;
42 +
        acc_t += delta.as_secs_f64();
43 +
        acc_r += delta.as_secs_f64();
44 +
45 +
        events.poll();
46 +
        app.poll(&mut ctx)?;
47 +
48 +
        for event in events.flush() {
49 +
            match &event {
50 +
                WindowEvent::Resized(size) => {
51 +
                    if size.is_zero() {
52 +
                        // On certain operating systems, the window size will be set to
53 +
                        // zero when the window is minimized. Since a zero-sized framebuffer
54 +
                        // is not valid, we don't render anything in this case.
55 +
                        minimized = true;
56 +
                    } else if *size != win_size {
57 +
                        minimized = false;
58 +
                        resized = Some(*size);
59 +
                        win_size = *size;
60 +
                    }
61 +
                }
62 +
                WindowEvent::Moved(_) => {
63 +
                    app.event(
64 +
                        WindowEvent::CursorMoved {
65 +
                            position: ctx.window.get_cursor_pos(),
66 +
                        },
67 +
                        &mut ctx,
68 +
                    )?;
69 +
                }
70 +
                WindowEvent::Minimized => {
71 +
                    minimized = true;
72 +
                }
73 +
                WindowEvent::Restored => {
74 +
                    minimized = false;
75 +
                }
76 +
                WindowEvent::KeyboardInput(platform::KeyboardInput {
77 +
                    key: Some(platform::Key::Escape),
78 +
                    state: platform::InputState::Pressed,
79 +
                    ..
80 +
                }) => {
81 +
                    break 'main;
82 +
                }
83 +
                _ => {
84 +
                    app.event(event, &mut ctx)?;
85 +
                }
86 +
            };
87 +
        }
88 +
89 +
        // If minimized, don't update or render.
90 +
        if minimized {
91 +
            continue;
92 +
        }
93 +
94 +
        // Since we may receive multiple resize events at once, instead of responding to each
95 +
        // resize event, we handle the resize only once.
96 +
        if let Some(size) = resized.take() {
97 +
            let position = ctx.window.get_cursor_pos();
98 +
99 +
            app.event(WindowEvent::Resized(size), &mut ctx)?;
100 +
            app.event(WindowEvent::CursorMoved { position }, &mut ctx)?;
101 +
        }
102 +
103 +
        // Tick the simulation ensuring we respect our tick rate.
104 +
        let tick = ctx.tick_rate.recip();
105 +
        while acc_t >= tick {
106 +
            app.tick(&mut ctx)?;
107 +
            acc_t -= tick;
108 +
        }
109 +
110 +
        // If we've accumulated enough time, render a new frame.
111 +
        if acc_r >= ctx.target_fps.recip() {
112 +
            acc_r = 0.;
113 +
            render_timer.measure(|_| {
114 +
                app.frame()?;
115 +
                ctx.window.present();
116 +
117 +
                Ok(())
118 +
            })?;
119 +
        }
120 +
    }
121 +
    Ok(())
122 +
}
ombre/src/runtime/time.rs added +375 -0
1 +
use std::collections::VecDeque;
2 +
pub use std::time::{Duration, Instant};
3 +
4 +
/// Calculates average frame-time using a moving average.
5 +
pub struct MovingAverageTimer {
6 +
    timings: VecDeque<u128>,
7 +
    avg: Duration,
8 +
    window: usize,
9 +
}
10 +
11 +
impl MovingAverageTimer {
12 +
    const DEFAULT_WINDOW: usize = 60;
13 +
14 +
    /// Create a new frame timer with a moving average window.
15 +
    pub fn new(window: usize) -> Self {
16 +
        Self {
17 +
            timings: VecDeque::with_capacity(window),
18 +
            avg: Duration::from_secs(0),
19 +
            window,
20 +
        }
21 +
    }
22 +
23 +
    /// Run a closure, while measuring elapsed time.
24 +
    pub fn measure<F, R>(&mut self, frame: F) -> R
25 +
    where
26 +
        F: FnOnce(Duration) -> R,
27 +
    {
28 +
        let start = Instant::now();
29 +
        let result = frame(self.avg);
30 +
        let elapsed = start.elapsed();
31 +
32 +
        self.timings.truncate(self.window);
33 +
        self.timings.push_front(elapsed.as_micros());
34 +
35 +
        let avg = self.timings.iter().sum::<u128>() / self.timings.len() as u128;
36 +
        self.avg = Duration::from_micros(avg as u64);
37 +
38 +
        result
39 +
    }
40 +
41 +
    /// Get the average frame time.
42 +
    pub fn get(&self) -> Duration {
43 +
        self.avg
44 +
    }
45 +
}
46 +
47 +
impl Default for MovingAverageTimer {
48 +
    fn default() -> Self {
49 +
        Self::new(MovingAverageTimer::DEFAULT_WINDOW)
50 +
    }
51 +
}
52 +
53 +
/// Manages timers and triggers timeouts.
54 +
pub struct TimeoutScheduler<K> {
55 +
    timeouts: Vec<(K, Instant)>,
56 +
    threshold: Duration,
57 +
}
58 +
59 +
impl Default for TimeoutScheduler<()> {
60 +
    fn default() -> Self {
61 +
        Self::new(Duration::from_millis(1))
62 +
    }
63 +
}
64 +
65 +
impl<K> TimeoutScheduler<K> {
66 +
    /// Create a new timeout scheduler.
67 +
    ///
68 +
    /// Takes a threshold below which two timeouts cannot overlap.
69 +
    pub fn new(threshold: Duration) -> Self {
70 +
        Self {
71 +
            timeouts: vec![],
72 +
            threshold,
73 +
        }
74 +
    }
75 +
76 +
    /// Return the number of timeouts being tracked.
77 +
    pub fn len(&self) -> usize {
78 +
        self.timeouts.len()
79 +
    }
80 +
81 +
    /// Check whether there are timeouts being tracked.
82 +
    pub fn is_empty(&self) -> bool {
83 +
        self.timeouts.is_empty()
84 +
    }
85 +
86 +
    /// Register a new timeout with an associated key and expiry time.
87 +
    ///
88 +
    /// ```
89 +
    /// use std::time::{Duration, Instant};
90 +
    /// use ombre::runtime::time::TimeoutScheduler;
91 +
    ///
92 +
    /// let mut ts = TimeoutScheduler::new(Duration::from_secs(1));
93 +
    /// let now = Instant::now();
94 +
    ///
95 +
    /// let registered = ts.register(0xA, now + Duration::from_secs(8));
96 +
    /// assert!(registered);
97 +
    ///
98 +
    /// let registered = ts.register(0xB, now + Duration::from_secs(9));
99 +
    /// assert!(registered);
100 +
    /// assert_eq!(ts.len(), 2);
101 +
    ///
102 +
    /// let registered = ts.register(0xC, now + Duration::from_millis(9541));
103 +
    /// assert!(!registered);
104 +
    ///
105 +
    /// let registered = ts.register(0xC, now + Duration::from_millis(9999));
106 +
    /// assert!(!registered);
107 +
    /// assert_eq!(ts.len(), 2);
108 +
    /// ```
109 +
    pub fn register(&mut self, key: K, time: Instant) -> bool {
110 +
        // If this timeout is too close to a pre-existing timeout,
111 +
        // don't register it.
112 +
        if self
113 +
            .timeouts
114 +
            .iter()
115 +
            .any(|(_, t)| time.duration_since(*t) < self.threshold)
116 +
        {
117 +
            return false;
118 +
        }
119 +
120 +
        self.timeouts.push((key, time));
121 +
        self.timeouts.sort_unstable_by(|(_, a), (_, b)| b.cmp(a));
122 +
123 +
        true
124 +
    }
125 +
126 +
    /// Get the minimum time duration we should wait for at least one timeout
127 +
    /// to be reached.  Returns `None` if there are no timeouts.
128 +
    ///
129 +
    /// ```
130 +
    /// use std::time::{Duration, Instant};
131 +
    /// use ombre::runtime::time::TimeoutScheduler;
132 +
    ///
133 +
    /// let mut ts = TimeoutScheduler::new(Duration::from_secs(0));
134 +
    /// let mut now = Instant::now();
135 +
    ///
136 +
    /// ts.register(0xA, now + Duration::from_millis(16));
137 +
    /// ts.register(0xB, now + Duration::from_millis(8));
138 +
    /// ts.register(0xC, now + Duration::from_millis(64));
139 +
    ///
140 +
    /// // We need to wait 8 millis to trigger the next timeout (1).
141 +
    /// assert!(ts.next(now) <= Some(Duration::from_millis(8)));
142 +
    ///
143 +
    /// // ... sleep for a millisecond ...
144 +
    /// let now = now + Duration::from_millis(1);
145 +
    ///
146 +
    /// // Now we don't need to wait as long!
147 +
    /// assert!(ts.next(now).unwrap() <= Duration::from_millis(7));
148 +
    /// ```
149 +
    pub fn next(&self, now: impl Into<Instant>) -> Option<Duration> {
150 +
        let now = now.into();
151 +
152 +
        self.timeouts.last().map(|(_, t)| t.duration_since(now))
153 +
    }
154 +
155 +
    /// Given the current time, populate the input vector with the keys that
156 +
    /// have timed out. Returns the number of keys that timed out.
157 +
    ///
158 +
    /// ```
159 +
    /// use std::time::{Duration, Instant};
160 +
    /// use ombre::runtime::time::TimeoutScheduler;
161 +
    ///
162 +
    /// let mut ts = TimeoutScheduler::new(Duration::from_secs(0));
163 +
    /// let now = Instant::now();
164 +
    ///
165 +
    /// ts.register(0xA, now + Duration::from_millis(8));
166 +
    /// ts.register(0xB, now + Duration::from_millis(16));
167 +
    /// ts.register(0xC, now + Duration::from_millis(64));
168 +
    /// ts.register(0xD, now + Duration::from_millis(72));
169 +
    ///
170 +
    /// let mut timeouts = Vec::new();
171 +
    ///
172 +
    /// assert_eq!(ts.expire(now + Duration::from_millis(21), &mut timeouts), 2);
173 +
    /// assert_eq!(timeouts, vec![0xA, 0xB]);
174 +
    /// assert_eq!(ts.len(), 2);
175 +
    /// ```
176 +
    pub fn expire(&mut self, now: Instant, expired: &mut Vec<K>) -> usize {
177 +
        let before = expired.len();
178 +
179 +
        while let Some((k, t)) = self.timeouts.pop() {
180 +
            if now >= t {
181 +
                expired.push(k);
182 +
            } else {
183 +
                self.timeouts.push((k, t));
184 +
                break;
185 +
            }
186 +
        }
187 +
        expired.len() - before
188 +
    }
189 +
}
190 +
191 +
/// A utility for tracking periodic events with a set interval.
192 +
pub struct IntervalTimer {
193 +
    /// Last time the timer was triggered.
194 +
    triggered: Instant,
195 +
    /// The interval this timer should trigger at.
196 +
    interval: Duration,
197 +
}
198 +
199 +
impl IntervalTimer {
200 +
    /// Creates a new Timer with the specified interval.
201 +
    pub fn new(interval: Duration) -> Self {
202 +
        Self {
203 +
            triggered: Instant::now(),
204 +
            interval,
205 +
        }
206 +
    }
207 +
208 +
    /// Creates a new timer from a frequency in Hz.
209 +
    pub fn from_hz(hz: f64) -> Self {
210 +
        Self::new(Duration::from_secs_f64(hz.recip()))
211 +
    }
212 +
213 +
    /// Checks if enough time has passed since the last trigger.
214 +
    /// Returns `true` if the interval has elapsed since the last trigger or reset.
215 +
    pub fn ready(&self) -> bool {
216 +
        self.elapsed() >= self.interval
217 +
    }
218 +
219 +
    /// Checks if the timer is ready and if so, updates the last trigger time.
220 +
    /// Returns `true` if the timer was ready and was reset, `false` otherwise.
221 +
    pub fn tick(&mut self) -> bool {
222 +
        if self.ready() {
223 +
            self.triggered = Instant::now();
224 +
            true
225 +
        } else {
226 +
            false
227 +
        }
228 +
    }
229 +
230 +
    /// Returns the duration since the last trigger or reset.
231 +
    pub fn elapsed(&self) -> Duration {
232 +
        Instant::now().duration_since(self.triggered)
233 +
    }
234 +
235 +
    /// Changes the timer's interval.
236 +
    pub fn set(&mut self, interval: Duration) {
237 +
        self.interval = interval;
238 +
    }
239 +
240 +
    /// Resets the timer, setting the last trigger time to now.
241 +
    pub fn reset(&mut self) {
242 +
        self.triggered = Instant::now();
243 +
    }
244 +
}
245 +
246 +
#[cfg(test)]
247 +
mod tests {
248 +
    use std::thread::sleep;
249 +
250 +
    use super::*;
251 +
    use crate::assert_approx_eq;
252 +
253 +
    #[test]
254 +
    fn test_properties() {
255 +
        let cases = [
256 +
            (vec![1, 2, 3, 4, 5], 0),
257 +
            (vec![1, 1, 2, 2, 3], 1),
258 +
            (vec![1, 2, 3, 4, 5], 1),
259 +
            (vec![1, 2, 3, 4, 5], 2),
260 +
            (vec![1, 2, 3, 4, 5], 5),
261 +
            (vec![2, 6, 10, 16], 2),
262 +
            (vec![2, 4, 8, 10], 3),
263 +
        ];
264 +
265 +
        for (timeouts, threshold) in cases {
266 +
            let threshold = Duration::from_secs(threshold);
267 +
            let mut ts = TimeoutScheduler::new(threshold);
268 +
            let mut now = Instant::now();
269 +
270 +
            for t in timeouts {
271 +
                ts.register(t, now + Duration::from_secs(t));
272 +
            }
273 +
274 +
            let mut woken = Vec::new();
275 +
            while let Some(delta) = ts.next(now) {
276 +
                now += delta;
277 +
                assert!(ts.expire(now, &mut woken) > 0);
278 +
            }
279 +
280 +
            let sorted = woken.windows(2).all(|w| w[0] <= w[1]);
281 +
            let granular = woken.windows(2).all(|w| w[1] - w[0] >= threshold.as_secs());
282 +
283 +
            assert!(sorted && granular)
284 +
        }
285 +
    }
286 +
287 +
    #[test]
288 +
    fn test_expire() {
289 +
        let mut ts = TimeoutScheduler::new(Duration::from_secs(0));
290 +
        let now = Instant::now();
291 +
292 +
        ts.register(0xA, now + Duration::from_millis(8));
293 +
        ts.register(0xB, now + Duration::from_millis(16));
294 +
        ts.register(0xC, now + Duration::from_millis(64));
295 +
        ts.register(0xD, now + Duration::from_millis(72));
296 +
297 +
        let mut timeouts = Vec::new();
298 +
299 +
        assert_eq!(ts.expire(now, &mut timeouts), 0);
300 +
        assert_eq!(timeouts, vec![]);
301 +
        assert_eq!(ts.len(), 4);
302 +
        assert_eq!(ts.expire(now + Duration::from_millis(9), &mut timeouts), 1);
303 +
        assert_eq!(timeouts, vec![0xA]);
304 +
        assert_eq!(ts.len(), 3, "one timeout has expired");
305 +
306 +
        timeouts.clear();
307 +
308 +
        assert_eq!(ts.expire(now + Duration::from_millis(66), &mut timeouts), 2);
309 +
        assert_eq!(timeouts, vec![0xB, 0xC]);
310 +
        assert_eq!(ts.len(), 1, "another two timeouts have expired");
311 +
312 +
        timeouts.clear();
313 +
314 +
        assert_eq!(ts.expire(now + Duration::from_millis(96), &mut timeouts), 1);
315 +
        assert_eq!(timeouts, vec![0xD]);
316 +
        assert!(ts.is_empty(), "all timeouts have expired");
317 +
    }
318 +
319 +
    #[test]
320 +
    fn test_new_interval_timer() {
321 +
        let timer = IntervalTimer::new(Duration::from_secs(1));
322 +
        assert!(!timer.ready());
323 +
        assert!(timer.elapsed() < Duration::from_millis(100));
324 +
    }
325 +
326 +
    #[test]
327 +
    fn test_from_hz() {
328 +
        let timer = IntervalTimer::from_hz(60.0);
329 +
        assert_approx_eq!(
330 +
            timer.interval.as_secs_f64(),
331 +
            Duration::from_secs_f64(1.0 / 60.0).as_secs_f64(),
332 +
            0.01
333 +
        );
334 +
    }
335 +
336 +
    #[test]
337 +
    fn test_timer_tick() {
338 +
        let mut timer = IntervalTimer::new(Duration::from_millis(50));
339 +
340 +
        assert!(!timer.tick()); // Shouldn't tick immediately
341 +
        sleep(Duration::from_millis(60));
342 +
        assert!(timer.tick()); // Should tick after waiting
343 +
        assert!(!timer.tick()); // Shouldn't tick again immediately
344 +
    }
345 +
346 +
    #[test]
347 +
    fn test_reset() {
348 +
        let mut timer = IntervalTimer::new(Duration::from_millis(50));
349 +
        sleep(Duration::from_millis(60));
350 +
        assert!(timer.ready());
351 +
352 +
        timer.reset();
353 +
        assert!(!timer.ready());
354 +
    }
355 +
356 +
    #[test]
357 +
    fn test_set_interval() {
358 +
        let mut timer = IntervalTimer::new(Duration::from_secs(1));
359 +
        timer.set(Duration::from_millis(50));
360 +
361 +
        assert!(!timer.ready());
362 +
        sleep(Duration::from_millis(60));
363 +
        assert!(timer.ready());
364 +
    }
365 +
366 +
    #[test]
367 +
    fn test_time_since_last() {
368 +
        let timer = IntervalTimer::new(Duration::from_secs(1));
369 +
        sleep(Duration::from_millis(50));
370 +
371 +
        let elapsed = timer.elapsed();
372 +
        assert!(elapsed >= Duration::from_millis(50));
373 +
        assert!(elapsed < Duration::from_millis(100));
374 +
    }
375 +
}
ombre/src/string.rs added +198 -0
1 +
use std::cmp::Ordering;
2 +
use std::hash::{Hash, Hasher};
3 +
use std::mem::MaybeUninit;
4 +
use std::{fmt, slice, str};
5 +
6 +
/// Maximum length of a [`Str`].
7 +
pub const MAX_LEN: usize = 23;
8 +
9 +
/// A small stack-allocated string.
10 +
#[repr(C)]
11 +
#[derive(Debug, Clone, Copy)]
12 +
pub struct Str {
13 +
    len: u8,
14 +
    data: [MaybeUninit<u8>; MAX_LEN],
15 +
}
16 +
17 +
impl Str {
18 +
    /// Create a new [`Str`] from an [`prim@str`].
19 +
    pub const fn new(s: &str) -> Self {
20 +
        let bytes = s.as_bytes();
21 +
        let len = bytes.len();
22 +
23 +
        assert!(len <= MAX_LEN, "String too long for `Str` type");
24 +
25 +
        let mut data = [MaybeUninit::uninit(); MAX_LEN];
26 +
        let mut i = 0;
27 +
28 +
        while i < len {
29 +
            data[i] = MaybeUninit::new(bytes[i]);
30 +
            i += 1;
31 +
        }
32 +
33 +
        Self {
34 +
            len: len as u8,
35 +
            data,
36 +
        }
37 +
    }
38 +
39 +
    /// Get the [`prim@str`] representation.
40 +
    pub fn as_str(&self) -> &str {
41 +
        unsafe {
42 +
            str::from_utf8_unchecked(slice::from_raw_parts(
43 +
                self.data.as_ptr() as *const u8,
44 +
                self.len as usize,
45 +
            ))
46 +
        }
47 +
    }
48 +
49 +
    /// Get the length of the string.
50 +
    pub fn len(&self) -> usize {
51 +
        self.len as usize
52 +
    }
53 +
54 +
    /// Check if the string is empty.
55 +
    pub fn is_empty(&self) -> bool {
56 +
        self.len == 0
57 +
    }
58 +
}
59 +
60 +
impl fmt::Display for Str {
61 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 +
        self.as_str().fmt(f)
63 +
    }
64 +
}
65 +
66 +
impl Default for Str {
67 +
    fn default() -> Self {
68 +
        Str {
69 +
            len: 0,
70 +
            data: [MaybeUninit::uninit(); MAX_LEN],
71 +
        }
72 +
    }
73 +
}
74 +
75 +
impl PartialEq for Str {
76 +
    fn eq(&self, other: &Self) -> bool {
77 +
        self.as_str() == other.as_str()
78 +
    }
79 +
}
80 +
81 +
impl Eq for Str {}
82 +
83 +
impl PartialOrd for Str {
84 +
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
85 +
        Some(self.cmp(other))
86 +
    }
87 +
}
88 +
89 +
impl Ord for Str {
90 +
    fn cmp(&self, other: &Self) -> Ordering {
91 +
        self.as_str().cmp(other.as_str())
92 +
    }
93 +
}
94 +
95 +
impl Hash for Str {
96 +
    fn hash<H: Hasher>(&self, state: &mut H) {
97 +
        self.as_str().hash(state);
98 +
    }
99 +
}
100 +
101 +
impl From<String> for Str {
102 +
    fn from(s: String) -> Self {
103 +
        Str::new(&s)
104 +
    }
105 +
}
106 +
107 +
impl From<&str> for Str {
108 +
    fn from(s: &str) -> Self {
109 +
        Str::new(s)
110 +
    }
111 +
}
112 +
113 +
impl From<Str> for String {
114 +
    fn from(s: Str) -> Self {
115 +
        s.to_string()
116 +
    }
117 +
}
118 +
119 +
impl AsRef<str> for Str {
120 +
    fn as_ref(&self) -> &str {
121 +
        self.as_str()
122 +
    }
123 +
}
124 +
125 +
#[cfg(test)]
126 +
mod tests {
127 +
    use super::*;
128 +
129 +
    #[test]
130 +
    fn test_str_creation() {
131 +
        let s = Str::new("Hello, world!");
132 +
        assert_eq!(s.as_str(), "Hello, world!");
133 +
        assert_eq!(s.len, 13);
134 +
    }
135 +
136 +
    #[test]
137 +
    fn test_str_empty() {
138 +
        let s = Str::new("");
139 +
        assert_eq!(s.as_str(), "");
140 +
        assert_eq!(s.len, 0);
141 +
    }
142 +
143 +
    #[test]
144 +
    fn test_str_max_length() {
145 +
        let max_string = "a".repeat(MAX_LEN);
146 +
        let s = Str::new(&max_string);
147 +
        assert_eq!(s.as_str(), max_string);
148 +
        assert_eq!(s.len as usize, MAX_LEN);
149 +
    }
150 +
151 +
    #[test]
152 +
    #[should_panic(expected = "String too long for `Str`")]
153 +
    fn test_str_too_long() {
154 +
        let too_long_string = "a".repeat(MAX_LEN + 1);
155 +
        Str::new(&too_long_string);
156 +
    }
157 +
158 +
    #[test]
159 +
    fn test_str_len_and_is_empty() {
160 +
        let s = Str::new("Hello");
161 +
        assert_eq!(s.len(), 5);
162 +
        assert!(!s.is_empty());
163 +
164 +
        let empty = Str::new("");
165 +
        assert_eq!(empty.len(), 0);
166 +
        assert!(empty.is_empty());
167 +
    }
168 +
169 +
    #[test]
170 +
    fn test_str_conversions() {
171 +
        let original = "Hello, world!";
172 +
        let s = Str::new(original);
173 +
174 +
        let string: String = s.to_string();
175 +
        assert_eq!(string, original);
176 +
177 +
        let from_string = Str::from(string);
178 +
        assert_eq!(from_string.as_str(), original);
179 +
180 +
        let from_str = Str::from(original);
181 +
        assert_eq!(from_str.as_str(), original);
182 +
183 +
        let back_to_string: String = s.into();
184 +
        assert_eq!(back_to_string, original);
185 +
    }
186 +
187 +
    #[test]
188 +
    fn test_str_as_ref() {
189 +
        let s = Str::new("Hello, world!");
190 +
        let str_ref: &str = s.as_ref();
191 +
        assert_eq!(str_ref, "Hello, world!");
192 +
193 +
        fn takes_str_ref<S: AsRef<str>>(s: S) -> usize {
194 +
            s.as_ref().len()
195 +
        }
196 +
        assert_eq!(takes_str_ref(s), 13);
197 +
    }
198 +
}
ombre/src/ui.rs added +63 -0
1 +
//! UI Library.
2 +
// FIXME: Putting the `cursor()` after `center()` doesn't work!
3 +
// TODO: Should we have MouseEnter/Exit events?
4 +
// TODO: MouseMove events only on hovered widgets?
5 +
// TODO: MouseDown events only on hovered widgets?
6 +
// TODO: MouseUp events on hovered and active widgets?
7 +
#![warn(missing_docs)]
8 +
pub mod context;
9 +
pub mod debug;
10 +
pub mod gfx;
11 +
pub mod interface;
12 +
pub mod lazy;
13 +
pub mod widgets;
14 +
15 +
#[cfg(test)]
16 +
mod tests;
17 +
18 +
pub use crate::bytes;
19 +
pub use crate::math;
20 +
pub use crate::platform;
21 +
22 +
pub use context::*;
23 +
pub use gfx::common::{Align, Align2D, Repaint};
24 +
pub use gfx::cursors::CursorDescriptor;
25 +
pub use gfx::fonts;
26 +
pub use gfx::fonts::FontDescriptor;
27 +
pub use gfx::text::{PlainText, RichTextStorage, TextAlign};
28 +
pub use interface::{interface, Error, Interface};
29 +
pub use lazy::Lazy;
30 +
pub use widgets::*;
31 +
pub use widgets::{Widget, WidgetEvent, WidgetExt};
32 +
33 +
#[cfg(test)]
34 +
mod test;
35 +
36 +
/// Bail out of a function with an error.
37 +
/// In debug mode, this panics with the error message.
38 +
/// In release mode, the error is logged and we return from the function early.
39 +
#[macro_export]
40 +
macro_rules! bail {
41 +
    ($fmt:expr, $($arg:tt)*) => {{
42 +
        #[cfg(debug_assertions)]
43 +
        {
44 +
            panic!($fmt, $($arg)*);
45 +
        }
46 +
        #[cfg(not(debug_assertions))]
47 +
        {
48 +
            log::error!(target: "ui", $fmt, $($arg)*);
49 +
            return;
50 +
        }
51 +
    }};
52 +
    ($fmt:expr) => {{
53 +
        #[cfg(debug_assertions)]
54 +
        {
55 +
            panic!($fmt);
56 +
        }
57 +
        #[cfg(not(debug_assertions))]
58 +
        {
59 +
            log::error!(target: "ui", $fmt);
60 +
            return;
61 +
        }
62 +
    }};
63 +
}
ombre/src/ui/context.rs added +342 -0
1 +
//! Widget context.
2 +
use std::collections::HashMap;
3 +
use std::ops::Deref;
4 +
use std::rc::Rc;
5 +
6 +
use crate::ui::gfx::font::Font;
7 +
8 +
use crate::ui::gfx::*;
9 +
use crate::ui::math::*;
10 +
11 +
/// Map of loaded fonts.
12 +
#[derive(Debug)]
13 +
pub struct Fonts<T> {
14 +
    /// The default font.
15 +
    pub default: Rc<Font<T>>,
16 +
    /// All the other loaded fonts.
17 +
    pub(crate) loaded: HashMap<FontName, Rc<Font<T>>>,
18 +
}
19 +
20 +
impl<T> Deref for Fonts<T> {
21 +
    type Target = HashMap<FontName, Rc<Font<T>>>;
22 +
23 +
    fn deref(&self) -> &Self::Target {
24 +
        &self.loaded
25 +
    }
26 +
}
27 +
28 +
impl<T> Fonts<T> {
29 +
    /// Create a new fonts database with a default font.
30 +
    pub fn new(font: Font<T>) -> Self {
31 +
        Self {
32 +
            default: Rc::new(font),
33 +
            loaded: HashMap::new(),
34 +
        }
35 +
    }
36 +
37 +
    /// Include a loaded font in the fonts map.
38 +
    pub fn with(mut self, name: FontName, font: Rc<Font<T>>) -> Self {
39 +
        self.loaded.insert(name, font);
40 +
        self
41 +
    }
42 +
43 +
    /// Lookup a loaded font, or return the default font if not found.
44 +
    pub fn lookup(&self, name: &FontName) -> &Rc<Font<T>> {
45 +
        self.loaded.get(name).unwrap_or(&self.default)
46 +
    }
47 +
}
48 +
49 +
/// Map of loaded cursors.
50 +
pub type Cursors = HashMap<&'static str, platform::Cursor>;
51 +
52 +
/// Global window state that can be modified by widgets.
53 +
#[derive(Debug, Clone)]
54 +
pub struct WindowCtx {
55 +
    /// The window title.
56 +
    pub title: String,
57 +
    /// The cursor icon currently set.
58 +
    pub cursor: Option<&'static str>,
59 +
    /// Window (inner) size.
60 +
    pub size: Size<u32>,
61 +
}
62 +
63 +
/// Widget context.
64 +
#[derive(Debug, Copy, Clone)]
65 +
pub struct Context {
66 +
    /// Widget transform. When applied, this converts widget-local coordinates
67 +
    /// to screen coordinates, ready for drawing.
68 +
    pub transform: Transform2D<Local, Screen>,
69 +
    /// Size of the context in pixels.
70 +
    pub size: Size<f32>,
71 +
    /// Whether this widget is active.
72 +
    pub active: bool,
73 +
    /// Cursor position relative to widget.
74 +
    pub cursor: Point2D<f32, Local>,
75 +
}
76 +
77 +
impl Context {
78 +
    /// Create a new context.
79 +
    pub fn new(cursor: impl Into<Point2D<f32, Local>>, size: impl Into<Size<f32>>) -> Self {
80 +
        Self {
81 +
            transform: Transform2D::identity(),
82 +
            cursor: cursor.into(),
83 +
            size: size.into(),
84 +
            active: false,
85 +
        }
86 +
    }
87 +
88 +
    /// Offset this context.
89 +
    pub fn offset(self, offset: impl Into<Vector2D<f32, Local>>) -> Self {
90 +
        let t = Transform2D::translate(offset.into());
91 +
        let transform = self.transform * t;
92 +
        let cursor = self.cursor.transform(t.inverse().convert());
93 +
94 +
        Self {
95 +
            transform,
96 +
            cursor,
97 +
            ..self
98 +
        }
99 +
    }
100 +
101 +
    /// Resize this context.
102 +
    pub fn resize(self, size: impl Into<Size<f32>>) -> Self {
103 +
        Self {
104 +
            size: size.into(),
105 +
            ..self
106 +
        }
107 +
    }
108 +
109 +
    /// Inset this context.
110 +
    pub fn inset(self, inset: Size<f32>) -> Self {
111 +
        Self {
112 +
            size: Size::new(self.size.w - inset.w * 2., self.size.h - inset.h * 2.),
113 +
            ..self.offset(Vector2D::new(inset.w, inset.h))
114 +
        }
115 +
    }
116 +
117 +
    /// Check if the current widget is hot.
118 +
    pub fn is_hot(&self) -> bool {
119 +
        Rect::origin(self.size).contains(self.cursor)
120 +
    }
121 +
122 +
    /// Check if the current widget is active.
123 +
    pub fn is_active(&self) -> bool {
124 +
        self.active
125 +
    }
126 +
127 +
    /// Set widget "active" state.
128 +
    pub fn active(self, active: bool) -> Self {
129 +
        Self { active, ..self }
130 +
    }
131 +
132 +
    /// Derive an event context.
133 +
    pub(crate) fn as_event(self, fonts: &Fonts<Image>) -> EventCtx<'_> {
134 +
        EventCtx { ctx: self, fonts }
135 +
    }
136 +
137 +
    /// Derive a layout context.
138 +
    pub(crate) fn as_layout(self, fonts: &Fonts<Image>) -> LayoutCtx<'_> {
139 +
        LayoutCtx {
140 +
            bounds: self.size,
141 +
            fonts,
142 +
            ctx: self,
143 +
        }
144 +
    }
145 +
146 +
    /// Derive a paint context.
147 +
    pub(crate) fn as_paint<'a>(
148 +
        self,
149 +
        fonts: &'a Fonts<Image>,
150 +
        ops: &'a mut Vec<PaintOp>,
151 +
    ) -> PaintCtx<'a> {
152 +
        PaintCtx {
153 +
            fonts,
154 +
            ops,
155 +
            ctx: self,
156 +
        }
157 +
    }
158 +
}
159 +
160 +
/// Layout function context.
161 +
#[derive(Clone)]
162 +
pub struct LayoutCtx<'a> {
163 +
    /// The set of loaded fonts.
164 +
    pub fonts: &'a Fonts<Image>,
165 +
    /// The size of the parent widget.
166 +
    pub bounds: Size<f32>,
167 +
    /// The parent context.
168 +
    pub ctx: Context,
169 +
}
170 +
171 +
impl LayoutCtx<'_> {
172 +
    /// Inset this context.
173 +
    pub fn inset(self, inset: Size<f32>) -> Self {
174 +
        let ctx = self.ctx.inset(inset);
175 +
176 +
        Self {
177 +
            ctx,
178 +
            fonts: self.fonts,
179 +
            bounds: ctx.size,
180 +
        }
181 +
    }
182 +
183 +
    /// Resize this context.
184 +
    pub fn resize(self, size: impl Into<Size<f32>>) -> Self {
185 +
        self.ctx.resize(size).as_layout(self.fonts)
186 +
    }
187 +
}
188 +
189 +
impl Deref for LayoutCtx<'_> {
190 +
    type Target = Context;
191 +
192 +
    fn deref(&self) -> &Self::Target {
193 +
        &self.ctx
194 +
    }
195 +
}
196 +
197 +
/// Paint function context.
198 +
pub struct PaintCtx<'a> {
199 +
    /// The parent context.
200 +
    pub ctx: Context,
201 +
    /// The set of loaded fonts.
202 +
    pub fonts: &'a Fonts<Image>,
203 +
    /// Paint operations.
204 +
    pub ops: &'a mut Vec<PaintOp>,
205 +
}
206 +
207 +
impl Deref for PaintCtx<'_> {
208 +
    type Target = Context;
209 +
210 +
    fn deref(&self) -> &Self::Target {
211 +
        &self.ctx
212 +
    }
213 +
}
214 +
215 +
impl PaintCtx<'_> {
216 +
    /// Blit an image.
217 +
    pub fn blit(&mut self, image: Image, blit: Blit<Local>) {
218 +
        self.ops.push(PaintOp::Blit {
219 +
            image,
220 +
            blit: blit.transform(self.transform),
221 +
        });
222 +
    }
223 +
224 +
    /// Fill a rectangle.
225 +
    pub fn fill(&mut self, rect: Rect<f32, Local>, color: Rgba<f32>, zdepth: ZDepth) {
226 +
        self.ops.push(PaintOp::Fill {
227 +
            rect: rect.transform(self.transform),
228 +
            color,
229 +
            zdepth,
230 +
        });
231 +
    }
232 +
233 +
    /// Stroke a rectangle.
234 +
    pub fn stroke(&mut self, rect: Rect<f32, Local>, color: Rgba<f32>, width: f32) {
235 +
        self.ops.push(PaintOp::Stroke {
236 +
            rect: rect.transform(self.transform),
237 +
            color,
238 +
            width,
239 +
        });
240 +
    }
241 +
242 +
    /// Draw a line.
243 +
    pub fn line(
244 +
        &mut self,
245 +
        from: Point2D<f32, Local>,
246 +
        to: Point2D<f32, Local>,
247 +
        width: f32,
248 +
        color: Rgba<f32>,
249 +
    ) {
250 +
        self.ops.push(PaintOp::Line {
251 +
            from: from.transform(self.transform),
252 +
            to: to.transform(self.transform),
253 +
            width,
254 +
            color,
255 +
        });
256 +
    }
257 +
258 +
    /// Offset this context.
259 +
    pub fn offset(self, offset: impl Into<Vector2D<f32, Local>>) -> Self {
260 +
        let ctx = self.ctx.offset(offset);
261 +
262 +
        Self {
263 +
            ctx,
264 +
            ops: self.ops,
265 +
            fonts: self.fonts,
266 +
        }
267 +
    }
268 +
269 +
    /// Inset this context.
270 +
    pub fn inset(self, inset: Size<f32>) -> Self {
271 +
        let ctx = self.ctx.inset(inset);
272 +
273 +
        Self {
274 +
            ctx,
275 +
            ops: self.ops,
276 +
            fonts: self.fonts,
277 +
        }
278 +
    }
279 +
280 +
    /// Resize this context.
281 +
    pub fn resize(self, size: impl Into<Size<f32>>) -> Self {
282 +
        Self {
283 +
            ctx: self.ctx.resize(size),
284 +
            ..self
285 +
        }
286 +
    }
287 +
288 +
    /// Set the "active" flag for this context.
289 +
    pub fn active(self, active: bool) -> Self {
290 +
        Self {
291 +
            ctx: self.ctx.active(active),
292 +
            ops: self.ops,
293 +
            fonts: self.fonts,
294 +
        }
295 +
    }
296 +
297 +
    /// Get the paint area bounds.
298 +
    pub fn rect(&self) -> Rect<f32, Local> {
299 +
        Rect::origin(self.ctx.size)
300 +
    }
301 +
}
302 +
303 +
/// Event function context.
304 +
#[derive(Debug, Copy, Clone)]
305 +
pub struct EventCtx<'a> {
306 +
    /// The parent widget context.
307 +
    pub ctx: Context,
308 +
    /// Placeholder to allow the parent type to hold a lifetime.
309 +
    pub fonts: &'a Fonts<Image>,
310 +
}
311 +
312 +
impl Deref for EventCtx<'_> {
313 +
    type Target = Context;
314 +
315 +
    fn deref(&self) -> &Self::Target {
316 +
        &self.ctx
317 +
    }
318 +
}
319 +
320 +
impl EventCtx<'_> {
321 +
    /// Offset this context.
322 +
    pub fn offset(self, offset: impl Into<Vector2D<f32, Local>>) -> Self {
323 +
        Self {
324 +
            ctx: self.ctx.offset(offset),
325 +
            fonts: self.fonts,
326 +
        }
327 +
    }
328 +
329 +
    /// Resize this context.
330 +
    pub fn resize(self, size: impl Into<Size<f32>>) -> Self {
331 +
        Self {
332 +
            ctx: self.ctx.resize(size),
333 +
            ..self
334 +
        }
335 +
    }
336 +
}
337 +
338 +
/// Graphics pipeline and its bindings.
339 +
pub(crate) struct Pipeline<const N: usize, const M: usize> {
340 +
    pub pipeline: PipelineId,
341 +
    pub bindings: Bindings<N, M>,
342 +
}
ombre/src/ui/debug.rs added +128 -0
1 +
//! Widget debugging utilities.
2 +
use std::io;
3 +
4 +
use crate::ui::Widget;
5 +
use crate::ui::{
6 +
    gfx::{Point2D, Size},
7 +
    math::{Local, Zero},
8 +
};
9 +
10 +
/// Debug information returned by widgets.
11 +
#[derive(Debug)]
12 +
pub struct DebugInfo {
13 +
    /// Name of widget.
14 +
    pub name: String,
15 +
    /// Size of widget.
16 +
    pub size: Option<Size<f32>>,
17 +
    /// Origin of widget.
18 +
    pub origin: Point2D<f32, Local>,
19 +
    /// Widget children.
20 +
    pub children: Vec<DebugInfo>,
21 +
    /// Extra debug string.
22 +
    pub extra: Option<String>,
23 +
    /// Whether this widget is hot.
24 +
    pub hot: bool,
25 +
    /// Whether this widget is active.
26 +
    pub active: bool,
27 +
}
28 +
29 +
impl DebugInfo {
30 +
    /// Create a new [`DebugInfo`].
31 +
    pub fn new(name: impl ToString) -> Self {
32 +
        Self {
33 +
            name: name.to_string(),
34 +
            size: None,
35 +
            origin: Point2D::ORIGIN,
36 +
            children: Vec::new(),
37 +
            hot: false,
38 +
            active: false,
39 +
            extra: None,
40 +
        }
41 +
    }
42 +
43 +
    /// Set `extra` field.
44 +
    pub fn extra(mut self, extra: impl ToString) -> Self {
45 +
        self.extra = Some(extra.to_string());
46 +
        self
47 +
    }
48 +
49 +
    /// Set `size` field.
50 +
    pub fn size(mut self, size: Size<f32>) -> Self {
51 +
        self.size = Some(size);
52 +
        self
53 +
    }
54 +
55 +
    /// Set `origin` field.
56 +
    pub fn origin(mut self, origin: impl Into<Point2D<f32, Local>>) -> Self {
57 +
        self.origin = origin.into();
58 +
        self
59 +
    }
60 +
61 +
    /// Set `active` field.
62 +
    pub fn active(mut self, active: bool) -> Self {
63 +
        self.active = active;
64 +
        self
65 +
    }
66 +
67 +
    /// Set `host` field.
68 +
    pub fn hot(mut self, hot: bool) -> Self {
69 +
        self.hot = hot;
70 +
        self
71 +
    }
72 +
73 +
    /// Set `children` field.
74 +
    pub fn children<'a, T, W: Widget<T> + 'a>(
75 +
        mut self,
76 +
        children: impl IntoIterator<Item = &'a W>,
77 +
    ) -> Self {
78 +
        self.children = children.into_iter().map(|c| c.debug()).collect();
79 +
        self
80 +
    }
81 +
82 +
    /// Print debug info to the given writer.
83 +
    pub fn print(&self, w: &mut impl io::Write) -> io::Result<()> {
84 +
        self.print_at(0, w)
85 +
    }
86 +
87 +
    fn print_meta(&self, w: &mut impl io::Write) -> io::Result<()> {
88 +
        write!(w, "{}", self.name)?;
89 +
90 +
        if let Some(size) = self.size {
91 +
            write!(w, " [{} x {}]", size.w, size.h)?;
92 +
        }
93 +
        if !self.origin.is_zero() {
94 +
            write!(w, " {{{}, {}}}", self.origin.x, self.origin.y)?;
95 +
        }
96 +
        if let Some(extra) = &self.extra {
97 +
            write!(w, " {extra}")?;
98 +
        }
99 +
        if self.hot {
100 +
            write!(w, " hot")?;
101 +
        }
102 +
        if self.active {
103 +
            write!(w, " active")?;
104 +
        }
105 +
        writeln!(w)
106 +
    }
107 +
108 +
    fn print_children(&self, depth: usize, w: &mut impl io::Write) -> io::Result<()> {
109 +
        let len = self.children.len();
110 +
111 +
        for (ix, child) in self.children.iter().enumerate() {
112 +
            if ix == len - 1 {
113 +
                write!(w, "{}└─ ", "   ".repeat(depth))?;
114 +
            } else {
115 +
                write!(w, "{}├─ ", "   ".repeat(depth))?;
116 +
            }
117 +
            child.print_at(depth + 1, w)?;
118 +
        }
119 +
        Ok(())
120 +
    }
121 +
122 +
    fn print_at(&self, depth: usize, w: &mut impl io::Write) -> io::Result<()> {
123 +
        self.print_meta(w)?;
124 +
        self.print_children(depth, w)?;
125 +
126 +
        Ok(())
127 +
    }
128 +
}
ombre/src/ui/gfx.rs added +61 -0
1 +
//! Nuit graphics module.
2 +
pub mod fonts;
3 +
4 +
pub(crate) mod common;
5 +
pub(crate) mod cursors;
6 +
pub(crate) mod present;
7 +
pub(crate) mod text;
8 +
9 +
pub use crate::draw::blit::Blit;
10 +
pub use crate::draw::pipeline::{Uniforms, Vertex};
11 +
pub use crate::draw::shape::{circle, line, rectangle, Circle, Line, Rectangle, Rotation};
12 +
pub use crate::draw::{batch, batch::VertexBatch, pipeline, shape};
13 +
pub use crate::gfx::*;
14 +
15 +
pub use common::*;
16 +
pub use cursors::CursorDescriptor;
17 +
pub use fonts::FontDescriptor;
18 +
pub use text::{FontStyle, PlainText, RichTextLayout, TextAlign, TextLayoutOptions, TextSpan};
19 +
20 +
use crate::ui::math::{Screen, ZDepth};
21 +
22 +
/// A paint operation.
23 +
#[derive(Debug, Clone, PartialEq)]
24 +
pub enum PaintOp {
25 +
    /// Blit an image onto the screen.
26 +
    Blit {
27 +
        /// Image to blit.
28 +
        image: Image,
29 +
        /// Blit instance for this image.
30 +
        blit: Blit<Screen>,
31 +
    },
32 +
    /// Fill a color.
33 +
    Fill {
34 +
        /// Rectangle to fill.
35 +
        rect: Rect<f32, Screen>,
36 +
        /// Fill color.
37 +
        color: Rgba<f32>,
38 +
        /// Fill depth.
39 +
        zdepth: ZDepth,
40 +
    },
41 +
    /// Draw a line,
42 +
    Line {
43 +
        /// Start point.
44 +
        from: Point2D<f32, Screen>,
45 +
        /// End point.
46 +
        to: Point2D<f32, Screen>,
47 +
        /// Stroke color.
48 +
        color: Rgba<f32>,
49 +
        /// Stroke width.
50 +
        width: f32,
51 +
    },
52 +
    /// Stroke a color.
53 +
    Stroke {
54 +
        /// Rectangle to stroke.
55 +
        rect: Rect<f32, Screen>,
56 +
        /// Stroke color.
57 +
        color: Rgba<f32>,
58 +
        /// Stroke width.
59 +
        width: f32,
60 +
    },
61 +
}
ombre/src/ui/gfx/common.rs added +112 -0
1 +
use crate::ui::gfx::{Size, Vector2D};
2 +
3 +
/// Generic vertical or horizontal alignment variants.
4 +
#[derive(Default, Debug, PartialEq, Eq, Copy, Clone)]
5 +
pub enum Align {
6 +
    /// Left or top alignment.
7 +
    Start,
8 +
    /// Center alignment.
9 +
    #[default]
10 +
    Center,
11 +
    /// Right or bottom alignment.
12 +
    End,
13 +
}
14 +
15 +
impl std::fmt::Display for Align {
16 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17 +
        match self {
18 +
            Self::Start => write!(f, "start"),
19 +
            Self::Center => write!(f, "center"),
20 +
            Self::End => write!(f, "end"),
21 +
        }
22 +
    }
23 +
}
24 +
25 +
/// Alignment in two dimensions.
26 +
pub type Align2D = Vector2D<Align>;
27 +
28 +
/// Insets into a rectangular area.
29 +
/// For example, can be used to specify padding, or distance from edges.
30 +
#[derive(Debug, Default, PartialEq, Eq, Clone)]
31 +
pub struct Insets<T = f32> {
32 +
    /// Distance from top edge.
33 +
    pub top: T,
34 +
    /// Distance from right edge.
35 +
    pub right: T,
36 +
    /// Distance from bottom edge.
37 +
    pub bottom: T,
38 +
    /// Distance from left edge.
39 +
    pub left: T,
40 +
}
41 +
42 +
impl<T: Copy> Insets<T> {
43 +
    /// Insets with the same value for all sides.
44 +
    pub fn uniform(val: T) -> Self {
45 +
        Self::from(val)
46 +
    }
47 +
}
48 +
49 +
impl<T: Copy> From<Vector2D<T>> for Insets<T> {
50 +
    fn from(vec: Vector2D<T>) -> Self {
51 +
        Self {
52 +
            top: vec.y,
53 +
            right: vec.x,
54 +
            bottom: vec.y,
55 +
            left: vec.x,
56 +
        }
57 +
    }
58 +
}
59 +
60 +
impl<T: Copy> From<Size<T>> for Insets<T> {
61 +
    fn from(size: Size<T>) -> Self {
62 +
        Self {
63 +
            top: size.h,
64 +
            right: size.w,
65 +
            bottom: size.h,
66 +
            left: size.w,
67 +
        }
68 +
    }
69 +
}
70 +
71 +
impl<T: Copy> From<T> for Insets<T> {
72 +
    fn from(val: T) -> Self {
73 +
        Self {
74 +
            top: val,
75 +
            right: val,
76 +
            bottom: val,
77 +
            left: val,
78 +
        }
79 +
    }
80 +
}
81 +
82 +
impl<T: Copy> From<(T, T)> for Insets<T> {
83 +
    fn from((v, h): (T, T)) -> Self {
84 +
        Self {
85 +
            top: v,
86 +
            right: h,
87 +
            bottom: v,
88 +
            left: h,
89 +
        }
90 +
    }
91 +
}
92 +
93 +
impl<T> From<(T, T, T, T)> for Insets<T> {
94 +
    fn from((top, right, bottom, left): (T, T, T, T)) -> Self {
95 +
        Self {
96 +
            top,
97 +
            right,
98 +
            bottom,
99 +
            left,
100 +
        }
101 +
    }
102 +
}
103 +
104 +
/// When to repaint a widget.
105 +
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
106 +
pub enum Repaint {
107 +
    /// Always repaint.
108 +
    Always,
109 +
    /// Only repaint when dirty.
110 +
    #[default]
111 +
    WhenDirty,
112 +
}
ombre/src/ui/gfx/cursors.rs added +14 -0
1 +
//! Pointing device cursors.
2 +
use crate::ui::gfx::{Image, Point2D};
3 +
use crate::ui::math::Local;
4 +
5 +
/// Describes a pointing device cursor.
6 +
#[derive(Debug, Clone, PartialEq, Eq)]
7 +
pub struct CursorDescriptor {
8 +
    /// Cursor name, used to set the cursor icon.
9 +
    pub name: &'static str,
10 +
    /// Cursor image.
11 +
    pub image: Image,
12 +
    /// Point on the cursor icon that is considered the position of the cursor.
13 +
    pub origin: Point2D<u32, Local>,
14 +
}
ombre/src/ui/gfx/fonts.rs added +38 -0
1 +
//! Font definitions.
2 +
3 +
// Re-exports.
4 +
pub use crate::ui::gfx::{Font, FontDescriptor, FontFormat, FontMetrics, FontName};
5 +
6 +
/// Default font identifier.
7 +
pub const DEFAULT_FONT: FontName = FontName::new("Default");
8 +
9 +
/// UF2 fonts.
10 +
pub mod uf2 {
11 +
    use super::*;
12 +
13 +
    /// Default font.
14 +
    pub const DEFAULT: FontDescriptor<'static> = FontDescriptor {
15 +
        name: DEFAULT_FONT,
16 +
        format: FontFormat::UF2,
17 +
        data: include_bytes!("fonts/gohu14.uf2"),
18 +
        metrics: FontMetrics {
19 +
            cap_height: 9,
20 +
            desc_height: 3,
21 +
            glyph_height: 14,
22 +
            baseline: 3,
23 +
        },
24 +
    };
25 +
26 +
    /// Venice.
27 +
    pub const VENICE: FontDescriptor<'static> = FontDescriptor {
28 +
        name: FontName::new("Venice"),
29 +
        format: FontFormat::UF2,
30 +
        data: include_bytes!("fonts/venice14.uf2"),
31 +
        metrics: FontMetrics {
32 +
            cap_height: 10,
33 +
            desc_height: 4,
34 +
            glyph_height: 16,
35 +
            baseline: 4,
36 +
        },
37 +
    };
38 +
}
ombre/src/ui/gfx/fonts/chicago12.uf2 added +0 -0

Binary file changed.

ombre/src/ui/gfx/fonts/courier12.uf2 added +0 -0

Binary file changed.

ombre/src/ui/gfx/fonts/diamond12.uf2 added +0 -0

Binary file changed.

ombre/src/ui/gfx/fonts/geneva12.uf2 added +0 -0

Binary file changed.

ombre/src/ui/gfx/fonts/gohu14.uf2 added +0 -0

Binary file changed.

ombre/src/ui/gfx/fonts/helvetica12.uf2 added +0 -0

Binary file changed.

ombre/src/ui/gfx/fonts/losangeles12.uf2 added +0 -0

Binary file changed.

ombre/src/ui/gfx/fonts/monaco12.uf2 added +0 -0

Binary file changed.

ombre/src/ui/gfx/fonts/msx816.uf2 added +0 -0

Binary file changed.

ombre/src/ui/gfx/fonts/newyork12.uf2 added +0 -0

Binary file changed.

ombre/src/ui/gfx/fonts/palatino12.uf2 added +0 -0

Binary file changed.

ombre/src/ui/gfx/fonts/sans10-regular.uf2 added +0 -0

Binary file changed.

ombre/src/ui/gfx/fonts/sapphire14.uf2 added +0 -0

Binary file changed.

ombre/src/ui/gfx/fonts/terminal12.uf2 added +0 -0

Binary file changed.

ombre/src/ui/gfx/fonts/venice14.uf2 added +0 -0

Binary file changed.

ombre/src/ui/gfx/present.rs added +4 -0
1 +
//! Presentation of offscreen pass to frontbuffer (screen).
2 +
mod pipeline;
3 +
4 +
pub use pipeline::*;
ombre/src/ui/gfx/present/fragment.glsl added +14 -0
1 +
#version 330 core
2 +
3 +
uniform sampler2D backbuffer;
4 +
5 +
in  vec2 vertUV;
6 +
out vec4 fragColor;
7 +
8 +
void main() {
9 +
	// Convert the UV coordinates to integer texel coordinates.
10 +
	ivec2 texSize = textureSize(backbuffer, 0);
11 +
	ivec2 texelCoord = ivec2(vec2(vertUV.s, 1 - vertUV.t) * texSize);
12 +
13 +
	fragColor = texelFetch(backbuffer, texelCoord, 0);
14 +
}
ombre/src/ui/gfx/present/pipeline.rs added +42 -0
1 +
use crate::ui::gfx;
2 +
use crate::ui::gfx::{BlendFactor, BlendOp, BlendState, ColorState, Rgba};
3 +
4 +
/// Create a pipeline for presenting to screen.
5 +
pub fn pipeline<T: gfx::RenderBackend>(backend: &mut T) -> Result<gfx::PipelineId, T::Error> {
6 +
    let shader = backend.shader(
7 +
        gfx::ShaderSource {
8 +
            vertex: include_str!("vertex.glsl"),
9 +
            fragment: include_str!("fragment.glsl"),
10 +
            geometry: None,
11 +
        },
12 +
        gfx::ShaderDescriptor {
13 +
            textures: &["backbuffer"],
14 +
            uniforms: gfx::UniformBlockLayout { uniforms: &[] },
15 +
        },
16 +
    )?;
17 +
18 +
    backend.pipeline(
19 +
        shader,
20 +
        gfx::PipelineDescriptor {
21 +
            layout: &[],
22 +
            depth: None,
23 +
            color: Some(ColorState {
24 +
                mask: Rgba::new(true, true, true, true),
25 +
                blend: BlendState {
26 +
                    rgb: Some(gfx::BlendEquation {
27 +
                        op: BlendOp::Add,
28 +
                        sfactor: BlendFactor::One,
29 +
                        dfactor: BlendFactor::Zero,
30 +
                    }),
31 +
                    alpha: Some(gfx::BlendEquation {
32 +
                        op: BlendOp::Add,
33 +
                        sfactor: BlendFactor::One,
34 +
                        dfactor: BlendFactor::Zero,
35 +
                    }),
36 +
                },
37 +
            }),
38 +
            culling: gfx::CullMode::Nothing,
39 +
            ..gfx::PipelineDescriptor::default()
40 +
        },
41 +
    )
42 +
}
ombre/src/ui/gfx/present/vertex.glsl added +26 -0
1 +
#version 330 core
2 +
3 +
const vec2[6] POSITION = vec2[](
4 +
	vec2(-1.0, -1.0),
5 +
	vec2( 1.0, -1.0),
6 +
	vec2( 1.0,  1.0),
7 +
	vec2(-1.0, -1.0),
8 +
	vec2(-1.0,  1.0),
9 +
	vec2( 1.0,  1.0)
10 +
);
11 +
12 +
const vec2[6] UV = vec2[](
13 +
	vec2(0.0, 1.0),
14 +
	vec2(1.0, 1.0),
15 +
	vec2(1.0, 0.0),
16 +
	vec2(0.0, 1.0),
17 +
	vec2(0.0, 0.0),
18 +
	vec2(1.0, 0.0)
19 +
);
20 +
21 +
out vec2 vertUV;
22 +
23 +
void main() {
24 +
	vertUV = UV[gl_VertexID];
25 +
	gl_Position = vec4(POSITION[gl_VertexID], 0.0, 1.0);
26 +
}
ombre/src/ui/gfx/text.rs added +242 -0
1 +
//! Text rendering.
2 +
mod plain;
3 +
mod rich;
4 +
5 +
use std::sync::Arc;
6 +
7 +
use crate::ui::context::Fonts;
8 +
use crate::ui::gfx::{Blit, FontMetrics, Image, Rgba8, Size};
9 +
use crate::ui::math::rect::Rect;
10 +
use crate::ui::math::*;
11 +
12 +
use super::fonts::DEFAULT_FONT;
13 +
14 +
pub use crate::ui::gfx::font::{Font, FontName};
15 +
pub use plain::PlainText;
16 +
pub use rich::{FontStyle, LoadedTextSpan, RichTextLayout, RichTextStorage, TextSpan};
17 +
18 +
/// Text value. Either static or dynamic.
19 +
pub enum TextValue<T> {
20 +
    /// For static text that never changes.
21 +
    Static(Arc<str>),
22 +
    /// For dynamic text that is a function of the application state.
23 +
    Dynamic(Arc<dyn Fn(&T) -> Arc<str>>),
24 +
}
25 +
26 +
impl<T> std::fmt::Debug for TextValue<T> {
27 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28 +
        match self {
29 +
            Self::Static(s) => write!(f, "Static({s:?})"),
30 +
            Self::Dynamic(_) => write!(f, "Dynamic(..)"),
31 +
        }
32 +
    }
33 +
}
34 +
35 +
impl<T> TextValue<T> {
36 +
    fn resolve(&self, data: &T) -> Arc<str> {
37 +
        match &self {
38 +
            TextValue::Static(s) => s.clone(),
39 +
            TextValue::Dynamic(f) => f(data),
40 +
        }
41 +
    }
42 +
}
43 +
44 +
impl<T> From<String> for TextValue<T> {
45 +
    fn from(value: String) -> Self {
46 +
        Self::Static(Arc::from(value))
47 +
    }
48 +
}
49 +
50 +
impl<T> From<&str> for TextValue<T> {
51 +
    fn from(value: &str) -> Self {
52 +
        Self::Static(value.into())
53 +
    }
54 +
}
55 +
56 +
impl<T, S, F> From<F> for TextValue<T>
57 +
where
58 +
    S: Into<Arc<str>>,
59 +
    F: Fn(&T) -> S + 'static,
60 +
{
61 +
    fn from(resolve: F) -> TextValue<T> {
62 +
        let f = Arc::new(move |state: &T| resolve(state).into());
63 +
        TextValue::Dynamic(f)
64 +
    }
65 +
}
66 +
67 +
/// Text alignment.
68 +
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
69 +
pub enum TextAlign {
70 +
    /// Left-align.
71 +
    #[default]
72 +
    Left,
73 +
    /// Center-align.
74 +
    Center,
75 +
    /// Right-align.
76 +
    Right,
77 +
}
78 +
79 +
/// Text layout options.
80 +
#[derive(Copy, Clone, Debug, Default)]
81 +
pub struct TextLayoutOptions {
82 +
    /// Line height. Defaults to the font tile height if `None`.
83 +
    pub line_height: Option<f32>,
84 +
    /// Text alignment (default: left).
85 +
    pub align: TextAlign,
86 +
}
87 +
88 +
impl TextLayoutOptions {
89 +
    /// Centered text.
90 +
    pub fn centered(self) -> Self {
91 +
        self.align(TextAlign::Center)
92 +
    }
93 +
94 +
    /// Set text alignment.
95 +
    pub fn align(mut self, align: impl Into<TextAlign>) -> Self {
96 +
        self.align = align.into();
97 +
        self
98 +
    }
99 +
}
100 +
101 +
/// A single layed out character.
102 +
#[derive(Clone, Debug)]
103 +
struct GlyphLayout {
104 +
    /// Character index into the texture.
105 +
    character: u8,
106 +
    /// Position of the glyph within the text area.
107 +
    bounds: Rect<f32, Local>,
108 +
}
109 +
110 +
/// An object that can store text.
111 +
/// Used by text input widgets to store the input value.
112 +
pub trait TextStorage {
113 +
    /// Clear the text value.
114 +
    fn clear(&mut self) {
115 +
        self.replace("")
116 +
    }
117 +
    /// Replace the text value.
118 +
    fn replace(&mut self, value: &str);
119 +
    /// Get a string representation of the value.
120 +
    fn as_str(&self) -> &str;
121 +
    /// Get the string length.
122 +
    fn len(&self) -> usize {
123 +
        self.as_str().len()
124 +
    }
125 +
    /// Remove a character.
126 +
    fn remove(&mut self, idx: usize) -> char;
127 +
    /// Insert a character.
128 +
    fn insert(&mut self, idx: usize, ch: char);
129 +
}
130 +
131 +
impl TextStorage for String {
132 +
    fn replace(&mut self, value: &str) {
133 +
        String::clear(self);
134 +
        String::push_str(self, value);
135 +
    }
136 +
137 +
    fn as_str(&self) -> &str {
138 +
        String::as_str(self)
139 +
    }
140 +
141 +
    fn remove(&mut self, idx: usize) -> char {
142 +
        String::remove(self, idx)
143 +
    }
144 +
145 +
    fn insert(&mut self, idx: usize, ch: char) {
146 +
        String::insert(self, idx, ch)
147 +
    }
148 +
}
149 +
150 +
pub struct RawLabel<'a> {
151 +
    tile: Size<f32>,
152 +
    glyphs: &'a [GlyphLayout],
153 +
    tint: Rgba8,
154 +
}
155 +
156 +
impl RawLabel<'_> {
157 +
    /// Render the glyphs as [`Blit`] objects, using the font texture information.
158 +
    pub fn render(&self, texture: Size<u32>) -> Vec<Blit<Local>> {
159 +
        let size = self.tile;
160 +
        let stride = texture.w / size.w as u32;
161 +
        let mut batch = Vec::new();
162 +
163 +
        if stride == 0 {
164 +
            panic!("RawLabel::render: texture stride must not be zero");
165 +
        }
166 +
        for g in self.glyphs {
167 +
            let i = g.character as u32;
168 +
            let x = (i % stride) as f32 * size.w;
169 +
            let y = (i / stride) as f32 * size.h;
170 +
171 +
            batch.push(
172 +
                Blit::<Local>::new(Rect::new([x, y], g.bounds.size), g.bounds).tint(self.tint),
173 +
            );
174 +
        }
175 +
        batch
176 +
    }
177 +
}
178 +
179 +
pub(crate) mod align {
180 +
    use super::*;
181 +
182 +
    pub(super) fn horizontal<'a>(
183 +
        glyphs: impl Iterator<Item = &'a mut GlyphLayout>,
184 +
        width: f32,
185 +
        align: TextAlign,
186 +
        bounds: Size<f32>,
187 +
    ) {
188 +
        if width >= bounds.w {
189 +
            return;
190 +
        }
191 +
        let offset = match align {
192 +
            TextAlign::Left => return,
193 +
            TextAlign::Center => (bounds.w - width) / 2.,
194 +
            TextAlign::Right => bounds.w - width,
195 +
        };
196 +
        for glyph in glyphs {
197 +
            glyph.bounds.origin.x += offset;
198 +
        }
199 +
    }
200 +
201 +
    //   ┌─────────────────────────────────┐__ Glyph height (14) (total)
202 +
    //  d│                                 │
203 +
    //  c│_________________________________│__ Cap height (9) (from baseline)
204 +
    //  b│ @@@@                            │
205 +
    //  a│@    @        ___________________│__ X-height (6) (from baseline)
206 +
    //  9│@       @ @@@                    │
207 +
    //  8│@       @@   @                   │
208 +
    //  7│ @@@@   @    @                   │
209 +
    //  6│     @  @    @                   │
210 +
    //  5│     @  @    @                   │
211 +
    //  4│@    @  @@   @                   │
212 +
    //  3│ @@@@   @ @@@ ___________________│__ Baseline (3)
213 +
    //  2│        @                        │
214 +
    //  1│        @                        │
215 +
    //  0│        @ _______________________│__ Descender height (3) (until baseline)
216 +
    //   │                                 │
217 +
    //   │                                 │
218 +
    //   └─────────────────────────────────┘
219 +
    //
220 +
    // The goal is to place the glyph such that `char_height` is vertically centered within
221 +
    // `line_height`, keeping in mind that `char_height` is offset by `baseline`.
222 +
    //
223 +
    pub(super) fn vertical<'a>(
224 +
        glyphs: impl Iterator<Item = &'a mut GlyphLayout>,
225 +
        line_height: f32, // Usually "cap height" + 2 * "descender height", unless line is taller.
226 +
        char_height: f32, // Usually "cap height".
227 +
        metrics: FontMetrics,
228 +
    ) {
229 +
        let glyph_height = metrics.glyph_height as f32;
230 +
        // The baseline as taken from the top of the glyph, instead of the bottom.
231 +
        let baseline = glyph_height - metrics.baseline as f32;
232 +
        let diff = line_height - char_height;
233 +
        // How much space we want above and below the centered piece.
234 +
        let padding = diff / 2.;
235 +
        let offset = (padding - baseline) + char_height;
236 +
        let offset = offset.truncate();
237 +
238 +
        for glyph in glyphs {
239 +
            glyph.bounds.origin.y += offset;
240 +
        }
241 +
    }
242 +
}
ombre/src/ui/gfx/text/plain.rs added +284 -0
1 +
//! Plain text layout.
2 +
use std::cell::OnceCell;
3 +
use std::rc::Rc;
4 +
use std::sync::Arc;
5 +
6 +
use super::*;
7 +
8 +
/// Text object with layout, style and data.
9 +
#[derive(Debug)]
10 +
pub struct PlainText<T> {
11 +
    pub(crate) font: FontName,
12 +
    pub(crate) value: TextValue<T>,
13 +
    pub(crate) opts: TextLayoutOptions,
14 +
    pub(crate) layout: Option<TextLayout>,
15 +
    pub(crate) bounds: Size<f32>,
16 +
17 +
    /// Loaded font.
18 +
    lfont: OnceCell<Rc<Font<Image>>>,
19 +
    /// Cached text value for comparisons.
20 +
    old: Arc<str>,
21 +
}
22 +
23 +
impl<T> From<String> for PlainText<T> {
24 +
    fn from(data: String) -> Self {
25 +
        Self::new(DEFAULT_FONT, TextLayoutOptions::default(), data)
26 +
    }
27 +
}
28 +
29 +
impl<T> PlainText<T> {
30 +
    /// Create a new text object.
31 +
    pub fn new(font: FontName, opts: TextLayoutOptions, data: impl Into<TextValue<T>>) -> Self {
32 +
        Self {
33 +
            font,
34 +
            lfont: OnceCell::default(),
35 +
            old: String::new().into(),
36 +
            value: data.into(),
37 +
            opts,
38 +
            layout: None,
39 +
            bounds: Size::ZERO,
40 +
        }
41 +
    }
42 +
43 +
    /// Set the value of the text.
44 +
    pub fn set(&mut self, data: impl ToString) {
45 +
        self.value = data.to_string().into();
46 +
        self.layout = None;
47 +
    }
48 +
49 +
    /// Get the font.
50 +
    pub fn font(&self) -> Option<&Font<Image>> {
51 +
        self.lfont.get().map(|lf| lf.as_ref())
52 +
    }
53 +
54 +
    /// Layout the text.
55 +
    pub fn layout(
56 +
        &mut self,
57 +
        data: &T,
58 +
        bounds: Size<f32>,
59 +
        fonts: &Fonts<Image>,
60 +
    ) -> (&TextLayout, &Font<Image>) {
61 +
        let text = self.value.resolve(data);
62 +
63 +
        if bounds != self.bounds || text != self.old {
64 +
            self.layout = None;
65 +
        }
66 +
        let font = self.lfont.get_or_init(|| fonts.lookup(&self.font).clone());
67 +
        let layout =
68 +
            self.layout
69 +
                .get_or_insert(TextLayout::new(text.as_ref(), font, self.opts, bounds));
70 +
71 +
        self.bounds = bounds;
72 +
        self.old = text;
73 +
74 +
        (layout, font)
75 +
    }
76 +
77 +
    /// Force re-layout of text.
78 +
    pub fn clear(&mut self) {
79 +
        self.layout = None;
80 +
    }
81 +
}
82 +
83 +
/// Text that has been layed out.
84 +
#[derive(Clone, Debug)]
85 +
pub struct TextLayout {
86 +
    /// Area used for the text layout.
87 +
    pub(crate) size: Size<f32>,
88 +
    /// Area bounds.
89 +
    pub(crate) bounds: Size<f32>,
90 +
    /// Font tile size.
91 +
    pub(crate) tile: Size<f32>,
92 +
    /// Font metrics.
93 +
    pub(crate) metrics: FontMetrics,
94 +
    /// Layed out text.
95 +
    glyphs: Vec<GlyphLayout>,
96 +
    /// Did we overflow the given bounds?
97 +
    overflow: bool,
98 +
}
99 +
100 +
impl TextLayout {
101 +
    /// Lay out the given text and return a [`TextLayout`] object.
102 +
    pub fn new<I>(text: &str, font: &Font<I>, opts: TextLayoutOptions, bounds: Size<f32>) -> Self {
103 +
        let tile = font.tile_size();
104 +
        let metrics = font.metrics;
105 +
        let mut overflow = false;
106 +
        let mut dst = Point2D::ZERO;
107 +
        let mut glyphs = Vec::new();
108 +
        let mut width = 0.;
109 +
110 +
        for c in text.bytes() {
111 +
            let w = font.glyph_width(c);
112 +
            if dst.x + w > bounds.w {
113 +
                overflow = true;
114 +
                break;
115 +
            }
116 +
            glyphs.push(GlyphLayout {
117 +
                character: c,
118 +
                bounds: Rect::new(dst, [w, metrics.glyph_height as f32]),
119 +
            });
120 +
            dst.x += w;
121 +
            width += w;
122 +
        }
123 +
        let height = opts.line_height.unwrap_or(metrics.line_height() as f32);
124 +
        // Align glyphs horizontally.
125 +
        align::horizontal(glyphs.iter_mut(), width, opts.align, bounds);
126 +
        // Align glyphs vertically. We use the "cap height" for alignment.
127 +
        align::vertical(
128 +
            glyphs.iter_mut(),
129 +
            height,
130 +
            metrics.cap_height as f32,
131 +
            metrics,
132 +
        );
133 +
134 +
        let size = if opts.align == TextAlign::Left {
135 +
            Size::new(width, height)
136 +
        } else {
137 +
            // If we are center-aligned, or right-aligned, we indicate that we are using up all the
138 +
            // horizontal space. Otherwise, alignment won't stack correctly if another alignment
139 +
            // calculation is used on top of this one.
140 +
            Size::new(bounds.w, height)
141 +
        };
142 +
143 +
        if size.w > bounds.w {
144 +
            log::warn!(target: "ui", "Text width ({}) overflows bounds ({})", size.w, bounds.w);
145 +
        }
146 +
        if size.h > bounds.h {
147 +
            log::warn!(target: "ui", "Text height ({}) overflows bounds ({})", size.h, bounds.h);
148 +
        }
149 +
150 +
        Self {
151 +
            tile,
152 +
            metrics,
153 +
            size,
154 +
            bounds,
155 +
            glyphs,
156 +
            overflow,
157 +
        }
158 +
    }
159 +
160 +
    /// Did we overflow the bounds?
161 +
    pub fn is_overflow(&self) -> bool {
162 +
        self.overflow
163 +
    }
164 +
165 +
    /// Check if there is space remaining for the given character.
166 +
    pub fn is_space_remaining<I>(&self, character: u8, font: &Font<I>) -> bool {
167 +
        self.bounds.w - self.size.w >= font.glyph_width(character)
168 +
    }
169 +
170 +
    /// Get the layed out characters and with their positions.
171 +
    pub fn chars(&self) -> impl Iterator<Item = &Rect<f32, Local>> {
172 +
        self.glyphs.iter().map(|g| &g.bounds)
173 +
    }
174 +
175 +
    /// Render the layed out text as [`Blit`] objects, using the font texture information.
176 +
    pub fn render(&self, texture: Size<u32>, tint: Rgba8) -> Vec<Blit<Local>> {
177 +
        RawLabel {
178 +
            tile: self.tile,
179 +
            glyphs: self.glyphs.as_slice(),
180 +
            tint,
181 +
        }
182 +
        .render(texture)
183 +
    }
184 +
185 +
    /// Final size of the text area, after layout.
186 +
    pub fn size(&self) -> Size<f32> {
187 +
        self.size
188 +
    }
189 +
190 +
    /// Line height of text.
191 +
    pub fn line_height(&self) -> f32 {
192 +
        self.metrics.line_height() as f32
193 +
    }
194 +
}
195 +
196 +
#[cfg(test)]
197 +
#[allow(clippy::unwrap_used)]
198 +
mod tests {
199 +
    use super::*;
200 +
    use crate::ui::fonts;
201 +
202 +
    #[test]
203 +
    fn test_text_layout_basic() {
204 +
        let input = "Sphinx";
205 +
        let font = fonts::uf2::DEFAULT.decode().unwrap();
206 +
        let opts = TextLayoutOptions::default();
207 +
        let bounds = Size::new(256., 256.);
208 +
        let layout = TextLayout::new(input, &font, opts, bounds);
209 +
210 +
        assert_eq!(
211 +
            layout.size,
212 +
            Size::new(font.text_width(input), font.metrics.line_height() as f32)
213 +
        );
214 +
        assert_eq!(layout.size, Size::new(48., 15.));
215 +
        assert_eq!(layout.glyphs.len(), input.len());
216 +
        assert!(!layout.is_overflow());
217 +
    }
218 +
219 +
    #[test]
220 +
    fn test_text_layout_overflow() {
221 +
        let input = "Sphinx";
222 +
        let font = fonts::uf2::DEFAULT.decode().unwrap();
223 +
        let opts = TextLayoutOptions::default();
224 +
        let layout = TextLayout::new(input, &font, opts, Size::new(48.0, 15.0));
225 +
        assert!(!layout.is_overflow());
226 +
227 +
        let layout = TextLayout::new(input, &font, opts, Size::new(48.0, 14.0));
228 +
        assert!(!layout.is_overflow()); // Vertical overflow is ignored.
229 +
230 +
        let layout = TextLayout::new(input, &font, opts, Size::new(47.0, 15.0));
231 +
        assert!(layout.is_overflow());
232 +
        assert!(layout.glyphs.len() < input.len()); // Should not contain all characters.
233 +
    }
234 +
235 +
    #[test]
236 +
    fn test_text_layout_alignment() {
237 +
        let input = "Sphinx";
238 +
        let f_default = fonts::uf2::DEFAULT.decode().unwrap();
239 +
        let f_venice = fonts::uf2::VENICE.decode().unwrap();
240 +
        let cases = [
241 +
            // Default font.
242 +
            (&f_default, Size::new(60., 19.), 19., Point2D::new(6., 3.)), // Even vertical fit.
243 +
            (&f_default, Size::new(60., 18.), 18., Point2D::new(6., 2.)), // Uneven vertical fit.
244 +
            (&f_default, Size::new(60., 15.), 15., Point2D::new(6., 1.)), // Tight vertical fit.
245 +
            // Venice font.
246 +
            (&f_venice, Size::new(60., 22.), 22., Point2D::new(4., 4.)), // Even vertical fit.
247 +
            (&f_venice, Size::new(60., 21.), 21., Point2D::new(4., 3.)), // Uneven vertical fit.
248 +
            (&f_venice, Size::new(60., 18.), 18., Point2D::new(4., 2.)), // Tight vertical fit.
249 +
        ];
250 +
        assert_eq!(f_venice.text_width(input), 52.);
251 +
        assert_eq!(f_default.text_width(input), 48.);
252 +
        assert_eq!(f_default.metrics.line_height(), 15);
253 +
        assert_eq!(f_venice.metrics.line_height(), 18);
254 +
255 +
        for (i, (font, bounds, line_height, expected)) in cases.iter().enumerate() {
256 +
            let layout = TextLayout::new(
257 +
                input,
258 +
                font,
259 +
                TextLayoutOptions {
260 +
                    line_height: Some(*line_height),
261 +
                    align: TextAlign::Center,
262 +
                },
263 +
                *bounds,
264 +
            );
265 +
            assert_eq!(layout.size.w, bounds.w, "case #{i}"); // Full width due to center alignment.
266 +
            assert_eq!(layout.size.h, *line_height, "case #{i}");
267 +
            assert_eq!(layout.glyphs[0].bounds.origin, *expected, "case #{i}");
268 +
        }
269 +
    }
270 +
271 +
    #[test]
272 +
    fn test_text_layout_empty_string() {
273 +
        let font = fonts::uf2::DEFAULT.decode().unwrap();
274 +
        let opts = TextLayoutOptions::default();
275 +
        let layout = TextLayout::new("", &font, opts, Size::new(48.0, 15.0));
276 +
277 +
        assert_eq!(
278 +
            layout.size,
279 +
            Size::new(0.0, font.metrics.line_height() as f32)
280 +
        );
281 +
        assert!(layout.glyphs.is_empty());
282 +
        assert!(!layout.is_overflow());
283 +
    }
284 +
}
ombre/src/ui/gfx/text/rich.rs added +340 -0
1 +
//! Rich text layout and rendering.
2 +
3 +
// A rendered layout is structured in the following hierarchy:
4 +
//
5 +
// RichTextLayout      (one per text area)
6 +
//   TextRowLayout*    (one per line of text)
7 +
//     TextSpanLayout* (one per style of text)
8 +
//       GlyphLayout*  (one per character)
9 +
//
10 +
// TODO: Hyphenation
11 +
use std::mem;
12 +
use std::ops::Range;
13 +
use std::rc::Rc;
14 +
15 +
use crate::ui::gfx::{Blit, FontFormat};
16 +
17 +
use crate::ui::math::*;
18 +
19 +
use super::{
20 +
    align, Font, FontName, Fonts, GlyphLayout, Image, RawLabel, Rgba8, TextAlign, TextLayoutOptions,
21 +
};
22 +
23 +
/// Storage for rich text. A type that can represent rich text.
24 +
pub trait RichTextStorage: AsRef<str> {
25 +
    /// Return the text spans that contain the styling information
26 +
    /// of the text returned by [`RichTextStorage::as_str`].
27 +
    fn spans(&self) -> impl Iterator<Item = &TextSpan>;
28 +
    /// Get a reference to the plain string.
29 +
    fn as_str(&self) -> &str {
30 +
        self.as_ref()
31 +
    }
32 +
    /// Get the string length.
33 +
    fn len(&self) -> usize {
34 +
        self.as_str().len()
35 +
    }
36 +
    /// Check if the string is empty.
37 +
    fn is_empty(&self) -> bool {
38 +
        self.len() == 0
39 +
    }
40 +
}
41 +
42 +
/// Font style.
43 +
#[derive(Clone, Copy, Debug, Default)]
44 +
pub enum FontStyle {
45 +
    /// The default font style.
46 +
    #[default]
47 +
    Normal,
48 +
}
49 +
50 +
/// A span of text contains text with a set style.
51 +
#[derive(Clone, Debug)]
52 +
pub struct TextSpan {
53 +
    /// The range of characters represented by this span,
54 +
    /// within the text.
55 +
    pub range: Range<usize>,
56 +
    /// The font.
57 +
    pub font: FontName,
58 +
    /// The font style.
59 +
    pub style: FontStyle,
60 +
    /// Text color.
61 +
    pub tint: Rgba8,
62 +
}
63 +
64 +
impl TextSpan {
65 +
    /// Resolve a [`TextSpan`] to a [`LoadedTextSpan`].
66 +
    pub(crate) fn load(&self, fonts: &Fonts<Image>) -> LoadedTextSpan {
67 +
        LoadedTextSpan {
68 +
            span: self.clone(),
69 +
            font: fonts.lookup(&self.font).clone(),
70 +
        }
71 +
    }
72 +
}
73 +
74 +
/// A [`TextSpan`] with a loaded font.
75 +
#[derive(Debug)]
76 +
pub struct LoadedTextSpan {
77 +
    span: TextSpan,
78 +
    font: Rc<Font<Image>>,
79 +
}
80 +
81 +
/// A span of text that was layed out with the layout engine.
82 +
#[derive(Clone, Debug)]
83 +
struct TextSpanLayout {
84 +
    /// The font used for this span.
85 +
    font: Rc<Font<Image>>,
86 +
    /// Text color.
87 +
    tint: Rgba8,
88 +
    /// The layed out glyphs.
89 +
    glyphs: Vec<GlyphLayout>,
90 +
}
91 +
92 +
impl TextSpanLayout {
93 +
    fn to_raw_label(&self) -> RawLabel<'_> {
94 +
        RawLabel {
95 +
            tile: self.font.tile_size(),
96 +
            glyphs: self.glyphs.as_slice(),
97 +
            tint: self.tint,
98 +
        }
99 +
    }
100 +
}
101 +
102 +
/// A row of text.
103 +
#[derive(Debug)]
104 +
struct TextRowLayout {
105 +
    /// Total text width for this row.
106 +
    width: f32,
107 +
    /// Glyphs, with their local screen position.
108 +
    spans: Vec<TextSpanLayout>,
109 +
}
110 +
111 +
/// Rich text that has been layed out.
112 +
#[derive(Debug)]
113 +
pub struct RichTextLayout {
114 +
    /// Area used for the text layout.
115 +
    size: Size<f32>,
116 +
    /// Lines of text.
117 +
    lines: Vec<TextRowLayout>,
118 +
}
119 +
120 +
impl RichTextLayout {
121 +
    /// Build a new rich text layout from the given inputs.
122 +
    pub fn build(
123 +
        text: &str,
124 +
        spans: &[LoadedTextSpan],
125 +
        opts: TextLayoutOptions,
126 +
        area: Size<f32>,
127 +
    ) -> Self {
128 +
        RichTextLayoutBuilder::new().build(text, spans, opts, area)
129 +
    }
130 +
}
131 +
132 +
/// Build a rich text layout.
133 +
#[derive(Debug)]
134 +
struct RichTextLayoutBuilder {
135 +
    // Glyph destination position within area.
136 +
    dst: Point2D<f32, Local>,
137 +
    // All lines.
138 +
    lines: Vec<TextRowLayout>,
139 +
    // Spans within the current line.
140 +
    line_spans: Vec<TextSpanLayout>,
141 +
    // Current line width.
142 +
    line_width: f32,
143 +
    // Glyphs within the current span.
144 +
    glyphs: Vec<GlyphLayout>,
145 +
    /// Maximum "cap height" in all spans.
146 +
    max_cap_height: u8,
147 +
    /// Maximum line height in all spans.
148 +
    max_line_height: u8,
149 +
}
150 +
151 +
impl RichTextLayoutBuilder {
152 +
    /// Create a new layout builder.
153 +
    fn new() -> Self {
154 +
        Self {
155 +
            dst: Point2D::ZERO,
156 +
            lines: Vec::new(),
157 +
            line_spans: Vec::new(),
158 +
            line_width: 0.,
159 +
            glyphs: Vec::new(),
160 +
            max_cap_height: 0,
161 +
            max_line_height: 0,
162 +
        }
163 +
    }
164 +
165 +
    /// Lay out the given text and return a [`RichTextLayout`] object.
166 +
    fn build(
167 +
        mut self,
168 +
        text: &str,
169 +
        spans: &[LoadedTextSpan],
170 +
        opts: TextLayoutOptions,
171 +
        area: Size<f32>,
172 +
    ) -> RichTextLayout {
173 +
        // Since we may have a mix of fonts, use the tallest to determine line height
174 +
        // and other metrics.
175 +
        for LoadedTextSpan { font, .. } in spans {
176 +
            assert_eq!(
177 +
                font.format,
178 +
                FontFormat::UF2,
179 +
                "RichTextLayout::new: only UF2 fonts are supported for rich text layout"
180 +
            );
181 +
            self.max_cap_height = self.max_cap_height.max(font.metrics.cap_height);
182 +
            self.max_line_height = self.max_line_height.max(font.metrics.line_height());
183 +
        }
184 +
        let line_height = opts.line_height.unwrap_or(self.max_line_height as f32);
185 +
186 +
        // Iterate over text spans.
187 +
        'outer: for LoadedTextSpan {
188 +
            span: TextSpan { range, tint, .. },
189 +
            font,
190 +
        } in spans
191 +
        {
192 +
            for word in text[range.start..range.end].split_inclusive(' ') {
193 +
                // Wrap text if the last glyph would overflow the area width.
194 +
                if self.dst.x + font.text_width(word) > area.w {
195 +
                    self.wrap_line(line_height, *tint, font.clone());
196 +
                    // Stop layout if we've overflowed the area height.
197 +
                    if self.dst.y > area.h {
198 +
                        break 'outer;
199 +
                    }
200 +
                }
201 +
                self.push_word(word, font);
202 +
            }
203 +
            self.push_span(*tint, font.clone());
204 +
        }
205 +
        self.push_line();
206 +
        self.finalize_layout(line_height, opts, area)
207 +
    }
208 +
209 +
    /// Move to the start of the next line.
210 +
    fn wrap_line(&mut self, line_height: f32, tint: Rgba8, font: Rc<Font<Image>>) {
211 +
        self.push_span(tint, font);
212 +
        self.push_line();
213 +
        self.dst.x = 0.;
214 +
        self.dst.y += line_height;
215 +
    }
216 +
217 +
    fn push_word(&mut self, word: &str, font: &Font<Image>) {
218 +
        // TODO: This is only correct for left-aligned text.
219 +
        for c in word.bytes() {
220 +
            // Only add glyphs if they aren't leading whitespace.
221 +
            if self.line_width > 0. || !c.is_ascii_whitespace() {
222 +
                self.push_glyph(c, font);
223 +
            }
224 +
        }
225 +
    }
226 +
227 +
    fn push_glyph(&mut self, c: u8, font: &Font<Image>) {
228 +
        let w = font.glyph_width(c);
229 +
230 +
        self.glyphs.push(GlyphLayout {
231 +
            character: c,
232 +
            bounds: Rect::new(self.dst, [w, font.metrics.glyph_height as f32]),
233 +
        });
234 +
        self.dst.x += w;
235 +
        self.line_width += w;
236 +
    }
237 +
238 +
    fn push_span(&mut self, tint: Rgba8, font: Rc<Font<Image>>) {
239 +
        self.line_spans.push(TextSpanLayout {
240 +
            font,
241 +
            tint,
242 +
            glyphs: mem::take(&mut self.glyphs),
243 +
        });
244 +
    }
245 +
246 +
    fn push_line(&mut self) {
247 +
        if !self.line_spans.is_empty() {
248 +
            self.lines.push(TextRowLayout {
249 +
                spans: mem::take(&mut self.line_spans),
250 +
                width: self.line_width,
251 +
            });
252 +
            self.line_width = 0.;
253 +
        }
254 +
    }
255 +
256 +
    fn finalize_layout(
257 +
        mut self,
258 +
        line_height: f32,
259 +
        opts: TextLayoutOptions,
260 +
        area: Size<f32>,
261 +
    ) -> RichTextLayout {
262 +
        // Align glyphs horizontally.
263 +
        for TextRowLayout { spans, width: w } in &mut self.lines {
264 +
            align::horizontal(
265 +
                spans.iter_mut().flat_map(|s| &mut s.glyphs),
266 +
                *w,
267 +
                opts.align,
268 +
                area,
269 +
            );
270 +
        }
271 +
        // Align glyphs vertically. We use the baseline for alignment.
272 +
        for TextRowLayout { spans, .. } in &mut self.lines {
273 +
            for span in spans {
274 +
                align::vertical(
275 +
                    span.glyphs.iter_mut(),
276 +
                    line_height,
277 +
                    self.max_cap_height as f32,
278 +
                    span.font.metrics,
279 +
                );
280 +
            }
281 +
        }
282 +
        // Calculate layout size.
283 +
        let height = line_height * self.lines.len() as f32;
284 +
        let size = if opts.align == TextAlign::Left {
285 +
            Size::new(
286 +
                self.lines
287 +
                    .iter()
288 +
                    .map(|l| l.width)
289 +
                    .max_by(|a, b| a.total_cmp(b))
290 +
                    .unwrap_or_default(),
291 +
                height,
292 +
            )
293 +
        } else {
294 +
            // If we are center-aligned, or right-aligned, we indicate that we are using up all the
295 +
            // horizontal space. Otherwise, alignment won't stack correctly if another alignment
296 +
            // calculation is used on top of this one.
297 +
            Size::new(area.w, height)
298 +
        };
299 +
300 +
        RichTextLayout {
301 +
            lines: self.lines,
302 +
            size,
303 +
        }
304 +
    }
305 +
}
306 +
307 +
impl RichTextLayout {
308 +
    /// Render the layed out text as [`Blit`] objects.
309 +
    pub fn render(&self) -> impl Iterator<Item = (Image, Blit<Local>)> + '_ {
310 +
        self.lines.iter().flat_map(|line| &line.spans).flat_map(|span| {
311 +
            let image = span.font.image.clone();
312 +
            span.to_raw_label()
313 +
                .render(image.size)
314 +
                .into_iter()
315 +
                .map(move |instance| (image.clone(), instance))
316 +
        })
317 +
    }
318 +
319 +
    /// Final size of the text area, after layout.
320 +
    pub fn size(&self) -> Size<f32> {
321 +
        self.size
322 +
    }
323 +
}
324 +
325 +
#[cfg(test)]
326 +
#[allow(clippy::unwrap_used)]
327 +
mod tests {
328 +
    use std::rc::Rc;
329 +
330 +
    use super::*;
331 +
    use crate::ui::fonts;
332 +
333 +
    #[allow(dead_code)]
334 +
    fn fonts() -> Fonts<Image> {
335 +
        let font_default = fonts::uf2::DEFAULT.decode().unwrap();
336 +
        let font_venice = fonts::uf2::VENICE.decode().unwrap();
337 +
338 +
        Fonts::new(font_default.clone()).with(fonts::uf2::VENICE.name, Rc::new(font_venice))
339 +
    }
340 +
}
ombre/src/ui/interface.rs added +693 -0
1 +
//! User interface types.
2 +
use std::collections::HashMap;
3 +
use std::marker::PhantomData;
4 +
use std::mem;
5 +
use std::ops::{Deref, DerefMut};
6 +
use std::rc::Rc;
7 +
8 +
use crate::draw::traits::Brush;
9 +
use crate::prelude::*;
10 +
use crate::ui::gfx::pipeline::Vertex;
11 +
use crate::ui::gfx::{batch::TextureInfo, pipeline, present, shape, PaintOp, VertexBatch};
12 +
use crate::ui::math::Zero;
13 +
use crate::ui::platform::WindowEvent;
14 +
use crate::ui::widgets;
15 +
use crate::ui::WindowCtx;
16 +
use crate::ui::{
17 +
    context::{Cursors, Fonts, Pipeline},
18 +
    Context, CursorDescriptor, FontDescriptor, Widget, WidgetEvent,
19 +
};
20 +
use crate::ui::{fonts, Pod};
21 +
22 +
/// Default number of vertices in the interface VBO.
23 +
/// Roughly 16MB of VRAM. This number has to be divisible by 3,
24 +
/// given that we are drawing triangles.
25 +
pub const DEFAULT_MAX_VERTICES: usize = 2usize.pow(18) - 1;
26 +
/// Default number of texture layers used by the rendering pipeline.
27 +
/// This is the maximum number of distinct texture objects available for rendering.
28 +
pub const DEFAULT_MAX_TEXTURE_LAYERS: usize = 16;
29 +
30 +
/// Interface error.
31 +
#[derive(Debug)]
32 +
pub enum Error<T: RenderBackend> {
33 +
    /// Render backend error.
34 +
    Render(T::Error),
35 +
    /// Font error.
36 +
    Font(font::FontError),
37 +
    /// Config error.
38 +
    Config(&'static str),
39 +
}
40 +
41 +
impl<T: RenderBackend> std::fmt::Display for Error<T> {
42 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43 +
        match self {
44 +
            Self::Render(e) => e.fmt(f),
45 +
            Self::Font(e) => e.fmt(f),
46 +
            Self::Config(e) => write!(f, "config: {e}"),
47 +
        }
48 +
    }
49 +
}
50 +
51 +
impl<T: RenderBackend + std::fmt::Debug> std::error::Error for Error<T> {}
52 +
53 +
impl<T: RenderBackend> From<font::FontError> for Error<T> {
54 +
    fn from(e: font::FontError) -> Self {
55 +
        Self::Font(e)
56 +
    }
57 +
}
58 +
59 +
/// Represents a layer in a 2D texture array, tracking both the source image and its index.
60 +
#[derive(Copy, Clone, PartialEq, Debug)]
61 +
struct TextureLayer {
62 +
    /// The source image ID if this layer contains an image, or `None` if the texture was generated
63 +
    /// programatically, eg. the blank texture used for shape rendering.
64 +
    image: Option<ImageId>,
65 +
    /// The GPU texture layer index where this texture is stored.
66 +
    index: u8,
67 +
}
68 +
69 +
/// Manages the state for a batched rendering system with a fixed number of texture layers.
70 +
///
71 +
/// RenderState tracks texture allocation, paint operations, and vertex batching for efficient
72 +
/// GPU rendering. It uses a fixed-size array of texture layers.
73 +
///
74 +
/// The system auto-allocates texture layers as needed when blitting images, up to the maximum
75 +
/// supported by the GPU (constant `N`). Each layer maintains its original size information, for
76 +
/// proper UV coordinate calculation in the shaders.
77 +
struct RenderState<const N: usize> {
78 +
    /// Array of texture layers
79 +
    /// The first slot is reserved for the blank texture used in shape rendering.
80 +
    textures: [Option<TextureLayer>; N],
81 +
    /// Parallel array to `textures` storing the dimensions of each image.
82 +
    /// Used for UV coordinate calculations.
83 +
    sizes: [Size<u32>; N],
84 +
    /// Queue of painting operations to be processed in the next batch.
85 +
    /// Operations are consumed and converted to vertices during batching.
86 +
    ops: Vec<PaintOp>,
87 +
    /// Accumulates vertices for all paint operations in the current batch.
88 +
    /// Used to minimize draw calls by batching compatible operations together.
89 +
    batch: VertexBatch,
90 +
}
91 +
92 +
impl<const N: usize> RenderState<N> {
93 +
    fn new(texture: TextureInfo) -> Self {
94 +
        let mut textures = [None; N];
95 +
        let sizes = [texture.size; N];
96 +
97 +
        // The first layer contains a blank texture used for rendering shapes.
98 +
        textures[0] = Some(TextureLayer {
99 +
            image: None,
100 +
            index: 0,
101 +
        });
102 +
103 +
        Self {
104 +
            textures,
105 +
            sizes,
106 +
            ops: Vec::with_capacity(256),
107 +
            batch: VertexBatch::new(texture),
108 +
        }
109 +
    }
110 +
111 +
    fn texture(&self) -> &TextureInfo {
112 +
        &self.batch.texture
113 +
    }
114 +
115 +
    // Helper function to find or create texture layer.
116 +
    fn get_or_create_layer<'f, F: RenderFrame<'f>>(
117 +
        &mut self,
118 +
        frame: &mut F,
119 +
        image: &Image,
120 +
    ) -> Option<TextureLayer> {
121 +
        // First try to find an existing layer with the given image.
122 +
        if let Some(&layer) = self.textures.iter().flatten().find(|l| l.image == Some(image.id())) {
123 +
            return Some(layer);
124 +
        }
125 +
        // Then try to create new layer.
126 +
        let index = self.textures.iter().position(Option::is_none)?;
127 +
        let layer = TextureLayer {
128 +
            image: Some(image.id()),
129 +
            index: index as u8,
130 +
        };
131 +
        self.textures[index] = Some(layer);
132 +
        self.sizes[index] = image.size;
133 +
134 +
        // Update backend texture layer with image data.
135 +
        if let Err(e) = frame.backend_mut().texture_update_layer(
136 +
            self.batch.texture.id,
137 +
            layer.index,
138 +
            Rect::origin(image.size),
139 +
            &image.pixels,
140 +
        ) {
141 +
            log::error!(target: "ui", "texture layer update error: {e}");
142 +
            return None;
143 +
        }
144 +
        Some(layer)
145 +
    }
146 +
147 +
    fn batch<'f, F: RenderFrame<'f>>(&mut self, frame: &mut F) -> Box<[Vertex]> {
148 +
        for op in mem::take(&mut self.ops) {
149 +
            match op {
150 +
                PaintOp::Blit { image, blit } => {
151 +
                    let Some(layer) = self.get_or_create_layer(frame, &image) else {
152 +
                        log::error!(
153 +
                            target: "ui",
154 +
                            "texture limit exceeded: renderer only supports {N} concurrent texture(s)"
155 +
                        );
156 +
                        continue;
157 +
                    };
158 +
                    self.batch.blit(blit, layer.index);
159 +
                }
160 +
                PaintOp::Fill {
161 +
                    rect,
162 +
                    color,
163 +
                    zdepth,
164 +
                } => {
165 +
                    self.batch.fill(
166 +
                        shape::Rectangle::from(rect).zdepth(zdepth),
167 +
                        Brush::Color(color),
168 +
                    );
169 +
                }
170 +
                PaintOp::Line {
171 +
                    from,
172 +
                    to,
173 +
                    color,
174 +
                    width,
175 +
                } => {
176 +
                    self.batch
177 +
                        .stroke(shape::Line::new(from, to), Brush::Color(color), width);
178 +
                }
179 +
                PaintOp::Stroke { rect, color, width } => {
180 +
                    self.batch
181 +
                        .stroke(shape::Rectangle::from(rect), Brush::Color(color), width);
182 +
                }
183 +
            }
184 +
        }
185 +
        self.batch.vertices()
186 +
    }
187 +
}
188 +
189 +
/// Holds debug render state.
190 +
struct DebugState {
191 +
    visible: bool,
192 +
    render: RenderState<8>,
193 +
    widget: widgets::Grid<()>,
194 +
}
195 +
196 +
/// Interface configuration.
197 +
pub struct Config {
198 +
    /// Maximum number of vertices that can be allocated by the renderer.
199 +
    /// Defaults to [`DEFAULT_MAX_VERTICES`].
200 +
    pub max_vertices: usize,
201 +
}
202 +
203 +
impl Default for Config {
204 +
    fn default() -> Self {
205 +
        Self {
206 +
            max_vertices: DEFAULT_MAX_VERTICES,
207 +
        }
208 +
    }
209 +
}
210 +
211 +
/// User interface state. Wraps the root widget with additional state
212 +
/// required to render the interface.
213 +
pub struct Interface<W, T, const N: usize = DEFAULT_MAX_TEXTURE_LAYERS> {
214 +
    /// Root of the widget tree.
215 +
    root: widgets::Pod<W, T>,
216 +
    /// Interface bounds in pixels.
217 +
    bounds: Size<f32>,
218 +
    /// UI scale.
219 +
    scale: f32,
220 +
    /// Offscreen pass ID.
221 +
    offscreen: PassId,
222 +
    /// Shading stage pipeline.
223 +
    shade: Pipeline<1, 1>,
224 +
    /// Present to screen pipeline.
225 +
    present: Pipeline<0, 1>,
226 +
    /// Render state.
227 +
    render: RenderState<N>,
228 +
    /// Debug state.
229 +
    debug: DebugState,
230 +
    /// Cursor position.
231 +
    cursor: Point2D<f32, Screen>,
232 +
    /// Current window state.
233 +
    window: WindowCtx,
234 +
    /// Size of presentation backbuffer, ie. the window's framebuffer.
235 +
    backbuffer: Size<f32>,
236 +
    /// Loaded fonts.
237 +
    fonts: Fonts<Image>,
238 +
    /// Loaded cursors.
239 +
    cursors: Cursors,
240 +
    /// Interface configuration.
241 +
    config: Config,
242 +
    /// Are there changes to render?
243 +
    dirty: bool,
244 +
    /// Widget data type witness.
245 +
    data: PhantomData<T>,
246 +
}
247 +
248 +
impl<W, T> Deref for Interface<W, T> {
249 +
    type Target = W;
250 +
251 +
    fn deref(&self) -> &Self::Target {
252 +
        &self.root.child
253 +
    }
254 +
}
255 +
256 +
impl<W, T> DerefMut for Interface<W, T> {
257 +
    fn deref_mut(&mut self) -> &mut Self::Target {
258 +
        &mut self.root.child
259 +
    }
260 +
}
261 +
262 +
impl<T, W: Widget<T>> Interface<W, T> {
263 +
    /// Get the root of the widget tree.
264 +
    pub fn root(&self) -> &W {
265 +
        &self.root.child
266 +
    }
267 +
268 +
    /// UI Event. Call this for every event received.
269 +
    pub fn event<R: RenderBackend>(
270 +
        &mut self,
271 +
        event: WindowEvent,
272 +
        data: &mut T,
273 +
        backend: &mut R,
274 +
        window: &mut platform::Window,
275 +
    ) -> Result<(), R::Error> {
276 +
        let wevent = match event {
277 +
            WindowEvent::CursorMoved { position } => {
278 +
                self.cursor = Point2D::new(position.x as f32, position.y as f32) / self.scale;
279 +
                WidgetEvent::MouseMove(self.cursor)
280 +
            }
281 +
            WindowEvent::Resized(size) => {
282 +
                // When the window is resized, we want to keep pixels aligned to the pixel grid,
283 +
                // even when UI scaling is used. To do this, we render to a subarea of the window's
284 +
                // framebuffer: the largest area with a size that is a multiple of the `scale`
285 +
                // value.
286 +
                // TODO: Use `window.set_size_limit`.
287 +
                let win_size = Size::new(size.width, size.height);
288 +
                let win_size_aligned = {
289 +
                    // Snap to the nearest multiple of the UI `scale`.
290 +
                    let w = (win_size.w as u32 / self.scale as u32) * self.scale as u32;
291 +
                    let h = (win_size.h as u32 / self.scale as u32) * self.scale as u32;
292 +
293 +
                    // Ensure minimum size.
294 +
                    let w = w.max(self.scale as u32);
295 +
                    let h = h.max(self.scale as u32);
296 +
297 +
                    Size::new(w, h)
298 +
                };
299 +
                let win_size_scaled = win_size_aligned.map(|n| n as f32) / self.scale;
300 +
301 +
                // The backbuffer is the size of the window without any scaling.
302 +
                self.backbuffer = win_size.map(|n| n as f32);
303 +
                // Window size after it is aligned to the pixel grid.
304 +
                self.window.size = win_size_aligned;
305 +
                // Interface bounds is the "virtual" size that is then scaled to the window size.
306 +
                self.bounds = win_size_scaled;
307 +
308 +
                log::debug!(
309 +
                    target: "ui",
310 +
                    "window resized to {}, aligned to {}, scaled by {} from {}",
311 +
                    win_size,
312 +
                    win_size_aligned,
313 +
                    self.scale,
314 +
                    win_size_scaled,
315 +
                );
316 +
                self.root.layout(data, self.context().as_layout(&self.fonts));
317 +
318 +
                backend.pass_resize_attachments(self.offscreen, self.bounds.map(|n| n as u32))?;
319 +
320 +
                return Ok(());
321 +
            }
322 +
            WindowEvent::RedrawRequested => {
323 +
                self.root.layout(data, self.context().as_layout(&self.fonts));
324 +
325 +
                return Ok(());
326 +
            }
327 +
            WindowEvent::MouseInput { state, button, .. } => match state {
328 +
                platform::InputState::Pressed => WidgetEvent::MouseDown(button),
329 +
                platform::InputState::Released => WidgetEvent::MouseUp(button),
330 +
                platform::InputState::Repeated => {
331 +
                    return Ok(());
332 +
                }
333 +
            },
334 +
            WindowEvent::KeyboardInput(i) if i.is_pressed() && i.key == Some(platform::Key::F9) => {
335 +
                self.debug.visible = !self.debug.visible;
336 +
337 +
                return Ok(());
338 +
            }
339 +
            WindowEvent::KeyboardInput(i) if i.is_pressed() && i.key == Some(platform::Key::F8) => {
340 +
                self.root.debug().print(&mut std::io::stdout()).ok();
341 +
342 +
                return Ok(());
343 +
            }
344 +
            WindowEvent::ReceivedCharacter(c, _mods) => WidgetEvent::Character(c),
345 +
            WindowEvent::KeyboardInput(i) => {
346 +
                if let Some(key) = i.key {
347 +
                    match i.state {
348 +
                        platform::InputState::Pressed => WidgetEvent::KeyDown(key),
349 +
                        platform::InputState::Repeated => WidgetEvent::KeyDown(key),
350 +
                        platform::InputState::Released => WidgetEvent::KeyUp(key),
351 +
                    }
352 +
                } else {
353 +
                    return Ok(());
354 +
                }
355 +
            }
356 +
            WindowEvent::CursorEntered => WidgetEvent::MouseEnter,
357 +
            WindowEvent::CursorLeft => WidgetEvent::MouseExit,
358 +
359 +
            _ => return Ok(()),
360 +
        };
361 +
        let mut win = self.window.clone();
362 +
        let ctx = self.context();
363 +
364 +
        // Process the event and re-run layout in case it was affected.
365 +
        self.root.event(&wevent, data, ctx.as_event(&self.fonts), &mut win);
366 +
        self.root.layout(data, ctx.as_layout(&self.fonts));
367 +
        self.dirty = true;
368 +
369 +
        // A widget has modified the window cursor.
370 +
        if win.cursor != self.window.cursor {
371 +
            let cursor = win.cursor.and_then(|name| self.cursors.remove(name));
372 +
            if let Some(old) = window.set_cursor(cursor) {
373 +
                if let Some(prev) = self.window.cursor {
374 +
                    self.cursors.insert(prev, old);
375 +
                }
376 +
            }
377 +
            self.window.cursor = win.cursor;
378 +
        }
379 +
380 +
        // A widget has modified the window title.
381 +
        if win.title != self.window.title {
382 +
            window.set_title(&win.title);
383 +
            self.window.title = win.title;
384 +
        }
385 +
386 +
        Ok(())
387 +
    }
388 +
389 +
    /// UI frame. Call this on every frame.
390 +
    pub fn frame<'a, 'f, F>(&mut self, data: &T, frame: &'a mut F) -> Result<(), F::Error>
391 +
    where
392 +
        F: RenderFrame<'f> + 'f,
393 +
    {
394 +
        let ctx = self.context();
395 +
396 +
        self.dirty = false;
397 +
        self.root.layout(data, ctx.as_layout(&self.fonts));
398 +
        self.root.paint(data, ctx.as_paint(&self.fonts, &mut self.render.ops));
399 +
400 +
        // Begin offscreen pass.
401 +
        frame.begin_pass(self.offscreen, PassAction::default());
402 +
        frame.apply_pipeline(&self.shade.pipeline)?;
403 +
        frame.apply_uniforms(&pipeline::Uniforms::new(
404 +
            self.bounds,
405 +
            Transform3D::identity(),
406 +
            self.render.sizes,
407 +
        ))?;
408 +
409 +
        let texture = self.render.texture().id;
410 +
        let batch = self.render.batch(frame);
411 +
        let length = batch.len();
412 +
        let chunk = self.config.max_vertices.min(length);
413 +
        let bindings = gfx::Bindings {
414 +
            vertex: self.shade.bindings.vertex,
415 +
            index: self.shade.bindings.index,
416 +
            textures: [texture],
417 +
        };
418 +
        if !batch.is_empty() {
419 +
            if log::log_enabled!(log::Level::Debug) && length > self.config.max_vertices {
420 +
                log::debug!(
421 +
                    target: "ui",
422 +
                    "vertex buffer capacity ({}) exceeded, \
423 +
                    splitting batch render of {length} vertices into {} draw calls..",
424 +
                    self.config.max_vertices,
425 +
                    length.div_ceil(chunk)
426 +
                );
427 +
            }
428 +
            for chunk in batch.chunks(chunk) {
429 +
                frame.buffer_update(bindings.vertex[0], BufferKind::Vertex, 0, chunk)?;
430 +
                frame.apply_bindings(&bindings)?;
431 +
                frame.draw(0, chunk.len(), 1)?;
432 +
            }
433 +
        }
434 +
        frame.end_pass();
435 +
436 +
        // Begin onscreen pass.
437 +
        //
438 +
        // The size of the pass is the full backbuffer size, so we clear to that size. But
439 +
        // we're only going to be drawing to a viewport that is the size of the aligned
440 +
        // window size.
441 +
        frame.begin_default_pass(PassAction::default(), self.backbuffer.map(|n| n as u32));
442 +
        frame.apply_viewport(Rect::new(
443 +
            [0, self.backbuffer.h as i32 - self.window.size.h as i32],
444 +
            self.window.size.map(|n| n as i32),
445 +
        ))?;
446 +
        frame.apply_pipeline(&self.present.pipeline)?;
447 +
        frame.apply_uniforms(&())?;
448 +
        frame.apply_bindings(&self.present.bindings)?;
449 +
        frame.draw(0, 6, 1)?;
450 +
451 +
        if self.debug.visible {
452 +
            let ctx = Context::new(self.cursor.convert(), self.window.size);
453 +
454 +
            self.debug.widget.layout(&(), ctx.as_layout(&self.fonts));
455 +
            self.debug
456 +
                .widget
457 +
                .paint(&(), ctx.as_paint(&self.fonts, &mut self.debug.render.ops));
458 +
459 +
            frame.apply_pipeline(&self.shade.pipeline)?;
460 +
            frame.apply_uniforms(&pipeline::Uniforms::new(
461 +
                [self.window.size.w as f32, self.window.size.h as f32],
462 +
                Transform3D::identity(),
463 +
                self.render.sizes,
464 +
            ))?;
465 +
466 +
            let texture = self.debug.render.texture().id;
467 +
            let batch = self.debug.render.batch(frame);
468 +
            let bindings = gfx::Bindings {
469 +
                vertex: self.shade.bindings.vertex,
470 +
                index: self.shade.bindings.index,
471 +
                textures: [texture],
472 +
            };
473 +
            frame.buffer_update(bindings.vertex[0], BufferKind::Vertex, 0, &batch)?;
474 +
            frame.apply_bindings(&bindings)?;
475 +
            frame.draw(0, batch.len(), 1)?;
476 +
        }
477 +
        frame.end_pass();
478 +
479 +
        Ok(())
480 +
    }
481 +
482 +
    /// Create a context object.
483 +
    fn context(&self) -> Context {
484 +
        debug_assert_ne!(self.bounds, Size::ZERO);
485 +
        Context::new(self.cursor.convert::<Local>(), self.bounds)
486 +
    }
487 +
}
488 +
489 +
/// Interface builder used to produce an [`Interface`].
490 +
pub struct InterfaceBuilder<'r, 'w, R: RenderBackend> {
491 +
    scale: f32,
492 +
    debug: bool,
493 +
    fonts: HashMap<FontName, Rc<Font<Image>>>,
494 +
    config: Config,
495 +
    cursors: Cursors,
496 +
    backend: &'r mut R,
497 +
    window: &'w platform::Window,
498 +
}
499 +
500 +
/// Build a new interface.
501 +
pub fn interface<'r, 'w, R: RenderBackend>(
502 +
    window: &'w platform::Window,
503 +
    backend: &'r mut R,
504 +
) -> InterfaceBuilder<'r, 'w, R> {
505 +
    InterfaceBuilder {
506 +
        debug: false,
507 +
        scale: 1.,
508 +
        fonts: HashMap::default(),
509 +
        cursors: Cursors::default(),
510 +
        config: Config::default(),
511 +
        backend,
512 +
        window,
513 +
    }
514 +
}
515 +
516 +
impl<R: RenderBackend> InterfaceBuilder<'_, '_, R> {
517 +
    /// Load a font.
518 +
    pub fn font(mut self, desc: FontDescriptor<'_>) -> Result<Self, Error<R>> {
519 +
        let name = desc.name;
520 +
        let font = self._font(desc)?;
521 +
522 +
        self.fonts.insert(name, font);
523 +
524 +
        Ok(self)
525 +
    }
526 +
527 +
    /// Load a custom cursor image.
528 +
    pub fn cursor(mut self, desc: CursorDescriptor) -> Result<Self, Error<R>> {
529 +
        let scaled = desc.image.scaled(self.scale as u32);
530 +
        let cursor = platform::Cursor::create(
531 +
            scaled.as_u32_slice(),
532 +
            scaled.size,
533 +
            desc.origin * self.scale as u32,
534 +
        );
535 +
        self.cursors.insert(desc.name, cursor);
536 +
537 +
        Ok(self)
538 +
    }
539 +
540 +
    /// Set the interface scale.
541 +
    pub fn scale(mut self, scale: f32) -> Self {
542 +
        self.scale = scale;
543 +
        self
544 +
    }
545 +
546 +
    /// Set the interface configuration.
547 +
    pub fn config(mut self, config: Config) -> Self {
548 +
        self.config = config;
549 +
        self
550 +
    }
551 +
552 +
    /// Set debug mode.
553 +
    pub fn debug(mut self, debug: bool) -> Self {
554 +
        self.debug = debug;
555 +
        self
556 +
    }
557 +
558 +
    /// Build the interface by giving it the root of the widget tree.
559 +
    pub fn build<T, W: Widget<T>>(mut self, root: W) -> Result<Interface<W, T>, Error<R>> {
560 +
        let default = self._font(fonts::uf2::DEFAULT)?;
561 +
        if self.config.max_vertices % 3 != 0 {
562 +
            return Err(Error::Config("`max_vertices` must be divisible by three"));
563 +
        }
564 +
        self._build(root, default).map_err(Error::Render)
565 +
    }
566 +
567 +
    /// Inner build function.
568 +
    fn _build<T, W: Widget<T>>(
569 +
        self,
570 +
        root: W,
571 +
        default: Rc<Font<Image>>,
572 +
    ) -> Result<Interface<W, T>, R::Error> {
573 +
        // TODO: Keep track of the fact these are scaled pixels, not real.
574 +
        let size: Size<f32> = self.window.size().into();
575 +
        // Snap this texture to the correct size!
576 +
        let size = (size / self.scale).map(|s| s.round() as u32);
577 +
        let offscreen_depth = self.backend.texture(gfx::Texture {
578 +
            data: gfx::Empty,
579 +
            access: gfx::TextureAccess::RenderTarget,
580 +
            size,
581 +
            format: gfx::TextureFormat::Depth,
582 +
            ..Default::default()
583 +
        })?;
584 +
        let offscreen_color = self.backend.texture(gfx::Texture {
585 +
            data: gfx::Empty,
586 +
            target: TextureKind::default(),
587 +
            size,
588 +
            access: gfx::TextureAccess::RenderTarget,
589 +
            wrap: gfx::TextureWrap::Clamp,
590 +
            format: gfx::TextureFormat::Rgba8,
591 +
            min_filter: FilterMode::Nearest,
592 +
            mag_filter: FilterMode::Nearest,
593 +
        })?;
594 +
        let offscreen = self.backend.pass(gfx::PassDescriptor {
595 +
            color_attachments: &[offscreen_color],
596 +
            depth_attachment: Some(offscreen_depth),
597 +
        })?;
598 +
599 +
        let layers = self.backend.texture(Texture {
600 +
            data: gfx::Empty,
601 +
            size: Size::new(256, 256),
602 +
            access: TextureAccess::Static,
603 +
            target: TextureKind::Texture2DArray { arity: 16 },
604 +
            format: TextureFormat::Srgba8,
605 +
            wrap: TextureWrap::Repeat,
606 +
            min_filter: FilterMode::Nearest,
607 +
            mag_filter: FilterMode::Nearest,
608 +
        })?;
609 +
        self.backend.texture_update_layer(
610 +
            layers,
611 +
            0,
612 +
            Rect::origin([256, 256]),
613 +
            &[Rgba8::WHITE; 256 * 256],
614 +
        )?;
615 +
        let vbo = self.backend.buffer(
616 +
            gfx::BufferKind::Vertex,
617 +
            gfx::BufferUsage::Stream,
618 +
            gfx::BufferSource::<pipeline::Vertex>::empty(self.config.max_vertices),
619 +
        )?;
620 +
        let shade = Pipeline {
621 +
            pipeline: pipeline::create::<_, DEFAULT_MAX_TEXTURE_LAYERS>(self.backend)?,
622 +
            bindings: gfx::Bindings {
623 +
                vertex: [vbo],
624 +
                index: None,
625 +
                textures: [layers],
626 +
            },
627 +
        };
628 +
        let present = Pipeline {
629 +
            pipeline: present::pipeline(self.backend)?,
630 +
            bindings: gfx::Bindings {
631 +
                vertex: [],
632 +
                index: None,
633 +
                textures: [offscreen_color],
634 +
            },
635 +
        };
636 +
        let layers = TextureInfo {
637 +
            id: layers,
638 +
            size: Size::new(256, 256),
639 +
        };
640 +
        let debug = DebugState {
641 +
            visible: self.debug,
642 +
            render: RenderState::new(layers.clone()),
643 +
            widget: widgets::grid().spacing(self.scale).color(Rgba::BLUE),
644 +
        };
645 +
        let render = RenderState::new(layers);
646 +
        let window = WindowCtx {
647 +
            title: self.window.get_title().to_owned(),
648 +
            cursor: None,
649 +
            size,
650 +
        };
651 +
        let fonts = Fonts {
652 +
            default,
653 +
            loaded: self.fonts,
654 +
        };
655 +
656 +
        Ok(Interface {
657 +
            root: Pod::new(root),
658 +
            shade,
659 +
            present,
660 +
            offscreen,
661 +
            debug,
662 +
            cursor: Point2D::ZERO,
663 +
            window,
664 +
            bounds: size.into(),
665 +
            backbuffer: self.window.size().into(),
666 +
            scale: self.scale,
667 +
            render,
668 +
            fonts,
669 +
            config: self.config,
670 +
            cursors: self.cursors,
671 +
            dirty: true,
672 +
            data: PhantomData,
673 +
        })
674 +
    }
675 +
676 +
    fn _font(&mut self, desc: FontDescriptor<'_>) -> Result<Rc<Font<Image>>, Error<R>> {
677 +
        let Font {
678 +
            widths,
679 +
            image,
680 +
            format,
681 +
            metrics,
682 +
        } = desc.decode()?;
683 +
684 +
        eprintln!("font {:?} image:{}", desc.name, image.id());
685 +
686 +
        Ok(Rc::new(Font {
687 +
            widths,
688 +
            image,
689 +
            format,
690 +
            metrics,
691 +
        }))
692 +
    }
693 +
}
ombre/src/ui/lazy.rs added +65 -0
1 +
//! Lazy values.
2 +
3 +
/// A value that gets initialized lazily, at runtime.
4 +
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
5 +
pub enum Lazy<T> {
6 +
    /// Uninitialized state.
7 +
    #[default]
8 +
    Uninit,
9 +
    /// Initialized state.
10 +
    Init(T),
11 +
}
12 +
13 +
impl<T: Copy> Lazy<T> {
14 +
    /// Return the value if it's initialized, otherwise initialize it first
15 +
    /// with the given function.
16 +
    pub fn try_get_or_init<E, F>(&mut self, init: F) -> Result<T, E>
17 +
    where
18 +
        F: FnOnce() -> Result<T, E>,
19 +
    {
20 +
        match self {
21 +
            Self::Init(val) => Ok(*val),
22 +
            Self::Uninit => {
23 +
                let val = init()?;
24 +
                *self = Self::Init(val);
25 +
                Ok(val)
26 +
            }
27 +
        }
28 +
    }
29 +
30 +
    /// Get the value if initialized.
31 +
    pub fn get(&self) -> Option<T> {
32 +
        match self {
33 +
            Self::Uninit => None,
34 +
            Self::Init(val) => Some(*val),
35 +
        }
36 +
    }
37 +
}
38 +
39 +
impl<T> Lazy<T> {
40 +
    /// Get a reference to the value, if initialized.
41 +
    pub fn get_ref(&self) -> Option<&T> {
42 +
        match self {
43 +
            Self::Uninit => None,
44 +
            Self::Init(val) => Some(val),
45 +
        }
46 +
    }
47 +
48 +
    /// Like [`Lazy::try_get_or_init`] but for infallible initializers.
49 +
    pub fn get_or_init<F>(&mut self, init: F) -> &T
50 +
    where
51 +
        F: FnOnce() -> T,
52 +
    {
53 +
        match self {
54 +
            Self::Init(val) => val,
55 +
            Self::Uninit => {
56 +
                let val = init();
57 +
                *self = Self::Init(val);
58 +
                let Self::Init(ref val) = self else {
59 +
                    todo!();
60 +
                };
61 +
                val
62 +
            }
63 +
        }
64 +
    }
65 +
}
ombre/src/ui/test.rs added +175 -0
1 +
//! Utilities for testing UIs.
2 +
use std::mem;
3 +
4 +
use crate::ui::fonts::*;
5 +
use crate::ui::gfx::PaintOp;
6 +
use crate::ui::math::*;
7 +
use crate::ui::*;
8 +
9 +
/// Test interface environment.
10 +
pub struct TestInterface<T> {
11 +
    pub(crate) ctx: Context,
12 +
    pub(crate) win: WindowCtx,
13 +
    pub(crate) fonts: Fonts<gfx::Image>,
14 +
    pub(crate) data: T,
15 +
    pub(crate) surface: TestSurface,
16 +
}
17 +
18 +
impl<T: Default> TestInterface<T> {
19 +
    /// Create a new test interface from starting data.
20 +
    pub fn new(size: impl Into<Size<u32>>) -> Self {
21 +
        let size = size.into();
22 +
        let font = dummy::font();
23 +
        let fonts = Fonts::new(font);
24 +
        let ctx = Context::new(Point2D::ZERO, size);
25 +
        let win = WindowCtx {
26 +
            title: String::from("test"),
27 +
            size,
28 +
            cursor: None,
29 +
        };
30 +
        Self {
31 +
            ctx,
32 +
            win,
33 +
            fonts,
34 +
            data: T::default(),
35 +
            surface: TestSurface::default(),
36 +
        }
37 +
    }
38 +
39 +
    /// Set a cursor position for this interface.
40 +
    pub fn with_cursor(mut self, cursor: impl Into<Point2D<f32, Local>>) -> Self {
41 +
        self.ctx.cursor = cursor.into();
42 +
        self
43 +
    }
44 +
45 +
    /// Clear the recorded paint operations.
46 +
    #[allow(dead_code)]
47 +
    pub fn clear(&mut self) {
48 +
        self.surface.operations.clear();
49 +
    }
50 +
51 +
    /// Layout a widget.
52 +
    pub fn layout<W: Widget<T>>(&mut self, widget: &mut W) -> Size<f32> {
53 +
        // TODO: How to make sure this happens in the real interface?
54 +
        self.ctx.size = widget.layout(&self.data, self.ctx.as_layout(&self.fonts));
55 +
        self.ctx.size
56 +
    }
57 +
58 +
    /// Paint a widget.
59 +
    pub fn paint<W: Widget<T>>(&mut self, widget: &mut W) {
60 +
        self.surface.operations.clear();
61 +
        widget.paint(
62 +
            &self.data,
63 +
            self.ctx.as_paint(&self.fonts, &mut self.surface.operations),
64 +
        );
65 +
    }
66 +
67 +
    /// Send an event to the UI.
68 +
    pub fn event<W: Widget<T>>(&mut self, root: &mut W, event: &WidgetEvent) -> bool {
69 +
        root.event(
70 +
            event,
71 +
            &mut self.data,
72 +
            self.ctx.as_event(&self.fonts),
73 +
            &mut self.win,
74 +
        )
75 +
    }
76 +
77 +
    /// Hover over the UI.
78 +
    pub fn hover<W: Widget<T>>(
79 +
        &mut self,
80 +
        root: &mut W,
81 +
        cursor: impl Into<Point2D<f32, Screen>>,
82 +
    ) -> bool {
83 +
        let cursor = cursor.into();
84 +
        self.ctx.cursor = cursor.transform(self.ctx.transform.inverse());
85 +
86 +
        log::debug!(target: "test", "Hover on {} @ {cursor}", root.type_name());
87 +
88 +
        self.event(root, &WidgetEvent::MouseMove(cursor))
89 +
    }
90 +
91 +
    /// Click on a UI.
92 +
    pub fn click<W: Widget<T>>(
93 +
        &mut self,
94 +
        root: &mut W,
95 +
        cursor: impl Into<Point2D<f32, Screen>>,
96 +
    ) -> bool {
97 +
        let cursor = cursor.into();
98 +
        self.ctx.cursor = cursor.transform(self.ctx.transform.inverse());
99 +
100 +
        log::debug!(target: "test", "Click on {} @ {cursor}", root.type_name());
101 +
102 +
        self.event(root, &WidgetEvent::MouseMove(cursor));
103 +
        self.event(root, &WidgetEvent::MouseDown(platform::MouseButton::Left))
104 +
            && self.event(root, &WidgetEvent::MouseUp(platform::MouseButton::Left))
105 +
    }
106 +
107 +
    /// Take the data and replace it with `None`.
108 +
    pub fn take(&mut self) -> T {
109 +
        mem::take(&mut self.data)
110 +
    }
111 +
}
112 +
113 +
/// A paint surface for testing that records paint operations.
114 +
#[derive(Default)]
115 +
pub struct TestSurface {
116 +
    pub operations: Vec<PaintOp>,
117 +
}
118 +
119 +
/// A widget that checks the received parent widget bounds.
120 +
pub struct AssertBounds {
121 +
    pub expected: Size<f32>,
122 +
}
123 +
124 +
impl<T> Widget<T> for AssertBounds {
125 +
    fn layout(&mut self, _: &T, _: LayoutCtx<'_>) -> Size<f32> {
126 +
        self.expected
127 +
    }
128 +
129 +
    fn event(&mut self, _: &WidgetEvent, _: &mut T, ctx: EventCtx<'_>, _: &mut WindowCtx) -> bool {
130 +
        assert_eq!(
131 +
            ctx.size, self.expected,
132 +
            "Child widget received incorrect size"
133 +
        );
134 +
        false
135 +
    }
136 +
137 +
    fn paint(&mut self, _: &T, ctx: PaintCtx<'_>) {
138 +
        assert_eq!(
139 +
            ctx.rect(),
140 +
            Rect::origin(self.expected),
141 +
            "Child widget received incorrect size"
142 +
        );
143 +
    }
144 +
}
145 +
146 +
/// Dummy objects.
147 +
pub mod dummy {
148 +
    use super::*;
149 +
150 +
    /// Dummy window context.
151 +
    #[allow(dead_code)]
152 +
    pub const WINDOW: WindowCtx = WindowCtx {
153 +
        title: String::new(),
154 +
        size: Size::new(640, 480),
155 +
        cursor: None,
156 +
    };
157 +
158 +
    /// Dummy font that is unusable.
159 +
    pub fn font() -> Font<gfx::Image> {
160 +
        Font {
161 +
            widths: [8; 256],
162 +
            metrics: FontMetrics {
163 +
                glyph_height: 16,
164 +
                desc_height: 3,
165 +
                cap_height: 8,
166 +
                baseline: 12,
167 +
            },
168 +
            image: gfx::Image {
169 +
                size: Size::new(256, 256),
170 +
                pixels: Default::default(),
171 +
            },
172 +
            format: FontFormat::UF2,
173 +
        }
174 +
    }
175 +
}
ombre/src/ui/tests.rs added +57 -0
1 +
use crate::ui::math::*;
2 +
use crate::ui::test::TestInterface;
3 +
use crate::ui::widgets::*;
4 +
5 +
#[test]
6 +
fn test_zstack_hover_cursor() {
7 +
    #[derive(Default, Debug, PartialEq, Eq)]
8 +
    struct Data {
9 +
        large: bool,
10 +
        small: bool,
11 +
    }
12 +
13 +
    let size = Size::new(3, 3);
14 +
    let large = Null
15 +
        .sized([3., 3.])
16 +
        .on_hover(|_, is_hot, s: &mut Data, _| s.large = is_hot)
17 +
        .cursor("large");
18 +
    let small = Null
19 +
        .sized([2., 2.])
20 +
        .on_hover(|_, is_hot, s: &mut Data, _| s.small = is_hot)
21 +
        .cursor("small");
22 +
23 +
    let mut root = zstack((large, small));
24 +
    let mut ui = TestInterface::new(size);
25 +
26 +
    assert_eq!(ui.layout(&mut root), size.into());
27 +
28 +
    assert!(ui.hover(&mut root, [2., 2.])); // Test hovering on the larger child.
29 +
    assert_eq!(
30 +
        ui.data,
31 +
        Data {
32 +
            large: true,
33 +
            small: false
34 +
        }
35 +
    );
36 +
    assert_eq!(ui.win.cursor, Some("large"));
37 +
38 +
    assert!(ui.hover(&mut root, [1., 1.])); // Test hovering over the smaller child.
39 +
    assert_eq!(
40 +
        ui.data,
41 +
        Data {
42 +
            large: true,
43 +
            small: true
44 +
        }
45 +
    );
46 +
    assert_eq!(ui.win.cursor, Some("small"));
47 +
48 +
    assert!(!ui.hover(&mut root, [3., 3.])); // Test moving out of the widget.
49 +
    assert_eq!(
50 +
        ui.data,
51 +
        Data {
52 +
            large: false,
53 +
            small: false
54 +
        }
55 +
    );
56 +
    assert_eq!(ui.win.cursor, None); // Cursor reset
57 +
}
ombre/src/ui/widgets.rs added +382 -0
1 +
//! UI widgets.
2 +
mod aligned;
3 +
mod button;
4 +
mod canvas;
5 +
mod checkbox;
6 +
mod click;
7 +
mod controller;
8 +
mod cursor;
9 +
mod dynamic;
10 +
mod grid;
11 +
mod hover;
12 +
mod hstack;
13 +
mod image;
14 +
mod input;
15 +
mod label;
16 +
mod lens;
17 +
mod null;
18 +
mod offset;
19 +
mod padding;
20 +
mod pod;
21 +
mod resized;
22 +
mod style;
23 +
mod text;
24 +
mod vstack;
25 +
mod zstack;
26 +
27 +
use std::fmt::Debug;
28 +
29 +
use crate::lenses::Lens;
30 +
use crate::ui::context::*;
31 +
use crate::ui::debug::DebugInfo;
32 +
use crate::ui::gfx::{Align, Insets, Rgba};
33 +
use crate::ui::math::*;
34 +
use crate::ui::platform;
35 +
36 +
pub use aligned::*;
37 +
pub use button::*;
38 +
pub use canvas::*;
39 +
pub use checkbox::*;
40 +
pub use click::Click;
41 +
pub use controller::*;
42 +
pub use cursor::*;
43 +
pub use dynamic::*;
44 +
pub use grid::*;
45 +
pub use hover::Hover;
46 +
pub use hstack::*;
47 +
pub use image::*;
48 +
pub use input::*;
49 +
pub use label::*;
50 +
pub use lens::*;
51 +
pub use null::*;
52 +
pub use offset::*;
53 +
pub use padding::*;
54 +
pub use pod::Pod;
55 +
pub use resized::*;
56 +
pub use style::*;
57 +
pub use text::*;
58 +
pub use vstack::*;
59 +
pub use zstack::*;
60 +
61 +
/// A widget event.
62 +
#[derive(Debug)]
63 +
pub enum WidgetEvent {
64 +
    /// Widget was resized.
65 +
    Resize(Size<u32>),
66 +
    /// Character was received from key input.
67 +
    Character(char),
68 +
    /// Key was pressed.
69 +
    KeyDown(platform::Key),
70 +
    /// Key was released.
71 +
    KeyUp(platform::Key),
72 +
    /// Mouse button was pressed.
73 +
    MouseDown(platform::MouseButton),
74 +
    /// Mouse button was released.
75 +
    MouseUp(platform::MouseButton),
76 +
    /// Mouse was scrolled.
77 +
    MouseScroll(platform::LogicalDelta),
78 +
    /// Mouse was moved.
79 +
    MouseMove(Point2D<f32, Screen>),
80 +
    /// Mouse pointer entered a widget.
81 +
    // FIXME: These are not generated.
82 +
    MouseEnter,
83 +
    /// Mouse pointer exited a widget.
84 +
    ///
85 +
    /// This event is needed because for eg. we don't get a [`WidgetEvent::MouseMove`] event
86 +
    /// when the cursor moves out of a widget.
87 +
    // FIXME: These are not generated.
88 +
    MouseExit,
89 +
    /// Animation tick.
90 +
    Tick,
91 +
}
92 +
93 +
/// A UI widget that can be painted on screen.
94 +
#[allow(unused_variables)]
95 +
pub trait Widget<T> {
96 +
    /// Compute widget size.
97 +
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
98 +
        ctx.bounds
99 +
    }
100 +
101 +
    /// Paint the widget.
102 +
    fn paint(&mut self, data: &T, ctx: PaintCtx<'_>) {}
103 +
104 +
    /// Process an event.
105 +
    /// Return `true` if the event was handled and shouldn't propagate further, or `false`
106 +
    /// if it wasn't handled, and should keep being propagated.
107 +
    fn event(
108 +
        &mut self,
109 +
        event: &WidgetEvent,
110 +
        data: &mut T,
111 +
        ctx: EventCtx<'_>,
112 +
        win: &mut WindowCtx,
113 +
    ) -> bool {
114 +
        false
115 +
    }
116 +
117 +
    /// Check whether this widget contains a point. The point is in widget-local coordinates,
118 +
    /// where `(0, 0)` is the top-left corner of the widget.
119 +
    fn contains(&self, point: Point2D<f32, Local>) -> bool {
120 +
        // Unless this widget has "holes", this should always return `true`.
121 +
        true
122 +
    }
123 +
124 +
    /// Check whether this widget is "hot".
125 +
    fn is_hot(&self, ctx: &Context) -> bool {
126 +
        ctx.is_hot() && self.contains(ctx.cursor)
127 +
    }
128 +
129 +
    /// Format this widget as a string.
130 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131 +
        self.type_name().fmt(f)
132 +
    }
133 +
134 +
    /// Widget type name.
135 +
    fn type_name(&self) -> &str {
136 +
        std::any::type_name::<Self>()
137 +
    }
138 +
139 +
    /// Widget debug information.
140 +
    fn debug(&self) -> DebugInfo {
141 +
        DebugInfo::new(self.type_name())
142 +
    }
143 +
}
144 +
145 +
impl<W, T> Widget<T> for Box<W>
146 +
where
147 +
    W: ?Sized + Widget<T>,
148 +
{
149 +
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
150 +
        (**self).layout(data, ctx)
151 +
    }
152 +
153 +
    fn paint(&mut self, data: &T, ctx: PaintCtx<'_>) {
154 +
        (**self).paint(data, ctx)
155 +
    }
156 +
157 +
    fn event(
158 +
        &mut self,
159 +
        event: &WidgetEvent,
160 +
        data: &mut T,
161 +
        ctx: EventCtx<'_>,
162 +
        win: &mut WindowCtx,
163 +
    ) -> bool {
164 +
        (**self).event(event, data, ctx, win)
165 +
    }
166 +
167 +
    fn contains(&self, point: Point2D<f32, Local>) -> bool {
168 +
        (**self).contains(point)
169 +
    }
170 +
171 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
172 +
        (**self).fmt(f)
173 +
    }
174 +
175 +
    fn type_name(&self) -> &str {
176 +
        (**self).type_name()
177 +
    }
178 +
179 +
    fn debug(&self) -> DebugInfo {
180 +
        (**self).debug()
181 +
    }
182 +
}
183 +
184 +
/// Widget extension methods.
185 +
pub trait WidgetExt<T>: Sized + Widget<T> + 'static {
186 +
    /// Box a widget.
187 +
    fn boxed(self) -> Box<dyn Widget<T> + 'static>;
188 +
    /// Convert to an [`Widget`] reference.
189 +
    fn as_dyn(&self) -> &dyn Widget<T>;
190 +
    /// Convert to a mutable [`Widget`] reference.
191 +
    fn as_dyn_mut(&mut self) -> &mut dyn Widget<T>;
192 +
    /// Center a widget.
193 +
    fn center(self) -> Aligned<Self, T>;
194 +
    /// Draw a stroke around a widget.
195 +
    fn stroke(self, stroke: impl Into<Stroke>) -> Style<Self, T>;
196 +
    /// Fill a widget with color.
197 +
    fn fill(self, color: impl Into<Rgba<f32>>) -> Style<Self, T>;
198 +
    /// Size a widget.
199 +
    fn sized<S: Into<Size<f32>>>(self, size: S) -> Resized<Self, T>;
200 +
    /// Add padding to a widget.
201 +
    fn padding(self, insets: impl Into<Insets>) -> Padding<Self, T>;
202 +
    /// Set a cursor for this widget.
203 +
    /// The cursor must be loaded with [`crate::ui::interface::InterfaceBuilder::cursor`].
204 +
    fn cursor(self, name: &str) -> Cursor<'_, Self, T>;
205 +
    /// Wrap this widget in a [`LensWrap`] widget for the provided [`Lens`].
206 +
    fn lens<U, L: Lens<T, U>>(self, lens: L) -> LensWrap<L, Self, U, T>;
207 +
}
208 +
209 +
impl<W: 'static, T> WidgetExt<T> for W
210 +
where
211 +
    W: Widget<T>,
212 +
{
213 +
    fn boxed(self) -> Box<dyn Widget<T> + 'static> {
214 +
        Box::new(self)
215 +
    }
216 +
217 +
    fn as_dyn(&self) -> &dyn Widget<T> {
218 +
        self
219 +
    }
220 +
221 +
    fn as_dyn_mut(&mut self) -> &mut dyn Widget<T> {
222 +
        self
223 +
    }
224 +
225 +
    fn stroke(self, stroke: impl Into<Stroke>) -> Style<Self, T> {
226 +
        Style::new(self).stroke(stroke)
227 +
    }
228 +
229 +
    fn fill(self, color: impl Into<Rgba<f32>>) -> Style<Self, T> {
230 +
        Style::new(self).fill(color)
231 +
    }
232 +
233 +
    fn sized<S: Into<Size<f32>>>(self, size: S) -> Resized<Self, T> {
234 +
        Resized::new(self, size.into())
235 +
    }
236 +
237 +
    fn padding(self, insets: impl Into<Insets>) -> Padding<Self, T> {
238 +
        Padding::new(self, insets.into())
239 +
    }
240 +
241 +
    fn center(self) -> Aligned<Self, T> {
242 +
        Aligned::new(self).align(Vector2D::splat(Align::Center))
243 +
    }
244 +
245 +
    fn cursor(self, name: &str) -> Cursor<'_, Self, T> {
246 +
        cursor(self).named(name)
247 +
    }
248 +
249 +
    fn lens<U, L: Lens<T, U>>(self, lens: L) -> LensWrap<L, Self, U, T> {
250 +
        LensWrap::new(self, lens)
251 +
    }
252 +
}
253 +
254 +
/// Widgets that can be interacted with.
255 +
pub trait WidgetInteract<T>: Sized + Widget<T> {
256 +
    /// Register a callback for when a widget is clicked.
257 +
    fn on_click<F>(self, action: F) -> Click<Self, T>
258 +
    where
259 +
        F: Fn(&mut Self, &mut T, &EventCtx<'_>) + 'static,
260 +
    {
261 +
        Click::new(self, action)
262 +
    }
263 +
264 +
    /// Register a callback for when a widget is hovered.
265 +
    fn on_hover<F>(self, action: F) -> Hover<Self, F>
266 +
    where
267 +
        F: Fn(&mut Self, bool, &mut T, &EventCtx<'_>),
268 +
    {
269 +
        Hover::new(self, action)
270 +
    }
271 +
272 +
    /// Register a callback that will receive all events.
273 +
    fn on_event<F>(self, action: F) -> Controller<Self, F>
274 +
    where
275 +
        F: Fn(&mut Self, &WidgetEvent, &mut T, EventCtx<'_>, &mut WindowCtx) -> bool,
276 +
    {
277 +
        Controller::new(self, action)
278 +
    }
279 +
}
280 +
281 +
impl<T, W> WidgetInteract<T> for W where W: Widget<T> + 'static {}
282 +
283 +
/// A widget list that can be converted to a widget vector.
284 +
pub trait WidgetList<T> {
285 +
    /// Convert list to vector.
286 +
    fn to_vec(self) -> Vec<Box<dyn Widget<T> + 'static>>;
287 +
}
288 +
289 +
impl<T, W1, W2> WidgetList<T> for (W1, W2)
290 +
where
291 +
    W1: Widget<T> + 'static,
292 +
    W2: Widget<T> + 'static,
293 +
{
294 +
    fn to_vec(self) -> Vec<Box<dyn Widget<T> + 'static>> {
295 +
        vec![Box::new(self.0), Box::new(self.1)]
296 +
    }
297 +
}
298 +
299 +
impl<T, W1, W2, W3> WidgetList<T> for (W1, W2, W3)
300 +
where
301 +
    W1: Widget<T> + 'static,
302 +
    W2: Widget<T> + 'static,
303 +
    W3: Widget<T> + 'static,
304 +
{
305 +
    fn to_vec(self) -> Vec<Box<dyn Widget<T> + 'static>> {
306 +
        vec![Box::new(self.0), Box::new(self.1), Box::new(self.2)]
307 +
    }
308 +
}
309 +
310 +
impl<T, W1, W2, W3, W4> WidgetList<T> for (W1, W2, W3, W4)
311 +
where
312 +
    W1: Widget<T> + 'static,
313 +
    W2: Widget<T> + 'static,
314 +
    W3: Widget<T> + 'static,
315 +
    W4: Widget<T> + 'static,
316 +
{
317 +
    fn to_vec(self) -> Vec<Box<dyn Widget<T> + 'static>> {
318 +
        vec![
319 +
            Box::new(self.0),
320 +
            Box::new(self.1),
321 +
            Box::new(self.2),
322 +
            Box::new(self.3),
323 +
        ]
324 +
    }
325 +
}
326 +
327 +
impl<T, W1, W2, W3, W4, W5> WidgetList<T> for (W1, W2, W3, W4, W5)
328 +
where
329 +
    W1: Widget<T> + 'static,
330 +
    W2: Widget<T> + 'static,
331 +
    W3: Widget<T> + 'static,
332 +
    W4: Widget<T> + 'static,
333 +
    W5: Widget<T> + 'static,
334 +
{
335 +
    fn to_vec(self) -> Vec<Box<dyn Widget<T> + 'static>> {
336 +
        vec![
337 +
            Box::new(self.0),
338 +
            Box::new(self.1),
339 +
            Box::new(self.2),
340 +
            Box::new(self.3),
341 +
            Box::new(self.4),
342 +
        ]
343 +
    }
344 +
}
345 +
346 +
impl<T, W> WidgetList<T> for Vec<W>
347 +
where
348 +
    W: Widget<T> + 'static,
349 +
{
350 +
    fn to_vec(self) -> Vec<Box<dyn Widget<T> + 'static>> {
351 +
        self.into_iter().map(|e| Box::new(e) as Box<dyn Widget<T>>).collect()
352 +
    }
353 +
}
354 +
355 +
impl<T, W, const N: usize> WidgetList<T> for [W; N]
356 +
where
357 +
    W: Widget<T> + 'static,
358 +
{
359 +
    fn to_vec(self) -> Vec<Box<dyn Widget<T> + 'static>> {
360 +
        self.into_iter().map(|e| Box::new(e) as Box<dyn Widget<T>>).collect()
361 +
    }
362 +
}
363 +
364 +
impl<T> Widget<T> for crate::ui::gfx::Rgba8 {
365 +
    fn paint(&mut self, data: &T, ctx: PaintCtx<'_>) {
366 +
        crate::ui::gfx::Rgba::<f32>::from(*self).paint(data, ctx)
367 +
    }
368 +
369 +
    fn debug(&self) -> DebugInfo {
370 +
        DebugInfo::new("Rgba8").extra(self)
371 +
    }
372 +
}
373 +
374 +
impl<T> Widget<T> for crate::ui::gfx::Rgba<f32> {
375 +
    fn paint(&mut self, _data: &T, mut ctx: PaintCtx<'_>) {
376 +
        ctx.fill(ctx.rect(), *self, ZDepth::ZERO);
377 +
    }
378 +
379 +
    fn debug(&self) -> DebugInfo {
380 +
        DebugInfo::new("Rgba").extra(crate::ui::gfx::Rgba8::from(*self))
381 +
    }
382 +
}
ombre/src/ui/widgets/aligned.rs added +193 -0
1 +
//! [`Aligned`] widget.
2 +
use std::marker::PhantomData;
3 +
4 +
use crate::ui::gfx::{Align, Align2D};
5 +
6 +
use super::*;
7 +
8 +
/// Aligns a child widget.
9 +
pub struct Aligned<W, T> {
10 +
    widget: Pod<Offset<W, T>, T>,
11 +
    size: Size<f32>,
12 +
    align: Align2D,
13 +
    data: PhantomData<T>,
14 +
}
15 +
16 +
impl<W, T> std::fmt::Debug for Aligned<W, T> {
17 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18 +
        f.debug_struct("Aligned")
19 +
            .field("align", &self.align)
20 +
            .field("size", &self.size)
21 +
            .field("origin", &self.widget.child.origin())
22 +
            .finish_non_exhaustive()
23 +
    }
24 +
}
25 +
26 +
impl<W: Widget<T>, T> Aligned<W, T> {
27 +
    /// Create a new [`Aligned`] widget from a child.
28 +
    pub fn new(widget: W) -> Self {
29 +
        Self {
30 +
            widget: Pod::new(Offset::new(widget)),
31 +
            align: Align2D::default(),
32 +
            size: Size::default(),
33 +
            data: PhantomData,
34 +
        }
35 +
    }
36 +
}
37 +
38 +
impl<W: Widget<T>, T> Widget<T> for Aligned<W, T> {
39 +
    fn event(
40 +
        &mut self,
41 +
        event: &WidgetEvent,
42 +
        data: &mut T,
43 +
        ctx: EventCtx<'_>,
44 +
        win: &mut WindowCtx,
45 +
    ) -> bool {
46 +
        self.widget.event(event, data, ctx, win)
47 +
    }
48 +
49 +
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
50 +
        let center: Vector2D<f32, ()> = Vector2D::from(ctx.bounds) / 2.;
51 +
        let parent = ctx.bounds;
52 +
        let child = self.widget.layout(data, ctx);
53 +
        let half = child / 2.;
54 +
55 +
        debug_assert_ne!(parent, Size::ZERO);
56 +
57 +
        self.widget.child.set(Vector2D::<f32, Local>::new(
58 +
            match self.align.x {
59 +
                Align::Start => 0.,
60 +
                Align::Center => center.x - half.w,
61 +
                Align::End => parent.w - child.w,
62 +
            },
63 +
            match self.align.y {
64 +
                Align::Start => 0.,
65 +
                Align::Center => center.y - half.h,
66 +
                Align::End => parent.h - child.h,
67 +
            },
68 +
        ));
69 +
        self.size = child;
70 +
71 +
        parent
72 +
    }
73 +
74 +
    fn paint(&mut self, data: &T, ctx: PaintCtx<'_>) {
75 +
        self.widget.paint(data, ctx);
76 +
    }
77 +
78 +
    fn contains(&self, point: Point2D<f32, Local>) -> bool {
79 +
        self.widget.contains(point)
80 +
    }
81 +
82 +
    fn debug(&self) -> DebugInfo {
83 +
        DebugInfo::new("Aligned")
84 +
            .children([&self.widget])
85 +
            .origin(self.widget.child.origin())
86 +
            .size(self.size)
87 +
            .extra(self.align)
88 +
    }
89 +
}
90 +
91 +
impl<W, T> Aligned<W, T> {
92 +
    /// Set the child widget alignment.
93 +
    pub fn align(mut self, align: impl Into<Align2D>) -> Self {
94 +
        self.align = align.into();
95 +
        self
96 +
    }
97 +
}
98 +
99 +
/// Create a new [`Aligned`] widget from a child.
100 +
pub fn aligned<T, W: Widget<T>>(widget: W) -> Aligned<W, T> {
101 +
    Aligned::new(widget)
102 +
}
103 +
104 +
#[cfg(test)]
105 +
mod tests {
106 +
    use super::*;
107 +
    use crate::ui::test;
108 +
    use crate::ui::test::TestInterface;
109 +
    use crate::ui::widgets;
110 +
111 +
    #[test]
112 +
    fn test_aligned_center() {
113 +
        let child = widgets::Null.sized([3., 3.]).on_click(|_, s, _| *s = true);
114 +
        let size = Size::<u32>::new(5, 5);
115 +
        let mut widget = aligned(child).align([Align::Center, Align::Center]);
116 +
        let mut ui = TestInterface::new(size);
117 +
118 +
        assert_eq!(ui.layout(&mut widget), size.into());
119 +
        assert!(ui.click(&mut widget, [2., 2.])); // Center of the widget
120 +
        assert_eq!(ui.take(), true);
121 +
        assert!(ui.click(&mut widget, [3., 3.])); // Bottom-right corner of the child
122 +
        assert_eq!(ui.take(), true);
123 +
        assert!(!ui.click(&mut widget, [0., 0.])); // Top-left corner (outside the child)
124 +
        assert_eq!(ui.take(), false);
125 +
        assert!(!ui.click(&mut widget, [4., 4.])); // Top-left corner (outside the child)
126 +
        assert_eq!(ui.take(), false);
127 +
    }
128 +
129 +
    #[test]
130 +
    fn test_aligned_top_left() {
131 +
        let child = widgets::Null.sized([3., 3.]).on_click(|_, s, _| *s = true);
132 +
        let size = Size::<u32>::new(5, 5);
133 +
        let mut widget = aligned(child).align([Align::Start, Align::Start]);
134 +
        let mut ui = TestInterface::new(size);
135 +
136 +
        assert_eq!(ui.layout(&mut widget), size.into());
137 +
        assert!(ui.click(&mut widget, [0., 0.])); // Top-left corner
138 +
        assert_eq!(ui.take(), true);
139 +
        assert!(ui.click(&mut widget, [2., 2.])); // Bottom-right corner of the child
140 +
        assert_eq!(ui.take(), true);
141 +
        assert!(!ui.click(&mut widget, [3., 3.])); // Outside the child
142 +
        assert_eq!(ui.take(), false);
143 +
    }
144 +
145 +
    #[test]
146 +
    fn test_aligned_bottom_right() {
147 +
        let child = widgets::Null.sized([3., 3.]).on_click(|_, s, _| *s = true);
148 +
        let size = Size::<u32>::new(5, 5);
149 +
        let mut widget = aligned(child).align([Align::End, Align::End]);
150 +
        let mut ui = TestInterface::new(size);
151 +
152 +
        assert_eq!(ui.layout(&mut widget), size.into());
153 +
        assert!(!ui.click(&mut widget, [0., 0.])); // Outside the child
154 +
        assert_eq!(ui.take(), false);
155 +
        assert!(!ui.click(&mut widget, [1., 1.])); // Outside the child
156 +
        assert_eq!(ui.take(), false);
157 +
        assert!(ui.click(&mut widget, [3., 3.])); // Center of the child
158 +
        assert_eq!(ui.take(), true);
159 +
        assert!(ui.click(&mut widget, [4., 4.])); // Bottom-right corner
160 +
        assert_eq!(ui.take(), true);
161 +
    }
162 +
163 +
    #[test]
164 +
    fn test_aligned_bottom_center() {
165 +
        let child = widgets::Null.sized([3., 3.]).on_click(|_, s, _| *s = true);
166 +
        let size = Size::<u32>::new(5, 5);
167 +
        let mut widget = aligned(child).align(Align2D::new(Align::Center, Align::End));
168 +
        let mut ui = TestInterface::new(size);
169 +
170 +
        assert_eq!(ui.layout(&mut widget), size.into());
171 +
        assert!(!ui.click(&mut widget, [0., 0.])); // Top-left corner (outside the child)
172 +
        assert_eq!(ui.take(), false);
173 +
        assert!(ui.click(&mut widget, [1., 2.])); // Top-left corner of the child
174 +
        assert_eq!(ui.take(), true);
175 +
        assert!(ui.click(&mut widget, [2., 2.])); // Top-center of the child
176 +
        assert_eq!(ui.take(), true);
177 +
        assert!(ui.click(&mut widget, [3., 4.])); // Bottom-right corner of the child
178 +
        assert_eq!(ui.take(), true);
179 +
        assert!(!ui.click(&mut widget, [4., 0.])); // Top-right corner (outside the child)
180 +
        assert_eq!(ui.take(), false);
181 +
    }
182 +
183 +
    #[test]
184 +
    fn test_aligned_child_size() {
185 +
        let expected = Size::new(30., 20.);
186 +
        let child = test::AssertBounds { expected };
187 +
        let mut widget = aligned(child).align([Align::Center, Align::Center]);
188 +
        let mut ui = TestInterface::<()>::new([100, 80]);
189 +
190 +
        ui.layout(&mut widget); // Cache size.
191 +
        ui.paint(&mut widget); // Trigger a size assertion.
192 +
    }
193 +
}
ombre/src/ui/widgets/button.rs added +59 -0
1 +
//! [`Button`] widget.
2 +
use super::*;
3 +
use crate::ui::gfx::text::TextValue;
4 +
5 +
/// A button that can be clicked.
6 +
#[derive(Debug)]
7 +
pub struct Button<T> {
8 +
    label: Click<Style<Padding<Label<T>, T>, T>, T>,
9 +
    size: Size<f32>,
10 +
}
11 +
12 +
impl<T> Widget<T> for Button<T> {
13 +
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
14 +
        debug_assert_ne!(ctx.bounds, Size::ZERO);
15 +
16 +
        self.size = self.label.layout(data, ctx);
17 +
        self.size
18 +
    }
19 +
20 +
    fn event(
21 +
        &mut self,
22 +
        event: &WidgetEvent,
23 +
        data: &mut T,
24 +
        ctx: EventCtx<'_>,
25 +
        win: &mut WindowCtx,
26 +
    ) -> bool {
27 +
        self.label.event(event, data, ctx, win)
28 +
    }
29 +
30 +
    fn paint(&mut self, data: &T, ctx: PaintCtx<'_>) {
31 +
        self.label.paint(data, ctx)
32 +
    }
33 +
34 +
    fn contains(&self, point: Point2D<f32, Local>) -> bool {
35 +
        self.label.contains(point)
36 +
    }
37 +
38 +
    fn debug(&self) -> DebugInfo {
39 +
        DebugInfo::new("Button").size(self.size).children([&self.label])
40 +
    }
41 +
}
42 +
43 +
impl<T> Button<T> {}
44 +
45 +
/// Create a new [`Button`] with the provided label.
46 +
pub fn button<F, T: 'static>(caption: impl Into<TextValue<T>>, on_click: F) -> Button<T>
47 +
where
48 +
    F: Fn(&mut Style<Padding<Label<T>, T>, T>, &mut T, &EventCtx<'_>) + 'static,
49 +
{
50 +
    let caption = caption.into();
51 +
52 +
    Button {
53 +
        label: label(caption)
54 +
            .padding((8.0, 12.0))
55 +
            .stroke(1.0)
56 +
            .on_click(move |btn, data, ctx| on_click(btn, data, ctx)),
57 +
        size: Size::default(),
58 +
    }
59 +
}
ombre/src/ui/widgets/canvas.rs added +113 -0
1 +
//! [`Canvas`] widget.
2 +
use crate::ui::gfx::Rgba;
3 +
4 +
use super::*;
5 +
use crate::ui::gfx::Blit;
6 +
use crate::ui::{gfx::color::Rgba8, gfx::Image, gfx::PlainText};
7 +
8 +
/// A surface that can be painted on.
9 +
pub struct Canvas<T> {
10 +
    func: Box<dyn Fn(&T, Rect<f32, Local>, Painter<'_, T>) + 'static>,
11 +
}
12 +
13 +
impl<T> Widget<T> for Canvas<T> {
14 +
    fn event(
15 +
        &mut self,
16 +
        _event: &WidgetEvent,
17 +
        _data: &mut T,
18 +
        _ctx: EventCtx<'_>,
19 +
        _win: &mut WindowCtx,
20 +
    ) -> bool {
21 +
        false
22 +
    }
23 +
24 +
    fn paint(&mut self, data: &T, ctx: PaintCtx<'_>) {
25 +
        (self.func)(
26 +
            data,
27 +
            ctx.rect(),
28 +
            Painter {
29 +
                data,
30 +
                fonts: ctx.fonts,
31 +
                ctx,
32 +
                zdepth: ZDepth::default(),
33 +
            },
34 +
        );
35 +
    }
36 +
37 +
    fn debug(&self) -> DebugInfo {
38 +
        DebugInfo::new("Canvas")
39 +
    }
40 +
}
41 +
42 +
/// Create a new [`Canvas`] with the provided paint function.
43 +
pub fn canvas<T, F>(func: F) -> Canvas<T>
44 +
where
45 +
    F: Fn(&T, Rect<f32, Local>, Painter<'_, T>) + 'static,
46 +
{
47 +
    Canvas {
48 +
        func: Box::new(func),
49 +
    }
50 +
}
51 +
52 +
/// Passed to the canvas function for painting.
53 +
pub struct Painter<'a, T> {
54 +
    data: &'a T,
55 +
    fonts: &'a Fonts<Image>,
56 +
    ctx: PaintCtx<'a>,
57 +
    zdepth: ZDepth,
58 +
}
59 +
60 +
impl<T> Painter<'_, T> {
61 +
    /// See [`PaintCtx::blit`].
62 +
    pub fn blit(
63 +
        &mut self,
64 +
        image: Image,
65 +
        src: Rect<f32, Screen>,
66 +
        dst: Rect<f32, Local>,
67 +
        tint: Rgba<f32>,
68 +
    ) {
69 +
        self.ctx.blit(image, Blit::new(src, dst).tint(tint));
70 +
    }
71 +
72 +
    /// See [`PaintCtx::fill`].
73 +
    pub fn fill(&mut self, rect: impl Into<Rect<f32, Local>>, color: impl Into<Rgba<f32>>) {
74 +
        self.ctx.fill(rect.into(), color.into(), self.zdepth)
75 +
    }
76 +
77 +
    /// See [`PaintCtx::line`].
78 +
    pub fn line(
79 +
        &mut self,
80 +
        from: impl Into<Point2D<f32, Local>>,
81 +
        to: impl Into<Point2D<f32, Local>>,
82 +
        width: f32,
83 +
        color: impl Into<Rgba<f32>>,
84 +
    ) {
85 +
        self.ctx.line(from.into(), to.into(), width, color.into())
86 +
    }
87 +
88 +
    /// Write text onto the canvas.
89 +
    pub fn write(
90 +
        &mut self,
91 +
        text: impl Into<PlainText<T>>,
92 +
        color: impl Into<Rgba8>,
93 +
        bounds: impl Into<Rect<f32, Local>>,
94 +
    ) {
95 +
        let bounds = bounds.into();
96 +
        let mut text = text.into();
97 +
        let (layout, font) = text.layout(self.data, bounds.size, self.fonts);
98 +
99 +
        for blit in layout.render(font.image.size, color.into()) {
100 +
            self.ctx.blit(font.image.clone(), blit);
101 +
        }
102 +
    }
103 +
104 +
    /// See [`PaintCtx::stroke`].
105 +
    pub fn stroke(
106 +
        &mut self,
107 +
        rect: impl Into<Rect<f32, Local>>,
108 +
        color: impl Into<Rgba<f32>>,
109 +
        width: f32,
110 +
    ) {
111 +
        self.ctx.stroke(rect.into(), color.into(), width)
112 +
    }
113 +
}
ombre/src/ui/widgets/checkbox.rs added +87 -0
1 +
//! [`Checkbox`] widget.
2 +
use crate::ui::gfx::Color;
3 +
4 +
use super::*;
5 +
use crate::ui::gfx::text::TextValue;
6 +
7 +
/// Padding between the checkbox and the caption.
8 +
const DEFAULT_PADDING: f32 = 7.;
9 +
/// Size of the checkbox.
10 +
const DEFAULT_CHECKBOX_SIZE: Size<f32> = Size::new(11., 11.);
11 +
/// Color of the checkbox.
12 +
const DEFAULT_COLOR: Rgba<f32> = Rgba::WHITE;
13 +
14 +
/// A checkbox.
15 +
#[derive(Debug)]
16 +
pub struct Checkbox {
17 +
    child: Click<Cursor<'static, HStack<bool>, bool>, bool>,
18 +
    size: Size<f32>,
19 +
}
20 +
21 +
impl Widget<bool> for Checkbox {
22 +
    fn layout(&mut self, data: &bool, ctx: LayoutCtx<'_>) -> Size<f32> {
23 +
        debug_assert_ne!(ctx.bounds, Size::ZERO);
24 +
25 +
        self.size = self.child.layout(data, ctx);
26 +
        self.size
27 +
    }
28 +
29 +
    fn event(
30 +
        &mut self,
31 +
        event: &WidgetEvent,
32 +
        data: &mut bool,
33 +
        ctx: EventCtx<'_>,
34 +
        win: &mut WindowCtx,
35 +
    ) -> bool {
36 +
        self.child.event(event, data, ctx, win)
37 +
    }
38 +
39 +
    fn paint(&mut self, active: &bool, ctx: PaintCtx<'_>) {
40 +
        self.child.paint(active, ctx)
41 +
    }
42 +
43 +
    fn contains(&self, point: Point2D<f32, Local>) -> bool {
44 +
        self.child.contains(point)
45 +
    }
46 +
47 +
    fn is_hot(&self, ctx: &Context) -> bool {
48 +
        self.child.is_hot(ctx)
49 +
    }
50 +
51 +
    fn debug(&self) -> DebugInfo {
52 +
        DebugInfo::new("Checkbox").size(self.size).children([&self.child])
53 +
    }
54 +
}
55 +
56 +
/// Create a new [`Checkbox`] with the provided caption.
57 +
pub fn checkbox(caption: impl Into<TextValue<bool>>) -> Checkbox {
58 +
    let caption = caption.into();
59 +
    let check = canvas(|active, _, mut painter| {
60 +
        if *active {
61 +
            // Draw an "X".
62 +
            painter.line(
63 +
                [0., 0.],
64 +
                [DEFAULT_CHECKBOX_SIZE.w, DEFAULT_CHECKBOX_SIZE.h],
65 +
                1.,
66 +
                DEFAULT_COLOR,
67 +
            );
68 +
            painter.line(
69 +
                [0., DEFAULT_CHECKBOX_SIZE.h],
70 +
                [DEFAULT_CHECKBOX_SIZE.w, 0.],
71 +
                1.,
72 +
                DEFAULT_COLOR,
73 +
            );
74 +
        }
75 +
        painter.stroke(Rect::origin(DEFAULT_CHECKBOX_SIZE), DEFAULT_COLOR, 1.);
76 +
    })
77 +
    .sized(DEFAULT_CHECKBOX_SIZE);
78 +
79 +
    Checkbox {
80 +
        child: hstack((check, label(caption)))
81 +
            .align(Align::Center)
82 +
            .gap(DEFAULT_PADDING) // TODO: Make configurable
83 +
            .cursor("pointer") // TODO: Make configurable
84 +
            .on_click(move |_, data, _| *data = !*data),
85 +
        size: Size::default(),
86 +
    }
87 +
}
ombre/src/ui/widgets/click.rs added +165 -0
1 +
//! [`Click`] widget.
2 +
use crate::ui::platform::MouseButton;
3 +
use crate::ui::widgets::*;
4 +
5 +
/// Adds click behavior to a widget.
6 +
pub struct Click<W, T> {
7 +
    /// Child widget.
8 +
    child: W,
9 +
    /// A closure that will be invoked when the child widget is clicked.
10 +
    action: Box<dyn Fn(&mut W, &mut T, &EventCtx<'_>)>,
11 +
    /// Whether the child widget is active.
12 +
    active: bool,
13 +
}
14 +
15 +
impl<W: std::fmt::Debug, T> std::fmt::Debug for Click<W, T> {
16 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17 +
        f.debug_struct("Click")
18 +
            .field("active", &self.active)
19 +
            .field("child", &self.child)
20 +
            .finish_non_exhaustive()
21 +
    }
22 +
}
23 +
24 +
impl<W: Widget<T>, T> Click<W, T> {
25 +
    /// Create a new [`Click`] widget.
26 +
    pub fn new<F>(child: W, action: F) -> Self
27 +
    where
28 +
        F: Fn(&mut W, &mut T, &EventCtx<'_>) + 'static,
29 +
    {
30 +
        Self {
31 +
            child,
32 +
            action: Box::new(action),
33 +
            active: false,
34 +
        }
35 +
    }
36 +
}
37 +
38 +
impl<W, T> Widget<T> for Click<W, T>
39 +
where
40 +
    W: Widget<T>,
41 +
{
42 +
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
43 +
        self.child.layout(data, ctx)
44 +
    }
45 +
46 +
    fn event(
47 +
        &mut self,
48 +
        event: &WidgetEvent,
49 +
        data: &mut T,
50 +
        ctx: EventCtx<'_>,
51 +
        win: &mut WindowCtx,
52 +
    ) -> bool {
53 +
        match event {
54 +
            WidgetEvent::MouseDown(MouseButton::Left) => {
55 +
                if self.is_hot(&ctx) {
56 +
                    self.active = true;
57 +
                    true
58 +
                } else {
59 +
                    false
60 +
                }
61 +
            }
62 +
            WidgetEvent::MouseUp(MouseButton::Left) => {
63 +
                if self.active && self.is_hot(&ctx) {
64 +
                    (self.action)(&mut self.child, data, &ctx);
65 +
                    self.active = false;
66 +
                    true
67 +
                } else {
68 +
                    false
69 +
                }
70 +
            }
71 +
            _ => self.child.event(event, data, ctx, win),
72 +
        }
73 +
    }
74 +
75 +
    fn paint(&mut self, data: &T, ctx: PaintCtx<'_>) {
76 +
        self.child.paint(data, ctx.active(self.active))
77 +
    }
78 +
79 +
    fn contains(&self, point: Point2D<f32, Local>) -> bool {
80 +
        self.child.contains(point)
81 +
    }
82 +
83 +
    fn debug(&self) -> DebugInfo {
84 +
        DebugInfo::new("Click").active(self.active).children([&self.child])
85 +
    }
86 +
}
87 +
88 +
#[cfg(test)]
89 +
mod tests {
90 +
    use super::*;
91 +
    use crate::ui::test::TestInterface;
92 +
    use crate::ui::widgets::Null;
93 +
94 +
    #[derive(Default, Debug)]
95 +
    struct State {
96 +
        clicks: usize,
97 +
    }
98 +
99 +
    #[test]
100 +
    fn test_mouse_down() {
101 +
        let mut ui = TestInterface::<State>::new([640, 480]).with_cursor([-1., -1.]);
102 +
        let mut click = Click::new(Null, |_, _, _| {});
103 +
        let handled = ui.event(&mut click, &WidgetEvent::MouseDown(MouseButton::Left));
104 +
105 +
        assert!(!ui.ctx.is_hot());
106 +
        assert!(!handled);
107 +
        assert!(!click.active);
108 +
    }
109 +
110 +
    #[test]
111 +
    fn test_mouse_down_hot() {
112 +
        let mut ui = TestInterface::<State>::new([640, 480]);
113 +
        let mut click = Click::new(Null, |_, _, _| {});
114 +
        let handled = ui.event(&mut click, &WidgetEvent::MouseDown(MouseButton::Left));
115 +
116 +
        assert!(ui.ctx.is_hot());
117 +
        assert!(handled);
118 +
        assert!(click.active);
119 +
    }
120 +
121 +
    #[test]
122 +
    fn test_mouse_up() {
123 +
        let mut ui = TestInterface::<State>::new([640, 480]);
124 +
        let mut click = Click::new(Null, move |_, s: &mut State, _| s.clicks += 1);
125 +
126 +
        assert!(!click.active);
127 +
        assert_eq!(ui.data.clicks, 0);
128 +
129 +
        click.active = true;
130 +
131 +
        let handled = ui.event(&mut click, &WidgetEvent::MouseUp(MouseButton::Left));
132 +
        assert!(handled);
133 +
        assert!(!click.active);
134 +
        assert_eq!(ui.data.clicks, 1);
135 +
136 +
        click.active = true;
137 +
138 +
        let handled = ui.event(&mut click, &WidgetEvent::MouseUp(MouseButton::Left));
139 +
        assert!(handled);
140 +
        assert!(!click.active);
141 +
        assert_eq!(ui.data.clicks, 2);
142 +
    }
143 +
144 +
    #[test]
145 +
    fn test_mouse_click_cancel() {
146 +
        let mut ui = TestInterface::<State>::new([640, 480]);
147 +
        let mut click = Click::new(Null, |_, s: &mut State, _| s.clicks += 1);
148 +
        let handled = ui.event(&mut click, &WidgetEvent::MouseMove(Point2D::new(1., 1.)));
149 +
150 +
        assert!(!handled); // Hover events aren't marked as "handled".
151 +
152 +
        let handled = ui.event(&mut click, &WidgetEvent::MouseDown(MouseButton::Left));
153 +
        assert!(handled);
154 +
        assert!(ui.ctx.is_hot());
155 +
        assert!(click.active);
156 +
157 +
        // Cursor has moved outside of widget bounds.
158 +
        ui.hover(&mut click, Point2D::new(-1., -1.));
159 +
160 +
        let handled = ui.event(&mut click, &WidgetEvent::MouseUp(MouseButton::Left));
161 +
        assert!(!handled);
162 +
        assert!(!ui.ctx.is_hot());
163 +
        assert_eq!(ui.data.clicks, 0);
164 +
    }
165 +
}
ombre/src/ui/widgets/controller.rs added +47 -0
1 +
//! The [`Controller`] widget.
2 +
use crate::ui::widgets::*;
3 +
4 +
/// Controls a widget via a supplied function.
5 +
pub struct Controller<W, F> {
6 +
    action: F,
7 +
    child: W,
8 +
}
9 +
10 +
impl<W, F> Controller<W, F> {
11 +
    /// Create a new controller.
12 +
    pub fn new(child: W, action: F) -> Self {
13 +
        Self { child, action }
14 +
    }
15 +
}
16 +
17 +
impl<T, W, F> Widget<T> for Controller<W, F>
18 +
where
19 +
    W: Widget<T>,
20 +
    F: Fn(&mut W, &WidgetEvent, &mut T, EventCtx<'_>, &mut WindowCtx) -> bool,
21 +
{
22 +
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
23 +
        self.child.layout(data, ctx)
24 +
    }
25 +
26 +
    fn event(
27 +
        &mut self,
28 +
        event: &WidgetEvent,
29 +
        data: &mut T,
30 +
        ctx: EventCtx<'_>,
31 +
        win: &mut WindowCtx,
32 +
    ) -> bool {
33 +
        (self.action)(&mut self.child, event, data, ctx, win)
34 +
    }
35 +
36 +
    fn paint(&mut self, data: &T, ctx: PaintCtx<'_>) {
37 +
        self.child.paint(data, ctx)
38 +
    }
39 +
40 +
    fn contains(&self, point: Point2D<f32, Local>) -> bool {
41 +
        self.child.contains(point)
42 +
    }
43 +
44 +
    fn debug(&self) -> DebugInfo {
45 +
        DebugInfo::new("Controller").children([&self.child])
46 +
    }
47 +
}
ombre/src/ui/widgets/cursor.rs added +116 -0
1 +
//! [`Cursor`] widget.
2 +
use std::marker::PhantomData;
3 +
4 +
use super::*;
5 +
6 +
/// Sets a cursor when the underlying widget is hot.
7 +
pub struct Cursor<'c, W, T> {
8 +
    widget: W,
9 +
    cursor: Option<&'c str>,
10 +
    hot: bool,
11 +
    data: PhantomData<T>,
12 +
}
13 +
14 +
impl<W, T> std::fmt::Debug for Cursor<'_, W, T> {
15 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16 +
        f.debug_struct("Cursor")
17 +
            .field("cursor", &self.cursor)
18 +
            .finish_non_exhaustive()
19 +
    }
20 +
}
21 +
22 +
impl<'c, W: Widget<T>, T> Cursor<'c, W, T> {
23 +
    /// Set this cursor using the name of a loaded cursor.
24 +
    pub fn named(mut self, name: &'c str) -> Self {
25 +
        self.cursor = Some(name);
26 +
        self
27 +
    }
28 +
}
29 +
30 +
impl<W: Widget<T>, T> Widget<T> for Cursor<'static, W, T> {
31 +
    fn event(
32 +
        &mut self,
33 +
        event: &WidgetEvent,
34 +
        data: &mut T,
35 +
        ctx: EventCtx<'_>,
36 +
        win: &mut WindowCtx,
37 +
    ) -> bool {
38 +
        let mut handled = false;
39 +
40 +
        if ctx.is_hot() {
41 +
            win.cursor = self.cursor;
42 +
            self.hot = true;
43 +
            handled = true;
44 +
        } else if self.hot {
45 +
            win.cursor = None;
46 +
            self.hot = false;
47 +
        }
48 +
        self.widget.event(event, data, ctx, win) || handled
49 +
    }
50 +
51 +
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
52 +
        self.widget.layout(data, ctx)
53 +
    }
54 +
55 +
    fn paint(&mut self, data: &T, ctx: PaintCtx<'_>) {
56 +
        self.widget.paint(data, ctx)
57 +
    }
58 +
59 +
    fn debug(&self) -> DebugInfo {
60 +
        DebugInfo::new("Cursor").hot(self.hot).children([&self.widget])
61 +
    }
62 +
}
63 +
64 +
/// Create a new [`Cursor`] widget from a child widget.
65 +
pub fn cursor<T, W: Widget<T>>(widget: W) -> Cursor<'static, W, T> {
66 +
    Cursor {
67 +
        widget,
68 +
        cursor: None,
69 +
        hot: false,
70 +
        data: PhantomData,
71 +
    }
72 +
}
73 +
74 +
#[cfg(test)]
75 +
mod tests {
76 +
    use super::*;
77 +
    use crate::ui::test::TestInterface;
78 +
    use crate::ui::widgets;
79 +
80 +
    #[test]
81 +
    fn test_cursor_set() {
82 +
        let child = widgets::Null.sized([10., 10.]);
83 +
        let mut widget = child.cursor("pointer");
84 +
        let mut ui = TestInterface::<()>::new([10, 10]);
85 +
86 +
        // Initial layout
87 +
        ui.layout(&mut widget);
88 +
89 +
        // Simulate mouse enter (making the widget hot)
90 +
        assert!(ui.hover(&mut widget, [5., 5.]));
91 +
        assert_eq!(ui.win.cursor, Some("pointer"));
92 +
93 +
        // Simulate mouse leave
94 +
        assert!(!ui.hover(&mut widget, [15., 15.])); // Move outside the widget
95 +
        assert_eq!(ui.win.cursor, None);
96 +
    }
97 +
98 +
    #[test]
99 +
    fn test_cursor_child_event() {
100 +
        let child = widgets::Null
101 +
            .sized([10., 10.])
102 +
            .on_click(|_, s: &mut bool, _| *s = true);
103 +
        let mut widget = child.cursor("pointer");
104 +
        let mut ui = TestInterface::new([10, 10]);
105 +
106 +
        // Initial layout
107 +
        ui.layout(&mut widget);
108 +
109 +
        // Simulate mouse enter and click
110 +
        assert!(ui.hover(&mut widget, [5., 5.]));
111 +
        assert!(ui.click(&mut widget, [5., 5.]));
112 +
113 +
        assert!(ui.take()); // Check if the click was registered
114 +
        assert_eq!(ui.win.cursor, Some("pointer"));
115 +
    }
116 +
}
ombre/src/ui/widgets/dynamic.rs added +40 -0
1 +
//! [`Dynamic`] widget.
2 +
use std::rc::Rc;
3 +
4 +
use super::*;
5 +
6 +
/// Generate a widget dynamically based on the UI state.
7 +
#[derive(Clone)]
8 +
pub struct Dynamic<W, T> {
9 +
    callback: Rc<dyn Fn(&T) -> W>,
10 +
}
11 +
12 +
impl<W, T> Widget<T> for Dynamic<W, T>
13 +
where
14 +
    W: Widget<T>,
15 +
{
16 +
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
17 +
        (self.callback)(data).layout(data, ctx)
18 +
    }
19 +
20 +
    fn event(
21 +
        &mut self,
22 +
        event: &WidgetEvent,
23 +
        data: &mut T,
24 +
        ctx: EventCtx<'_>,
25 +
        win: &mut WindowCtx,
26 +
    ) -> bool {
27 +
        (self.callback)(data).event(event, data, ctx, win)
28 +
    }
29 +
30 +
    fn paint(&mut self, data: &T, ctx: PaintCtx<'_>) {
31 +
        (self.callback)(data).paint(data, ctx)
32 +
    }
33 +
}
34 +
35 +
/// Create a new [`Dynamic`] widget.
36 +
pub fn dynamic<W, T>(callback: impl Fn(&T) -> W + 'static) -> Dynamic<W, T> {
37 +
    Dynamic {
38 +
        callback: Rc::new(callback),
39 +
    }
40 +
}
ombre/src/ui/widgets/grid.rs added +98 -0
1 +
//! [`Grid`] widget.
2 +
use std::marker::PhantomData;
3 +
4 +
use crate::ui::gfx::{Color, Rgba};
5 +
6 +
use super::*;
7 +
8 +
/// Grid widget.
9 +
pub struct Grid<T> {
10 +
    /// Line color.
11 +
    color: Rgba<f32>,
12 +
    /// Line width.
13 +
    width: f32,
14 +
    /// Line spacing.
15 +
    spacing: f32,
16 +
    data: PhantomData<T>,
17 +
}
18 +
19 +
impl<T> std::fmt::Debug for Grid<T> {
20 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21 +
        f.debug_struct("Grid")
22 +
            .field("color", &self.color)
23 +
            .field("width", &self.width)
24 +
            .field("spacing", &self.spacing)
25 +
            .finish()
26 +
    }
27 +
}
28 +
29 +
impl<T> Default for Grid<T> {
30 +
    /// Create a new [`Grid`] widget.
31 +
    fn default() -> Self {
32 +
        Self {
33 +
            color: Rgba::WHITE,
34 +
            width: 1.0,
35 +
            spacing: 1.0,
36 +
            data: PhantomData,
37 +
        }
38 +
    }
39 +
}
40 +
41 +
impl<T> Widget<T> for Grid<T> {
42 +
    fn layout(&mut self, _data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
43 +
        ctx.size
44 +
    }
45 +
46 +
    fn paint(&mut self, _data: &T, mut ctx: PaintCtx<'_>) {
47 +
        // The grid lines sit on pixel boundaries.
48 +
        let mut x = -self.width / 2.;
49 +
        let mut y = -self.width / 2.;
50 +
51 +
        while x <= ctx.size.w {
52 +
            ctx.fill(
53 +
                Rect::new([x, 0.], [self.width, ctx.size.h]),
54 +
                self.color,
55 +
                ZDepth::default(),
56 +
            );
57 +
            x += self.spacing;
58 +
        }
59 +
60 +
        while y <= ctx.size.h {
61 +
            ctx.fill(
62 +
                Rect::new([0., y], [ctx.size.w, self.width]),
63 +
                self.color,
64 +
                ZDepth::default(),
65 +
            );
66 +
            y += self.spacing;
67 +
        }
68 +
    }
69 +
70 +
    fn debug(&self) -> DebugInfo {
71 +
        DebugInfo::new("Grid")
72 +
    }
73 +
}
74 +
75 +
impl<T> Grid<T> {
76 +
    /// Set line color.
77 +
    pub fn color(mut self, color: impl Into<Rgba<f32>>) -> Self {
78 +
        self.color = color.into();
79 +
        self
80 +
    }
81 +
82 +
    /// Set grid spacing.
83 +
    pub fn spacing(mut self, spacing: f32) -> Self {
84 +
        self.spacing = spacing;
85 +
        self
86 +
    }
87 +
88 +
    /// Set line width.
89 +
    pub fn width(mut self, width: f32) -> Self {
90 +
        self.width = width;
91 +
        self
92 +
    }
93 +
}
94 +
95 +
/// Create a new [`Grid`] widget.
96 +
pub fn grid<T>() -> Grid<T> {
97 +
    Grid::default()
98 +
}
ombre/src/ui/widgets/hover.rs added +121 -0
1 +
//! [`Hover`] widget.
2 +
use crate::ui::widgets::*;
3 +
4 +
/// Adds hover behavior to a widget.
5 +
pub struct Hover<W, F> {
6 +
    /// Child widget.
7 +
    child: W,
8 +
    /// A closure that will be invoked when the child widget is hovered.
9 +
    action: F,
10 +
    /// Is the widget hot?
11 +
    hot: bool,
12 +
}
13 +
14 +
impl<W, F> Hover<W, F> {
15 +
    /// Create a new [`Hover`] widget.
16 +
    pub fn new(child: W, action: F) -> Self {
17 +
        Self {
18 +
            child,
19 +
            action,
20 +
            hot: false,
21 +
        }
22 +
    }
23 +
}
24 +
25 +
impl<T, W, F> Widget<T> for Hover<W, F>
26 +
where
27 +
    W: Widget<T>,
28 +
    F: Fn(&mut W, bool, &mut T, &EventCtx<'_>),
29 +
{
30 +
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
31 +
        self.child.layout(data, ctx)
32 +
    }
33 +
34 +
    fn event(
35 +
        &mut self,
36 +
        event: &WidgetEvent,
37 +
        data: &mut T,
38 +
        ctx: EventCtx<'_>,
39 +
        win: &mut WindowCtx,
40 +
    ) -> bool {
41 +
        match event {
42 +
            WidgetEvent::MouseMove(_) if self.child.is_hot(&ctx) => {
43 +
                if !self.hot {
44 +
                    (self.action)(&mut self.child, true, data, &ctx);
45 +
                    self.hot = true;
46 +
                }
47 +
            }
48 +
            WidgetEvent::MouseMove(_) if !self.child.is_hot(&ctx) => {
49 +
                if self.hot {
50 +
                    (self.action)(&mut self.child, false, data, &ctx);
51 +
                    self.hot = false;
52 +
                }
53 +
            }
54 +
            _ => {}
55 +
        }
56 +
        self.child.event(event, data, ctx, win)
57 +
    }
58 +
59 +
    fn paint(&mut self, data: &T, ctx: PaintCtx<'_>) {
60 +
        self.child.paint(data, ctx)
61 +
    }
62 +
63 +
    fn contains(&self, point: Point2D<f32, Local>) -> bool {
64 +
        self.child.contains(point)
65 +
    }
66 +
67 +
    fn debug(&self) -> DebugInfo {
68 +
        DebugInfo::new("Hover").hot(self.hot).children([&self.child])
69 +
    }
70 +
}
71 +
72 +
#[cfg(test)]
73 +
mod tests {
74 +
    use super::*;
75 +
    use crate::ui::test::TestInterface;
76 +
77 +
    #[test]
78 +
    fn test_hover() {
79 +
        #[derive(Default)]
80 +
        struct TestData {
81 +
            events: usize,
82 +
            is_hot: bool,
83 +
        }
84 +
        let child = Null.sized([3., 3.]);
85 +
        let mut widget = child.on_hover(|_, is_hot, data: &mut TestData, _| {
86 +
            data.events += 1;
87 +
            data.is_hot = is_hot;
88 +
        });
89 +
90 +
        let mut ui = TestInterface::<TestData>::new([4, 4]);
91 +
        ui.layout(&mut widget);
92 +
93 +
        // Test entering hover area.
94 +
        assert!(!ui.hover(&mut widget, [1., 1.])); // Event is never marked as "handled".
95 +
        assert_eq!(ui.data.events, 1);
96 +
        assert!(ui.data.is_hot);
97 +
98 +
        // Test staying within hover area.
99 +
        assert!(!ui.hover(&mut widget, [2., 2.]));
100 +
        assert_eq!(ui.data.events, 1); // Shouldn't increase.
101 +
        assert!(ui.data.is_hot);
102 +
103 +
        // Test leaving hover area.
104 +
        assert!(!ui.hover(&mut widget, [3., 3.]));
105 +
        assert_eq!(ui.data.events, 2);
106 +
        assert!(!ui.data.is_hot);
107 +
    }
108 +
109 +
    #[test]
110 +
    fn test_hover_propagation() {
111 +
        let child = Null.sized([3., 3.]).on_click(|_, data: &mut bool, _| *data = true);
112 +
        let mut widget = child.on_hover(|_, _, _, _| {});
113 +
114 +
        let mut ui = TestInterface::<bool>::new([3, 3]);
115 +
        ui.layout(&mut widget);
116 +
117 +
        // Test that hover doesn't interfere with child's event handling.
118 +
        assert!(ui.click(&mut widget, [2., 2.]));
119 +
        assert!(ui.data);
120 +
    }
121 +
}
ombre/src/ui/widgets/hstack.rs added +405 -0
1 +
//! [`HStack`] widget.
2 +
use std::ops::Range;
3 +
4 +
use super::*;
5 +
use crate::ui::widgets::Offset;
6 +
7 +
/// Horizontal stack.
8 +
#[derive(Debug)]
9 +
pub struct HStack<T> {
10 +
    size: Size,
11 +
    gap: f32,
12 +
    align: Align,
13 +
    children: Vec<Offset<Box<dyn Widget<T>>, T>>,
14 +
}
15 +
16 +
impl<T> Default for HStack<T> {
17 +
    fn default() -> Self {
18 +
        Self {
19 +
            size: Size::default(),
20 +
            gap: 0.,
21 +
            align: Align::default(),
22 +
            children: Vec::default(),
23 +
        }
24 +
    }
25 +
}
26 +
27 +
impl<T> HStack<T> {
28 +
    /// Create a new [`HStack`] from a list of child widgets.
29 +
    pub fn new(children: Vec<Box<dyn Widget<T>>>) -> Self {
30 +
        Self {
31 +
            size: Size::default(),
32 +
            gap: 0.,
33 +
            align: Align::default(),
34 +
            children: children.into_iter().map(Offset::new).collect(),
35 +
        }
36 +
    }
37 +
38 +
    /// Push a child to the widget without consuming the object.
39 +
    pub fn push(&mut self, child: impl Widget<T> + 'static) {
40 +
        self.children.push(Offset::new(Box::new(child)));
41 +
    }
42 +
43 +
    /// Add a child to the widget.
44 +
    pub fn child(mut self, child: impl Widget<T> + 'static) -> Self {
45 +
        self.push(child);
46 +
        self
47 +
    }
48 +
49 +
    /// Set item alignment.
50 +
    pub fn align(mut self, align: Align) -> Self {
51 +
        self.align = align;
52 +
        self
53 +
    }
54 +
55 +
    /// Set the gap between children.
56 +
    pub fn gap(mut self, gap: f32) -> Self {
57 +
        self.gap = gap;
58 +
        self
59 +
    }
60 +
61 +
    /// Get the widget bounds.
62 +
    pub fn bounds(&self) -> Rect<f32, Local> {
63 +
        Rect::origin(self.size)
64 +
    }
65 +
66 +
    /// Get the numebr of children.
67 +
    pub fn len(&self) -> usize {
68 +
        self.children.len()
69 +
    }
70 +
71 +
    /// Check if the widget is empty.
72 +
    pub fn is_empty(&self) -> bool {
73 +
        self.len() == 0
74 +
    }
75 +
}
76 +
77 +
impl<T> Widget<T> for HStack<T> {
78 +
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
79 +
        let mut offset = Vector2D::ZERO;
80 +
        let mut max_rh: f32 = 0.; // Max row height.
81 +
        let mut max_rw: f32 = 0.; // Max row width.
82 +
        let mut rows: Vec<(f32, Range<usize>)> = Vec::new(); // Rows.
83 +
        let mut row_start = 0;
84 +
85 +
        for (ix, widget) in self.children.iter_mut().enumerate() {
86 +
            let size = widget.layout(data, ctx.clone());
87 +
88 +
            // Check if we need to wrap to the next row.
89 +
            if offset.x + size.w > ctx.bounds.w && offset.x > 0. {
90 +
                offset.x = 0.;
91 +
                offset.y += max_rh + self.gap;
92 +
93 +
                rows.push((max_rh, row_start..ix));
94 +
                row_start = ix;
95 +
                max_rh = 0.;
96 +
            }
97 +
            widget.set(offset);
98 +
            offset.x += size.w + self.gap;
99 +
100 +
            max_rh = max_rh.max(size.h);
101 +
            max_rw = max_rw.max(offset.x - self.gap);
102 +
        }
103 +
        // Last row.
104 +
        rows.push((max_rh, row_start..self.children.len()));
105 +
106 +
        // Adjust vertical alignments.
107 +
        for (height, range) in rows {
108 +
            for child in &mut self.children[range] {
109 +
                match self.align {
110 +
                    Align::Start => {}
111 +
                    Align::End => {
112 +
                        let offset = height - child.size.h;
113 +
                        child.set([child.offset.x, child.offset.y + offset]);
114 +
                    }
115 +
                    Align::Center => {
116 +
                        let offset = (height - child.size.h) / 2.;
117 +
                        child.set([child.offset.x, child.offset.y + offset]);
118 +
                    }
119 +
                }
120 +
            }
121 +
        }
122 +
        self.size = Size::new(max_rw.min(ctx.bounds.w), offset.y + max_rh);
123 +
        self.size
124 +
    }
125 +
126 +
    fn paint(&mut self, data: &T, ctx: PaintCtx<'_>) {
127 +
        for widget in &mut self.children {
128 +
            widget.paint(
129 +
                data,
130 +
                PaintCtx {
131 +
                    ops: ctx.ops,
132 +
                    ..ctx
133 +
                },
134 +
            );
135 +
        }
136 +
    }
137 +
138 +
    fn event(
139 +
        &mut self,
140 +
        event: &WidgetEvent,
141 +
        data: &mut T,
142 +
        ctx: EventCtx<'_>,
143 +
        win: &mut WindowCtx,
144 +
    ) -> bool {
145 +
        for widget in &mut self.children {
146 +
            if widget.event(event, data, ctx, win) {
147 +
                return true;
148 +
            }
149 +
        }
150 +
        false
151 +
    }
152 +
153 +
    fn contains(&self, point: Point2D<f32, Local>) -> bool {
154 +
        if !self.bounds().contains(point) {
155 +
            return false;
156 +
        }
157 +
        for child in &self.children {
158 +
            if child.contains(point) {
159 +
                return true;
160 +
            }
161 +
        }
162 +
        false
163 +
    }
164 +
165 +
    fn debug(&self) -> DebugInfo {
166 +
        DebugInfo::new("HStack").children(&self.children).size(self.size)
167 +
    }
168 +
}
169 +
170 +
/// Create a new [`HStack`] from a list of child widgets.
171 +
pub fn hstack<W, T>(children: W) -> HStack<T>
172 +
where
173 +
    W: WidgetList<T>,
174 +
{
175 +
    HStack::new(children.to_vec())
176 +
}
177 +
178 +
#[cfg(test)]
179 +
mod tests {
180 +
    use super::*;
181 +
    use crate::ui::gfx::{Color, PaintOp, Rgba8};
182 +
    use crate::ui::test::TestInterface;
183 +
    use crate::ui::widgets;
184 +
185 +
    #[test]
186 +
    fn test_hstack() {
187 +
        let child1: widgets::Click<_, Option<u8>> =
188 +
            widgets::Null.sized([3., 3.]).on_click(|_, s, _| *s = Some(1));
189 +
        let child2: widgets::Click<_, Option<u8>> =
190 +
            widgets::Null.sized([3., 3.]).on_click(|_, s, _| *s = Some(2));
191 +
        let child3: widgets::Click<_, Option<u8>> =
192 +
            widgets::Null.sized([3., 3.]).on_click(|_, s, _| *s = Some(3));
193 +
        let size = Size::<u32>::new(3 * 3 + 2, 3); // Just enough space for the widgets with the gap.
194 +
        let mut widget = hstack((child1, child2, child3)).gap(1.);
195 +
        let mut ui = TestInterface::new(size);
196 +
197 +
        assert_eq!(ui.layout(&mut widget), size.into());
198 +
        assert!(ui.click(&mut widget, [0., 0.])); // First child.
199 +
        assert_eq!(ui.take(), Some(1));
200 +
        assert!(ui.click(&mut widget, [1., 1.])); // First child.
201 +
        assert_eq!(ui.take(), Some(1));
202 +
        assert!(!ui.click(&mut widget, [3., 1.])); // Gap between children.
203 +
        assert_eq!(ui.take(), None);
204 +
        assert!(ui.click(&mut widget, [6., 1.])); // Second child.
205 +
        assert_eq!(ui.take(), Some(2));
206 +
        assert!(!ui.click(&mut widget, [7., 1.])); // Gap between children.
207 +
        assert_eq!(ui.take(), None);
208 +
        assert!(ui.click(&mut widget, [9., 1.])); // Third child.
209 +
        assert_eq!(ui.take(), Some(3));
210 +
        assert!(!ui.click(&mut widget, [11., 1.])); // Out of bounds.
211 +
        assert_eq!(ui.take(), None);
212 +
    }
213 +
214 +
    #[test]
215 +
    fn test_hstack_paint_nowrap() {
216 +
        let child1: Resized<_, ()> = Rgba8::RED.sized([3., 3.]);
217 +
        let child2: Resized<_, ()> = Rgba8::GREEN.sized([3., 3.]);
218 +
        let child3: Resized<_, ()> = Rgba8::BLUE.sized([3., 3.]);
219 +
        let size = Size::<u32>::new(3 * 3 + 2, 3); // Just enough space for the widgets with the gap.
220 +
        let mut widget = hstack((child1, child2, child3)).gap(1.);
221 +
        let mut ui = TestInterface::new(size);
222 +
223 +
        ui.layout(&mut widget);
224 +
        ui.paint(&mut widget);
225 +
226 +
        let ops = ui.surface.operations.as_slice();
227 +
        assert_eq!(ops.len(), 3); // One fill operation for each child
228 +
229 +
        if let [PaintOp::Fill {
230 +
            rect: r1,
231 +
            color: c1,
232 +
            ..
233 +
        }, PaintOp::Fill {
234 +
            rect: r2,
235 +
            color: c2,
236 +
            ..
237 +
        }, PaintOp::Fill {
238 +
            rect: r3,
239 +
            color: c3,
240 +
            ..
241 +
        }] = ops
242 +
        {
243 +
            assert_eq!(r1.origin, Point2D::new(0., 0.));
244 +
            assert_eq!(r1.size, Size::new(3., 3.));
245 +
            assert_eq!(c1, &Rgba::RED);
246 +
247 +
            assert_eq!(r2.origin, Point2D::new(4., 0.));
248 +
            assert_eq!(r2.size, Size::new(3., 3.));
249 +
            assert_eq!(c2, &Rgba::GREEN);
250 +
251 +
            assert_eq!(r3.origin, Point2D::new(8., 0.));
252 +
            assert_eq!(r3.size, Size::new(3., 3.));
253 +
            assert_eq!(c3, &Rgba::BLUE);
254 +
        } else {
255 +
            panic!("Unexpected paint operations {ops:#?}");
256 +
        }
257 +
    }
258 +
259 +
    #[test]
260 +
    fn test_hstack_paint_wrap() {
261 +
        let child1: Resized<_, ()> = Rgba8::RED.sized([3., 3.]);
262 +
        let child2: Resized<_, ()> = Rgba8::GREEN.sized([3., 3.]);
263 +
        let child3: Resized<_, ()> = Rgba8::BLUE.sized([3., 3.]);
264 +
        let child4: Resized<_, ()> = Rgba8::YELLOW.sized([3., 3.]);
265 +
266 +
        // Window width is 7, which can fit two 3-pixel widgets with a 1-pixel gap
267 +
        let size = Size::<u32>::new(7, 10);
268 +
        let mut widget = hstack((child1, child2, child3, child4)).gap(1.);
269 +
        let mut ui = TestInterface::new(size);
270 +
271 +
        let layout_size = ui.layout(&mut widget);
272 +
        assert_eq!(layout_size, Size::new(7., 7.)); // Two rows of height 3 with a 1-pixel gap between them
273 +
274 +
        ui.paint(&mut widget);
275 +
276 +
        let ops = ui.surface.operations.as_slice();
277 +
        assert_eq!(ops.len(), 4); // One fill operation for each child
278 +
279 +
        if let [PaintOp::Fill {
280 +
            rect: r1,
281 +
            color: c1,
282 +
            ..
283 +
        }, PaintOp::Fill {
284 +
            rect: r2,
285 +
            color: c2,
286 +
            ..
287 +
        }, PaintOp::Fill {
288 +
            rect: r3,
289 +
            color: c3,
290 +
            ..
291 +
        }, PaintOp::Fill {
292 +
            rect: r4,
293 +
            color: c4,
294 +
            ..
295 +
        }] = ops
296 +
        {
297 +
            // First row
298 +
            assert_eq!(r1.origin, Point2D::new(0., 0.));
299 +
            assert_eq!(r1.size, Size::new(3., 3.));
300 +
            assert_eq!(c1, &Rgba::RED);
301 +
302 +
            assert_eq!(r2.origin, Point2D::new(4., 0.)); // 3 + 1 gap
303 +
            assert_eq!(r2.size, Size::new(3., 3.));
304 +
            assert_eq!(c2, &Rgba::GREEN);
305 +
306 +
            // Second row (wrapped)
307 +
            assert_eq!(r3.origin, Point2D::new(0., 4.)); // 3 + 1 vertical gap
308 +
            assert_eq!(r3.size, Size::new(3., 3.));
309 +
            assert_eq!(c3, &Rgba::BLUE);
310 +
311 +
            assert_eq!(r4.origin, Point2D::new(4., 4.)); // 3 + 1 horizontal gap, 3 + 1 vertical gap
312 +
            assert_eq!(r4.size, Size::new(3., 3.));
313 +
            assert_eq!(c4, &Rgba::YELLOW);
314 +
        } else {
315 +
            panic!("Unexpected paint operations {ops:#?}");
316 +
        }
317 +
    }
318 +
319 +
    #[test]
320 +
    fn test_hstack_paint_center_aligned() {
321 +
        let red: Resized<_, ()> = Rgba8::RED.sized([2., 2.]);
322 +
        let green: Resized<_, ()> = Rgba8::GREEN.sized([3., 4.]);
323 +
        let blue: Resized<_, ()> = Rgba8::BLUE.sized([1., 6.]);
324 +
        let size = Size::<u32>::new(12, 6);
325 +
        let mut widget: HStack<()> = hstack((red, green, blue)).align(Align::Center);
326 +
        let mut ui = TestInterface::new(size);
327 +
328 +
        ui.layout(&mut widget);
329 +
        ui.paint(&mut widget);
330 +
331 +
        let ops = ui.surface.operations.as_slice();
332 +
        assert_eq!(ops.len(), 3); // One fill operation for each child
333 +
334 +
        if let [PaintOp::Fill {
335 +
            rect: r1,
336 +
            color: c1,
337 +
            ..
338 +
        }, PaintOp::Fill {
339 +
            rect: r2,
340 +
            color: c2,
341 +
            ..
342 +
        }, PaintOp::Fill {
343 +
            rect: r3,
344 +
            color: c3,
345 +
            ..
346 +
        }] = ops
347 +
        {
348 +
            assert_eq!(r1.origin, Point2D::new(0., 2.));
349 +
            assert_eq!(r1.size, Size::new(2., 2.));
350 +
            assert_eq!(c1, &Rgba::RED);
351 +
352 +
            assert_eq!(r2.origin, Point2D::new(2., 1.));
353 +
            assert_eq!(r2.size, Size::new(3., 4.));
354 +
            assert_eq!(c2, &Rgba::GREEN);
355 +
356 +
            assert_eq!(r3.origin, Point2D::new(5., 0.));
357 +
            assert_eq!(r3.size, Size::new(1., 6.));
358 +
            assert_eq!(c3, &Rgba::BLUE);
359 +
        } else {
360 +
            panic!("Unexpected paint operations {ops:#?}");
361 +
        }
362 +
    }
363 +
364 +
    #[test]
365 +
    fn test_hstack_wrap() {
366 +
        let child1 = widgets::Null.sized([3., 3.]);
367 +
        let child2 = widgets::Null.sized([3., 3.]);
368 +
        let child3 = widgets::Null.sized([3., 3.]);
369 +
        let child4 = widgets::Null.sized([3., 3.]);
370 +
        let mut widget = hstack((child1, child2, child3, child4)).gap(1.);
371 +
372 +
        // Test cases: (container size, expected layout size).
373 +
        let tests = vec![
374 +
            ([15, u32::MAX], [15., 3.]), // Fits all 4 widgets in one row.
375 +
            ([11, u32::MAX], [11., 7.]), // Fits only 3 widgets in one row.
376 +
            ([8, u32::MAX], [7., 7.]),   // Fits 2 widgets per row.
377 +
            ([5, u32::MAX], [3., 15.]),  // Fits 1 widget per row.
378 +
            ([2, u32::MAX], [2., 15.]),  // Container smaller than widgets.
379 +
        ];
380 +
381 +
        for (container, expected) in tests {
382 +
            let expected = Size::from(expected);
383 +
            let container = Size::<u32>::from(container);
384 +
385 +
            let mut ui = TestInterface::<()>::new(container);
386 +
            let actual = ui.layout(&mut widget);
387 +
388 +
            assert_eq!(
389 +
                actual, expected,
390 +
                "For container {container}, expected {expected}, got {actual}",
391 +
            );
392 +
393 +
            // Ensure no child extends beyond the layout width.
394 +
            ui.paint(&mut widget);
395 +
            for op in &ui.surface.operations {
396 +
                if let PaintOp::Fill { rect, .. } = op {
397 +
                    assert!(
398 +
                        rect.max().x <= expected.w,
399 +
                        "Child extends beyond container {container}",
400 +
                    );
401 +
                }
402 +
            }
403 +
        }
404 +
    }
405 +
}
ombre/src/ui/widgets/image.rs added +36 -0
1 +
//! [`Image`] widget.
2 +
use crate::ui::gfx::color::Rgba;
3 +
use crate::ui::gfx::Blit;
4 +
use crate::ui::gfx::Color;
5 +
6 +
use crate::ui::gfx;
7 +
use crate::ui::widgets::*;
8 +
9 +
/// Paints an image on the screen.
10 +
pub struct Image {
11 +
    src: gfx::Image,
12 +
    tint: Rgba<f32>,
13 +
}
14 +
15 +
impl From<gfx::Image> for Image {
16 +
    fn from(src: gfx::Image) -> Self {
17 +
        image(src)
18 +
    }
19 +
}
20 +
21 +
impl<T> Widget<T> for Image {
22 +
    fn paint(&mut self, _data: &T, mut ctx: PaintCtx<'_>) {
23 +
        ctx.blit(
24 +
            self.src.clone(),
25 +
            Blit::new(Rect::origin(self.src.size), ctx.rect()).tint(self.tint),
26 +
        );
27 +
    }
28 +
}
29 +
30 +
/// Create a new [`Image`] widget.
31 +
pub fn image(src: gfx::Image) -> Image {
32 +
    Image {
33 +
        src,
34 +
        tint: Rgba::TRANSPARENT,
35 +
    }
36 +
}
ombre/src/ui/widgets/input.rs added +363 -0
1 +
//! [`Input`] widget.
2 +
use std::marker::PhantomData;
3 +
4 +
use crate::ui::gfx::{Color as _, Rgba8};
5 +
6 +
use super::*;
7 +
use crate::bail;
8 +
use crate::ui::fonts::{FontName, DEFAULT_FONT};
9 +
use crate::ui::gfx::text::{PlainText, TextStorage};
10 +
use crate::ui::gfx::TextLayoutOptions;
11 +
use crate::ui::widgets::Label;
12 +
13 +
/// A text input field.
14 +
#[derive(Debug)]
15 +
pub struct Input<T> {
16 +
    text: PlainText<T>,
17 +
    color: Rgba8,
18 +
    cursor: usize,
19 +
    size: Size<f32>,
20 +
    placeholder: Label<String>,
21 +
    padding: Size<f32>,
22 +
    active: bool,
23 +
    witness: PhantomData<T>,
24 +
}
25 +
26 +
impl<T: TextStorage> Widget<T> for Input<T> {
27 +
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
28 +
        debug_assert_ne!(ctx.bounds, Size::ZERO);
29 +
30 +
        self.text.layout(data, ctx.bounds - self.padding * 2., ctx.fonts);
31 +
32 +
        self.size = ctx.bounds;
33 +
        self.size
34 +
    }
35 +
36 +
    fn event(
37 +
        &mut self,
38 +
        event: &WidgetEvent,
39 +
        data: &mut T,
40 +
        ctx: EventCtx<'_>,
41 +
        _win: &mut WindowCtx,
42 +
    ) -> bool {
43 +
        match event {
44 +
            WidgetEvent::MouseDown(_) => {
45 +
                self.active = ctx.is_hot();
46 +
                // The event is considered handled if we clicked on the input.
47 +
                return self.active;
48 +
            }
49 +
            WidgetEvent::KeyDown(platform::Key::Left) if self.active => {
50 +
                if self.cursor > 0 {
51 +
                    self.cursor -= 1;
52 +
                }
53 +
            }
54 +
            WidgetEvent::KeyDown(platform::Key::Right) if self.active => {
55 +
                if self.cursor < data.len() {
56 +
                    self.cursor += 1;
57 +
                }
58 +
            }
59 +
            WidgetEvent::KeyDown(platform::Key::Home) if self.active => {
60 +
                self.cursor = 0;
61 +
            }
62 +
            WidgetEvent::KeyDown(platform::Key::End) if self.active => {
63 +
                self.cursor = data.len();
64 +
            }
65 +
            WidgetEvent::KeyDown(platform::Key::Backspace) if self.active => {
66 +
                if self.cursor > 0 {
67 +
                    self.cursor -= 1;
68 +
                    data.remove(self.cursor);
69 +
                    self.text.set(data.as_str());
70 +
                }
71 +
            }
72 +
            WidgetEvent::KeyDown(platform::Key::Delete) if self.active => {
73 +
                if self.cursor < data.len() {
74 +
                    data.remove(self.cursor);
75 +
                    self.text.set(data.as_str());
76 +
                }
77 +
            }
78 +
            WidgetEvent::Character(c) if self.active => {
79 +
                if let Some(layout) = &self.text.layout {
80 +
                    let font = ctx.fonts.lookup(&self.text.font);
81 +
                    if layout.is_space_remaining(*c as u8, font) {
82 +
                        data.insert(self.cursor, *c);
83 +
                        self.text.set(data.as_str());
84 +
                        self.cursor += 1;
85 +
                    }
86 +
                }
87 +
            }
88 +
            _ => return false,
89 +
        }
90 +
        self.active
91 +
    }
92 +
93 +
    fn paint(&mut self, _data: &T, ctx: PaintCtx<'_>) {
94 +
        let mut ctx = ctx.inset(self.padding);
95 +
        let Some(font) = self.text.font() else {
96 +
            bail!("Font {:?} was not initialized", self.text.font)
97 +
        };
98 +
        let Some(layout) = &self.text.layout else {
99 +
            log::error!(target: "ui", "Cannot compute character offset: text layout not found");
100 +
            return;
101 +
        };
102 +
        // Text offset.
103 +
        let offset = if ctx.size.h != layout.size.h {
104 +
            Vector2D::new(0., (ctx.size.h - layout.size.h) / 2.).expand()
105 +
        } else {
106 +
            Vector2D::ZERO
107 +
        };
108 +
        if self.active {
109 +
            let ix = self.cursor;
110 +
            let position = if ix == 0 {
111 +
                Some(offset.into())
112 +
            } else {
113 +
                layout.chars().nth(ix).map(|r| r.origin).or_else(|| {
114 +
                    layout
115 +
                        .chars()
116 +
                        .last()
117 +
                        .map(|last| Point2D::new(last.origin.x + last.width(), offset.y))
118 +
                })
119 +
            };
120 +
121 +
            if let Some(cursor) = position {
122 +
                ctx.fill(
123 +
                    Rect::new([cursor.x, cursor.y], [1., layout.line_height()]),
124 +
                    Rgba::RED,
125 +
                    ZDepth::ZERO,
126 +
                );
127 +
            }
128 +
        }
129 +
        for blit in layout.render(font.image.size, self.color) {
130 +
            ctx.blit(
131 +
                font.image.clone(),
132 +
                blit.transform(Transform2D::translate(offset)),
133 +
            );
134 +
        }
135 +
    }
136 +
137 +
    fn debug(&self) -> DebugInfo {
138 +
        DebugInfo::new("Input").children([&self.placeholder])
139 +
    }
140 +
}
141 +
142 +
impl<T> Input<T> {
143 +
    /// Set the input font.
144 +
    pub fn font(mut self, font: impl Into<FontName>) -> Self {
145 +
        self.text.font = font.into();
146 +
        self
147 +
    }
148 +
149 +
    /// Set the padding.
150 +
    pub fn padding(mut self, padding: impl Into<Size<f32>>) -> Self {
151 +
        self.padding = padding.into();
152 +
        self
153 +
    }
154 +
}
155 +
156 +
/// Create a new [`Input`] with the provided placeholder.
157 +
pub fn input<T>(placeholder: Label<String>) -> Input<T> {
158 +
    let style = TextLayoutOptions::default();
159 +
160 +
    Input {
161 +
        color: Rgba8::WHITE,
162 +
        size: Size::default(),
163 +
        text: PlainText::new(DEFAULT_FONT, style, ""),
164 +
        cursor: 0,
165 +
        active: false,
166 +
        placeholder,
167 +
        witness: PhantomData,
168 +
        padding: Size::default(),
169 +
    }
170 +
}
171 +
172 +
#[cfg(test)]
173 +
mod tests {
174 +
    use super::*;
175 +
    use crate::ui::test::TestInterface;
176 +
    use crate::ui::widgets;
177 +
178 +
    fn activate(widget: &mut Input<String>, ui: &mut TestInterface<String>) {
179 +
        ui.layout(widget);
180 +
        ui.click(widget, [10., 15.]);
181 +
182 +
        assert!(widget.active);
183 +
    }
184 +
185 +
    #[test]
186 +
    fn test_input_basic() {
187 +
        let mut widget = input(widgets::label("Type something.."));
188 +
        let mut ui = TestInterface::<String>::new([64, 16]);
189 +
        let size = ui.layout(&mut widget);
190 +
        assert_eq!(size, Size::new(64., 16.));
191 +
192 +
        activate(&mut widget, &mut ui);
193 +
194 +
        ui.event(&mut widget, &WidgetEvent::Character('H'));
195 +
        ui.layout(&mut widget);
196 +
        ui.event(&mut widget, &WidgetEvent::Character('e'));
197 +
        ui.layout(&mut widget);
198 +
        ui.event(&mut widget, &WidgetEvent::Character('l'));
199 +
        ui.layout(&mut widget);
200 +
        ui.event(&mut widget, &WidgetEvent::Character('l'));
201 +
        ui.layout(&mut widget);
202 +
        ui.event(&mut widget, &WidgetEvent::Character('o'));
203 +
        ui.layout(&mut widget);
204 +
205 +
        assert_eq!(ui.data, "Hello");
206 +
        assert_eq!(widget.cursor, 5);
207 +
    }
208 +
209 +
    #[test]
210 +
    fn test_input_key_left() {
211 +
        let mut widget = input(widgets::label("Type something.."));
212 +
        let mut ui = TestInterface::<String>::new([64, 16]);
213 +
        activate(&mut widget, &mut ui);
214 +
215 +
        ui.data = String::from("Hello");
216 +
        widget.cursor = 5;
217 +
218 +
        ui.event(&mut widget, &WidgetEvent::KeyDown(platform::Key::Left));
219 +
        assert_eq!(widget.cursor, 4);
220 +
221 +
        // Test left key at start of input
222 +
        widget.cursor = 0;
223 +
        ui.event(&mut widget, &WidgetEvent::KeyDown(platform::Key::Left));
224 +
        assert_eq!(widget.cursor, 0);
225 +
    }
226 +
227 +
    #[test]
228 +
    fn test_input_key_right() {
229 +
        let mut widget = input(widgets::label("Type something.."));
230 +
        let mut ui = TestInterface::<String>::new([64, 16]);
231 +
        activate(&mut widget, &mut ui);
232 +
233 +
        ui.data = String::from("Hello");
234 +
        widget.cursor = 0;
235 +
236 +
        ui.event(&mut widget, &WidgetEvent::KeyDown(platform::Key::Right));
237 +
        assert_eq!(widget.cursor, 1);
238 +
239 +
        // Test right key at end of input
240 +
        widget.cursor = 5;
241 +
        ui.event(&mut widget, &WidgetEvent::KeyDown(platform::Key::Right));
242 +
        assert_eq!(widget.cursor, 5);
243 +
    }
244 +
245 +
    #[test]
246 +
    fn test_input_key_home() {
247 +
        let mut widget = input(widgets::label("Type something.."));
248 +
        let mut ui = TestInterface::<String>::new([64, 16]);
249 +
        activate(&mut widget, &mut ui);
250 +
251 +
        ui.data = String::from("Hello");
252 +
        widget.cursor = 3;
253 +
254 +
        ui.event(&mut widget, &WidgetEvent::KeyDown(platform::Key::Home));
255 +
        assert_eq!(widget.cursor, 0);
256 +
    }
257 +
258 +
    #[test]
259 +
    fn test_input_key_end() {
260 +
        let mut widget = input(widgets::label("Type something.."));
261 +
        let mut ui = TestInterface::<String>::new([64, 16]);
262 +
        activate(&mut widget, &mut ui);
263 +
264 +
        ui.data = String::from("Hello");
265 +
        widget.cursor = 2;
266 +
267 +
        ui.event(&mut widget, &WidgetEvent::KeyDown(platform::Key::End));
268 +
        assert_eq!(widget.cursor, 5);
269 +
    }
270 +
271 +
    #[test]
272 +
    fn test_input_key_backspace() {
273 +
        let mut widget = input(widgets::label("Type something.."));
274 +
        let mut ui = TestInterface::<String>::new([64, 16]);
275 +
        activate(&mut widget, &mut ui);
276 +
277 +
        ui.data = String::from("Hello");
278 +
        widget.cursor = 5;
279 +
280 +
        ui.event(&mut widget, &WidgetEvent::KeyDown(platform::Key::Backspace));
281 +
        assert_eq!(ui.data, "Hell");
282 +
        assert_eq!(widget.cursor, 4);
283 +
284 +
        // Test backspace in middle of input.
285 +
        widget.cursor = 2;
286 +
287 +
        ui.event(&mut widget, &WidgetEvent::KeyDown(platform::Key::Backspace));
288 +
        ui.event(&mut widget, &WidgetEvent::KeyDown(platform::Key::Backspace));
289 +
        assert_eq!(ui.data, "ll");
290 +
        assert_eq!(widget.cursor, 0);
291 +
292 +
        // Test backspace at start of input
293 +
        ui.event(&mut widget, &WidgetEvent::KeyDown(platform::Key::Backspace));
294 +
        assert_eq!(ui.data, "ll");
295 +
        assert_eq!(widget.cursor, 0);
296 +
    }
297 +
298 +
    #[test]
299 +
    fn test_input_key_delete() {
300 +
        let mut widget = input(widgets::label("Type something.."));
301 +
        let mut ui = TestInterface::<String>::new([64, 16]);
302 +
        activate(&mut widget, &mut ui);
303 +
304 +
        ui.data = String::from("Hello");
305 +
        widget.cursor = 2;
306 +
307 +
        ui.event(&mut widget, &WidgetEvent::KeyDown(platform::Key::Delete));
308 +
        assert_eq!(ui.data, "Helo");
309 +
        assert_eq!(widget.cursor, 2);
310 +
311 +
        // Test delete at end of input
312 +
        widget.cursor = 4;
313 +
314 +
        ui.event(&mut widget, &WidgetEvent::KeyDown(platform::Key::Delete));
315 +
        assert_eq!(ui.data, "Helo");
316 +
        assert_eq!(widget.cursor, 4);
317 +
    }
318 +
319 +
    #[test]
320 +
    fn test_input_overflow() {
321 +
        let mut widget = input(widgets::label("Type something..")).padding(0.);
322 +
        let mut ui = TestInterface::<String>::new([64, 16]);
323 +
        activate(&mut widget, &mut ui);
324 +
325 +
        // Add more text than the input can visually fit.
326 +
        for _ in 0..12 {
327 +
            ui.event(&mut widget, &WidgetEvent::Character('z'));
328 +
            ui.layout(&mut widget);
329 +
        }
330 +
        assert_eq!(ui.data.len(), 8);
331 +
332 +
        // Ensure the widget doesn't crash or misbehave with overflow.
333 +
        ui.paint(&mut widget);
334 +
    }
335 +
336 +
    #[test]
337 +
    fn test_input_customization() {
338 +
        let mut widget = input(widgets::label("Type something.."))
339 +
            .font("Monospace")
340 +
            .padding(Size::new(5., 5.));
341 +
        let mut ui = TestInterface::<String>::new([64, 16]);
342 +
343 +
        let size = ui.layout(&mut widget);
344 +
        assert_eq!(size, Size::new(64., 16.));
345 +
346 +
        assert_eq!(widget.text.font.as_str(), "Monospace");
347 +
        assert_eq!(widget.padding, Size::new(5., 5.));
348 +
    }
349 +
350 +
    #[test]
351 +
    fn test_input_deactivation() {
352 +
        let mut widget = input(widgets::label("Type something.."));
353 +
        let mut ui = TestInterface::<String>::new([64, 16]);
354 +
        activate(&mut widget, &mut ui);
355 +
356 +
        // Click outside the input to deactivate it
357 +
        assert!(!ui.click(&mut widget, [250., 50.]));
358 +
        assert!(!widget.active);
359 +
360 +
        ui.event(&mut widget, &WidgetEvent::Character('Z'));
361 +
        assert!(ui.data.is_empty());
362 +
    }
363 +
}
ombre/src/ui/widgets/label.rs added +84 -0
1 +
//! [`Label`] widget.
2 +
use crate::ui::gfx::Color;
3 +
4 +
use super::*;
5 +
use crate::bail;
6 +
use crate::ui::{
7 +
    fonts::{FontName, DEFAULT_FONT},
8 +
    gfx::{
9 +
        text::{PlainText, TextAlign, TextLayoutOptions, TextValue},
10 +
        Rgba8,
11 +
    },
12 +
};
13 +
14 +
/// A text label with wrapping.
15 +
#[derive(Debug)]
16 +
pub struct Label<T> {
17 +
    text: PlainText<T>,
18 +
    tint: Rgba8,
19 +
    size: Size<f32>,
20 +
}
21 +
22 +
impl<T> Widget<T> for Label<T> {
23 +
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
24 +
        debug_assert_ne!(ctx.bounds, Size::ZERO);
25 +
26 +
        let (layout, _) = self.text.layout(data, ctx.bounds, ctx.fonts);
27 +
28 +
        self.size = layout.size;
29 +
        self.size
30 +
    }
31 +
32 +
    fn paint(&mut self, _data: &T, mut ctx: PaintCtx<'_>) {
33 +
        let Some(font) = self.text.font() else {
34 +
            bail!("Font {:?} was not initialized", self.text.font)
35 +
        };
36 +
        let Some(layout) = self.text.layout.as_ref() else {
37 +
            bail!("Widget layout was not run")
38 +
        };
39 +
        for blit in layout.render(font.image.size, self.tint) {
40 +
            ctx.blit(font.image.clone(), blit);
41 +
        }
42 +
    }
43 +
44 +
    fn debug(&self) -> DebugInfo {
45 +
        DebugInfo::new("Label").size(self.size)
46 +
    }
47 +
}
48 +
49 +
impl<T> Label<T> {
50 +
    /// Create an empty label.
51 +
    pub fn empty() -> Self {
52 +
        label(String::default())
53 +
    }
54 +
55 +
    /// Set the label font.
56 +
    pub fn font(mut self, font: impl Into<FontName>) -> Self {
57 +
        self.text.font = font.into();
58 +
        self
59 +
    }
60 +
61 +
    /// Set the label tint.
62 +
    pub fn tint(mut self, color: impl Into<Rgba8>) -> Self {
63 +
        self.tint = color.into();
64 +
        self
65 +
    }
66 +
67 +
    /// Set the label text alignment.
68 +
    pub fn align(mut self, align: impl Into<TextAlign>) -> Self {
69 +
        self.text.opts.align = align.into();
70 +
        self
71 +
    }
72 +
}
73 +
74 +
/// Create a new [`Label`] with the provided text.
75 +
pub fn label<T>(text: impl Into<TextValue<T>>) -> Label<T> {
76 +
    let font = DEFAULT_FONT;
77 +
    let text = text.into();
78 +
79 +
    Label {
80 +
        text: PlainText::new(font, TextLayoutOptions::default(), text),
81 +
        size: Size::default(),
82 +
        tint: Rgba8::WHITE,
83 +
    }
84 +
}
ombre/src/ui/widgets/lens.rs added +58 -0
1 +
//! The [`LensWrap`] widget.
2 +
use std::marker::PhantomData;
3 +
4 +
use super::*;
5 +
use crate::lenses::Lens;
6 +
7 +
/// A widget wrapped with a lens.
8 +
pub struct LensWrap<L, W, U, T> {
9 +
    lens: L,
10 +
    child: W,
11 +
    input: PhantomData<U>,
12 +
    data: PhantomData<T>,
13 +
}
14 +
15 +
impl<L, W, U, T> LensWrap<L, W, U, T> {
16 +
    /// Create a new [`LensWrap`] from a widget and lens.
17 +
    pub fn new(child: W, lens: L) -> Self {
18 +
        Self {
19 +
            lens,
20 +
            child,
21 +
            input: PhantomData,
22 +
            data: PhantomData,
23 +
        }
24 +
    }
25 +
}
26 +
27 +
impl<L, W, U, T> Widget<T> for LensWrap<L, W, U, T>
28 +
where
29 +
    L: Lens<T, U>,
30 +
    W: Widget<U>,
31 +
{
32 +
    fn event(
33 +
        &mut self,
34 +
        event: &WidgetEvent,
35 +
        data: &mut T,
36 +
        ctx: EventCtx<'_>,
37 +
        win: &mut WindowCtx,
38 +
    ) -> bool {
39 +
        let child = &mut self.child;
40 +
        self.lens.with_mut(data, |data| child.event(event, data, ctx, win))
41 +
    }
42 +
43 +
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
44 +
        self.lens.with(data, |data| self.child.layout(data, ctx))
45 +
    }
46 +
47 +
    fn paint(&mut self, data: &T, ctx: PaintCtx<'_>) {
48 +
        self.lens.with(data, |data| self.child.paint(data, ctx))
49 +
    }
50 +
51 +
    fn contains(&self, point: Point2D<f32, Local>) -> bool {
52 +
        self.child.contains(point)
53 +
    }
54 +
55 +
    fn debug(&self) -> DebugInfo {
56 +
        DebugInfo::new("LensWrap").children([&self.child])
57 +
    }
58 +
}
ombre/src/ui/widgets/null.rs added +41 -0
1 +
//! The [`Null`] widget does nothing.
2 +
use crate::ui::widgets::*;
3 +
4 +
/// A widget that does nothing.
5 +
#[derive(Default)]
6 +
pub struct Null;
7 +
8 +
impl<T> Widget<T> for Null {
9 +
    fn layout(&mut self, _data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
10 +
        ctx.size
11 +
    }
12 +
13 +
    fn event(
14 +
        &mut self,
15 +
        _event: &WidgetEvent,
16 +
        _data: &mut T,
17 +
        _ctx: EventCtx<'_>,
18 +
        _win: &mut WindowCtx,
19 +
    ) -> bool {
20 +
        false
21 +
    }
22 +
23 +
    fn paint(&mut self, _data: &T, _ctx: PaintCtx<'_>) {
24 +
        // Does nothing.
25 +
    }
26 +
27 +
    fn contains(&self, _point: Point2D<f32, Local>) -> bool {
28 +
        true
29 +
    }
30 +
31 +
    fn debug(&self) -> DebugInfo {
32 +
        DebugInfo::new("Null")
33 +
    }
34 +
}
35 +
36 +
impl Null {
37 +
    /// Creates a new [`Null`] widget.
38 +
    pub fn new() -> Self {
39 +
        Null
40 +
    }
41 +
}
ombre/src/ui/widgets/offset.rs added +115 -0
1 +
//! [`Offset`] widget.
2 +
use std::marker::PhantomData;
3 +
4 +
use super::*;
5 +
6 +
/// Offset a child widget.
7 +
pub struct Offset<W, T> {
8 +
    /// The widget offset.
9 +
    pub offset: Vector2D<f32, Local>,
10 +
    /// The widget size after layout.
11 +
    pub size: Size<f32>,
12 +
13 +
    widget: W,
14 +
    data: PhantomData<T>,
15 +
}
16 +
17 +
impl<W, T> std::fmt::Debug for Offset<W, T> {
18 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19 +
        f.debug_struct("Offset")
20 +
            .field("offset", &self.offset)
21 +
            .field("size", &self.size)
22 +
            .finish_non_exhaustive()
23 +
    }
24 +
}
25 +
26 +
impl<W, T> Offset<W, T> {
27 +
    /// Create a new [`Offset`] from a child widget.
28 +
    pub fn new(widget: W) -> Self {
29 +
        Self {
30 +
            widget,
31 +
            size: Size::default(),
32 +
            offset: Vector2D::default(),
33 +
            data: PhantomData,
34 +
        }
35 +
    }
36 +
37 +
    /// Set the offset.
38 +
    pub fn set(&mut self, offset: impl Into<Vector2D<f32, Local>>) {
39 +
        self.offset = offset.into().expand();
40 +
    }
41 +
42 +
    /// Get the offset point.
43 +
    pub fn origin(&self) -> Point2D<f32, Local> {
44 +
        self.offset.into()
45 +
    }
46 +
}
47 +
48 +
impl<W: Widget<T>, T> Widget<T> for Offset<W, T> {
49 +
    fn event(
50 +
        &mut self,
51 +
        event: &WidgetEvent,
52 +
        data: &mut T,
53 +
        ctx: EventCtx<'_>,
54 +
        win: &mut WindowCtx,
55 +
    ) -> bool {
56 +
        self.widget.event(event, data, ctx.offset(self.offset), win)
57 +
    }
58 +
59 +
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
60 +
        self.size = self.widget.layout(data, ctx);
61 +
        self.size
62 +
    }
63 +
64 +
    fn paint(&mut self, data: &T, ctx: PaintCtx<'_>) {
65 +
        self.widget.paint(data, ctx.offset(self.offset));
66 +
    }
67 +
68 +
    fn contains(&self, point: Point2D<f32, Local>) -> bool {
69 +
        Rect::new(self.offset, self.size).contains(point)
70 +
    }
71 +
72 +
    fn debug(&self) -> DebugInfo {
73 +
        DebugInfo::new("Offset")
74 +
            .children([&self.widget])
75 +
            .origin(self.offset)
76 +
            .size(self.size)
77 +
    }
78 +
}
79 +
80 +
impl<W, T> Offset<W, T> {
81 +
    /// Set the child offset by providing a vector.
82 +
    pub fn at(mut self, offset: impl Into<Vector2D<f32, Local>>) -> Self {
83 +
        self.offset = offset.into();
84 +
        self
85 +
    }
86 +
}
87 +
88 +
/// Create a new [`Offset`] from a child widget.
89 +
pub fn offset<T, W: Widget<T>>(widget: W) -> Offset<W, T> {
90 +
    Offset::new(widget)
91 +
}
92 +
93 +
#[cfg(test)]
94 +
mod tests {
95 +
    use super::*;
96 +
    use crate::ui::test::TestInterface;
97 +
    use crate::ui::widgets;
98 +
99 +
    #[test]
100 +
    fn test_offset() {
101 +
        let child: widgets::Click<_, Option<bool>> =
102 +
            widgets::Null.sized([32., 32.]).on_click(|_, s, _| *s = Some(true));
103 +
        let mut widget = Offset::new(child).at([64., 64.]);
104 +
        let mut ui = TestInterface::new([256, 256]);
105 +
106 +
        assert_eq!(ui.layout(&mut widget), Size::new(32., 32.));
107 +
        assert!(!ui.click(&mut widget, [8., 8.]));
108 +
        assert!(!ui.click(&mut widget, [112., 112.]));
109 +
        assert!(!ui.click(&mut widget, [128., 128.]));
110 +
        assert_eq!(ui.take(), None);
111 +
        assert!(ui.click(&mut widget, [72., 72.]));
112 +
        assert!(ui.click(&mut widget, [64., 64.]));
113 +
        assert_eq!(ui.take(), Some(true));
114 +
    }
115 +
}
ombre/src/ui/widgets/padding.rs added +88 -0
1 +
//! [`Padding`] widget.
2 +
use std::marker::PhantomData;
3 +
4 +
use super::*;
5 +
6 +
/// Add padding to a child widget.
7 +
pub struct Padding<W, T> {
8 +
    /// Padding insets.
9 +
    pub insets: Insets,
10 +
    /// The widget size after layout.
11 +
    pub size: Size<f32>,
12 +
13 +
    widget: W,
14 +
    data: PhantomData<T>,
15 +
}
16 +
17 +
impl<W, T> std::fmt::Debug for Padding<W, T> {
18 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19 +
        f.debug_struct("Padding")
20 +
            .field("insets", &self.insets)
21 +
            .field("size", &self.size)
22 +
            .finish_non_exhaustive()
23 +
    }
24 +
}
25 +
26 +
impl<W, T> Padding<W, T> {
27 +
    /// Create a new [`Padding`] from a child widget.
28 +
    pub fn new(widget: W, insets: Insets) -> Self {
29 +
        Self {
30 +
            widget,
31 +
            size: Size::default(),
32 +
            insets,
33 +
            data: PhantomData,
34 +
        }
35 +
    }
36 +
37 +
    /// Get the insets.
38 +
    pub fn insets(&self) -> &Insets {
39 +
        &self.insets
40 +
    }
41 +
}
42 +
43 +
impl<W: Widget<T>, T> Widget<T> for Padding<W, T> {
44 +
    fn event(
45 +
        &mut self,
46 +
        event: &WidgetEvent,
47 +
        data: &mut T,
48 +
        ctx: EventCtx<'_>,
49 +
        win: &mut WindowCtx,
50 +
    ) -> bool {
51 +
        self.widget.event(
52 +
            event,
53 +
            data,
54 +
            ctx.offset([self.insets.left, self.insets.top]),
55 +
            win,
56 +
        )
57 +
    }
58 +
59 +
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
60 +
        let child = self.widget.layout(data, ctx);
61 +
62 +
        self.size = Size::new(
63 +
            child.w + self.insets.left + self.insets.right,
64 +
            child.h + self.insets.top + self.insets.bottom,
65 +
        );
66 +
        self.size
67 +
    }
68 +
69 +
    fn paint(&mut self, data: &T, ctx: PaintCtx<'_>) {
70 +
        self.widget.paint(
71 +
            data,
72 +
            ctx.offset([self.insets.left, self.insets.top]).resize(self.size),
73 +
        );
74 +
    }
75 +
76 +
    fn contains(&self, point: Point2D<f32, Local>) -> bool {
77 +
        Rect::origin(self.size).contains(point) && self.widget.contains(point)
78 +
    }
79 +
80 +
    fn debug(&self) -> DebugInfo {
81 +
        DebugInfo::new("Padding").children([&self.widget]).size(self.size)
82 +
    }
83 +
}
84 +
85 +
/// Create a new [`Padding`] from a child widget.
86 +
pub fn padding<T, W: Widget<T>>(insets: impl Into<Insets>, widget: W) -> Padding<W, T> {
87 +
    Padding::new(widget, insets.into())
88 +
}
ombre/src/ui/widgets/pod.rs added +57 -0
1 +
//! [`Pod`] widget.
2 +
use std::marker::PhantomData;
3 +
4 +
use super::*;
5 +
6 +
/// A wrapper around a widget that caches the child widget's size
7 +
/// and passes a resized context to it.
8 +
pub struct Pod<W, T> {
9 +
    /// The child widget.
10 +
    pub child: W,
11 +
    /// The size of the child widget, as returned by [`Widget::layout`].
12 +
    pub size: Size<f32>,
13 +
14 +
    data: PhantomData<T>,
15 +
}
16 +
17 +
impl<W, T> Pod<W, T>
18 +
where
19 +
    W: Widget<T>,
20 +
{
21 +
    /// Create a new pod.
22 +
    pub fn new(child: W) -> Self {
23 +
        Self {
24 +
            child,
25 +
            size: Size::ZERO,
26 +
            data: PhantomData,
27 +
        }
28 +
    }
29 +
}
30 +
31 +
impl<W, T> Widget<T> for Pod<W, T>
32 +
where
33 +
    W: Widget<T>,
34 +
{
35 +
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
36 +
        self.size = self.child.layout(data, ctx);
37 +
        self.size
38 +
    }
39 +
40 +
    fn paint(&mut self, data: &T, ctx: PaintCtx<'_>) {
41 +
        self.child.paint(data, ctx.resize(self.size));
42 +
    }
43 +
44 +
    fn event(
45 +
        &mut self,
46 +
        event: &WidgetEvent,
47 +
        data: &mut T,
48 +
        ctx: EventCtx<'_>,
49 +
        win: &mut WindowCtx,
50 +
    ) -> bool {
51 +
        self.child.event(event, data, ctx.resize(self.size), win)
52 +
    }
53 +
54 +
    fn debug(&self) -> DebugInfo {
55 +
        DebugInfo::new("Pod").size(self.size).children([&self.child])
56 +
    }
57 +
}
ombre/src/ui/widgets/resized.rs added +94 -0
1 +
//! [`Resized`] widget.
2 +
use std::marker::PhantomData;
3 +
4 +
use super::*;
5 +
6 +
/// Resize an underlying widget.
7 +
pub struct Resized<W, T> {
8 +
    widget: W,
9 +
    size: Size<f32>,
10 +
    data: PhantomData<T>,
11 +
}
12 +
13 +
impl<W, T> std::fmt::Debug for Resized<W, T> {
14 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
15 +
        f.debug_struct("Resized")
16 +
            .field("size", &self.size)
17 +
            .finish_non_exhaustive()
18 +
    }
19 +
}
20 +
21 +
impl<W: Widget<T>, T> Resized<W, T> {
22 +
    /// Create a new [`Resized`] widget.
23 +
    pub fn new(widget: W, size: Size<f32>) -> Self {
24 +
        assert!(!size.is_zero(), "Resized::new: size cannot be zero");
25 +
26 +
        Self {
27 +
            widget,
28 +
            size,
29 +
            data: PhantomData,
30 +
        }
31 +
    }
32 +
}
33 +
34 +
impl<W: Widget<T>, T> Widget<T> for Resized<W, T> {
35 +
    fn event(
36 +
        &mut self,
37 +
        event: &WidgetEvent,
38 +
        data: &mut T,
39 +
        ctx: EventCtx<'_>,
40 +
        win: &mut WindowCtx,
41 +
    ) -> bool {
42 +
        let size = self.size.constrain(ctx.size);
43 +
        self.widget.event(
44 +
            event,
45 +
            data,
46 +
            Context::new(ctx.cursor, size).as_event(ctx.fonts),
47 +
            win,
48 +
        )
49 +
    }
50 +
51 +
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
52 +
        let size = self.size.constrain(ctx.bounds);
53 +
54 +
        debug_assert_ne!(size, Size::ZERO);
55 +
56 +
        self.widget.layout(data, ctx.resize(size));
57 +
        size
58 +
    }
59 +
60 +
    fn paint(&mut self, data: &T, ctx: PaintCtx<'_>) {
61 +
        self.widget.paint(data, ctx.resize(self.size));
62 +
    }
63 +
64 +
    fn contains(&self, point: Point2D<f32, Local>) -> bool {
65 +
        Rect::origin(self.size).contains(point) && self.widget.contains(point)
66 +
    }
67 +
68 +
    fn debug(&self) -> DebugInfo {
69 +
        DebugInfo::new("Resized").children([&self.widget]).size(self.size)
70 +
    }
71 +
}
72 +
73 +
#[cfg(test)]
74 +
mod tests {
75 +
    use super::*;
76 +
    use crate::ui::test::TestInterface;
77 +
    use crate::ui::widgets;
78 +
79 +
    #[test]
80 +
    fn test_resized() {
81 +
        let child = widgets::Null;
82 +
        let mut widget =
83 +
            Resized::new(child, Size::new(32., 32.)).on_click(|_, s, _| *s = Some(true));
84 +
        let mut ui = TestInterface::new([256, 256]);
85 +
86 +
        assert_eq!(ui.layout(&mut widget), Size::new(32., 32.));
87 +
        assert!(ui.click(&mut widget, [0., 0.]));
88 +
        assert!(ui.click(&mut widget, [8., 8.]));
89 +
        assert_eq!(ui.data.take(), Some(true));
90 +
        assert!(!ui.click(&mut widget, [32., 32.]));
91 +
        assert!(!ui.click(&mut widget, [64., 64.]));
92 +
        assert_eq!(ui.data.take(), None);
93 +
    }
94 +
}
ombre/src/ui/widgets/style.rs added +154 -0
1 +
//! [`Style`] widget.
2 +
use std::marker::PhantomData;
3 +
4 +
use super::*;
5 +
use crate::ui::gfx::{Color, Rgba, Rgba8};
6 +
7 +
/// Defines the stroke properties for rendering shape outlines.
8 +
#[derive(PartialEq, Copy, Clone, Debug)]
9 +
pub struct Stroke {
10 +
    /// Stroke width.
11 +
    pub width: f32,
12 +
    /// Offset from shape (positive = outset, negative = inset).
13 +
    pub offset: f32,
14 +
    /// Stroke color.
15 +
    pub color: Rgba<f32>,
16 +
}
17 +
18 +
impl Stroke {
19 +
    /// No stroke.
20 +
    pub const NONE: Self = Self {
21 +
        width: 0.,
22 +
        offset: 0.,
23 +
        color: Rgba::TRANSPARENT,
24 +
    };
25 +
26 +
    /// Create a new stroke.
27 +
    pub fn new(width: f32, color: impl Into<Rgba<f32>>) -> Self {
28 +
        Self {
29 +
            width,
30 +
            offset: 0.,
31 +
            color: color.into(),
32 +
        }
33 +
    }
34 +
35 +
    /// Offset the stroke so that it rests inside the shape.
36 +
    pub fn inside(mut self) -> Self {
37 +
        self.offset -= self.width;
38 +
        self
39 +
    }
40 +
}
41 +
42 +
impl Default for Stroke {
43 +
    fn default() -> Self {
44 +
        Self::NONE
45 +
    }
46 +
}
47 +
48 +
impl From<Rgba8> for Stroke {
49 +
    fn from(color: Rgba8) -> Self {
50 +
        Self::new(1.0, color)
51 +
    }
52 +
}
53 +
54 +
impl From<Rgba<f32>> for Stroke {
55 +
    fn from(color: Rgba<f32>) -> Self {
56 +
        Self::new(1.0, color)
57 +
    }
58 +
}
59 +
60 +
impl From<f32> for Stroke {
61 +
    fn from(width: f32) -> Self {
62 +
        Self::new(width, Rgba::WHITE)
63 +
    }
64 +
}
65 +
66 +
/// Style a widget with a stroke or fill color.
67 +
pub struct Style<W, T> {
68 +
    widget: W,
69 +
    fill: Rgba<f32>,
70 +
    stroke: Stroke,
71 +
    size: Size<f32>,
72 +
    data: PhantomData<T>,
73 +
}
74 +
75 +
impl<W, T> std::fmt::Debug for Style<W, T> {
76 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77 +
        f.debug_struct("Style")
78 +
            .field("fill", &self.fill)
79 +
            .field("stroke", &self.stroke)
80 +
            .finish_non_exhaustive()
81 +
    }
82 +
}
83 +
84 +
impl<W: Widget<T>, T> Style<W, T> {
85 +
    /// Create a new [`Style`] widget from a child widget.
86 +
    pub fn new(widget: W) -> Self {
87 +
        Self {
88 +
            widget,
89 +
            fill: Rgba::TRANSPARENT,
90 +
            stroke: Stroke::NONE,
91 +
            size: Size::ZERO,
92 +
            data: PhantomData,
93 +
        }
94 +
    }
95 +
}
96 +
97 +
impl<W: Widget<T>, T> Widget<T> for Style<W, T> {
98 +
    fn event(
99 +
        &mut self,
100 +
        event: &WidgetEvent,
101 +
        data: &mut T,
102 +
        ctx: EventCtx<'_>,
103 +
        win: &mut WindowCtx,
104 +
    ) -> bool {
105 +
        self.widget.event(event, data, ctx, win)
106 +
    }
107 +
108 +
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
109 +
        self.size = self.widget.layout(data, ctx);
110 +
        self.size
111 +
    }
112 +
113 +
    fn paint(&mut self, data: &T, mut ctx: PaintCtx<'_>) {
114 +
        let rect = Rect::origin(self.size);
115 +
116 +
        self.widget.paint(
117 +
            data,
118 +
            PaintCtx {
119 +
                ops: ctx.ops,
120 +
                ..ctx
121 +
            },
122 +
        );
123 +
124 +
        if self.fill != Rgba::TRANSPARENT {
125 +
            ctx.fill(rect, self.fill, ZDepth::ZERO);
126 +
        }
127 +
        if self.stroke != Stroke::NONE {
128 +
            ctx.stroke(rect, self.stroke.color, self.stroke.width);
129 +
        }
130 +
    }
131 +
132 +
    fn debug(&self) -> DebugInfo {
133 +
        DebugInfo::new("Style").children([&self.widget])
134 +
    }
135 +
}
136 +
137 +
impl<W, T> Style<W, T> {
138 +
    /// Set fill color.
139 +
    pub fn fill(mut self, color: impl Into<Rgba<f32>>) -> Self {
140 +
        self.fill = color.into();
141 +
        self
142 +
    }
143 +
144 +
    /// Set stroke color and width.
145 +
    pub fn stroke(mut self, stroke: impl Into<Stroke>) -> Self {
146 +
        self.stroke = stroke.into();
147 +
        self
148 +
    }
149 +
}
150 +
151 +
/// Create a new [`Style`] widget from a child widget.
152 +
pub fn style<T, W: Widget<T>>(widget: W) -> Style<W, T> {
153 +
    Style::new(widget)
154 +
}
ombre/src/ui/widgets/text.rs added +103 -0
1 +
//! [`RichText`] widget.
2 +
use super::{DebugInfo, LayoutCtx, PaintCtx, Size, Widget};
3 +
use crate::bail;
4 +
use crate::ui::gfx::text::{
5 +
    LoadedTextSpan, RichTextLayout, RichTextStorage, TextAlign, TextLayoutOptions,
6 +
};
7 +
use crate::ui::math::Zero;
8 +
9 +
/// A rich text block.
10 +
#[derive(Debug)]
11 +
pub struct RichText {
12 +
    /// Lazy loaded spans.
13 +
    spans: Option<Vec<LoadedTextSpan>>,
14 +
    /// Lazy text layout.
15 +
    layout: Option<RichTextLayout>,
16 +
    /// Final size of layed out text. Fits within `bounds`.
17 +
    size: Size<f32>,
18 +
    /// Parent bounds constraining text layout.
19 +
    bounds: Size<f32>,
20 +
    /// Text layout options. Applies to the entire block of text.
21 +
    options: TextLayoutOptions,
22 +
}
23 +
24 +
impl<T> Widget<T> for RichText
25 +
where
26 +
    T: RichTextStorage,
27 +
{
28 +
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
29 +
        debug_assert_ne!(ctx.bounds, Size::ZERO);
30 +
31 +
        // Load all spans the first time we do a layout.
32 +
        // This makes the font information available for layout.
33 +
        let spans = self
34 +
            .spans
35 +
            .get_or_insert_with(|| data.spans().map(|s| s.load(ctx.fonts)).collect());
36 +
37 +
        if ctx.bounds != self.bounds {
38 +
            self.layout = None;
39 +
        }
40 +
        let layout = self.layout.get_or_insert_with(|| {
41 +
            RichTextLayout::build(data.as_str(), spans, self.options, ctx.bounds)
42 +
        });
43 +
        self.bounds = ctx.bounds;
44 +
        self.size = layout.size();
45 +
        self.size
46 +
    }
47 +
48 +
    fn paint(&mut self, _data: &T, mut ctx: PaintCtx<'_>) {
49 +
        let Some(layout) = &self.layout else {
50 +
            bail!("RichText::paint: widget layout was not run!");
51 +
        };
52 +
        for (img, blit) in layout.render() {
53 +
            ctx.blit(img, blit);
54 +
        }
55 +
    }
56 +
57 +
    fn debug(&self) -> DebugInfo {
58 +
        DebugInfo::new("RichText").size(self.size)
59 +
    }
60 +
}
61 +
62 +
impl Default for RichText {
63 +
    /// Create a new rich text widget.
64 +
    fn default() -> Self {
65 +
        Self {
66 +
            spans: None,
67 +
            layout: None,
68 +
            size: Size::default(),
69 +
            bounds: Size::default(),
70 +
            options: TextLayoutOptions::default(),
71 +
        }
72 +
    }
73 +
}
74 +
75 +
impl RichText {
76 +
    /// Get the text style.
77 +
    pub fn style(&self) -> TextLayoutOptions {
78 +
        self.options
79 +
    }
80 +
81 +
    /// Get the styles, mutably.
82 +
    pub fn style_mut(&mut self) -> &mut TextLayoutOptions {
83 +
        &mut self.options
84 +
    }
85 +
86 +
    /// Refresh the text layout.
87 +
    /// Call this when the text content or appearance changed.
88 +
    pub fn refresh(&mut self) {
89 +
        self.spans.take();
90 +
        self.layout.take();
91 +
    }
92 +
93 +
    /// Set the text alignment.
94 +
    pub fn align(mut self, align: impl Into<TextAlign>) -> Self {
95 +
        self.options.align = align.into();
96 +
        self
97 +
    }
98 +
}
99 +
100 +
/// Create a new [`RichText`] with the provided text and styling spans.
101 +
pub fn text() -> RichText {
102 +
    RichText::default()
103 +
}
ombre/src/ui/widgets/vstack.rs added +250 -0
1 +
//! [`VStack`] widget.
2 +
use super::*;
3 +
use crate::ui::widgets::Offset;
4 +
5 +
/// Vertical stack.
6 +
pub struct VStack<T> {
7 +
    size: Size,
8 +
    gap: f32,
9 +
    children: Vec<Offset<Box<dyn Widget<T>>, T>>,
10 +
}
11 +
12 +
impl<T> Default for VStack<T> {
13 +
    fn default() -> Self {
14 +
        Self {
15 +
            size: Size::default(),
16 +
            gap: 0.,
17 +
            children: Vec::default(),
18 +
        }
19 +
    }
20 +
}
21 +
22 +
impl<T> VStack<T> {
23 +
    /// Create a new [`VStack`] from a list of child widgets.
24 +
    pub fn new(children: Vec<Box<dyn Widget<T>>>) -> Self {
25 +
        Self {
26 +
            size: Size::default(),
27 +
            gap: 0.,
28 +
            children: children.into_iter().map(Offset::new).collect(),
29 +
        }
30 +
    }
31 +
32 +
    /// Push a child to the widget without consuming the object.
33 +
    pub fn push(&mut self, child: impl Widget<T> + 'static) {
34 +
        self.children.push(Offset::new(Box::new(child)));
35 +
    }
36 +
37 +
    /// Add a child to the widget.
38 +
    pub fn child(mut self, child: impl Widget<T> + 'static) -> Self {
39 +
        self.push(child);
40 +
        self
41 +
    }
42 +
43 +
    /// Set the gap between children.
44 +
    pub fn gap(mut self, gap: f32) -> Self {
45 +
        self.gap = gap;
46 +
        self
47 +
    }
48 +
49 +
    /// Get the widget bounds.
50 +
    pub fn bounds(&self) -> Rect<f32, Local> {
51 +
        Rect::origin(self.size)
52 +
    }
53 +
54 +
    /// Get the numebr of children.
55 +
    pub fn len(&self) -> usize {
56 +
        self.children.len()
57 +
    }
58 +
59 +
    /// Check if the widget is empty.
60 +
    pub fn is_empty(&self) -> bool {
61 +
        self.len() == 0
62 +
    }
63 +
}
64 +
65 +
impl<T> Widget<T> for VStack<T> {
66 +
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
67 +
        let mut offset = Vector2D::ZERO;
68 +
        let mut max_ch: f32 = 0.; // Max column height.
69 +
        let mut max_cw: f32 = 0.; // Max column width.
70 +
71 +
        for widget in &mut self.children {
72 +
            let size = widget.layout(data, ctx.clone());
73 +
74 +
            // Check if we need to wrap to the next column.
75 +
            if offset.y + size.h > ctx.bounds.h {
76 +
                offset.y = 0.;
77 +
                offset.x += max_cw + self.gap;
78 +
                max_cw = 0.;
79 +
            }
80 +
            widget.set(offset);
81 +
            offset.y += size.h + self.gap;
82 +
83 +
            max_cw = max_cw.max(size.w);
84 +
            max_ch = max_ch.max(offset.y - self.gap);
85 +
        }
86 +
        self.size = Size::new(offset.x + max_cw, max_ch.min(ctx.bounds.h));
87 +
        self.size
88 +
    }
89 +
90 +
    fn paint(&mut self, data: &T, ctx: PaintCtx<'_>) {
91 +
        for widget in &mut self.children {
92 +
            widget.paint(
93 +
                data,
94 +
                PaintCtx {
95 +
                    ops: ctx.ops,
96 +
                    ..ctx
97 +
                },
98 +
            );
99 +
        }
100 +
    }
101 +
102 +
    fn event(
103 +
        &mut self,
104 +
        event: &WidgetEvent,
105 +
        data: &mut T,
106 +
        ctx: EventCtx<'_>,
107 +
        win: &mut WindowCtx,
108 +
    ) -> bool {
109 +
        for widget in &mut self.children {
110 +
            if widget.event(event, data, ctx, win) {
111 +
                return true;
112 +
            }
113 +
        }
114 +
        false
115 +
    }
116 +
117 +
    fn contains(&self, point: Point2D<f32, Local>) -> bool {
118 +
        self.bounds().contains(point)
119 +
    }
120 +
121 +
    fn debug(&self) -> DebugInfo {
122 +
        DebugInfo::new("VStack").children(&self.children)
123 +
    }
124 +
}
125 +
126 +
/// Create a new [`VStack`] from a list of child widgets.
127 +
pub fn vstack<W, T>(children: W) -> VStack<T>
128 +
where
129 +
    W: WidgetList<T>,
130 +
{
131 +
    VStack::new(children.to_vec())
132 +
}
133 +
134 +
#[cfg(test)]
135 +
mod tests {
136 +
    use super::*;
137 +
    use crate::ui::gfx::{Color, PaintOp, Rgba8};
138 +
    use crate::ui::test::TestInterface;
139 +
    use crate::ui::widgets;
140 +
141 +
    #[test]
142 +
    fn test_vstack() {
143 +
        let child1 = widgets::Null.sized([3., 3.]).on_click(|_, s, _| *s = Some(1));
144 +
        let child2 = widgets::Null.sized([3., 3.]).on_click(|_, s, _| *s = Some(2));
145 +
        let child3 = widgets::Null.sized([3., 3.]).on_click(|_, s, _| *s = Some(3));
146 +
        let size = Size::<u32>::new(3, 3 * 3 + 2); // Just enough space for the widgets with the gap.
147 +
        let mut widget = vstack((child1, child2, child3)).gap(1.);
148 +
        let mut ui = TestInterface::new(size);
149 +
150 +
        assert_eq!(ui.layout(&mut widget), size.into());
151 +
        assert!(ui.click(&mut widget, [0., 0.])); // First child.
152 +
        assert_eq!(ui.take(), Some(1));
153 +
        assert!(ui.click(&mut widget, [1., 1.])); // First child.
154 +
        assert_eq!(ui.take(), Some(1));
155 +
        assert!(!ui.click(&mut widget, [1., 3.])); // Gap between children.
156 +
        assert_eq!(ui.take(), None);
157 +
        assert!(ui.click(&mut widget, [1., 5.])); // Second child.
158 +
        assert_eq!(ui.take(), Some(2));
159 +
        assert!(!ui.click(&mut widget, [1., 7.])); // Gap between children.
160 +
        assert_eq!(ui.take(), None);
161 +
        assert!(ui.click(&mut widget, [1., 9.])); // Third child.
162 +
        assert_eq!(ui.take(), Some(3));
163 +
        assert!(!ui.click(&mut widget, [1., 11.])); // Out of bounds.
164 +
        assert_eq!(ui.take(), None);
165 +
    }
166 +
167 +
    #[test]
168 +
    fn test_vstack_paint() {
169 +
        let child1: Resized<_, ()> = Rgba8::RED.sized([3., 3.]);
170 +
        let child2: Resized<_, ()> = Rgba8::GREEN.sized([3., 3.]);
171 +
        let child3: Resized<_, ()> = Rgba8::BLUE.sized([3., 3.]);
172 +
        let size = Size::<u32>::new(3, 3 * 3 + 2); // Just enough space for the widgets with the gap.
173 +
        let mut widget = vstack((child1, child2, child3)).gap(1.);
174 +
        let mut ui = TestInterface::new(size);
175 +
176 +
        ui.layout(&mut widget);
177 +
        ui.paint(&mut widget);
178 +
179 +
        let ops = ui.surface.operations.as_slice();
180 +
        assert_eq!(ops.len(), 3); // One fill operation for each child
181 +
182 +
        if let [PaintOp::Fill {
183 +
            rect: r1,
184 +
            color: c1,
185 +
            ..
186 +
        }, PaintOp::Fill {
187 +
            rect: r2,
188 +
            color: c2,
189 +
            ..
190 +
        }, PaintOp::Fill {
191 +
            rect: r3,
192 +
            color: c3,
193 +
            ..
194 +
        }] = ops
195 +
        {
196 +
            assert_eq!(r1.origin, Point2D::new(0., 0.));
197 +
            assert_eq!(r1.size, Size::new(3., 3.));
198 +
            assert_eq!(c1, &Rgba::RED);
199 +
200 +
            assert_eq!(r2.origin, Point2D::new(0., 4.));
201 +
            assert_eq!(r2.size, Size::new(3., 3.));
202 +
            assert_eq!(c2, &Rgba::GREEN);
203 +
204 +
            assert_eq!(r3.origin, Point2D::new(0., 8.));
205 +
            assert_eq!(r3.size, Size::new(3., 3.));
206 +
            assert_eq!(c3, &Rgba::BLUE);
207 +
        } else {
208 +
            panic!("Unexpected paint operations {ops:#?}");
209 +
        }
210 +
    }
211 +
212 +
    #[test]
213 +
    fn test_vstack_wrap() {
214 +
        let child1 = widgets::Null.sized([3., 3.]);
215 +
        let child2 = widgets::Null.sized([3., 3.]);
216 +
        let child3 = widgets::Null.sized([3., 3.]);
217 +
        let child4 = widgets::Null.sized([3., 3.]);
218 +
        let mut widget = vstack((child1, child2, child3, child4)).gap(1.);
219 +
220 +
        // Test cases: (container size, expected layout size).
221 +
        let tests = vec![
222 +
            ([u32::MAX, 15], [3., 15.]), // Fits all 4 widgets in one column.
223 +
            ([u32::MAX, 11], [7., 11.]), // Fits only 3 widgets in one column.
224 +
            ([u32::MAX, 8], [7., 7.]),   // Fits 2 widgets per column.
225 +
            ([u32::MAX, 5], [15., 3.]),  // Fits 1 widget per column.
226 +
            ([u32::MAX, 2], [15., 2.]),  // Container smaller than widgets.
227 +
        ];
228 +
229 +
        for (container, expected) in tests {
230 +
            let expected = Size::from(expected);
231 +
            let container = Size::<u32>::from(container);
232 +
            let mut ui = TestInterface::<()>::new(container);
233 +
            let actual = ui.layout(&mut widget);
234 +
            assert_eq!(
235 +
                actual, expected,
236 +
                "For container {container}, expected {expected}, got {actual}",
237 +
            );
238 +
            // Ensure no child extends beyond the layout height.
239 +
            ui.paint(&mut widget);
240 +
            for op in &ui.surface.operations {
241 +
                if let PaintOp::Fill { rect, .. } = op {
242 +
                    assert!(
243 +
                        rect.max().y <= expected.h,
244 +
                        "Child extends beyond container {container}",
245 +
                    );
246 +
                }
247 +
            }
248 +
        }
249 +
    }
250 +
}
ombre/src/ui/widgets/zstack.rs added +135 -0
1 +
//! [`ZStack`] widget.
2 +
use std::cmp;
3 +
4 +
use super::*;
5 +
6 +
/// Z-stack.
7 +
pub struct ZStack<T> {
8 +
    children: Vec<Pod<Box<dyn Widget<T>>, T>>,
9 +
}
10 +
11 +
impl<T> Default for ZStack<T> {
12 +
    fn default() -> Self {
13 +
        Self {
14 +
            children: Vec::default(),
15 +
        }
16 +
    }
17 +
}
18 +
19 +
impl<T> ZStack<T> {
20 +
    /// Create a new [`ZStack`] from a list of child widgets.
21 +
    pub fn new(children: Vec<Box<dyn Widget<T>>>) -> Self {
22 +
        Self {
23 +
            children: children.into_iter().map(Pod::new).collect(),
24 +
        }
25 +
    }
26 +
27 +
    /// Push a child to the widget without consuming the object.
28 +
    pub fn push(&mut self, child: impl Widget<T> + 'static) {
29 +
        self.children.push(Pod::new(Box::new(child)));
30 +
    }
31 +
32 +
    /// Add a child to the widget.
33 +
    pub fn child(mut self, child: impl Widget<T> + 'static) -> Self {
34 +
        self.push(child);
35 +
        self
36 +
    }
37 +
38 +
    /// Get the numebr of children.
39 +
    pub fn len(&self) -> usize {
40 +
        self.children.len()
41 +
    }
42 +
43 +
    /// Check if the widget is empty.
44 +
    pub fn is_empty(&self) -> bool {
45 +
        self.len() == 0
46 +
    }
47 +
}
48 +
49 +
impl<T> Widget<T> for ZStack<T> {
50 +
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
51 +
        for widget in &mut self.children {
52 +
            widget.layout(data, ctx.clone());
53 +
        }
54 +
        self.children
55 +
            .iter()
56 +
            .map(|p| p.size)
57 +
            .max_by(|a, b| a.partial_cmp(b).unwrap_or(cmp::Ordering::Equal))
58 +
            .unwrap_or_default()
59 +
    }
60 +
61 +
    fn paint(&mut self, data: &T, ctx: PaintCtx<'_>) {
62 +
        for widget in &mut self.children {
63 +
            widget.paint(
64 +
                data,
65 +
                PaintCtx {
66 +
                    ops: ctx.ops,
67 +
                    ..ctx
68 +
                },
69 +
            );
70 +
        }
71 +
    }
72 +
73 +
    fn event(
74 +
        &mut self,
75 +
        event: &WidgetEvent,
76 +
        data: &mut T,
77 +
        ctx: EventCtx<'_>,
78 +
        win: &mut WindowCtx,
79 +
    ) -> bool {
80 +
        for widget in self.children.iter_mut().rev() {
81 +
            if widget.event(event, data, ctx, win) {
82 +
                return true;
83 +
            }
84 +
        }
85 +
        false
86 +
    }
87 +
88 +
    fn contains(&self, point: Point2D<f32, Local>) -> bool {
89 +
        self.children.iter().any(|c| c.contains(point))
90 +
    }
91 +
92 +
    fn debug(&self) -> DebugInfo {
93 +
        DebugInfo::new("ZStack").children(&self.children)
94 +
    }
95 +
}
96 +
97 +
/// Create a new [`ZStack`] from a list of child widgets.
98 +
pub fn zstack<W, T>(children: W) -> ZStack<T>
99 +
where
100 +
    W: WidgetList<T>,
101 +
{
102 +
    ZStack::new(children.to_vec())
103 +
}
104 +
105 +
#[cfg(test)]
106 +
mod tests {
107 +
    use super::*;
108 +
    use crate::ui::test::TestInterface;
109 +
    use crate::ui::widgets;
110 +
111 +
    #[test]
112 +
    fn test_zstack() {
113 +
        let child1 = widgets::Null.sized([5., 5.]).on_click(|_, s, _| *s = Some(1));
114 +
        let child2 = widgets::Null.sized([3., 3.]).on_click(|_, s, _| *s = Some(2));
115 +
        let child3 = widgets::Null.sized([1., 1.]).on_click(|_, s, _| *s = Some(3));
116 +
        let size = Size::new(5, 5); // Size of the largest child
117 +
118 +
        let mut widget = zstack((child1, child2, child3));
119 +
        let mut ui = TestInterface::new(size);
120 +
121 +
        assert_eq!(ui.layout(&mut widget), size.into());
122 +
123 +
        assert!(ui.click(&mut widget, [0., 0.])); // Hits all children, top-most (child3) responds
124 +
        assert_eq!(ui.take(), Some(3));
125 +
126 +
        assert!(ui.click(&mut widget, [2., 2.])); // Hits child1 and child2, child2 responds
127 +
        assert_eq!(ui.take(), Some(2));
128 +
129 +
        assert!(ui.click(&mut widget, [4., 4.])); // Only hits child1
130 +
        assert_eq!(ui.take(), Some(1));
131 +
132 +
        assert!(!ui.click(&mut widget, [5., 5.])); // Out of bounds
133 +
        assert_eq!(ui.take(), None);
134 +
    }
135 +
}
reve/Cargo.toml added +14 -0
1 +
[package]
2 +
name = "reve"
3 +
description = "Dream in three dimensions"
4 +
keywords = ["graphics", "3d", "modeler"]
5 +
categories = ["graphics", "rendering", "game-development"]
6 +
version = "0.0.0"
7 +
edition = "2021"
8 +
9 +
[dependencies]
10 +
ombre = { version = "0.6", path = "../ombre", features = ["derive"] }
11 +
log = { version = "0.4.20", features = ["std"] }
12 +
13 +
[lints]
14 +
workspace = true
reve/README added +14 -0
1 +
2 +
                           rêve
3 +
                                     rêve
4 +
                rêve
5 +
6 +
                               rêve                   rêve
7 +
                   rêve
8 +
                       rêve
9 +
                                         rêve
10 +
          rêve
11 +
                          rêve
12 +
                                               rêve
13 +
                            rêve
14 +
reve/src/camera.rs added +120 -0
1 +
//! Camera abstraction for creating 2D projections from a 3D scene.
2 +
use std::f32::consts::PI;
3 +
4 +
use ombre::prelude::*;
5 +
6 +
/// Camera input sensitivty settings.
7 +
#[derive(Debug)]
8 +
pub struct CameraSensitivity {
9 +
    /// Orbit sensitivty.
10 +
    pub orbit: f32,
11 +
    /// Dolly sensitivty.
12 +
    pub dolly: f32,
13 +
    /// Pan sensitivty.
14 +
    pub pan: f32,
15 +
}
16 +
17 +
impl CameraSensitivity {
18 +
    pub fn fov(angle: f32) -> Self {
19 +
        Self {
20 +
            orbit: 0.0015 * angle / 90.,
21 +
            dolly: 0.0020 * angle / 90.,
22 +
            pan: 0.0015 * angle / 90.,
23 +
        }
24 +
    }
25 +
}
26 +
27 +
impl Default for CameraSensitivity {
28 +
    fn default() -> Self {
29 +
        Self {
30 +
            orbit: 0.0025,
31 +
            dolly: 0.0050,
32 +
            pan: 0.0025,
33 +
        }
34 +
    }
35 +
}
36 +
37 +
/// Camera object.
38 +
#[derive(Debug)]
39 +
pub struct Camera {
40 +
    /// Camera "eye" position.
41 +
    pub eye: Vector3D<f32, World>,
42 +
    /// Where the camera is looking at.
43 +
    pub target: Vector3D<f32, World>,
44 +
    /// An optional object position that is in focus.
45 +
    /// When resetting the camera, we set the target to this object.
46 +
    pub object: Option<Vector3D<f32, World>>,
47 +
    /// Up vector (roll).
48 +
    pub up: Vector3D<f32, World>,
49 +
    /// Controls the sensitivty to user input.
50 +
    pub sensitivity: CameraSensitivity,
51 +
    /// Near Z-plane.
52 +
    pub near: f32,
53 +
    /// Far Z-plane.
54 +
    pub far: f32,
55 +
    /// Field of view (degrees).
56 +
    pub fov: f32,
57 +
}
58 +
59 +
impl Camera {
60 +
    /// Reset the camera so that it looks at its object straight on.
61 +
    pub fn reset(&mut self) {
62 +
        self.target = self.object.unwrap_or_default();
63 +
        self.eye = self.target + Vector3D::new(0., 0., 5.); // TODO: Compute distance.
64 +
    }
65 +
66 +
    /// Pan the camera.
67 +
    pub fn pan(&mut self, delta: Vector2D<f32, Screen>) {
68 +
        let scale = self.sensitivity.pan * (self.target - self.eye).magnitude();
69 +
        let forward = (self.target - self.eye).normalize();
70 +
        let right = Vector3D::cross(forward, self.up).normalize();
71 +
        let up = Vector3D::cross(right, forward).normalize();
72 +
        let horizontal = right * -delta.x * scale;
73 +
        let vertical = up * delta.y * scale;
74 +
75 +
        self.eye = self.eye + horizontal + vertical;
76 +
        self.target = self.target + horizontal + vertical;
77 +
    }
78 +
79 +
    /// Dolly the camera.
80 +
    pub fn dolly(&mut self, delta: Vector2D<f32, Screen>) {
81 +
        let mut sph = self.eye.to_spherical(self.target);
82 +
83 +
        // Scale sensitivty based on distance from object.
84 +
        sph.x -= (delta.y * self.sensitivity.dolly) * sph.x;
85 +
        sph.x = sph.x.max(0.1);
86 +
87 +
        // Convert back to cartesian coordinates.
88 +
        self.eye = sph.to_world() + self.target;
89 +
    }
90 +
91 +
    /// Orbit the camera around its target.
92 +
    pub fn orbit(&mut self, delta: impl Into<Vector2D<f32, Screen>>) {
93 +
        let delta = delta.into();
94 +
        let mut sph = self.eye.to_spherical(self.target);
95 +
        let max = self.sensitivity.orbit * 10.;
96 +
97 +
        sph.y += (delta.x * self.sensitivity.orbit * sph.x).clamp(-max, max);
98 +
        sph.z -= (delta.y * self.sensitivity.orbit * sph.x).clamp(-max, max);
99 +
100 +
        // Clamp phi to avoid going over the poles.
101 +
        sph.z = sph.z.clamp(0.01, PI - 0.01);
102 +
        // Convert back to cartesian coordinates.
103 +
        self.eye = sph.to_world() + self.target;
104 +
    }
105 +
106 +
    /// Return a projection transform based on the camera, ie. a perspective matrix.
107 +
    pub fn projection(&self, size: Size<f32>) -> Transform3D<f32, World, Screen> {
108 +
        Transform3D::<f32, World, Screen>::perspective(
109 +
            self.fov,
110 +
            size.w / size.h,
111 +
            self.near,
112 +
            self.far,
113 +
        ) * Transform3D::<f32, Screen, Screen>::from_nonuniform_scale(1.0, -1.0, 1.0)
114 +
    }
115 +
116 +
    /// Return a view transform based on the camera, ie. a "look at" matrix.
117 +
    pub fn view(&self) -> Transform3D<f32, World> {
118 +
        Transform3D::<f32, World>::look_at(self.eye, self.target, self.up)
119 +
    }
120 +
}
reve/src/lib.rs added +368 -0
1 +
#![allow(clippy::too_many_arguments)]
2 +
#![allow(clippy::collapsible_if)]
3 +
#![allow(clippy::single_match)]
4 +
mod camera;
5 +
mod renderer;
6 +
7 +
use camera::{Camera, CameraSensitivity};
8 +
use ombre::collections::IntMap;
9 +
use ombre::{math::Zero, prelude::*};
10 +
use renderer::{InteractionMode, NodeId, RenderStyle, Renderer};
11 +
12 +
#[derive(Debug, Default)]
13 +
pub struct Options {}
14 +
15 +
#[derive(Debug)]
16 +
pub enum Error<T: RenderBackend> {
17 +
    Renderer(renderer::Error<T::Error>),
18 +
    Backend(T::Error),
19 +
}
20 +
21 +
impl<T: RenderBackend> From<renderer::Error<T::Error>> for Error<T> {
22 +
    fn from(e: renderer::Error<T::Error>) -> Self {
23 +
        Self::Renderer(e)
24 +
    }
25 +
}
26 +
27 +
impl<T: RenderBackend> std::fmt::Display for Error<T>
28 +
where
29 +
    T::Error: std::fmt::Display,
30 +
{
31 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32 +
        match self {
33 +
            Self::Renderer(e) => e.fmt(f),
34 +
            Self::Backend(e) => e.fmt(f),
35 +
        }
36 +
    }
37 +
}
38 +
39 +
impl<T: RenderBackend + std::fmt::Debug> std::error::Error for Error<T> {}
40 +
41 +
#[derive(Debug, Default)]
42 +
pub struct Mouse {
43 +
    pressed: IntMap<platform::MouseButton, u64>,
44 +
    scroll: Vector2D<f32, Screen>,
45 +
    counter: u64,
46 +
    moved: bool,
47 +
}
48 +
49 +
impl Mouse {
50 +
    fn is_down(&self, button: platform::MouseButton) -> bool {
51 +
        self.pressed.contains_key(&button)
52 +
    }
53 +
54 +
    fn is_pressed(&self, button: platform::MouseButton) -> bool {
55 +
        self.pressed.get(&button).map_or(false, |c| *c == self.counter)
56 +
    }
57 +
}
58 +
59 +
#[derive(Debug, Default)]
60 +
pub struct KeyboardModifiers {
61 +
    ctrl: bool,
62 +
    shift: bool,
63 +
    alt: bool,
64 +
}
65 +
66 +
#[derive(Debug, Default)]
67 +
pub struct Keyboard {
68 +
    pressed: IntMap<platform::Key, u64>,
69 +
    modifiers: KeyboardModifiers,
70 +
    counter: u64,
71 +
}
72 +
73 +
impl Keyboard {
74 +
    fn is_down(&self, key: platform::Key) -> bool {
75 +
        self.pressed.contains_key(&key)
76 +
    }
77 +
78 +
    fn is_pressed(&self, key: platform::Key) -> bool {
79 +
        self.pressed.get(&key).map_or(false, |c| *c == self.counter)
80 +
    }
81 +
}
82 +
83 +
pub struct State<T> {
84 +
    renderer: Renderer<T>,
85 +
    cursor: Point2D<f32, Screen>,
86 +
    selected: Option<NodeId>,
87 +
    drag: Option<Point2D<f32, Screen>>,
88 +
    mode: InteractionMode,
89 +
    mouse: Mouse,
90 +
    keyboard: Keyboard,
91 +
    camera: Camera,
92 +
    width: f64,
93 +
    height: f64,
94 +
}
95 +
96 +
impl<T: gfx::RenderBackend + std::fmt::Debug + 'static> ApplicationExt for State<T> {
97 +
    type Error = Error<T>;
98 +
99 +
    fn update(
100 +
        &mut self,
101 +
        _delta: runtime::time::Duration,
102 +
        _win: &mut platform::Window,
103 +
    ) -> Result<(), Self::Error> {
104 +
        Ok(())
105 +
    }
106 +
107 +
    fn window_resized(&mut self, size: platform::LogicalSize) -> Result<(), Error<T>> {
108 +
        self.width = size.width;
109 +
        self.height = size.height;
110 +
        self.renderer.window_resized(size)?;
111 +
112 +
        Ok(())
113 +
    }
114 +
115 +
    fn key_down(&mut self, key: platform::Key) {
116 +
        if self.mouse.pressed.is_empty() {
117 +
            match key {
118 +
                platform::Key::Control => self.keyboard.modifiers.ctrl = true,
119 +
                platform::Key::Shift => self.keyboard.modifiers.shift = true,
120 +
                platform::Key::Alt => self.keyboard.modifiers.alt = true,
121 +
                _ => {
122 +
                    self.keyboard.pressed.insert(key, self.keyboard.counter);
123 +
                }
124 +
            }
125 +
        }
126 +
    }
127 +
128 +
    fn key_up(&mut self, key: platform::Key) {
129 +
        match key {
130 +
            platform::Key::Control => self.keyboard.modifiers.ctrl = false,
131 +
            platform::Key::Shift => self.keyboard.modifiers.shift = false,
132 +
            platform::Key::Alt => self.keyboard.modifiers.alt = false,
133 +
            _ => {
134 +
                self.keyboard.pressed.remove(&key);
135 +
            }
136 +
        }
137 +
    }
138 +
139 +
    fn mouse_down(&mut self, button: platform::MouseButton) {
140 +
        self.mouse.pressed.insert(button, self.mouse.counter);
141 +
    }
142 +
143 +
    fn mouse_up(&mut self, button: platform::MouseButton) {
144 +
        self.mouse.pressed.remove(&button);
145 +
    }
146 +
147 +
    fn mouse_moved(&mut self, position: Point2D<f32, Screen>) {
148 +
        self.mouse.moved = self.cursor != position;
149 +
        self.cursor = position;
150 +
    }
151 +
152 +
    fn mouse_scroll(&mut self, delta: Vector2D<f32, Screen>) {
153 +
        self.mouse.scroll = delta;
154 +
    }
155 +
156 +
    fn present(&mut self) -> Result<(), Error<T>> {
157 +
        if !self.mouse.pressed.is_empty() {
158 +
            if self.drag.is_none() {
159 +
                self.drag = Some(self.cursor);
160 +
            }
161 +
        } else {
162 +
            self.drag = None;
163 +
        }
164 +
        if let Some(previous) = self.drag {
165 +
            let delta = self.cursor - previous;
166 +
            if !delta.is_zero() {
167 +
                if self.keyboard.is_down(platform::Key::S) {
168 +
                    if self.mouse.is_down(platform::MouseButton::Right) {
169 +
                        self.camera.orbit(delta);
170 +
                    } else if self.mouse.is_down(platform::MouseButton::Left) {
171 +
                        self.camera.pan(delta);
172 +
                    } else if self.mouse.is_down(platform::MouseButton::Middle) {
173 +
                        self.camera.dolly(Vector2D::new(delta.y, delta.x));
174 +
                    }
175 +
                    self.drag = None;
176 +
                }
177 +
            }
178 +
        }
179 +
        if !self.mouse.scroll.is_zero() {
180 +
            if self.keyboard.is_down(platform::Key::S) {
181 +
                self.camera.dolly(self.mouse.scroll);
182 +
            }
183 +
        }
184 +
185 +
        if self.mouse.moved && self.keyboard.pressed.is_empty() {
186 +
            if let Some(node) = self.selected {
187 +
                if let Some(v) = self.renderer.polygon_at(self.cursor)? {
188 +
                    match self.mode {
189 +
                        InteractionMode::Polygons => {
190 +
                            self.renderer
191 +
                                .active(node, Some(renderer::Component::Polygon(v as i32)));
192 +
                        }
193 +
                        _ => {}
194 +
                    }
195 +
                } else {
196 +
                    self.renderer.active(node, None);
197 +
                }
198 +
            }
199 +
        }
200 +
201 +
        if self.mouse.is_pressed(platform::MouseButton::Left) && self.keyboard.pressed.is_empty() {
202 +
            match self.mode {
203 +
                InteractionMode::Objects => {
204 +
                    if let Some(node) = self.renderer.node_at(self.cursor)? {
205 +
                        self.select(node);
206 +
                    } else if let Some(node) = self.selected {
207 +
                        self.deselect(node);
208 +
                    }
209 +
                }
210 +
                InteractionMode::Points => {
211 +
                    if let Some(node) = self.selected {
212 +
                        // TODO: Use hover state?
213 +
                        if let Some(v) = self.renderer.vertex_at(self.cursor)? {
214 +
                            self.renderer.select_vertices(&[v], node)?;
215 +
                        }
216 +
                    }
217 +
                }
218 +
                InteractionMode::Polygons => {
219 +
                    if let Some(node) = self.selected {
220 +
                        // TODO: Use hover state?
221 +
                        if let Some(p) = self.renderer.polygon_at(self.cursor)? {
222 +
                            self.renderer.select_polygons(&[p], node)?;
223 +
                        }
224 +
                    }
225 +
                }
226 +
                _ => {}
227 +
            }
228 +
        }
229 +
        if self.keyboard.is_down(platform::Key::Left) {
230 +
            self.camera.orbit([-0.5, 0.])
231 +
        }
232 +
        if self.keyboard.is_down(platform::Key::Right) {
233 +
            self.camera.orbit([0.5, 0.])
234 +
        }
235 +
        if self.keyboard.is_pressed(platform::Key::R) {
236 +
            self.camera.reset();
237 +
        }
238 +
        if self.keyboard.is_pressed(platform::Key::A) {
239 +
            // TODO: Frame all
240 +
        }
241 +
        if self.keyboard.is_pressed(platform::Key::F) {
242 +
            // TODO: Frame selection
243 +
        }
244 +
        if self.keyboard.is_pressed(platform::Key::Escape) {
245 +
            self.mode = InteractionMode::Objects;
246 +
        }
247 +
        if self.keyboard.is_pressed(platform::Key::E) {
248 +
            if self.selected.is_some() {
249 +
                self.mode.toggle(InteractionMode::Edges);
250 +
            }
251 +
        }
252 +
        if self.keyboard.is_pressed(platform::Key::T) {
253 +
            if self.selected.is_some() {
254 +
                self.mode.toggle(InteractionMode::Points);
255 +
            }
256 +
        }
257 +
        if self.keyboard.is_pressed(platform::Key::Y) {
258 +
            if self.selected.is_some() {
259 +
                self.mode.toggle(InteractionMode::Polygons);
260 +
            }
261 +
        }
262 +
        if self.keyboard.is_pressed(platform::Key::Num1) && self.keyboard.modifiers.ctrl {
263 +
            self.renderer.model(renderer::ModelBuilder::cube(1.))?;
264 +
        }
265 +
        if self.keyboard.is_pressed(platform::Key::Num2) && self.keyboard.modifiers.ctrl {
266 +
            self.renderer.model(renderer::ModelBuilder::sphere())?;
267 +
        }
268 +
269 +
        if let Some(id) = self.selected {
270 +
            if let Some(node) = self.renderer.scene.get_mut(&id) {
271 +
                match &mut node.object {
272 +
                    renderer::Object::Mesh { mode, .. } => {
273 +
                        *mode = self.mode;
274 +
                    }
275 +
                    _ => {}
276 +
                }
277 +
            }
278 +
        }
279 +
280 +
        self.mouse.scroll = Vector2D::zero();
281 +
        self.renderer.frame(&self.camera)?;
282 +
        self.keyboard.counter += 1;
283 +
        self.mouse.counter += 1;
284 +
        self.mouse.moved = false;
285 +
286 +
        Ok(())
287 +
    }
288 +
}
289 +
290 +
impl<T: gfx::RenderBackend> State<T> {
291 +
    pub fn init(viewport: platform::LogicalSize, backend: T) -> Result<Self, T::Error> {
292 +
        let renderer = Renderer::init(viewport, backend)?;
293 +
294 +
        Ok(Self {
295 +
            renderer,
296 +
            drag: None,
297 +
            mode: InteractionMode::default(),
298 +
            selected: None,
299 +
            cursor: Point2D::ORIGIN,
300 +
            mouse: Mouse::default(),
301 +
            keyboard: Keyboard::default(),
302 +
            camera: Camera {
303 +
                eye: Vector3D::new(0., 0., 5.),
304 +
                fov: 60.,
305 +
                near: 0.01,
306 +
                far: 10.,
307 +
                up: Vector3D::new(0.0, 1.0, 0.0),
308 +
                sensitivity: CameraSensitivity::fov(60.),
309 +
                target: Vector3D::ZERO,
310 +
                object: None,
311 +
            },
312 +
            width: 1.,
313 +
            height: 1.,
314 +
        })
315 +
    }
316 +
317 +
    fn select(&mut self, node: NodeId) {
318 +
        if let Some(node) = self.renderer.scene.get_mut(&node) {
319 +
            match &mut node.object {
320 +
                renderer::Object::Mesh { style, .. } => {
321 +
                    *style |= RenderStyle::WIREFRAME;
322 +
                }
323 +
                _ => {}
324 +
            }
325 +
        }
326 +
        self.selected = Some(node);
327 +
    }
328 +
329 +
    fn deselect(&mut self, node: NodeId) {
330 +
        if let Some(node) = self.renderer.scene.get_mut(&node) {
331 +
            match node.object {
332 +
                renderer::Object::Mesh {
333 +
                    ref mut style,
334 +
                    ref mut mode,
335 +
                    ..
336 +
                } => {
337 +
                    *style = RenderStyle::default();
338 +
                    *mode = InteractionMode::Objects;
339 +
                }
340 +
                _ => {}
341 +
            }
342 +
        }
343 +
        self.selected = None;
344 +
    }
345 +
}
346 +
347 +
/// Main entry point.
348 +
pub fn run(_opts: Options) -> Result<(), Box<dyn std::error::Error + 'static>> {
349 +
    logger::init(log::Level::Debug)?;
350 +
351 +
    let viewport = platform::LogicalSize {
352 +
        width: 640.,
353 +
        height: 480.,
354 +
    };
355 +
    let (mut win, events) = platform::init(
356 +
        "ombre3d",
357 +
        viewport.width as u32,
358 +
        viewport.height as u32,
359 +
        &[],
360 +
        platform::GraphicsContext::Gl,
361 +
    )?;
362 +
    let backend = gfx::gl::Context::load(&mut win)?;
363 +
    let renderer = State::init(viewport, backend)?;
364 +
365 +
    ombre::runtime::default::run(win, events, renderer)?;
366 +
367 +
    Ok(())
368 +
}
reve/src/main.rs added +10 -0
1 +
use std::process;
2 +
3 +
fn main() {
4 +
    use reve::*;
5 +
6 +
    if let Err(e) = run(Options::default()) {
7 +
        eprintln!("fatal: {e}");
8 +
        process::exit(1);
9 +
    }
10 +
}
reve/src/renderer.rs added +617 -0
1 +
mod mesh;
2 +
mod scene;
3 +
mod shaders;
4 +
5 +
use std::ops::Not;
6 +
7 +
use ombre::derive::Packed;
8 +
use ombre::prelude::*;
9 +
10 +
pub use mesh::*;
11 +
pub use scene::*;
12 +
13 +
use crate::camera::Camera;
14 +
15 +
#[derive(Debug)]
16 +
pub enum Error<T> {
17 +
    InvalidVertexId(u32),
18 +
    Backend(T),
19 +
}
20 +
21 +
impl<T> From<T> for Error<T> {
22 +
    fn from(e: T) -> Self {
23 +
        Self::Backend(e)
24 +
    }
25 +
}
26 +
27 +
impl<T> std::fmt::Display for Error<T>
28 +
where
29 +
    T: std::fmt::Display,
30 +
{
31 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32 +
        match self {
33 +
            Self::InvalidVertexId(id) => write!(f, "invalid vertex id {id}"),
34 +
            Self::Backend(e) => e.fmt(f),
35 +
        }
36 +
    }
37 +
}
38 +
39 +
struct Pipeline<U> {
40 +
    id: gfx::PipelineId,
41 +
    uniforms: U,
42 +
}
43 +
44 +
impl<U> Pipeline<U> {
45 +
    fn new(id: gfx::PipelineId, uniforms: U) -> Self {
46 +
        Self { id, uniforms }
47 +
    }
48 +
}
49 +
50 +
struct Pipelines {
51 +
    offscreen: Pipeline<shaders::default::Uniforms>,
52 +
    display: Pipeline<shaders::display::Uniforms>,
53 +
    gizmo: Pipeline<shaders::constant::Uniforms>,
54 +
}
55 +
56 +
struct Passes {
57 +
    offscreen: OffscreenPass,
58 +
    default: DefaultPass,
59 +
}
60 +
61 +
struct OffscreenPass {
62 +
    id: PassId,
63 +
}
64 +
65 +
struct DefaultPass {
66 +
    bindings: gfx::Bindings<0, 1>,
67 +
}
68 +
69 +
#[derive(Debug, Copy, Clone)]
70 +
pub enum Component {
71 +
    Point(i32),
72 +
    Polygon(i32),
73 +
    Edge(i32),
74 +
}
75 +
76 +
impl From<Component> for i32 {
77 +
    fn from(value: Component) -> Self {
78 +
        match value {
79 +
            Component::Point(id) => id,
80 +
            Component::Polygon(id) => id,
81 +
            Component::Edge(id) => id,
82 +
        }
83 +
    }
84 +
}
85 +
86 +
struct ActiveState {
87 +
    pub node: NodeId,
88 +
    pub component: Option<Component>,
89 +
}
90 +
91 +
pub struct Renderer<T> {
92 +
    pub scene: scene::Graph,
93 +
94 +
    pipelines: Pipelines,
95 +
    passes: Passes,
96 +
    viewport: Size<f64>,
97 +
    active: Option<ActiveState>,
98 +
    backend: T,
99 +
}
100 +
101 +
impl<T: gfx::RenderBackend> Renderer<T> {
102 +
    pub fn init(viewport: platform::LogicalSize, mut backend: T) -> Result<Self, T::Error> {
103 +
        let viewport = Size::new(viewport.width, viewport.height);
104 +
        let passes = {
105 +
            let default = backend.texture(gfx::Texture {
106 +
                data: gfx::Empty,
107 +
                target: TextureKind::default(),
108 +
                size: viewport.map(|n| n.floor() as u32),
109 +
                access: gfx::TextureAccess::RenderTarget,
110 +
                wrap: gfx::TextureWrap::Clamp,
111 +
                format: gfx::TextureFormat::Rgba8,
112 +
                min_filter: FilterMode::Nearest,
113 +
                mag_filter: FilterMode::Nearest,
114 +
            })?;
115 +
            let ids = backend.texture(gfx::Texture {
116 +
                data: gfx::Empty,
117 +
                target: TextureKind::default(),
118 +
                size: viewport.map(|n| n.floor() as u32),
119 +
                access: gfx::TextureAccess::RenderTarget,
120 +
                wrap: gfx::TextureWrap::Clamp,
121 +
                format: gfx::TextureFormat::Signed,
122 +
                min_filter: FilterMode::Nearest,
123 +
                mag_filter: FilterMode::Nearest,
124 +
            })?;
125 +
            let depth = backend.texture(gfx::Texture {
126 +
                data: gfx::Empty,
127 +
                access: gfx::TextureAccess::RenderTarget,
128 +
                size: viewport.map(|n| n.floor() as u32),
129 +
                format: gfx::TextureFormat::Depth,
130 +
                ..Default::default()
131 +
            })?;
132 +
            let offscreen = backend.pass(gfx::PassDescriptor {
133 +
                color_attachments: &[default, ids],
134 +
                depth_attachment: Some(depth),
135 +
            })?;
136 +
            let bindings = gfx::Bindings {
137 +
                vertex: [],
138 +
                index: None,
139 +
                textures: [default],
140 +
            };
141 +
142 +
            Passes {
143 +
                offscreen: OffscreenPass { id: offscreen },
144 +
                default: DefaultPass { bindings },
145 +
            }
146 +
        };
147 +
148 +
        // Default pipeline for shading models.
149 +
        let default_shader =
150 +
            backend.shader(shaders::default::source(), shaders::default::description())?;
151 +
        let default_pipeline = backend.pipeline(
152 +
            default_shader,
153 +
            gfx::PipelineDescriptor {
154 +
                layout: &[
155 +
                    gfx::BufferLayout {
156 +
                        attrs: &shaders::default::attributes()[0..=5],
157 +
                        stride: Some(mesh::Vertex::stride()),
158 +
                        ..gfx::BufferLayout::default()
159 +
                    },
160 +
                    gfx::BufferLayout {
161 +
                        attrs: &shaders::default::attributes()[6..=6],
162 +
                        stride: None,
163 +
                        ..gfx::BufferLayout::default()
164 +
                    },
165 +
                ],
166 +
                depth: Some(gfx::DepthState {
167 +
                    compare: gfx::Comparison::LessOrEqual,
168 +
                    offset: None,
169 +
                }),
170 +
                culling: gfx::CullMode::Nothing,
171 +
                ..gfx::PipelineDescriptor::default()
172 +
            },
173 +
        )?;
174 +
175 +
        // Pipeline for rendering gizmos, like for manipulating objects.
176 +
        let gizmo_shader = backend.shader(
177 +
            shaders::constant::source(),
178 +
            shaders::constant::description(),
179 +
        )?;
180 +
        let gizmo_pipeline = backend.pipeline(
181 +
            gizmo_shader,
182 +
            gfx::PipelineDescriptor {
183 +
                layout: &[gfx::BufferLayout {
184 +
                    attrs: &shaders::constant::attributes(),
185 +
                    stride: Some(mesh::Vertex::stride()),
186 +
                    ..gfx::BufferLayout::default()
187 +
                }],
188 +
                depth: Some(gfx::DepthState {
189 +
                    compare: gfx::Comparison::LessOrEqual,
190 +
                    offset: None,
191 +
                }),
192 +
                culling: gfx::CullMode::Nothing,
193 +
                ..gfx::PipelineDescriptor::default()
194 +
            },
195 +
        )?;
196 +
197 +
        // Pipeline for rendering backbuffer to the screen.
198 +
        let display_shader =
199 +
            backend.shader(shaders::display::source(), shaders::display::description())?;
200 +
        let display_pipeline = backend.pipeline(
201 +
            display_shader,
202 +
            gfx::PipelineDescriptor {
203 +
                layout: &[],
204 +
                depth: None,
205 +
                culling: gfx::CullMode::Nothing,
206 +
                ..gfx::PipelineDescriptor::default()
207 +
            },
208 +
        )?;
209 +
210 +
        Ok(Self {
211 +
            pipelines: Pipelines {
212 +
                offscreen: Pipeline::new(
213 +
                    default_pipeline,
214 +
                    shaders::default::Uniforms {
215 +
                        model: Transform3D::default(),
216 +
                        view: Transform3D::default(),
217 +
                        proj: Transform3D::default(),
218 +
                        light: Vector3D::new(5., 3., 2.),
219 +
                        window_size: viewport.map(|n| n.floor() as f32),
220 +
                        enable_tomemap: 0,
221 +
                        render_mode: 1,
222 +
                        object_id: 0,
223 +
                        interaction_mode: InteractionMode::default().into(),
224 +
                        vertex_hovered: -1,
225 +
                    },
226 +
                ),
227 +
                display: Pipeline::new(display_pipeline, ()),
228 +
                gizmo: Pipeline::new(
229 +
                    gizmo_pipeline,
230 +
                    shaders::constant::Uniforms {
231 +
                        model: Transform3D::default(),
232 +
                        view: Transform3D::default(),
233 +
                        proj: Transform3D::default(),
234 +
                    },
235 +
                ),
236 +
            },
237 +
            passes,
238 +
            active: None,
239 +
            scene: scene::Graph::default(),
240 +
            viewport,
241 +
            backend,
242 +
        })
243 +
    }
244 +
245 +
    pub fn frame(&mut self, camera: &Camera) -> Result<(), Error<T::Error>> {
246 +
        let mut frame = self.backend.frame();
247 +
        let proj = camera.projection(self.viewport.map(|n| n.floor() as f32));
248 +
        let view = camera.view();
249 +
        let model = Transform3D::rotation(30., Vector3D::new(0., 1., 0.))
250 +
            * Transform3D::<f32>::rotation(30., Vector3D::new(1., 0., 0.));
251 +
252 +
        //
253 +
        // Offscreen pass.
254 +
        //
255 +
        self.pipelines.offscreen.uniforms.model = model;
256 +
        self.pipelines.offscreen.uniforms.view = view;
257 +
        self.pipelines.offscreen.uniforms.proj = proj;
258 +
        self.pipelines.offscreen.uniforms.window_size = self.viewport.map(|n| n.floor() as f32);
259 +
260 +
        frame.begin_pass(self.passes.offscreen.id, gfx::PassAction::default());
261 +
        frame.apply_pipeline(&self.pipelines.offscreen.id)?;
262 +
263 +
        for node in self.scene.iter() {
264 +
            if let scene::Object::Mesh {
265 +
                bindings,
266 +
                elements,
267 +
                style,
268 +
                mode,
269 +
                ..
270 +
            } = &node.object
271 +
            {
272 +
                self.pipelines.offscreen.uniforms.object_id = node.id.into();
273 +
                self.pipelines.offscreen.uniforms.render_mode = style.into();
274 +
                self.pipelines.offscreen.uniforms.interaction_mode = (*mode).into();
275 +
276 +
                if let Some(hover) = &self.active {
277 +
                    if hover.node == node.id {
278 +
                        if let Some(c) = hover.component {
279 +
                            self.pipelines.offscreen.uniforms.vertex_hovered = c.into();
280 +
                        } else {
281 +
                            self.pipelines.offscreen.uniforms.vertex_hovered = -1;
282 +
                        }
283 +
                    }
284 +
                }
285 +
286 +
                frame.apply_uniforms(&self.pipelines.offscreen.uniforms)?;
287 +
                frame.apply_bindings(bindings)?;
288 +
                frame.draw(0, *elements, 1)?;
289 +
            }
290 +
        }
291 +
        frame.end_pass();
292 +
293 +
        //
294 +
        // Default pass.
295 +
        //
296 +
        frame.begin_default_pass(gfx::PassAction::default(), self.viewport.map(|n| n as u32));
297 +
        frame.apply_pipeline(&self.pipelines.display.id)?;
298 +
        frame.apply_uniforms(&self.pipelines.display.uniforms)?;
299 +
        frame.apply_bindings(&self.passes.default.bindings)?;
300 +
        frame.draw(0, 6, 1)?;
301 +
302 +
        //
303 +
        // Gizmo pipeline
304 +
        //
305 +
        self.pipelines.gizmo.uniforms.model = model;
306 +
        self.pipelines.gizmo.uniforms.view = view;
307 +
        self.pipelines.gizmo.uniforms.proj = proj;
308 +
309 +
        frame.apply_pipeline(&self.pipelines.gizmo.id)?;
310 +
        frame.apply_uniforms(&self.pipelines.gizmo.uniforms)?;
311 +
312 +
        for node in self.scene.iter() {
313 +
            if let scene::Object::Null = &node.object {
314 +
                // TODO
315 +
            }
316 +
        }
317 +
        frame.end_pass();
318 +
        frame.commit();
319 +
320 +
        Ok(())
321 +
    }
322 +
323 +
    pub fn active(&mut self, node: NodeId, component: Option<Component>) {
324 +
        self.active = Some(ActiveState { node, component });
325 +
    }
326 +
327 +
    #[allow(dead_code)]
328 +
    pub fn inactive(&mut self) {
329 +
        self.active = None;
330 +
    }
331 +
332 +
    pub fn model(&mut self, builder: ModelBuilder) -> Result<scene::NodeId, Error<T::Error>> {
333 +
        let bindings = {
334 +
            let vbo = self.backend.buffer(
335 +
                gfx::BufferKind::Vertex,
336 +
                gfx::BufferUsage::Immutable,
337 +
                gfx::BufferSource::slice(&builder.mesh.vertices),
338 +
            )?;
339 +
            let svbo = self.backend.buffer(
340 +
                gfx::BufferKind::Vertex,
341 +
                gfx::BufferUsage::Dynamic,
342 +
                gfx::BufferSource::<Flag>::zero(builder.mesh.vertices.len()),
343 +
            )?;
344 +
            let ibo = builder
345 +
                .mesh
346 +
                .indices
347 +
                .as_ref()
348 +
                .map(|i| {
349 +
                    self.backend.buffer(
350 +
                        gfx::BufferKind::Index,
351 +
                        gfx::BufferUsage::Immutable,
352 +
                        gfx::BufferSource::slice(i),
353 +
                    )
354 +
                })
355 +
                .transpose()?;
356 +
            let blank = self.backend.texture(gfx::Texture {
357 +
                data: [Rgba8::WHITE].as_slice(),
358 +
                size: Size::new(1, 1),
359 +
                wrap: gfx::TextureWrap::Repeat,
360 +
                ..gfx::Texture::default()
361 +
            })?;
362 +
363 +
            gfx::Bindings {
364 +
                vertex: [vbo, svbo],
365 +
                index: ibo,
366 +
                textures: [blank, blank],
367 +
            }
368 +
        };
369 +
370 +
        let node = Node::new(scene::Object::Mesh {
371 +
            bindings,
372 +
            selection: vec![Flag::NO; builder.mesh.vertices.len()],
373 +
            elements: builder.mesh.elements(),
374 +
            vertices: builder.mesh.vertices,
375 +
            style: RenderStyle::default(),
376 +
            mode: InteractionMode::default(),
377 +
        });
378 +
        let id = node.id;
379 +
        let parent = self.scene.root().id;
380 +
381 +
        self.scene.insert(node, parent);
382 +
383 +
        Ok(id)
384 +
    }
385 +
386 +
    #[allow(dead_code)]
387 +
    pub fn color_at(
388 +
        &mut self,
389 +
        point: Point2D<f32, Screen>,
390 +
    ) -> Result<Option<Rgba<f32>>, Error<T::Error>> {
391 +
        if let Some(color) = self.at::<Rgba<f32>>(point, 0)? {
392 +
            return Ok(Some(color));
393 +
        }
394 +
        Ok(None)
395 +
    }
396 +
397 +
    pub fn vertex_at(
398 +
        &mut self,
399 +
        point: Point2D<f32, Screen>,
400 +
    ) -> Result<Option<u32>, Error<T::Error>> {
401 +
        if let Some(id) = self.at::<u32>(point, 1)? {
402 +
            return Ok(id.checked_sub(1));
403 +
        }
404 +
        Ok(None)
405 +
    }
406 +
407 +
    pub fn polygon_at(
408 +
        &mut self,
409 +
        point: Point2D<f32, Screen>,
410 +
    ) -> Result<Option<u32>, Error<T::Error>> {
411 +
        if let Some(id) = self.at::<u32>(point, 1)? {
412 +
            if id.is_zero() {
413 +
                return Ok(None);
414 +
            }
415 +
            return Ok(Some(id));
416 +
        }
417 +
        Ok(None)
418 +
    }
419 +
420 +
    pub fn node_at(
421 +
        &mut self,
422 +
        point: Point2D<f32, Screen>,
423 +
    ) -> Result<Option<NodeId>, Error<T::Error>> {
424 +
        if let Some(pixel) = self.at::<u32>(point, 1)? {
425 +
            return Ok(NodeId::new(pixel));
426 +
        }
427 +
        Ok(None)
428 +
    }
429 +
430 +
    pub fn window_resized(&mut self, size: platform::LogicalSize) -> Result<(), Error<T::Error>> {
431 +
        self.backend.window_resized(size);
432 +
        self.backend.pass_resize_attachments(
433 +
            self.passes.offscreen.id,
434 +
            Size::new(size.width as u32, size.height as u32),
435 +
        )?;
436 +
        self.viewport = Size::new(size.width, size.height);
437 +
438 +
        Ok(())
439 +
    }
440 +
441 +
    pub fn at<S: Default + Clone + Copy>(
442 +
        &mut self,
443 +
        point: Point2D<f32, Screen>,
444 +
        index: usize,
445 +
    ) -> Result<Option<S>, Error<T::Error>> {
446 +
        // TODO: Use `MaybeUninit` (measure)?
447 +
        let mut output = vec![S::default(); self.viewport.area() as usize];
448 +
        self.backend
449 +
            .pass_read_color_attachment(self.passes.offscreen.id, index, &mut output)?;
450 +
451 +
        // TODO: Use conversion functions instead.
452 +
        let y = self.viewport.h as usize - point.y as usize;
453 +
        let pixels =
454 +
            pixels::Pixels::new(&output, self.viewport.w as usize, self.viewport.h as usize);
455 +
        let pixel = pixels.get(point.x.floor() as usize, self.viewport.h as usize - y);
456 +
457 +
        if let Some(pixel) = pixel {
458 +
            return Ok(Some(*pixel));
459 +
        }
460 +
        Ok(None)
461 +
    }
462 +
463 +
    pub fn select_vertices(&mut self, ixs: &[u32], node: NodeId) -> Result<(), Error<T::Error>> {
464 +
        if let Some(node) = self.scene.get_mut(&node) {
465 +
            match &mut node.object {
466 +
                Object::Mesh {
467 +
                    bindings,
468 +
                    selection,
469 +
                    vertices,
470 +
                    ..
471 +
                } => {
472 +
                    for ix in ixs.iter() {
473 +
                        // Find all vertices at this position, and select them.
474 +
                        let pos = vertices
475 +
                            .get(*ix as usize)
476 +
                            .ok_or(Error::InvalidVertexId(*ix))?
477 +
                            .position;
478 +
                        for (i, v) in vertices.iter().enumerate() {
479 +
                            if v.position == pos {
480 +
                                selection[i] = Flag::YES;
481 +
                            }
482 +
                        }
483 +
                    }
484 +
                    // Update the selection buffer for this mesh.
485 +
                    self.backend
486 +
                        .buffer_update(bindings.vertex[1], BufferKind::Vertex, 0, selection)
487 +
                        .map_err(Error::Backend)?;
488 +
                }
489 +
                _ => {}
490 +
            }
491 +
        }
492 +
        Ok(())
493 +
    }
494 +
495 +
    pub fn select_polygons(&mut self, ids: &[u32], node: NodeId) -> Result<(), Error<T::Error>> {
496 +
        if let Some(node) = self.scene.get_mut(&node) {
497 +
            match &mut node.object {
498 +
                Object::Mesh {
499 +
                    bindings,
500 +
                    selection,
501 +
                    vertices,
502 +
                    ..
503 +
                } => {
504 +
                    for id in ids.iter() {
505 +
                        for (i, v) in vertices.iter().enumerate() {
506 +
                            if v.polygon == *id {
507 +
                                selection[i] = Flag::YES;
508 +
                            }
509 +
                        }
510 +
                    }
511 +
                    // Update the selection buffer for this mesh.
512 +
                    self.backend
513 +
                        .buffer_update(bindings.vertex[1], BufferKind::Vertex, 0, selection)
514 +
                        .map_err(Error::Backend)?;
515 +
                }
516 +
                _ => {}
517 +
            }
518 +
        }
519 +
        Ok(())
520 +
    }
521 +
}
522 +
523 +
pub struct ModelBuilder {
524 +
    mesh: Mesh,
525 +
}
526 +
527 +
impl ModelBuilder {
528 +
    pub fn cube(size: f32) -> Self {
529 +
        Self {
530 +
            mesh: Mesh::<u16>::cube(size),
531 +
        }
532 +
    }
533 +
534 +
    pub fn sphere() -> Self {
535 +
        Self {
536 +
            mesh: Mesh::<u16>::sphere(Rgba8::new(130, 47, 61, 255), 1.0, 12, 12),
537 +
        }
538 +
    }
539 +
}
540 +
541 +
/// On/off flag. Essentially a boolean in disguise, since GLSL shaders
542 +
/// do not support booleans as input.
543 +
#[derive(Debug, Copy, Clone, PartialEq, Default, Packed)]
544 +
#[repr(C)]
545 +
pub struct Flag(f32);
546 +
547 +
impl Flag {
548 +
    pub const YES: Flag = Flag(1.0);
549 +
    pub const NO: Flag = Flag(0.0);
550 +
}
551 +
552 +
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
553 +
#[repr(u8)]
554 +
pub enum InteractionMode {
555 +
    #[default]
556 +
    Objects = 0,
557 +
    Edges = 1,
558 +
    Points = 2,
559 +
    Polygons = 3,
560 +
}
561 +
562 +
impl InteractionMode {
563 +
    pub fn toggle(&mut self, mode: Self) {
564 +
        if *self == mode {
565 +
            *self = Self::Objects;
566 +
        } else {
567 +
            *self = mode;
568 +
        }
569 +
    }
570 +
}
571 +
572 +
impl From<InteractionMode> for u32 {
573 +
    fn from(rm: InteractionMode) -> Self {
574 +
        rm as u32
575 +
    }
576 +
}
577 +
578 +
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
579 +
pub struct RenderStyle(u32);
580 +
581 +
impl RenderStyle {
582 +
    pub const DIFFUSE: Self = Self(0b00000001);
583 +
    pub const FLAT_SHADED: Self = Self(0b00000010);
584 +
    pub const SPECULAR: Self = Self(0b00000100);
585 +
    pub const TEXTURED: Self = Self(0b00001000);
586 +
    pub const WIREFRAME: Self = Self(0b00010000);
587 +
588 +
    pub fn remove(&mut self, other: Self) {
589 +
        self.0 &= other.0.not();
590 +
    }
591 +
}
592 +
593 +
impl std::ops::BitOr for RenderStyle {
594 +
    type Output = Self;
595 +
596 +
    fn bitor(self, rhs: Self) -> Self::Output {
597 +
        Self(self.0 | rhs.0)
598 +
    }
599 +
}
600 +
601 +
impl std::ops::BitOrAssign for RenderStyle {
602 +
    fn bitor_assign(&mut self, rhs: Self) {
603 +
        self.0 |= rhs.0
604 +
    }
605 +
}
606 +
607 +
impl From<&RenderStyle> for u32 {
608 +
    fn from(rs: &RenderStyle) -> Self {
609 +
        rs.0
610 +
    }
611 +
}
612 +
613 +
impl Default for RenderStyle {
614 +
    fn default() -> Self {
615 +
        Self::DIFFUSE | Self::SPECULAR
616 +
    }
617 +
}
reve/src/renderer/mesh.rs added +310 -0
1 +
//! Mesh objects.
2 +
use std::f32::consts::PI;
3 +
use std::{io, mem};
4 +
5 +
use ombre::bytes::encoding::{Decode, Encode};
6 +
use ombre::derive::Packed;
7 +
use ombre::prelude::*;
8 +
9 +
/// File extension for XYZW meshes.
10 +
#[allow(dead_code)]
11 +
pub const FILE_EXTENSION: &str = "xyzw";
12 +
/// File header magic.
13 +
pub const MAGIC: [u8; 4] = [b'X', b'Y', b'Z', b'W'];
14 +
15 +
/// Mesh vertex.
16 +
#[derive(Debug, Clone, PartialEq, Packed)]
17 +
#[repr(C)]
18 +
pub struct Vertex {
19 +
    pub position: Vector3D<f32>,
20 +
    pub color: Rgba<f32>,
21 +
    pub normal: Vector3D<f32>,
22 +
    pub uv: Vector2D<f32>,
23 +
    pub opacity: f32,
24 +
    pub polygon: u32,
25 +
}
26 +
27 +
impl Vertex {
28 +
    /// Create a new vertex.
29 +
    pub const fn new(x: f32, y: f32, z: f32, nx: f32, ny: f32, nz: f32, u: f32, v: f32) -> Self {
30 +
        Self {
31 +
            position: Vector3D::new(x, y, z),
32 +
            color: Rgba::WHITE,
33 +
            normal: Vector3D::new(nx, ny, nz),
34 +
            uv: Vector2D::new(u, v),
35 +
            opacity: 1.0,
36 +
            polygon: 0,
37 +
        }
38 +
    }
39 +
40 +
    /// Stride used in buffer layout calculations.
41 +
    #[allow(dead_code)]
42 +
    pub fn stride() -> usize {
43 +
        mem::size_of::<Self>()
44 +
    }
45 +
}
46 +
47 +
impl Encode for Vertex {
48 +
    fn encode<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error> {
49 +
        let mut n = 0;
50 +
51 +
        n += self.position.encode(writer)?;
52 +
        n += self.color.encode(writer)?;
53 +
        n += self.normal.encode(writer)?;
54 +
        n += self.uv.encode(writer)?;
55 +
        n += self.opacity.encode(writer)?;
56 +
        n += self.polygon.encode(writer)?;
57 +
58 +
        Ok(n)
59 +
    }
60 +
}
61 +
62 +
impl Decode for Vertex {
63 +
    fn decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> {
64 +
        Ok(Self {
65 +
            position: Decode::decode(reader)?,
66 +
            color: Decode::decode(reader)?,
67 +
            normal: Decode::decode(reader)?,
68 +
            uv: Decode::decode(reader)?,
69 +
            opacity: Decode::decode(reader)?,
70 +
            polygon: Decode::decode(reader)?,
71 +
        })
72 +
    }
73 +
}
74 +
75 +
/// A mesh with vertices and optional indices.
76 +
///
77 +
/// When encoded, uses the following format:
78 +
///
79 +
/// .------------.
80 +
/// |  MAGIC     | "XYZW" (4 bytes)
81 +
/// +------------+
82 +
/// |  NVERTICES |        (4 bytes) (Big Endian) Number of vertices
83 +
/// +------------+
84 +
/// |  NINDICES  |        (4 bytes) (Big Endian) Number of indices
85 +
/// +------------+
86 +
/// |  VERTICES  |        (NVERTICES * N bytes) Vertex data
87 +
/// |  ....      |
88 +
/// +------------+
89 +
/// |  INDICES   |        (NINDICES * 4 bytes) Index data
90 +
/// |  ....      |
91 +
/// '------------'
92 +
///
93 +
#[derive(Debug, PartialEq)]
94 +
pub struct Mesh<I = u16> {
95 +
    /// Mesh vertices. Used as vertex buffer.
96 +
    pub vertices: Vec<Vertex>,
97 +
    /// Mesh indices. Used as index buffer.
98 +
    pub indices: Option<Vec<I>>,
99 +
}
100 +
101 +
impl Mesh<u16> {
102 +
    /// Create a "cube" mesh.
103 +
    pub fn cube(size: f32) -> Self {
104 +
        let s = size / 2.0;
105 +
        #[rustfmt::skip]
106 +
        let mut vertices = vec![
107 +
            // Front face.
108 +
            Vertex::new(-s, -s,  s,  0.0,  0.0,  1.0,  0.0,  0.0),
109 +
            Vertex::new( s, -s,  s,  0.0,  0.0,  1.0,  1.0,  0.0),
110 +
            Vertex::new( s,  s,  s,  0.0,  0.0,  1.0,  1.0,  1.0),
111 +
            Vertex::new(-s,  s,  s,  0.0,  0.0,  1.0,  0.0,  1.0),
112 +
113 +
            // Back face.
114 +
            Vertex::new(-s, -s, -s,  0.0,  0.0, -1.0,  1.0,  0.0),
115 +
            Vertex::new(-s,  s, -s,  0.0,  0.0, -1.0,  1.0,  1.0),
116 +
            Vertex::new( s,  s, -s,  0.0,  0.0, -1.0,  0.0,  1.0),
117 +
            Vertex::new( s, -s, -s,  0.0,  0.0, -1.0,  0.0,  0.0),
118 +
119 +
            // Left face.
120 +
            Vertex::new(-s, -s, -s, -1.0,  0.0,  0.0,  0.0,  0.0),
121 +
            Vertex::new(-s, -s,  s, -1.0,  0.0,  0.0,  1.0,  0.0),
122 +
            Vertex::new(-s,  s,  s, -1.0,  0.0,  0.0,  1.0,  1.0),
123 +
            Vertex::new(-s,  s, -s, -1.0,  0.0,  0.0,  0.0,  1.0),
124 +
125 +
            // Right face.
126 +
            Vertex::new( s, -s,  s,  1.0,  0.0,  0.0,  0.0,  0.0),
127 +
            Vertex::new( s, -s, -s,  1.0,  0.0,  0.0,  1.0,  0.0),
128 +
            Vertex::new( s,  s, -s,  1.0,  0.0,  0.0,  1.0,  1.0),
129 +
            Vertex::new( s,  s,  s,  1.0,  0.0,  0.0,  0.0,  1.0),
130 +
131 +
            // Top face.
132 +
            Vertex::new(-s,  s,  s,  0.0,  1.0,  0.0,  0.0,  0.0),
133 +
            Vertex::new(-s,  s, -s,  0.0,  1.0,  0.0,  0.0,  1.0),
134 +
            Vertex::new( s,  s, -s,  0.0,  1.0,  0.0,  1.0,  1.0),
135 +
            Vertex::new( s,  s,  s,  0.0,  1.0,  0.0,  1.0,  0.0),
136 +
137 +
            // Bottom face.
138 +
            Vertex::new(-s, -s, -s,  0.0, -1.0,  0.0,  1.0,  1.0),
139 +
            Vertex::new( s, -s, -s,  0.0, -1.0,  0.0,  0.0,  1.0),
140 +
            Vertex::new( s, -s,  s,  0.0, -1.0,  0.0,  0.0,  0.0),
141 +
            Vertex::new(-s, -s,  s,  0.0, -1.0,  0.0,  1.0,  0.0),
142 +
        ];
143 +
144 +
        // Assign polygon IDs, starting from `1`.
145 +
        for (i, quad) in vertices.chunks_exact_mut(4).enumerate() {
146 +
            for v in quad {
147 +
                v.polygon = i as u32 + 1;
148 +
            }
149 +
        }
150 +
151 +
        Mesh {
152 +
            vertices,
153 +
            #[rustfmt::skip]
154 +
            indices: Some(vec![
155 +
                0,  1,  2,  0,  2,  3,
156 +
                4,  5,  6,  4,  6,  7,
157 +
                8,  9,  10, 8,  10, 11,
158 +
                12, 13, 14, 12, 14, 15,
159 +
                16, 17, 18, 16, 18, 19,
160 +
                20, 21, 22, 20, 22, 23,
161 +
            ]),
162 +
        }
163 +
    }
164 +
165 +
    /// Create a "sphere" mesh.
166 +
    pub fn sphere(color: Rgba8, radius: f32, segments: usize, rings: usize) -> Self {
167 +
        let mut vertices = Vec::new();
168 +
        let mut indices = Vec::new();
169 +
170 +
        // Vertices.
171 +
        for i in 0..=rings {
172 +
            let phi = i as f32 / rings as f32 * PI;
173 +
            for j in 0..=segments {
174 +
                let theta = j as f32 / segments as f32 * 2. * PI;
175 +
                let position = Vector3D::new(
176 +
                    radius * phi.sin() * theta.cos(),
177 +
                    radius * phi.cos(),
178 +
                    radius * phi.sin() * theta.sin(),
179 +
                );
180 +
                vertices.push(Vertex {
181 +
                    position,
182 +
                    color: color.into(),
183 +
                    normal: position.normalize(),
184 +
                    uv: Vector2D::default(),
185 +
                    opacity: 1.,
186 +
                    polygon: 0, // TODO
187 +
                });
188 +
            }
189 +
        }
190 +
        // Indices.
191 +
        for i in 0..rings {
192 +
            for j in 0..segments {
193 +
                let first = (i * (segments + 1)) + j;
194 +
                let second = first + segments + 1;
195 +
196 +
                // Create the first triangle (upper)
197 +
                indices.push((first + 1) as u16);
198 +
                indices.push(second as u16);
199 +
                indices.push(first as u16);
200 +
201 +
                // Create the second triangle (lower)
202 +
                indices.push((first + 1) as u16);
203 +
                indices.push((second + 1) as u16);
204 +
                indices.push(second as u16);
205 +
            }
206 +
        }
207 +
208 +
        Mesh {
209 +
            vertices,
210 +
            indices: Some(indices),
211 +
        }
212 +
    }
213 +
214 +
    /// Number of elements to render for this mesh.
215 +
    pub fn elements(&self) -> usize {
216 +
        self.indices.as_ref().map(|i| i.len()).unwrap_or(self.vertices.len())
217 +
    }
218 +
}
219 +
220 +
impl<I: Encode> Encode for Mesh<I> {
221 +
    fn encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
222 +
        let mut n = 0;
223 +
224 +
        n += MAGIC.encode(w)?;
225 +
226 +
        let vertices = &self.vertices;
227 +
        let indices = &self.indices.as_deref().unwrap_or(&[]);
228 +
229 +
        assert!(vertices.len() <= u32::MAX as usize);
230 +
        assert!(indices.len() <= u32::MAX as usize);
231 +
232 +
        n += (vertices.len() as u32).encode(w)?;
233 +
        n += (indices.len() as u32).encode(w)?;
234 +
235 +
        for v in vertices {
236 +
            n += v.encode(w)?;
237 +
        }
238 +
        for i in indices.iter() {
239 +
            n += i.encode(w)?;
240 +
        }
241 +
        Ok(n)
242 +
    }
243 +
}
244 +
245 +
impl<I: Decode> Decode for Mesh<I> {
246 +
    fn decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> {
247 +
        let magic: [u8; 4] = Decode::decode(reader)?;
248 +
        if magic != MAGIC {
249 +
            return Err(io::ErrorKind::InvalidData.into());
250 +
        }
251 +
        let nvertices = u32::decode(reader)? as usize;
252 +
        let nindices = u32::decode(reader)? as usize;
253 +
254 +
        let mut vertices = Vec::with_capacity(nvertices);
255 +
        while vertices.len() < nvertices {
256 +
            let v = Vertex::decode(reader)?;
257 +
            vertices.push(v);
258 +
        }
259 +
260 +
        let mut indices = Vec::<I>::with_capacity(nindices);
261 +
        while indices.len() < nindices {
262 +
            let ix = I::decode(reader)?;
263 +
            indices.push(ix);
264 +
        }
265 +
266 +
        Ok(Self {
267 +
            vertices,
268 +
            indices: (!indices.is_empty()).then_some(indices),
269 +
        })
270 +
    }
271 +
}
272 +
273 +
impl<I: Decode> TryFrom<&[u8]> for Mesh<I> {
274 +
    type Error = io::Error;
275 +
276 +
    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
277 +
        let mut cursor = io::Cursor::new(bytes);
278 +
        let mesh = Mesh::<I>::decode(&mut cursor)?;
279 +
280 +
        Ok(mesh)
281 +
    }
282 +
}
283 +
284 +
#[cfg(test)]
285 +
mod tests {
286 +
    #![allow(clippy::unwrap_used)]
287 +
    use super::*;
288 +
289 +
    #[test]
290 +
    fn test_encode_sphere() {
291 +
        let sphere = Mesh::<u16>::sphere(Rgba8::GREEN, 32.0, 16, 32);
292 +
        let mut out = Vec::new();
293 +
294 +
        sphere.encode(&mut out).unwrap();
295 +
296 +
        let decoded = Mesh::<u16>::try_from(out.as_slice()).unwrap();
297 +
        assert_eq!(sphere, decoded);
298 +
    }
299 +
300 +
    #[test]
301 +
    fn test_encode_cube() {
302 +
        let cube = Mesh::<u16>::cube(16.0);
303 +
        let mut out = Vec::new();
304 +
305 +
        cube.encode(&mut out).unwrap();
306 +
307 +
        let decoded = Mesh::<u16>::try_from(out.as_slice()).unwrap();
308 +
        assert_eq!(cube, decoded);
309 +
    }
310 +
}
reve/src/renderer/scene.rs added +154 -0
1 +
use std::collections::VecDeque;
2 +
use std::sync::atomic::{AtomicU32, Ordering};
3 +
4 +
use super::*;
5 +
6 +
use ombre::collections::{IntMap, IntSet};
7 +
8 +
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
9 +
pub struct NodeId(u32);
10 +
11 +
impl NodeId {
12 +
    /// Get the next unique identifier.
13 +
    fn next() -> Self {
14 +
        static NEXT: AtomicU32 = AtomicU32::new(1);
15 +
        NodeId(NEXT.fetch_add(1, Ordering::SeqCst))
16 +
    }
17 +
18 +
    pub(super) fn new(n: u32) -> Option<Self> {
19 +
        if n > 0 {
20 +
            Some(Self(n))
21 +
        } else {
22 +
            None
23 +
        }
24 +
    }
25 +
}
26 +
27 +
impl From<NodeId> for u32 {
28 +
    fn from(value: NodeId) -> Self {
29 +
        value.0
30 +
    }
31 +
}
32 +
33 +
#[derive(Debug, Default)]
34 +
pub enum Object {
35 +
    #[default]
36 +
    Null,
37 +
    Mesh {
38 +
        bindings: Bindings<2, 2>,
39 +
        selection: Vec<Flag>,
40 +
        vertices: Vec<Vertex>,
41 +
        elements: usize,
42 +
        style: RenderStyle,
43 +
        mode: InteractionMode,
44 +
    },
45 +
    #[allow(dead_code)]
46 +
    Light,
47 +
}
48 +
49 +
#[derive(Debug)]
50 +
pub struct Node {
51 +
    pub id: NodeId,
52 +
    pub object: Object,
53 +
    #[allow(dead_code)]
54 +
    pub transform: Transform3D<f32, Local, World>,
55 +
    pub children: IntSet<NodeId>,
56 +
}
57 +
58 +
impl Node {
59 +
    pub fn new(object: Object) -> Self {
60 +
        Self {
61 +
            id: NodeId::next(),
62 +
            object,
63 +
            transform: Transform3D::default(),
64 +
            children: IntSet::default(),
65 +
        }
66 +
    }
67 +
}
68 +
69 +
/// Scene graph.
70 +
#[derive(Debug)]
71 +
pub struct Graph {
72 +
    root: NodeId,
73 +
    nodes: IntMap<NodeId, Node>,
74 +
}
75 +
76 +
impl Default for Graph {
77 +
    fn default() -> Self {
78 +
        Self::new(Node::new(Object::Null))
79 +
    }
80 +
}
81 +
82 +
impl Graph {
83 +
    pub fn new(root: Node) -> Self {
84 +
        Self {
85 +
            root: root.id,
86 +
            nodes: IntMap::from_iter([(root.id, root)]),
87 +
        }
88 +
    }
89 +
90 +
    pub fn get(&self, id: &NodeId) -> Option<&Node> {
91 +
        self.nodes.get(id)
92 +
    }
93 +
94 +
    pub fn root(&self) -> &Node {
95 +
        &self.nodes[&self.root]
96 +
    }
97 +
98 +
    pub fn insert(&mut self, node: Node, parent: NodeId) -> bool {
99 +
        if let Some(parent) = self.nodes.get_mut(&parent) {
100 +
            parent.children.insert(node.id);
101 +
            self.nodes.insert(node.id, node);
102 +
103 +
            return true;
104 +
        }
105 +
        false
106 +
    }
107 +
108 +
    pub fn get_mut(&mut self, id: &NodeId) -> Option<&mut Node> {
109 +
        self.nodes.get_mut(id)
110 +
    }
111 +
112 +
    #[allow(dead_code)]
113 +
    pub fn remove(&mut self, id: NodeId) -> Option<Node> {
114 +
        if let Some(node) = self.nodes.remove(&id) {
115 +
            for child in node.children.iter().copied() {
116 +
                self.remove(child);
117 +
            }
118 +
            for node in self.nodes.values_mut() {
119 +
                node.children.remove(&id);
120 +
            }
121 +
            return Some(node);
122 +
        }
123 +
        None
124 +
    }
125 +
126 +
    pub fn iter(&self) -> Iter<'_> {
127 +
        Iter {
128 +
            graph: self,
129 +
            queue: VecDeque::from(vec![self.root]),
130 +
        }
131 +
    }
132 +
}
133 +
134 +
/// Graph iterator.
135 +
pub struct Iter<'a> {
136 +
    graph: &'a Graph,
137 +
    queue: VecDeque<NodeId>,
138 +
}
139 +
140 +
impl<'a> Iterator for Iter<'a> {
141 +
    type Item = &'a Node;
142 +
143 +
    fn next(&mut self) -> Option<Self::Item> {
144 +
        self.queue.pop_front().and_then(|id| {
145 +
            if let Some(node) = self.graph.get(&id) {
146 +
                for child_id in &node.children {
147 +
                    self.queue.push_back(*child_id);
148 +
                }
149 +
                return Some(node);
150 +
            }
151 +
            None
152 +
        })
153 +
    }
154 +
}
reve/src/renderer/shaders.rs added +179 -0
1 +
use ombre::prelude::*;
2 +
3 +
// Display shader, for rendering a backbuffer to the frontbuffer.
4 +
pub mod display {
5 +
    use super::*;
6 +
7 +
    // No uniforms used.
8 +
    pub type Uniforms = ();
9 +
10 +
    pub const fn source() -> gfx::ShaderSource<'static> {
11 +
        gfx::ShaderSource {
12 +
            vertex: include_str!("shaders/display/vertex.glsl"),
13 +
            fragment: include_str!("shaders/display/fragment.glsl"),
14 +
            geometry: None,
15 +
        }
16 +
    }
17 +
18 +
    pub const fn description() -> gfx::ShaderDescriptor<'static> {
19 +
        gfx::ShaderDescriptor {
20 +
            textures: &["backbuffer"],
21 +
            uniforms: gfx::UniformBlockLayout { uniforms: &[] },
22 +
        }
23 +
    }
24 +
}
25 +
26 +
/// Constant shader, for gizmos and other UI components.
27 +
#[allow(dead_code)]
28 +
pub mod constant {
29 +
    use super::*;
30 +
31 +
    #[repr(C)]
32 +
    pub struct Uniforms {
33 +
        pub model: Transform3D<f32>,
34 +
        pub view: Transform3D<f32, World>,
35 +
        pub proj: Transform3D<f32, World, Screen>,
36 +
    }
37 +
    unsafe impl bytes::Packed for Uniforms {}
38 +
39 +
    pub const fn source() -> gfx::ShaderSource<'static> {
40 +
        gfx::ShaderSource {
41 +
            vertex: include_str!("shaders/mvp/vertex.glsl"),
42 +
            fragment: include_str!("shaders/constant/fragment.glsl"),
43 +
            geometry: None,
44 +
        }
45 +
    }
46 +
47 +
    pub const fn attributes() -> [gfx::VertexAttribute; 2] {
48 +
        [
49 +
            gfx::VertexAttribute::new("position", gfx::VertexFormat::Float3),
50 +
            gfx::VertexAttribute::new("color", gfx::VertexFormat::Float4),
51 +
        ]
52 +
    }
53 +
54 +
    pub const fn description() -> gfx::ShaderDescriptor<'static> {
55 +
        gfx::ShaderDescriptor {
56 +
            textures: &[],
57 +
            uniforms: gfx::UniformBlockLayout {
58 +
                uniforms: &[
59 +
                    gfx::UniformDescriptor {
60 +
                        name: "model",
61 +
                        kind: gfx::UniformKind::Mat4,
62 +
                        arity: 1,
63 +
                    },
64 +
                    gfx::UniformDescriptor {
65 +
                        name: "view",
66 +
                        kind: gfx::UniformKind::Mat4,
67 +
                        arity: 1,
68 +
                    },
69 +
                    gfx::UniformDescriptor {
70 +
                        name: "proj",
71 +
                        kind: gfx::UniformKind::Mat4,
72 +
                        arity: 1,
73 +
                    },
74 +
                ],
75 +
            },
76 +
        }
77 +
    }
78 +
}
79 +
80 +
/// The default shader.
81 +
/// This is a Blinn/Cook-Torance shader with some additional capabilities.
82 +
pub mod default {
83 +
    use super::*;
84 +
85 +
    #[repr(C)]
86 +
    pub struct Uniforms {
87 +
        pub model: Transform3D,
88 +
        pub view: Transform3D<f32, World>,
89 +
        pub proj: Transform3D<f32, World, Screen>,
90 +
        pub light: Vector3D,
91 +
        pub window_size: Size<f32>,
92 +
        pub enable_tomemap: u32,
93 +
        pub render_mode: u32,
94 +
        pub interaction_mode: u32,
95 +
        pub object_id: u32,
96 +
        pub vertex_hovered: i32,
97 +
    }
98 +
    unsafe impl bytes::Packed for Uniforms {}
99 +
100 +
    pub const fn source() -> gfx::ShaderSource<'static> {
101 +
        gfx::ShaderSource {
102 +
            vertex: include_str!("shaders/blinn/vertex.glsl"),
103 +
            fragment: include_str!("shaders/blinn/fragment.glsl"),
104 +
            geometry: Some(include_str!("shaders/blinn/geometry.glsl")),
105 +
        }
106 +
    }
107 +
108 +
    pub const fn attributes() -> [gfx::VertexAttribute; 7] {
109 +
        [
110 +
            gfx::VertexAttribute::new("position", gfx::VertexFormat::Float3),
111 +
            gfx::VertexAttribute::new("color", gfx::VertexFormat::Float4),
112 +
            gfx::VertexAttribute::new("normal", gfx::VertexFormat::Float3),
113 +
            gfx::VertexAttribute::new("uv", gfx::VertexFormat::Float2),
114 +
            gfx::VertexAttribute::new("opacity", gfx::VertexFormat::Float1),
115 +
            gfx::VertexAttribute::new("polygon", gfx::VertexFormat::Int1),
116 +
            gfx::VertexAttribute::new("selected", gfx::VertexFormat::Float1),
117 +
        ]
118 +
    }
119 +
120 +
    pub const fn description() -> gfx::ShaderDescriptor<'static> {
121 +
        gfx::ShaderDescriptor {
122 +
            textures: &["diffuseSampler", "specularSampler"],
123 +
            uniforms: gfx::UniformBlockLayout {
124 +
                uniforms: &[
125 +
                    gfx::UniformDescriptor {
126 +
                        name: "model",
127 +
                        kind: gfx::UniformKind::Mat4,
128 +
                        arity: 1,
129 +
                    },
130 +
                    gfx::UniformDescriptor {
131 +
                        name: "view",
132 +
                        kind: gfx::UniformKind::Mat4,
133 +
                        arity: 1,
134 +
                    },
135 +
                    gfx::UniformDescriptor {
136 +
                        name: "proj",
137 +
                        kind: gfx::UniformKind::Mat4,
138 +
                        arity: 1,
139 +
                    },
140 +
                    gfx::UniformDescriptor {
141 +
                        name: "light",
142 +
                        kind: gfx::UniformKind::Float3,
143 +
                        arity: 1,
144 +
                    },
145 +
                    gfx::UniformDescriptor {
146 +
                        name: "windowSize",
147 +
                        kind: gfx::UniformKind::Float2,
148 +
                        arity: 1,
149 +
                    },
150 +
                    gfx::UniformDescriptor {
151 +
                        name: "enableTonemap",
152 +
                        kind: gfx::UniformKind::UInt1,
153 +
                        arity: 1,
154 +
                    },
155 +
                    gfx::UniformDescriptor {
156 +
                        name: "renderMode",
157 +
                        kind: gfx::UniformKind::UInt1,
158 +
                        arity: 1,
159 +
                    },
160 +
                    gfx::UniformDescriptor {
161 +
                        name: "interactionMode",
162 +
                        kind: gfx::UniformKind::UInt1,
163 +
                        arity: 1,
164 +
                    },
165 +
                    gfx::UniformDescriptor {
166 +
                        name: "objectId",
167 +
                        kind: gfx::UniformKind::UInt1,
168 +
                        arity: 1,
169 +
                    },
170 +
                    gfx::UniformDescriptor {
171 +
                        name: "vertexHovered",
172 +
                        kind: gfx::UniformKind::Int1,
173 +
                        arity: 1,
174 +
                    },
175 +
                ],
176 +
            },
177 +
        }
178 +
    }
179 +
}
reve/src/renderer/shaders/blinn/fragment.glsl added +202 -0
1 +
// TODO: When tonemapping is enabled, the diffuse channel needs to be brightened.
2 +
#version 330 core
3 +
4 +
const uint InteractionModeObjects  = 0u;
5 +
const uint InteractionModeEdges    = 1u;
6 +
const uint InteractionModePoints   = 2u;
7 +
const uint InteractionModePolygons = 3u;
8 +
9 +
// Render diffuse color.
10 +
const uint RenderDiffuse = 1u;
11 +
// Flat shading.
12 +
const uint RenderFlatShaded = 1u << 1;
13 +
// Show specular highlights.
14 +
const uint RenderSpecular = 1u << 2;
15 +
// Show textures.
16 +
const uint RenderTexture = 1u << 3;
17 +
// Render wireframes.
18 +
const uint RenderWireframe = 1u << 4;
19 +
20 +
const uint VertexStyleDefault  = 1u << 0;
21 +
const uint VertexStyleConstant = 1u << 1;
22 +
23 +
const float PI = 3.1415926535897932384626433832795;
24 +
25 +
// Parameters for selection pattern.
26 +
const float SelectionGridSpacing = 3.0; // Controls the size of the grid cells
27 +
const float SelectionDotRadius = 1.0; // Controls the size of the dots, relative to the grid size
28 +
29 +
smooth        in vec3  fragPosWorld;
30 +
smooth        in vec2  textureCoord;
31 +
smooth        in vec3  viewDirWorld;
32 +
smooth        in vec4  vertexColor;
33 +
smooth        in float vertexOpacity;
34 +
smooth        in vec3  vertexNormalSmooth;
35 +
flat          in int   vertexObjectId;
36 +
flat          in float vertexSelected;
37 +
flat          in float vertexHovered;
38 +
flat          in vec3  vertexNormalFlat;
39 +
flat          in uint  vertexStyle;
40 +
noperspective in vec3  vertexDist;
41 +
42 +
layout(location = 0) out vec4 fragColor;
43 +
layout(location = 1) out uint objectIdOutput;
44 +
45 +
uniform bool      enableTonemap;
46 +
uniform uint      renderMode;
47 +
uniform vec3      light;
48 +
uniform sampler2D diffuseSampler;
49 +
uniform sampler2D specularSampler;
50 +
uniform uint      interactionMode;
51 +
52 +
struct lightState {
53 +
	vec4 intensity;
54 +
	vec4 ambience;
55 +
	float attenuation;
56 +
	float incidence;
57 +
};
58 +
59 +
vec4 tonemap(in vec4 color) {
60 +
	const float A = 0.22; // Shoulder strength
61 +
	const float B = 0.30; // Linear Strength
62 +
	const float C = 0.10; // Linear Angle
63 +
	const float D = 0.20; // Toe Strength
64 +
	const float E = 0.01; // Toe Numerator
65 +
	const float F = 0.30; // Toe Denominator
66 +
67 +
	return ((color * (A * color + C * B) + D * E) / (color * (A * color + B) + D * F)) - E/F;
68 +
}
69 +
70 +
vec4 computeFragColor(in vec4 diffuse, in vec4 specular, in float blinnTerm, in lightState l) {
71 +
	float W = 11.2; // Whitepoint
72 +
73 +
	vec4 color = (diffuse * l.intensity * l.incidence * l.attenuation)  +
74 +
		   		 (specular * l.attenuation * blinnTerm) +
75 +
		   		 (diffuse * l.ambience);
76 +
77 +
	float exposure = 1.0f;
78 +
79 +
	if (enableTonemap) {
80 +
		return tonemap(exposure * color) / tonemap(vec4(W));
81 +
	} else {
82 +
		return color;
83 +
	}
84 +
}
85 +
86 +
float cookTorrance(in float roughness, in vec3 halfAngle, in vec3 normal, in vec3 viewDir, in vec3 lightDir) {
87 +
	float F0 = 0.8; // Reflectance at normal incidence
88 +
	float m2 = roughness * roughness;
89 +
90 +
	float NdotH = dot(normal, halfAngle);
91 +
	float NdotV = dot(normal, viewDir);
92 +
	float NdotL = dot(normal, lightDir);
93 +
	float VdotH = dot(viewDir, halfAngle);
94 +
95 +
	// Beckman's distribution function D
96 +
	float x = (NdotH * NdotH - 1.0) / (NdotH * NdotH * m2);
97 +
	float D = exp(x) / (4.0 * m2 * pow(NdotH, 4));
98 +
99 +
	// Fresnel term F
100 +
	float F = pow(1.0 - NdotV, 5.0);
101 +
	F *= (1.0 - F0);
102 +
	F += F0;
103 +
104 +
	// Self-shadowing term G
105 +
	float X = 2.0 * NdotH / VdotH;
106 +
	float G = min(1.0, min(X * NdotL, X * NdotV));
107 +
108 +
	return (D * F * G) / (NdotV * PI);
109 +
}
110 +
111 +
float gaussian(in float roughness, in vec3 halfAngle, in vec3 normal) {
112 +
	float angleNormalHalf = acos(dot(halfAngle, normal));
113 +
	float exponent = angleNormalHalf / roughness;
114 +
	exponent = -(exponent * exponent);
115 +
116 +
	return exp(exponent);
117 +
}
118 +
119 +
float blinn(in float roughness, in vec3 halfAngle, in vec3 normal) {
120 +
	float blinnTerm = clamp(dot(normal, halfAngle), 0, 1);
121 +
	blinnTerm = pow(blinnTerm, roughness);
122 +
123 +
	return blinnTerm;
124 +
}
125 +
126 +
void main() {
127 +
	lightState l;
128 +
129 +
	if (vertexStyle == VertexStyleConstant) {
130 +
		objectIdOutput = uint(vertexObjectId) + 1u; // Vertex IDs start from `1`, as the zero value is reserved for no selection.
131 +
		fragColor = vertexSelected >= 1.0 ? vec4(1.0, 0.0, 0.0, 1.0) : vertexColor;
132 +
		return;
133 +
	}
134 +
135 +
	// TODO: Intensity should be a uniform.
136 +
	l.intensity = vec4(1.0, 1.0, 0.9, 0.0) * 30;
137 +
	l.ambience = vec4(0.05, 0.05, 0.08, 0.0);
138 +
139 +
	const float roughness = 0.3;
140 +
	const float specularIntensity = 15.0;
141 +
142 +
	vec4 diffuse = bool(renderMode & RenderDiffuse)
143 +
		? vertexColor
144 +
		: vec4(0.0);
145 +
146 +
	vec3 vertexNormal = bool(renderMode & RenderFlatShaded)
147 +
		? vertexNormalFlat
148 +
		: vertexNormalSmooth;
149 +
150 +
	vec4 specular = bool(renderMode & RenderSpecular)
151 +
		? vec4(texture(specularSampler, textureCoord).rgb * specularIntensity, 1.0)
152 +
		: vec4(0.0);
153 +
154 +
	if (bool(renderMode & RenderTexture)) {
155 +
		vec2 uv = vec2(textureCoord.s, 1.0 - textureCoord.t);
156 +
		vec4 texel = texture(diffuseSampler, uv);
157 +
		vec4 textured = vec4(mix(texel.rgb, vertexColor.rgb, vertexColor.a), texel.a);
158 +
159 +
		diffuse = textured;
160 +
	}
161 +
162 +
	float lightDistance = length(light - fragPosWorld);
163 +
	vec3 lightDirWorld = normalize(light - fragPosWorld);
164 +
165 +
	l.attenuation = 1.0 / (1.0 + lightDistance * lightDistance);
166 +
	l.incidence = clamp(dot(lightDirWorld, vertexNormal), 0, 1);
167 +
168 +
	vec3 halfAngle = normalize(lightDirWorld + viewDirWorld);
169 +
	float specTerm = cookTorrance(roughness, halfAngle, vertexNormal, viewDirWorld, lightDirWorld);
170 +
171 +
	if (l.incidence == 0.0) {
172 +
		specTerm = 0.0;
173 +
	}
174 +
	vec4 outputColor = computeFragColor(diffuse, specular, specTerm, l);
175 +
176 +
	// Polygon selections.
177 +
	if (interactionMode == InteractionModePolygons) {
178 +
		if (bool(vertexSelected)) {
179 +
			vec2 gridPosition = mod(gl_FragCoord.xy, SelectionGridSpacing);
180 +
			vec2 fromCenter = abs(gridPosition - SelectionGridSpacing * 0.5); // Distance of each fragment from the center of the grid cell
181 +
			float isDot = step(length(fromCenter), SelectionDotRadius); // Check if the fragment is within the dot radius
182 +
183 +
			if (isDot >= 1.0) {
184 +
				outputColor = vec4(1.0, 0.0, 0.0, 1.0);
185 +
			}
186 +
		}
187 +
		if (bool(vertexHovered)) {
188 +
			outputColor = mix(outputColor, vec4(1.0, 0.0, 0.0, 1.0), 0.25);
189 +
		}
190 +
	}
191 +
	// Wireframe overlay.
192 +
	if (bool(renderMode & RenderWireframe)) {
193 +
		float minDistance = min(vertexDist.x, min(vertexDist.y, vertexDist.z));
194 +
		float wireWidth = 1.0;
195 +
		vec4 wireColor = mix(vec4(1.0), outputColor, 0.33);
196 +
		float wireAlpha = smoothstep(wireWidth, 2.0 * wireWidth, minDistance);
197 +
198 +
		outputColor = mix(wireColor, outputColor, wireAlpha);
199 +
	}
200 +
	objectIdOutput = uint(vertexObjectId);
201 +
	fragColor = vec4(outputColor.rgb, vertexOpacity);
202 +
}
reve/src/renderer/shaders/blinn/geometry.glsl added +180 -0
1 +
#version 330 core
2 +
3 +
const uint InteractionModeObjects  = 0u;
4 +
const uint InteractionModeEdges    = 1u;
5 +
const uint InteractionModePoints   = 2u;
6 +
const uint InteractionModePolygons = 3u;
7 +
8 +
const uint VertexStyleDefault  = 1u << 0;
9 +
const uint VertexStyleConstant = 1u << 1;
10 +
11 +
layout(triangles)                         in;
12 +
layout(triangle_strip, max_vertices = 15) out;
13 +
14 +
smooth        in  vec3  vertViewDirWorld[];
15 +
smooth        in  vec3  vertPosWorld[];
16 +
smooth        in  vec3  vertNormalSmooth[];
17 +
flat          in  vec3  vertNormalFlat[];
18 +
flat          in  float vertSelected[];
19 +
flat          in  float vertHovered[];
20 +
flat          in  int   vertID[];
21 +
flat          in  uint  vertDecorate[];
22 +
smooth        in  float vertExcludeEdge[];
23 +
smooth        in  vec4  vertColor[];
24 +
smooth        in  float vertOpacity[];
25 +
smooth        in  vec2  vertTextureCoord[];
26 +
27 +
smooth        out vec3  fragPosWorld;
28 +
smooth        out vec2  textureCoord;
29 +
smooth        out vec3  viewDirWorld;
30 +
smooth        out vec4  vertexColor;
31 +
smooth        out float vertexOpacity;
32 +
smooth        out vec3  vertexNormalSmooth;
33 +
flat          out int   vertexObjectId;
34 +
flat          out uint  vertexStyle;
35 +
flat          out float vertexSelected;
36 +
flat          out float vertexHovered;
37 +
flat          out vec3  vertexNormalFlat;
38 +
noperspective out vec3  vertexDist;
39 +
40 +
uniform mat4 model;
41 +
uniform mat4 view;
42 +
uniform mat4 proj;
43 +
uniform vec2 windowSize; // Window sizea for screen-space calculations.
44 +
uniform uint renderMode;
45 +
uniform uint interactionMode;
46 +
uniform uint objectId;
47 +
48 +
int vertexId(int i) {
49 +
	if (interactionMode == InteractionModeObjects) {
50 +
		return int(objectId);
51 +
	}
52 +
	return vertID[i];
53 +
}
54 +
55 +
float isVertexSelected() {
56 +
	for (int i = 0; i < gl_in.length(); ++i) {
57 +
		if (vertSelected[i] < 1.0) {
58 +
			return 0.0;
59 +
		}
60 +
	}
61 +
	return 1.0;
62 +
}
63 +
64 +
float isVertexHovered() {
65 +
	if (interactionMode == InteractionModePolygons) {
66 +
		for (int i = 0; i < gl_in.length(); ++i) {
67 +
			if (vertHovered[i] < 1.0) {
68 +
				return 0.0;
69 +
			}
70 +
		}
71 +
		return 1.0;
72 +
	}
73 +
	return 0.0;
74 +
}
75 +
76 +
void emitVertex(int i, vec3 dist) {
77 +
    fragPosWorld = vertPosWorld[i];
78 +
    viewDirWorld = vertViewDirWorld[i];
79 +
    textureCoord = vertTextureCoord[i];
80 +
    vertexNormalSmooth = vertNormalSmooth[i];
81 +
    vertexNormalFlat = vertNormalFlat[i];
82 +
    vertexColor = vertColor[i];
83 +
    vertexOpacity = vertOpacity[i];
84 +
	vertexStyle = VertexStyleDefault;
85 +
	vertexSelected = isVertexSelected();
86 +
	vertexHovered = isVertexHovered();
87 +
	vertexObjectId = vertexId(i);
88 +
	vertexDist = dist;
89 +
    gl_Position = gl_in[i].gl_Position;
90 +
91 +
    EmitVertex();
92 +
}
93 +
94 +
// Emit vertices for a screen-aligned quad.
95 +
void emitVertexDecoration(int i) {
96 +
    // Perform perspective division to get to NDC.
97 +
	vec4 clipSpacePosition = gl_in[i].gl_Position;
98 +
    vec3 ndc = clipSpacePosition.xyz / clipSpacePosition.w;
99 +
100 +
	float squareNDCSize = 10.0;
101 +
102 +
    // Calculate the size of the billboard in NDC
103 +
    vec2 halfSize = vec2(
104 +
		squareNDCSize / windowSize.x,
105 +
		squareNDCSize / windowSize.y
106 +
	);
107 +
	float depthOffset = 0.0001 * gl_in[i].gl_Position.w;
108 +
109 +
	vec2 offsets[4] = vec2[4](
110 +
		vec2(-halfSize.x, -halfSize.y),
111 +
		vec2( halfSize.x, -halfSize.y),
112 +
		vec2(-halfSize.x,  halfSize.y),
113 +
		vec2( halfSize.x,  halfSize.y)
114 +
	);
115 +
	for (int j = 0; j < 4; j++) {
116 +
		vertexColor = vec4(0.0, 0.0, 1.0, 1.0);
117 +
		vertexStyle = VertexStyleConstant;
118 +
		vertexObjectId = vertID[i];
119 +
		vertexSelected = vertSelected[i];
120 +
		vertexHovered = -1;
121 +
		gl_Position = vec4(ndc.xy + offsets[j], ndc.z - depthOffset, 1.0);
122 +
		EmitVertex();
123 +
	}
124 +
    EndPrimitive();
125 +
}
126 +
127 +
vec2 screenSpaceCoord(int ix) {
128 +
    return windowSize * gl_in[ix].gl_Position.xy / gl_in[ix].gl_Position.w;
129 +
}
130 +
131 +
void main() {
132 +
	const float maxEdgeWidth = 100.0;
133 +
134 +
	// Screen-space coordinates of vertices.
135 +
    vec2 p0 = screenSpaceCoord(0);
136 +
    vec2 p1 = screenSpaceCoord(1);
137 +
    vec2 p2 = screenSpaceCoord(2);
138 +
139 +
	// Screen-space edge vectors.
140 +
    vec2 v0 = p2 - p1;
141 +
    vec2 v1 = p2 - p0;
142 +
    vec2 v2 = p1 - p0;
143 +
    float area = abs(v1.x * v2.y - v1.y * v2.x);
144 +
145 +
	vec3 distances[3] = vec3[3](
146 +
		vec3(
147 +
			area / length(v0),
148 +
			vertExcludeEdge[1] * maxEdgeWidth,
149 +
			vertExcludeEdge[2] * maxEdgeWidth
150 +
		),
151 +
		vec3(
152 +
			vertExcludeEdge[0] * maxEdgeWidth,
153 +
			area / length(v1),
154 +
			vertExcludeEdge[2] * maxEdgeWidth
155 +
		),
156 +
		vec3(
157 +
			vertExcludeEdge[0] * maxEdgeWidth,
158 +
			vertExcludeEdge[1] * maxEdgeWidth,
159 +
			area / length(v2)
160 +
		)
161 +
	);
162 +
163 +
	// Emit the input vertices with additional distance information, for
164 +
	// rendering wireframes in the fragment shader.
165 +
    for (int i = 0; i < gl_in.length(); ++i) {
166 +
		emitVertex(i, distances[i]);
167 +
    }
168 +
    EndPrimitive();
169 +
170 +
	// Emit squares at each vertex of the triangle, in screen space.
171 +
	if (interactionMode == InteractionModePoints) {
172 +
		for (int i = 0; i < gl_in.length(); ++i) {
173 +
			// Don't render decorations for vertices that aren't facing the camera.
174 +
			if (dot(vertNormalSmooth[i], vertViewDirWorld[i]) > 0) {
175 +
				emitVertexDecoration(i);
176 +
			}
177 +
		}
178 +
	}
179 +
}
180 +
reve/src/renderer/shaders/blinn/vertex.glsl added +66 -0
1 +
#version 330 core
2 +
3 +
const uint InteractionModeObjects  = 0u;
4 +
const uint InteractionModeEdges    = 1u;
5 +
const uint InteractionModePoints   = 2u;
6 +
const uint InteractionModePolygons = 3u;
7 +
8 +
layout(location = 0) in vec3  position;
9 +
layout(location = 1) in vec4  color;
10 +
layout(location = 2) in vec3  normal;
11 +
layout(location = 3) in vec2  uv;
12 +
layout(location = 4) in float opacity;
13 +
layout(location = 5) in uint  polygon;
14 +
layout(location = 6) in float selected; // `0` or `1`.
15 +
16 +
smooth out vec3  vertViewDirWorld;
17 +
smooth out vec3  vertPosWorld;
18 +
smooth out vec4  vertColor;
19 +
smooth out float vertOpacity;
20 +
smooth out float vertExcludeEdge;
21 +
smooth out vec3  vertNormalSmooth;
22 +
flat   out vec3  vertNormalFlat;
23 +
flat   out int   vertID;
24 +
flat   out float vertSelected;
25 +
flat   out float vertHovered;
26 +
smooth out vec2  vertTextureCoord;
27 +
28 +
uniform vec3 light;
29 +
uniform mat4 model;
30 +
uniform mat4 view;
31 +
uniform mat4 proj;
32 +
uniform uint interactionMode;
33 +
uniform int  vertexHovered;
34 +
35 +
int getVertexID() {
36 +
	if (interactionMode == InteractionModePoints) {
37 +
		return gl_VertexID;
38 +
	}
39 +
	if (interactionMode == InteractionModePolygons) {
40 +
		return int(polygon);
41 +
	}
42 +
	return -1;
43 +
}
44 +
45 +
float isVertexHovered() {
46 +
	return vertexHovered == getVertexID() ? 1.0 : 0.0;
47 +
}
48 +
49 +
void main() {
50 +
	vec3 cameraPosWorld = vec3(inverse(view) * vec4(0.0, 0.0, 0.0, 1.0));
51 +
	vec3 normalWorld = normalize(mat3(model) * normal);
52 +
53 +
	vertPosWorld = vec3(model * vec4(position, 1));
54 +
	vertViewDirWorld = normalize(cameraPosWorld - vertPosWorld);
55 +
	vertNormalFlat = normalWorld;
56 +
	vertNormalSmooth = normalWorld;
57 +
	vertColor = color;
58 +
	vertOpacity = opacity;
59 +
	vertTextureCoord = uv;
60 +
	vertExcludeEdge = 0.0;
61 +
	vertID = getVertexID();
62 +
	vertSelected = selected;
63 +
	vertHovered = isVertexHovered();
64 +
65 +
	gl_Position = proj * view * model * vec4(position, 1);
66 +
}
reve/src/renderer/shaders/constant/fragment.glsl added +8 -0
1 +
#version 330 core
2 +
3 +
in vec4 vertexColor;
4 +
out vec4 fragColor;
5 +
6 +
void main() {
7 +
	fragColor = vertexColor;
8 +
}
reve/src/renderer/shaders/display/fragment.glsl added +13 -0
1 +
#version 330 core
2 +
3 +
uniform sampler2D backbuffer;
4 +
5 +
in  vec2 vertUV;
6 +
out vec4 fragColor;
7 +
8 +
void main() {
9 +
	fragColor = texture(
10 +
		backbuffer,
11 +
		vec2(vertUV.s, 1.0 - vertUV.t)
12 +
	);
13 +
}
reve/src/renderer/shaders/display/vertex.glsl added +26 -0
1 +
#version 330 core
2 +
3 +
const vec2[6] POSITION = vec2[](
4 +
	vec2(-1.0, -1.0),
5 +
	vec2( 1.0, -1.0),
6 +
	vec2( 1.0,  1.0),
7 +
	vec2(-1.0, -1.0),
8 +
	vec2(-1.0,  1.0),
9 +
	vec2( 1.0,  1.0)
10 +
);
11 +
12 +
const vec2[6] UV = vec2[](
13 +
	vec2(0.0, 0.0),
14 +
	vec2(1.0, 0.0),
15 +
	vec2(1.0, 1.0),
16 +
	vec2(0.0, 0.0),
17 +
	vec2(0.0, 1.0),
18 +
	vec2(1.0, 1.0)
19 +
);
20 +
21 +
out vec2 vertUV;
22 +
23 +
void main() {
24 +
	vertUV = UV[gl_VertexID];
25 +
	gl_Position = vec4(POSITION[gl_VertexID], 0.0, 1.0);
26 +
}
reve/src/renderer/shaders/mvp/vertex.glsl added +15 -0
1 +
#version 330 core
2 +
3 +
in vec3 position;
4 +
in vec4 color;
5 +
6 +
out vec4 vertexColor;
7 +
8 +
uniform mat4 model;
9 +
uniform mat4 view;
10 +
uniform mat4 proj;
11 +
12 +
void main() {
13 +
	vertexColor = color;
14 +
	gl_Position = proj * view * model * vec4(position, 1.0);
15 +
}
rust-toolchain.toml added +4 -0
1 +
[toolchain]
2 +
channel = "1.83"
3 +
profile = "default"
4 +
components = ["rust-src"]
rustfmt.toml added +2 -0
1 +
# Max width of a function call chain.
2 +
chain_width = 70
syntaxe/.gitignore added +2 -0
1 +
/target
2 +
Cargo.lock
syntaxe/Cargo.toml added +18 -0
1 +
[package]
2 +
name = "syntaxe"
3 +
description = "Simple, declarative parser combinators"
4 +
documentation = "https://docs.rs/syntaxe"
5 +
version = "0.1.0"
6 +
edition = "2021"
7 +
authors = ["cloudhead <self@cloudhead.io>"]
8 +
license = "MIT"
9 +
10 +
[lints]
11 +
workspace = true
12 +
13 +
[dev-dependencies]
14 +
ombre = { version = "*", path = "../ombre" }
15 +
16 +
[[bench]]
17 +
name = "json"
18 +
harness = false
syntaxe/README.md added +3 -0
1 +
# syntaxe
2 +
3 +
A simple, declarative parser-combinator library.
syntaxe/benches/json.rs added +89 -0
1 +
#![allow(clippy::unwrap_used)]
2 +
use std::collections::HashMap;
3 +
4 +
use syntaxe::*;
5 +
6 +
#[derive(Debug, PartialEq)]
7 +
enum Json {
8 +
    Null,
9 +
    Bool(bool),
10 +
    Number(f64),
11 +
    Str(String),
12 +
    Array(Vec<Json>),
13 +
    Object(HashMap<String, Json>),
14 +
}
15 +
16 +
fn json_parser<'a>() -> impl Parser<'a, Output = Json> {
17 +
    |input| json_value().parse_at(input)
18 +
}
19 +
20 +
fn json_value<'a>() -> impl Parser<'a, Output = Json> {
21 +
    string("null")
22 +
        .map(|_| Json::Null)
23 +
        .or(string("true").map(|_| Json::Bool(true)))
24 +
        .or(string("false").map(|_| Json::Bool(false)))
25 +
        .or(json_number())
26 +
        .or(json_string().map(Json::Str))
27 +
        .or(json_array())
28 +
        .or(json_object())
29 +
}
30 +
31 +
fn json_number<'a>() -> impl Parser<'a, Output = Json> {
32 +
    signed(float::<f64>())
33 +
        .map(Json::Number)
34 +
        .or(signed(natural::<i64>()).map(|i| Json::Number(i as f64)))
35 +
}
36 +
37 +
fn json_string<'a>() -> impl Parser<'a, Output = String> {
38 +
    let escaped_char = symbol('\\')
39 +
        .then(choice([
40 +
            symbol('"').value('"'),
41 +
            symbol('\\').value('\\'),
42 +
            symbol('/').value('/'),
43 +
            symbol('n').value('\n'),
44 +
            symbol('t').value('\t'),
45 +
        ]))
46 +
        .map(|(_, c)| c);
47 +
48 +
    let string_char = escaped_char.or(satisfy(|c| *c != '"' && *c != '\\'));
49 +
50 +
    between(symbol('"'), symbol('"'), many::<_, String>(string_char))
51 +
}
52 +
53 +
fn json_array<'a>() -> impl Parser<'a, Output = Json> {
54 +
    between(
55 +
        symbol('[').skip(whitespace()),
56 +
        whitespace().then(symbol(']')),
57 +
        (|input| json_value().skip(whitespace()).parse_at(input))
58 +
            .delimited_by(symbol(',').skip(whitespace())),
59 +
    )
60 +
    .map(Json::Array)
61 +
}
62 +
63 +
fn json_object<'a>() -> impl Parser<'a, Output = Json> {
64 +
    let key_value = json_string()
65 +
        .skip(symbol(':'))
66 +
        .skip(whitespace())
67 +
        .then(|input| json_value().parse_at(input))
68 +
        .skip(whitespace());
69 +
70 +
    between(
71 +
        symbol('{').then(whitespace()),
72 +
        whitespace().then(symbol('}')),
73 +
        key_value.delimited_by(symbol(',').skip(whitespace())),
74 +
    )
75 +
    .map(|pairs| Json::Object(pairs.into_iter().collect()))
76 +
}
77 +
78 +
fn main() {
79 +
    let input = include_str!("twitter.json");
80 +
    let parser = json_parser();
81 +
    let size = input.bytes().len();
82 +
    let options = ombre::bench::Options::default();
83 +
    let result = ombre::bench::run(&options, || {
84 +
        parser.parse(input).unwrap();
85 +
    });
86 +
    let t = result.throughput_bytes(size as u128);
87 +
88 +
    println!("{t}");
89 +
}
syntaxe/benches/twitter.json added +1840 -0
1 +
{
2 +
  "results": [
3 +
    {
4 +
      "from_user_id_str": "3646730",
5 +
      "profile_image_url": "http://a3.twimg.com/profile_images/404973767/avatar_normal.jpg",
6 +
      "created_at": "Wed, 26 Jan 2011 04:35:07 +0000",
7 +
      "from_user": "nicolaslara",
8 +
      "id_str": "30121530767708160",
9 +
      "metadata": {
10 +
        "result_type": "recent"
11 +
      },
12 +
      "to_user_id": 18616016,
13 +
      "text": "@josej30 Python y Clojure. Obviamente son diferentes, y cada uno tiene sus ventajas y desventajas. De Haskell faltaría pattern matching",
14 +
      "id": 30121530767708160,
15 +
      "from_user_id": 3646730,
16 +
      "to_user": "josej30",
17 +
      "geo": null,
18 +
      "iso_language_code": "es",
19 +
      "to_user_id_str": "18616016",
20 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot; rel=&quot;nofollow&quot;&gt;Twitter for iPhone&lt;/a&gt;"
21 +
    },
22 +
    {
23 +
      "from_user_id_str": "207858021",
24 +
      "profile_image_url": "http://a3.twimg.com/sticky/default_profile_images/default_profile_2_normal.png",
25 +
      "created_at": "Wed, 26 Jan 2011 04:30:38 +0000",
26 +
      "from_user": "pboudarga",
27 +
      "id_str": "30120402839666689",
28 +
      "metadata": {
29 +
        "result_type": "recent"
30 +
      },
31 +
      "to_user_id": null,
32 +
      "text": "I'm at Rolla Sushi Grill (27737 Bouquet Canyon Road, #106, Btw Haskell Canyon and Rosedell Drive, Saugus) http://4sq.com/gqqdhs",
33 +
      "id": 30120402839666689,
34 +
      "from_user_id": 207858021,
35 +
      "geo": null,
36 +
      "iso_language_code": "en",
37 +
      "to_user_id_str": null,
38 +
      "source": "&lt;a href=&quot;http://foursquare.com&quot; rel=&quot;nofollow&quot;&gt;foursquare&lt;/a&gt;"
39 +
    },
40 +
    {
41 +
      "from_user_id_str": "69988683",
42 +
      "profile_image_url": "http://a0.twimg.com/profile_images/1211955817/avatar_7888_normal.gif",
43 +
      "created_at": "Wed, 26 Jan 2011 04:25:23 +0000",
44 +
      "from_user": "YNK33",
45 +
      "id_str": "30119083059978240",
46 +
      "metadata": {
47 +
        "result_type": "recent"
48 +
      },
49 +
      "to_user_id": null,
50 +
      "text": "hsndfile 0.5.0: Free and open source Haskell bindings for libsndfile http://bit.ly/gHaBWG Mac Os",
51 +
      "id": 30119083059978240,
52 +
      "from_user_id": 69988683,
53 +
      "geo": null,
54 +
      "iso_language_code": "en",
55 +
      "to_user_id_str": null,
56 +
      "source": "&lt;a href=&quot;http://twitterfeed.com&quot; rel=&quot;nofollow&quot;&gt;twitterfeed&lt;/a&gt;"
57 +
    },
58 +
    {
59 +
      "from_user_id_str": "81492",
60 +
      "profile_image_url": "http://a1.twimg.com/profile_images/423894208/Picture_7_normal.jpg",
61 +
      "created_at": "Wed, 26 Jan 2011 04:24:28 +0000",
62 +
      "from_user": "satzz",
63 +
      "id_str": "30118851488251904",
64 +
      "metadata": {
65 +
        "result_type": "recent"
66 +
      },
67 +
      "to_user_id": null,
68 +
      "text": "Emacsのモード表示が今(Ruby Controller Outputz RoR Flymake REl hs)となっててよくわからないんだけど最後のRElとかhsって何だろう…haskellとか2年以上書いてないけど…",
69 +
      "id": 30118851488251904,
70 +
      "from_user_id": 81492,
71 +
      "geo": null,
72 +
      "iso_language_code": "ja",
73 +
      "to_user_id_str": null,
74 +
      "source": "&lt;a href=&quot;http://www.hootsuite.com&quot; rel=&quot;nofollow&quot;&gt;HootSuite&lt;/a&gt;"
75 +
    },
76 +
    {
77 +
      "from_user_id_str": "9518356",
78 +
      "profile_image_url": "http://a2.twimg.com/profile_images/119165723/ocaml-icon_normal.png",
79 +
      "created_at": "Wed, 26 Jan 2011 04:19:19 +0000",
80 +
      "from_user": "planet_ocaml",
81 +
      "id_str": "30117557788741632",
82 +
      "metadata": {
83 +
        "result_type": "recent"
84 +
      },
85 +
      "to_user_id": null,
86 +
      "text": "I so miss #haskell type classes in #ocaml - i want to do something like refinement. Also why does ocaml not have... http://bit.ly/geYRwt",
87 +
      "id": 30117557788741632,
88 +
      "from_user_id": 9518356,
89 +
      "geo": null,
90 +
      "iso_language_code": "en",
91 +
      "to_user_id_str": null,
92 +
      "source": "&lt;a href=&quot;http://twitterfeed.com&quot; rel=&quot;nofollow&quot;&gt;twitterfeed&lt;/a&gt;"
93 +
    },
94 +
    {
95 +
      "from_user_id_str": "218059",
96 +
      "profile_image_url": "http://a1.twimg.com/profile_images/1053837723/twitter-icon9_normal.jpg",
97 +
      "created_at": "Wed, 26 Jan 2011 04:16:32 +0000",
98 +
      "from_user": "aprikip",
99 +
      "id_str": "30116854940835840",
100 +
      "metadata": {
101 +
        "result_type": "recent"
102 +
      },
103 +
      "to_user_id": null,
104 +
      "text": "yatex-modeやhaskell-modeのことですね、わかります。",
105 +
      "id": 30116854940835840,
106 +
      "from_user_id": 218059,
107 +
      "geo": null,
108 +
      "iso_language_code": "ja",
109 +
      "to_user_id_str": null,
110 +
      "source": "&lt;a href=&quot;http://sites.google.com/site/yorufukurou/&quot; rel=&quot;nofollow&quot;&gt;YoruFukurou&lt;/a&gt;"
111 +
    },
112 +
    {
113 +
      "from_user_id_str": "216363",
114 +
      "profile_image_url": "http://a1.twimg.com/profile_images/72454310/Tim-Avatar_normal.png",
115 +
      "created_at": "Wed, 26 Jan 2011 04:15:30 +0000",
116 +
      "from_user": "dysinger",
117 +
      "id_str": "30116594684264448",
118 +
      "metadata": {
119 +
        "result_type": "recent"
120 +
      },
121 +
      "to_user_id": null,
122 +
      "text": "Haskell in Hawaii tonight for me... #fun",
123 +
      "id": 30116594684264448,
124 +
      "from_user_id": 216363,
125 +
      "geo": null,
126 +
      "iso_language_code": "en",
127 +
      "to_user_id_str": null,
128 +
      "source": "&lt;a href=&quot;http://www.nambu.com/&quot; rel=&quot;nofollow&quot;&gt;Nambu&lt;/a&gt;"
129 +
    },
130 +
    {
131 +
      "from_user_id_str": "1774820",
132 +
      "profile_image_url": "http://a2.twimg.com/profile_images/61169291/dan_desert_thumb_normal.jpg",
133 +
      "created_at": "Wed, 26 Jan 2011 04:13:36 +0000",
134 +
      "from_user": "DanMil",
135 +
      "id_str": "30116117682851840",
136 +
      "metadata": {
137 +
        "result_type": "recent"
138 +
      },
139 +
      "to_user_id": 1594784,
140 +
      "text": "@ojrac @chewedwire @tomheon Haskell isn't a language, it's a belief system.  A seductive one...",
141 +
      "id": 30116117682851840,
142 +
      "from_user_id": 1774820,
143 +
      "to_user": "ojrac",
144 +
      "geo": null,
145 +
      "iso_language_code": "en",
146 +
      "to_user_id_str": "1594784",
147 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
148 +
    },
149 +
    {
150 +
      "from_user_id_str": "659256",
151 +
      "profile_image_url": "http://a0.twimg.com/profile_images/746976711/angular-final_normal.jpg",
152 +
      "created_at": "Wed, 26 Jan 2011 04:11:06 +0000",
153 +
      "from_user": "djspiewak",
154 +
      "id_str": "30115488931520512",
155 +
      "metadata": {
156 +
        "result_type": "recent"
157 +
      },
158 +
      "to_user_id": null,
159 +
      "text": "One of the very nice things about Haskell as opposed to SML is the reduced proliferation of identifiers (e.g. andb, orb, etc). #typeclasses",
160 +
      "id": 30115488931520512,
161 +
      "from_user_id": 659256,
162 +
      "geo": null,
163 +
      "iso_language_code": "en",
164 +
      "to_user_id_str": null,
165 +
      "source": "&lt;a href=&quot;http://itunes.apple.com/us/app/twitter/id409789998?mt=12&quot; rel=&quot;nofollow&quot;&gt;Twitter for Mac&lt;/a&gt;"
166 +
    },
167 +
    {
168 +
      "from_user_id_str": "144546280",
169 +
      "profile_image_url": "http://a1.twimg.com/a/1295051201/images/default_profile_1_normal.png",
170 +
      "created_at": "Wed, 26 Jan 2011 04:06:12 +0000",
171 +
      "from_user": "listwarenet",
172 +
      "id_str": "30114255890026496",
173 +
      "metadata": {
174 +
        "result_type": "recent"
175 +
      },
176 +
      "to_user_id": null,
177 +
      "text": "http://www.listware.net/201101/haskell-cafe/84752-re-haskell-cafe-gpl-license-of-h-matrix-and-prelude-numeric.html Re: Haskell-c",
178 +
      "id": 30114255890026496,
179 +
      "from_user_id": 144546280,
180 +
      "geo": null,
181 +
      "iso_language_code": "no",
182 +
      "to_user_id_str": null,
183 +
      "source": "&lt;a href=&quot;http://1e10.org/cloud/&quot; rel=&quot;nofollow&quot;&gt;1e10&lt;/a&gt;"
184 +
    },
185 +
    {
186 +
      "from_user_id_str": "1594784",
187 +
      "profile_image_url": "http://a2.twimg.com/profile_images/378515773/square-profile_normal.jpg",
188 +
      "created_at": "Wed, 26 Jan 2011 04:01:29 +0000",
189 +
      "from_user": "ojrac",
190 +
      "id_str": "30113067333324800",
191 +
      "metadata": {
192 +
        "result_type": "recent"
193 +
      },
194 +
      "to_user_id": null,
195 +
      "text": "RT @tomheon: @ojrac @chewedwire Don't worry, learning Haskell will not give you any clear idea what monad means.",
196 +
      "id": 30113067333324800,
197 +
      "from_user_id": 1594784,
198 +
      "geo": null,
199 +
      "iso_language_code": "en",
200 +
      "to_user_id_str": null,
201 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
202 +
    },
203 +
    {
204 +
      "from_user_id_str": "207589736",
205 +
      "profile_image_url": "http://a3.twimg.com/profile_images/1225527428/headshot_1_normal.jpg",
206 +
      "created_at": "Wed, 26 Jan 2011 04:00:13 +0000",
207 +
      "from_user": "ashleevelazq101",
208 +
      "id_str": "30112747555397632",
209 +
      "metadata": {
210 +
        "result_type": "recent"
211 +
      },
212 +
      "to_user_id": null,
213 +
      "text": "Federal investigation finds safety violations at The Acadia Hospital: By Meg Haskell, BDN Staff The investigatio... http://bit.ly/dONnpn",
214 +
      "id": 30112747555397632,
215 +
      "from_user_id": 207589736,
216 +
      "geo": null,
217 +
      "iso_language_code": "en",
218 +
      "to_user_id_str": null,
219 +
      "source": "&lt;a href=&quot;http://twitterfeed.com&quot; rel=&quot;nofollow&quot;&gt;twitterfeed&lt;/a&gt;"
220 +
    },
221 +
    {
222 +
      "from_user_id_str": "17671137",
223 +
      "profile_image_url": "http://a2.twimg.com/profile_images/290264834/Haskell-logo-outer-glow_normal.png",
224 +
      "created_at": "Wed, 26 Jan 2011 03:58:00 +0000",
225 +
      "from_user": "Hackage",
226 +
      "id_str": "30112192346984448",
227 +
      "metadata": {
228 +
        "result_type": "recent"
229 +
      },
230 +
      "to_user_id": null,
231 +
      "text": "streams 0.4, added by EdwardKmett: Various Haskell 2010 stream comonads http://bit.ly/idBkPe",
232 +
      "id": 30112192346984448,
233 +
      "from_user_id": 17671137,
234 +
      "geo": null,
235 +
      "iso_language_code": "en",
236 +
      "to_user_id_str": null,
237 +
      "source": "&lt;a href=&quot;http://twitterfeed.com&quot; rel=&quot;nofollow&quot;&gt;twitterfeed&lt;/a&gt;"
238 +
    },
239 +
    {
240 +
      "from_user_id_str": "17489366",
241 +
      "profile_image_url": "http://a3.twimg.com/sticky/default_profile_images/default_profile_2_normal.png",
242 +
      "created_at": "Wed, 26 Jan 2011 03:58:00 +0000",
243 +
      "from_user": "aapnoot",
244 +
      "id_str": "30112191881420800",
245 +
      "metadata": {
246 +
        "result_type": "recent"
247 +
      },
248 +
      "to_user_id": null,
249 +
      "text": "streams 0.4, added by EdwardKmett: Various Haskell 2010 stream comonads http://bit.ly/idBkPe",
250 +
      "id": 30112191881420800,
251 +
      "from_user_id": 17489366,
252 +
      "geo": null,
253 +
      "iso_language_code": "en",
254 +
      "to_user_id_str": null,
255 +
      "source": "&lt;a href=&quot;http://twitterfeed.com&quot; rel=&quot;nofollow&quot;&gt;twitterfeed&lt;/a&gt;"
256 +
    },
257 +
    {
258 +
      "from_user_id_str": "8530482",
259 +
      "profile_image_url": "http://a2.twimg.com/profile_images/137867266/n608671563_7396_normal.jpg",
260 +
      "created_at": "Wed, 26 Jan 2011 03:50:12 +0000",
261 +
      "from_user": "jeffmclamb",
262 +
      "id_str": "30110229207187456",
263 +
      "metadata": {
264 +
        "result_type": "recent"
265 +
      },
266 +
      "to_user_id": null,
267 +
      "text": "Angel - daemon to run and monitor processes like daemontools or god, written in Haskell http://ff.im/-wNyLk",
268 +
      "id": 30110229207187456,
269 +
      "from_user_id": 8530482,
270 +
      "geo": null,
271 +
      "iso_language_code": "en",
272 +
      "to_user_id_str": null,
273 +
      "source": "&lt;a href=&quot;http://friendfeed.com&quot; rel=&quot;nofollow&quot;&gt;FriendFeed&lt;/a&gt;"
274 +
    },
275 +
    {
276 +
      "from_user_id_str": "177539201",
277 +
      "profile_image_url": "http://a0.twimg.com/profile_images/1178368800/img_normal.jpeg",
278 +
      "created_at": "Wed, 26 Jan 2011 03:46:01 +0000",
279 +
      "from_user": "tomheon",
280 +
      "id_str": "30109174645919744",
281 +
      "metadata": {
282 +
        "result_type": "recent"
283 +
      },
284 +
      "to_user_id": 1594784,
285 +
      "text": "@ojrac @chewedwire Don't worry, learning Haskell will not give you any clear idea what monad means.",
286 +
      "id": 30109174645919744,
287 +
      "from_user_id": 177539201,
288 +
      "to_user": "ojrac",
289 +
      "geo": null,
290 +
      "iso_language_code": "en",
291 +
      "to_user_id_str": "1594784",
292 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
293 +
    },
294 +
    {
295 +
      "from_user_id_str": "1594784",
296 +
      "profile_image_url": "http://a2.twimg.com/profile_images/378515773/square-profile_normal.jpg",
297 +
      "created_at": "Wed, 26 Jan 2011 03:44:34 +0000",
298 +
      "from_user": "ojrac",
299 +
      "id_str": "30108808684503040",
300 +
      "metadata": {
301 +
        "result_type": "recent"
302 +
      },
303 +
      "to_user_id": 128028225,
304 +
      "text": "@chewedwire @tomheon Why are you making me curious about Haskell? I LIKE not knowing what monad means!!",
305 +
      "id": 30108808684503040,
306 +
      "from_user_id": 1594784,
307 +
      "to_user": "chewedwire",
308 +
      "geo": null,
309 +
      "iso_language_code": "en",
310 +
      "to_user_id_str": "128028225",
311 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
312 +
    },
313 +
    {
314 +
      "from_user_id_str": "23750094",
315 +
      "profile_image_url": "http://a0.twimg.com/profile_images/951373780/Moeinthecar_normal.jpg",
316 +
      "created_at": "Wed, 26 Jan 2011 03:41:54 +0000",
317 +
      "from_user": "shokalshab",
318 +
      "id_str": "30108140443795456",
319 +
      "metadata": {
320 +
        "result_type": "recent"
321 +
      },
322 +
      "to_user_id": null,
323 +
      "text": "I'm at Magnitude Cheer @ Gymnastics Olympica USA (7735 Haskell Ave., btw Saticoy &amp; Strathern, Van Nuys) http://4sq.com/gmXfaL",
324 +
      "id": 30108140443795456,
325 +
      "from_user_id": 23750094,
326 +
      "geo": null,
327 +
      "iso_language_code": "en",
328 +
      "place": {
329 +
        "id": "4e4a2a2f86cb2946",
330 +
        "type_": "poi",
331 +
        "full_name": "Gymnastics Olympica USA, Van Nuys"
332 +
      },
333 +
      "to_user_id_str": null,
334 +
      "source": "&lt;a href=&quot;http://foursquare.com&quot; rel=&quot;nofollow&quot;&gt;foursquare&lt;/a&gt;"
335 +
    },
336 +
    {
337 +
      "from_user_id_str": "8135112",
338 +
      "profile_image_url": "http://a0.twimg.com/profile_images/1165240350/LIMITED_normal.jpg",
339 +
      "created_at": "Wed, 26 Jan 2011 03:41:35 +0000",
340 +
      "from_user": "Claricei",
341 +
      "id_str": "30108059208515584",
342 +
      "metadata": {
343 +
        "result_type": "recent"
344 +
      },
345 +
      "to_user_id": null,
346 +
      "text": "RT @kristenmchugh22: @KeithOlbermann Ryan looks like Jughead w/o the hat. And sounds as mealy-mouthed as Eddie Haskell.",
347 +
      "id": 30108059208515584,
348 +
      "from_user_id": 8135112,
349 +
      "geo": null,
350 +
      "iso_language_code": "en",
351 +
      "to_user_id_str": null,
352 +
      "source": "&lt;a href=&quot;http://www.tweetdeck.com&quot; rel=&quot;nofollow&quot;&gt;TweetDeck&lt;/a&gt;"
353 +
    },
354 +
    {
355 +
      "from_user_id_str": "128028225",
356 +
      "profile_image_url": "http://a1.twimg.com/profile_images/1224994593/Coding_Drunk_normal.jpg",
357 +
      "created_at": "Wed, 26 Jan 2011 03:40:02 +0000",
358 +
      "from_user": "chewedwire",
359 +
      "id_str": "30107670367182848",
360 +
      "metadata": {
361 +
        "result_type": "recent"
362 +
      },
363 +
      "to_user_id": 177539201,
364 +
      "text": "@tomheon Cool, I'll take a look. I feel like I should mention this: http://bit.ly/hVstDM",
365 +
      "id": 30107670367182848,
366 +
      "from_user_id": 128028225,
367 +
      "to_user": "tomheon",
368 +
      "geo": null,
369 +
      "iso_language_code": "en",
370 +
      "to_user_id_str": "177539201",
371 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
372 +
    },
373 +
    {
374 +
      "from_user_id_str": "8679778",
375 +
      "profile_image_url": "http://a3.twimg.com/profile_images/1195318056/me_nyc_12_18_10_icon_normal.jpg",
376 +
      "created_at": "Wed, 26 Jan 2011 03:38:42 +0000",
377 +
      "from_user": "kristenmchugh22",
378 +
      "id_str": "30107332381777920",
379 +
      "metadata": {
380 +
        "result_type": "recent"
381 +
      },
382 +
      "to_user_id": 756269,
383 +
      "text": "@KeithOlbermann Ryan looks like Jughead w/o the hat. And sounds as mealy-mouthed as Eddie Haskell.",
384 +
      "id": 30107332381777920,
385 +
      "from_user_id": 8679778,
386 +
      "to_user": "KeithOlbermann",
387 +
      "geo": null,
388 +
      "iso_language_code": "en",
389 +
      "to_user_id_str": "756269",
390 +
      "source": "&lt;a href=&quot;http://www.tweetdeck.com&quot; rel=&quot;nofollow&quot;&gt;TweetDeck&lt;/a&gt;"
391 +
    },
392 +
    {
393 +
      "from_user_id_str": "103316559",
394 +
      "profile_image_url": "http://a1.twimg.com/profile_images/1179458751/bc3beab4-d59d-4e78-b13b-50747986cfa2_normal.png",
395 +
      "created_at": "Wed, 26 Jan 2011 03:36:15 +0000",
396 +
      "from_user": "cityslikr",
397 +
      "id_str": "30106719153557504",
398 +
      "metadata": {
399 +
        "result_type": "recent"
400 +
      },
401 +
      "to_user_id": null,
402 +
      "text": "&quot;Social safety net into a hammock.&quot; So says Eddie Haskell with the GOP response. #SOTU",
403 +
      "id": 30106719153557504,
404 +
      "from_user_id": 103316559,
405 +
      "geo": null,
406 +
      "iso_language_code": "en",
407 +
      "to_user_id_str": null,
408 +
      "source": "&lt;a href=&quot;http://blackberry.com/twitter&quot; rel=&quot;nofollow&quot;&gt;Twitter for BlackBerry®&lt;/a&gt;"
409 +
    },
410 +
    {
411 +
      "from_user_id_str": "169063143",
412 +
      "profile_image_url": "http://a0.twimg.com/profile_images/1160506212/9697_1_normal.gif",
413 +
      "created_at": "Wed, 26 Jan 2011 03:31:52 +0000",
414 +
      "from_user": "wrkforce_safety",
415 +
      "id_str": "30105614919143424",
416 +
      "metadata": {
417 +
        "result_type": "recent"
418 +
      },
419 +
      "to_user_id": null,
420 +
      "text": "Federal investigation finds safety violations at The Acadia Hospital: By Meg Haskell, BDN Staff The investigatio... http://bit.ly/gA60C1",
421 +
      "id": 30105614919143424,
422 +
      "from_user_id": 169063143,
423 +
      "geo": null,
424 +
      "iso_language_code": "en",
425 +
      "to_user_id_str": null,
426 +
      "source": "&lt;a href=&quot;http://twitterfeed.com&quot; rel=&quot;nofollow&quot;&gt;twitterfeed&lt;/a&gt;"
427 +
    },
428 +
    {
429 +
      "from_user_id_str": "177539201",
430 +
      "profile_image_url": "http://a0.twimg.com/profile_images/1178368800/img_normal.jpeg",
431 +
      "created_at": "Wed, 26 Jan 2011 03:29:40 +0000",
432 +
      "from_user": "tomheon",
433 +
      "id_str": "30105060960632832",
434 +
      "metadata": {
435 +
        "result_type": "recent"
436 +
      },
437 +
      "to_user_id": 128028225,
438 +
      "text": "@chewedwire Great book on Haskell: http://oreilly.com/catalog/9780596514983",
439 +
      "id": 30105060960632832,
440 +
      "from_user_id": 177539201,
441 +
      "to_user": "chewedwire",
442 +
      "geo": null,
443 +
      "iso_language_code": "en",
444 +
      "to_user_id_str": "128028225",
445 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
446 +
    },
447 +
    {
448 +
      "from_user_id_str": "782692",
449 +
      "profile_image_url": "http://a0.twimg.com/profile_images/1031304589/Profile.2007.1_normal.jpg",
450 +
      "created_at": "Wed, 26 Jan 2011 03:29:19 +0000",
451 +
      "from_user": "turnageb",
452 +
      "id_str": "30104974591533057",
453 +
      "metadata": {
454 +
        "result_type": "recent"
455 +
      },
456 +
      "to_user_id": null,
457 +
      "text": "RT @ovillalon: Paul Ryan solves the mystery of whatever happened to Eddie Haskell. #sotu",
458 +
      "id": 30104974591533057,
459 +
      "from_user_id": 782692,
460 +
      "geo": null,
461 +
      "iso_language_code": "en",
462 +
      "to_user_id_str": null,
463 +
      "source": "&lt;a href=&quot;http://www.tweetdeck.com&quot; rel=&quot;nofollow&quot;&gt;TweetDeck&lt;/a&gt;"
464 +
    },
465 +
    {
466 +
      "from_user_id_str": "128028225",
467 +
      "profile_image_url": "http://a1.twimg.com/profile_images/1224994593/Coding_Drunk_normal.jpg",
468 +
      "created_at": "Wed, 26 Jan 2011 03:28:04 +0000",
469 +
      "from_user": "chewedwire",
470 +
      "id_str": "30104657267265536",
471 +
      "metadata": {
472 +
        "result_type": "recent"
473 +
      },
474 +
      "to_user_id": 177539201,
475 +
      "text": "@tomheon I always loved the pattern matching in SML and it looks like Haskell is MUCH better at it. I'm messing around now at tryhaskell.org",
476 +
      "id": 30104657267265536,
477 +
      "from_user_id": 128028225,
478 +
      "to_user": "tomheon",
479 +
      "geo": null,
480 +
      "iso_language_code": "en",
481 +
      "to_user_id_str": "177539201",
482 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
483 +
    },
484 +
    {
485 +
      "from_user_id_str": "12834082",
486 +
      "profile_image_url": "http://a3.twimg.com/profile_images/1083036140/mugshot_normal.png",
487 +
      "created_at": "Wed, 26 Jan 2011 03:28:01 +0000",
488 +
      "from_user": "ovillalon",
489 +
      "id_str": "30104647213518848",
490 +
      "metadata": {
491 +
        "result_type": "recent"
492 +
      },
493 +
      "to_user_id": null,
494 +
      "text": "Paul Ryan solves the mystery of whatever happened to Eddie Haskell. #sotu",
495 +
      "id": 30104647213518848,
496 +
      "from_user_id": 12834082,
497 +
      "geo": null,
498 +
      "iso_language_code": "en",
499 +
      "to_user_id_str": null,
500 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
501 +
    },
502 +
    {
503 +
      "from_user_id_str": "13540930",
504 +
      "profile_image_url": "http://a1.twimg.com/profile_images/1205312219/23467_350321383101_821143101_5114147_3010041_n_normal.jpg",
505 +
      "created_at": "Wed, 26 Jan 2011 03:26:02 +0000",
506 +
      "from_user": "goodfox",
507 +
      "id_str": "30104146455560192",
508 +
      "metadata": {
509 +
        "result_type": "recent"
510 +
      },
511 +
      "to_user_id": 10226179,
512 +
      "text": "@billykeene22 Bordeaux is one of my heroes. I was so excited when he accepted the invitation to campus. He's been a great friend to Haskell.",
513 +
      "id": 30104146455560192,
514 +
      "from_user_id": 13540930,
515 +
      "to_user": "billykeene22",
516 +
      "geo": null,
517 +
      "iso_language_code": "en",
518 +
      "to_user_id_str": "10226179",
519 +
      "source": "&lt;a href=&quot;http://www.ubertwitter.com/bb/download.php&quot; rel=&quot;nofollow&quot;&gt;ÜberTwitter&lt;/a&gt;"
520 +
    },
521 +
    {
522 +
      "from_user_id_str": "18616016",
523 +
      "profile_image_url": "http://a2.twimg.com/profile_images/1173522726/214397343_normal.jpg",
524 +
      "created_at": "Wed, 26 Jan 2011 03:25:18 +0000",
525 +
      "from_user": "josej30",
526 +
      "id_str": "30103962313031681",
527 +
      "metadata": {
528 +
        "result_type": "recent"
529 +
      },
530 +
      "to_user_id": 14870909,
531 +
      "text": "@cris7ian Ahh bueno multiparadigma ya es respetable :) Empezaré a explotar la parte funcional de los lenguajes ahora #Haskell",
532 +
      "id": 30103962313031681,
533 +
      "from_user_id": 18616016,
534 +
      "to_user": "Cris7ian",
535 +
      "geo": null,
536 +
      "iso_language_code": "es",
537 +
      "to_user_id_str": "14870909",
538 +
      "source": "&lt;a href=&quot;http://www.tweetdeck.com&quot; rel=&quot;nofollow&quot;&gt;TweetDeck&lt;/a&gt;"
539 +
    },
540 +
    {
541 +
      "from_user_id_str": "14870909",
542 +
      "profile_image_url": "http://a2.twimg.com/profile_images/1176930429/oso_yo_normal.png",
543 +
      "created_at": "Wed, 26 Jan 2011 03:23:43 +0000",
544 +
      "from_user": "Cris7ian",
545 +
      "id_str": "30103562360983553",
546 +
      "metadata": {
547 +
        "result_type": "recent"
548 +
      },
549 +
      "to_user_id": 18616016,
550 +
      "text": "@josej30 hahaha no, es multiparadigma y es bastante lazy. Nothing like haskell, pero sí, el de Flash",
551 +
      "id": 30103562360983553,
552 +
      "from_user_id": 14870909,
553 +
      "to_user": "josej30",
554 +
      "geo": null,
555 +
      "iso_language_code": "es",
556 +
      "to_user_id_str": "18616016",
557 +
      "source": "&lt;a href=&quot;http://www.echofon.com/&quot; rel=&quot;nofollow&quot;&gt;Echofon&lt;/a&gt;"
558 +
    },
559 +
    {
560 +
      "from_user_id_str": "2421643",
561 +
      "profile_image_url": "http://a0.twimg.com/profile_images/1190361665/ernestgrumbles-17_normal.jpg",
562 +
      "created_at": "Wed, 26 Jan 2011 03:20:24 +0000",
563 +
      "from_user": "ernestgrumbles",
564 +
      "id_str": "30102730756333568",
565 +
      "metadata": {
566 +
        "result_type": "recent"
567 +
      },
568 +
      "to_user_id": null,
569 +
      "text": "Wow... WolframAlpha did not know who Eddie Haskell is.  Guess I'll never use that &quot;knowledge engine&quot; again.",
570 +
      "id": 30102730756333568,
571 +
      "from_user_id": 2421643,
572 +
      "geo": null,
573 +
      "iso_language_code": "en",
574 +
      "to_user_id_str": null,
575 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
576 +
    },
577 +
    {
578 +
      "from_user_id_str": "128028225",
579 +
      "profile_image_url": "http://a1.twimg.com/profile_images/1224994593/Coding_Drunk_normal.jpg",
580 +
      "created_at": "Wed, 26 Jan 2011 03:14:21 +0000",
581 +
      "from_user": "chewedwire",
582 +
      "id_str": "30101204428132352",
583 +
      "metadata": {
584 +
        "result_type": "recent"
585 +
      },
586 +
      "to_user_id": 177539201,
587 +
      "text": "@tomheon How is Haskell better/different from CL or Scheme? I honestly don't know, although I'm becoming more curious.",
588 +
      "id": 30101204428132352,
589 +
      "from_user_id": 128028225,
590 +
      "to_user": "tomheon",
591 +
      "geo": null,
592 +
      "iso_language_code": "en",
593 +
      "to_user_id_str": "177539201",
594 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
595 +
    },
596 +
    {
597 +
      "from_user_id_str": "13540930",
598 +
      "profile_image_url": "http://a1.twimg.com/profile_images/1205312219/23467_350321383101_821143101_5114147_3010041_n_normal.jpg",
599 +
      "created_at": "Wed, 26 Jan 2011 03:06:54 +0000",
600 +
      "from_user": "goodfox",
601 +
      "id_str": "30099329809129473",
602 +
      "metadata": {
603 +
        "result_type": "recent"
604 +
      },
605 +
      "to_user_id": null,
606 +
      "text": "A day of vision &amp; speeches. #SOTU now. And a wonderful Haskell Convocation address earlier today by Sinte Gleske President Lionel Bordeaux.",
607 +
      "id": 30099329809129473,
608 +
      "from_user_id": 13540930,
609 +
      "geo": null,
610 +
      "iso_language_code": "en",
611 +
      "to_user_id_str": null,
612 +
      "source": "&lt;a href=&quot;http://www.ubertwitter.com/bb/download.php&quot; rel=&quot;nofollow&quot;&gt;ÜberTwitter&lt;/a&gt;"
613 +
    },
614 +
    {
615 +
      "from_user_id_str": "119185220",
616 +
      "profile_image_url": "http://a0.twimg.com/profile_images/1089027228/dfg_normal.jpg",
617 +
      "created_at": "Wed, 26 Jan 2011 03:03:38 +0000",
618 +
      "from_user": "LaLiciouz_03",
619 +
      "id_str": "30098510623805440",
620 +
      "metadata": {
621 +
        "result_type": "recent"
622 +
      },
623 +
      "to_user_id": null,
624 +
      "text": "The Game with the girl room 330 Haskell follow us...",
625 +
      "id": 30098510623805440,
626 +
      "from_user_id": 119185220,
627 +
      "geo": null,
628 +
      "iso_language_code": "en",
629 +
      "to_user_id_str": null,
630 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
631 +
    },
632 +
    {
633 +
      "from_user_id_str": "18616016",
634 +
      "profile_image_url": "http://a2.twimg.com/profile_images/1173522726/214397343_normal.jpg",
635 +
      "created_at": "Wed, 26 Jan 2011 02:57:25 +0000",
636 +
      "from_user": "josej30",
637 +
      "id_str": "30096946144215040",
638 +
      "metadata": {
639 +
        "result_type": "recent"
640 +
      },
641 +
      "to_user_id": null,
642 +
      "text": "Voy a extrañar Haskell cuando regrese al mundo imperativo. Hay algún lenguaje imperativo que tenga este poder funcional? #ci3661",
643 +
      "id": 30096946144215040,
644 +
      "from_user_id": 18616016,
645 +
      "geo": null,
646 +
      "iso_language_code": "es",
647 +
      "to_user_id_str": null,
648 +
      "source": "&lt;a href=&quot;http://www.tweetdeck.com&quot; rel=&quot;nofollow&quot;&gt;TweetDeck&lt;/a&gt;"
649 +
    },
650 +
    {
651 +
      "from_user_id_str": "17671137",
652 +
      "profile_image_url": "http://a2.twimg.com/profile_images/290264834/Haskell-logo-outer-glow_normal.png",
653 +
      "created_at": "Wed, 26 Jan 2011 02:55:32 +0000",
654 +
      "from_user": "Hackage",
655 +
      "id_str": "30096471814574080",
656 +
      "metadata": {
657 +
        "result_type": "recent"
658 +
      },
659 +
      "to_user_id": null,
660 +
      "text": "comonad-transformers 0.9.0, added by EdwardKmett: Haskell 98 comonad transformers http://bit.ly/h6xIsf",
661 +
      "id": 30096471814574080,
662 +
      "from_user_id": 17671137,
663 +
      "geo": null,
664 +
      "iso_language_code": "no",
665 +
      "to_user_id_str": null,
666 +
      "source": "&lt;a href=&quot;http://twitterfeed.com&quot; rel=&quot;nofollow&quot;&gt;twitterfeed&lt;/a&gt;"
667 +
    },
668 +
    {
669 +
      "from_user_id_str": "177539201",
670 +
      "profile_image_url": "http://a0.twimg.com/profile_images/1178368800/img_normal.jpeg",
671 +
      "created_at": "Wed, 26 Jan 2011 02:48:12 +0000",
672 +
      "from_user": "tomheon",
673 +
      "id_str": "30094626920603649",
674 +
      "metadata": {
675 +
        "result_type": "recent"
676 +
      },
677 +
      "to_user_id": null,
678 +
      "text": "Every time I look at Haskell I love it more.",
679 +
      "id": 30094626920603649,
680 +
      "from_user_id": 177539201,
681 +
      "geo": null,
682 +
      "iso_language_code": "en",
683 +
      "to_user_id_str": null,
684 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
685 +
    },
686 +
    {
687 +
      "from_user_id_str": "60792568",
688 +
      "profile_image_url": "http://a0.twimg.com/profile_images/1203647517/glenda-flash_normal.jpg",
689 +
      "created_at": "Wed, 26 Jan 2011 02:40:42 +0000",
690 +
      "from_user": "r_takaishi",
691 +
      "id_str": "30092735935422464",
692 +
      "metadata": {
693 +
        "result_type": "recent"
694 +
      },
695 +
      "to_user_id": null,
696 +
      "text": "HaskellよりD言語が上とは思わなかった. http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html",
697 +
      "id": 30092735935422464,
698 +
      "from_user_id": 60792568,
699 +
      "geo": null,
700 +
      "iso_language_code": "ja",
701 +
      "to_user_id_str": null,
702 +
      "source": "&lt;a href=&quot;http://twmode.sf.net/&quot; rel=&quot;nofollow&quot;&gt;twmode&lt;/a&gt;"
703 +
    },
704 +
    {
705 +
      "from_user_id_str": "160145510",
706 +
      "profile_image_url": "http://a0.twimg.com/profile_images/1218108166/going_galt_normal.jpg",
707 +
      "created_at": "Wed, 26 Jan 2011 02:39:31 +0000",
708 +
      "from_user": "wtp1787",
709 +
      "id_str": "30092439653974018",
710 +
      "metadata": {
711 +
        "result_type": "recent"
712 +
      },
713 +
      "to_user_id": null,
714 +
      "text": "RT @KLSouth: Eddie Haskell Goes to Washington...  &quot;You look really nice tonight, Ms Cleaver&quot;",
715 +
      "id": 30092439653974018,
716 +
      "from_user_id": 160145510,
717 +
      "geo": null,
718 +
      "iso_language_code": "en",
719 +
      "to_user_id_str": null,
720 +
      "source": "&lt;a href=&quot;http://www.tweetdeck.com&quot; rel=&quot;nofollow&quot;&gt;TweetDeck&lt;/a&gt;"
721 +
    },
722 +
    {
723 +
      "from_user_id_str": "96616016",
724 +
      "profile_image_url": "http://a1.twimg.com/profile_images/1196978169/Picture0002_normal.jpg",
725 +
      "created_at": "Wed, 26 Jan 2011 02:39:20 +0000",
726 +
      "from_user": "MelissaRNMBA",
727 +
      "id_str": "30092392203816960",
728 +
      "metadata": {
729 +
        "result_type": "recent"
730 +
      },
731 +
      "to_user_id": 14862975,
732 +
      "text": "@KLSouth At least Eddie Haskell was entertaining.",
733 +
      "id": 30092392203816960,
734 +
      "from_user_id": 96616016,
735 +
      "to_user": "KLSouth",
736 +
      "geo": null,
737 +
      "iso_language_code": "en",
738 +
      "to_user_id_str": "14862975",
739 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
740 +
    },
741 +
    {
742 +
      "from_user_id_str": "14862975",
743 +
      "profile_image_url": "http://a0.twimg.com/profile_images/421596393/kls_4_normal.JPG",
744 +
      "created_at": "Wed, 26 Jan 2011 02:38:29 +0000",
745 +
      "from_user": "KLSouth",
746 +
      "id_str": "30092178327871489",
747 +
      "metadata": {
748 +
        "result_type": "recent"
749 +
      },
750 +
      "to_user_id": null,
751 +
      "text": "Eddie Haskell Goes to Washington...  &quot;You look really nice tonight, Ms Cleaver&quot;",
752 +
      "id": 30092178327871489,
753 +
      "from_user_id": 14862975,
754 +
      "geo": null,
755 +
      "iso_language_code": "en",
756 +
      "to_user_id_str": null,
757 +
      "source": "&lt;a href=&quot;http://www.tweetdeck.com&quot; rel=&quot;nofollow&quot;&gt;TweetDeck&lt;/a&gt;"
758 +
    },
759 +
    {
760 +
      "from_user_id_str": "144546280",
761 +
      "profile_image_url": "http://a1.twimg.com/a/1295051201/images/default_profile_1_normal.png",
762 +
      "created_at": "Wed, 26 Jan 2011 02:36:17 +0000",
763 +
      "from_user": "listwarenet",
764 +
      "id_str": "30091626869161984",
765 +
      "metadata": {
766 +
        "result_type": "recent"
767 +
      },
768 +
      "to_user_id": null,
769 +
      "text": "http://www.listware.net/201101/haskell-beginners/84641-haskell-beginners-wildcards-in-expressions.html Haskell-beginners -  Wild",
770 +
      "id": 30091626869161984,
771 +
      "from_user_id": 144546280,
772 +
      "geo": null,
773 +
      "iso_language_code": "no",
774 +
      "to_user_id_str": null,
775 +
      "source": "&lt;a href=&quot;http://1e10.org/cloud/&quot; rel=&quot;nofollow&quot;&gt;1e10&lt;/a&gt;"
776 +
    },
777 +
    {
778 +
      "from_user_id_str": "24538048",
779 +
      "profile_image_url": "http://a2.twimg.com/profile_images/1117267605/rope_normal.jpg",
780 +
      "created_at": "Wed, 26 Jan 2011 02:23:14 +0000",
781 +
      "from_user": "dbph",
782 +
      "id_str": "30088341030440960",
783 +
      "metadata": {
784 +
        "result_type": "recent"
785 +
      },
786 +
      "to_user_id": null,
787 +
      "text": "RT @dnene: Skilled Calisthenics. Haskell code that outputs python which spits ruby which emits the haskell source. http://j.mp/YlQUL via @mfeathers",
788 +
      "id": 30088341030440960,
789 +
      "from_user_id": 24538048,
790 +
      "geo": null,
791 +
      "iso_language_code": "en",
792 +
      "to_user_id_str": null,
793 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
794 +
    },
795 +
    {
796 +
      "from_user_id_str": "158951567",
797 +
      "profile_image_url": "http://a3.twimg.com/profile_images/962721419/Logo_3_normal.jpg",
798 +
      "created_at": "Wed, 26 Jan 2011 01:58:31 +0000",
799 +
      "from_user": "YubaVetTech",
800 +
      "id_str": "30082124207886336",
801 +
      "metadata": {
802 +
        "result_type": "recent"
803 +
      },
804 +
      "to_user_id": null,
805 +
      "text": "Dr. Haskell has just been awarded the prestigious Hayward Award for ‘Excellence in Education’. This award honors... http://fb.me/QgQCxd74",
806 +
      "id": 30082124207886336,
807 +
      "from_user_id": 158951567,
808 +
      "geo": null,
809 +
      "iso_language_code": "en",
810 +
      "to_user_id_str": null,
811 +
      "source": "&lt;a href=&quot;http://www.facebook.com/twitter&quot; rel=&quot;nofollow&quot;&gt;Facebook&lt;/a&gt;"
812 +
    },
813 +
    {
814 +
      "from_user_id_str": "158951567",
815 +
      "profile_image_url": "http://a3.twimg.com/profile_images/962721419/Logo_3_normal.jpg",
816 +
      "created_at": "Wed, 26 Jan 2011 01:56:04 +0000",
817 +
      "from_user": "YubaVetTech",
818 +
      "id_str": "30081505476743168",
819 +
      "metadata": {
820 +
        "result_type": "recent"
821 +
      },
822 +
      "to_user_id": null,
823 +
      "text": "Dr. Haskell has just been awarded the prestigous Haward Award for Excellence in Education. This award honors... http://fb.me/PC9mYmCR",
824 +
      "id": 30081505476743168,
825 +
      "from_user_id": 158951567,
826 +
      "geo": null,
827 +
      "iso_language_code": "en",
828 +
      "to_user_id_str": null,
829 +
      "source": "&lt;a href=&quot;http://www.facebook.com/twitter&quot; rel=&quot;nofollow&quot;&gt;Facebook&lt;/a&gt;"
830 +
    },
831 +
    {
832 +
      "from_user_id_str": "2331498",
833 +
      "profile_image_url": "http://a3.twimg.com/profile_images/494632120/me_normal.jpg",
834 +
      "created_at": "Wed, 26 Jan 2011 01:43:50 +0000",
835 +
      "from_user": "Verus",
836 +
      "id_str": "30078427155406848",
837 +
      "metadata": {
838 +
        "result_type": "recent"
839 +
      },
840 +
      "to_user_id": 79273052,
841 +
      "text": "@kami_joe いや,課題は解決対象(パズルとか)を与えられて,問題定義とプログラミング(指定言語はC++もしくはJava)といういわば普通な課題ではあるんだけど.関数型言語はHaskellの授業がまた別にあるの.",
842 +
      "id": 30078427155406848,
843 +
      "from_user_id": 2331498,
844 +
      "to_user": "kami_joe",
845 +
      "geo": null,
846 +
      "iso_language_code": "ja",
847 +
      "to_user_id_str": "79273052",
848 +
      "source": "&lt;a href=&quot;http://itunes.apple.com/us/app/twitter/id409789998?mt=12&quot; rel=&quot;nofollow&quot;&gt;Twitter for Mac&lt;/a&gt;"
849 +
    },
850 +
    {
851 +
      "from_user_id_str": "79151233",
852 +
      "profile_image_url": "http://a2.twimg.com/a/1295051201/images/default_profile_2_normal.png",
853 +
      "created_at": "Wed, 26 Jan 2011 01:40:37 +0000",
854 +
      "from_user": "cz_newdrafts",
855 +
      "id_str": "30077617361125376",
856 +
      "metadata": {
857 +
        "result_type": "recent"
858 +
      },
859 +
      "to_user_id": null,
860 +
      "text": "Haskell programming language http://bit.ly/gpPAwB",
861 +
      "id": 30077617361125376,
862 +
      "from_user_id": 79151233,
863 +
      "geo": null,
864 +
      "iso_language_code": "no",
865 +
      "to_user_id_str": null,
866 +
      "source": "&lt;a href=&quot;http://tommorris.org/&quot; rel=&quot;nofollow&quot;&gt;tommorris' hacksample&lt;/a&gt;"
867 +
    },
868 +
    {
869 +
      "from_user_id_str": "2331498",
870 +
      "profile_image_url": "http://a3.twimg.com/profile_images/494632120/me_normal.jpg",
871 +
      "created_at": "Wed, 26 Jan 2011 01:02:57 +0000",
872 +
      "from_user": "Verus",
873 +
      "id_str": "30068139416879104",
874 +
      "metadata": {
875 +
        "result_type": "recent"
876 +
      },
877 +
      "to_user_id": 9252720,
878 +
      "text": "@shukukei JavaとCはある程度書けてあたりまえなところがあるからなー.Pythonは個人的に感覚が合わない.感覚なので,もうどうしようもないw いまはScalaとHaskellをもっと極めたいところ.",
879 +
      "id": 30068139416879104,
880 +
      "from_user_id": 2331498,
881 +
      "to_user": "shukukei",
882 +
      "geo": null,
883 +
      "iso_language_code": "ja",
884 +
      "to_user_id_str": "9252720",
885 +
      "source": "&lt;a href=&quot;http://itunes.apple.com/us/app/twitter/id409789998?mt=12&quot; rel=&quot;nofollow&quot;&gt;Twitter for Mac&lt;/a&gt;"
886 +
    },
887 +
    {
888 +
      "from_user_id_str": "2781460",
889 +
      "profile_image_url": "http://a0.twimg.com/profile_images/82526625/.joeyicon_normal.jpg",
890 +
      "created_at": "Wed, 26 Jan 2011 01:02:35 +0000",
891 +
      "from_user": "joeyhess",
892 +
      "id_str": "30068046538219520",
893 +
      "metadata": {
894 +
        "result_type": "recent"
895 +
      },
896 +
      "to_user_id": null,
897 +
      "text": "just figured out that I can use parameterized types to remove a dependency loop in git-annex's type definitions. whee #haskell",
898 +
      "id": 30068046538219520,
899 +
      "from_user_id": 2781460,
900 +
      "geo": null,
901 +
      "iso_language_code": "en",
902 +
      "to_user_id_str": null,
903 +
      "source": "&lt;a href=&quot;http://identi.ca&quot; rel=&quot;nofollow&quot;&gt;identica&lt;/a&gt;"
904 +
    },
905 +
    {
906 +
      "from_user_id_str": "144546280",
907 +
      "profile_image_url": "http://a1.twimg.com/a/1295051201/images/default_profile_1_normal.png",
908 +
      "created_at": "Wed, 26 Jan 2011 00:54:22 +0000",
909 +
      "from_user": "listwarenet",
910 +
      "id_str": "30065977920061440",
911 +
      "metadata": {
912 +
        "result_type": "recent"
913 +
      },
914 +
      "to_user_id": null,
915 +
      "text": "http://www.listware.net/201101/haskell-beginners/84466-haskell-beginners-bytestring-question.html Haskell-beginners -  Bytestrin",
916 +
      "id": 30065977920061440,
917 +
      "from_user_id": 144546280,
918 +
      "geo": null,
919 +
      "iso_language_code": "no",
920 +
      "to_user_id_str": null,
921 +
      "source": "&lt;a href=&quot;http://1e10.org/cloud/&quot; rel=&quot;nofollow&quot;&gt;1e10&lt;/a&gt;"
922 +
    },
923 +
    {
924 +
      "from_user_id_str": "1291845",
925 +
      "profile_image_url": "http://a0.twimg.com/profile_images/1225743404/ThinOxygen-small-opaque-solidarity_normal.png",
926 +
      "created_at": "Wed, 26 Jan 2011 00:52:07 +0000",
927 +
      "from_user": "_aaron_",
928 +
      "id_str": "30065412242669568",
929 +
      "metadata": {
930 +
        "result_type": "recent"
931 +
      },
932 +
      "to_user_id": null,
933 +
      "text": "wanted: librly licensed high level native compiled lang with min runtime (otherwise cobra/mono would be perfect) for win. lua? haskell? ooc?",
934 +
      "id": 30065412242669568,
935 +
      "from_user_id": 1291845,
936 +
      "geo": null,
937 +
      "iso_language_code": "en",
938 +
      "to_user_id_str": null,
939 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
940 +
    },
941 +
    {
942 +
      "from_user_id_str": "5912444",
943 +
      "profile_image_url": "http://a2.twimg.com/profile_images/546261026/ssf0xg11_normal.jpg",
944 +
      "created_at": "Wed, 26 Jan 2011 00:45:45 +0000",
945 +
      "from_user": "shelarcy",
946 +
      "id_str": "30063810773516288",
947 +
      "metadata": {
948 +
        "result_type": "recent"
949 +
      },
950 +
      "to_user_id": null,
951 +
      "text": "RT @Hackage: download 0.3.1.1, added by MagnusTherning: High-level file download based on URLs http://bit.ly/eHfiJB",
952 +
      "id": 30063810773516288,
953 +
      "from_user_id": 5912444,
954 +
      "geo": null,
955 +
      "iso_language_code": "en",
956 +
      "to_user_id_str": null,
957 +
      "source": "&lt;a href=&quot;http://twitterfeed.com&quot; rel=&quot;nofollow&quot;&gt;twitterfeed&lt;/a&gt;"
958 +
    },
959 +
    {
960 +
      "from_user_id_str": "135993",
961 +
      "profile_image_url": "http://a2.twimg.com/profile_images/1190667086/myface2010small_normal.jpg",
962 +
      "created_at": "Wed, 26 Jan 2011 00:41:00 +0000",
963 +
      "from_user": "kudzu_naoki",
964 +
      "id_str": "30062613287141376",
965 +
      "metadata": {
966 +
        "result_type": "recent"
967 +
      },
968 +
      "to_user_id": null,
969 +
      "text": "RT @tanakh: 魔法Haskell少女候補を探すのも大変なんだ",
970 +
      "id": 30062613287141376,
971 +
      "from_user_id": 135993,
972 +
      "geo": null,
973 +
      "iso_language_code": "ja",
974 +
      "to_user_id_str": null,
975 +
      "source": "&lt;a href=&quot;http://www.hootsuite.com&quot; rel=&quot;nofollow&quot;&gt;HootSuite&lt;/a&gt;"
976 +
    },
977 +
    {
978 +
      "from_user_id_str": "52620546",
979 +
      "profile_image_url": "http://a1.twimg.com/profile_images/434693356/twitter-icon_normal.png",
980 +
      "created_at": "Wed, 26 Jan 2011 00:40:25 +0000",
981 +
      "from_user": "omasanori",
982 +
      "id_str": "30062465656033280",
983 +
      "metadata": {
984 +
        "result_type": "recent"
985 +
      },
986 +
      "to_user_id": null,
987 +
      "text": "魔法Haskell少女の一日はGHC HEADのビルドから始まる",
988 +
      "id": 30062465656033280,
989 +
      "from_user_id": 52620546,
990 +
      "geo": null,
991 +
      "iso_language_code": "ja",
992 +
      "to_user_id_str": null,
993 +
      "source": "&lt;a href=&quot;http://www.movatwi.jp&quot; rel=&quot;nofollow&quot;&gt;www.movatwi.jp&lt;/a&gt;"
994 +
    },
995 +
    {
996 +
      "from_user_id_str": "52620546",
997 +
      "profile_image_url": "http://a1.twimg.com/profile_images/434693356/twitter-icon_normal.png",
998 +
      "created_at": "Wed, 26 Jan 2011 00:37:12 +0000",
999 +
      "from_user": "omasanori",
1000 +
      "id_str": "30061656331526144",
1001 +
      "metadata": {
1002 +
        "result_type": "recent"
1003 +
      },
1004 +
      "to_user_id": null,
1005 +
      "text": "RT @tanakh: 僕と契約して魔法Haskell少女になろうよ!",
1006 +
      "id": 30061656331526144,
1007 +
      "from_user_id": 52620546,
1008 +
      "geo": null,
1009 +
      "iso_language_code": "ja",
1010 +
      "to_user_id_str": null,
1011 +
      "source": "&lt;a href=&quot;http://www.hootsuite.com&quot; rel=&quot;nofollow&quot;&gt;HootSuite&lt;/a&gt;"
1012 +
    },
1013 +
    {
1014 +
      "from_user_id_str": "135993",
1015 +
      "profile_image_url": "http://a2.twimg.com/profile_images/1190667086/myface2010small_normal.jpg",
1016 +
      "created_at": "Wed, 26 Jan 2011 00:35:42 +0000",
1017 +
      "from_user": "kudzu_naoki",
1018 +
      "id_str": "30061282665168896",
1019 +
      "metadata": {
1020 +
        "result_type": "recent"
1021 +
      },
1022 +
      "to_user_id": null,
1023 +
      "text": "RT @tanakh: 僕と契約して魔法Haskell少女になろうよ!",
1024 +
      "id": 30061282665168896,
1025 +
      "from_user_id": 135993,
1026 +
      "geo": null,
1027 +
      "iso_language_code": "ja",
1028 +
      "to_user_id_str": null,
1029 +
      "source": "&lt;a href=&quot;http://www.hootsuite.com&quot; rel=&quot;nofollow&quot;&gt;HootSuite&lt;/a&gt;"
1030 +
    },
1031 +
    {
1032 +
      "from_user_id_str": "1631333",
1033 +
      "profile_image_url": "http://a1.twimg.com/profile_images/81268862/profile300_normal.jpg",
1034 +
      "created_at": "Wed, 26 Jan 2011 00:30:02 +0000",
1035 +
      "from_user": "qnighy",
1036 +
      "id_str": "30059855884582913",
1037 +
      "metadata": {
1038 +
        "result_type": "recent"
1039 +
      },
1040 +
      "to_user_id": null,
1041 +
      "text": "RT @tanakh: 僕と契約して魔法Haskell少女になろうよ!",
1042 +
      "id": 30059855884582913,
1043 +
      "from_user_id": 1631333,
1044 +
      "geo": null,
1045 +
      "iso_language_code": "ja",
1046 +
      "to_user_id_str": null,
1047 +
      "source": "&lt;a href=&quot;http://www.hootsuite.com&quot; rel=&quot;nofollow&quot;&gt;HootSuite&lt;/a&gt;"
1048 +
    },
1049 +
    {
1050 +
      "from_user_id_str": "9093754",
1051 +
      "profile_image_url": "http://a1.twimg.com/profile_images/99435906/PHD_3d_col_blk_normal.jpg",
1052 +
      "created_at": "Wed, 26 Jan 2011 00:26:20 +0000",
1053 +
      "from_user": "phdwine",
1054 +
      "id_str": "30058925516656640",
1055 +
      "metadata": {
1056 +
        "result_type": "recent"
1057 +
      },
1058 +
      "to_user_id": null,
1059 +
      "text": "Last weekend of Tri Nations Tasting with PHD wines at Haskell Vineyards. Hope you didn't miss the Pinot Noir tasting last week !",
1060 +
      "id": 30058925516656640,
1061 +
      "from_user_id": 9093754,
1062 +
      "geo": null,
1063 +
      "iso_language_code": "en",
1064 +
      "to_user_id_str": null,
1065 +
      "source": "&lt;a href=&quot;http://www.tweetdeck.com&quot; rel=&quot;nofollow&quot;&gt;TweetDeck&lt;/a&gt;"
1066 +
    },
1067 +
    {
1068 +
      "from_user_id_str": "2119923",
1069 +
      "profile_image_url": "http://a2.twimg.com/profile_images/1096701078/djayprofile_normal.jpg",
1070 +
      "created_at": "Wed, 26 Jan 2011 00:21:14 +0000",
1071 +
      "from_user": "djay75",
1072 +
      "id_str": "30057639543050240",
1073 +
      "metadata": {
1074 +
        "result_type": "recent"
1075 +
      },
1076 +
      "to_user_id": null,
1077 +
      "text": "RT @dnene: Skilled Calisthenics. Haskell code that outputs python which spits ruby which emits the haskell source. http://j.mp/YlQUL via @mfeathers",
1078 +
      "id": 30057639543050240,
1079 +
      "from_user_id": 2119923,
1080 +
      "geo": null,
1081 +
      "iso_language_code": "en",
1082 +
      "to_user_id_str": null,
1083 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
1084 +
    },
1085 +
    {
1086 +
      "from_user_id_str": "134323731",
1087 +
      "profile_image_url": "http://a2.twimg.com/profile_images/1225818824/IMG00518-20110125-1547_normal.jpg",
1088 +
      "created_at": "Wed, 26 Jan 2011 00:19:30 +0000",
1089 +
      "from_user": "PrinceOfBrkeley",
1090 +
      "id_str": "30057205554216960",
1091 +
      "metadata": {
1092 +
        "result_type": "recent"
1093 +
      },
1094 +
      "to_user_id": 167093027,
1095 +
      "text": "@PayThaPrince go to haskell.",
1096 +
      "id": 30057205554216960,
1097 +
      "from_user_id": 134323731,
1098 +
      "to_user": "PayThaPrince",
1099 +
      "geo": null,
1100 +
      "iso_language_code": "en",
1101 +
      "to_user_id_str": "167093027",
1102 +
      "source": "&lt;a href=&quot;http://blackberry.com/twitter&quot; rel=&quot;nofollow&quot;&gt;Twitter for BlackBerry®&lt;/a&gt;"
1103 +
    },
1104 +
    {
1105 +
      "from_user_id_str": "705857",
1106 +
      "profile_image_url": "http://a1.twimg.com/profile_images/429483912/ben_twitter_normal.jpg",
1107 +
      "created_at": "Wed, 26 Jan 2011 00:03:28 +0000",
1108 +
      "from_user": "bennadel",
1109 +
      "id_str": "30053166972141569",
1110 +
      "metadata": {
1111 +
        "result_type": "recent"
1112 +
      },
1113 +
      "to_user_id": null,
1114 +
      "text": "Using #Homebrew to install Haskell - the last of the Seven Languages (in Seven Weeks) http://bit.ly/eA9Cv1 This has been some journey.",
1115 +
      "id": 30053166972141569,
1116 +
      "from_user_id": 705857,
1117 +
      "geo": null,
1118 +
      "iso_language_code": "en",
1119 +
      "to_user_id_str": null,
1120 +
      "source": "&lt;a href=&quot;http://www.tweetdeck.com&quot; rel=&quot;nofollow&quot;&gt;TweetDeck&lt;/a&gt;"
1121 +
    },
1122 +
    {
1123 +
      "from_user_id_str": "251466",
1124 +
      "profile_image_url": "http://a2.twimg.com/profile_images/1194100934/pass_normal.jpg",
1125 +
      "created_at": "Wed, 26 Jan 2011 00:02:54 +0000",
1126 +
      "from_user": "simonszu",
1127 +
      "id_str": "30053025502466048",
1128 +
      "metadata": {
1129 +
        "result_type": "recent"
1130 +
      },
1131 +
      "to_user_id": null,
1132 +
      "text": "Ouh yeah! Ich werde doch produktiv sein, diese Semesterferien. Ich werde funktional Programmieren lernen. #haskell, Baby.",
1133 +
      "id": 30053025502466048,
1134 +
      "from_user_id": 251466,
1135 +
      "geo": null,
1136 +
      "iso_language_code": "de",
1137 +
      "to_user_id_str": null,
1138 +
      "source": "&lt;a href=&quot;http://www.echofon.com/&quot; rel=&quot;nofollow&quot;&gt;Echofon&lt;/a&gt;"
1139 +
    },
1140 +
    {
1141 +
      "from_user_id_str": "357786",
1142 +
      "profile_image_url": "http://a0.twimg.com/profile_images/612044841/FM_2010_normal.jpg",
1143 +
      "created_at": "Tue, 25 Jan 2011 23:59:13 +0000",
1144 +
      "from_user": "diligiant",
1145 +
      "id_str": "30052100973006848",
1146 +
      "metadata": {
1147 +
        "result_type": "recent"
1148 +
      },
1149 +
      "to_user_id": null,
1150 +
      "text": "RT @paulrbrown: &quot;...we only discovered a single bug after compilation.&quot; (http://t.co/K0wlEYz) #haskell",
1151 +
      "id": 30052100973006848,
1152 +
      "from_user_id": 357786,
1153 +
      "geo": null,
1154 +
      "iso_language_code": "en",
1155 +
      "to_user_id_str": null,
1156 +
      "source": "&lt;a href=&quot;http://itunes.apple.com/us/app/twitter/id409789998?mt=12&quot; rel=&quot;nofollow&quot;&gt;Twitter for Mac&lt;/a&gt;"
1157 +
    },
1158 +
    {
1159 +
      "from_user_id_str": "101597523",
1160 +
      "profile_image_url": "http://a1.twimg.com/profile_images/1206183256/2010-12-12-204902_normal.jpg",
1161 +
      "created_at": "Tue, 25 Jan 2011 23:54:46 +0000",
1162 +
      "from_user": "wlad_kent",
1163 +
      "id_str": "30050977964892160",
1164 +
      "metadata": {
1165 +
        "result_type": "recent"
1166 +
      },
1167 +
      "to_user_id": 86297184,
1168 +
      "text": "@Nilson_Neto Isso eh bem basico. quando vc estiver estudando recursão em Haskell, ai vc vai ver oq eh papo de nerd - kkk - 1º periodo isso.",
1169 +
      "id": 30050977964892160,
1170 +
      "from_user_id": 101597523,
1171 +
      "to_user": "Nilson_Neto",
1172 +
      "geo": null,
1173 +
      "iso_language_code": "pt",
1174 +
      "to_user_id_str": "86297184",
1175 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
1176 +
    },
1177 +
    {
1178 +
      "from_user_id_str": "144546280",
1179 +
      "profile_image_url": "http://a1.twimg.com/a/1295051201/images/default_profile_1_normal.png",
1180 +
      "created_at": "Tue, 25 Jan 2011 23:51:22 +0000",
1181 +
      "from_user": "listwarenet",
1182 +
      "id_str": "30050123383832577",
1183 +
      "metadata": {
1184 +
        "result_type": "recent"
1185 +
      },
1186 +
      "to_user_id": null,
1187 +
      "text": "http://www.listware.net/201101/haskell-cafe/84336-haskell-cafe-monomorphic-let-bindings-and-darcs.html Haskell-cafe -  Monomorph",
1188 +
      "id": 30050123383832577,
1189 +
      "from_user_id": 144546280,
1190 +
      "geo": null,
1191 +
      "iso_language_code": "en",
1192 +
      "to_user_id_str": null,
1193 +
      "source": "&lt;a href=&quot;http://1e10.org/cloud/&quot; rel=&quot;nofollow&quot;&gt;1e10&lt;/a&gt;"
1194 +
    },
1195 +
    {
1196 +
      "from_user_id_str": "5776901",
1197 +
      "profile_image_url": "http://a0.twimg.com/profile_images/472682157/lucabw_normal.JPG",
1198 +
      "created_at": "Tue, 25 Jan 2011 23:48:40 +0000",
1199 +
      "from_user": "lsbardel",
1200 +
      "id_str": "30049446469312512",
1201 +
      "metadata": {
1202 +
        "result_type": "recent"
1203 +
      },
1204 +
      "to_user_id": null,
1205 +
      "text": "Very interesting technology stack these guys use http://bit.ly/ghAjS7 #python #redis #haskell",
1206 +
      "id": 30049446469312512,
1207 +
      "from_user_id": 5776901,
1208 +
      "geo": null,
1209 +
      "iso_language_code": "en",
1210 +
      "to_user_id_str": null,
1211 +
      "source": "&lt;a href=&quot;http://www.tweetdeck.com&quot; rel=&quot;nofollow&quot;&gt;TweetDeck&lt;/a&gt;"
1212 +
    },
1213 +
    {
1214 +
      "from_user_id_str": "3005901",
1215 +
      "profile_image_url": "http://a0.twimg.com/profile_images/278943006/Lone_Pine_Peak_-_Peter_200x200_normal.jpg",
1216 +
      "created_at": "Tue, 25 Jan 2011 23:45:48 +0000",
1217 +
      "from_user": "pmonks",
1218 +
      "id_str": "30048721110573056",
1219 +
      "metadata": {
1220 +
        "result_type": "recent"
1221 +
      },
1222 +
      "to_user_id": 203834278,
1223 +
      "text": "@techielicous Haskell: http://bit.ly/gy3oFi  ;-)",
1224 +
      "id": 30048721110573056,
1225 +
      "from_user_id": 3005901,
1226 +
      "to_user": "techielicous",
1227 +
      "geo": null,
1228 +
      "iso_language_code": "en",
1229 +
      "to_user_id_str": "203834278",
1230 +
      "source": "&lt;a href=&quot;http://www.tweetdeck.com&quot; rel=&quot;nofollow&quot;&gt;TweetDeck&lt;/a&gt;"
1231 +
    },
1232 +
    {
1233 +
      "from_user_id_str": "162697074",
1234 +
      "profile_image_url": "http://a2.twimg.com/profile_images/826205838/ryan3_normal.jpg",
1235 +
      "created_at": "Tue, 25 Jan 2011 23:44:47 +0000",
1236 +
      "from_user": "TheRonaldMCD",
1237 +
      "id_str": "30048468781244416",
1238 +
      "metadata": {
1239 +
        "result_type": "recent"
1240 +
      },
1241 +
      "to_user_id": null,
1242 +
      "text": "I'm at Aldi Food Market (4122 Gaston Ave, Haskell, Dallas) http://4sq.com/ekqRY7",
1243 +
      "id": 30048468781244416,
1244 +
      "from_user_id": 162697074,
1245 +
      "geo": null,
1246 +
      "iso_language_code": "no",
1247 +
      "to_user_id_str": null,
1248 +
      "source": "&lt;a href=&quot;http://foursquare.com&quot; rel=&quot;nofollow&quot;&gt;foursquare&lt;/a&gt;"
1249 +
    },
1250 +
    {
1251 +
      "from_user_id_str": "203834278",
1252 +
      "profile_image_url": "http://a0.twimg.com/profile_images/1223375080/me_normal.jpg",
1253 +
      "created_at": "Tue, 25 Jan 2011 23:44:04 +0000",
1254 +
      "from_user": "techielicous",
1255 +
      "id_str": "30048286589067264",
1256 +
      "metadata": {
1257 +
        "result_type": "recent"
1258 +
      },
1259 +
      "to_user_id": 3005901,
1260 +
      "text": "@pmonks I was thinking Haskell or Scheme",
1261 +
      "id": 30048286589067264,
1262 +
      "from_user_id": 203834278,
1263 +
      "to_user": "pmonks",
1264 +
      "geo": null,
1265 +
      "iso_language_code": "en",
1266 +
      "to_user_id_str": "3005901",
1267 +
      "source": "&lt;a href=&quot;http://www.tweetdeck.com&quot; rel=&quot;nofollow&quot;&gt;TweetDeck&lt;/a&gt;"
1268 +
    },
1269 +
    {
1270 +
      "from_user_id_str": "537690",
1271 +
      "profile_image_url": "http://a3.twimg.com/profile_images/45665122/nushiostamp_normal.jpg",
1272 +
      "created_at": "Tue, 25 Jan 2011 23:38:14 +0000",
1273 +
      "from_user": "nushio",
1274 +
      "id_str": "30046818658164737",
1275 +
      "metadata": {
1276 +
        "result_type": "recent"
1277 +
      },
1278 +
      "to_user_id": null,
1279 +
      "text": "そういや契約によるプログラミングとかあったな。Haskellなんかよりあっちの方が魔法少女呼ばわりにふさわしい。",
1280 +
      "id": 30046818658164737,
1281 +
      "from_user_id": 537690,
1282 +
      "geo": null,
1283 +
      "iso_language_code": "ja",
1284 +
      "to_user_id_str": null,
1285 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
1286 +
    },
1287 +
    {
1288 +
      "from_user_id_str": "181192",
1289 +
      "profile_image_url": "http://a2.twimg.com/profile_images/1089890701/q530888600_9828_normal.jpg",
1290 +
      "created_at": "Tue, 25 Jan 2011 23:38:03 +0000",
1291 +
      "from_user": "aodag",
1292 +
      "id_str": "30046772223016960",
1293 +
      "metadata": {
1294 +
        "result_type": "recent"
1295 +
      },
1296 +
      "to_user_id": null,
1297 +
      "text": "RT @omasanori: 「もう何年もHaskellのことしか考えてなかったからな、ループの使い方忘れてた」",
1298 +
      "id": 30046772223016960,
1299 +
      "from_user_id": 181192,
1300 +
      "geo": null,
1301 +
      "iso_language_code": "ja",
1302 +
      "to_user_id_str": null,
1303 +
      "source": "&lt;a href=&quot;http://www.movatwi.jp&quot; rel=&quot;nofollow&quot;&gt;www.movatwi.jp&lt;/a&gt;"
1304 +
    },
1305 +
    {
1306 +
      "from_user_id_str": "5886055",
1307 +
      "profile_image_url": "http://a3.twimg.com/profile_images/85531669/ichi_normal.jpg",
1308 +
      "created_at": "Tue, 25 Jan 2011 23:37:53 +0000",
1309 +
      "from_user": "kanaya",
1310 +
      "id_str": "30046729243983873",
1311 +
      "metadata": {
1312 +
        "result_type": "recent"
1313 +
      },
1314 +
      "to_user_id": null,
1315 +
      "text": "麗しい。“@omasanori: 「もう何年もHaskellのことしか考えてなかったからな、ループの使い方忘れてた」”",
1316 +
      "id": 30046729243983873,
1317 +
      "from_user_id": 5886055,
1318 +
      "geo": null,
1319 +
      "iso_language_code": "ja",
1320 +
      "to_user_id_str": null,
1321 +
      "source": "&lt;a href=&quot;http://itunes.apple.com/app/twitter/id333903271?mt=8&quot; rel=&quot;nofollow&quot;&gt;Twitter for iPad&lt;/a&gt;"
1322 +
    },
1323 +
    {
1324 +
      "from_user_id_str": "52620546",
1325 +
      "profile_image_url": "http://a1.twimg.com/profile_images/434693356/twitter-icon_normal.png",
1326 +
      "created_at": "Tue, 25 Jan 2011 23:36:26 +0000",
1327 +
      "from_user": "omasanori",
1328 +
      "id_str": "30046367187476481",
1329 +
      "metadata": {
1330 +
        "result_type": "recent"
1331 +
      },
1332 +
      "to_user_id": null,
1333 +
      "text": "「もう何年もHaskellのことしか考えてなかったからな、ループの使い方忘れてた」",
1334 +
      "id": 30046367187476481,
1335 +
      "from_user_id": 52620546,
1336 +
      "geo": null,
1337 +
      "iso_language_code": "ja",
1338 +
      "to_user_id_str": null,
1339 +
      "source": "&lt;a href=&quot;http://www.movatwi.jp&quot; rel=&quot;nofollow&quot;&gt;www.movatwi.jp&lt;/a&gt;"
1340 +
    },
1341 +
    {
1342 +
      "from_user_id_str": "1659992",
1343 +
      "profile_image_url": "http://a1.twimg.com/profile_images/504488750/1_normal.jpg",
1344 +
      "created_at": "Tue, 25 Jan 2011 23:16:13 +0000",
1345 +
      "from_user": "finalfusion",
1346 +
      "id_str": "30041278544609280",
1347 +
      "metadata": {
1348 +
        "result_type": "recent"
1349 +
      },
1350 +
      "to_user_id": null,
1351 +
      "text": "RT @necocen: Haskellのミサワ、というものを考えてみてぱっとしない",
1352 +
      "id": 30041278544609280,
1353 +
      "from_user_id": 1659992,
1354 +
      "geo": null,
1355 +
      "iso_language_code": "ja",
1356 +
      "to_user_id_str": null,
1357 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot; rel=&quot;nofollow&quot;&gt;Twitter for iPhone&lt;/a&gt;"
1358 +
    },
1359 +
    {
1360 +
      "from_user_id_str": "272513",
1361 +
      "profile_image_url": "http://a2.twimg.com/profile_images/320244078/Mike_Painting2_normal.png",
1362 +
      "created_at": "Tue, 25 Jan 2011 23:05:09 +0000",
1363 +
      "from_user": "mikehadlow",
1364 +
      "id_str": "30038492373319680",
1365 +
      "metadata": {
1366 +
        "result_type": "recent"
1367 +
      },
1368 +
      "to_user_id": null,
1369 +
      "text": "Just written the same simple program in C#, F# and Haskell: 18, 12 and 9 LoC respectively. And I'm much better at C# than F# or Haskell.",
1370 +
      "id": 30038492373319680,
1371 +
      "from_user_id": 272513,
1372 +
      "geo": null,
1373 +
      "iso_language_code": "en",
1374 +
      "to_user_id_str": null,
1375 +
      "source": "&lt;a href=&quot;http://www.tweetdeck.com&quot; rel=&quot;nofollow&quot;&gt;TweetDeck&lt;/a&gt;"
1376 +
    },
1377 +
    {
1378 +
      "from_user_id_str": "89393264",
1379 +
      "profile_image_url": "http://a0.twimg.com/profile_images/1169486472/020_portland_me_normal.jpg",
1380 +
      "created_at": "Tue, 25 Jan 2011 23:01:28 +0000",
1381 +
      "from_user": "newsportlandme",
1382 +
      "id_str": "30037564589084673",
1383 +
      "metadata": {
1384 +
        "result_type": "recent"
1385 +
      },
1386 +
      "to_user_id": null,
1387 +
      "text": "Governor's Choice to Run Maine DOC Under Scrutiny - MPBN: State Rep. Anne Haskell, a Portland Democrat, says Mai... http://bit.ly/fO30gC",
1388 +
      "id": 30037564589084673,
1389 +
      "from_user_id": 89393264,
1390 +
      "geo": null,
1391 +
      "iso_language_code": "en",
1392 +
      "to_user_id_str": null,
1393 +
      "source": "&lt;a href=&quot;http://twitterfeed.com&quot; rel=&quot;nofollow&quot;&gt;twitterfeed&lt;/a&gt;"
1394 +
    },
1395 +
    {
1396 +
      "from_user_id_str": "38138",
1397 +
      "profile_image_url": "http://a3.twimg.com/profile_images/1212565885/Screen_shot_2011-01-11_at_5.28.47_PM_normal.png",
1398 +
      "created_at": "Tue, 25 Jan 2011 22:59:55 +0000",
1399 +
      "from_user": "michaelneale",
1400 +
      "id_str": "30037174615281664",
1401 +
      "metadata": {
1402 +
        "result_type": "recent"
1403 +
      },
1404 +
      "to_user_id": null,
1405 +
      "text": "The haskell EvilMangler http://t.co/P2Tls7J",
1406 +
      "id": 30037174615281664,
1407 +
      "from_user_id": 38138,
1408 +
      "geo": null,
1409 +
      "iso_language_code": "no",
1410 +
      "to_user_id_str": null,
1411 +
      "source": "&lt;a href=&quot;http://itunes.apple.com/us/app/twitter/id409789998?mt=12&quot; rel=&quot;nofollow&quot;&gt;Twitter for Mac&lt;/a&gt;"
1412 +
    },
1413 +
    {
1414 +
      "from_user_id_str": "45692",
1415 +
      "profile_image_url": "http://a3.twimg.com/profile_images/1177741507/dogkarno_r_normal.jpg",
1416 +
      "created_at": "Tue, 25 Jan 2011 22:45:06 +0000",
1417 +
      "from_user": "karno",
1418 +
      "id_str": "30033448286552064",
1419 +
      "metadata": {
1420 +
        "result_type": "recent"
1421 +
      },
1422 +
      "to_user_id": null,
1423 +
      "text": "Haskellって関数にカレー粉ぶち込むとかなんとか",
1424 +
      "id": 30033448286552064,
1425 +
      "from_user_id": 45692,
1426 +
      "geo": null,
1427 +
      "iso_language_code": "ja",
1428 +
      "to_user_id_str": null,
1429 +
      "source": "&lt;a href=&quot;http://yubitter.com/&quot; rel=&quot;nofollow&quot;&gt;yubitter&lt;/a&gt;"
1430 +
    },
1431 +
    {
1432 +
      "from_user_id_str": "27605",
1433 +
      "profile_image_url": "http://a2.twimg.com/profile_images/15826632/meron_normal.jpg",
1434 +
      "created_at": "Tue, 25 Jan 2011 22:44:23 +0000",
1435 +
      "from_user": "celeron1ghz",
1436 +
      "id_str": "30033268761956352",
1437 +
      "metadata": {
1438 +
        "result_type": "recent"
1439 +
      },
1440 +
      "to_user_id": null,
1441 +
      "text": "RT @necocen: Haskellのミサワ、というものを考えてみてぱっとしない",
1442 +
      "id": 30033268761956352,
1443 +
      "from_user_id": 27605,
1444 +
      "geo": null,
1445 +
      "iso_language_code": "ja",
1446 +
      "to_user_id_str": null,
1447 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot; rel=&quot;nofollow&quot;&gt;Twitter for iPhone&lt;/a&gt;"
1448 +
    },
1449 +
    {
1450 +
      "from_user_id_str": "12901",
1451 +
      "profile_image_url": "http://a1.twimg.com/profile_images/56091349/haruhi_nagato-Y_normal.jpg",
1452 +
      "created_at": "Tue, 25 Jan 2011 22:43:30 +0000",
1453 +
      "from_user": "necocen",
1454 +
      "id_str": "30033044035346432",
1455 +
      "metadata": {
1456 +
        "result_type": "recent"
1457 +
      },
1458 +
      "to_user_id": null,
1459 +
      "text": "まあHaskell知らんしね",
1460 +
      "id": 30033044035346432,
1461 +
      "from_user_id": 12901,
1462 +
      "geo": null,
1463 +
      "iso_language_code": "ja",
1464 +
      "to_user_id_str": null,
1465 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot; rel=&quot;nofollow&quot;&gt;Twitter for iPhone&lt;/a&gt;"
1466 +
    },
1467 +
    {
1468 +
      "from_user_id_str": "12901",
1469 +
      "profile_image_url": "http://a1.twimg.com/profile_images/56091349/haruhi_nagato-Y_normal.jpg",
1470 +
      "created_at": "Tue, 25 Jan 2011 22:42:54 +0000",
1471 +
      "from_user": "necocen",
1472 +
      "id_str": "30032894856531968",
1473 +
      "metadata": {
1474 +
        "result_type": "recent"
1475 +
      },
1476 +
      "to_user_id": null,
1477 +
      "text": "Haskellのミサワ、というものを考えてみてぱっとしない",
1478 +
      "id": 30032894856531968,
1479 +
      "from_user_id": 12901,
1480 +
      "geo": null,
1481 +
      "iso_language_code": "ja",
1482 +
      "to_user_id_str": null,
1483 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot; rel=&quot;nofollow&quot;&gt;Twitter for iPhone&lt;/a&gt;"
1484 +
    },
1485 +
    {
1486 +
      "from_user_id_str": "10821270",
1487 +
      "profile_image_url": "http://a0.twimg.com/profile_images/1195474259/Salto_Marlon_normal.jpg",
1488 +
      "created_at": "Tue, 25 Jan 2011 22:35:09 +0000",
1489 +
      "from_user": "jjedMoriAnktah",
1490 +
      "id_str": "30030942106025984",
1491 +
      "metadata": {
1492 +
        "result_type": "recent"
1493 +
      },
1494 +
      "to_user_id": null,
1495 +
      "text": "&quot;A Haskell program that outputs a Python program that outputs a Ruby program that outputs the original Haskell program&quot; http://is.gd/E6Julu",
1496 +
      "id": 30030942106025984,
1497 +
      "from_user_id": 10821270,
1498 +
      "geo": null,
1499 +
      "iso_language_code": "en",
1500 +
      "to_user_id_str": null,
1501 +
      "source": "&lt;a href=&quot;http://www.tweetdeck.com&quot; rel=&quot;nofollow&quot;&gt;TweetDeck&lt;/a&gt;"
1502 +
    },
1503 +
    {
1504 +
      "from_user_id_str": "7554762",
1505 +
      "profile_image_url": "http://a0.twimg.com/profile_images/100515212/ajay-photo_normal.jpg",
1506 +
      "created_at": "Tue, 25 Jan 2011 22:34:30 +0000",
1507 +
      "from_user": "comatose_kid",
1508 +
      "id_str": "30030780205899776",
1509 +
      "metadata": {
1510 +
        "result_type": "recent"
1511 +
      },
1512 +
      "to_user_id": null,
1513 +
      "text": "RT @bumptech: Bump Dev Blog - Why we use Haskell at Bump http://devblog.bu.mp/haskell-at-bump",
1514 +
      "id": 30030780205899776,
1515 +
      "from_user_id": 7554762,
1516 +
      "geo": null,
1517 +
      "iso_language_code": "en",
1518 +
      "to_user_id_str": null,
1519 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
1520 +
    },
1521 +
    {
1522 +
      "from_user_id_str": "148474705",
1523 +
      "profile_image_url": "http://a0.twimg.com/profile_images/1119234716/fur_hat_-_gilbeys_vodka_-_life_-_11-30-1962_normal.JPG",
1524 +
      "created_at": "Tue, 25 Jan 2011 22:29:19 +0000",
1525 +
      "from_user": "landmvintage",
1526 +
      "id_str": "30029476003840000",
1527 +
      "metadata": {
1528 +
        "result_type": "recent"
1529 +
      },
1530 +
      "to_user_id": null,
1531 +
      "text": "RT @faerymoongodess: Magnificent Miriam Haskell Baroque Pearl Necklace by @MercyMadge http://etsy.me/hqRl51",
1532 +
      "id": 30029476003840000,
1533 +
      "from_user_id": 148474705,
1534 +
      "geo": null,
1535 +
      "iso_language_code": "en",
1536 +
      "to_user_id_str": null,
1537 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
1538 +
    },
1539 +
    {
1540 +
      "from_user_id_str": "37715508",
1541 +
      "profile_image_url": "http://a1.twimg.com/profile_images/1207891411/ballerina_normal.jpg",
1542 +
      "created_at": "Tue, 25 Jan 2011 22:24:52 +0000",
1543 +
      "from_user": "faerymoongodess",
1544 +
      "id_str": "30028356326002688",
1545 +
      "metadata": {
1546 +
        "result_type": "recent"
1547 +
      },
1548 +
      "to_user_id": null,
1549 +
      "text": "Magnificent Miriam Haskell Baroque Pearl Necklace by @MercyMadge http://etsy.me/hqRl51",
1550 +
      "id": 30028356326002688,
1551 +
      "from_user_id": 37715508,
1552 +
      "geo": null,
1553 +
      "iso_language_code": "en",
1554 +
      "to_user_id_str": null,
1555 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
1556 +
    },
1557 +
    {
1558 +
      "from_user_id_str": "17671137",
1559 +
      "profile_image_url": "http://a2.twimg.com/profile_images/290264834/Haskell-logo-outer-glow_normal.png",
1560 +
      "created_at": "Tue, 25 Jan 2011 22:17:16 +0000",
1561 +
      "from_user": "Hackage",
1562 +
      "id_str": "30026442456694784",
1563 +
      "metadata": {
1564 +
        "result_type": "recent"
1565 +
      },
1566 +
      "to_user_id": null,
1567 +
      "text": "base16-bytestring 0.1.0.0, added by BryanOSullivan: Fast base16 (hex) encoding and deconding for ByteStrings http://bit.ly/eu75TN",
1568 +
      "id": 30026442456694784,
1569 +
      "from_user_id": 17671137,
1570 +
      "geo": null,
1571 +
      "iso_language_code": "en",
1572 +
      "to_user_id_str": null,
1573 +
      "source": "&lt;a href=&quot;http://twitterfeed.com&quot; rel=&quot;nofollow&quot;&gt;twitterfeed&lt;/a&gt;"
1574 +
    },
1575 +
    {
1576 +
      "from_user_id_str": "199750997",
1577 +
      "profile_image_url": "http://a3.twimg.com/sticky/default_profile_images/default_profile_2_normal.png",
1578 +
      "created_at": "Tue, 25 Jan 2011 22:12:07 +0000",
1579 +
      "from_user": "benreads",
1580 +
      "id_str": "30025146991382528",
1581 +
      "metadata": {
1582 +
        "result_type": "recent"
1583 +
      },
1584 +
      "to_user_id": null,
1585 +
      "text": "Writing Systems Software in a Functional Language -- brief, but fun. I want to see how well they can make Systems Haskell perform at scale.",
1586 +
      "id": 30025146991382528,
1587 +
      "from_user_id": 199750997,
1588 +
      "geo": null,
1589 +
      "iso_language_code": "en",
1590 +
      "to_user_id_str": null,
1591 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot;&gt;web&lt;/a&gt;"
1592 +
    },
1593 +
    {
1594 +
      "from_user_id_str": "35359797",
1595 +
      "profile_image_url": "http://a1.twimg.com/profile_images/1173453785/48893_521140819_1896062_q_normal.jpg",
1596 +
      "created_at": "Tue, 25 Jan 2011 22:09:45 +0000",
1597 +
      "from_user": "jcawthorne1",
1598 +
      "id_str": "30024549265309696",
1599 +
      "metadata": {
1600 +
        "result_type": "recent"
1601 +
      },
1602 +
      "to_user_id": null,
1603 +
      "text": "Just saw Jeff Haskell give the middle finger!! Lol awesome",
1604 +
      "id": 30024549265309696,
1605 +
      "from_user_id": 35359797,
1606 +
      "geo": null,
1607 +
      "iso_language_code": "en",
1608 +
      "to_user_id_str": null,
1609 +
      "source": "&lt;a href=&quot;http://twitter.com/&quot; rel=&quot;nofollow&quot;&gt;Twitter for iPhone&lt;/a&gt;"
1610 +
    },
1611 +
    {
1612 +
      "from_user_id_str": "13540930",
1613 +
      "profile_image_url": "http://a1.twimg.com/profile_images/1205312219/23467_350321383101_821143101_5114147_3010041_n_normal.jpg",
1614 +
      "created_at": "Tue, 25 Jan 2011 22:06:44 +0000",
1615 +
      "from_user": "goodfox",
1616 +
      "id_str": "30023790381498369",
1617 +
      "metadata": {
1618 +
        "result_type": "recent"
1619 +
      },
1620 +
      "to_user_id": null,
1621 +
      "text": "At the Haskell Convocation. (@ Haskell Indian Nations U Auditorium) http://4sq.com/eKKXyn",
1622 +
      "id": 30023790381498369,
1623 +
      "from_user_id": 13540930,
1624 +
      "geo": null,
1625 +
      "iso_language_code": "en",
1626 +
      "to_user_id_str": null,
1627 +
      "source": "&lt;a href=&quot;http://foursquare.com&quot; rel=&quot;nofollow&quot;&gt;foursquare&lt;/a&gt;"
1628 +
    },
1629 +
    {
1630 +
      "from_user_id_str": "14674418",
1631 +
      "profile_image_url": "http://a2.twimg.com/profile_images/238230125/IMG_1030-1_normal.jpg",
1632 +
      "created_at": "Tue, 25 Jan 2011 22:02:31 +0000",
1633 +
      "from_user": "sanityinc",
1634 +
      "id_str": "30022731919523840",
1635 +
      "metadata": {
1636 +
        "result_type": "recent"
1637 +
      },
1638 +
      "to_user_id": 371289,
1639 +
      "text": "@xshay Haskell's great, but Clojure's similarly lazy in all the ways that matter, and is more practical for day-to-day use.",
1640 +
      "id": 30022731919523840,
1641 +
      "from_user_id": 14674418,
1642 +
      "to_user": "xshay",
1643 +
      "geo": null,
1644 +
      "iso_language_code": "en",
1645 +
      "to_user_id_str": "371289",
1646 +
      "source": "&lt;a href=&quot;http://www.echofon.com/&quot; rel=&quot;nofollow&quot;&gt;Echofon&lt;/a&gt;"
1647 +
    },
1648 +
    {
1649 +
      "from_user_id_str": "371289",
1650 +
      "profile_image_url": "http://a2.twimg.com/profile_images/1113482439/me-brisbane_normal.jpg",
1651 +
      "created_at": "Tue, 25 Jan 2011 21:58:29 +0000",
1652 +
      "from_user": "xshay",
1653 +
      "id_str": "30021714444292096",
1654 +
      "metadata": {
1655 +
        "result_type": "recent"
1656 +
      },
1657 +
      "to_user_id": null,
1658 +
      "text": "Just made a lazy sequence of prime numbers in haskell. I'm smitten.",
1659 +
      "id": 30021714444292096,
1660 +
      "from_user_id": 371289,
1661 +
      "geo": null,
1662 +
      "iso_language_code": "en",
1663 +
      "to_user_id_str": null,
1664 +
      "source": "&lt;a href=&quot;http://itunes.apple.com/us/app/twitter/id409789998?mt=12&quot; rel=&quot;nofollow&quot;&gt;Twitter for Mac&lt;/a&gt;"
1665 +
    },
1666 +
    {
1667 +
      "from_user_id_str": "199453873",
1668 +
      "profile_image_url": "http://a3.twimg.com/a/1294785484/images/default_profile_3_normal.png",
1669 +
      "created_at": "Tue, 25 Jan 2011 21:48:40 +0000",
1670 +
      "from_user": "stackfeed",
1671 +
      "id_str": "30019243982454784",
1672 +
      "metadata": {
1673 +
        "result_type": "recent"
1674 +
      },
1675 +
      "to_user_id": null,
1676 +
      "text": "Practical Scala reference manual, for searching things like method names: Hello, \n\nInspired by\nHaskell API Searc... http://bit.ly/g4zWZQ",
1677 +
      "id": 30019243982454784,
1678 +
      "from_user_id": 199453873,
1679 +
      "geo": null,
1680 +
      "iso_language_code": "en",
1681 +
      "to_user_id_str": null,
1682 +
      "source": "&lt;a href=&quot;http://twitterfeed.com&quot; rel=&quot;nofollow&quot;&gt;twitterfeed&lt;/a&gt;"
1683 +
    },
1684 +
    {
1685 +
      "from_user_id_str": "17489366",
1686 +
      "profile_image_url": "http://a3.twimg.com/sticky/default_profile_images/default_profile_2_normal.png",
1687 +
      "created_at": "Tue, 25 Jan 2011 21:45:32 +0000",
1688 +
      "from_user": "aapnoot",
1689 +
      "id_str": "30018455189065728",
1690 +
      "metadata": {
1691 +
        "result_type": "recent"
1692 +
      },
1693 +
      "to_user_id": null,
1694 +
      "text": "download 0.3.1, added by MagnusTherning: High-level file download based on URLs http://bit.ly/i8mYvi",
1695 +
      "id": 30018455189065728,
1696 +
      "from_user_id": 17489366,
1697 +
      "geo": null,
1698 +
      "iso_language_code": "en",
1699 +
      "to_user_id_str": null,
1700 +
      "source": "&lt;a href=&quot;http://twitterfeed.com&quot; rel=&quot;nofollow&quot;&gt;twitterfeed&lt;/a&gt;"
1701 +
    },
1702 +
    {
1703 +
      "from_user_id_str": "17489366",
1704 +
      "profile_image_url": "http://a3.twimg.com/sticky/default_profile_images/default_profile_2_normal.png",
1705 +
      "created_at": "Tue, 25 Jan 2011 21:45:31 +0000",
1706 +
      "from_user": "aapnoot",
1707 +
      "id_str": "30018452601180160",
1708 +
      "metadata": {
1709 +
        "result_type": "recent"
1710 +
      },
1711 +
      "to_user_id": null,
1712 +
      "text": "download 0.3.1.1, added by MagnusTherning: High-level file download based on URLs http://bit.ly/eHfiJB",
1713 +
      "id": 30018452601180160,
1714 +
      "from_user_id": 17489366,
1715 +
      "geo": null,
1716 +
      "iso_language_code": "en",
1717 +
      "to_user_id_str": null,
1718 +
      "source": "&lt;a href=&quot;http://twitterfeed.com&quot; rel=&quot;nofollow&quot;&gt;twitterfeed&lt;/a&gt;"
1719 +
    },
1720 +
    {
1721 +
      "from_user_id_str": "17671137",
1722 +
      "profile_image_url": "http://a2.twimg.com/profile_images/290264834/Haskell-logo-outer-glow_normal.png",
1723 +
      "created_at": "Tue, 25 Jan 2011 21:45:31 +0000",
1724 +
      "from_user": "Hackage",
1725 +
      "id_str": "30018451867176960",
1726 +
      "metadata": {
1727 +
        "result_type": "recent"
1728 +
      },
1729 +
      "to_user_id": null,
1730 +
      "text": "download 0.3.1, added by MagnusTherning: High-level file download based on URLs http://bit.ly/i8mYvi",
1731 +
      "id": 30018451867176960,
1732 +
      "from_user_id": 17671137,
1733 +
      "geo": null,
1734 +
      "iso_language_code": "en",
1735 +
      "to_user_id_str": null,
1736 +
      "source": "&lt;a href=&quot;http://twitterfeed.com&quot; rel=&quot;nofollow&quot;&gt;twitterfeed&lt;/a&gt;"
1737 +
    },
1738 +
    {
1739 +
      "from_user_id_str": "138502705",
1740 +
      "profile_image_url": "http://a1.twimg.com/profile_images/1083845614/yclogo_normal.gif",
1741 +
      "created_at": "Tue, 25 Jan 2011 21:45:04 +0000",
1742 +
      "from_user": "newsyc100",
1743 +
      "id_str": "30018340839755777",
1744 +
      "metadata": {
1745 +
        "result_type": "recent"
1746 +
      },
1747 +
      "to_user_id": null,
1748 +
      "text": "Haskell improves log processing 4x over Python http://devblog.bu.mp/haskell-at-bump (http://bit.ly/gQxxR8)",
1749 +
      "id": 30018340839755777,
1750 +
      "from_user_id": 138502705,
1751 +
      "geo": null,
1752 +
      "iso_language_code": "en",
1753 +
      "to_user_id_str": null,
1754 +
      "source": "&lt;a href=&quot;http://news.ycombinator.com&quot; rel=&quot;nofollow&quot;&gt;newsyc&lt;/a&gt;"
1755 +
    },
1756 +
    {
1757 +
      "from_user_id_str": "1578246",
1758 +
      "profile_image_url": "http://a0.twimg.com/profile_images/59312315/avatar_simpson_small_normal.jpg",
1759 +
      "created_at": "Tue, 25 Jan 2011 21:43:32 +0000",
1760 +
      "from_user": "magthe",
1761 +
      "id_str": "30017953801969665",
1762 +
      "metadata": {
1763 +
        "result_type": "recent"
1764 +
      },
1765 +
      "to_user_id": null,
1766 +
      "text": "New version of download uploaded to #hackage #haskell",
1767 +
      "id": 30017953801969665,
1768 +
      "from_user_id": 1578246,
1769 +
      "geo": null,
1770 +
      "iso_language_code": "en",
1771 +
      "to_user_id_str": null,
1772 +
      "source": "&lt;a href=&quot;http://api.supertweet.net&quot; rel=&quot;nofollow&quot;&gt;MyAuth API Proxy&lt;/a&gt;"
1773 +
    },
1774 +
    {
1775 +
      "from_user_id_str": "135838970",
1776 +
      "profile_image_url": "http://a2.twimg.com/profile_images/1079929891/logo_normal.png",
1777 +
      "created_at": "Tue, 25 Jan 2011 21:37:51 +0000",
1778 +
      "from_user": "reward999",
1779 +
      "id_str": "30016525180084224",
1780 +
      "metadata": {
1781 +
        "result_type": "recent"
1782 +
      },
1783 +
      "to_user_id": null,
1784 +
      "text": "Found Great Dane (Main &amp; Haskell- Dallas): We found a great dane. 214-712-0000 http://bit.ly/fQ8iBw",
1785 +
      "id": 30016525180084224,
1786 +
      "from_user_id": 135838970,
1787 +
      "geo": null,
1788 +
      "iso_language_code": "en",
1789 +
      "to_user_id_str": null,
1790 +
      "source": "&lt;a href=&quot;http://twitterfeed.com&quot; rel=&quot;nofollow&quot;&gt;twitterfeed&lt;/a&gt;"
1791 +
    },
1792 +
    {
1793 +
      "from_user_id_str": "137719265",
1794 +
      "profile_image_url": "http://a2.twimg.com/profile_images/1092224079/8__4__normal.jpg",
1795 +
      "created_at": "Tue, 25 Jan 2011 21:34:22 +0000",
1796 +
      "from_user": "WeiMatas",
1797 +
      "id_str": "30015646020411392",
1798 +
      "metadata": {
1799 +
        "result_type": "recent"
1800 +
      },
1801 +
      "to_user_id": null,
1802 +
      "text": "Fourth day Rez party Eddie Haskell County in second life – which took place in cabaret Tadd",
1803 +
      "id": 30015646020411392,
1804 +
      "from_user_id": 137719265,
1805 +
      "geo": null,
1806 +
      "iso_language_code": "en",
1807 +
      "to_user_id_str": null,
1808 +
      "source": "&lt;a href=&quot;http://dlvr.it&quot; rel=&quot;nofollow&quot;&gt;dlvr.it&lt;/a&gt;"
1809 +
    },
1810 +
    {
1811 +
      "from_user_id_str": "144546280",
1812 +
      "profile_image_url": "http://a1.twimg.com/a/1295051201/images/default_profile_1_normal.png",
1813 +
      "created_at": "Tue, 25 Jan 2011 21:33:21 +0000",
1814 +
      "from_user": "listwarenet",
1815 +
      "id_str": "30015392571195392",
1816 +
      "metadata": {
1817 +
        "result_type": "recent"
1818 +
      },
1819 +
      "to_user_id": null,
1820 +
      "text": "http://www.listware.net/201101/haskell-cafe/83889-haskell-cafe-gpl-license-of-h-matrix-and-prelude-numeric.html Haskell-cafe -",
1821 +
      "id": 30015392571195392,
1822 +
      "from_user_id": 144546280,
1823 +
      "geo": null,
1824 +
      "iso_language_code": "no",
1825 +
      "to_user_id_str": null,
1826 +
      "source": "&lt;a href=&quot;http://1e10.org/cloud/&quot; rel=&quot;nofollow&quot;&gt;1e10&lt;/a&gt;"
1827 +
    }
1828 +
  ],
1829 +
  "max_id": 30121530767708160,
1830 +
  "since_id": 0,
1831 +
  "refresh_url": "?since_id=30121530767708160&q=haskell",
1832 +
  "next_page": "?page=2&max_id=30121530767708160&rpp=100&q=haskell",
1833 +
  "results_per_page": 100,
1834 +
  "page": 1,
1835 +
  "completed_in": 1.195569,
1836 +
  "since_id_str": "0",
1837 +
  "max_id_str": "30121530767708160",
1838 +
  "query": "haskell",
1839 +
  "success": true
1840 +
}
syntaxe/src/lib.rs added +24 -0
1 +
#![warn(missing_docs)]
2 +
#![allow(clippy::type_complexity)]
3 +
4 +
//! Memoir is a library of self-describing, reflective parser-combinators.
5 +
//! Parsers are represented as reified objects that can print themselves
6 +
//! as documentation.
7 +
//!
8 +
//! For most purposes, syntaxe's *prelude* should be imported.
9 +
//!
10 +
//! ```
11 +
//! use syntaxe::*;
12 +
//!
13 +
//! let parser =
14 +
//!     string("set").then(optional(symbol('!')))
15 +
//!     .then(whitespace())
16 +
//!     .then(string("on").or(string("off")));
17 +
//!
18 +
//! assert!(parser.parse("set on").is_ok());
19 +
//! ```
20 +
pub mod parsers;
21 +
pub mod prelude;
22 +
pub mod result;
23 +
24 +
pub use parsers::*;
syntaxe/src/parsers.rs added +1310 -0
1 +
//! Core parser types.
2 +
use std::fmt;
3 +
use std::iter::FromIterator;
4 +
use std::marker::PhantomData;
5 +
use std::num::{ParseFloatError, ParseIntError};
6 +
use std::ops::Deref;
7 +
use std::rc::Rc;
8 +
use std::str;
9 +
10 +
use crate::result::{Cursor, Error, ErrorKind, Result};
11 +
12 +
/// Either left or right. Used for parsers that can return
13 +
/// either of two types of output.
14 +
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
15 +
pub enum Either<L, R> {
16 +
    /// The left case.
17 +
    Left(L),
18 +
    /// The right case.
19 +
    Right(R),
20 +
}
21 +
22 +
/// A self-describing parser combinator.
23 +
pub trait Parser<'a> {
24 +
    /// The output of the parser, in case of success.
25 +
    type Output;
26 +
27 +
    /// Parse from the given [`Cursor`].
28 +
    fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output>;
29 +
30 +
    /// Parse an input string and return a result. On success, returns an output, and any leftover
31 +
    /// input. Otherwise, returns an error.
32 +
    fn parse(&self, input: &'a str) -> std::result::Result<(Self::Output, &'a str), Error<'a>> {
33 +
        self.parse_at(Cursor::from(input))
34 +
            .map(|(out, rest)| (out, rest.input))
35 +
    }
36 +
37 +
    /// Convert this parser into a boxed trait object.
38 +
    ///
39 +
    /// This is useful when you need to store parsers of different concrete types
40 +
    /// in the same collection, or return different parser implementations from a function.
41 +
    ///
42 +
    /// ```
43 +
    /// use syntaxe::prelude::*;
44 +
    ///
45 +
    /// let parsers: Vec<Box<dyn Parser<Output = char>>> = vec![
46 +
    ///     symbol('!').boxed(),
47 +
    ///     symbol('?').boxed(),
48 +
    /// ];
49 +
    /// ```
50 +
    fn boxed(self) -> Box<dyn Parser<'a, Output = Self::Output>>
51 +
    where
52 +
        Self: Sized + 'static,
53 +
    {
54 +
        Box::new(self)
55 +
    }
56 +
57 +
    /// Sequence this parser with the next one.
58 +
    ///
59 +
    /// ```
60 +
    /// use syntaxe::*;
61 +
    ///
62 +
    /// let p = string("moo").then(symbol('!')).then(symbol('?'));
63 +
    /// assert!(p.parse("moo!?").is_ok());
64 +
    /// ```
65 +
    fn then<P: Parser<'a>>(self, next: P) -> (Self, P)
66 +
    where
67 +
        Self: Sized,
68 +
    {
69 +
        (self, next)
70 +
    }
71 +
72 +
    /// Apply this parser, then try to apply the other parser.
73 +
    /// Only the output from this parser is returned.
74 +
    ///
75 +
    /// ```
76 +
    /// use syntaxe::prelude::*;
77 +
    ///
78 +
    /// let p = symbol('X').skip(symbol('Y')).then(symbol('Z'));
79 +
    ///
80 +
    /// assert_eq!(p.parse("XYZ"), Ok((('X', 'Z'), "")));
81 +
    /// assert!(p.parse("XZ").is_err());
82 +
    ///
83 +
    /// let p = symbol('X').skip(optional(symbol('Y'))).then(symbol('Z'));
84 +
    ///
85 +
    /// assert_eq!(p.parse("XYZ"), Ok((('X', 'Z'), "")));
86 +
    /// assert_eq!(p.parse("XZ"), Ok((('X', 'Z'), "")));
87 +
    /// ```
88 +
    fn skip<P: Parser<'a>>(self, skip: P) -> impl Parser<'a, Output = Self::Output>
89 +
    where
90 +
        Self: Sized,
91 +
    {
92 +
        move |input| {
93 +
            let (out, rest) = self.parse_at(input)?;
94 +
            skip.parse_at(rest).map(|(_, skipped)| (out, skipped))
95 +
        }
96 +
    }
97 +
98 +
    /// If this parser fails, try another one.
99 +
    ///
100 +
    /// ```
101 +
    /// use syntaxe::prelude::*;
102 +
    ///
103 +
    /// let p = symbol('!').or(symbol('?'));
104 +
    ///
105 +
    /// assert_eq!(p.parse("?"), Ok(('?', "")));
106 +
    /// ```
107 +
    fn or<P: Parser<'a, Output = Self::Output>>(
108 +
        self,
109 +
        other: P,
110 +
    ) -> impl Parser<'a, Output = Self::Output>
111 +
    where
112 +
        Self: Sized,
113 +
    {
114 +
        move |input| match self.parse_at(input) {
115 +
            Ok(result) => Ok(result),
116 +
            Err(_) => other.parse_at(input),
117 +
        }
118 +
    }
119 +
120 +
    /// Modify the parser output if it succeeds, with the provided function.
121 +
    ///
122 +
    /// ```
123 +
    /// use syntaxe::prelude::*;
124 +
    ///
125 +
    /// let p = symbol('X').map(|out| (out, out));
126 +
    ///
127 +
    /// assert_eq!(p.parse("X"), Ok((('X', 'X'), "")));
128 +
    /// ```
129 +
    fn map<F, O>(self, f: F) -> Map<Self, F>
130 +
    where
131 +
        Self: Sized,
132 +
        F: Fn(Self::Output) -> O,
133 +
    {
134 +
        Map { parser: self, f }
135 +
    }
136 +
137 +
    /// Modify the parser output if it succeeds, with the provided fallible function.
138 +
    ///
139 +
    /// ```
140 +
    /// use std::io;
141 +
    /// use syntaxe::prelude::*;
142 +
    ///
143 +
    /// let p = symbol('X').try_map::<String, _>(|out|
144 +
    ///     Err(io::Error::new(io::ErrorKind::Other, format!("failed to parse {out:?}")))
145 +
    /// );
146 +
    /// assert!(p.parse("X").is_err())
147 +
    /// ```
148 +
    fn try_map<O, E>(
149 +
        self,
150 +
        f: impl Fn(Self::Output) -> std::result::Result<O, E>,
151 +
    ) -> impl Parser<'a, Output = O>
152 +
    where
153 +
        E: std::error::Error + 'static,
154 +
        Self: Sized,
155 +
    {
156 +
        move |cursor| {
157 +
            self.parse_at(cursor).and_then(|(out, rest)| match f(out) {
158 +
                Ok(result) => Ok((result, rest)),
159 +
                Err(e) => Err(Error::new(ErrorKind::TryMap(Rc::new(e)), cursor)),
160 +
            })
161 +
        }
162 +
    }
163 +
164 +
    /// Modify the parser output if it succeeds, with the provided value.
165 +
    ///
166 +
    /// ```
167 +
    /// use syntaxe::*;
168 +
    ///
169 +
    /// let p = symbol('X').value('Y');
170 +
    ///
171 +
    /// assert_eq!(p.parse("X"), Ok(('Y', "")));
172 +
    /// ```
173 +
    fn value<V: Clone>(self, val: V) -> impl Parser<'a, Output = V>
174 +
    where
175 +
        Self: Sized,
176 +
    {
177 +
        self.map(move |_| val.clone())
178 +
    }
179 +
180 +
    /// Provide a custom error message in case this parser fails.
181 +
    /// This is useful for more complex parsers, or when the default error is not adequate.
182 +
    fn with_err(self, err: ErrorKind<'a>) -> impl Parser<'a, Output = Self::Output>
183 +
    where
184 +
        Self: Sized,
185 +
    {
186 +
        move |cursor| self.parse_at(cursor).map_err(|e| Error::new(err.clone(), e.cursor))
187 +
    }
188 +
189 +
    /// Try to convert the output of the parser from a string to the specified type.
190 +
    ///
191 +
    /// ```
192 +
    /// use syntaxe::prelude::*;
193 +
    ///
194 +
    /// let p = many::<_, String>(digit()).from_str::<u64>();
195 +
    ///
196 +
    /// assert_eq!(p.parse("12345"), Ok((12345, "")));
197 +
    /// assert!(p.parse("abcde").is_err());
198 +
    ///
199 +
    /// ```
200 +
    #[allow(clippy::wrong_self_convention)]
201 +
    fn from_str<O>(self) -> FromStr<Self, O>
202 +
    where
203 +
        Self: Sized,
204 +
    {
205 +
        FromStr(self, PhantomData)
206 +
    }
207 +
208 +
    /// Fail this parser if the predicate fails.
209 +
    ///
210 +
    /// ```
211 +
    /// use syntaxe::*;
212 +
    ///
213 +
    /// let p = string("moo").followed_by(symbol('.'));
214 +
    /// assert_eq!(p.parse("moo."), Ok(("moo", ".")));
215 +
    /// assert!(p.parse("moo").is_err());
216 +
    /// ```
217 +
    fn followed_by<P>(self, next: P) -> impl Parser<'a, Output = Self::Output>
218 +
    where
219 +
        P: Parser<'a>,
220 +
        Self: Sized,
221 +
    {
222 +
        self.skip(peek(next))
223 +
    }
224 +
225 +
    /// Applies the parser at least once, separating subsequent applications
226 +
    /// with a separator.
227 +
    ///
228 +
    /// ```
229 +
    /// use syntaxe::*;
230 +
    ///
231 +
    /// let p = natural().delimited_by(symbol(','));
232 +
    /// assert_eq!(p.parse("1,2,3,4"), Ok((vec![1, 2, 3, 4], "")));
233 +
    /// assert_eq!(p.parse("2"), Ok((vec![2], "")));
234 +
    /// assert_eq!(p.parse(""), Ok((vec![], "")));
235 +
    /// assert!(p.parse("1,").is_err());
236 +
    ///
237 +
    /// let p = natural().delimited_by(spaces1());
238 +
    /// assert_eq!(p.parse("1 2 3 4"), Ok((vec![1, 2, 3, 4], "")));
239 +
    /// ```
240 +
    fn delimited_by<S>(self, separator: S) -> impl Parser<'a, Output = Vec<Self::Output>>
241 +
    where
242 +
        S: Parser<'a>,
243 +
        Self: Sized,
244 +
    {
245 +
        move |cursor| {
246 +
            // Parse first element if it exists.
247 +
            let Ok((item, mut cursor)) = self.parse_at(cursor) else {
248 +
                return Ok((Vec::new(), cursor));
249 +
            };
250 +
            let mut results = vec![item];
251 +
252 +
            // Keep parsing separator plus item pairs.
253 +
            while let Ok((_, rest)) = separator.parse_at(cursor) {
254 +
                let (item, rest) = self.parse_at(rest)?;
255 +
256 +
                results.push(item);
257 +
                cursor = rest;
258 +
            }
259 +
            Ok((results, cursor))
260 +
        }
261 +
    }
262 +
}
263 +
264 +
impl<'a, O> Parser<'a> for Box<dyn Parser<'a, Output = O>> {
265 +
    type Output = O;
266 +
267 +
    fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output> {
268 +
        self.deref().parse_at(input)
269 +
    }
270 +
}
271 +
272 +
impl<'a, F, O> Parser<'a> for F
273 +
where
274 +
    F: Fn(Cursor<'a>) -> Result<'a, O>,
275 +
{
276 +
    type Output = O;
277 +
278 +
    fn parse_at(&self, input: Cursor<'a>) -> Result<'a, O> {
279 +
        self(input)
280 +
    }
281 +
}
282 +
283 +
impl<'a> Parser<'a> for char {
284 +
    type Output = char;
285 +
286 +
    fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output> {
287 +
        Symbol(*self).parse_at(input)
288 +
    }
289 +
}
290 +
291 +
/// Applies the first parser and if it succeeds, the second.
292 +
impl<'a, P, Q> Parser<'a> for (P, Q)
293 +
where
294 +
    P: Parser<'a>,
295 +
    Q: Parser<'a>,
296 +
{
297 +
    type Output = (P::Output, Q::Output);
298 +
299 +
    fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output> {
300 +
        self.0
301 +
            .parse_at(input)
302 +
            .and_then(|(out0, rest)| self.1.parse_at(rest).map(|(out1, rest)| ((out0, out1), rest)))
303 +
    }
304 +
}
305 +
306 +
/// A parser that converts its output from a string.
307 +
#[derive(Copy)]
308 +
pub struct FromStr<P, O>(P, PhantomData<O>);
309 +
impl<'a, P, O, S, E> Parser<'a> for FromStr<P, O>
310 +
where
311 +
    P: Parser<'a, Output = S>,
312 +
    S: AsRef<str>,
313 +
    O: str::FromStr<Err = E>,
314 +
    E: std::error::Error + 'static,
315 +
{
316 +
    type Output = O;
317 +
318 +
    fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output> {
319 +
        match self.0.parse_at(input) {
320 +
            Ok((out, rest)) => match out.as_ref().parse::<O>() {
321 +
                Ok(o) => Ok((o, rest)),
322 +
                Err(e) => Err(Error::new(ErrorKind::FromStr(Rc::new(e)), rest)),
323 +
            },
324 +
            Err(err) => Err(err),
325 +
        }
326 +
    }
327 +
}
328 +
329 +
impl<P: Clone, O> Clone for FromStr<P, O> {
330 +
    fn clone(&self) -> Self {
331 +
        Self(self.0.clone(), self.1)
332 +
    }
333 +
}
334 +
335 +
/// A parser that applies a mapping function to transform its output.
336 +
#[derive(Clone)]
337 +
pub struct Map<P, F> {
338 +
    parser: P,
339 +
    f: F,
340 +
}
341 +
342 +
impl<'a, P, F, O> Parser<'a> for Map<P, F>
343 +
where
344 +
    P: Parser<'a>,
345 +
    F: Fn(P::Output) -> O,
346 +
{
347 +
    type Output = O;
348 +
349 +
    fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output> {
350 +
        self.parser.parse_at(input).map(|(out, rest)| ((self.f)(out), rest))
351 +
    }
352 +
}
353 +
354 +
/// Try two different parsers and return either result.
355 +
/// Returns the first successful parse as `Either::Left`, or the second as `Either::Right`.
356 +
///
357 +
/// ```
358 +
/// use syntaxe::prelude::*;
359 +
///
360 +
/// let p = either(float(), natural());
361 +
///
362 +
/// assert_eq!(p.parse("42"), Ok((Either::Right(42), "")));
363 +
/// assert_eq!(p.parse("42.912"), Ok((Either::Left(42.912), "")));
364 +
/// ```
365 +
pub fn either<'a, L, R>(left: L, right: R) -> impl Parser<'a, Output = Either<L::Output, R::Output>>
366 +
where
367 +
    L: Parser<'a>,
368 +
    R: Parser<'a>,
369 +
{
370 +
    move |input| {
371 +
        if let Ok((out, rest)) = left.parse_at(input) {
372 +
            Ok((Either::Left(out), rest))
373 +
        } else {
374 +
            match right.parse_at(input) {
375 +
                Ok((out, rest)) => Ok((Either::Right(out), rest)),
376 +
                Err(err) => Err(err),
377 +
            }
378 +
        }
379 +
    }
380 +
}
381 +
382 +
/// Parses if the predicate returns `true` on the input's next `char`.
383 +
#[derive(Clone)]
384 +
pub struct Satisfy(fn(&char) -> bool);
385 +
impl<'a> Parser<'a> for Satisfy {
386 +
    type Output = char;
387 +
388 +
    fn parse_at(&self, cursor: Cursor<'a>) -> Result<'a, Self::Output> {
389 +
        let predicate = &self.0;
390 +
391 +
        match cursor.input.chars().next() {
392 +
            Some(c) if predicate(&c) => Ok((c, cursor.advance(c.len_utf8()))),
393 +
            Some(c) => Err(Error::new(ErrorKind::UnexpectedChar(c), cursor)),
394 +
            None => Err(Error::new(ErrorKind::UnexpectedEof, cursor)),
395 +
        }
396 +
    }
397 +
}
398 +
399 +
/// Tries to parse a single character.
400 +
#[derive(Clone, Debug)]
401 +
pub struct Symbol(char);
402 +
impl<'a> Parser<'a> for Symbol {
403 +
    type Output = char;
404 +
405 +
    fn parse_at(&self, cursor: Cursor<'a>) -> Result<'a, Self::Output> {
406 +
        match cursor.input.chars().next() {
407 +
            Some(c) if c == self.0 => Ok((c, cursor.advance(c.len_utf8()))),
408 +
            _ => Err(Error::new(ErrorKind::ExpectedChar(self.0), cursor)),
409 +
        }
410 +
    }
411 +
}
412 +
413 +
impl fmt::Display for Symbol {
414 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
415 +
        write!(f, "'{}'", self.0)
416 +
    }
417 +
}
418 +
419 +
/// Parse a string literal.
420 +
#[derive(Clone, Debug)]
421 +
pub struct Keyword<'a>(&'a str);
422 +
impl<'a> Parser<'a> for Keyword<'a> {
423 +
    type Output = &'a str;
424 +
425 +
    fn parse_at(&self, cursor: Cursor<'a>) -> Result<'a, Self::Output> {
426 +
        match cursor.input.get(..self.0.len()) {
427 +
            Some(word) if word == self.0 => Ok((word, cursor.advance(word.len()))),
428 +
            _ => Err(Error::new(ErrorKind::ExpectedString(self.0), cursor)),
429 +
        }
430 +
    }
431 +
}
432 +
433 +
impl fmt::Display for Keyword<'_> {
434 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
435 +
        write!(f, "\"{}\"", self.0)
436 +
    }
437 +
}
438 +
439 +
impl From<char> for Symbol {
440 +
    fn from(c: char) -> Self {
441 +
        symbol(c)
442 +
    }
443 +
}
444 +
445 +
/// Fail with a message.
446 +
///
447 +
/// ```
448 +
/// use syntaxe::*;
449 +
/// use syntaxe::result::{Location, Error};
450 +
///
451 +
/// let parser = symbol('!').or(fail("only `!` is allowed"));
452 +
/// let err = parser.parse("?").unwrap_err();
453 +
///
454 +
/// assert_eq!(err.to_string(), "only `!` is allowed");
455 +
/// ```
456 +
pub fn fail<'a, S: Into<Rc<str>>, U>(err: S) -> impl Parser<'a, Output = U> {
457 +
    let err = err.into();
458 +
    move |cursor: Cursor<'a>| Err(Error::new(ErrorKind::Custom(err.clone()), cursor))
459 +
}
460 +
461 +
/// Call the given predicate on the next character. If it returns `true`,
462 +
/// consume the character.
463 +
/// Create a parser that matches a single character if it satisfies the predicate function.
464 +
///
465 +
/// ```
466 +
/// use syntaxe::prelude::*;
467 +
///
468 +
/// let parser = satisfy(|c| c.is_ascii_uppercase());
469 +
/// assert_eq!(parser.parse("ABC"), Ok(('A', "BC")));
470 +
/// assert!(parser.parse("abc").is_err());
471 +
/// ```
472 +
pub fn satisfy(predicate: fn(&char) -> bool) -> Satisfy {
473 +
    Satisfy(predicate)
474 +
}
475 +
476 +
/// Apply *open*, then *between*, then *close*.
477 +
///
478 +
/// ```
479 +
/// use syntaxe::*;
480 +
///
481 +
/// let parser = between(symbol('{'), symbol('}'), any::<_, String>(letter()));
482 +
///
483 +
/// assert!(parser.parse("{acme}").is_ok());
484 +
/// assert_eq!(parser.parse("{acme}"), Ok(("acme".to_owned(), "")));
485 +
/// ```
486 +
/// Parse content between opening and closing delimiters.
487 +
///
488 +
/// ```
489 +
/// use syntaxe::prelude::*;
490 +
///
491 +
/// let parser = between(symbol('['), symbol(']'), many::<_, String>(letter()));
492 +
/// assert_eq!(parser.parse("[hello]"), Ok(("hello".to_string(), "")));
493 +
/// assert!(parser.parse("[123]").is_err());
494 +
/// ```
495 +
pub fn between<'a, P, R, Q, O>(open: P, close: R, between: Q) -> impl Parser<'a, Output = O>
496 +
where
497 +
    P: Parser<'a>,
498 +
    R: Parser<'a>,
499 +
    Q: Parser<'a, Output = O>,
500 +
{
501 +
    open.then(between).then(close).map(|((_, body), _)| body)
502 +
}
503 +
504 +
/// Try to apply a parser, returning None if it fails without consuming input.
505 +
///
506 +
/// ```
507 +
/// use syntaxe::*;
508 +
///
509 +
/// let p = optional(symbol('!'));
510 +
/// assert_eq!(p.parse("!"), Ok((Some('!'), "")));
511 +
/// assert_eq!(p.parse("?"), Ok((None, "?")));
512 +
/// assert_eq!(p.parse(""), Ok((None, "")));
513 +
/// ```
514 +
pub fn optional<'a, O: 'a, P>(parser: P) -> impl Parser<'a, Output = Option<P::Output>>
515 +
where
516 +
    P: Parser<'a, Output = O>,
517 +
{
518 +
    move |input| match parser.parse_at(input) {
519 +
        Ok((out, rest)) => Ok((Some(out), rest)),
520 +
        Err(_) => Ok((None, input)),
521 +
    }
522 +
}
523 +
524 +
/// Apply the parser until the other parser succeeds.
525 +
///
526 +
/// ```
527 +
/// use syntaxe::*;
528 +
///
529 +
/// let p = until(symbol('!'));
530 +
/// let (out, rest) = p.parse("Hello World!").unwrap();
531 +
///
532 +
/// assert_eq!(out, "Hello World");
533 +
/// assert_eq!(rest, "!");
534 +
///
535 +
/// assert!(p.parse("!").is_ok());
536 +
/// assert!(p.parse("Hello World").is_err());
537 +
/// ```
538 +
pub fn until<'a, P>(parser: P) -> impl Parser<'a, Output = &'a str>
539 +
where
540 +
    P: Parser<'a>,
541 +
{
542 +
    move |mut cursor: Cursor<'a>| -> Result<'a, &'a str> {
543 +
        let input = cursor.input;
544 +
        let mut chars = input.chars();
545 +
        let mut error;
546 +
547 +
        loop {
548 +
            match parser.parse_at(cursor) {
549 +
                Ok((_, _)) => return Ok((&input[..cursor.location.index], cursor)),
550 +
                Err(e) => error = e,
551 +
            }
552 +
            if let Some(c) = chars.next() {
553 +
                cursor = cursor.advance(c.len_utf8());
554 +
            } else {
555 +
                break;
556 +
            }
557 +
        }
558 +
        Err(error)
559 +
    }
560 +
}
561 +
562 +
/// Succeeds when the input is empty.
563 +
///
564 +
/// ```
565 +
/// use syntaxe::prelude::*;
566 +
///
567 +
/// end().parse("").is_ok();
568 +
/// end().parse("#").is_err();
569 +
///
570 +
/// let (out, rest) = until(end()).parse("Hello World!").unwrap();
571 +
/// assert_eq!(out, String::from("Hello World!"));
572 +
/// assert_eq!(rest, "");
573 +
/// ```
574 +
pub fn end<'a>() -> impl Parser<'a, Output = ()> {
575 +
    (|cursor: Cursor<'a>| {
576 +
        if cursor.input.is_empty() {
577 +
            Ok(((), cursor))
578 +
        } else {
579 +
            Err(Error::new(ErrorKind::ExpectedEof, cursor))
580 +
        }
581 +
    })
582 +
    .with_err(ErrorKind::ExpectedEof)
583 +
}
584 +
585 +
/// Parses a single character.
586 +
pub fn symbol(c: char) -> Symbol {
587 +
    Symbol(c)
588 +
}
589 +
590 +
/// Parses a single letter.
591 +
///
592 +
/// ```
593 +
/// use syntaxe::prelude::*;
594 +
///
595 +
/// let letter = satisfy(char::is_ascii_alphabetic);
596 +
/// ```
597 +
pub fn letter<'a>() -> impl Parser<'a, Output = char> {
598 +
    satisfy(char::is_ascii_alphabetic).with_err(ErrorKind::ExpectedOther("a-Z".into()))
599 +
}
600 +
601 +
/// Parses any character. Always succeeds.
602 +
/// Parse any single character.
603 +
///
604 +
/// ```
605 +
/// use syntaxe::prelude::*;
606 +
///
607 +
/// let parser = character();
608 +
/// assert_eq!(parser.parse("abc"), Ok(('a', "bc")));
609 +
/// assert_eq!(parser.parse("123"), Ok(('1', "23")));
610 +
/// assert!(parser.parse("").is_err());
611 +
/// ```
612 +
pub fn character<'a>() -> impl Parser<'a, Output = char> {
613 +
    satisfy(|_| true)
614 +
}
615 +
616 +
/// Applies the parser any number of times.
617 +
///
618 +
/// ```
619 +
/// use syntaxe::prelude::*;
620 +
///
621 +
/// let p = any(symbol('?'));
622 +
///
623 +
/// assert_eq!(p.parse("???"), Ok((String::from("???"), "")));
624 +
/// assert!(p.parse("").is_ok());
625 +
/// assert!(p.parse("?").is_ok());
626 +
/// assert!(p.parse("??????").is_ok());
627 +
/// ```
628 +
pub fn any<'a, P, U>(parser: P) -> Any<P, U>
629 +
where
630 +
    P: Parser<'a>,
631 +
{
632 +
    Any(parser, PhantomData)
633 +
}
634 +
635 +
/// Applies the underlying parser zero or more times. Never fails.
636 +
/// Returns the outputs as a vector.
637 +
#[derive(Debug)]
638 +
pub struct Any<P, O>(P, PhantomData<O>);
639 +
impl<'a, P, O> Parser<'a> for Any<P, O>
640 +
where
641 +
    P: 'a + Parser<'a>,
642 +
    O: 'a + FromIterator<P::Output> + Default + Extend<P::Output>,
643 +
{
644 +
    type Output = O;
645 +
646 +
    fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output> {
647 +
        let mut input = input;
648 +
        let mut outs = O::default();
649 +
650 +
        while let Ok((out, rest)) = self.0.parse_at(input) {
651 +
            outs.extend(std::iter::once(out));
652 +
            input = rest;
653 +
        }
654 +
        Ok((outs, input))
655 +
    }
656 +
}
657 +
658 +
impl<'a, P: Parser<'a> + Clone, O> Clone for Any<P, O> {
659 +
    fn clone(&self) -> Self {
660 +
        Self(self.0.clone(), self.1)
661 +
    }
662 +
}
663 +
664 +
/// Applies the parser one or more times.
665 +
///
666 +
/// ```
667 +
/// use syntaxe::*;
668 +
///
669 +
/// let p = many::<_, String>(symbol('!'));
670 +
///
671 +
/// assert!(p.parse("!").is_ok());
672 +
/// assert!(p.parse("!!").is_ok());
673 +
/// assert!(p.parse("!!!").is_ok());
674 +
/// assert!(p.parse("").is_err());
675 +
/// ```
676 +
pub fn many<'a, P, O>(parser: P) -> impl Parser<'a, Output = O> + 'a
677 +
where
678 +
    P: Parser<'a> + 'a,
679 +
    O: FromIterator<P::Output> + Default + Extend<P::Output> + 'a,
680 +
{
681 +
    move |input| {
682 +
        let mut input = input;
683 +
        let mut outs = O::default();
684 +
685 +
        let (out, rest) = parser.parse_at(input)?;
686 +
        outs.extend(std::iter::once(out));
687 +
        input = rest;
688 +
689 +
        while let Ok((out, rest)) = parser.parse_at(input) {
690 +
            outs.extend(std::iter::once(out));
691 +
            input = rest;
692 +
        }
693 +
        Ok((outs, input))
694 +
    }
695 +
}
696 +
697 +
/// Tries multiple parsers in sequence until one succeeds.
698 +
/// Returns the first successful parse result.
699 +
///
700 +
/// ```
701 +
/// use syntaxe::*;
702 +
///
703 +
/// let p = choice([symbol('?'), symbol('!'), symbol('.')]);
704 +
///
705 +
/// assert_eq!(p.parse("?").ok(), Some(('?', "")));
706 +
/// assert_eq!(p.parse("!").ok(), Some(('!', "")));
707 +
/// assert_eq!(p.parse(".").ok(), Some(('.', "")));
708 +
///
709 +
/// assert!(p.parse("@").is_err());
710 +
/// assert!(p.parse(",").is_err());
711 +
/// assert!(p.parse("").is_err());
712 +
/// ```
713 +
pub fn choice<'a, P: Parser<'a>>(
714 +
    parsers: impl IntoIterator<Item = P>,
715 +
) -> impl Parser<'a, Output = P::Output> {
716 +
    let parsers: Vec<P> = parsers.into_iter().collect();
717 +
718 +
    move |input| {
719 +
        let mut expected = Vec::new();
720 +
        for p in &parsers {
721 +
            match p.parse_at(input) {
722 +
                Ok(result) => return Ok(result),
723 +
                Err(e) => {
724 +
                    if let Some(exp) = e.expected() {
725 +
                        expected.push(exp)
726 +
                    }
727 +
                }
728 +
            }
729 +
        }
730 +
        Err(Error::new(ErrorKind::ExpectedOneOf(expected), input))
731 +
    }
732 +
}
733 +
734 +
/// Parses a string literal.
735 +
///
736 +
/// ```
737 +
/// use syntaxe::*;
738 +
/// use syntaxe::result::Error;
739 +
///
740 +
/// let p = string("set");
741 +
///
742 +
/// assert!(p.parse("set").is_ok());
743 +
/// assert!(p.parse("").is_err());
744 +
///
745 +
/// let err = p.parse("get").unwrap_err();
746 +
/// assert_eq!(err.to_string(), "expected `set`, got `get`");
747 +
///
748 +
/// let p = string("true").from_str::<bool>();
749 +
/// assert_eq!(p.parse("true!"), Ok((true, "!")));
750 +
/// ```
751 +
pub fn string(input: &str) -> Keyword<'_> {
752 +
    Keyword(input)
753 +
}
754 +
755 +
/// Optional whitespace.
756 +
///
757 +
/// ```
758 +
/// use syntaxe::*;
759 +
///
760 +
/// let p = whitespace();
761 +
///
762 +
/// assert!(p.parse(" ").is_ok());
763 +
/// assert!(p.parse("   ").is_ok());
764 +
/// assert!(p.parse("\t \t").is_ok());
765 +
/// assert!(p.parse("\n").is_ok());
766 +
/// assert!(p.parse("").is_ok());
767 +
/// ```
768 +
pub fn whitespace<'a>() -> impl Parser<'a, Output = &'a str> {
769 +
    take_while(char::is_ascii_whitespace)
770 +
}
771 +
772 +
/// Optional spaces.
773 +
///
774 +
/// ```
775 +
/// use syntaxe::*;
776 +
///
777 +
/// let p = spaces();
778 +
///
779 +
/// assert!(p.parse(" ").is_ok());
780 +
/// assert!(p.parse("   ").is_ok());
781 +
/// assert!(p.parse("\t").is_ok());
782 +
/// assert!(p.parse("").is_ok());
783 +
/// ```
784 +
pub fn spaces<'a>() -> impl Parser<'a, Output = &'a str> {
785 +
    take_while(|c| *c == ' ' || *c == '\t')
786 +
}
787 +
788 +
/// One or more horizontal spaces (space or tab).
789 +
///
790 +
/// ```
791 +
/// use syntaxe::*;
792 +
///
793 +
/// let p = spaces1();
794 +
///
795 +
/// assert!(p.parse(" ").is_ok());
796 +
/// assert!(p.parse("   ").is_ok());
797 +
/// assert!(p.parse("\t").is_ok());
798 +
/// assert!(p.parse("\t  ").is_ok());
799 +
/// assert!(p.parse("").is_err());
800 +
/// ```
801 +
pub fn spaces1<'a>() -> impl Parser<'a, Output = &'a str> {
802 +
    take_while1(|c| *c == ' ' || *c == '\t')
803 +
}
804 +
805 +
/// Parses a single line-feed token.
806 +
///
807 +
/// ```
808 +
/// use syntaxe::*;
809 +
///
810 +
/// let p = linebreaks();
811 +
/// assert_eq!(p.parse("\n"), Ok(("\n", "")));
812 +
/// assert_eq!(p.parse("\r\n"), Ok(("\r\n", "")));
813 +
/// ```
814 +
/// Parse zero or more vertical whitespace characters (newline or carriage return).
815 +
///
816 +
/// ```
817 +
/// use syntaxe::prelude::*;
818 +
///
819 +
/// let parser = linebreaks();
820 +
/// assert_eq!(parser.parse("\n\r\n"), Ok(("\n\r\n", "")));
821 +
/// assert_eq!(parser.parse("abc"), Ok(("", "abc")));
822 +
/// ```
823 +
pub fn linebreaks<'a>() -> impl Parser<'a, Output = &'a str> {
824 +
    take_while(|c| *c == '\n' || *c == '\r')
825 +
}
826 +
827 +
/// Parses a single base ten digit.
828 +
///
829 +
/// ```
830 +
/// use syntaxe::*;
831 +
///
832 +
/// let digit = satisfy(|c: &char| c.is_digit(10));
833 +
/// ```
834 +
pub fn digit<'a>() -> impl Parser<'a, Output = char> {
835 +
    satisfy(char::is_ascii_digit).with_err(ErrorKind::ExpectedOther("0-9".into()))
836 +
}
837 +
838 +
/// Unsigned decimal integer.
839 +
///
840 +
/// ```
841 +
/// use syntaxe::*;
842 +
///
843 +
/// let p = natural::<u64>();
844 +
///
845 +
/// assert!(p.parse("0").is_ok());
846 +
/// assert!(p.parse("123").is_ok());
847 +
/// assert!(p.parse("043").is_ok());
848 +
/// assert!(p.parse("-55").is_err());
849 +
/// ```
850 +
pub fn natural<'a, O>() -> impl Parser<'a, Output = O>
851 +
where
852 +
    O: str::FromStr<Err = ParseIntError> + 'a,
853 +
{
854 +
    repeat(digit()).from_str::<O>()
855 +
}
856 +
857 +
/// Unsigned floating point number.
858 +
///
859 +
/// ```
860 +
/// use syntaxe::*;
861 +
///
862 +
/// let p = float::<f64>();
863 +
///
864 +
/// assert!(p.parse("123.456").is_ok());
865 +
/// assert!(p.parse(".42").is_ok());
866 +
/// assert!(p.parse("0").is_err());
867 +
/// assert!(p.parse("42").is_err());
868 +
/// assert!(p.parse("42.").is_err());
869 +
/// assert!(p.parse("-1.23").is_err());
870 +
/// ```
871 +
pub fn float<'a, O>() -> impl Parser<'a, Output = O>
872 +
where
873 +
    O: str::FromStr<Err = ParseFloatError> + 'a,
874 +
{
875 +
    let whole = repeat(digit());
876 +
    let fract = repeat(digit());
877 +
878 +
    (optional(whole).then(symbol('.')).then(fract))
879 +
        .map(|((w, _), d)| match w {
880 +
            Some(w) => format!("{}.{}", w, d),
881 +
            None => format!("0.{}", d),
882 +
        })
883 +
        .from_str::<O>()
884 +
}
885 +
886 +
/// Makes a parser accept an optional sign prefix.
887 +
///
888 +
/// ```
889 +
/// use syntaxe::*;
890 +
///
891 +
/// let p = signed(float::<f64>());
892 +
/// assert_eq!(p.parse("42.019"), Ok((42.019, "")));
893 +
/// assert_eq!(p.parse("-4.23"), Ok((-4.23, "")));
894 +
/// assert_eq!(p.parse("+4.23"), Ok((4.23, "")));
895 +
///
896 +
/// let p = signed(natural::<i64>());
897 +
/// assert_eq!(p.parse("42"), Ok((42, "")));
898 +
/// assert_eq!(p.parse("-42"), Ok((-42, "")));
899 +
/// assert_eq!(p.parse("+42"), Ok((42, "")));
900 +
/// ```
901 +
pub fn signed<'a, P, O>(parser: P) -> impl Parser<'a, Output = O>
902 +
where
903 +
    P: Parser<'a, Output = O>,
904 +
    O: std::ops::Neg<Output = O> + 'a,
905 +
{
906 +
    let sign = optional(symbol('-').or(symbol('+')));
907 +
908 +
    sign.then(parser).map(|(s, n)| match s {
909 +
        Some('-') => -n,
910 +
        _ => n,
911 +
    })
912 +
}
913 +
914 +
/// Apply the given parser, and if it fails, don't consume any input.
915 +
///
916 +
/// ```
917 +
/// use syntaxe::*;
918 +
///
919 +
/// let p = choice([
920 +
///     peek(string("leave").skip(whitespace()).then(string("england"))),
921 +
///     peek(string("leave").skip(whitespace()).then(string("france"))),
922 +
/// ]);
923 +
///
924 +
/// assert!(p.parse("leave england").is_ok());
925 +
/// assert!(p.parse("leave france").is_ok());
926 +
/// ```
927 +
pub fn peek<'a, P: Parser<'a>>(parser: P) -> impl Parser<'a, Output = P::Output> {
928 +
    move |input| match parser.parse_at(input) {
929 +
        Ok((out, _)) => Ok((out, input)),
930 +
        Err(err) => Err(err),
931 +
    }
932 +
}
933 +
934 +
/// Repeatedly apply a parser until it fails, returning the concatenated string of all matches.
935 +
/// Returns an error if the first application fails.
936 +
///
937 +
/// ```
938 +
/// use syntaxe::*;
939 +
///
940 +
/// let p = repeat(letter());
941 +
/// let (out, rest) = p.parse("Bazinga!").unwrap();
942 +
///
943 +
/// assert_eq!(out, "Bazinga");
944 +
/// assert_eq!(rest, "!");
945 +
///
946 +
/// assert!(p.parse("!").is_err());
947 +
/// ```
948 +
pub fn repeat<'a, P>(parser: P) -> impl Parser<'a, Output = &'a str>
949 +
where
950 +
    P: Parser<'a> + 'a,
951 +
{
952 +
    move |cursor: Cursor<'a>| -> Result<'a, &'a str> {
953 +
        let input = cursor.input;
954 +
        let (_, mut cursor) = parser.parse_at(cursor)?;
955 +
956 +
        while let Ok((_, rest)) = parser.parse_at(cursor) {
957 +
            cursor = rest;
958 +
        }
959 +
        let len = input.len() - cursor.input.len();
960 +
961 +
        Ok((&input[..len], cursor))
962 +
    }
963 +
}
964 +
965 +
/// Parse characters as long as they match the predicate function.
966 +
/// Returns all matching characters as a string slice.
967 +
/// Returns an empty string if no characters match.
968 +
///
969 +
/// ```
970 +
/// use syntaxe::prelude::*;
971 +
///
972 +
/// let parser = take_while(|c| c.is_ascii_digit());
973 +
/// assert_eq!(parser.parse("123abc"), Ok(("123", "abc")));
974 +
/// assert_eq!(parser.parse("abc"), Ok(("", "abc"))); // No match returns empty string
975 +
/// ```
976 +
pub fn take_while<'a, F: Fn(&char) -> bool>(pred: F) -> impl Parser<'a, Output = &'a str> {
977 +
    move |cursor: Cursor<'a>| {
978 +
        let input = cursor.input;
979 +
        let mut len = 0;
980 +
981 +
        for c in input.chars() {
982 +
            if !pred(&c) {
983 +
                break;
984 +
            }
985 +
            len += c.len_utf8();
986 +
        }
987 +
        Ok((&input[..len], cursor.advance(len)))
988 +
    }
989 +
}
990 +
991 +
/// Like [`take_while`], but requires at least one matching character.
992 +
/// Parse one or more characters matching a predicate.
993 +
/// Returns an error if no characters match.
994 +
///
995 +
/// ```
996 +
/// use syntaxe::prelude::*;
997 +
///
998 +
/// let parser = take_while1(|c| c.is_ascii_digit());
999 +
/// assert_eq!(parser.parse("123abc"), Ok(("123", "abc")));
1000 +
/// assert!(parser.parse("abc").is_err());
1001 +
/// ```
1002 +
pub fn take_while1<'a, F: Fn(&char) -> bool + Copy + 'static>(
1003 +
    pred: F,
1004 +
) -> impl Parser<'a, Output = &'a str> {
1005 +
    move |cursor: Cursor<'a>| {
1006 +
        let Some(c) = cursor.input.chars().next() else {
1007 +
            return Err(Error::new(ErrorKind::UnexpectedEof, cursor));
1008 +
        };
1009 +
        if !pred(&c) {
1010 +
            return Err(Error::new(ErrorKind::UnexpectedChar(c), cursor));
1011 +
        }
1012 +
        take_while(pred).parse_at(cursor)
1013 +
    }
1014 +
}
1015 +
1016 +
/// Parse characters until one matches the predicate function.
1017 +
/// Returns all non-matching characters as a string slice.
1018 +
/// Returns an error if the input is empty or if no terminating character is found.
1019 +
///
1020 +
/// ```
1021 +
/// use syntaxe::prelude::*;
1022 +
///
1023 +
/// let parser = take_until(|c| c == '.');
1024 +
/// assert_eq!(parser.parse("abc.def"), Ok(("abc", ".def")));
1025 +
/// assert!(parser.parse("abc").is_err()); // No terminator found
1026 +
/// ```
1027 +
pub fn take_until<'a, F: Fn(char) -> bool + Copy + 'static>(
1028 +
    term: F,
1029 +
) -> impl Parser<'a, Output = &'a str> {
1030 +
    move |cursor: Cursor<'a>| {
1031 +
        let input = cursor.input;
1032 +
        let mut len = 0;
1033 +
1034 +
        for c in input.chars() {
1035 +
            if term(c) {
1036 +
                return Ok((&input[..len], cursor.advance(len)));
1037 +
            }
1038 +
            len += c.len_utf8();
1039 +
        }
1040 +
        Err(Error::new(ErrorKind::UnexpectedEof, cursor.advance(len)))
1041 +
    }
1042 +
}
1043 +
1044 +
/// Takes the rest of the input as a string slice.
1045 +
/// Always succeeds.
1046 +
///
1047 +
/// ```
1048 +
/// use syntaxe::prelude::*;
1049 +
///
1050 +
/// let parser = take_str();
1051 +
/// assert_eq!(parser.parse("hello world"), Ok(("hello world", "")));
1052 +
/// assert!(parser.parse("").is_ok());
1053 +
/// ```
1054 +
pub fn take_str<'a>() -> impl Parser<'a, Output = &'a str> {
1055 +
    move |cursor: Cursor<'a>| Ok((cursor.input, cursor.advance(cursor.input.len())))
1056 +
}
1057 +
1058 +
/// Takes exactly `n` characters from the input.
1059 +
/// Fails if there aren't enough characters available.
1060 +
///
1061 +
/// ```
1062 +
/// use syntaxe::prelude::*;
1063 +
///
1064 +
/// let parser = take(5);
1065 +
/// assert_eq!(parser.parse("hello world"), Ok(("hello", " world")));
1066 +
/// assert!(parser.parse("hi").is_err());
1067 +
/// ```
1068 +
pub fn take<'a>(n: usize) -> impl Parser<'a, Output = &'a str> {
1069 +
    move |cursor: Cursor<'a>| {
1070 +
        if cursor.input.len() < n {
1071 +
            return Err(Error::new(ErrorKind::UnexpectedEof, cursor));
1072 +
        }
1073 +
        Ok((&cursor.input[..n], cursor.advance(n)))
1074 +
    }
1075 +
}
1076 +
1077 +
/// Attempt to parse, and if it fails, backtrack as if no input had been consumed.
1078 +
///
1079 +
/// ```
1080 +
/// use syntaxe::prelude::*;
1081 +
///
1082 +
/// // Without `backtrack`.
1083 +
/// let parser = string("hello").skip(whitespace()).then(string("tom"));
1084 +
/// let result = parser.parse("hello bob").unwrap_err();
1085 +
/// assert_eq!(result.unparsed(), "bob");
1086 +
///
1087 +
/// // With `backtrack`.
1088 +
/// let parser = backtrack(string("hello").skip(whitespace()).then(string("tom")));
1089 +
/// let result = parser.parse("hello bob").unwrap_err();
1090 +
/// assert_eq!(result.unparsed(), "hello bob");
1091 +
/// ```
1092 +
pub fn backtrack<'a, P>(parser: P) -> impl Parser<'a, Output = P::Output>
1093 +
where
1094 +
    P: Parser<'a>,
1095 +
{
1096 +
    move |cursor: Cursor<'a>| parser.parse_at(cursor).map_err(|e| Error::new(e.kind, cursor))
1097 +
}
1098 +
1099 +
/// Silence a parser. Discard its output and return `()` instead.
1100 +
/// Useful when you need to match a pattern but don't care about capturing its value.
1101 +
pub fn hush<'a, P>(parser: P) -> impl Parser<'a, Output = ()>
1102 +
where
1103 +
    P: Parser<'a>,
1104 +
{
1105 +
    parser.value(())
1106 +
}
1107 +
1108 +
#[cfg(test)]
1109 +
#[allow(clippy::unwrap_used)]
1110 +
mod test {
1111 +
    use super::*;
1112 +
    use crate::result::Location;
1113 +
1114 +
    #[test]
1115 +
    fn test_choice_backtracking() {
1116 +
        let p = choice([
1117 +
            string("leave").skip(whitespace()).then(string("england")),
1118 +
            string("learn").skip(whitespace()).then(string("english")),
1119 +
            string("leave").skip(whitespace()).then(string("britain")),
1120 +
        ]);
1121 +
1122 +
        assert!(p.parse("learn english").is_ok());
1123 +
        assert!(p.parse("leave england").is_ok());
1124 +
        assert!(p.parse("leave britain").is_ok());
1125 +
1126 +
        let err = p.parse("leave english").err().unwrap();
1127 +
        assert_eq!(err.unparsed(), "leave english");
1128 +
    }
1129 +
1130 +
    #[test]
1131 +
    fn test_choice_backtracking_skip() {
1132 +
        let p = choice([
1133 +
            string("leave").skip(whitespace()).skip(string("england")).boxed(),
1134 +
            string("leave/england").boxed(),
1135 +
        ]);
1136 +
1137 +
        assert!(p.parse("leave england").is_ok());
1138 +
        assert!(p.parse("leave/england").is_ok());
1139 +
1140 +
        let p = choice([
1141 +
            backtrack(string("leave").skip(whitespace()))
1142 +
                .skip(string("england"))
1143 +
                .boxed(),
1144 +
            string("leave/england").boxed(),
1145 +
        ]);
1146 +
1147 +
        assert!(p.parse("leave england").is_ok());
1148 +
        assert!(p.parse("leave/england").is_ok());
1149 +
    }
1150 +
1151 +
    #[test]
1152 +
    fn test_or() {
1153 +
        let p = string("leave")
1154 +
            .skip(whitespace())
1155 +
            .then(string("england"))
1156 +
            .or(string("learn").skip(whitespace()).then(string("english")))
1157 +
            .or(string("leave").skip(whitespace()).then(string("britain")));
1158 +
1159 +
        // Test backtracking.
1160 +
        assert!(p.parse("learn english").is_ok());
1161 +
        assert!(p.parse("leave england").is_ok());
1162 +
        assert!(p.parse("leave britain").is_ok());
1163 +
1164 +
        let err = p.parse("leave english").err().unwrap();
1165 +
        assert_eq!(err.unparsed(), "english");
1166 +
        assert_eq!(err.to_string(), "expected `britain`, got `english`");
1167 +
    }
1168 +
1169 +
    #[test]
1170 +
    fn test_zero_copy() {
1171 +
        let input = "fnord!";
1172 +
        let (result, rest) = string("fnord").parse(input).unwrap();
1173 +
1174 +
        assert_eq!(result, "fnord".to_owned());
1175 +
        assert_eq!(rest, "!");
1176 +
        assert_eq!(input[5..6].as_ptr(), rest.as_ptr());
1177 +
    }
1178 +
1179 +
    #[test]
1180 +
    fn test_lisp() {
1181 +
        #[derive(PartialEq, Debug)]
1182 +
        enum Expr {
1183 +
            List(Vec<Expr>),
1184 +
            Op(char),
1185 +
            Num(u8),
1186 +
        }
1187 +
1188 +
        fn expr<'a>() -> impl Parser<'a, Output = Expr> {
1189 +
            let num = natural::<u8>().map(Expr::Num);
1190 +
            let op = choice([symbol('*'), symbol('+'), symbol('^')]).map(Expr::Op);
1191 +
            let list =
1192 +
                between('(', ')', (|c| expr().parse_at(c)).delimited_by(spaces1())).map(Expr::List);
1193 +
1194 +
            list.or(num).or(op)
1195 +
        }
1196 +
        let (output, rest) = expr().parse("(+ 1 (* (^ 2 3) 4))").unwrap();
1197 +
1198 +
        assert_eq!(
1199 +
            output,
1200 +
            Expr::List(vec![
1201 +
                Expr::Op('+'),
1202 +
                Expr::Num(1),
1203 +
                Expr::List(vec![
1204 +
                    Expr::Op('*'),
1205 +
                    Expr::List(vec![Expr::Op('^'), Expr::Num(2), Expr::Num(3)]),
1206 +
                    Expr::Num(4)
1207 +
                ]),
1208 +
            ])
1209 +
        );
1210 +
        assert_eq!(rest, "");
1211 +
    }
1212 +
1213 +
    #[test]
1214 +
    fn test_errors() {
1215 +
        struct TestCase {
1216 +
            input: &'static str,
1217 +
            parser: Box<dyn Parser<'static, Output = ()>>,
1218 +
            location: Location,
1219 +
            message: &'static str,
1220 +
        }
1221 +
1222 +
        let cases = vec![
1223 +
            TestCase {
1224 +
                input: "abc\ndef\nghi",
1225 +
                parser: string("xyz").value(()).boxed(),
1226 +
                location: Location {
1227 +
                    index: 0,
1228 +
                    line: 1,
1229 +
                    column: 1,
1230 +
                },
1231 +
                message: "<stdin>:1:1: error: expected `xyz`, got `abc`",
1232 +
            },
1233 +
            TestCase {
1234 +
                input: "123\n456\n789",
1235 +
                parser: many::<_, String>(digit()).then(symbol('x')).value(()).boxed(),
1236 +
                location: Location {
1237 +
                    index: 3,
1238 +
                    line: 1,
1239 +
                    column: 4,
1240 +
                },
1241 +
                message: "<stdin>:1:4: error: expected 'x', got `\n`",
1242 +
            },
1243 +
            TestCase {
1244 +
                input: "hello\nworld!",
1245 +
                parser: string("hello")
1246 +
                    .then(linebreaks())
1247 +
                    .then(string("earth"))
1248 +
                    .value(())
1249 +
                    .boxed(),
1250 +
                location: Location {
1251 +
                    index: 6,
1252 +
                    line: 2,
1253 +
                    column: 1,
1254 +
                },
1255 +
                message: "<stdin>:2:1: error: expected `earth`, got `world!`",
1256 +
            },
1257 +
            TestCase {
1258 +
                input: "",
1259 +
                parser: digit().value(()).boxed(),
1260 +
                location: Location {
1261 +
                    index: 0,
1262 +
                    line: 1,
1263 +
                    column: 1,
1264 +
                },
1265 +
                message: "<stdin>:1:1: error: expected 0-9, got end-of-input",
1266 +
            },
1267 +
            TestCase {
1268 +
                input: "hello\nworld",
1269 +
                parser: until(symbol('!')).value(()).boxed(),
1270 +
                location: Location {
1271 +
                    index: 11,
1272 +
                    line: 2,
1273 +
                    column: 6,
1274 +
                },
1275 +
                message: "<stdin>:2:6: error: expected '!', got end-of-input",
1276 +
            },
1277 +
            TestCase {
1278 +
                input: "#@!",
1279 +
                parser: end().boxed(),
1280 +
                location: Location {
1281 +
                    index: 0,
1282 +
                    line: 1,
1283 +
                    column: 1,
1284 +
                },
1285 +
                message: "<stdin>:1:1: error: expected end-of-input, got `#@!`",
1286 +
            },
1287 +
        ];
1288 +
1289 +
        for (i, case) in cases.into_iter().enumerate() {
1290 +
            let result = case.parser.parse(case.input);
1291 +
            let err = result.expect_err(&format!(
1292 +
                "Case #{i}: expected error for input: `{}`",
1293 +
                case.input
1294 +
            ));
1295 +
1296 +
            assert_eq!(
1297 +
                err.explain(),
1298 +
                case.message,
1299 +
                "Case #{i}: wrong error message for input: expected {:?}, got {:?}",
1300 +
                case.input,
1301 +
                err
1302 +
            );
1303 +
            assert_eq!(
1304 +
                err.cursor.location, case.location,
1305 +
                "Case #{i}: wrong location for input: expected {:?}, got {:?}",
1306 +
                case.location, err.cursor.location,
1307 +
            );
1308 +
        }
1309 +
    }
1310 +
}
syntaxe/src/prelude.rs added +8 -0
1 +
//! Exports all the common parser combinators.
2 +
3 +
pub use crate::parsers::{
4 +
    any, backtrack, between, character, choice, digit, either, end, float, letter, linebreaks,
5 +
    many, natural, optional, satisfy, signed, spaces, spaces1, string, symbol, take, take_str,
6 +
    take_until, take_while, take_while1, until, whitespace,
7 +
};
8 +
pub use crate::parsers::{Either, Parser};
syntaxe/src/result.rs added +243 -0
1 +
//! Parser result types.
2 +
3 +
use std::fmt;
4 +
use std::path::PathBuf;
5 +
use std::rc::Rc;
6 +
7 +
/// A location in a string.
8 +
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
9 +
pub struct Location {
10 +
    /// Byte index (0-indexed).
11 +
    pub index: usize,
12 +
    /// Line (1-indexed).
13 +
    pub line: usize,
14 +
    /// Column (1-indexed).
15 +
    pub column: usize,
16 +
}
17 +
18 +
impl Default for Location {
19 +
    fn default() -> Self {
20 +
        Self {
21 +
            index: 0,
22 +
            line: 1,
23 +
            column: 1,
24 +
        }
25 +
    }
26 +
}
27 +
28 +
/// A sub-string at a specific location.
29 +
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
30 +
pub struct Cursor<'a> {
31 +
    /// The input string reference.
32 +
    pub input: &'a str,
33 +
    /// The location of the string reference in the string.
34 +
    pub location: Location,
35 +
}
36 +
37 +
impl<'a> Cursor<'a> {
38 +
    /// Create a new cursor.
39 +
    pub fn new(input: &'a str, location: Location) -> Self {
40 +
        Self { input, location }
41 +
    }
42 +
43 +
    /// Advance the cursor by consuming `n` characters.
44 +
    pub fn advance(&self, n: usize) -> Self {
45 +
        let mut loc = self.location;
46 +
        let mut chars = self.input.chars();
47 +
48 +
        for _ in 0..n {
49 +
            // SAFETY: Since this function should only be called to consume
50 +
            // input that we have already peeked at, a missing character
51 +
            // indicates a bug.
52 +
            let ch = chars.next().expect("Cursor::advance: unexpected end of input");
53 +
            if ch == '\n' {
54 +
                loc.line += 1;
55 +
                loc.column = 1;
56 +
            } else {
57 +
                loc.column += 1;
58 +
            }
59 +
            loc.index += 1;
60 +
        }
61 +
62 +
        Self {
63 +
            input: &self.input[n..],
64 +
            location: loc,
65 +
        }
66 +
    }
67 +
}
68 +
69 +
impl<'a> From<&'a str> for Cursor<'a> {
70 +
    fn from(input: &'a str) -> Self {
71 +
        Self {
72 +
            input,
73 +
            location: Location::default(),
74 +
        }
75 +
    }
76 +
}
77 +
78 +
/// Result of applying a `Parser` to an input.
79 +
pub type Result<'a, T> = std::result::Result<(T, Cursor<'a>), Error<'a>>;
80 +
81 +
/// The specific type of parser error that occurred.
82 +
#[derive(Debug, Clone)]
83 +
pub enum ErrorKind<'a> {
84 +
    /// Expected end of input but found more content.
85 +
    ExpectedEof,
86 +
    /// Expected a specific character.
87 +
    ExpectedChar(char),
88 +
    /// Expected a specific string.
89 +
    ExpectedString(&'a str),
90 +
    /// Expected one of several possible values.
91 +
    ExpectedOneOf(Vec<Rc<str>>),
92 +
    /// Expected something described by the string.
93 +
    ExpectedOther(Rc<str>),
94 +
    /// A custom error message.
95 +
    Custom(Rc<str>),
96 +
    /// Error converting from string using FromStr.
97 +
    FromStr(Rc<dyn std::error::Error>),
98 +
    /// Error mapping a value using try_map.
99 +
    TryMap(Rc<dyn std::error::Error>),
100 +
    /// Found an unexpected character.
101 +
    UnexpectedChar(char),
102 +
    /// Found unexpected end of input.
103 +
    UnexpectedEof,
104 +
}
105 +
106 +
impl PartialEq for ErrorKind<'_> {
107 +
    fn eq(&self, other: &Self) -> bool {
108 +
        use ErrorKind::*;
109 +
110 +
        match (self, other) {
111 +
            (ExpectedEof, ExpectedEof) => true,
112 +
            (ExpectedChar(a), ExpectedChar(b)) => a == b,
113 +
            (ExpectedString(a), ExpectedString(b)) => a == b,
114 +
            (ExpectedOneOf(a), ExpectedOneOf(b)) => a == b,
115 +
            (FromStr(a), FromStr(b)) => Rc::ptr_eq(a, b),
116 +
            (TryMap(a), TryMap(b)) => Rc::ptr_eq(a, b),
117 +
            (ExpectedOther(a), ExpectedOther(b)) => a == b,
118 +
            (UnexpectedChar(a), UnexpectedChar(b)) => a == b,
119 +
            (UnexpectedEof, UnexpectedEof) => true,
120 +
            _ => false,
121 +
        }
122 +
    }
123 +
}
124 +
125 +
impl Eq for ErrorKind<'_> {}
126 +
127 +
/// A parser error.
128 +
#[derive(Debug, Clone, PartialEq, Eq)]
129 +
pub struct Error<'a> {
130 +
    /// Error message (without source location).
131 +
    pub kind: ErrorKind<'a>,
132 +
    /// The place in the input where the error occurred.
133 +
    pub cursor: Cursor<'a>,
134 +
    /// File path of the source.
135 +
    pub path: Option<PathBuf>,
136 +
}
137 +
138 +
impl<'a> Error<'a> {
139 +
    /// Create a new parser error from a message.
140 +
    pub fn new(kind: ErrorKind<'a>, cursor: Cursor<'a>) -> Self {
141 +
        Self {
142 +
            kind,
143 +
            cursor,
144 +
            path: None,
145 +
        }
146 +
    }
147 +
148 +
    /// Returns the unparsed portion of the input at the error location
149 +
    pub fn unparsed(&self) -> &'a str {
150 +
        self.cursor.input
151 +
    }
152 +
153 +
    /// Returns a description of what was expected, if applicable
154 +
    pub fn expected(&self) -> Option<Rc<str>> {
155 +
        match &self.kind {
156 +
            ErrorKind::ExpectedChar(c) => Some(c.to_string().into()),
157 +
            ErrorKind::ExpectedString(s) => Some((*s).into()),
158 +
            ErrorKind::ExpectedOther(s) => Some(s.clone()),
159 +
            ErrorKind::ExpectedEof => Some("end of file".into()),
160 +
            _ => None,
161 +
        }
162 +
    }
163 +
164 +
    /// Returns a formatted error message including file location and details
165 +
    pub fn explain(&self) -> String {
166 +
        format!(
167 +
            "{}:{}:{}: error: {}",
168 +
            self.path
169 +
                .as_ref()
170 +
                .map(|p| p.display().to_string())
171 +
                .unwrap_or("<stdin>".to_owned()),
172 +
            self.cursor.location.line,
173 +
            self.cursor.location.column,
174 +
            self,
175 +
        )
176 +
    }
177 +
}
178 +
179 +
impl std::fmt::Display for Error<'_> {
180 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181 +
        let input = self.cursor.input;
182 +
        let eof = input.is_empty();
183 +
        let actual = input
184 +
            .find('\n')
185 +
            .map(|i| if i > 0 { &input[..i] } else { "\n" })
186 +
            .unwrap_or(input);
187 +
        match &self.kind {
188 +
            ErrorKind::ExpectedEof => {
189 +
                write!(f, "expected end-of-input, got `{actual}`")
190 +
            }
191 +
            ErrorKind::ExpectedChar(c) => {
192 +
                if eof {
193 +
                    write!(f, "expected '{c}', got end-of-input")
194 +
                } else {
195 +
                    write!(f, "expected '{c}', got `{actual}`")
196 +
                }
197 +
            }
198 +
            ErrorKind::ExpectedString(s) => {
199 +
                if eof {
200 +
                    write!(f, "expected `{s}`, got end-of-input")
201 +
                } else {
202 +
                    write!(f, "expected `{s}`, got `{actual}`")
203 +
                }
204 +
            }
205 +
            ErrorKind::ExpectedOther(expected) => {
206 +
                if eof {
207 +
                    write!(f, "expected {expected}, got end-of-input")
208 +
                } else {
209 +
                    write!(f, "expected {expected}, got `{actual}`")
210 +
                }
211 +
            }
212 +
            ErrorKind::ExpectedOneOf(expected) => {
213 +
                let choices = expected
214 +
                    .iter()
215 +
                    .map(|c| format!("`{c}`"))
216 +
                    .collect::<Vec<_>>()
217 +
                    .join(", ");
218 +
                if eof {
219 +
                    write!(f, "expected one of {choices}, got end-of-input")
220 +
                } else {
221 +
                    write!(f, "expected one of {choices}, got `{actual}`")
222 +
                }
223 +
            }
224 +
            ErrorKind::Custom(err) => {
225 +
                write!(f, "{err}")
226 +
            }
227 +
            ErrorKind::FromStr(e) => {
228 +
                write!(f, "string conversion failed: {e}")
229 +
            }
230 +
            ErrorKind::TryMap(e) => {
231 +
                write!(f, "value conversion failed: {e}")
232 +
            }
233 +
            ErrorKind::UnexpectedEof => {
234 +
                write!(f, "unexpected end-of-input")
235 +
            }
236 +
            ErrorKind::UnexpectedChar(c) => {
237 +
                write!(f, "unexpected '{c}'")
238 +
            }
239 +
        }
240 +
    }
241 +
}
242 +
243 +
impl std::error::Error for Error<'_> {}