summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Cargo.lock591
-rw-r--r--Cargo.toml2
-rw-r--r--TODO.md4
-rw-r--r--ecs-macros/src/lib.rs175
-rw-r--r--ecs/Cargo.toml1
-rw-r--r--ecs/examples/component_changed_event.rs78
-rw-r--r--ecs/examples/component_events.rs64
-rw-r--r--ecs/examples/component_relationship.rs65
-rw-r--r--ecs/examples/component_removed_event.rs46
-rw-r--r--ecs/examples/event_loop.rs38
-rw-r--r--ecs/examples/optional_component.rs2
-rw-r--r--ecs/examples/relationship.rs20
-rw-r--r--ecs/examples/with_local.rs3
-rw-r--r--ecs/examples/with_sole.rs16
-rw-r--r--ecs/src/actions.rs181
-rw-r--r--ecs/src/component.rs478
-rw-r--r--ecs/src/component/local.rs75
-rw-r--r--ecs/src/component/storage.rs192
-rw-r--r--ecs/src/component/storage/archetype.rs178
-rw-r--r--ecs/src/component/storage/graph.rs38
-rw-r--r--ecs/src/entity.rs285
-rw-r--r--ecs/src/entity/obtainer.rs29
-rw-r--r--ecs/src/event.rs104
-rw-r--r--ecs/src/event/component.rs133
-rw-r--r--ecs/src/extension.rs17
-rw-r--r--ecs/src/lib.rs668
-rw-r--r--ecs/src/lock.rs148
-rw-r--r--ecs/src/pair.rs687
-rw-r--r--ecs/src/phase.rs20
-rw-r--r--ecs/src/private.rs2
-rw-r--r--ecs/src/query.rs237
-rw-r--r--ecs/src/query/flexible.rs41
-rw-r--r--ecs/src/query/term.rs102
-rw-r--r--ecs/src/relationship.rs466
-rw-r--r--ecs/src/sole.rs27
-rw-r--r--ecs/src/system.rs126
-rw-r--r--ecs/src/system/initializable.rs131
-rw-r--r--ecs/src/system/observer.rs310
-rw-r--r--ecs/src/system/stateful.rs292
-rw-r--r--ecs/src/type_name.rs15
-rw-r--r--ecs/src/uid.rs197
-rw-r--r--ecs/src/util.rs92
-rw-r--r--ecs/src/util/array_vec.rs42
-rw-r--r--ecs/tests/query.rs109
-rw-r--r--engine/Cargo.toml3
-rw-r--r--engine/src/asset.rs777
-rw-r--r--engine/src/camera/fly.rs22
-rw-r--r--engine/src/data_types/dimens.rs40
-rw-r--r--engine/src/data_types/vector.rs1
-rw-r--r--engine/src/draw_flags.rs2
-rw-r--r--engine/src/file_format/wavefront/mtl.rs200
-rw-r--r--engine/src/file_format/wavefront/obj.rs5
-rw-r--r--engine/src/image.rs184
-rw-r--r--engine/src/input.rs13
-rw-r--r--engine/src/lib.rs31
-rw-r--r--engine/src/lighting.rs8
-rw-r--r--engine/src/material.rs117
-rw-r--r--engine/src/mesh.rs29
-rw-r--r--engine/src/mesh/cube.rs20
-rw-r--r--engine/src/model.rs176
-rw-r--r--engine/src/opengl/buffer.rs40
-rw-r--r--engine/src/opengl/shader.rs101
-rw-r--r--engine/src/opengl/texture.rs97
-rw-r--r--engine/src/opengl/vertex_array.rs20
-rw-r--r--engine/src/projection.rs2
-rw-r--r--engine/src/renderer.rs15
-rw-r--r--engine/src/renderer/opengl.rs307
-rw-r--r--engine/src/renderer/opengl/vertex.rs (renamed from engine/src/vertex.rs)27
-rw-r--r--engine/src/texture.rs220
-rw-r--r--engine/src/transform.rs6
-rw-r--r--engine/src/util.rs38
-rw-r--r--engine/src/window.rs15
-rw-r--r--engine/src/work_queue.rs44
-rw-r--r--opengl-bindings/Cargo.toml65
-rw-r--r--opengl-bindings/build.rs107
-rw-r--r--opengl-bindings/src/buffer.rs167
-rw-r--r--opengl-bindings/src/data_types.rs37
-rw-r--r--opengl-bindings/src/debug.rs161
-rw-r--r--opengl-bindings/src/lib.rs119
-rw-r--r--opengl-bindings/src/misc.rs190
-rw-r--r--opengl-bindings/src/shader.rs366
-rw-r--r--opengl-bindings/src/texture.rs236
-rw-r--r--opengl-bindings/src/vertex_array.rs260
-rw-r--r--src/main.rs97
84 files changed, 8012 insertions, 2880 deletions
diff --git a/Cargo.lock b/Cargo.lock
index 625d625..36c48d2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -36,6 +36,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9"
[[package]]
+name = "anyhow"
+version = "1.0.100"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"
+
+[[package]]
name = "autocfg"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -64,7 +70,7 @@ dependencies = [
"regex",
"rustc-hash 1.1.0",
"shlex",
- "syn",
+ "syn 2.0.100",
]
[[package]]
@@ -78,13 +84,13 @@ dependencies = [
"clang-sys",
"itertools",
"log",
- "prettyplease",
+ "prettyplease 0.2.31",
"proc-macro2",
"quote",
"regex",
"rustc-hash 2.1.1",
"shlex",
- "syn",
+ "syn 2.0.100",
]
[[package]]
@@ -133,6 +139,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
+name = "cfg_aliases"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
+
+[[package]]
+name = "cgl"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ced0551234e87afee12411d535648dd89d2e7f34c78b753395567aff3d447ff"
+dependencies = [
+ "libc",
+]
+
+[[package]]
name = "ciborium"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -251,13 +272,31 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43da5946c66ffcc7745f48db692ffbb10a83bfe0afd96235c5c2a4fb23994929"
[[package]]
+name = "dispatch2"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "89a09f22a6c6069a18470eb92d2298acf25463f14256d24778e1230d789a2aec"
+dependencies = [
+ "bitflags 2.9.0",
+ "objc2",
+]
+
+[[package]]
+name = "dlib"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "330c60081dcc4c72131f8eb70510f1ac07223e5d4163db481a04a0befcffa412"
+dependencies = [
+ "libloading",
+]
+
+[[package]]
name = "ecs"
version = "0.1.0"
dependencies = [
"criterion",
"ecs-macros",
"hashbrown",
- "linkme",
"parking_lot",
"paste",
"seq-macro",
@@ -273,7 +312,7 @@ version = "0.1.0"
dependencies = [
"proc-macro2",
"quote",
- "syn",
+ "syn 2.0.100",
"toml",
]
@@ -306,6 +345,41 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
+name = "ext-trait"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d772df1c1a777963712fb68e014235e80863d6a91a85c4e06ba2d16243a310e5"
+dependencies = [
+ "ext-trait-proc_macros",
+]
+
+[[package]]
+name = "ext-trait-proc_macros"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ab7934152eaf26aa5aa9f7371408ad5af4c31357073c9e84c3b9d7f11ad639a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "extension-traits"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a296e5a895621edf9fa8329c83aa1cb69a964643e36cf54d8d7a69b789089537"
+dependencies = [
+ "ext-trait",
+]
+
+[[package]]
+name = "extern-c"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "320bea982e85d42441eb25c49b41218e7eaa2657e8f90bc4eca7437376751e23"
+
+[[package]]
name = "fdeflate"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -340,6 +414,17 @@ dependencies = [
]
[[package]]
+name = "getrandom"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "wasi",
+]
+
+[[package]]
name = "gl"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -377,6 +462,60 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2"
[[package]]
+name = "glutin"
+version = "0.32.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12124de845cacfebedff80e877bb37b5b75c34c5a4c89e47e1cdd67fb6041325"
+dependencies = [
+ "bitflags 2.9.0",
+ "cfg_aliases",
+ "cgl",
+ "dispatch2",
+ "glutin_egl_sys",
+ "glutin_glx_sys",
+ "glutin_wgl_sys",
+ "libloading",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-core-foundation",
+ "objc2-foundation",
+ "once_cell",
+ "raw-window-handle",
+ "wayland-sys",
+ "windows-sys 0.52.0",
+ "x11-dl",
+]
+
+[[package]]
+name = "glutin_egl_sys"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4c4680ba6195f424febdc3ba46e7a42a0e58743f2edb115297b86d7f8ecc02d2"
+dependencies = [
+ "gl_generator",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "glutin_glx_sys"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7bb2938045a88b612499fbcba375a77198e01306f52272e692f8c1f3751185"
+dependencies = [
+ "gl_generator",
+ "x11-dl",
+]
+
+[[package]]
+name = "glutin_wgl_sys"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e"
+dependencies = [
+ "gl_generator",
+]
+
+[[package]]
name = "graphviz-sys"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -428,9 +567,9 @@ dependencies = [
[[package]]
name = "indexmap"
-version = "2.8.0"
+version = "2.11.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3954d50fe15b02142bf25d3b8bdadb634ec3948f103d04ffe3031bc8fe9d7058"
+checksum = "4b0f83760fb341a774ed326568e19f5a863af4a952def8c39f9ab92fd95b88e5"
dependencies = [
"equivalent",
"hashbrown",
@@ -444,7 +583,7 @@ checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9"
dependencies = [
"hermit-abi",
"libc",
- "windows-sys",
+ "windows-sys 0.59.0",
]
[[package]]
@@ -503,26 +642,6 @@ dependencies = [
]
[[package]]
-name = "linkme"
-version = "0.3.32"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "22d227772b5999ddc0690e733f734f95ca05387e329c4084fe65678c51198ffe"
-dependencies = [
- "linkme-impl",
-]
-
-[[package]]
-name = "linkme-impl"
-version = "0.3.32"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "71a98813fa0073a317ed6a8055dcd4722a49d9b862af828ee68449adb799b6be"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
-
-[[package]]
name = "lock_api"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -539,6 +658,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30bde2b3dc3671ae49d8e2e9f044c7c005836e7a023ee57cffa25ab82764bb9e"
[[package]]
+name = "macro_rules_attribute"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf0c9b980bf4f3a37fd7b1c066941dd1b1d0152ce6ee6e8fe8c49b9f6810d862"
+dependencies = [
+ "macro_rules_attribute-proc_macro",
+ "paste",
+]
+
+[[package]]
+name = "macro_rules_attribute-proc_macro"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "58093314a45e00c77d5c508f76e77c3396afbbc0d01506e7fae47b018bac2b1d"
+
+[[package]]
name = "matchers"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -599,6 +734,55 @@ dependencies = [
]
[[package]]
+name = "objc2"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "561f357ba7f3a2a61563a186a163d0a3a5247e1089524a3981d49adb775078bc"
+dependencies = [
+ "objc2-encode",
+]
+
+[[package]]
+name = "objc2-app-kit"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6f29f568bec459b0ddff777cec4fe3fd8666d82d5a40ebd0ff7e66134f89bcc"
+dependencies = [
+ "bitflags 2.9.0",
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-core-foundation"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c10c2894a6fed806ade6027bcd50662746363a9589d3ec9d9bef30a4e4bc166"
+dependencies = [
+ "bitflags 2.9.0",
+ "dispatch2",
+ "objc2",
+]
+
+[[package]]
+name = "objc2-encode"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
+
+[[package]]
+name = "objc2-foundation"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "900831247d2fe1a09a683278e5384cfb8c80c79fe6b166f9d14bfdde0ea1b03c"
+dependencies = [
+ "bitflags 2.9.0",
+ "objc2",
+ "objc2-core-foundation",
+]
+
+[[package]]
name = "once_cell"
version = "1.21.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -611,6 +795,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
[[package]]
+name = "opengl-bindings"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "bitflags 2.9.0",
+ "gl_generator",
+ "glutin",
+ "safer-ffi",
+ "thiserror",
+ "toml",
+ "util-macros",
+]
+
+[[package]]
name = "overload"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -658,6 +856,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"
[[package]]
+name = "pkg-config"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
+
+[[package]]
name = "png"
version = "0.17.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -671,13 +875,41 @@ dependencies = [
]
[[package]]
+name = "ppv-lite86"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
+dependencies = [
+ "zerocopy",
+]
+
+[[package]]
+name = "prettyplease"
+version = "0.1.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c8646e95016a7a6c4adea95bafa8a16baab64b583356217f2c85db4a39d9a86"
+dependencies = [
+ "proc-macro2",
+ "syn 1.0.109",
+]
+
+[[package]]
name = "prettyplease"
version = "0.2.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5316f57387668042f561aae71480de936257848f9c43ce528e311d89a07cadeb"
dependencies = [
"proc-macro2",
- "syn",
+ "syn 2.0.100",
+]
+
+[[package]]
+name = "proc-macro-crate"
+version = "3.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "219cb19e96be00ab2e37d6e299658a0cfa83e52429179969b0f0121b4ac46983"
+dependencies = [
+ "toml_edit 0.23.6",
]
[[package]]
@@ -699,6 +931,42 @@ dependencies = [
]
[[package]]
+name = "rand"
+version = "0.8.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
+dependencies = [
+ "libc",
+ "rand_chacha",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
+dependencies = [
+ "ppv-lite86",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
+dependencies = [
+ "getrandom",
+]
+
+[[package]]
+name = "raw-window-handle"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
+
+[[package]]
name = "redox_syscall"
version = "0.5.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -764,12 +1032,58 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"
[[package]]
+name = "rustc_version"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
+dependencies = [
+ "semver",
+]
+
+[[package]]
+name = "rustversion"
+version = "1.0.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
+
+[[package]]
name = "ryu"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f"
[[package]]
+name = "safer-ffi"
+version = "0.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "435fdd58b61a6f1d8545274c1dfa458e905ff68c166e65e294a0130ef5e675bd"
+dependencies = [
+ "extern-c",
+ "libc",
+ "macro_rules_attribute",
+ "paste",
+ "safer_ffi-proc_macros",
+ "scopeguard",
+ "stabby",
+ "uninit",
+ "unwind_safe",
+ "with_builtin_macros",
+]
+
+[[package]]
+name = "safer_ffi-proc_macros"
+version = "0.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0f25be5ba5f319542edb31925517e0380245ae37df50a9752cdbc05ef948156"
+dependencies = [
+ "macro_rules_attribute",
+ "prettyplease 0.1.25",
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -785,6 +1099,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
+name = "semver"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"
+
+[[package]]
name = "seq-macro"
version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -792,22 +1112,32 @@ checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc"
[[package]]
name = "serde"
-version = "1.0.219"
+version = "1.0.225"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6"
+checksum = "fd6c24dee235d0da097043389623fb913daddf92c76e9f5a1db88607a0bcbd1d"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.225"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "659356f9a0cb1e529b24c01e43ad2bdf520ec4ceaf83047b83ddcc2251f96383"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
-version = "1.0.219"
+version = "1.0.225"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00"
+checksum = "0ea936adf78b1f766949a4977b91d2f5595825bd6ec079aa9543ad2685fc4516"
dependencies = [
"proc-macro2",
"quote",
- "syn",
+ "syn 2.0.100",
]
[[package]]
@@ -832,6 +1162,12 @@ dependencies = [
]
[[package]]
+name = "sha2-const-stable"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5f179d4e11094a893b82fff208f74d448a7512f99f5a0acbd5c679b705f83ed9"
+
+[[package]]
name = "sharded-slab"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -859,6 +1195,52 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fcf8323ef1faaee30a44a340193b1ac6814fd9b7b4e88e9d4519a3e4abe1cfd"
[[package]]
+name = "stabby"
+version = "36.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "89b7e94eaf470c2e76b5f15fb2fb49714471a36cc512df5ee231e62e82ec79f8"
+dependencies = [
+ "rustversion",
+ "stabby-abi",
+]
+
+[[package]]
+name = "stabby-abi"
+version = "36.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0dc7a63b8276b54e51bfffe3d85da56e7906b2dcfcb29018a8ab666c06734c1a"
+dependencies = [
+ "rustc_version",
+ "rustversion",
+ "sha2-const-stable",
+ "stabby-macros",
+]
+
+[[package]]
+name = "stabby-macros"
+version = "36.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eecb7ec5611ec93ec79d120fbe55f31bea234dc1bed1001d4a071bb688651615"
+dependencies = [
+ "proc-macro-crate",
+ "proc-macro2",
+ "quote",
+ "rand",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "syn"
+version = "1.0.109"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
name = "syn"
version = "2.0.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -886,7 +1268,7 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
dependencies = [
"proc-macro2",
"quote",
- "syn",
+ "syn 2.0.100",
]
[[package]]
@@ -917,8 +1299,8 @@ checksum = "cd87a5cdd6ffab733b2f74bc4fd7ee5fff6634124999ac278c35fc78c6120148"
dependencies = [
"serde",
"serde_spanned",
- "toml_datetime",
- "toml_edit",
+ "toml_datetime 0.6.8",
+ "toml_edit 0.22.24",
]
[[package]]
@@ -931,6 +1313,15 @@ dependencies = [
]
[[package]]
+name = "toml_datetime"
+version = "0.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32f1085dec27c2b6632b04c80b3bb1b4300d6495d1e129693bdda7d91e72eec1"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
name = "toml_edit"
version = "0.22.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -939,7 +1330,28 @@ dependencies = [
"indexmap",
"serde",
"serde_spanned",
- "toml_datetime",
+ "toml_datetime 0.6.8",
+ "winnow",
+]
+
+[[package]]
+name = "toml_edit"
+version = "0.23.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f3effe7c0e86fdff4f69cdd2ccc1b96f933e24811c5441d44904e8683e27184b"
+dependencies = [
+ "indexmap",
+ "toml_datetime 0.7.2",
+ "toml_parser",
+ "winnow",
+]
+
+[[package]]
+name = "toml_parser"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cf893c33be71572e0e9aa6dd15e6677937abd686b066eac3f8cd3531688a627"
+dependencies = [
"winnow",
]
@@ -962,7 +1374,7 @@ checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d"
dependencies = [
"proc-macro2",
"quote",
- "syn",
+ "syn 2.0.100",
]
[[package]]
@@ -998,12 +1410,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
[[package]]
+name = "uninit"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3e130f2ed46ca5d8ec13c7ff95836827f92f5f5f37fd2b2bf16f33c408d98bb6"
+dependencies = [
+ "extension-traits",
+]
+
+[[package]]
+name = "unwind_safe"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0976c77def3f1f75c4ef892a292c31c0bbe9e3d0702c63044d7c76db298171a3"
+
+[[package]]
name = "util-macros"
version = "0.1.0"
dependencies = [
"proc-macro2",
"quote",
- "syn",
+ "syn 2.0.100",
]
[[package]]
@@ -1027,6 +1454,24 @@ dependencies = [
]
[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "wayland-sys"
+version = "0.31.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34949b42822155826b41db8e5d0c1be3a2bd296c747577a43a3e6daefc296142"
+dependencies = [
+ "dlib",
+ "log",
+ "once_cell",
+ "pkg-config",
+]
+
+[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1048,7 +1493,7 @@ version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb"
dependencies = [
- "windows-sys",
+ "windows-sys 0.59.0",
]
[[package]]
@@ -1059,6 +1504,15 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows-sys"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+dependencies = [
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
@@ -1132,15 +1586,66 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "winnow"
-version = "0.7.4"
+version = "0.7.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0e97b544156e9bebe1a0ffbc03484fc1ffe3100cbce3ffb17eac35f7cdd7ab36"
+checksum = "21a0236b59786fed61e2a80582dd500fe61f18b5dca67a4a067d0bc9039339cf"
dependencies = [
"memchr",
]
[[package]]
+name = "with_builtin_macros"
+version = "0.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a59d55032495429b87f9d69954c6c8602e4d3f3e0a747a12dea6b0b23de685da"
+dependencies = [
+ "with_builtin_macros-proc_macros",
+]
+
+[[package]]
+name = "with_builtin_macros-proc_macros"
+version = "0.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "15bd7679c15e22924f53aee34d4e448c45b674feb6129689af88593e129f8f42"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "x11-dl"
+version = "2.21.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f"
+dependencies = [
+ "libc",
+ "once_cell",
+ "pkg-config",
+]
+
+[[package]]
name = "xml-rs"
version = "0.8.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5b940ebc25896e71dd073bad2dbaa2abfe97b0a391415e22ad1326d9c54e3c4"
+
+[[package]]
+name = "zerocopy"
+version = "0.8.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0894878a5fa3edfd6da3f88c4805f4c8558e2b996227a3d864f47fe11e38282c"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.100",
+]
diff --git a/Cargo.toml b/Cargo.toml
index e14b33c..8ba4ecc 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2021"
[workspace]
-members = ["glfw", "engine", "ecs", "ecs-macros", "util-macros"]
+members = ["glfw", "engine", "ecs", "ecs-macros", "util-macros", "opengl-bindings"]
[dependencies]
engine = { path = "./engine" }
diff --git a/TODO.md b/TODO.md
index 5a68b7d..ecbb8e7 100644
--- a/TODO.md
+++ b/TODO.md
@@ -3,7 +3,7 @@
- [ ] Remove possible edge cases in ECS component storage
- [ ] A Query<()> yields all components. Should this be the behaviour?
- [ ] Improve ECS component storage performance
- - [ ] Give archetypes edges for faster component addition & removal
+ - [x] Give archetypes edges for faster component addition & removal
- [ ] Store components of the same kind in the same memory allocation (not boxed)
- [ ] Investigate what happends when a entity has all of it's components removed.
- [ ] Audio
@@ -21,7 +21,7 @@
- [ ] Improve vertex code.
- [ ] Add support for optionally rendering objects without a projection
- [ ] Add shadow mapping
-- [ ] Use Blinn-phong lighting instead of phong lighting
+- [x] Use Blinn-phong lighting instead of phong lighting
- [x] Support for multiple textures
- [x] Non-hardcoded projection settings
- [x] Model importing
diff --git a/ecs-macros/src/lib.rs b/ecs-macros/src/lib.rs
index 862b0b1..7d00736 100644
--- a/ecs-macros/src/lib.rs
+++ b/ecs-macros/src/lib.rs
@@ -1,3 +1,4 @@
+#![deny(clippy::all, clippy::pedantic)]
use std::path::PathBuf as FsPathBuf;
use proc_macro::TokenStream;
@@ -6,7 +7,6 @@ use syn::spanned::Spanned;
use syn::{
parse,
Attribute,
- GenericParam,
Generics,
Ident,
Item,
@@ -14,7 +14,6 @@ use syn::{
ItemStruct,
ItemUnion,
Path,
- Type,
};
use toml::value::{Table as TomlTable, Value as TomlValue};
@@ -42,60 +41,35 @@ macro_rules! syn_path_segment {
};
}
-#[proc_macro_derive(Component, attributes(component))]
+/// Generates a `Component` implementation.
+///
+/// # Panics
+/// Will panic if:
+/// - Not attributed to a type item
+/// - The attributed-to type item is generic
+/// - If parsing the user crate's `Cargo.toml` file fails.
+#[proc_macro_derive(Component)]
pub fn component_derive(input: TokenStream) -> TokenStream
{
let item: TypeItem = parse::<Item>(input).unwrap().try_into().unwrap();
- let ComponentAttribute { handle_type, handle_mut_type } = item
- .attribute::<ComponentAttribute>("component")
- .unwrap_or_default();
-
let item_ident = item.ident();
let (impl_generics, type_generics, where_clause) = item.generics().split_for_impl();
let ecs_path = find_engine_ecs_crate_path().unwrap_or_else(|| syn_path!(ecs));
- let (id_or_ids, get_id) = if !item.generics().params.is_empty() {
- let id_lut_ident =
- format_ident!("{}_ID_LUT", item_ident.to_string().to_uppercase());
+ assert!(
+ item.generics().params.is_empty(),
+ "Generic types are not supported as components"
+ );
- let id_lut = quote! {
- static #id_lut_ident: LazyLock<Mutex<HashMap<TypeId, Uid>>> =
- LazyLock::new(|| Mutex::new(HashMap::new()));
- };
+ let id_var_ident = format_ident!("{}_ID", item_ident.to_string().to_uppercase());
- let generics = item.generics().params.iter().map(|param| match param {
- GenericParam::Type(type_param) => type_param.ident.clone(),
- GenericParam::Lifetime(_) => panic!("Lifetime generics are not supported"),
- GenericParam::Const(_) => panic!("Const generics are not supported"),
+ let id_var = quote! {
+ static #id_var_ident: LazyLock<Uid> = LazyLock::new(|| {
+ Uid::new_unique(UidKind::Component)
});
-
- let get_id = quote! {
- *#id_lut_ident
- .try_lock()
- .unwrap()
- .entry(TypeId::of::<(#(#generics,)*)>())
- .or_insert_with(|| Uid::new_unique(UidKind::Component))
- };
-
- (id_lut, get_id)
- } else {
- let id_lazylock_ident =
- format_ident!("{}_ID", item_ident.to_string().to_uppercase());
-
- let id_lazylock = quote! {
- static #id_lazylock_ident: LazyLock<Uid> = LazyLock::new(|| {
- Uid::new_unique(UidKind::Component)
- });
- };
-
- let get_id = quote! {
- *#id_lazylock_ident
- };
-
- (id_lazylock, get_id)
};
let mod_ident = format_ident!(
@@ -107,48 +81,26 @@ pub fn component_derive(input: TokenStream) -> TokenStream
mod #mod_ident {
use ::std::any::{Any, TypeId};
use ::std::sync::{LazyLock, Mutex};
- use ::std::collections::HashMap;
use #ecs_path::component::Component;
- use #ecs_path::event::component::{
- Removed as ComponentRemovedEvent,
- Kind as ComponentEventKind,
- };
- use #ecs_path::component::{
- Handle as ComponentHandle,
- HandleMut as ComponentHandleMut
- };
use #ecs_path::uid::{Uid, Kind as UidKind};
use #ecs_path::system::Input as SystemInput;
- use #ecs_path::type_name::TypeName;
use super::*;
- #id_or_ids
+ #id_var
impl #impl_generics Component for #item_ident #type_generics
#where_clause
{
- type Component = Self;
-
- type HandleMut<'component> = #handle_mut_type;
- type Handle<'component> = #handle_type;
-
fn id() -> Uid
{
- #get_id
+ *#id_var_ident
}
- fn get_event_uid(&self, event_kind: ComponentEventKind) -> Uid
+ fn name(&self) -> &'static str
{
- match event_kind {
- ComponentEventKind::Removed => ComponentRemovedEvent::<Self>::id(),
- _ => {
- panic!(
- "Support for event kind {event_kind:?} not implemented!"
- );
- }
- }
+ std::any::type_name::<Self>()
}
}
@@ -156,20 +108,16 @@ pub fn component_derive(input: TokenStream) -> TokenStream
#where_clause
{
}
-
- impl #impl_generics TypeName for #item_ident #type_generics
- #where_clause
- {
- fn type_name(&self) -> &'static str
- {
- std::any::type_name::<Self>()
- }
- }
}
}
.into()
}
+/// Generates a `Sole` implementation.
+///
+/// # Panics
+/// Will panic if not attributed to a type item or if parsing the user crate's
+/// `Cargo.toml` file fails.
#[proc_macro_derive(Sole, attributes(sole))]
pub fn sole_derive(input: TokenStream) -> TokenStream
{
@@ -204,15 +152,6 @@ pub fn sole_derive(input: TokenStream) -> TokenStream
self
}
}
-
- impl #impl_generics #ecs_path::type_name::TypeName for #item_ident #type_generics
- #where_clause
- {
- fn type_name(&self) -> &'static str
- {
- std::any::type_name::<Self>()
- }
- }
}
.into()
}
@@ -251,9 +190,7 @@ impl TypeItem
let mut attr: Option<&Attribute> = None;
for item_attr in item_attrs {
- if attr.is_some() {
- panic!("Expected only one {} attribute", attr_ident);
- }
+ assert!(attr.is_none(), "Expected only one {attr_ident} attribute");
if item_attr.path().get_ident()? == attr_ident {
attr = Some(item_attr);
@@ -377,61 +314,3 @@ fn find_engine_ecs_crate_path() -> Option<Path>
None
})
}
-
-#[derive(Debug)]
-struct ComponentAttribute
-{
- handle_type: proc_macro2::TokenStream,
- handle_mut_type: proc_macro2::TokenStream,
-}
-
-impl FromAttribute for ComponentAttribute
-{
- fn from_attribute(attribute: &Attribute) -> Result<Self, syn::Error>
- {
- let mut handle_type: Option<Type> = None;
- let mut handle_mut_type: Option<Type> = None;
-
- attribute.parse_nested_meta(|meta| {
- let Some(flag) = meta.path.get_ident() else {
- return Err(meta.error("Not a single identifier"));
- };
-
- if flag == "handle_type" {
- let value = meta.value()?;
-
- handle_type = Some(value.parse::<Type>()?);
-
- return Ok(());
- } else if flag == "handle_mut_type" {
- let value = meta.value()?;
-
- handle_mut_type = Some(value.parse::<Type>()?);
-
- return Ok(());
- }
-
- Err(meta.error("Unrecognized token"))
- })?;
-
- Ok(Self {
- handle_type: handle_type
- .map(|handle_type| handle_type.into_token_stream())
- .unwrap_or_else(|| Self::default().handle_type),
- handle_mut_type: handle_mut_type
- .map(|handle_mut_type| handle_mut_type.into_token_stream())
- .unwrap_or_else(|| Self::default().handle_mut_type),
- })
- }
-}
-
-impl Default for ComponentAttribute
-{
- fn default() -> Self
- {
- Self {
- handle_type: quote! { ComponentHandle<'component, Self> },
- handle_mut_type: quote! { ComponentHandleMut<'component, Self> },
- }
- }
-}
diff --git a/ecs/Cargo.toml b/ecs/Cargo.toml
index cf35a74..5ea9fc7 100644
--- a/ecs/Cargo.toml
+++ b/ecs/Cargo.toml
@@ -11,7 +11,6 @@ seq-macro = "0.3.5"
paste = "1.0.14"
thiserror = "1.0.49"
tracing = "0.1.39"
-linkme = "0.3.29"
hashbrown = "0.15.2"
parking_lot = "0.12.3"
ecs-macros = { path = "../ecs-macros" }
diff --git a/ecs/examples/component_changed_event.rs b/ecs/examples/component_changed_event.rs
new file mode 100644
index 0000000..1a53a88
--- /dev/null
+++ b/ecs/examples/component_changed_event.rs
@@ -0,0 +1,78 @@
+use ecs::event::component::Changed;
+use ecs::pair::Pair;
+use ecs::phase::UPDATE as UPDATE_PHASE;
+use ecs::system::observer::Observe;
+use ecs::{Component, Query, World};
+
+#[derive(Component)]
+struct SomeData
+{
+ num: u64,
+}
+
+#[derive(Component)]
+struct Greeting
+{
+ greeting: String,
+}
+
+fn say_hello(query: Query<(&SomeData, &mut Greeting)>)
+{
+ for (data, mut greeting) in &query {
+ println!("{}: {}", greeting.greeting, data.num);
+
+ if greeting.greeting == "Good evening" {
+ greeting.greeting = "Good morning".to_string();
+ greeting.set_changed();
+ }
+ }
+}
+
+fn print_changed_greetings(observe: Observe<'_, Pair<Changed, Greeting>>)
+{
+ println!("\nChanged greetings:");
+
+ for evt_match in &observe {
+ let greeting = evt_match.get_changed_comp();
+
+ println!("A greeting changed to {}", greeting.greeting);
+ }
+
+ println!("");
+}
+
+fn main()
+{
+ let mut world = World::new();
+
+ world.register_system(*UPDATE_PHASE, say_hello);
+
+ world.register_observer(print_changed_greetings);
+
+ world.create_entity((
+ SomeData { num: 987_654 },
+ Greeting {
+ greeting: "Good afternoon".to_string(),
+ },
+ ));
+
+ world.create_entity((
+ SomeData { num: 345 },
+ Greeting { greeting: "Good evening".to_string() },
+ ));
+
+ world.step();
+
+ world.step();
+
+ for (mut greeting,) in &world.query::<(&mut Greeting,), ()>() {
+ if greeting.greeting == "Good afternoon" {
+ greeting.greeting = "Yo yo".to_string();
+ greeting.set_changed();
+ }
+ }
+
+ world.step();
+
+ world.step();
+}
diff --git a/ecs/examples/component_events.rs b/ecs/examples/component_events.rs
new file mode 100644
index 0000000..af09ff9
--- /dev/null
+++ b/ecs/examples/component_events.rs
@@ -0,0 +1,64 @@
+use ecs::actions::Actions;
+use ecs::component::Component;
+use ecs::event::component::{Changed, Removed};
+use ecs::pair::Pair;
+use ecs::phase::UPDATE;
+use ecs::system::observer::Observe;
+use ecs::{Component, Query, World};
+
+#[derive(Debug, Component)]
+struct CheeseCrumbs
+{
+ cnt: usize,
+}
+
+#[derive(Debug, Component)]
+struct Cheese
+{
+ name: &'static str,
+}
+
+fn eat_cheese(query: Query<(&Cheese, &mut CheeseCrumbs)>, mut actions: Actions)
+{
+ for (cheese_ent_id, (_, mut cheese_crumbs)) in query.iter_with_euids() {
+ println!("Eating cheese!");
+
+ cheese_crumbs.cnt += 40;
+ cheese_crumbs.set_changed();
+
+ actions.remove_components(cheese_ent_id, [Cheese::id()]);
+ }
+}
+
+fn on_cheese_removed(observe: Observe<Pair<Removed, Cheese>>)
+{
+ for evt_match in &observe {
+ let cheese = evt_match.get_removed_comp();
+
+ println!("{} cheese was eaten", cheese.name);
+ }
+}
+
+fn on_cheese_crumbs_changed(observe: Observe<Pair<Changed, CheeseCrumbs>>)
+{
+ for evt_match in &observe {
+ let cheese_crumbs = evt_match.get_changed_comp();
+
+ println!("Cheese crumbs count changed to {}", cheese_crumbs.cnt);
+ }
+}
+
+fn main()
+{
+ let mut world = World::new();
+
+ world.register_system(*UPDATE, eat_cheese);
+ world.register_observer(on_cheese_removed);
+ world.register_observer(on_cheese_crumbs_changed);
+
+ world.create_entity((Cheese { name: "Brie" }, CheeseCrumbs { cnt: 0 }));
+ world.create_entity((Cheese { name: "Parmesan" }, CheeseCrumbs { cnt: 0 }));
+ world.create_entity((Cheese { name: "Gouda" }, CheeseCrumbs { cnt: 0 }));
+
+ world.step();
+}
diff --git a/ecs/examples/component_relationship.rs b/ecs/examples/component_relationship.rs
new file mode 100644
index 0000000..e07b214
--- /dev/null
+++ b/ecs/examples/component_relationship.rs
@@ -0,0 +1,65 @@
+use ecs::pair::Pair;
+use ecs::phase::START as START_PHASE;
+use ecs::{Component, Query, World};
+
+#[derive(Component)]
+struct Person
+{
+ name: String,
+}
+
+fn print_dog_likers(query: Query<(&Person, Pair<Likes, &Dogs>)>)
+{
+ for (person, liked_dogs) in &query {
+ println!(
+ "{} likes {} dogs!",
+ person.name,
+ if liked_dogs.large { "large" } else { "small" },
+ );
+ }
+}
+
+#[derive(Component)]
+struct Likes;
+
+#[derive(Component)]
+struct Cats;
+
+#[derive(Component)]
+struct Dogs
+{
+ large: bool,
+}
+
+fn main()
+{
+ let mut world = World::new();
+
+ world.register_system(*START_PHASE, print_dog_likers);
+
+ world.create_entity((
+ Person { name: "Irving".to_string() },
+ Pair::builder()
+ .relation::<Likes>()
+ .target_as_data(Dogs { large: true })
+ .build(),
+ ));
+
+ world.create_entity((
+ Person { name: "Mark".to_string() },
+ Pair::builder()
+ .relation::<Likes>()
+ .target_as_data(Cats)
+ .build(),
+ ));
+
+ world.create_entity((
+ Person { name: "Helena".to_string() },
+ Pair::builder()
+ .relation::<Likes>()
+ .target_as_data(Dogs { large: false })
+ .build(),
+ ));
+
+ world.step();
+}
diff --git a/ecs/examples/component_removed_event.rs b/ecs/examples/component_removed_event.rs
new file mode 100644
index 0000000..776aa48
--- /dev/null
+++ b/ecs/examples/component_removed_event.rs
@@ -0,0 +1,46 @@
+use ecs::actions::Actions;
+use ecs::component::Component;
+use ecs::event::component::Removed;
+use ecs::pair::Pair;
+use ecs::phase::UPDATE;
+use ecs::system::observer::Observe;
+use ecs::{Component, Query, World};
+
+#[derive(Debug, Component)]
+struct Cheese
+{
+ name: &'static str,
+}
+
+fn eat_cheese(query: Query<(&Cheese,)>, mut actions: Actions)
+{
+ for (cheese_ent_id, (_,)) in query.iter_with_euids() {
+ println!("Eating cheese!");
+
+ actions.remove_components(cheese_ent_id, [Cheese::id()]);
+ }
+}
+
+fn on_cheese_removed(observe: Observe<Pair<Removed, Cheese>>)
+{
+ for evt_match in &observe {
+ let cheese = evt_match.get_removed_comp();
+
+ println!("{} cheese was eaten", cheese.name);
+ }
+}
+
+fn main()
+{
+ let mut world = World::new();
+
+ world.register_system(*UPDATE, eat_cheese);
+ world.register_observer(on_cheese_removed);
+
+ world.create_entity((Cheese { name: "Brie" },));
+ world.create_entity((Cheese { name: "Parmesan" },));
+ world.create_entity((Cheese { name: "Gouda" },));
+
+ world.step();
+ world.step();
+}
diff --git a/ecs/examples/event_loop.rs b/ecs/examples/event_loop.rs
index 2365eb0..bec2c00 100644
--- a/ecs/examples/event_loop.rs
+++ b/ecs/examples/event_loop.rs
@@ -1,7 +1,7 @@
use ecs::actions::Actions;
+use ecs::pair::{ChildOf, Pair};
use ecs::phase::{Phase, UPDATE as UPDATE_PHASE};
-use ecs::relationship::{ChildOf, Relationship};
-use ecs::{static_entity, Component, Query, World};
+use ecs::{declare_entity, Component, Query, World};
#[derive(Component)]
struct Wool
@@ -65,25 +65,47 @@ fn age(query: Query<(&mut Health, &Name)>, mut actions: Actions)
}
}
-static_entity!(
+declare_entity!(
SHEER_PHASE,
- (Phase, <Relationship<ChildOf, Phase>>::new(*UPDATE_PHASE))
+ (
+ Phase,
+ Pair::builder()
+ .relation::<ChildOf>()
+ .target_id(*UPDATE_PHASE)
+ .build()
+ )
);
-static_entity!(
+declare_entity!(
FEED_PHASE,
- (Phase, <Relationship<ChildOf, Phase>>::new(*SHEER_PHASE))
+ (
+ Phase,
+ Pair::builder()
+ .relation::<ChildOf>()
+ .target_id(*SHEER_PHASE)
+ .build()
+ )
);
-static_entity!(
+declare_entity!(
AGE_PHASE,
- (Phase, <Relationship<ChildOf, Phase>>::new(*FEED_PHASE))
+ (
+ Phase,
+ Pair::builder()
+ .relation::<ChildOf>()
+ .target_id(*FEED_PHASE)
+ .build()
+ )
);
fn main()
{
let mut world = World::new();
+ world.create_declared_entity(&SHEER_PHASE);
+ world.create_declared_entity(&FEED_PHASE);
+ world.create_declared_entity(&AGE_PHASE);
+
world.register_system(*SHEER_PHASE, sheer);
world.register_system(*FEED_PHASE, feed);
world.register_system(*AGE_PHASE, age);
diff --git a/ecs/examples/optional_component.rs b/ecs/examples/optional_component.rs
index 488dad2..ebc9115 100644
--- a/ecs/examples/optional_component.rs
+++ b/ecs/examples/optional_component.rs
@@ -21,7 +21,7 @@ pub struct CatName
name: String,
}
-fn pet_cats(query: Query<(&CatName, &mut PettingCapacity, &Option<Aggressivity>)>)
+fn pet_cats(query: Query<(&CatName, &mut PettingCapacity, Option<&Aggressivity>)>)
{
for (cat_name, mut petting_capacity, aggressivity) in &query {
let Some(aggressivity) = aggressivity else {
diff --git a/ecs/examples/relationship.rs b/ecs/examples/relationship.rs
index 240884a..4e94151 100644
--- a/ecs/examples/relationship.rs
+++ b/ecs/examples/relationship.rs
@@ -1,5 +1,5 @@
+use ecs::pair::{Pair, Wildcard};
use ecs::phase::START as START_PHASE;
-use ecs::relationship::Relationship;
use ecs::{Component, Query, World};
#[derive(Component)]
@@ -17,16 +17,19 @@ struct Health
health: u32,
}
+#[derive(Component)]
struct Holding;
-fn print_player_stats(
- player_query: Query<(&Player, &Health, &Relationship<Holding, Sword>)>,
-)
+fn print_player_stats(player_query: Query<(&Player, &Health, Pair<Holding, Wildcard>)>)
{
- for (_, health, sword_relationship) in &player_query {
+ for (_, health, target_sword) in &player_query {
println!("Player health: {}", health.health);
- if let Some(sword) = sword_relationship.get(0) {
+ if let Some(sword_ent) = target_sword.get_target_ent() {
+ let sword = sword_ent
+ .get::<Sword>()
+ .expect("Sword entity is missing sword component");
+
println!("Player sword attack strength: {}", sword.attack_strength);
}
}
@@ -43,7 +46,10 @@ fn main()
world.create_entity((
Player,
Health { health: 180 },
- Relationship::<Holding, Sword>::new(sword_uid),
+ Pair::builder()
+ .relation::<Holding>()
+ .target_id(sword_uid)
+ .build(),
));
world.step();
diff --git a/ecs/examples/with_local.rs b/ecs/examples/with_local.rs
index 4658fc0..7a36d0e 100644
--- a/ecs/examples/with_local.rs
+++ b/ecs/examples/with_local.rs
@@ -1,6 +1,7 @@
use ecs::component::local::Local;
use ecs::phase::UPDATE as UPDATE_PHASE;
-use ecs::system::{Into, System};
+use ecs::system::initializable::Initializable;
+use ecs::system::Into;
use ecs::{Component, Query, World};
#[derive(Component)]
diff --git a/ecs/examples/with_sole.rs b/ecs/examples/with_sole.rs
index 689e562..7e89b0a 100644
--- a/ecs/examples/with_sole.rs
+++ b/ecs/examples/with_sole.rs
@@ -1,7 +1,7 @@
+use ecs::pair::{ChildOf, Pair};
use ecs::phase::{Phase, UPDATE as UPDATE_PHASE};
-use ecs::relationship::{ChildOf, Relationship};
use ecs::sole::Single;
-use ecs::{static_entity, Component, Query, Sole, World};
+use ecs::{declare_entity, Component, Query, Sole, World};
#[derive(Component)]
struct Ammo
@@ -31,15 +31,23 @@ fn print_total_ammo_count(ammo_counter: Single<AmmoCounter>)
assert_eq!(ammo_counter.counter, 19);
}
-static_entity!(
+declare_entity!(
PRINT_AMMO_COUNT_PHASE,
- (Phase, <Relationship<ChildOf, Phase>>::new(*UPDATE_PHASE))
+ (
+ Phase,
+ Pair::builder()
+ .relation::<ChildOf>()
+ .target_id(*UPDATE_PHASE)
+ .build()
+ )
);
fn main()
{
let mut world = World::new();
+ world.create_declared_entity(&PRINT_AMMO_COUNT_PHASE);
+
world.register_system(*UPDATE_PHASE, count_ammo);
world.register_system(*PRINT_AMMO_COUNT_PHASE, print_total_ammo_count);
diff --git a/ecs/src/actions.rs b/ecs/src/actions.rs
index 7dff3a5..549e341 100644
--- a/ecs/src/actions.rs
+++ b/ecs/src/actions.rs
@@ -1,13 +1,12 @@
+use std::any::type_name;
use std::marker::PhantomData;
-use std::sync::{Arc, Weak};
-
-use crate::component::{
- Component,
- Metadata as ComponentMetadata,
- Sequence as ComponentSequence,
-};
-use crate::system::{Param as SystemParam, System};
-use crate::uid::{Kind as UidKind, Uid};
+use std::rc::{Rc, Weak};
+
+use crate::component::{Parts as ComponentParts, Sequence as ComponentSequence};
+use crate::event::component::Removed;
+use crate::pair::Pair;
+use crate::system::{Metadata as SystemMetadata, Param as SystemParam};
+use crate::uid::{Kind as UidKind, Uid, WithUidTuple};
use crate::{ActionQueue, World};
/// Used to to queue up actions for a [`World`] to perform.
@@ -15,18 +14,23 @@ use crate::{ActionQueue, World};
pub struct Actions<'world>
{
action_queue: &'world ActionQueue,
- action_queue_weak: Weak<ActionQueue>,
+ world: Option<&'world World>,
}
-impl<'world> Actions<'world>
+impl Actions<'_>
{
- /// Queues up a entity to spawn at the end of the current tick.
- pub fn spawn<Comps: ComponentSequence>(&mut self, components: Comps)
+ /// Queues up a entity to spawn at the end of the current tick, returning the [`Uid`]
+ /// that the entity will have.
+ pub fn spawn<Comps: ComponentSequence>(&mut self, components: Comps) -> Uid
{
+ let new_entity_uid = Uid::new_unique(UidKind::Entity);
+
self.action_queue.push(Action::Spawn(
- components.into_array().into(),
- EventIds { ids: Comps::added_event_ids() },
+ new_entity_uid,
+ components.into_parts_array().into(),
));
+
+ new_entity_uid
}
/// Queues up despawning a entity at the end of the current tick.
@@ -34,6 +38,31 @@ impl<'world> Actions<'world>
{
debug_assert_eq!(entity_uid.kind(), UidKind::Entity);
+ let Some(world) = self.world else {
+ self.action_queue.push(Action::Despawn(entity_uid));
+ return;
+ };
+
+ let Some(ent) = world.get_entity(entity_uid) else {
+ tracing::warn!("Cannot entity that doesn't exist");
+ return;
+ };
+
+ // TODO: Submit all events with a single function call to reduce overhead
+ for comp_id in ent.component_ids() {
+ if comp_id.kind() == UidKind::Pair {
+ continue;
+ }
+
+ world.event_submitter().submit_event(
+ &Pair::builder()
+ .relation::<Removed>()
+ .target_id(comp_id)
+ .build(),
+ entity_uid,
+ );
+ }
+
self.action_queue.push(Action::Despawn(entity_uid));
}
@@ -50,27 +79,70 @@ impl<'world> Actions<'world>
self.action_queue.push(Action::AddComponents(
entity_uid,
- components.into_array().into(),
- EventIds { ids: Comps::added_event_ids() },
+ components.into_parts_array().into(),
));
}
/// Queues up removing component(s) from a entity at the end of the current tick.
- pub fn remove_components<Comps>(&mut self, entity_uid: Uid)
- where
- Comps: ComponentSequence,
+ #[tracing::instrument(skip(self, component_ids))]
+ pub fn remove_components(
+ &mut self,
+ entity_uid: Uid,
+ component_ids: impl IntoIterator<Item = Uid>,
+ )
{
debug_assert_eq!(entity_uid.kind(), UidKind::Entity);
- if Comps::COUNT == 0 {
+ let mut component_ids = component_ids.into_iter().peekable();
+
+ if component_ids.peek().is_none() {
return;
}
- self.action_queue.push(Action::RemoveComponents(
- entity_uid,
- Comps::metadata().into_iter().collect(),
- EventIds { ids: Comps::removed_event_ids() },
- ));
+ let Some(world) = self.world else {
+ self.action_queue.push(Action::RemoveComponents(
+ entity_uid,
+ component_ids.collect(),
+ ));
+ return;
+ };
+
+ let Some(ent) = world.get_entity(entity_uid) else {
+ tracing::warn!("Cannot remove components from entity that doesn't exist");
+ return;
+ };
+
+ let component_ids = component_ids
+ .filter(|comp_id| ent.has_component(*comp_id))
+ .collect::<Vec<_>>();
+
+ if component_ids.is_empty() {
+ return;
+ }
+
+ // TODO: Submit all events with a single function call to reduce overhead
+ for comp_id in &component_ids {
+ if comp_id.kind() == UidKind::Pair {
+ continue;
+ }
+
+ world.event_submitter().submit_event(
+ &Pair::builder()
+ .relation::<Removed>()
+ .target_id(*comp_id)
+ .build(),
+ entity_uid,
+ );
+ }
+
+ self.action_queue
+ .push(Action::RemoveComponents(entity_uid, component_ids));
+ }
+
+ /// Queues up removing component(s) from a entity at the end of the current tick.
+ pub fn remove_comps<Ids: WithUidTuple>(&mut self, entity_uid: Uid)
+ {
+ self.remove_components(entity_uid, Ids::uids());
}
/// Stops the [`World`]. The world will finish the current tick and that tick will be
@@ -83,19 +155,22 @@ impl<'world> Actions<'world>
/// Returns a struct which holds a weak reference to the [`World`] that `Actions`
/// references and that can be used to aquire a new `Actions` instance if the
/// referenced [`World`] is still alive.
+ ///
+ /// # Panics
+ /// This function will panic if `self` was retrieved from a [`WeakRef`].
#[must_use]
pub fn to_weak_ref(&self) -> WeakRef
{
- WeakRef {
- action_queue: self.action_queue_weak.clone(),
- }
- }
+ let world = self.world.unwrap_or_else(|| {
+ panic!(
+ "This function cannot be called if the {} was retrieved from a {}",
+ type_name::<Self>(),
+ type_name::<WeakRef>()
+ )
+ });
- fn new(action_queue: &'world Arc<ActionQueue>) -> Self
- {
- Self {
- action_queue,
- action_queue_weak: Arc::downgrade(action_queue),
+ WeakRef {
+ action_queue: Rc::downgrade(&world.data.action_queue),
}
}
}
@@ -104,19 +179,12 @@ impl<'world> SystemParam<'world> for Actions<'world>
{
type Input = ();
- fn initialize<SystemImpl>(
- _system: &mut impl System<'world, SystemImpl>,
- _input: Self::Input,
- )
- {
- }
-
- fn new<SystemImpl>(
- _system: &'world impl System<'world, SystemImpl>,
- world: &'world World,
- ) -> Self
+ fn new(world: &'world World, _system_metadata: &SystemMetadata) -> Self
{
- Self::new(&world.data.action_queue)
+ Self {
+ action_queue: &world.data.action_queue,
+ world: Some(world),
+ }
}
}
@@ -146,7 +214,7 @@ impl WeakRef
#[derive(Debug, Clone)]
pub struct Ref<'weak_ref>
{
- action_queue: Arc<ActionQueue>,
+ action_queue: Rc<ActionQueue>,
_pd: PhantomData<&'weak_ref ()>,
}
@@ -155,23 +223,20 @@ impl Ref<'_>
#[must_use]
pub fn to_actions(&self) -> Actions<'_>
{
- Actions::new(&self.action_queue)
+ Actions {
+ action_queue: &self.action_queue,
+ world: None,
+ }
}
}
-#[derive(Debug)]
-pub(crate) struct EventIds
-{
- pub(crate) ids: Vec<Uid>,
-}
-
/// A action for a [`System`] to perform.
#[derive(Debug)]
pub(crate) enum Action
{
- Spawn(Vec<(Uid, Box<dyn Component>)>, EventIds),
+ Spawn(Uid, Vec<ComponentParts>),
Despawn(Uid),
- AddComponents(Uid, Vec<(Uid, Box<dyn Component>)>, EventIds),
- RemoveComponents(Uid, Vec<ComponentMetadata>, EventIds),
+ AddComponents(Uid, Vec<ComponentParts>),
+ RemoveComponents(Uid, Vec<Uid>),
Stop,
}
diff --git a/ecs/src/component.rs b/ecs/src/component.rs
index 525bd98..17b279b 100644
--- a/ecs/src/component.rs
+++ b/ecs/src/component.rs
@@ -4,66 +4,34 @@ use std::ops::{Deref, DerefMut};
use seq_macro::seq;
-use crate::event::component::{
- Added as ComponentAddedEvent,
- Kind as ComponentEventKind,
- Removed as ComponentRemovedEvent,
-};
+use crate::event::component::Changed;
+use crate::event::Submitter as EventSubmitter;
use crate::lock::{
Error as LockError,
- Lock,
MappedReadGuard,
MappedWriteGuard,
ReadGuard,
WriteGuard,
};
+use crate::pair::Pair;
use crate::system::Input as SystemInput;
-use crate::type_name::TypeName;
use crate::uid::Uid;
use crate::util::Array;
-use crate::World;
+use crate::{EntityComponentRef, World};
pub mod local;
pub(crate) mod storage;
-pub trait Component: SystemInput + Any + TypeName
+pub trait Component: SystemInput + Any
{
- /// The component type in question. Will usually be `Self`
- type Component: Component
- where
- Self: Sized;
-
- type HandleMut<'component>: FromLockedOptional<'component>
- where
- Self: Sized;
-
- type Handle<'component>: FromLockedOptional<'component>
- where
- Self: Sized;
-
/// Returns the ID of this component.
fn id() -> Uid
where
Self: Sized;
- /// Returns the component UID of a component event for this component.
- fn get_event_uid(&self, event_kind: ComponentEventKind) -> Uid;
-
- /// Returns whether the component `self` is optional.
- fn self_is_optional(&self) -> bool
- {
- false
- }
-
- /// Returns whether this component is optional.
- #[must_use]
- fn is_optional() -> bool
- where
- Self: Sized,
- {
- false
- }
+ /// Returns the name of this component.
+ fn name(&self) -> &'static str;
}
impl dyn Component
@@ -92,199 +60,55 @@ impl Debug for dyn Component
}
}
-impl TypeName for Box<dyn Component>
-{
- fn type_name(&self) -> &'static str
- {
- self.as_ref().type_name()
- }
-}
-
-impl<ComponentT> Component for Option<ComponentT>
-where
- ComponentT: Component,
- for<'a> Option<ComponentT::Handle<'a>>: FromLockedOptional<'a>,
- for<'a> Option<ComponentT::HandleMut<'a>>: FromLockedOptional<'a>,
-{
- type Component = ComponentT;
- type Handle<'component> = Option<ComponentT::Handle<'component>>;
- type HandleMut<'component> = Option<ComponentT::HandleMut<'component>>;
-
- fn id() -> Uid
- {
- ComponentT::id()
- }
-
- fn get_event_uid(&self, event_kind: ComponentEventKind) -> Uid
- {
- match event_kind {
- ComponentEventKind::Removed => ComponentRemovedEvent::<Self>::id(),
- }
- }
-
- fn self_is_optional(&self) -> bool
- {
- true
- }
-
- fn is_optional() -> bool
- {
- true
- }
-}
-
-impl<ComponentT> TypeName for Option<ComponentT>
-where
- ComponentT: Component,
-{
- fn type_name(&self) -> &'static str
- {
- type_name::<Self>()
- }
-}
-
-impl<ComponentT> SystemInput for Option<ComponentT> where ComponentT: Component {}
-
/// A sequence of components.
pub trait Sequence
{
/// The number of components in this component sequence.
const COUNT: usize;
- type Array: Array<(Uid, Box<dyn Component>)>;
-
- fn into_array(self) -> Self::Array;
-
- fn metadata() -> impl Array<Metadata>;
-
- fn added_event_ids() -> Vec<Uid>;
-
- fn removed_event_ids() -> Vec<Uid>;
-}
+ type PartsArray: Array<Parts>;
-/// A mutable or immutable reference to a component.
-pub trait Ref
-{
- type Component: Component;
- type Handle<'component>: FromLockedOptional<'component>;
+ fn into_parts_array(self) -> Self::PartsArray;
}
-impl<ComponentT> Ref for &ComponentT
-where
- ComponentT: Component,
-{
- type Component = ComponentT;
- type Handle<'component> = ComponentT::Handle<'component>;
-}
-
-impl<ComponentT> Ref for &mut ComponentT
-where
- ComponentT: Component,
-{
- type Component = ComponentT;
- type Handle<'component> = ComponentT::HandleMut<'component>;
-}
-
-/// [`Component`] metadata.
-#[derive(Debug, Clone)]
-#[non_exhaustive]
-pub struct Metadata
+#[derive(Debug)]
+pub struct Handle<'a, DataT: 'static>
{
- pub id: Uid,
- pub is_optional: bool,
+ inner: MappedReadGuard<'a, DataT>,
}
-impl Metadata
+impl<'comp, DataT: 'static> Handle<'comp, DataT>
{
- #[must_use]
- pub fn new_non_optional(id: Uid) -> Self
- {
- Self { id, is_optional: false }
- }
-
- #[must_use]
- pub fn of<ComponentT: Component>() -> Self
- {
- Self {
- id: ComponentT::id(),
- is_optional: ComponentT::is_optional(),
- }
- }
-}
-
-pub trait FromLockedOptional<'comp>: Sized
-{
- /// Converts a reference to a optional locked boxed component to a instance of `Self`.
+ /// Creates a new handle instance from a [`EntityComponentRef`].
///
/// # Errors
- /// Returns `Err` if taking the lock (in a non-blocking way) fails.
- fn from_locked_optional_component(
- optional_component: Option<&'comp Lock<Box<dyn Component>>>,
- world: &'comp World,
- ) -> Result<Self, LockError>;
-}
-
-#[derive(Debug)]
-pub struct Handle<'a, ComponentT: Component>
-{
- inner: MappedReadGuard<'a, ComponentT>,
-}
-
-impl<'a, ComponentT: Component> Handle<'a, ComponentT>
-{
- pub(crate) fn new(inner: ReadGuard<'a, Box<dyn Component>>) -> Self
+ /// Will return `Err` if acquiring the component's lock fails.
+ pub fn from_entity_component_ref(
+ entity_component_ref: &EntityComponentRef<'comp>,
+ ) -> Result<Self, HandleError>
{
- Self {
- inner: inner.map(|component| {
- component.downcast_ref::<ComponentT>().unwrap_or_else(|| {
- panic!(
- "Cannot downcast component {} to type {}",
- component.type_name(),
- type_name::<ComponentT>()
- );
- })
- }),
- }
+ Self::new(
+ entity_component_ref
+ .component()
+ .read_nonblock()
+ .map_err(AcquireLockError)?,
+ )
}
-}
-impl<'component, ComponentT: Component> FromLockedOptional<'component>
- for Handle<'component, ComponentT>
-{
- fn from_locked_optional_component(
- optional_component: Option<&'component crate::lock::Lock<Box<dyn Component>>>,
- _world: &'component World,
- ) -> Result<Self, LockError>
- {
- let component = optional_component.unwrap_or_else(|| {
- panic!(
- "Component {} was not found in entity",
- type_name::<ComponentT>()
- );
- });
-
- Ok(Self::new(component.read_nonblock()?))
- }
-}
-
-impl<'comp, ComponentT> FromLockedOptional<'comp> for Option<Handle<'comp, ComponentT>>
-where
- ComponentT: Component,
-{
- fn from_locked_optional_component(
- optional_component: Option<&'comp Lock<Box<dyn Component>>>,
- _world: &'comp World,
- ) -> Result<Self, LockError>
+ fn new(inner: ReadGuard<'comp, Box<dyn Any>>) -> Result<Self, HandleError>
{
- optional_component
- .map(|lock| Ok(Handle::new(lock.read_nonblock()?)))
- .transpose()
+ Ok(Self {
+ inner: ReadGuard::try_map(inner, |component| {
+ component.downcast_ref::<DataT>()
+ })
+ .map_err(|_| HandleError::IncorrectType)?,
+ })
}
}
-impl<ComponentT: Component> Deref for Handle<'_, ComponentT>
+impl<DataT: 'static> Deref for Handle<'_, DataT>
{
- type Target = ComponentT;
+ type Target = DataT;
fn deref(&self) -> &Self::Target
{
@@ -293,67 +117,54 @@ impl<ComponentT: Component> Deref for Handle<'_, ComponentT>
}
#[derive(Debug)]
-pub struct HandleMut<'a, ComponentT: Component>
+pub struct HandleMut<'a, DataT: 'static>
{
- inner: MappedWriteGuard<'a, ComponentT>,
+ entity_component_ref: EntityComponentRef<'a>,
+ inner: MappedWriteGuard<'a, DataT>,
+ event_submitter: EventSubmitter<'a>,
}
-impl<'a, ComponentT: Component> HandleMut<'a, ComponentT>
+impl<'comp, DataT: 'static> HandleMut<'comp, DataT>
{
- pub(crate) fn new(inner: WriteGuard<'a, Box<dyn Component>>) -> Self
+ /// Creates a new handle instance from a [`EntityComponentRef`].
+ ///
+ /// # Errors
+ /// Will return `Err` if acquiring the component's lock fails.
+ pub fn from_entity_component_ref(
+ entity_component_ref: &EntityComponentRef<'comp>,
+ world: &'comp World,
+ ) -> Result<Self, HandleError>
{
- Self {
- inner: inner.map(|component| {
- let component_type_name = component.type_name();
-
- component.downcast_mut::<ComponentT>().unwrap_or_else(|| {
- panic!(
- "Cannot downcast component {component_type_name} to type {}",
- type_name::<ComponentT>()
- );
- })
- }),
- }
+ let inner = entity_component_ref
+ .component()
+ .write_nonblock()
+ .map_err(AcquireLockError)?;
+
+ Ok(Self {
+ entity_component_ref: entity_component_ref.clone(),
+ inner: WriteGuard::try_map(inner, |component| {
+ component.downcast_mut::<DataT>()
+ })
+ .map_err(|_| HandleError::IncorrectType)?,
+ event_submitter: world.event_submitter(),
+ })
}
-}
-impl<'component, ComponentT: Component> FromLockedOptional<'component>
- for HandleMut<'component, ComponentT>
-{
- fn from_locked_optional_component(
- optional_component: Option<&'component Lock<Box<dyn Component>>>,
- _world: &'component World,
- ) -> Result<Self, LockError>
+ pub fn set_changed(&self)
{
- let component = optional_component.unwrap_or_else(|| {
- panic!(
- "Component {} was not found in entity",
- type_name::<ComponentT>()
- );
- });
-
- Ok(Self::new(component.write_nonblock()?))
+ self.event_submitter.submit_event(
+ &Pair::builder()
+ .relation::<Changed>()
+ .target_id(self.entity_component_ref.id())
+ .build(),
+ self.entity_component_ref.entity_id(),
+ );
}
}
-impl<'comp, ComponentT> FromLockedOptional<'comp> for Option<HandleMut<'comp, ComponentT>>
-where
- ComponentT: Component,
-{
- fn from_locked_optional_component(
- optional_component: Option<&'comp Lock<Box<dyn Component>>>,
- _world: &'comp World,
- ) -> Result<Self, LockError>
- {
- optional_component
- .map(|lock| Ok(HandleMut::new(lock.write_nonblock()?)))
- .transpose()
- }
-}
-
-impl<ComponentT: Component> Deref for HandleMut<'_, ComponentT>
+impl<DataT: 'static> Deref for HandleMut<'_, DataT>
{
- type Target = ComponentT;
+ type Target = DataT;
fn deref(&self) -> &Self::Target
{
@@ -361,7 +172,7 @@ impl<ComponentT: Component> Deref for HandleMut<'_, ComponentT>
}
}
-impl<ComponentT: Component> DerefMut for HandleMut<'_, ComponentT>
+impl<DataT: 'static> DerefMut for HandleMut<'_, DataT>
{
fn deref_mut(&mut self) -> &mut Self::Target
{
@@ -369,53 +180,35 @@ impl<ComponentT: Component> DerefMut for HandleMut<'_, ComponentT>
}
}
+#[derive(Debug, thiserror::Error)]
+pub enum HandleError
+{
+ #[error(transparent)]
+ AcquireLockFailed(#[from] AcquireLockError),
+
+ #[error("Incorrect component type")]
+ IncorrectType,
+}
+
+#[derive(Debug, thiserror::Error)]
+#[error("Failed to acquire component lock")]
+pub struct AcquireLockError(#[source] LockError);
+
macro_rules! inner {
($c: tt) => {
seq!(I in 0..=$c {
- impl<#(IntoComp~I,)*> Sequence for (#(IntoComp~I,)*)
- where
- #(
- for<'comp> IntoComp~I: Into<Component: Component>,
- )*
+ impl<#(IntoCompParts~I: IntoParts,)*> Sequence for (#(IntoCompParts~I,)*)
{
const COUNT: usize = $c + 1;
- type Array = [(Uid, Box<dyn Component>); $c + 1];
+ type PartsArray = [Parts; $c + 1];
- fn into_array(self) -> Self::Array
+ fn into_parts_array(self) -> Self::PartsArray
{
[#({
- let (id, component) = self.I.into_component();
-
- (id, Box::new(component))
+ self.I.into_parts()
},)*]
}
-
- fn metadata() -> impl Array<Metadata>
- {
- [
- #(
- Metadata {
- id: IntoComp~I::Component::id(),
- is_optional: IntoComp~I::Component::is_optional(),
- },
- )*
- ]
- }
-
- fn added_event_ids() -> Vec<Uid>
- {
- vec![
- #(ComponentAddedEvent::<IntoComp~I::Component>::id(),)*
- ]
- }
-
- fn removed_event_ids() -> Vec<Uid>
- {
- vec![
- #(ComponentRemovedEvent::<IntoComp~I::Component>::id(),)*
- ]
- }
}
});
};
@@ -427,46 +220,105 @@ seq!(C in 0..=16 {
impl Sequence for ()
{
- type Array = [(Uid, Box<dyn Component>); 0];
+ type PartsArray = [Parts; 0];
const COUNT: usize = 0;
- fn into_array(self) -> Self::Array
+ fn into_parts_array(self) -> Self::PartsArray
{
[]
}
+}
+
+pub trait IntoParts
+{
+ fn into_parts(self) -> Parts;
+}
- fn metadata() -> impl Array<Metadata>
+impl<ComponentT> IntoParts for ComponentT
+where
+ ComponentT: Component,
+{
+ fn into_parts(self) -> Parts
{
- []
+ Parts::builder()
+ .name(type_name::<Self>())
+ .build(Self::id(), self)
+ }
+}
+
+/// The parts of a component.
+#[derive(Debug)]
+#[non_exhaustive]
+pub struct Parts
+{
+ id: Uid,
+ name: &'static str,
+ data: Box<dyn Any>,
+}
+
+impl Parts
+{
+ #[must_use]
+ pub fn id(&self) -> Uid
+ {
+ self.id
+ }
+
+ #[must_use]
+ pub fn name(&self) -> &'static str
+ {
+ self.name
}
- fn added_event_ids() -> Vec<Uid>
+ #[must_use]
+ pub fn builder() -> PartsBuilder
{
- Vec::new()
+ PartsBuilder::default()
}
- fn removed_event_ids() -> Vec<Uid>
+ pub(crate) fn into_data(self) -> Box<dyn Any>
{
- Vec::new()
+ self.data
}
}
-pub trait Into
+#[derive(Debug)]
+pub struct PartsBuilder
{
- type Component;
-
- fn into_component(self) -> (Uid, Self::Component);
+ name: &'static str,
}
-impl<ComponentT> Into for ComponentT
-where
- ComponentT: Component,
+impl PartsBuilder
{
- type Component = Self;
+ #[must_use]
+ pub fn name(mut self, name: &'static str) -> Self
+ {
+ self.name = name;
+ self
+ }
- fn into_component(self) -> (Uid, Self::Component)
+ #[must_use]
+ pub fn build<Data: 'static>(self, id: Uid, data: Data) -> Parts
+ {
+ Parts {
+ id,
+ name: self.name,
+ data: Box::new(data),
+ }
+ }
+
+ #[must_use]
+ pub fn build_with_any_data(self, id: Uid, data: Box<dyn Any>) -> Parts
+ {
+ Parts { id, name: self.name, data }
+ }
+}
+
+impl Default for PartsBuilder
+{
+ fn default() -> Self
{
- (Self::id(), self)
+ Self { name: "(unspecified)" }
}
}
diff --git a/ecs/src/component/local.rs b/ecs/src/component/local.rs
index 0f6f641..b19a30b 100644
--- a/ecs/src/component/local.rs
+++ b/ecs/src/component/local.rs
@@ -1,7 +1,17 @@
+use std::any::type_name;
use std::ops::{Deref, DerefMut};
-use crate::component::{Component, HandleMut as ComponentHandleMut};
-use crate::system::{Param as SystemParam, System};
+use ecs_macros::Component;
+
+use crate::component::{
+ Component,
+ HandleMut as ComponentHandleMut,
+ IntoParts as _,
+ Parts as ComponentParts,
+};
+use crate::pair::Pair;
+use crate::system::initializable::Param as InitializableParam;
+use crate::system::{Metadata as SystemMetadata, Param as SystemParam};
use crate::World;
/// Holds a component which is local to a single system.
@@ -17,27 +27,52 @@ where
{
type Input = LocalComponent;
- fn initialize<SystemImpl>(
- system: &mut impl System<'world, SystemImpl>,
- input: Self::Input,
- )
+ fn new(world: &'world World, system_metadata: &SystemMetadata) -> Self
{
- system.set_local_component(input);
- }
+ let Some(system_ent) = world.get_entity(system_metadata.ent_id) else {
+ panic!(
+ "System entity with ID {} does not exist",
+ system_metadata.ent_id
+ );
+ };
- fn new<SystemImpl>(
- system: &'world impl System<'world, SystemImpl>,
- _world: &'world World,
- ) -> Self
- {
- let local_component = system
- .get_local_component_mut::<LocalComponent>()
- .expect("Local component is uninitialized");
+ let Some(local_component) = system_ent.get_with_id_mut::<LocalComponent>(
+ Pair::builder()
+ .relation::<IsLocalComponent>()
+ .target::<LocalComponent>()
+ .build()
+ .id(),
+ ) else {
+ panic!(
+ "Local component {} of system with ID {} is uninitialized",
+ type_name::<LocalComponent>(),
+ system_metadata.ent_id
+ );
+ };
Self { local_component }
}
}
+impl<'world, LocalComponent, SystemT> InitializableParam<'world, SystemT>
+ for Local<'world, LocalComponent>
+where
+ LocalComponent: Component,
+ SystemT: SystemWithLocalComponents,
+ Self: SystemParam<'world, Input = LocalComponent>,
+{
+ fn initialize(system: &mut SystemT, input: Self::Input)
+ {
+ system.add_local_component(
+ Pair::builder()
+ .relation::<IsLocalComponent>()
+ .target_as_data(input)
+ .build()
+ .into_parts(),
+ );
+ }
+}
+
impl<LocalComponent> Deref for Local<'_, LocalComponent>
where
LocalComponent: Component,
@@ -59,3 +94,11 @@ where
&mut self.local_component
}
}
+
+pub trait SystemWithLocalComponents
+{
+ fn add_local_component(&mut self, component_parts: ComponentParts);
+}
+
+#[derive(Component)]
+struct IsLocalComponent;
diff --git a/ecs/src/component/storage.rs b/ecs/src/component/storage.rs
index 40909fb..a8711c5 100644
--- a/ecs/src/component/storage.rs
+++ b/ecs/src/component/storage.rs
@@ -1,4 +1,4 @@
-use std::any::type_name;
+use std::any::Any;
use std::array::IntoIter as ArrayIter;
use std::cell::RefCell;
use std::vec::IntoIter as VecIntoIter;
@@ -17,8 +17,6 @@ use crate::component::storage::graph::{
ArchetypeEdges,
Graph,
};
-use crate::component::Component;
-use crate::type_name::TypeName;
use crate::uid::{Kind as UidKind, Uid};
use crate::util::{BorrowedOrOwned, Either, StreamingIterator, VecExt};
@@ -35,14 +33,43 @@ pub struct ArchetypeSearchTerms<'a>
impl ArchetypeSearchTerms<'_>
{
- fn excluded_contains(&self, uid: Uid) -> bool
+ fn excluded_contains(&self, comp_id: Uid) -> bool
{
- self.excluded_components.binary_search(&uid).is_ok()
+ let comp_id_kind = comp_id.kind();
+
+ debug_assert!(
+ comp_id_kind == UidKind::Component
+ || (comp_id_kind == UidKind::Pair
+ && comp_id.target_component() != Uid::wildcard())
+ );
+
+ let is_found = self.excluded_components.binary_search(&comp_id).is_ok();
+
+ if !is_found && comp_id_kind == UidKind::Pair {
+ return self.excluded_components.iter().any(|excluded_comp_id| {
+ excluded_comp_id.kind() == UidKind::Pair
+ && excluded_comp_id.has_same_relation_as(comp_id)
+ && excluded_comp_id.target_component() == Uid::wildcard()
+ });
+ }
+
+ is_found
+ }
+
+ fn contains_conflicting(&self) -> bool
+ {
+ self.excluded_components.iter().any(|excluded_comp_id| {
+ self.required_components
+ .binary_search(excluded_comp_id)
+ .is_ok()
+ })
}
- fn required_contains(&self, uid: Uid) -> bool
+ fn archetype_contains_all_required(&self, archetype: &Archetype) -> bool
{
- self.required_components.binary_search(&uid).is_ok()
+ self.required_components
+ .iter()
+ .all(|comp_id| archetype.contains_matching_component(*comp_id))
}
}
@@ -61,13 +88,9 @@ impl Storage
search_terms: ArchetypeSearchTerms<'search_terms>,
) -> ArchetypeRefIter<'_, 'search_terms>
{
- let archetype_id = ArchetypeId::new(&search_terms.required_components);
+ let archetype_id = ArchetypeId::new(search_terms.required_components);
- if search_terms
- .excluded_components
- .iter()
- .any(|excluded_comp_id| search_terms.required_contains(*excluded_comp_id))
- {
+ if search_terms.contains_conflicting() {
return ArchetypeRefIter {
storage: self,
pre_iter: Either::B(Vec::new().into_iter()),
@@ -82,8 +105,21 @@ impl Storage
self.imaginary_archetypes
.borrow_mut()
.push(ImaginaryArchetype {
- id: archetype_id,
- component_ids: search_terms.required_components.to_vec(),
+ id: ArchetypeId::new(search_terms.required_components.iter().filter(
+ |required_comp_id| {
+ required_comp_id.kind() != UidKind::Pair
+ || required_comp_id.target_component() != Uid::wildcard()
+ },
+ )),
+ component_ids: search_terms
+ .required_components
+ .iter()
+ .copied()
+ .filter(|required_comp_id| {
+ required_comp_id.kind() != UidKind::Pair
+ || required_comp_id.target_component() != Uid::wildcard()
+ })
+ .collect(),
});
let found_archetypes = self.find_all_archetype_with_comps(&search_terms);
@@ -117,7 +153,7 @@ impl Storage
return Err(Error::EntityAlreadyExists(uid));
}
- let empty_archetype_id = ArchetypeId::from_components_metadata(&[]);
+ let empty_archetype_id = ArchetypeId::new_empty();
let archetype_node = self.graph.get_or_create_node(empty_archetype_id, &[]);
@@ -161,16 +197,9 @@ impl Storage
pub fn add_entity_component(
&mut self,
entity_uid: Uid,
- component: (Uid, Box<dyn Component>),
+ (component_id, component_name, component): (Uid, &'static str, Box<dyn Any>),
) -> Result<(), Error>
{
- let (component_id, component) = component;
-
- debug_assert!(
- !component.self_is_optional(),
- "Adding a optional component to a entity is not supported"
- );
-
let Some(archetype_id) = self.entity_archetype_lookup.get(&entity_uid) else {
return Err(Error::EntityDoesNotExist(entity_uid));
};
@@ -184,7 +213,7 @@ impl Storage
if archetype_node
.archetype()
- .has_component_with_id(component_id)
+ .contains_component_with_exact_id(component_id)
{
return Err(Error::ComponentAlreadyInEntity {
entity: entity_uid,
@@ -192,56 +221,36 @@ impl Storage
});
}
- let add_edge_archetype_id = match archetype_node
+ let add_edge_archetype_id = if let Some(add_edge_id) = archetype_node
.get_or_insert_edges(component_id, ArchetypeEdges::default)
.add
{
- Some(add_edge_id) => {
- if !self.graph.contains_archetype(add_edge_id) {
- let (_, add_edge_comp_ids) = self
- .graph
- .get_node_by_id(archetype_id)
- .expect("Archetype should exist")
- .make_add_edge(component_id);
-
- self.graph.create_node(add_edge_id, &add_edge_comp_ids);
- }
-
- add_edge_id
- }
- None => {
- let archetype_node = self
+ if !self.graph.contains_archetype(add_edge_id) {
+ let (_, add_edge_comp_ids) = self
.graph
- .get_node_by_id_mut(archetype_id)
- .expect("Archetype should exist");
-
- let (add_edge_id, add_edge_comp_ids) =
- archetype_node.make_add_edge(component_id);
-
- archetype_node
- .get_edges_mut(component_id)
- .expect("Edges for component in archetype should exist")
- .add = Some(add_edge_id);
+ .get_node_by_id(archetype_id)
+ .expect("Archetype should exist")
+ .make_add_edge(component_id);
- if !self.graph.contains_archetype(add_edge_id) {
- self.graph.create_node(add_edge_id, &add_edge_comp_ids);
- }
-
- add_edge_id
+ self.graph.create_node(add_edge_id, &add_edge_comp_ids);
}
- };
- {
- let add_edge_archetype_node = self
+ add_edge_id
+ } else {
+ let archetype_node = self
.graph
- .get_node_by_id_mut(add_edge_archetype_id)
- .expect("Add edge archetype should exist");
+ .get_node_by_id(archetype_id)
+ .expect("Archetype should exist");
- let add_edge_archetype_edges = add_edge_archetype_node
- .get_or_insert_edges(component_id, ArchetypeEdges::default);
+ let (add_edge_id, add_edge_comp_ids) =
+ archetype_node.make_add_edge(component_id);
- add_edge_archetype_edges.remove = Some(archetype_id);
- }
+ if !self.graph.contains_archetype(add_edge_id) {
+ self.graph.create_node(add_edge_id, &add_edge_comp_ids);
+ }
+
+ add_edge_id
+ };
let archetype_node = self
.graph
@@ -261,7 +270,7 @@ impl Storage
entity.insert_component(
component_id,
- ArchetypeEntityComponent::new(component),
+ ArchetypeEntityComponent::new(component, component_name),
add_edge_archetype,
);
@@ -292,7 +301,7 @@ impl Storage
if !archetype_node
.archetype()
- .has_component_with_id(component_id)
+ .contains_component_with_exact_id(component_id)
{
return Err(Error::ComponentNotFoundInEntity {
entity: entity_uid,
@@ -312,11 +321,6 @@ impl Storage
let (remove_edge_id, remove_edge_comp_ids) =
archetype_node.make_remove_edge(component_id);
- archetype_node
- .get_edges_mut(component_id)
- .expect("Edges for component in archetype should exist")
- .remove = Some(remove_edge_id);
-
if !self.graph.contains_archetype(remove_edge_id) {
self.graph
.create_node(remove_edge_id, &remove_edge_comp_ids);
@@ -367,9 +371,12 @@ impl Storage
) -> Vec<ArchetypeId>
{
let Some(mut search_iter) =
- self.graph.dfs_archetype_add_edges(ArchetypeId::new(&[]))
+ self.graph.dfs_archetype_add_edges(ArchetypeId::new_empty())
else {
// If the root archetype doesn't exist, no other archetype can exist either
+ //
+ // TODO: The above comment is not true. Cases where imaginary archetypes have
+ // been created should be handled as well
return Vec::new();
};
@@ -398,11 +405,7 @@ impl Storage
continue;
}
- if !search_terms
- .required_components
- .iter()
- .all(|comp_id| node.archetype().has_component_with_id(*comp_id))
- {
+ if !search_terms.archetype_contains_all_required(node.archetype()) {
continue;
}
@@ -415,14 +418,6 @@ impl Storage
}
}
-impl TypeName for Storage
-{
- fn type_name(&self) -> &'static str
- {
- type_name::<Self>()
- }
-}
-
#[cfg(feature = "vizoxide")]
impl Storage
{
@@ -602,8 +597,7 @@ pub struct ArchetypeRefIter<'storage, 'search_terms>
search_terms: ArchetypeSearchTerms<'search_terms>,
}
-impl<'component_storage, 'search_terms> Iterator
- for ArchetypeRefIter<'component_storage, 'search_terms>
+impl<'component_storage> Iterator for ArchetypeRefIter<'component_storage, '_>
{
type Item = &'component_storage Archetype;
@@ -648,18 +642,15 @@ impl<'component_storage, 'search_terms> Iterator
let mut add_edge_archetype_comps =
archetype.component_ids_sorted().collect::<Vec<_>>();
- add_edge_archetype_comps.insert_at_partition_point_by_key(
- add_edge_component_id,
- |comp_id| *comp_id,
- );
+ add_edge_archetype_comps
+ .insert_at_part_pt_by_key(add_edge_component_id, |comp_id| {
+ comp_id
+ });
self.storage.imaginary_archetypes.borrow_mut().push(
ImaginaryArchetype {
id: add_edge_archetype_id,
- component_ids: add_edge_archetype_comps
- .iter()
- .map(|comp_id| *comp_id)
- .collect::<Vec<_>>(),
+ component_ids: add_edge_archetype_comps.clone(),
},
);
@@ -673,8 +664,6 @@ impl<'component_storage, 'search_terms> Iterator
)),
found.into_iter(),
));
-
- continue;
}
_ => {
unreachable!();
@@ -723,8 +712,7 @@ impl ArchetypeRefIter<'_, '_>
let mut add_edge_comp_ids = imaginary_archetype_comps.to_vec();
- add_edge_comp_ids
- .insert_at_partition_point_by_key(unique_comp_id, |id| *id);
+ add_edge_comp_ids.insert_at_part_pt_by_key(unique_comp_id, |id| id);
let add_edge = ArchetypeId::new(&add_edge_comp_ids);
@@ -784,7 +772,7 @@ mod tests
let archetype_node = new_storage
.graph
- .get_node_by_id(ArchetypeId::from_components_metadata(&[]))
+ .get_node_by_id(ArchetypeId::new_empty())
.expect("Archetype for entities with no component doesn't exist");
assert_eq!(archetype_node.archetype().component_cnt(), 0);
@@ -792,7 +780,7 @@ mod tests
assert_eq!(
new_storage.entity_archetype_lookup.get(&uid).copied(),
- Some(ArchetypeId::from_components_metadata(&[]))
+ Some(ArchetypeId::new_empty())
);
}
}
diff --git a/ecs/src/component/storage/archetype.rs b/ecs/src/component/storage/archetype.rs
index 5306cf9..d96632e 100644
--- a/ecs/src/component/storage/archetype.rs
+++ b/ecs/src/component/storage/archetype.rs
@@ -1,12 +1,15 @@
+use std::any::Any;
+use std::array::IntoIter as ArrayIntoIter;
use std::hash::{DefaultHasher, Hash, Hasher};
+use std::iter::{Enumerate, Filter, Map, RepeatN, Zip};
+use std::option::IntoIter as OptionIntoIter;
use std::slice::Iter as SliceIter;
use hashbrown::HashMap;
-use crate::component::{Component, Metadata as ComponentMetadata};
use crate::lock::Lock;
use crate::uid::{Kind as UidKind, Uid};
-use crate::util::HashMapExt;
+use crate::util::{Either, HashMapExt};
#[derive(Debug)]
pub struct Archetype
@@ -116,8 +119,54 @@ impl Archetype
self.component_index_lookup.len()
}
+ pub fn get_matching_component_indices(
+ &self,
+ component_id: Uid,
+ ) -> MatchingComponentIter<'_>
+ {
+ assert!(
+ component_id.kind() == UidKind::Component
+ || component_id.kind() == UidKind::Pair
+ );
+
+ if component_id.kind() == UidKind::Pair
+ && component_id.target_component() == Uid::wildcard()
+ {
+ return MatchingComponentIter {
+ inner: Either::A(
+ self.component_ids
+ .iter()
+ .enumerate()
+ .zip(std::iter::repeat_n(component_id, self.component_ids.len()))
+ .filter(
+ (|((_, other_comp_id), component_id)| {
+ other_comp_id.kind() == UidKind::Pair
+ && other_comp_id.has_same_relation_as(*component_id)
+ })
+ as MatchingComponentIterFilterFn,
+ )
+ .map(|((index, other_comp_id), _)| (*other_comp_id, index)),
+ ),
+ };
+ }
+
+ MatchingComponentIter {
+ inner: Either::B(
+ [component_id]
+ .into_iter()
+ .zip(self.get_index_for_component(component_id)),
+ ),
+ }
+ }
+
pub fn get_index_for_component(&self, component_id: Uid) -> Option<usize>
{
+ assert!(
+ component_id.kind() == UidKind::Component
+ || (component_id.kind() == UidKind::Pair
+ && component_id.target_component() != Uid::wildcard())
+ );
+
self.component_index_lookup.get(&component_id).copied()
}
@@ -131,14 +180,70 @@ impl Archetype
self.component_ids.iter().copied()
}
- pub fn has_component_with_id(&self, component_id: Uid) -> bool
+ pub fn contains_matching_component(&self, component_id: Uid) -> bool
{
- debug_assert_eq!(component_id.kind(), UidKind::Component);
+ let component_id_kind = component_id.kind();
+
+ debug_assert!(
+ component_id_kind == UidKind::Component || component_id_kind == UidKind::Pair
+ );
+
+ if component_id.kind() == UidKind::Pair
+ && component_id.target_component() == Uid::wildcard()
+ {
+ return self.component_ids.iter().any(|other_comp_id| {
+ other_comp_id.kind() == UidKind::Pair
+ && other_comp_id.has_same_relation_as(component_id)
+ });
+ }
+
+ self.contains_component_with_exact_id(component_id)
+ }
+
+ pub fn contains_component_with_exact_id(&self, component_id: Uid) -> bool
+ {
+ let component_id_kind = component_id.kind();
+
+ debug_assert!(
+ component_id_kind == UidKind::Component
+ || (component_id_kind == UidKind::Pair
+ && component_id.target_component() != Uid::wildcard())
+ );
self.component_index_lookup.contains_key(&component_id)
}
}
+type MatchingComponentIterFilterFn = fn(&((usize, &Uid), Uid)) -> bool;
+
+type MatchingComponentIterMapFn = fn(((usize, &Uid), Uid)) -> (Uid, usize);
+
+type InnerMatchingComponentIterA<'archetype> = Map<
+ Filter<
+ Zip<Enumerate<SliceIter<'archetype, Uid>>, RepeatN<Uid>>,
+ MatchingComponentIterFilterFn,
+ >,
+ MatchingComponentIterMapFn,
+>;
+
+type InnerMatchingComponentIterB = Zip<ArrayIntoIter<Uid, 1>, OptionIntoIter<usize>>;
+
+#[derive(Debug)]
+pub struct MatchingComponentIter<'archetype>
+{
+ inner: Either<InnerMatchingComponentIterA<'archetype>, InnerMatchingComponentIterB>,
+}
+
+impl Iterator for MatchingComponentIter<'_>
+{
+ type Item = (Uid, usize);
+
+ fn next(&mut self) -> Option<Self::Item>
+ {
+ self.inner.next()
+ }
+}
+
#[derive(Debug)]
pub struct EntityIter<'archetype>
{
@@ -209,26 +314,19 @@ impl Entity
#[derive(Debug)]
pub struct EntityComponent
{
- name: &'static str,
- component: Lock<Box<dyn Component>>,
+ component: Lock<Box<dyn Any>>,
}
impl EntityComponent
{
- pub fn new(component: Box<dyn Component>) -> Self
+ pub fn new(component: Box<dyn Any>, component_name: &'static str) -> Self
{
Self {
- name: component.type_name(),
- component: Lock::new(component),
+ component: Lock::new(component, component_name),
}
}
- pub fn name(&self) -> &str
- {
- self.name
- }
-
- pub fn component(&self) -> &Lock<Box<dyn Component>>
+ pub fn component(&self) -> &Lock<Box<dyn Any>>
{
&self.component
}
@@ -243,56 +341,32 @@ pub struct Id
impl Id
{
- pub fn new(component_ids: &impl AsRef<[Uid]>) -> Self
+ pub fn new_empty() -> Self
{
- if component_ids.as_ref().is_empty() {
- return Self { hash: 0 };
- }
-
- debug_assert!(
- component_ids.as_ref().is_sorted(),
- "Cannot create archetype ID from unsorted component IDs"
- );
-
- let mut hasher = DefaultHasher::new();
-
- for component_id in component_ids.as_ref() {
- component_id.hash(&mut hasher);
- }
-
- Self { hash: hasher.finish() }
+ Self { hash: 0 }
}
- pub fn from_components_metadata<'a>(
- components_metadata: impl IntoIterator<Item = &'a ComponentMetadata>,
- ) -> Self
+ pub fn new<'a>(component_ids: impl IntoIterator<Item = &'a Uid>) -> Self
{
let mut hasher = DefaultHasher::new();
let mut prev_component_id: Option<Uid> = None;
- let mut comp_metadata_iter = components_metadata.into_iter().peekable();
+ let mut component_id_iter = component_ids.into_iter().peekable();
- if comp_metadata_iter.peek().is_none() {
- return Self { hash: 0 };
+ if component_id_iter.peek().is_none() {
+ return Self::new_empty();
}
- for comp_metadata in comp_metadata_iter {
- if prev_component_id
- .is_some_and(|prev_comp_id| comp_metadata.id < prev_comp_id)
- {
- panic!(
- "Cannot create archetype ID from a unsorted component metadata list"
- );
- }
-
- prev_component_id = Some(comp_metadata.id);
+ for comp_id in component_id_iter {
+ assert!(
+ prev_component_id.is_none_or(|prev_comp_id| *comp_id >= prev_comp_id),
+ "Cannot create archetype ID from a unsorted component metadata list"
+ );
- if comp_metadata.is_optional {
- continue;
- }
+ prev_component_id = Some(*comp_id);
- comp_metadata.id.hash(&mut hasher);
+ comp_id.hash(&mut hasher);
}
Self { hash: hasher.finish() }
diff --git a/ecs/src/component/storage/graph.rs b/ecs/src/component/storage/graph.rs
index 11160e7..76200f9 100644
--- a/ecs/src/component/storage/graph.rs
+++ b/ecs/src/component/storage/graph.rs
@@ -80,7 +80,7 @@ impl Graph
pub fn dfs_archetype_add_edges(
&self,
archetype_id: ArchetypeId,
- ) -> Option<ArchetypeAddEdgeDfsIter>
+ ) -> Option<ArchetypeAddEdgeDfsIter<'_>>
{
let node = self.get_node_by_id(archetype_id)?;
@@ -140,19 +140,31 @@ impl Graph
}
fn create_missing_subset_node_edges(
- target_node: &ArchetypeNode,
+ target_node: &mut ArchetypeNode,
subset_node: &mut ArchetypeNode,
)
{
let uniq_comp_id = target_node
.archetype()
.component_ids_sorted()
- .find(|id| !subset_node.archetype().has_component_with_id(*id))
+ .find(|id| {
+ !subset_node
+ .archetype()
+ .contains_component_with_exact_id(*id)
+ })
.unwrap();
subset_node
.get_or_insert_edges(uniq_comp_id, ArchetypeEdges::default)
.add = Some(subset_node.make_add_edge(uniq_comp_id).0);
+
+ if target_node.archetype().component_cnt()
+ == subset_node.archetype().component_cnt() + 1
+ {
+ target_node
+ .get_or_insert_edges(uniq_comp_id, ArchetypeEdges::default)
+ .remove = Some(subset_node.archetype().id());
+ }
}
fn create_missing_superset_node_edges(
@@ -169,7 +181,7 @@ impl Graph
.find(|other_archetype_comp_id| {
!target_node
.archetype()
- .has_component_with_id(*other_archetype_comp_id)
+ .contains_component_with_exact_id(*other_archetype_comp_id)
})
.or_else(|| {
if target_node.archetype().component_cnt() != 0 {
@@ -196,7 +208,11 @@ impl Graph
let extra_comp_id = superset_node
.archetype()
.component_ids_unsorted()
- .find(|comp_id| !target_node.archetype().has_component_with_id(*comp_id))
+ .find(|comp_id| {
+ !target_node
+ .archetype()
+ .contains_component_with_exact_id(*comp_id)
+ })
.expect("Archetype should contain one extra component ID");
superset_node
@@ -234,7 +250,10 @@ impl ArchetypeNode
insert_fn: impl FnOnce() -> ArchetypeEdges,
) -> &mut ArchetypeEdges
{
- debug_assert_eq!(component_id.kind(), UidKind::Component);
+ debug_assert!(matches!(
+ component_id.kind(),
+ UidKind::Component | UidKind::Pair
+ ));
self.edges.entry(component_id).or_insert_with(insert_fn)
}
@@ -245,13 +264,6 @@ impl ArchetypeNode
self.edges.iter()
}
- pub fn get_edges_mut(&mut self, component_id: Uid) -> Option<&mut ArchetypeEdges>
- {
- debug_assert_eq!(component_id.kind(), UidKind::Component);
-
- self.edges.get_mut(&component_id)
- }
-
pub fn make_add_edge(&self, component_id: Uid) -> (ArchetypeId, Vec<Uid>)
{
let mut edge_comp_ids = self
diff --git a/ecs/src/entity.rs b/ecs/src/entity.rs
index a43f9ce..ad9f179 100644
--- a/ecs/src/entity.rs
+++ b/ecs/src/entity.rs
@@ -1,14 +1,35 @@
-use linkme::distributed_slice;
+use std::any::type_name;
+use std::ops::Deref;
+use std::sync::LazyLock;
-use crate::component::storage::archetype::{Archetype, Entity as ArchetypeEntity};
-use crate::uid::Uid;
+use crate::component::storage::archetype::{
+ Archetype,
+ Entity as ArchetypeEntity,
+ MatchingComponentIter as ArchetypeMatchingComponentIter,
+};
+use crate::component::{
+ Component,
+ Handle as ComponentHandle,
+ HandleMut as ComponentHandleMut,
+};
+use crate::pair::{
+ ComponentOrWildcard,
+ MultipleWithWildcard as PairMultipleWithWildcard,
+ Pair,
+ WithWildcard as PairWithWildcard,
+};
+use crate::uid::{Kind as UidKind, Uid};
use crate::{EntityComponentRef, World};
+pub mod obtainer;
+
/// A handle to a entity.
+#[derive(Debug, Clone)]
pub struct Handle<'a>
{
archetype: &'a Archetype,
entity: &'a ArchetypeEntity,
+ world: &'a World,
}
impl<'a> Handle<'a>
@@ -21,48 +42,254 @@ impl<'a> Handle<'a>
self.entity.uid()
}
+ /// Returns a reference to the specified component in this entity. `None` is
+ /// returned if the component isn't found in the entity.
+ ///
+ /// # Panics
+ /// Will panic if:
+ /// - The component's ID is not a component ID
+ /// - The component is mutably borrowed elsewhere
+ #[must_use]
+ pub fn get<ComponentT: Component>(&self) -> Option<ComponentHandle<'a, ComponentT>>
+ {
+ assert_eq!(ComponentT::id().kind(), UidKind::Component);
+
+ let component = self.get_matching_components(ComponentT::id()).next()?;
+
+ Some(
+ ComponentHandle::from_entity_component_ref(&component).unwrap_or_else(
+ |err| {
+ panic!(
+ "Creating handle to component {} failed: {err}",
+ type_name::<ComponentT>()
+ );
+ },
+ ),
+ )
+ }
+
+ /// Returns a mutable reference to the specified component in this entity. `None` is
+ /// returned if the component isn't found in the entity.
+ ///
+ /// # Panics
+ /// Will panic if:
+ /// - The component's ID is not a component ID
+ /// - The component is borrowed elsewhere
+ #[must_use]
+ pub fn get_mut<ComponentT: Component>(
+ &self,
+ ) -> Option<ComponentHandleMut<'a, ComponentT>>
+ {
+ assert_eq!(ComponentT::id().kind(), UidKind::Component);
+
+ let component = self.get_matching_components(ComponentT::id()).next()?;
+
+ Some(
+ ComponentHandleMut::from_entity_component_ref(&component, self.world)
+ .unwrap_or_else(|err| {
+ panic!(
+ "Creating handle to component {} failed: {err}",
+ type_name::<ComponentT>()
+ );
+ }),
+ )
+ }
+
+ /// Returns a reference to the component with the ID `id` in this entity.
+ /// `None` is returned if the component isn't found.
+ ///
+ /// # Panics
+ /// Will panic if:
+ /// - The ID is not a component/pair ID
+ /// - The component is borrowed mutably elsewhere
+ /// - The component type is incorrect
+ #[must_use]
+ pub fn get_with_id<ComponentDataT: 'static>(
+ &self,
+ id: Uid,
+ ) -> Option<ComponentHandle<'a, ComponentDataT>>
+ {
+ assert!(
+ matches!(id.kind(), UidKind::Component | UidKind::Pair),
+ "ID {id:?} is not a component/pair ID"
+ );
+
+ let component = self.get_matching_components(id).next()?;
+
+ Some(
+ ComponentHandle::from_entity_component_ref(&component).unwrap_or_else(
+ |err| {
+ panic!(
+ "Creating handle to component {} failed: {err}",
+ type_name::<ComponentDataT>()
+ );
+ },
+ ),
+ )
+ }
+
+ /// Returns a mutable reference to the component with the ID `id` in this entity.
+ /// `None` is returned if the component isn't found.
+ ///
+ /// # Panics
+ /// Will panic if:
+ /// - The ID is not a component/pair ID
+ /// - The component is borrowed elsewhere
+ /// - The component type is incorrect
+ #[must_use]
+ pub fn get_with_id_mut<ComponentDataT: 'static>(
+ &self,
+ id: Uid,
+ ) -> Option<ComponentHandleMut<'a, ComponentDataT>>
+ {
+ assert!(
+ matches!(id.kind(), UidKind::Component | UidKind::Pair),
+ "ID {id:?} is not a component/pair ID"
+ );
+
+ let component = self.get_matching_components(id).next()?;
+
+ Some(
+ ComponentHandleMut::from_entity_component_ref(&component, self.world)
+ .unwrap_or_else(|err| {
+ panic!(
+ "Creating handle to component {} failed: {err}",
+ type_name::<ComponentDataT>()
+ );
+ }),
+ )
+ }
+
+ #[must_use]
+ pub fn get_first_wildcard_pair_match<Relation, Target>(
+ &self,
+ ) -> Option<PairWithWildcard<'a, Relation, Target>>
+ where
+ Relation: ComponentOrWildcard,
+ Target: ComponentOrWildcard,
+ {
+ let mut matching_comps = self.get_matching_components(
+ Pair::builder()
+ .relation_id(Relation::uid())
+ .target_id(Target::uid())
+ .build()
+ .id(),
+ );
+
+ Some(PairWithWildcard::new(self.world, matching_comps.next()?))
+ }
+
+ #[must_use]
+ pub fn get_wildcard_pair_matches<Relation, Target>(
+ &self,
+ ) -> PairMultipleWithWildcard<'a, Relation, Target>
+ where
+ Relation: ComponentOrWildcard,
+ Target: ComponentOrWildcard,
+ {
+ PairMultipleWithWildcard::new(self.world, self.clone())
+ }
+
#[inline]
#[must_use]
- pub fn get_component(&self, component_uid: Uid) -> Option<EntityComponentRef<'a>>
+ pub fn get_matching_components(&self, component_uid: Uid)
+ -> MatchingComponentIter<'a>
{
- let index = self.archetype.get_index_for_component(component_uid)?;
+ MatchingComponentIter {
+ inner: self.archetype.get_matching_component_indices(component_uid),
+ entity: self.entity,
+ }
+ }
+
+ /// Returns whether or not this entity contains a component with the specified `Uid`.
+ #[must_use]
+ pub fn has_component(&self, component_uid: Uid) -> bool
+ {
+ self.archetype
+ .contains_component_with_exact_id(component_uid)
+ }
+
+ /// Returns the `Uids`s of the components this entity has.
+ pub fn component_ids(&self) -> impl Iterator<Item = Uid> + '_
+ {
+ self.archetype.component_ids_sorted()
+ }
+
+ pub(crate) fn new(
+ archetype: &'a Archetype,
+ entity: &'a ArchetypeEntity,
+ world: &'a World,
+ ) -> Self
+ {
+ Self { archetype, entity, world }
+ }
+}
+
+#[derive(Debug)]
+pub struct MatchingComponentIter<'a>
+{
+ inner: ArchetypeMatchingComponentIter<'a>,
+ entity: &'a ArchetypeEntity,
+}
+
+impl<'a> Iterator for MatchingComponentIter<'a>
+{
+ type Item = EntityComponentRef<'a>;
+
+ fn next(&mut self) -> Option<Self::Item>
+ {
+ let (matching_component_id, index) = self.inner.next()?;
Some(EntityComponentRef::new(
+ matching_component_id,
self.entity.components().get(index).unwrap(),
+ self.entity.uid(),
))
}
+}
+
+/// The data type of a declaration of a entity.
+#[derive(Debug)]
+pub struct Declaration
+{
+ uid: LazyLock<Uid>,
+ create_func: fn(&mut World),
+}
+
+impl Declaration
+{
+ pub(crate) fn create(&self, world: &mut World)
+ {
+ (self.create_func)(world);
+ }
+
+ #[doc(hidden)]
+ pub const fn new(create_func: fn(&mut World)) -> Self
+ {
+ Self {
+ uid: LazyLock::new(|| Uid::new_unique(UidKind::Entity)),
+ create_func,
+ }
+ }
+}
- pub(crate) fn new(archetype: &'a Archetype, entity: &'a ArchetypeEntity) -> Self
+impl Deref for Declaration
+{
+ type Target = Uid;
+
+ fn deref(&self) -> &Self::Target
{
- Self { archetype, entity }
+ &self.uid
}
}
#[allow(clippy::module_name_repetitions)]
#[macro_export]
-macro_rules! static_entity {
+macro_rules! declare_entity {
($visibility: vis $ident: ident, $components: expr) => {
- $visibility static $ident: ::std::sync::LazyLock<$crate::uid::Uid> =
- ::std::sync::LazyLock::new(|| {
- $crate::uid::Uid::new_unique($crate::uid::Kind::Entity)
+ $visibility static $ident: $crate::entity::Declaration =
+ $crate::entity::Declaration::new(|world| {
+ world.create_entity_with_uid(*$ident, $components);
});
-
- $crate::private::paste::paste! {
- mod [<__ecs_ $ident:lower _static_entity_priv>] {
- use super::*;
-
- #[$crate::private::linkme::distributed_slice(
- $crate::entity::CREATE_STATIC_ENTITIES
- )]
- #[linkme(crate=$crate::private::linkme)]
- static CREATE_STATIC_ENTITY: fn(&$crate::World) = |world| {
- world.create_entity_with_uid($components, *$ident);
- };
- }
- }
}
}
-
-#[distributed_slice]
-#[doc(hidden)]
-pub static CREATE_STATIC_ENTITIES: [fn(&World)];
diff --git a/ecs/src/entity/obtainer.rs b/ecs/src/entity/obtainer.rs
new file mode 100644
index 0000000..6c2ea96
--- /dev/null
+++ b/ecs/src/entity/obtainer.rs
@@ -0,0 +1,29 @@
+use crate::entity::Handle as EntityHandle;
+use crate::system::{Metadata as SystemMetadata, Param as SystemParam};
+use crate::uid::Uid;
+use crate::World;
+
+#[derive(Debug)]
+pub struct Obtainer<'world>
+{
+ world: &'world World,
+}
+
+impl<'world> SystemParam<'world> for Obtainer<'world>
+{
+ type Input = ();
+
+ fn new(world: &'world World, _system_metadata: &SystemMetadata) -> Self
+ {
+ Self { world }
+ }
+}
+
+impl Obtainer<'_>
+{
+ #[must_use]
+ pub fn get_entity(&self, entity_id: Uid) -> Option<EntityHandle<'_>>
+ {
+ self.world.get_entity(entity_id)
+ }
+}
diff --git a/ecs/src/event.rs b/ecs/src/event.rs
index 9cea807..15455b6 100644
--- a/ecs/src/event.rs
+++ b/ecs/src/event.rs
@@ -1 +1,105 @@
+use crate::lock::Lock;
+use crate::pair::Pair;
+use crate::uid::{Kind as UidKind, Uid};
+use crate::util::VecExt;
+
pub mod component;
+
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct Emitted<'a>
+{
+ pub event: Uid,
+ pub match_ids: &'a [Uid],
+}
+
+#[derive(Debug)]
+pub struct Submitter<'world>
+{
+ new_events: &'world Lock<NewEvents>,
+}
+
+impl<'world> Submitter<'world>
+{
+ /// Submits a event to be handled later.
+ ///
+ /// # Panics
+ /// Will panic if unable to acquire a read-write lock to the event store.
+ pub fn submit_event(&self, event: &Pair<Uid, Uid>, match_id: Uid)
+ {
+ let mut new_events_lock = self
+ .new_events
+ .write_nonblock()
+ .expect("Failed to acquire read-write lock to new events");
+
+ new_events_lock.push_event_match(event, match_id);
+ }
+
+ pub(crate) fn new(new_events: &'world Lock<NewEvents>) -> Self
+ {
+ Self { new_events }
+ }
+}
+
+#[derive(Debug, Default)]
+pub(crate) struct NewEvents
+{
+ events: Vec<(Uid, Matches)>,
+}
+
+impl NewEvents
+{
+ pub fn push_event_match(&mut self, event: &Pair<Uid, Uid>, match_id: Uid)
+ {
+ let event_id = event.id();
+
+ assert_eq!(event_id.kind(), UidKind::Pair);
+
+ if let Ok(event_index) = self
+ .events
+ .binary_search_by_key(&event_id, |(other_event_id, _)| *other_event_id)
+ {
+ let Some((_, matches)) = self.events.get_mut(event_index) else {
+ unreachable!();
+ };
+
+ matches.sorted_push(match_id);
+
+ return;
+ }
+
+ self.events.insert_at_part_pt_by_key(
+ (event_id, Matches { match_ids: Vec::from([match_id]) }),
+ |(other_event_id, _)| other_event_id,
+ );
+ }
+
+ pub fn take(&mut self) -> Vec<(Uid, Matches)>
+ {
+ std::mem::take(&mut self.events)
+ }
+
+ pub fn is_empty(&self) -> bool
+ {
+ self.events.is_empty()
+ }
+}
+
+#[derive(Debug)]
+pub(crate) struct Matches
+{
+ pub match_ids: Vec<Uid>,
+}
+
+impl Matches
+{
+ fn sorted_push(&mut self, match_id: Uid)
+ {
+ if self.match_ids.binary_search(&match_id).is_ok() {
+ return;
+ }
+
+ self.match_ids
+ .insert_at_part_pt_by_key(match_id, |other_match_id| other_match_id);
+ }
+}
diff --git a/ecs/src/event/component.rs b/ecs/src/event/component.rs
index b4edffc..ed6b7cf 100644
--- a/ecs/src/event/component.rs
+++ b/ecs/src/event/component.rs
@@ -1,84 +1,71 @@
//! Component events.
-use std::fmt::{Debug, Formatter};
-use std::marker::PhantomData;
+use std::convert::Infallible;
-use ecs_macros::Component;
+use crate::component::{Handle as ComponentHandle, HandleMut as ComponentHandleMut};
+use crate::entity::Handle as EntityHandle;
+use crate::pair::Pair;
+use crate::system::observer::EventMatch;
+use crate::util::impl_multiple;
+use crate::Component;
-use crate::component::Component;
+/// Pair relation for events emitted when:
+/// a) A entity with the target component is spawned.
+/// b) The target component is added to a entity.
+#[derive(Debug, Component)]
+pub struct Added(Infallible);
-/// Event emitted when:
-/// a) A entity with component `ComponentT` is spawned.
-/// b) A component `ComponentT` is added to a entity.
-#[derive(Clone, Component)]
-pub struct Added<ComponentT>
-where
- ComponentT: Component,
-{
- _pd: PhantomData<ComponentT>,
-}
+/// Pair relation for events emitted **before**:
+/// a) The target component is removed from a entity.
+/// b) A entity with the target component is despawned.
+#[derive(Debug, Component)]
+pub struct Removed(Infallible);
-impl<ComponentT> Debug for Added<ComponentT>
-where
- ComponentT: Component,
-{
- fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result
- {
- formatter
- .debug_struct("Added")
- .field("_pd", &self._pd)
- .finish()
- }
-}
+#[derive(Debug, Component)]
+pub struct Changed(Infallible);
-impl<ComponentT> Default for Added<ComponentT>
-where
- ComponentT: Component,
-{
- fn default() -> Self
- {
- Self { _pd: PhantomData }
- }
-}
+impl_multiple!(
+ EventMatch,
+ (
+ impl<Target: Component> _<'_><Pair<Removed, Target>> (removed),
+ impl<Target: Component> _<'_><Pair<Added, Target>> (added),
+ impl<Target: Component> _<'_><Pair<Changed, Target>> (changed)
+ )
+ cb=(type_params=(observable_type), event_name) => {
+ paste::paste! {
+ #[must_use]
+ pub fn [<get_ $event_name _comp>](&self) -> ComponentHandle<'_, Target>
+ {
+ let ent = self.get_ent_infallible();
-/// Event emitted when:
-/// a) A `ComponentT` component is removed from a entity.
-/// b) A entity with component `ComponentT` is despawned.
-#[derive(Clone, Component)]
-pub struct Removed<ComponentT>
-where
- ComponentT: Component,
-{
- _pd: PhantomData<ComponentT>,
-}
+ let Some(comp) = ent.get::<Target>() else {
+ unreachable!();
+ };
-impl<ComponentT> Debug for Removed<ComponentT>
-where
- ComponentT: Component,
-{
- fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result
- {
- formatter
- .debug_struct("Removed")
- .field("_pd", &self._pd)
- .finish()
- }
-}
+ comp
+ }
-impl<ComponentT> Default for Removed<ComponentT>
-where
- ComponentT: Component,
-{
- fn default() -> Self
- {
- Self { _pd: PhantomData }
- }
-}
+ #[must_use]
+ pub fn [<get_ $event_name _comp_mut>](&self) -> ComponentHandleMut<'_, Target>
+ {
+ let ent = self.get_ent_infallible();
-/// Specifies a kind of component event UID.
-#[derive(Debug, Clone, Copy)]
-#[non_exhaustive]
-pub enum Kind
-{
- Removed,
-}
+ let Some(comp) = ent.get_mut::<Target>() else {
+ unreachable!();
+ };
+
+ comp
+ }
+ }
+
+ #[must_use]
+ pub fn get_ent_infallible(&self) -> EntityHandle<'_>
+ {
+ let Some(ent) = self.get_entity() else {
+ unreachable!();
+ };
+
+ ent
+ }
+ }
+);
diff --git a/ecs/src/extension.rs b/ecs/src/extension.rs
index 42ebef9..9c6614b 100644
--- a/ecs/src/extension.rs
+++ b/ecs/src/extension.rs
@@ -1,5 +1,7 @@
use crate::component::Sequence as ComponentSequence;
+use crate::entity::Declaration as EntityDeclaration;
use crate::sole::Sole;
+use crate::system::observer::Observer;
use crate::system::System;
use crate::uid::Uid;
use crate::{SoleAlreadyExistsError, World};
@@ -34,6 +36,15 @@ impl<'world> Collector<'world>
self.world.register_system(phase_euid, system);
}
+ /// Adds a observer system to the [`World`].
+ pub fn add_observer<'this, SystemImpl>(
+ &'this mut self,
+ observer: impl Observer<'this, SystemImpl>,
+ )
+ {
+ self.world.register_observer(observer);
+ }
+
/// Adds a entity to the [`World`].
pub fn add_entity<Comps>(&mut self, components: Comps)
where
@@ -42,6 +53,12 @@ impl<'world> Collector<'world>
self.world.create_entity(components);
}
+ /// Adds a declared entity to the [`World`].
+ pub fn add_declared_entity(&mut self, entity_decl: &EntityDeclaration)
+ {
+ self.world.create_declared_entity(entity_decl);
+ }
+
/// Adds a globally shared singleton value to the [`World`].
///
/// # Errors
diff --git a/ecs/src/lib.rs b/ecs/src/lib.rs
index 32d82bc..f6fba64 100644
--- a/ecs/src/lib.rs
+++ b/ecs/src/lib.rs
@@ -1,9 +1,9 @@
#![deny(clippy::all, clippy::pedantic)]
-use std::any::{type_name, TypeId};
-use std::cell::RefCell;
+use std::any::{type_name, Any, TypeId};
use std::fmt::Debug;
use std::mem::ManuallyDrop;
+use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
@@ -12,26 +12,37 @@ use hashbrown::HashMap;
use crate::actions::Action;
use crate::component::storage::archetype::EntityComponent as ArchetypeEntityComponent;
use crate::component::storage::Storage as ComponentStorage;
-use crate::component::{Component, Sequence as ComponentSequence};
-use crate::entity::CREATE_STATIC_ENTITIES;
-use crate::event::component::Kind as ComponentEventKind;
+use crate::component::{
+ Component,
+ IntoParts as IntoComponentParts,
+ Parts as ComponentParts,
+ Sequence as ComponentSequence,
+};
+use crate::entity::{Declaration as EntityDeclaration, Handle as EntityHandle};
+use crate::event::component::Added;
+use crate::event::{Emitted as EmittedEvent, NewEvents, Submitter as EventSubmitter};
use crate::extension::{Collector as ExtensionCollector, Extension};
-use crate::lock::{Lock, WriteGuard};
-use crate::phase::{Phase, START as START_PHASE};
+use crate::lock::Lock;
+use crate::pair::{ChildOf, DependsOn, Pair};
+use crate::phase::{
+ Phase,
+ POST_UPDATE as POST_UPDATE_PHASE,
+ PRE_UPDATE as PRE_UPDATE_PHASE,
+ START as START_PHASE,
+ UPDATE as UPDATE_PHASE,
+};
use crate::query::flexible::Query as FlexibleQuery;
-use crate::query::term::Without;
use crate::query::{
- Iter as QueryIter,
TermWithFieldTuple as QueryTermWithFieldTuple,
TermWithoutFieldTuple as QueryTermWithoutFieldTuple,
Terms as QueryTerms,
TermsBuilderInterface,
+ MAX_TERM_CNT as QUERY_MAX_TERM_CNT,
};
-use crate::relationship::{ChildOf, DependsOn, Relationship};
-use crate::sole::Sole;
+use crate::sole::{Single, Sole};
use crate::stats::Stats;
-use crate::system::{System, SystemComponent};
-use crate::type_name::TypeName;
+use crate::system::observer::{Observer, WrapperComponent as ObserverWrapperComponent};
+use crate::system::{Callbacks, Metadata as SystemMetadata, System, SystemComponent};
use crate::uid::{Kind as UidKind, Uid};
pub mod actions;
@@ -39,20 +50,17 @@ pub mod component;
pub mod entity;
pub mod event;
pub mod extension;
-pub mod lock;
+pub mod pair;
pub mod phase;
pub mod query;
-pub mod relationship;
pub mod sole;
pub mod stats;
pub mod system;
pub mod tuple;
-pub mod type_name;
pub mod uid;
pub mod util;
-#[doc(hidden)]
-pub mod private;
+mod lock;
pub use ecs_macros::{Component, Sole};
@@ -77,56 +85,49 @@ impl World
is_first_tick: AtomicBool::new(false),
};
- world.add_sole(Stats::default()).ok();
+ crate::phase::spawn_entities(&mut world);
- for create_static_entity in CREATE_STATIC_ENTITIES {
- create_static_entity(&world);
- }
+ world.add_sole(Stats::default()).ok();
world
}
- /// Creates a new entity with the given components.
- ///
- /// # Panics
- /// Will panic if mutable internal lock cannot be acquired.
+ /// Creates a entity with the given components. A new unique [`Uid`] will be generated
+ /// for this entity.
pub fn create_entity<Comps>(&mut self, components: Comps) -> Uid
where
Comps: ComponentSequence,
{
let entity_uid = Uid::new_unique(UidKind::Entity);
- self.create_entity_with_uid(components, entity_uid);
+ self.create_entity_with_uid(entity_uid, components);
entity_uid
}
+ /// Creates a entity with the given components. The entity will have the specified
+ /// [`Uid`].
#[tracing::instrument(skip_all)]
- #[doc(hidden)]
- pub fn create_entity_with_uid<Comps>(&self, components: Comps, entity_uid: Uid)
+ pub fn create_entity_with_uid<Comps>(&mut self, entity_uid: Uid, components: Comps)
where
Comps: ComponentSequence,
{
- debug_assert_eq!(entity_uid.kind(), UidKind::Entity);
-
- {
- let mut component_storage_lock = self.lock_component_storage_rw();
-
- if let Err(err) = component_storage_lock.create_entity(entity_uid) {
- tracing::warn!("Failed to create entity: {err}");
- return;
- };
+ self.create_ent(entity_uid, components.into_parts_array());
+ }
- Self::add_entity_components(
- entity_uid,
- components.into_array(),
- &mut component_storage_lock,
- );
- }
+ pub fn add_component(&mut self, entity_id: Uid, component_parts: ComponentParts)
+ {
+ Self::add_entity_components(
+ entity_id,
+ [component_parts],
+ &mut self.data.component_storage,
+ &EventSubmitter::new(&self.data.new_events),
+ );
+ }
- for added_event_id in Comps::added_event_ids() {
- self.emit_event_by_id(added_event_id);
- }
+ pub fn create_declared_entity(&mut self, entity_decl: &EntityDeclaration)
+ {
+ entity_decl.create(self);
}
/// Adds a globally shared singleton value.
@@ -140,35 +141,48 @@ impl World
self.data.sole_storage.insert(sole)
}
- pub fn register_system<'this, SystemImpl>(
+ pub fn register_observer<'this, SystemImpl, ObserverT>(
&'this mut self,
- phase_euid: Uid,
- system: impl System<'this, SystemImpl>,
- )
+ observer: ObserverT,
+ ) where
+ ObserverT: Observer<'this, SystemImpl>,
{
- self.create_entity((
- SystemComponent { system: system.into_type_erased() },
- Relationship::<DependsOn, Phase>::new(phase_euid),
- ));
+ let (wrapper_comp, mut system_callbacks) = observer.finish_observer();
+
+ let ent_id = Uid::new_unique(UidKind::Entity);
+
+ self.create_ent(
+ ent_id,
+ [wrapper_comp.into_parts()].into_iter().chain(
+ ObserverT::observed_events()
+ .into_iter()
+ .map(IntoComponentParts::into_parts),
+ ),
+ );
+
+ system_callbacks.on_created(self, SystemMetadata { ent_id });
}
- pub fn register_observer_system<'this, SystemImpl, Event>(
+ pub fn register_system<'this, SystemImpl>(
&'this mut self,
+ phase_euid: Uid,
system: impl System<'this, SystemImpl>,
- event: Event,
- ) where
- Event: Component,
+ )
{
- self.create_entity::<(SystemComponent, Event)>((
- SystemComponent { system: system.into_type_erased() },
- event,
+ let (type_erased_system, mut system_callbacks) = system.finish();
+
+ let system_ent_id = self.create_entity((
+ SystemComponent { system: type_erased_system },
+ Pair::builder()
+ .relation::<DependsOn>()
+ .target_id(phase_euid)
+ .build(),
));
+
+ system_callbacks.on_created(self, SystemMetadata { ent_id: system_ent_id });
}
/// Adds a extensions.
- ///
- /// # Panics
- /// Will panic if mutable internal lock cannot be acquired.
pub fn add_extension(&mut self, extension: impl Extension)
{
let extension_collector = ExtensionCollector::new(self);
@@ -176,7 +190,9 @@ impl World
extension.collect(extension_collector);
}
- pub fn query<FieldTerms, FieldlessTerms>(&self) -> Query<FieldTerms, FieldlessTerms>
+ pub fn query<FieldTerms, FieldlessTerms>(
+ &self,
+ ) -> Query<'_, FieldTerms, FieldlessTerms>
where
FieldTerms: QueryTermWithFieldTuple,
FieldlessTerms: QueryTermWithoutFieldTuple,
@@ -192,11 +208,34 @@ impl World
FlexibleQuery::new(self, terms)
}
+ pub fn get_entity(&self, entity_id: Uid) -> Option<EntityHandle<'_>>
+ {
+ let archetype = self
+ .data
+ .component_storage
+ .get_entity_archetype(entity_id)?;
+
+ let Some(entity) = archetype.get_entity_by_id(entity_id) else {
+ unreachable!("Should exist since archetype was found by entity id");
+ };
+
+ Some(EntityHandle::new(archetype, entity, self))
+ }
+
+ pub fn get_sole<SoleT: Sole>(&self) -> Option<Single<'_, SoleT>>
+ {
+ Some(Single::new(self.data.sole_storage.get::<SoleT>()?))
+ }
+
+ pub fn event_submitter(&self) -> EventSubmitter<'_>
+ {
+ EventSubmitter::new(&self.data.new_events)
+ }
+
/// Performs a single tick.
- ///
/// # Panics
- /// Will panic if a internal lock cannot be acquired.
- pub fn step(&self) -> StepResult
+ /// Will panic if mutable internal lock cannot be acquired.
+ pub fn step(&mut self) -> StepResult
{
if self.stop.load(Ordering::Relaxed) {
return StepResult::Stop;
@@ -212,8 +251,9 @@ impl World
self.perform_phases();
- self.lock_component_storage_rw()
- .create_imaginary_archetypes();
+ self.emit_new_events();
+
+ self.data.component_storage.create_imaginary_archetypes();
self.perform_queued_actions();
@@ -221,17 +261,9 @@ impl World
return StepResult::Stop;
}
- let mut stats_lock = self
- .data
- .sole_storage
- .get::<Stats>()
- .expect("No stats sole found")
- .write_nonblock()
- .expect("Failed to aquire read-write stats sole lock");
-
- let stats = stats_lock
- .downcast_mut::<Stats>()
- .expect("Casting stats sole to Stats type failed");
+ let Some(mut stats) = self.get_sole::<Stats>() else {
+ unreachable!(); // Reason: is added in World::new
+ };
stats.current_tick += 1;
@@ -239,10 +271,7 @@ impl World
}
/// Starts a loop which calls [`Self::step`] until the world is stopped.
- ///
- /// # Panics
- /// Will panic if a internal lock cannot be acquired.
- pub fn start_loop(&self)
+ pub fn start_loop(&mut self)
{
while let StepResult::Continue = self.step() {}
}
@@ -260,13 +289,7 @@ impl World
VizoxideArchetypeGraphParams,
};
- let component_storage_lock = self
- .data
- .component_storage
- .read_nonblock()
- .expect("Failed to acquire read-only component storage lock");
-
- component_storage_lock.create_vizoxide_archetype_graph(
+ self.data.component_storage.create_vizoxide_archetype_graph(
name,
VizoxideArchetypeGraphParams {
create_node_name: |archetype, _| {
@@ -275,7 +298,7 @@ impl World
archetype
.component_ids_sorted()
.into_iter()
- .map(|comp_id| comp_id.id().to_string())
+ .map(|comp_id| comp_id.to_string())
.collect::<Vec<_>>()
.join(", ")
))
@@ -300,161 +323,168 @@ impl World
)
}
- fn query_and_run_systems(&self, phase_euid: Uid)
+ #[tracing::instrument(skip_all)]
+ fn create_ent(
+ &mut self,
+ entity_uid: Uid,
+ components: impl IntoIterator<Item = ComponentParts>,
+ )
{
- let system_comps_query =
- self.query::<(&SystemComponent, &Relationship<DependsOn, Phase>), ()>();
+ debug_assert_eq!(entity_uid.kind(), UidKind::Entity);
+
+ if let Err(err) = self.data.component_storage.create_entity(entity_uid) {
+ tracing::warn!("Failed to create entity: {err}");
+ return;
+ }
- let system_iter = system_comps_query.iter().filter(|(_, phase_rel)| {
- phase_rel
- .target_uids()
- .any(|target_uid| target_uid == phase_euid)
- });
+ Self::add_entity_components(
+ entity_uid,
+ components,
+ &mut self.data.component_storage,
+ &EventSubmitter::new(&self.data.new_events),
+ );
+ }
- for (system_component, _) in system_iter {
+ fn query_and_run_systems(&self, phase_euid: Uid)
+ {
+ let system_query = Query::<(&SystemComponent,)>::from_flexible_query(
+ self.flexible_query(
+ QueryTerms::<QUERY_MAX_TERM_CNT>::builder()
+ .with_required([
+ SystemComponent::id(),
+ Pair::builder()
+ .relation::<DependsOn>()
+ .target_id(phase_euid)
+ .build()
+ .id(),
+ ])
+ .build(),
+ ),
+ );
+
+ for (system_ent_id, (system_component,)) in system_query.iter_with_euids() {
// SAFETY: The world lives long enough
unsafe {
- system_component.system.run(self);
+ system_component
+ .system
+ .run(self, SystemMetadata { ent_id: system_ent_id });
}
}
}
fn perform_child_phases(&self, parent_phase_euid: Uid)
{
- let phase_query = self.query::<(&Phase, &Relationship<ChildOf, Phase>), ()>();
-
- for (child_phase_euid, (_, phase_rel)) in phase_query.iter_with_euids() {
- if !phase_rel
- .target_uids()
- .any(|phase_euid| phase_euid == parent_phase_euid)
- {
- continue;
- }
+ let phase_query = self.flexible_query(
+ QueryTerms::<2>::builder()
+ .with_required([
+ Phase::id(),
+ Pair::builder()
+ .relation::<ChildOf>()
+ .target_id(parent_phase_euid)
+ .build()
+ .id(),
+ ])
+ .build(),
+ );
- self.query_and_run_systems(child_phase_euid);
- self.perform_child_phases(child_phase_euid);
+ for child_phase_entity in &phase_query {
+ self.query_and_run_systems(child_phase_entity.uid());
+ self.perform_child_phases(child_phase_entity.uid());
}
}
+ fn perform_single_phase(&self, phase_entity_id: Uid)
+ {
+ self.query_and_run_systems(phase_entity_id);
+ self.perform_child_phases(phase_entity_id);
+ }
+
fn perform_phases(&self)
{
- let phase_query =
- self.query::<(&Phase,), (Without<Relationship<ChildOf, Phase>>,)>();
+ self.perform_single_phase(*PRE_UPDATE_PHASE);
+ self.perform_single_phase(*UPDATE_PHASE);
+ self.perform_single_phase(*POST_UPDATE_PHASE);
+ }
- for (phase_euid, (_,)) in phase_query.iter_with_euids() {
- if phase_euid == *START_PHASE {
- continue;
- }
+ fn emit_new_events(&self)
+ {
+ loop {
+ let new_events = {
+ let mut new_events_lock = self
+ .data
+ .new_events
+ .write_nonblock()
+ .expect("Failed to acquire read-write lock to new events");
+
+ if new_events_lock.is_empty() {
+ break;
+ }
+
+ new_events_lock.take()
+ };
- self.query_and_run_systems(phase_euid);
- self.perform_child_phases(phase_euid);
+ for (event_id, event_matches) in new_events {
+ self.emit_event_observers(
+ event_id,
+ &EmittedEvent {
+ event: event_id,
+ match_ids: &event_matches.match_ids,
+ },
+ );
+ }
}
}
#[tracing::instrument(skip_all)]
- fn perform_queued_actions(&self)
+ fn perform_queued_actions(&mut self)
{
- let mut active_action_queue = match *self.data.action_queue.active_queue.borrow()
- {
- ActiveActionQueue::A => &self.data.action_queue.queue_a,
- ActiveActionQueue::B => &self.data.action_queue.queue_b,
- }
- .write_nonblock()
- .unwrap_or_else(|err| {
- panic!(
- "Failed to take read-write action queue lock {:?}: {err}",
- self.data.action_queue.active_queue
- );
- });
-
- let mut has_swapped_active_queue = false;
+ let mut action_queue_lock = self
+ .data
+ .action_queue
+ .queue
+ .write_nonblock()
+ .unwrap_or_else(|err| {
+ panic!("Failed to take read-write action queue lock: {err}",);
+ });
- for action in active_action_queue.drain(..) {
+ for action in action_queue_lock.drain(..) {
match action {
- Action::Spawn(components, component_added_event_ids) => {
+ Action::Spawn(new_entity_uid, components) => {
+ if let Err(err) =
+ self.data.component_storage.create_entity(new_entity_uid)
{
- let mut component_storage_lock = self.lock_component_storage_rw();
-
- let new_entity_uid = Uid::new_unique(UidKind::Entity);
-
- if let Err(err) =
- component_storage_lock.create_entity(new_entity_uid)
- {
- tracing::warn!("Failed to create entity: {err}");
- continue;
- };
-
- Self::add_entity_components(
- new_entity_uid,
- components,
- &mut component_storage_lock,
- );
+ tracing::warn!("Failed to create entity: {err}");
+ continue;
}
- if !has_swapped_active_queue {
- self.swap_event_queue(&mut has_swapped_active_queue);
- }
-
- for comp_added_event_id in component_added_event_ids.ids {
- self.emit_event_by_id(comp_added_event_id);
- }
+ Self::add_entity_components(
+ new_entity_uid,
+ components,
+ &mut self.data.component_storage,
+ &EventSubmitter::new(&self.data.new_events),
+ );
}
Action::Despawn(entity_uid) => {
- self.despawn_entity(entity_uid, &mut has_swapped_active_queue);
- }
- Action::AddComponents(
- entity_uid,
- components,
- component_added_event_ids,
- ) => {
+ if let Err(err) =
+ self.data.component_storage.remove_entity(entity_uid)
{
- let mut component_storage_lock = self.lock_component_storage_rw();
-
- Self::add_entity_components(
- entity_uid,
- components,
- &mut component_storage_lock,
- );
- }
-
- if !has_swapped_active_queue {
- self.swap_event_queue(&mut has_swapped_active_queue);
- }
-
- // TODO: Fix that events are emitted for components that haven't been
- // added because a error occurred (for example, the entity already has
- // the component)
- for comp_added_event_id in component_added_event_ids.ids {
- self.emit_event_by_id(comp_added_event_id);
+ tracing::error!("Failed to despawn entity: {err}");
}
}
- Action::RemoveComponents(
- entity_uid,
- components_metadata,
- component_removed_event_ids,
- ) => {
- {
- let mut component_storage_lock = self.lock_component_storage_rw();
-
- Self::remove_entity_components(
- entity_uid,
- components_metadata
- .iter()
- .map(|comp_metadata| comp_metadata.id),
- &mut component_storage_lock,
- );
- }
-
- if !has_swapped_active_queue {
- self.swap_event_queue(&mut has_swapped_active_queue);
- }
-
- // TODO: Fix that events are emitted for components that haven't been
- // removed because a error occurred (for example, the entity does not
- // have the component)
- for comp_removed_event_id in component_removed_event_ids.ids {
- self.emit_event_by_id(comp_removed_event_id);
- }
+ Action::AddComponents(entity_uid, components) => {
+ Self::add_entity_components(
+ entity_uid,
+ components,
+ &mut self.data.component_storage,
+ &EventSubmitter::new(&self.data.new_events),
+ );
+ }
+ Action::RemoveComponents(entity_uid, component_ids) => {
+ Self::remove_entity_components(
+ entity_uid,
+ component_ids,
+ &mut self.data.component_storage,
+ );
}
Action::Stop => {
self.stop.store(true, Ordering::Relaxed);
@@ -463,59 +493,39 @@ impl World
}
}
- #[tracing::instrument(skip_all)]
- fn despawn_entity(&self, entity_uid: Uid, has_swapped_active_queue: &mut bool)
- {
- let mut component_storage_lock = self.lock_component_storage_rw();
-
- let removed_entity = match component_storage_lock.remove_entity(entity_uid) {
- Ok(components) => components,
- Err(err) => {
- tracing::error!("Failed to despawn entity: {err}");
- return;
- }
- };
-
- let component_removed_event_uids = removed_entity
- .components()
- .iter()
- .map(|component| {
- component
- .component()
- .read_nonblock()
- .unwrap_or_else(|_| {
- panic!(
- "Failed to acquire read-only {} component lock",
- component.name()
- )
- })
- .get_event_uid(ComponentEventKind::Removed)
- })
- .collect::<Vec<_>>();
-
- drop(component_storage_lock);
-
- if !*has_swapped_active_queue {
- self.swap_event_queue(has_swapped_active_queue);
- }
-
- for comp_removed_event_id in component_removed_event_uids {
- self.emit_event_by_id(comp_removed_event_id);
- }
- }
-
fn add_entity_components(
entity_uid: Uid,
- components: impl IntoIterator<Item = (Uid, Box<dyn Component>)>,
+ components: impl IntoIterator<Item = ComponentParts>,
component_storage: &mut ComponentStorage,
+ event_submitter: &EventSubmitter<'_>,
)
{
- for (component_id, component) in components {
- if let Err(err) = component_storage
- .add_entity_component(entity_uid, (component_id, component))
- {
- tracing::error!("Failed to add component to entity: {err}");
+ let component_iter = components.into_iter();
+
+ for component_parts in component_iter {
+ let comp_id = component_parts.id();
+
+ let comp_name = component_parts.name();
+
+ if let Err(err) = component_storage.add_entity_component(
+ entity_uid,
+ (comp_id, comp_name, component_parts.into_data()),
+ ) {
+ tracing::error!("Failed to add component {comp_name} to entity: {err}");
+ continue;
+ }
+
+ if comp_id.kind() == UidKind::Pair {
+ continue;
}
+
+ event_submitter.submit_event(
+ &Pair::builder()
+ .relation::<Added>()
+ .target_id(comp_id)
+ .build(),
+ entity_uid,
+ );
}
}
@@ -525,7 +535,9 @@ impl World
component_storage: &mut ComponentStorage,
)
{
- for component_id in component_ids {
+ let component_id_iter = component_ids.into_iter();
+
+ for component_id in component_id_iter {
if let Err(err) =
component_storage.remove_entity_component(entity_uid, component_id)
{
@@ -534,40 +546,28 @@ impl World
}
}
- fn emit_event_by_id(&self, event_id: Uid)
+ fn emit_event_observers(&self, event_id: Uid, emitted_event: &EmittedEvent<'_>)
{
- let query = self.flexible_query(
- QueryTerms::<2>::builder()
- .with_required([SystemComponent::id(), event_id])
- .build(),
+ assert_eq!(event_id.kind(), UidKind::Pair);
+
+ let query = Query::<(&ObserverWrapperComponent,)>::from_flexible_query(
+ self.flexible_query(
+ QueryTerms::<QUERY_MAX_TERM_CNT>::builder()
+ .with_required([ObserverWrapperComponent::id(), event_id])
+ .build(),
+ ),
);
- for (system,) in QueryIter::<(&SystemComponent,), _>::new(self, query.iter()) {
+ for (observer_ent_id, (observer,)) in query.iter_with_euids() {
unsafe {
- system.system.run(self);
+ observer.run(
+ self,
+ SystemMetadata { ent_id: observer_ent_id },
+ emitted_event.clone(),
+ );
}
}
}
-
- fn swap_event_queue(&self, has_swapped_active_queue: &mut bool)
- {
- let mut active_queue = self.data.action_queue.active_queue.borrow_mut();
-
- *active_queue = match *active_queue {
- ActiveActionQueue::A => ActiveActionQueue::B,
- ActiveActionQueue::B => ActiveActionQueue::A,
- };
-
- *has_swapped_active_queue = true;
- }
-
- fn lock_component_storage_rw(&self) -> WriteGuard<'_, ComponentStorage>
- {
- self.data
- .component_storage
- .write_nonblock()
- .expect("Failed to acquire read-write component storage lock")
- }
}
impl Default for World
@@ -589,72 +589,66 @@ pub enum StepResult
}
#[derive(Debug, Default)]
-pub struct WorldData
+struct WorldData
{
- component_storage: Arc<Lock<ComponentStorage>>,
+ component_storage: ComponentStorage,
sole_storage: SoleStorage,
- action_queue: Arc<ActionQueue>,
+ action_queue: Rc<ActionQueue>,
+ new_events: Lock<NewEvents>,
}
-#[derive(Debug)]
+#[derive(Debug, Clone)]
pub struct EntityComponentRef<'a>
{
- comp: &'a ArchetypeEntityComponent,
+ component_id: Uid,
+ component: &'a ArchetypeEntityComponent,
+ entity_id: Uid,
}
impl<'a> EntityComponentRef<'a>
{
- pub fn component(&self) -> &'a Lock<Box<dyn Component>>
+ fn component(&self) -> &'a Lock<Box<dyn Any>>
{
- self.comp.component()
+ self.component.component()
}
- fn new(comp: &'a ArchetypeEntityComponent) -> Self
+ #[must_use]
+ pub fn id(&self) -> Uid
{
- Self { comp }
+ self.component_id
}
-}
-#[derive(Debug, Default, Clone, Copy)]
-enum ActiveActionQueue
-{
- #[default]
- A,
- B,
+ #[must_use]
+ pub fn entity_id(&self) -> Uid
+ {
+ self.entity_id
+ }
+
+ fn new(component_id: Uid, comp: &'a ArchetypeEntityComponent, entity_id: Uid)
+ -> Self
+ {
+ Self {
+ component_id,
+ component: comp,
+ entity_id,
+ }
+ }
}
#[derive(Debug, Default)]
struct ActionQueue
{
- queue_a: Lock<Vec<Action>>,
- queue_b: Lock<Vec<Action>>,
- active_queue: RefCell<ActiveActionQueue>,
+ queue: Lock<Vec<Action>>,
}
impl ActionQueue
{
fn push(&self, action: Action)
{
- match *self.active_queue.borrow() {
- ActiveActionQueue::A => self
- .queue_a
- .write_nonblock()
- .expect("Failed to aquire read-write action queue A lock")
- .push(action),
- ActiveActionQueue::B => self
- .queue_b
- .write_nonblock()
- .expect("Failed to aquire read-write action queue A lock")
- .push(action),
- }
- }
-}
-
-impl TypeName for ActionQueue
-{
- fn type_name(&self) -> &'static str
- {
- type_name::<Self>()
+ self.queue
+ .write_nonblock()
+ .expect("Failed to aquire read-write lock to action queue")
+ .push(action);
}
}
@@ -699,7 +693,7 @@ impl SoleStorage
self.storage.insert(
sole_type_id,
ManuallyDrop::new(StoredSole {
- sole: Arc::new(Lock::new(Box::new(sole))),
+ sole: Arc::new(Lock::new(Box::new(sole), type_name::<SoleT>())),
drop_last,
}),
);
@@ -716,18 +710,9 @@ impl Drop for SoleStorage
for sole in self.storage.values_mut() {
if sole.drop_last {
- tracing::trace!(
- "Sole {} pushed to dropping last queue",
- sole.sole.read_nonblock().unwrap().type_name()
- );
-
soles_to_drop_last.push(sole);
continue;
}
- tracing::trace!(
- "Dropping sole {}",
- sole.sole.read_nonblock().unwrap().type_name()
- );
unsafe {
ManuallyDrop::drop(sole);
@@ -735,11 +720,6 @@ impl Drop for SoleStorage
}
for sole in &mut soles_to_drop_last {
- tracing::trace!(
- "Dropping sole {} last",
- sole.sole.read_nonblock().unwrap().type_name()
- );
-
unsafe {
ManuallyDrop::drop(sole);
}
diff --git a/ecs/src/lock.rs b/ecs/src/lock.rs
index d6ed40e..fe4e08b 100644
--- a/ecs/src/lock.rs
+++ b/ecs/src/lock.rs
@@ -1,3 +1,4 @@
+use std::any::type_name;
use std::mem::forget;
use std::ops::{Deref, DerefMut};
@@ -9,57 +10,64 @@ use parking_lot::{
RwLockWriteGuard,
};
-use crate::type_name::TypeName;
-
-#[derive(Debug, Default)]
+#[derive(Debug)]
pub struct Lock<Value>
-where
- Value: TypeName,
{
inner: RwLock<Value>,
+ value_type_name: &'static str,
}
impl<Value> Lock<Value>
-where
- Value: TypeName,
{
- pub fn new(value: Value) -> Self
+ pub fn new(value: Value, value_type_name: &'static str) -> Self
{
- Self { inner: RwLock::new(value) }
+ Self {
+ inner: RwLock::new(value),
+ value_type_name,
+ }
}
/// Tries to a acquire a handle to the resource with read access.
///
/// # Errors
/// Returns `Err` if unavailable (A mutable handle is hold).
- pub fn read_nonblock(&self) -> Result<ReadGuard<Value>, Error>
+ pub fn read_nonblock(&self) -> Result<ReadGuard<'_, Value>, Error>
{
let guard = self.inner.try_read().ok_or(Error::ReadUnavailable)?;
- tracing::trace!("Acquired lock to value of type {}", guard.type_name());
+ tracing::trace!("Acquired lock to value of type {}", self.value_type_name);
- Ok(ReadGuard { inner: guard })
+ Ok(ReadGuard {
+ inner: guard,
+ value_type_name: self.value_type_name,
+ })
}
/// Tries to a acquire a handle to the resource with mutable access.
///
/// # Errors
/// Returns `Err` if unavailable (A mutable or immutable handle is hold).
- pub fn write_nonblock(&self) -> Result<WriteGuard<Value>, Error>
+ pub fn write_nonblock(&self) -> Result<WriteGuard<'_, Value>, Error>
{
let guard = self.inner.try_write().ok_or(Error::WriteUnavailable)?;
tracing::trace!(
"Acquired mutable lock to value of type {}",
- guard.type_name()
+ self.value_type_name
);
- Ok(WriteGuard { inner: guard })
+ Ok(WriteGuard {
+ inner: guard,
+ value_type_name: self.value_type_name,
+ })
}
+}
- pub fn into_inner(self) -> Value
+impl<Value: Default + 'static> Default for Lock<Value>
+{
+ fn default() -> Self
{
- self.inner.into_inner()
+ Self::new(Value::default(), type_name::<Value>())
}
}
@@ -75,37 +83,38 @@ pub enum Error
#[derive(Debug)]
pub struct ReadGuard<'guard, Value>
-where
- Value: TypeName,
{
inner: RwLockReadGuard<'guard, Value>,
+ value_type_name: &'static str,
}
impl<'guard, Value> ReadGuard<'guard, Value>
-where
- Value: TypeName,
{
- pub fn map<NewValue>(
- self,
- func: impl FnOnce(&Value) -> &NewValue,
- ) -> MappedReadGuard<'guard, NewValue>
- where
- NewValue: TypeName,
+ pub fn try_map<NewValue>(
+ this: Self,
+ func: impl FnOnce(&Value) -> Option<&NewValue>,
+ ) -> Result<MappedReadGuard<'guard, NewValue>, Self>
{
+ let value_type_name = this.value_type_name;
+
// The 'inner' field cannot be moved out of ReadGuard in a normal way since
// ReadGuard implements Drop
- let inner = unsafe { std::ptr::read(&self.inner) };
- forget(self);
-
- MappedReadGuard {
- inner: RwLockReadGuard::map(inner, func),
+ let inner = unsafe { std::ptr::read(&raw const this.inner) };
+ forget(this);
+
+ match RwLockReadGuard::try_map(inner, func) {
+ Ok(mapped_guard) => {
+ Ok(MappedReadGuard { inner: mapped_guard, value_type_name })
+ }
+ Err(unmapped_guard) => Err(Self {
+ inner: unmapped_guard,
+ value_type_name,
+ }),
}
}
}
impl<Value> Deref for ReadGuard<'_, Value>
-where
- Value: TypeName,
{
type Target = Value;
@@ -116,26 +125,21 @@ where
}
impl<Value> Drop for ReadGuard<'_, Value>
-where
- Value: TypeName,
{
fn drop(&mut self)
{
- tracing::trace!("Dropped lock to value of type {}", self.type_name());
+ tracing::trace!("Dropped lock to value of type {}", self.value_type_name);
}
}
#[derive(Debug)]
pub struct MappedReadGuard<'guard, Value>
-where
- Value: TypeName,
{
inner: MappedRwLockReadGuard<'guard, Value>,
+ value_type_name: &'static str,
}
impl<Value> Deref for MappedReadGuard<'_, Value>
-where
- Value: TypeName,
{
type Target = Value;
@@ -146,48 +150,50 @@ where
}
impl<Value> Drop for MappedReadGuard<'_, Value>
-where
- Value: TypeName,
{
fn drop(&mut self)
{
- tracing::trace!("Dropped mapped lock to value of type {}", self.type_name());
+ tracing::trace!(
+ "Dropped mapped lock to value of type {}",
+ self.value_type_name
+ );
}
}
#[derive(Debug)]
pub struct WriteGuard<'guard, Value>
-where
- Value: TypeName,
{
inner: RwLockWriteGuard<'guard, Value>,
+ value_type_name: &'static str,
}
impl<'guard, Value> WriteGuard<'guard, Value>
-where
- Value: TypeName,
{
- pub fn map<NewValue>(
- self,
- func: impl FnOnce(&mut Value) -> &mut NewValue,
- ) -> MappedWriteGuard<'guard, NewValue>
- where
- NewValue: TypeName,
+ pub fn try_map<NewValue>(
+ this: Self,
+ func: impl FnOnce(&mut Value) -> Option<&mut NewValue>,
+ ) -> Result<MappedWriteGuard<'guard, NewValue>, Self>
{
+ let value_type_name = this.value_type_name;
+
// The 'inner' field cannot be moved out of ReadGuard in a normal way since
// ReadGuard implements Drop
- let inner = unsafe { std::ptr::read(&self.inner) };
- forget(self);
-
- MappedWriteGuard {
- inner: RwLockWriteGuard::map(inner, func),
+ let inner = unsafe { std::ptr::read(&raw const this.inner) };
+ forget(this);
+
+ match RwLockWriteGuard::try_map(inner, func) {
+ Ok(mapped_guard) => {
+ Ok(MappedWriteGuard { inner: mapped_guard, value_type_name })
+ }
+ Err(unmapped_guard) => Err(Self {
+ inner: unmapped_guard,
+ value_type_name,
+ }),
}
}
}
impl<Value> Deref for WriteGuard<'_, Value>
-where
- Value: TypeName,
{
type Target = Value;
@@ -198,8 +204,6 @@ where
}
impl<Value> DerefMut for WriteGuard<'_, Value>
-where
- Value: TypeName,
{
fn deref_mut(&mut self) -> &mut Self::Target
{
@@ -208,26 +212,24 @@ where
}
impl<Value> Drop for WriteGuard<'_, Value>
-where
- Value: TypeName,
{
fn drop(&mut self)
{
- tracing::trace!("Dropped mutable lock to value of type {}", self.type_name());
+ tracing::trace!(
+ "Dropped mutable lock to value of type {}",
+ self.value_type_name
+ );
}
}
#[derive(Debug)]
pub struct MappedWriteGuard<'guard, Value>
-where
- Value: TypeName,
{
inner: MappedRwLockWriteGuard<'guard, Value>,
+ value_type_name: &'static str,
}
impl<Value> Deref for MappedWriteGuard<'_, Value>
-where
- Value: TypeName,
{
type Target = Value;
@@ -238,8 +240,6 @@ where
}
impl<Value> DerefMut for MappedWriteGuard<'_, Value>
-where
- Value: TypeName,
{
fn deref_mut(&mut self) -> &mut Self::Target
{
@@ -248,14 +248,12 @@ where
}
impl<Value> Drop for MappedWriteGuard<'_, Value>
-where
- Value: TypeName,
{
fn drop(&mut self)
{
tracing::trace!(
"Dropped mapped mutable lock to value of type {}",
- self.type_name()
+ self.value_type_name
);
}
}
diff --git a/ecs/src/pair.rs b/ecs/src/pair.rs
new file mode 100644
index 0000000..b4bfa57
--- /dev/null
+++ b/ecs/src/pair.rs
@@ -0,0 +1,687 @@
+use std::any::type_name;
+use std::convert::Infallible;
+use std::marker::PhantomData;
+
+use crate::component::{
+ Handle as ComponentHandle,
+ HandleError as ComponentHandleError,
+ HandleMut as ComponentHandleMut,
+ IntoParts as IntoComponentParts,
+ Parts as ComponentParts,
+};
+use crate::entity::{
+ Handle as EntityHandle,
+ MatchingComponentIter as EntityMatchingComponentIter,
+};
+use crate::query::{
+ TermWithField as QueryTermWithField,
+ TermsBuilder as QueryTermsBuilder,
+ TermsBuilderInterface,
+};
+use crate::uid::{Kind as UidKind, PairParams as UidPairParams, Uid, With as WithUid};
+use crate::util::impl_multiple;
+use crate::{Component, EntityComponentRef, World};
+
+/// Pair builder.
+#[derive(Debug)]
+pub struct Builder<Relation, Target>
+{
+ relation: Relation,
+ target: Target,
+}
+
+impl<Relation, Target> Builder<Relation, Target>
+{
+ pub fn relation<NewRelation: Component>(self) -> Builder<Uid, Target>
+ {
+ Builder {
+ relation: NewRelation::id(),
+ target: self.target,
+ }
+ }
+
+ pub fn relation_id(self, id: Uid) -> Builder<Uid, Target>
+ {
+ Builder { relation: id, target: self.target }
+ }
+
+ pub fn target<NewTarget: Component>(self) -> Builder<Relation, Uid>
+ {
+ Builder {
+ relation: self.relation,
+ target: NewTarget::id(),
+ }
+ }
+
+ pub fn target_id(self, id: Uid) -> Builder<Relation, Uid>
+ {
+ Builder { relation: self.relation, target: id }
+ }
+}
+
+impl_multiple!(
+ Builder,
+ (impl<Target> _<><Uid, Target>, impl<Target> _<><(), Target>)
+ cb=(type_params=(ty_param_1, ty_param_2)) => {
+ pub fn target_as_data<NewTarget: Component>(
+ self,
+ data: NewTarget,
+ ) -> Builder<$ty_param_1, NewTarget>
+ {
+ Builder {
+ relation: self.relation,
+ target: data,
+ }
+ }
+ }
+);
+
+impl_multiple!(
+ Builder,
+ (impl<Relation> _<><Relation, Uid>, impl<Relation> _<><Relation, ()>)
+ cb=(type_params=(ty_param_1, ty_param_2)) => {
+ pub fn relation_as_data<NewRelation: Component>(
+ self,
+ data: NewRelation,
+ ) -> Builder<NewRelation, $ty_param_2>
+ {
+ Builder {
+ relation: data,
+ target: self.target,
+ }
+ }
+ }
+);
+
+impl_multiple!(
+ Builder,
+ (
+ impl _<><Uid, Uid>,
+ impl<Relation: Component> _<><Relation, Uid>,
+ impl<Target: Component> _<><Uid, Target>,
+ impl<Relation: Component, Target: Component> _<><Relation, Target>
+ )
+ cb=(type_params=(ty_param_1, ty_param_2)) => {
+ #[must_use]
+ pub fn build(self) -> Pair<$ty_param_1, $ty_param_2>
+ {
+ Pair {
+ relation: self.relation,
+ target: self.target
+ }
+ }
+ }
+);
+
+impl Default for Builder<(), ()>
+{
+ fn default() -> Self
+ {
+ Self { relation: (), target: () }
+ }
+}
+
+#[derive(Debug)]
+pub struct Pair<Relation, Target>
+{
+ relation: Relation,
+ target: Target,
+}
+
+impl Pair<(), ()>
+{
+ #[must_use]
+ pub fn builder() -> Builder<(), ()>
+ {
+ Builder { relation: (), target: () }
+ }
+}
+
+impl Pair<Uid, Uid>
+{
+ #[must_use]
+ pub fn id(&self) -> Uid
+ {
+ Uid::new_pair(&UidPairParams {
+ relation: self.relation,
+ target: self.target,
+ })
+ }
+}
+
+impl IntoComponentParts for Pair<Uid, Uid>
+{
+ fn into_parts(self) -> ComponentParts
+ {
+ ComponentParts::builder().name("Pair").build(self.id(), ())
+ }
+}
+
+impl<Target> IntoComponentParts for Pair<Uid, Target>
+where
+ Target: Component,
+{
+ fn into_parts(self) -> ComponentParts
+ {
+ let id = Uid::new_pair(&UidPairParams {
+ relation: self.relation,
+ target: Target::id(),
+ });
+
+ ComponentParts::builder()
+ .name("Pair")
+ .build(id, self.target)
+ }
+}
+
+impl<Relation> IntoComponentParts for Pair<Relation, Uid>
+where
+ Relation: Component,
+{
+ fn into_parts(self) -> ComponentParts
+ {
+ let id = Uid::new_pair(&UidPairParams {
+ relation: Relation::id(),
+ target: self.target,
+ });
+
+ ComponentParts::builder()
+ .name("Pair")
+ .build(id, self.relation)
+ }
+}
+
+impl<Relation, Target> QueryTermWithField for Pair<Relation, &Target>
+where
+ Relation: Component,
+ Target: Component,
+{
+ type Field<'a> = ComponentHandle<'a, Target>;
+
+ fn apply_to_terms_builder<const MAX_TERM_CNT: usize>(
+ terms_builder: &mut QueryTermsBuilder<MAX_TERM_CNT>,
+ )
+ {
+ terms_builder.with_required([Pair::<Relation, Target>::uid()]);
+ }
+
+ fn get_field<'world>(
+ entity_handle: &EntityHandle<'world>,
+ _world: &'world World,
+ ) -> Self::Field<'world>
+ {
+ let target_component = entity_handle
+ .get_matching_components(Pair::<Relation, Target>::uid())
+ .next()
+ .expect("Not possible");
+
+ Self::Field::from_entity_component_ref(&target_component).unwrap_or_else(|err| {
+ panic!(
+ "Creating handle to target component {} failed: {err}",
+ type_name::<Target>()
+ );
+ })
+ }
+}
+
+impl<Relation, Target> QueryTermWithField for Pair<Relation, &mut Target>
+where
+ Relation: Component,
+ Target: Component,
+{
+ type Field<'a> = ComponentHandleMut<'a, Target>;
+
+ fn apply_to_terms_builder<const MAX_TERM_CNT: usize>(
+ terms_builder: &mut QueryTermsBuilder<MAX_TERM_CNT>,
+ )
+ {
+ terms_builder.with_required([Pair::<Relation, Target>::uid()]);
+ }
+
+ fn get_field<'world>(
+ entity_handle: &EntityHandle<'world>,
+ world: &'world World,
+ ) -> Self::Field<'world>
+ {
+ let target_component = entity_handle
+ .get_matching_components(Pair::<Relation, Target>::uid())
+ .next()
+ .expect("Not possible");
+
+ Self::Field::from_entity_component_ref(&target_component, world).unwrap_or_else(
+ |err| {
+ panic!(
+ "Creating handle to target component {} failed: {err}",
+ type_name::<Target>()
+ );
+ },
+ )
+ }
+}
+
+// TODO: implement QueryTermWithField for Pair<&Relation, Target> (or equivalent)
+// TODO: implement QueryTermWithField for Pair<&mut Relation, Target> (or equivalent)
+
+impl<Relation> QueryTermWithField for Pair<Relation, Wildcard>
+where
+ Relation: Component,
+{
+ type Field<'a> = WithWildcard<'a, Relation, Wildcard>;
+
+ fn apply_to_terms_builder<const MAX_TERM_CNT: usize>(
+ terms_builder: &mut QueryTermsBuilder<MAX_TERM_CNT>,
+ )
+ {
+ terms_builder.with_required([Self::uid()]);
+ }
+
+ fn get_field<'world>(
+ entity_handle: &EntityHandle<'world>,
+ world: &'world World,
+ ) -> Self::Field<'world>
+ {
+ let first_matching_comp = entity_handle
+ .get_matching_components(Self::uid())
+ .next()
+ .expect("Not possible");
+
+ WithWildcard {
+ world,
+ component_ref: first_matching_comp,
+ _pd: PhantomData,
+ }
+ }
+}
+
+impl<Relation, Target> WithUid for Pair<Relation, Target>
+where
+ Relation: Component,
+ Target: Component,
+{
+ fn uid() -> Uid
+ {
+ Uid::new_pair(&UidPairParams {
+ relation: Relation::id(),
+ target: Target::id(),
+ })
+ }
+}
+
+impl<Relation> WithUid for Pair<Relation, Wildcard>
+where
+ Relation: Component,
+{
+ fn uid() -> Uid
+ {
+ Uid::new_pair(&UidPairParams {
+ relation: Relation::id(),
+ target: Wildcard::uid(),
+ })
+ }
+}
+
+impl<Relation> QueryTermWithField for &'_ [Pair<Relation, Wildcard>]
+where
+ Relation: Component,
+{
+ type Field<'a> = MultipleWithWildcard<'a, Relation, Wildcard>;
+
+ fn apply_to_terms_builder<const MAX_TERM_CNT: usize>(
+ _terms_builder: &mut QueryTermsBuilder<MAX_TERM_CNT>,
+ )
+ {
+ }
+
+ fn get_field<'world>(
+ entity_handle: &EntityHandle<'world>,
+ world: &'world World,
+ ) -> Self::Field<'world>
+ {
+ MultipleWithWildcard {
+ entity_handle: entity_handle.clone(),
+ world,
+ _pd: PhantomData,
+ }
+ }
+}
+
+/// Reference to a pair with a wildcard relation/target.
+#[derive(Debug)]
+pub struct WithWildcard<'world, Relation, Target>
+{
+ world: &'world World,
+ component_ref: EntityComponentRef<'world>,
+ _pd: PhantomData<(Relation, Target)>,
+}
+
+impl<'world, Relation, Target> WithWildcard<'world, Relation, Target>
+{
+ /// Returns a new `WithWildcard`.
+ ///
+ /// # Panics
+ /// This function will panic if:
+ /// - The given component's ID is not a pair ID.
+ /// - `Relation::uid()` is not wildcard and does not equal to the relation of the
+ /// given component's ID
+ /// - `Target::uid()` is not wildcard and does not equal to the target of the given
+ /// component's ID
+ /// - Both `Relation::uid()` and `Target::uid()` are wildcards
+ /// - Neither `Relation::uid()` or `Target::uid()` are wildcards
+ pub fn new(world: &'world World, component_ref: EntityComponentRef<'world>) -> Self
+ where
+ Relation: ComponentOrWildcard,
+ Target: ComponentOrWildcard,
+ {
+ let component_id = component_ref.id();
+
+ assert!(component_id.kind() == UidKind::Pair);
+
+ assert!(
+ Relation::uid() == Wildcard::uid()
+ || component_id.relation_component() == Relation::uid()
+ );
+
+ assert!(
+ Target::uid() == Wildcard::uid()
+ || component_id.target_component() == Target::uid()
+ );
+
+ assert!(Relation::uid() == Wildcard::uid() || Target::uid() == Wildcard::uid());
+
+ assert!(
+ !(Relation::uid() == Wildcard::uid() && Target::uid() == Wildcard::uid())
+ );
+
+ WithWildcard {
+ world,
+ component_ref,
+ _pd: PhantomData,
+ }
+ }
+
+ /// Returns the [`Uid`] of the pair.
+ #[must_use]
+ pub fn id(&self) -> Uid
+ {
+ self.component_ref.id()
+ }
+
+ /// Attempts to get the component data of this pair, returning `None` if the `Data`
+ /// type is incorrect.
+ ///
+ /// # Panics
+ /// Will panic if the component data is mutably borrowed elsewhere.
+ #[must_use]
+ pub fn get_data<Data>(&self) -> Option<ComponentHandle<'_, Data>>
+ where
+ Data: 'static,
+ {
+ ComponentHandle::<Data>::from_entity_component_ref(&self.component_ref)
+ .map_or_else(
+ |err| match err {
+ ComponentHandleError::IncorrectType => None,
+ err @ ComponentHandleError::AcquireLockFailed(_) => {
+ panic!(
+ "Creating handle to pair data as component {} failed: {err}",
+ type_name::<Data>()
+ );
+ }
+ },
+ Some,
+ )
+ }
+
+ /// Attempts to get the component data of this pair, returning `None` if the `Data`
+ /// type is incorrect.
+ ///
+ /// # Panics
+ /// Will panic if the component data is borrowed elsewhere.
+ #[must_use]
+ pub fn get_data_mut<Data>(&self) -> Option<ComponentHandleMut<'_, Data>>
+ where
+ Data: 'static,
+ {
+ ComponentHandleMut::<Data>::from_entity_component_ref(
+ &self.component_ref,
+ self.world,
+ )
+ .map_or_else(
+ |err| match err {
+ ComponentHandleError::IncorrectType => None,
+ err @ ComponentHandleError::AcquireLockFailed(_) => {
+ panic!(
+ "Creating handle to pair data as component {} failed: {err}",
+ type_name::<Data>()
+ );
+ }
+ },
+ Some,
+ )
+ }
+}
+
+impl<Relation> WithWildcard<'_, Relation, Wildcard>
+where
+ Relation: Component,
+{
+ /// Attempts to retrieve the target as a entity, returning `None` if not found.
+ #[must_use]
+ pub fn get_target_ent(&self) -> Option<EntityHandle<'_>>
+ {
+ let archetype = self
+ .world
+ .data
+ .component_storage
+ .get_entity_archetype(self.component_ref.id().target_entity())?;
+
+ let Some(archetype_entity) =
+ archetype.get_entity_by_id(self.component_ref.id().target_entity())
+ else {
+ unreachable!();
+ };
+
+ Some(EntityHandle::new(archetype, archetype_entity, self.world))
+ }
+
+ /// Attempts to get the component data of this pair, returning `None` if the
+ /// `Relation` type is incorrect.
+ ///
+ /// # Panics
+ /// Will panic if the component data is mutably borrowed elsewhere.
+ #[must_use]
+ pub fn get_data_as_relation(&self) -> Option<ComponentHandle<'_, Relation>>
+ {
+ ComponentHandle::<Relation>::from_entity_component_ref(&self.component_ref)
+ .map_or_else(
+ |err| match err {
+ ComponentHandleError::IncorrectType => None,
+ err @ ComponentHandleError::AcquireLockFailed(_) => {
+ panic!(
+ "Creating handle to pair data as component {} failed: {err}",
+ type_name::<Relation>()
+ );
+ }
+ },
+ Some,
+ )
+ }
+
+ /// Attempts to get the component data of this pair, returning `None` if the
+ /// `Relation` type is incorrect.
+ ///
+ /// # Panics
+ /// Will panic if the component data is borrowed elsewhere.
+ #[must_use]
+ pub fn get_data_as_relation_mut(&self) -> Option<ComponentHandleMut<'_, Relation>>
+ {
+ ComponentHandleMut::<Relation>::from_entity_component_ref(
+ &self.component_ref,
+ self.world,
+ )
+ .map_or_else(
+ |err| match err {
+ ComponentHandleError::IncorrectType => None,
+ err @ ComponentHandleError::AcquireLockFailed(_) => {
+ panic!(
+ "Creating handle to pair data as component {} failed: {err}",
+ type_name::<Relation>()
+ );
+ }
+ },
+ Some,
+ )
+ }
+}
+
+/// Used to access matching pairs in a entity containing zero or more matching pairs.
+#[derive(Debug)]
+pub struct MultipleWithWildcard<'a, Relation, Target>
+{
+ entity_handle: EntityHandle<'a>,
+ world: &'a World,
+ _pd: PhantomData<(Relation, Target)>,
+}
+
+impl<'world, Relation, Target> MultipleWithWildcard<'world, Relation, Target>
+{
+ /// Returns a new `MultipleWithWildcard`.
+ ///
+ /// # Panics
+ /// This function will panic if:
+ /// - Both `Relation::uid()` and `Target::uid()` are wildcards
+ /// - Neither `Relation::uid()` or `Target::uid()` are wildcards
+ pub fn new(world: &'world World, entity_handle: EntityHandle<'world>) -> Self
+ where
+ Relation: ComponentOrWildcard,
+ Target: ComponentOrWildcard,
+ {
+ assert!(Relation::uid() == Wildcard::uid() || Target::uid() == Wildcard::uid());
+
+ assert!(
+ !(Relation::uid() == Wildcard::uid() && Target::uid() == Wildcard::uid())
+ );
+
+ MultipleWithWildcard {
+ entity_handle,
+ world,
+ _pd: PhantomData,
+ }
+ }
+}
+
+impl<'a, Relation: Component> MultipleWithWildcard<'a, Relation, Wildcard>
+{
+ #[must_use]
+ pub fn get_with_target_id(
+ &self,
+ target_id: Uid,
+ ) -> Option<WithWildcard<'a, Relation, Wildcard>>
+ {
+ Some(WithWildcard {
+ world: self.world,
+ component_ref: self
+ .entity_handle
+ .get_matching_components(
+ Pair::builder()
+ .relation::<Relation>()
+ .target_id(target_id)
+ .build()
+ .id(),
+ )
+ .next()?,
+ _pd: PhantomData,
+ })
+ }
+}
+
+impl<'a, Relation: Component> IntoIterator
+ for MultipleWithWildcard<'a, Relation, Wildcard>
+{
+ type IntoIter = WithWildcardIter<'a, Relation, Wildcard>;
+ type Item = <Self::IntoIter as Iterator>::Item;
+
+ fn into_iter(self) -> Self::IntoIter
+ {
+ WithWildcardIter {
+ inner: self
+ .entity_handle
+ .get_matching_components(Pair::<Relation, Wildcard>::uid()),
+ world: self.world,
+ _pd: PhantomData,
+ }
+ }
+}
+
+/// Iterator of matching pairs in a entity.
+pub struct WithWildcardIter<'a, Relation, Target>
+{
+ inner: EntityMatchingComponentIter<'a>,
+ world: &'a World,
+ _pd: PhantomData<(Relation, Target)>,
+}
+
+impl<'a, Relation, Target> Iterator for WithWildcardIter<'a, Relation, Target>
+{
+ type Item = WithWildcard<'a, Relation, Target>;
+
+ fn next(&mut self) -> Option<Self::Item>
+ {
+ let matching_comp = self.inner.next()?;
+
+ Some(WithWildcard {
+ world: self.world,
+ component_ref: matching_comp,
+ _pd: PhantomData,
+ })
+ }
+}
+
+/// Relation denoting a dependency to another entity
+#[derive(Debug, Default, Clone, Copy, Component)]
+pub struct DependsOn;
+
+/// Relation denoting being the child of another entity.
+#[derive(Debug, Default, Clone, Copy, Component)]
+pub struct ChildOf;
+
+#[derive(Debug)]
+pub struct Wildcard(Infallible);
+
+impl Wildcard
+{
+ #[must_use]
+ pub fn uid() -> Uid
+ {
+ Uid::wildcard()
+ }
+}
+
+pub trait ComponentOrWildcard: sealed::Sealed
+{
+ fn uid() -> Uid;
+}
+
+impl<ComponentT: Component> ComponentOrWildcard for ComponentT
+{
+ fn uid() -> Uid
+ {
+ ComponentT::id()
+ }
+}
+
+impl<ComponentT: Component> sealed::Sealed for ComponentT {}
+
+impl ComponentOrWildcard for Wildcard
+{
+ fn uid() -> Uid
+ {
+ Wildcard::uid()
+ }
+}
+
+impl sealed::Sealed for Wildcard {}
+
+mod sealed
+{
+ pub trait Sealed {}
+}
diff --git a/ecs/src/phase.rs b/ecs/src/phase.rs
index b8660f2..39f2a08 100644
--- a/ecs/src/phase.rs
+++ b/ecs/src/phase.rs
@@ -1,15 +1,19 @@
use ecs_macros::Component;
-use crate::relationship::{ChildOf, Relationship};
-use crate::static_entity;
+use crate::{declare_entity, World};
#[derive(Debug, Default, Clone, Copy, Component)]
pub struct Phase;
-static_entity!(pub START, (Phase,));
+declare_entity!(pub START, (Phase,));
+declare_entity!(pub PRE_UPDATE, (Phase,));
+declare_entity!(pub UPDATE, (Phase,));
+declare_entity!(pub POST_UPDATE, (Phase,));
-static_entity!(pub PRE_UPDATE, (Phase,));
-
-static_entity!(pub UPDATE, (Phase, <Relationship<ChildOf, Phase>>::new(*PRE_UPDATE)));
-
-static_entity!(pub PRESENT, (Phase, <Relationship<ChildOf, Phase>>::new(*UPDATE)));
+pub(crate) fn spawn_entities(world: &mut World)
+{
+ world.create_declared_entity(&START);
+ world.create_declared_entity(&PRE_UPDATE);
+ world.create_declared_entity(&UPDATE);
+ world.create_declared_entity(&POST_UPDATE);
+}
diff --git a/ecs/src/private.rs b/ecs/src/private.rs
deleted file mode 100644
index 56a6552..0000000
--- a/ecs/src/private.rs
+++ /dev/null
@@ -1,2 +0,0 @@
-#[doc(hidden)]
-pub use {linkme, paste};
diff --git a/ecs/src/query.rs b/ecs/src/query.rs
index b29db3d..5f13579 100644
--- a/ecs/src/query.rs
+++ b/ecs/src/query.rs
@@ -3,11 +3,15 @@ use std::marker::PhantomData;
use seq_macro::seq;
-use crate::component::{Component, FromLockedOptional, Ref as ComponentRef};
+use crate::component::{
+ Component,
+ Handle as ComponentHandle,
+ HandleMut as ComponentHandleMut,
+};
use crate::entity::Handle as EntityHandle;
use crate::query::flexible::{Iter as FlexibleQueryIter, Query as FlexibleQuery};
-use crate::system::{Param as SystemParam, System};
-use crate::uid::Uid;
+use crate::system::{Metadata as SystemMetadata, Param as SystemParam};
+use crate::uid::{Kind as UidKind, Uid, With as WithUid};
use crate::util::array_vec::ArrayVec;
use crate::util::Array;
use crate::World;
@@ -15,15 +19,16 @@ use crate::World;
pub mod flexible;
pub mod term;
+// A term tuple type can have a maximum of 17 elements
+pub const MAX_TERM_CNT: usize = 17;
+
#[derive(Debug)]
pub struct Query<'world, FieldTerms, FieldlessTerms = ()>
where
FieldTerms: TermWithFieldTuple,
FieldlessTerms: TermWithoutFieldTuple,
{
- world: &'world World,
- // A term tuple type can have a maximum of 17 elements
- inner: FlexibleQuery<'world, 17>,
+ inner: FlexibleQuery<'world, MAX_TERM_CNT>,
_pd: PhantomData<(FieldTerms, FieldlessTerms)>,
}
@@ -42,8 +47,8 @@ where
tracing::trace!("Searching for {}", std::any::type_name::<FieldTerms>());
Iter {
- world: self.world,
- iter: self.inner.iter(),
+ world: self.inner.world(),
+ inner: self.inner.iter(),
comps_pd: PhantomData,
}
}
@@ -58,7 +63,7 @@ where
tracing::trace!("Searching for {}", std::any::type_name::<FieldTerms>());
ComponentAndEuidIter {
- world: self.world,
+ world: self.inner.world(),
iter: self.inner.iter(),
comps_pd: PhantomData,
}
@@ -80,8 +85,8 @@ where
tracing::trace!("Searching for {}", std::any::type_name::<FieldTerms>());
Iter {
- world: self.world,
- iter: func(self.inner.iter()),
+ world: self.inner.world(),
+ inner: func(self.inner.iter()),
comps_pd: PhantomData,
}
}
@@ -93,6 +98,25 @@ where
Some(self.inner.iter().nth(entity_index)?.uid())
}
+ /// Returns a new `Query` created from a [`FlexibleQuery`].
+ ///
+ /// # Important notes
+ /// The terms in `FieldTerms` and `FieldlessTerms` must be compatible with the terms
+ /// in the given [`FlexibleQuery`], otherwise any method call or iterating might
+ /// panic.
+ #[must_use]
+ pub fn from_flexible_query(
+ flexible_query: FlexibleQuery<'world, MAX_TERM_CNT>,
+ ) -> Self
+ {
+ // TODO: Check compatability of terms
+
+ Self {
+ inner: flexible_query,
+ _pd: PhantomData,
+ }
+ }
+
pub(crate) fn new(world: &'world World) -> Self
{
let mut terms_builder = Terms::builder();
@@ -101,7 +125,6 @@ where
FieldlessTerms::apply_terms_to_builder(&mut terms_builder);
Self {
- world,
inner: world.flexible_query(terms_builder.build()),
_pd: PhantomData,
}
@@ -111,7 +134,7 @@ where
impl<'query, 'world, FieldTerms, FieldlessTerms> IntoIterator
for &'query Query<'world, FieldTerms, FieldlessTerms>
where
- FieldTerms: TermWithFieldTuple + 'world,
+ FieldTerms: TermWithFieldTuple,
FieldlessTerms: TermWithoutFieldTuple,
{
type IntoIter = Iter<'query, 'world, FieldTerms, FlexibleQueryIter<'query>>;
@@ -131,17 +154,7 @@ where
{
type Input = ();
- fn initialize<SystemImpl>(
- _system: &mut impl System<'world, SystemImpl>,
- _input: Self::Input,
- )
- {
- }
-
- fn new<SystemImpl>(
- _system: &'world impl System<'world, SystemImpl>,
- world: &'world World,
- ) -> Self
+ fn new(world: &'world World, _system_metadata: &SystemMetadata) -> Self
{
Self::new(world)
}
@@ -163,19 +176,23 @@ impl<const MAX_TERM_CNT: usize> Terms<MAX_TERM_CNT>
}
#[derive(Debug, Default)]
+#[must_use]
pub struct TermsBuilder<const MAX_TERM_CNT: usize>
{
required_components: ArrayVec<Uid, MAX_TERM_CNT>,
excluded_components: ArrayVec<Uid, MAX_TERM_CNT>,
}
+#[allow(clippy::return_self_not_must_use)]
pub trait TermsBuilderInterface
{
- fn with<ComponentT: Component>(self) -> Self;
+ fn with<WithUidT: WithUid>(self) -> Self;
- fn without<ComponentT: Component>(self) -> Self;
+ fn without<WithUidT: WithUid>(self) -> Self;
fn with_required(self, ids: impl Array<Uid>) -> Self;
+
+ fn without_ids(self, ids: impl Array<Uid>) -> Self;
}
macro_rules! impl_terms_builder {
@@ -196,36 +213,25 @@ macro_rules! impl_terms_builder {
impl_terms_builder! {
#[allow(unused_mut)]
- fn with<ComponentT: Component>(mut self) -> Self
+ fn with<WithUidT: WithUid>(mut self) -> Self
{
- if ComponentT::is_optional() {
- return self;
- }
-
let insert_index = self.required_components
- .partition_point(|id| *id <= ComponentT::id());
+ .partition_point(|id| *id <= WithUidT::uid());
self.required_components
- .insert(insert_index, ComponentT::id());
+ .insert(insert_index, WithUidT::uid());
self
}
#[allow(unused_mut)]
- fn without<ComponentT: Component>(mut self) -> Self
+ fn without<WithUidT: WithUid>(mut self) -> Self
{
- if ComponentT::is_optional() {
- panic!(
- "{}::without cannot take optional component",
- type_name::<Self>()
- );
- }
-
let insert_index = self.excluded_components
- .partition_point(|id| *id <= ComponentT::id());
+ .partition_point(|id| *id <= WithUidT::uid());
self.excluded_components
- .insert(insert_index, ComponentT::id());
+ .insert(insert_index, WithUidT::uid());
self
}
@@ -237,7 +243,7 @@ impl_terms_builder! {
ids.as_mut().sort();
}
- if self.required_components.len() == 0 {
+ if self.required_components.is_empty() {
self.required_components.extend(ids);
return self;
}
@@ -261,14 +267,47 @@ impl_terms_builder! {
self
}
+
+ #[allow(unused_mut)]
+ fn without_ids(mut self, mut ids: impl Array<Uid>) -> Self
+ {
+ if !ids.as_ref().is_sorted() {
+ ids.as_mut().sort();
+ }
+
+ if self.excluded_components.is_empty() {
+ self.excluded_components.extend(ids);
+ return self;
+ }
+
+ let mut id_iter = ids.into_iter();
+
+ while let Some(id) = id_iter.next() {
+ let insert_index = self.excluded_components
+ .partition_point(|other_id| *other_id <= id);
+
+ if insert_index == self.excluded_components.len() {
+ self.excluded_components.extend([id].into_iter().chain(id_iter));
+
+ return self;
+ }
+
+ self.excluded_components
+ .insert(insert_index, id);
+
+ }
+
+ self
+ }
}
impl<const MAX_TERM_CNT: usize> TermsBuilder<MAX_TERM_CNT>
{
+ #[must_use]
pub fn build(self) -> Terms<MAX_TERM_CNT>
{
- assert!(self.required_components.is_sorted());
- assert!(self.excluded_components.is_sorted());
+ debug_assert!(self.required_components.is_sorted());
+ debug_assert!(self.excluded_components.is_sorted());
Terms {
required_components: self.required_components,
@@ -298,15 +337,56 @@ pub trait TermWithField
) -> Self::Field<'world>;
}
-impl<ComponentRefT: ComponentRef> TermWithField for ComponentRefT
+impl<ComponentT: Component> TermWithField for &ComponentT
{
- type Field<'a> = ComponentRefT::Handle<'a>;
+ type Field<'a> = ComponentHandle<'a, ComponentT>;
fn apply_to_terms_builder<const MAX_TERM_CNT: usize>(
terms_builder: &mut TermsBuilder<MAX_TERM_CNT>,
)
{
- terms_builder.with::<ComponentRefT::Component>();
+ terms_builder.with::<ComponentT>();
+ }
+
+ fn get_field<'world>(
+ entity_handle: &EntityHandle<'world>,
+ _world: &'world World,
+ ) -> Self::Field<'world>
+ {
+ assert_eq!(ComponentT::id().kind(), UidKind::Component);
+
+ let Some(component) = entity_handle
+ .get_matching_components(ComponentT::id())
+ .next()
+ else {
+ panic!(
+ concat!(
+ "Component {} was not found in entity {}. There ",
+ "is most likely a bug in the entity querying"
+ ),
+ type_name::<ComponentT>(),
+ entity_handle.uid()
+ );
+ };
+
+ Self::Field::from_entity_component_ref(&component).unwrap_or_else(|err| {
+ panic!(
+ "Creating handle to component {} failed: {err}",
+ type_name::<ComponentT>()
+ );
+ })
+ }
+}
+
+impl<ComponentT: Component> TermWithField for &mut ComponentT
+{
+ type Field<'a> = ComponentHandleMut<'a, ComponentT>;
+
+ fn apply_to_terms_builder<const MAX_TERM_CNT: usize>(
+ terms_builder: &mut TermsBuilder<MAX_TERM_CNT>,
+ )
+ {
+ terms_builder.with::<ComponentT>();
}
fn get_field<'world>(
@@ -314,16 +394,26 @@ impl<ComponentRefT: ComponentRef> TermWithField for ComponentRefT
world: &'world World,
) -> Self::Field<'world>
{
- Self::Field::from_locked_optional_component(
- entity_handle
- .get_component(ComponentRefT::Component::id())
- .map(|component| component.component()),
- world,
- )
- .unwrap_or_else(|err| {
+ assert_eq!(ComponentT::id().kind(), UidKind::Component);
+
+ let Some(component) = entity_handle
+ .get_matching_components(ComponentT::id())
+ .next()
+ else {
+ panic!(
+ concat!(
+ "Component {} was not found in entity {}. There ",
+ "is most likely a bug in the entity querying"
+ ),
+ type_name::<ComponentT>(),
+ entity_handle.uid()
+ );
+ };
+
+ Self::Field::from_entity_component_ref(&component, world).unwrap_or_else(|err| {
panic!(
- "Taking component {} lock failed: {err}",
- type_name::<ComponentRefT::Component>()
+ "Creating handle to component {} failed: {err}",
+ type_name::<ComponentT>()
);
})
}
@@ -352,37 +442,18 @@ pub trait TermWithFieldTuple
pub struct Iter<'query, 'world, FieldTerms, EntityHandleIter>
where
- FieldTerms: TermWithFieldTuple + 'world,
+ FieldTerms: TermWithFieldTuple,
EntityHandleIter: Iterator<Item = EntityHandle<'query>>,
{
world: &'world World,
- iter: EntityHandleIter,
+ inner: EntityHandleIter,
comps_pd: PhantomData<FieldTerms>,
}
-impl<'query, 'world, FieldTerms, EntityHandleIter>
- Iter<'query, 'world, FieldTerms, EntityHandleIter>
-where
- FieldTerms: TermWithFieldTuple + 'world,
- EntityHandleIter: Iterator<Item = EntityHandle<'query>>,
- 'world: 'query,
-{
- /// Creates a new iterator from the given entity handle iterator.
- ///
- /// # Important
- /// All of the yielded entities of the entity handle iterator should match the
- /// terms `Terms`. The [`Self::next`] function will panic if it encounters a
- /// entity that does not match the terms `Terms`.
- pub fn new(world: &'world World, iter: EntityHandleIter) -> Self
- {
- Self { world, iter, comps_pd: PhantomData }
- }
-}
-
impl<'query, 'world, FieldTerms, EntityHandleIter> Iterator
for Iter<'query, 'world, FieldTerms, EntityHandleIter>
where
- FieldTerms: TermWithFieldTuple + 'world,
+ FieldTerms: TermWithFieldTuple,
EntityHandleIter: Iterator<Item = EntityHandle<'query>>,
'world: 'query,
{
@@ -390,7 +461,7 @@ where
fn next(&mut self) -> Option<Self::Item>
{
- let entity_handle = self.iter.next()?;
+ let entity_handle = self.inner.next()?;
Some(FieldTerms::get_fields(&entity_handle, self.world))
}
@@ -398,7 +469,7 @@ where
pub struct ComponentAndEuidIter<'query, 'world, FieldTerms, EntityHandleIter>
where
- FieldTerms: TermWithFieldTuple + 'world,
+ FieldTerms: TermWithFieldTuple,
EntityHandleIter: Iterator<Item = EntityHandle<'query>>,
{
world: &'world World,
@@ -409,7 +480,7 @@ where
impl<'query, 'world, FieldTerms, EntityHandleIter> Iterator
for ComponentAndEuidIter<'query, 'world, FieldTerms, EntityHandleIter>
where
- FieldTerms: TermWithFieldTuple + 'world,
+ FieldTerms: TermWithFieldTuple,
EntityHandleIter: Iterator<Item = EntityHandle<'query>>,
'world: 'query,
{
diff --git a/ecs/src/query/flexible.rs b/ecs/src/query/flexible.rs
index 2f0b5e7..936ab82 100644
--- a/ecs/src/query/flexible.rs
+++ b/ecs/src/query/flexible.rs
@@ -2,13 +2,8 @@
use std::iter::{repeat_n, FlatMap, RepeatN, Zip};
use crate::component::storage::archetype::{Archetype, EntityIter};
-use crate::component::storage::{
- ArchetypeRefIter,
- ArchetypeSearchTerms,
- Storage as ComponentStorage,
-};
+use crate::component::storage::{ArchetypeRefIter, ArchetypeSearchTerms};
use crate::entity::Handle as EntityHandle;
-use crate::lock::ReadGuard;
use crate::query::Terms;
use crate::World;
@@ -16,7 +11,7 @@ use crate::World;
#[derive(Debug)]
pub struct Query<'world, const MAX_TERM_CNT: usize>
{
- component_storage: ReadGuard<'world, ComponentStorage>,
+ world: &'world World,
terms: Terms<MAX_TERM_CNT>,
}
@@ -28,6 +23,8 @@ impl<'world, const MAX_TERM_CNT: usize> Query<'world, MAX_TERM_CNT>
{
Iter {
iter: self
+ .world
+ .data
.component_storage
.search_archetypes(ArchetypeSearchTerms {
required_components: &self.terms.required_components,
@@ -39,25 +36,37 @@ impl<'world, const MAX_TERM_CNT: usize> Query<'world, MAX_TERM_CNT>
.zip(archetype.entities())
}) as ComponentIterMapFn,
),
+ world: self.world,
}
}
+ #[must_use]
+ pub fn world(&self) -> &'world World
+ {
+ self.world
+ }
+
pub(crate) fn new(world: &'world World, terms: Terms<MAX_TERM_CNT>) -> Self
{
- Self {
- component_storage: world
- .data
- .component_storage
- .read_nonblock()
- .expect("Failed to acquire read-only component storage lock"),
- terms,
- }
+ Self { world, terms }
+ }
+}
+
+impl<'query, const MAX_TERM_CNT: usize> IntoIterator for &'query Query<'_, MAX_TERM_CNT>
+{
+ type IntoIter = Iter<'query>;
+ type Item = EntityHandle<'query>;
+
+ fn into_iter(self) -> Self::IntoIter
+ {
+ self.iter()
}
}
pub struct Iter<'query>
{
iter: QueryEntityIter<'query>,
+ world: &'query World,
}
impl<'query> Iterator for Iter<'query>
@@ -68,7 +77,7 @@ impl<'query> Iterator for Iter<'query>
{
let (archetype, entity) = self.iter.next()?;
- Some(EntityHandle::new(archetype, entity))
+ Some(EntityHandle::new(archetype, entity, self.world))
}
}
diff --git a/ecs/src/query/term.rs b/ecs/src/query/term.rs
index ce453f0..0683918 100644
--- a/ecs/src/query/term.rs
+++ b/ecs/src/query/term.rs
@@ -1,42 +1,116 @@
+use std::any::type_name;
use std::marker::PhantomData;
-use crate::component::Component;
-use crate::query::{TermWithoutField, TermsBuilder, TermsBuilderInterface};
+use crate::component::{
+ Component,
+ Handle as ComponentHandle,
+ HandleMut as ComponentHandleMut,
+};
+use crate::query::{
+ TermWithField,
+ TermWithoutField,
+ TermsBuilder,
+ TermsBuilderInterface,
+};
+use crate::uid::With as WithUid;
-pub struct With<ComponentT>
+pub struct With<WithUidT>
where
- ComponentT: Component,
+ WithUidT: WithUid,
{
- _pd: PhantomData<ComponentT>,
+ _pd: PhantomData<WithUidT>,
}
-impl<ComponentT> TermWithoutField for With<ComponentT>
+impl<WithUidT> TermWithoutField for With<WithUidT>
where
- ComponentT: Component,
+ WithUidT: WithUid,
{
fn apply_to_terms_builder<const MAX_TERM_CNT: usize>(
terms_builder: &mut TermsBuilder<MAX_TERM_CNT>,
)
{
- terms_builder.with::<ComponentT>();
+ terms_builder.with::<WithUidT>();
}
}
-pub struct Without<ComponentT>
+pub struct Without<WithUidT>
where
- ComponentT: Component,
+ WithUidT: WithUid,
{
- _pd: PhantomData<ComponentT>,
+ _pd: PhantomData<WithUidT>,
}
-impl<ComponentT> TermWithoutField for Without<ComponentT>
+impl<WithUidT> TermWithoutField for Without<WithUidT>
where
- ComponentT: Component,
+ WithUidT: WithUid,
{
fn apply_to_terms_builder<const MAX_TERM_CNT: usize>(
terms_builder: &mut TermsBuilder<MAX_TERM_CNT>,
)
{
- terms_builder.without::<ComponentT>();
+ terms_builder.without::<WithUidT>();
+ }
+}
+
+impl<ComponentT: Component> TermWithField for Option<&ComponentT>
+{
+ type Field<'a> = Option<ComponentHandle<'a, ComponentT>>;
+
+ fn apply_to_terms_builder<const MAX_TERM_CNT: usize>(
+ _terms_builder: &mut TermsBuilder<MAX_TERM_CNT>,
+ )
+ {
+ }
+
+ fn get_field<'world>(
+ entity_handle: &crate::entity::Handle<'world>,
+ _world: &'world crate::World,
+ ) -> Self::Field<'world>
+ {
+ Some(
+ ComponentHandle::<'world, ComponentT>::from_entity_component_ref(
+ &entity_handle
+ .get_matching_components(ComponentT::id())
+ .next()?,
+ )
+ .unwrap_or_else(|err| {
+ panic!(
+ "Creating handle to component {} failed: {err}",
+ type_name::<ComponentT>()
+ );
+ }),
+ )
+ }
+}
+
+impl<ComponentT: Component> TermWithField for Option<&mut ComponentT>
+{
+ type Field<'a> = Option<ComponentHandleMut<'a, ComponentT>>;
+
+ fn apply_to_terms_builder<const MAX_TERM_CNT: usize>(
+ _terms_builder: &mut TermsBuilder<MAX_TERM_CNT>,
+ )
+ {
+ }
+
+ fn get_field<'world>(
+ entity_handle: &crate::entity::Handle<'world>,
+ world: &'world crate::World,
+ ) -> Self::Field<'world>
+ {
+ Some(
+ ComponentHandleMut::<'world, ComponentT>::from_entity_component_ref(
+ &entity_handle
+ .get_matching_components(ComponentT::id())
+ .next()?,
+ world,
+ )
+ .unwrap_or_else(|err| {
+ panic!(
+ "Creating handle to component {} failed: {err}",
+ type_name::<ComponentT>()
+ );
+ }),
+ )
}
}
diff --git a/ecs/src/relationship.rs b/ecs/src/relationship.rs
deleted file mode 100644
index 45fa265..0000000
--- a/ecs/src/relationship.rs
+++ /dev/null
@@ -1,466 +0,0 @@
-use std::any::type_name;
-use std::marker::PhantomData;
-
-use ecs_macros::Component;
-
-use crate::component::storage::Storage as ComponentStorage;
-use crate::component::{
- Component,
- FromLockedOptional as FromLockedOptionalComponent,
- Handle as ComponentHandle,
- HandleMut as ComponentHandleMut,
-};
-use crate::lock::{Error as LockError, Lock, ReadGuard};
-use crate::uid::{Kind as UidKind, Uid};
-use crate::World;
-
-/// A relationship to one or more targets.
-#[derive(Debug, Component)]
-#[component(
- handle_type = Relation<'component, Kind, ComponentT>,
- handle_mut_type = RelationMut<'component, Kind, ComponentT>,
-)]
-pub struct Relationship<Kind, ComponentT: Component>
-where
- Kind: 'static,
-{
- entity_uid: SingleOrMultiple<Uid>,
- _pd: PhantomData<(Kind, ComponentT)>,
-}
-
-impl<Kind, ComponentT> Relationship<Kind, ComponentT>
-where
- ComponentT: Component,
-{
- /// Creates a new `Relationship` with a single target.
- #[must_use]
- pub fn new(entity_uid: Uid) -> Self
- {
- debug_assert_eq!(entity_uid.kind(), UidKind::Entity);
-
- Self {
- entity_uid: SingleOrMultiple::Single(entity_uid),
- _pd: PhantomData,
- }
- }
-
- /// Creates a new `Relationship` with multiple targets.
- #[must_use]
- pub fn new_multiple(entity_uids: impl IntoIterator<Item = Uid>) -> Self
- {
- let uids = entity_uids.into_iter().collect::<Vec<_>>();
-
- for euid in &uids {
- debug_assert_eq!(euid.kind(), UidKind::Entity);
- }
-
- Self {
- entity_uid: SingleOrMultiple::Multiple(uids),
- _pd: PhantomData,
- }
- }
-}
-
-pub struct RelationMut<'rel_comp, Kind, ComponentT>
-where
- Kind: 'static,
- ComponentT: Component,
-{
- component_storage_lock: ReadGuard<'rel_comp, ComponentStorage>,
- relationship_comp: ComponentHandleMut<'rel_comp, Relationship<Kind, ComponentT>>,
-}
-
-impl<'rel_comp, Kind, ComponentT> FromLockedOptionalComponent<'rel_comp>
- for RelationMut<'rel_comp, Kind, ComponentT>
-where
- ComponentT: Component,
-{
- fn from_locked_optional_component(
- optional_component: Option<&'rel_comp crate::lock::Lock<Box<dyn Component>>>,
- world: &'rel_comp World,
- ) -> Result<Self, LockError>
- {
- let relationship_comp_handle_from_locked_opt_comp = ComponentHandleMut::<
- Relationship<Kind, ComponentT>,
- >::from_locked_optional_component;
-
- let relationship_comp =
- relationship_comp_handle_from_locked_opt_comp(optional_component, world)?;
-
- let component_storage_lock = world
- .data
- .component_storage
- .read_nonblock()
- .expect("Failed to aquire read-only component storage lock");
-
- Ok(Self {
- relationship_comp,
- component_storage_lock,
- })
- }
-}
-
-impl<'rel_comp, Kind, ComponentT> FromLockedOptionalComponent<'rel_comp>
- for Option<RelationMut<'rel_comp, Kind, ComponentT>>
-where
- ComponentT: Component,
-{
- fn from_locked_optional_component(
- optional_component: Option<&'rel_comp Lock<Box<dyn Component>>>,
- world: &'rel_comp World,
- ) -> Result<Self, crate::lock::Error>
- {
- optional_component
- .map(|component| {
- RelationMut::from_locked_optional_component(Some(component), world)
- })
- .transpose()
- }
-}
-
-impl<'rel_comp, Kind, ComponentT> RelationMut<'rel_comp, Kind, ComponentT>
-where
- ComponentT: Component,
-{
- /// Returns the component of the target at the specified index.
- ///
- /// # Panics
- /// Will panic if the entity does not exist in the archetype it belongs to. This
- /// should hopefully never happend.
- #[must_use]
- pub fn get(&self, index: usize) -> Option<ComponentHandleMut<'_, ComponentT>>
- {
- let target = self.get_target(index)?;
-
- let archetype = self.component_storage_lock.get_entity_archetype(*target)?;
-
- let entity = archetype
- .get_entity_by_id(*target)
- .expect("Target entity is gone from archetype");
-
- let component_index = archetype.get_index_for_component(ComponentT::id())?;
-
- let component = ComponentHandleMut::new(
- entity
- .components()
- .get(component_index)?
- .component()
- .write_nonblock()
- .unwrap_or_else(|_| {
- panic!(
- "Failed to aquire read-write lock of component {}",
- type_name::<ComponentT>()
- )
- }),
- );
-
- Some(component)
- }
-
- /// Returns a reference to the target at the specified index.
- #[must_use]
- pub fn get_target(&self, index: usize) -> Option<&Uid>
- {
- match &self.relationship_comp.entity_uid {
- SingleOrMultiple::Single(entity_uid) if index == 0 => Some(entity_uid),
- SingleOrMultiple::Multiple(entity_uids) => entity_uids.get(index),
- SingleOrMultiple::Single(_) => None,
- }
- }
-
- /// Returns a mutable reference to the target at the specified index.
- #[must_use]
- pub fn get_target_mut(&mut self, index: usize) -> Option<&mut Uid>
- {
- match &mut self.relationship_comp.entity_uid {
- SingleOrMultiple::Single(entity_uid) if index == 0 => Some(entity_uid),
- SingleOrMultiple::Multiple(entity_uids) => entity_uids.get_mut(index),
- SingleOrMultiple::Single(_) => None,
- }
- }
-
- /// Adds a target to the relationship.
- pub fn add_target(&mut self, entity_uid: Uid)
- {
- debug_assert_eq!(entity_uid.kind(), UidKind::Entity);
-
- match &mut self.relationship_comp.entity_uid {
- SingleOrMultiple::Single(prev_entity_uid) => {
- self.relationship_comp.entity_uid =
- SingleOrMultiple::Multiple(vec![*prev_entity_uid, entity_uid]);
- }
- SingleOrMultiple::Multiple(entity_uids) => entity_uids.push(entity_uid),
- }
- }
-
- /// Removes a target to the relationship, returning it.
- pub fn remove_target(&mut self, index: usize) -> Option<Uid>
- {
- match &mut self.relationship_comp.entity_uid {
- SingleOrMultiple::Single(entity_uid) => {
- let prev_entity_uid = *entity_uid;
-
- self.relationship_comp.entity_uid =
- SingleOrMultiple::Multiple(Vec::new());
-
- Some(prev_entity_uid)
- }
- SingleOrMultiple::Multiple(entity_uids) => {
- if index >= entity_uids.len() {
- return None;
- }
-
- Some(entity_uids.remove(index))
- }
- }
- }
-
- #[must_use]
- pub fn target_count(&self) -> usize
- {
- match &self.relationship_comp.entity_uid {
- SingleOrMultiple::Single(_) => 1,
- SingleOrMultiple::Multiple(entity_uids) => entity_uids.len(),
- }
- }
-
- /// Returns a iterator of the components of the targets of this relationship.
- #[must_use]
- pub fn iter(&self) -> TargetComponentIterMut<'_, 'rel_comp, Kind, ComponentT>
- {
- TargetComponentIterMut { relation: self, index: 0 }
- }
-}
-
-impl<'relationship, 'rel_comp, Kind, ComponentT> IntoIterator
- for &'relationship RelationMut<'rel_comp, Kind, ComponentT>
-where
- 'relationship: 'rel_comp,
- ComponentT: Component,
-{
- type IntoIter = TargetComponentIterMut<'relationship, 'rel_comp, Kind, ComponentT>;
- type Item = ComponentHandleMut<'rel_comp, ComponentT>;
-
- fn into_iter(self) -> Self::IntoIter
- {
- self.iter()
- }
-}
-
-/// Iterator of the components of the targets of a relationship.
-pub struct TargetComponentIterMut<'relationship, 'rel_comp, Kind, ComponentT>
-where
- Kind: 'static,
- ComponentT: Component,
-{
- relation: &'relationship RelationMut<'rel_comp, Kind, ComponentT>,
- index: usize,
-}
-
-impl<'relationship, 'rel_comp, Kind, ComponentT> Iterator
- for TargetComponentIterMut<'relationship, 'rel_comp, Kind, ComponentT>
-where
- 'relationship: 'rel_comp,
- Kind: 'static,
- ComponentT: Component,
-{
- type Item = ComponentHandleMut<'rel_comp, ComponentT>;
-
- fn next(&mut self) -> Option<Self::Item>
- {
- let index = self.index;
-
- self.index += 1;
-
- self.relation.get(index)
- }
-}
-
-#[derive(Debug)]
-enum SingleOrMultiple<Value>
-{
- Single(Value),
- Multiple(Vec<Value>),
-}
-
-pub struct Relation<'rel_comp, Kind, ComponentT>
-where
- Kind: 'static,
- ComponentT: Component,
-{
- component_storage_lock: ReadGuard<'rel_comp, ComponentStorage>,
- relationship_comp: ComponentHandle<'rel_comp, Relationship<Kind, ComponentT>>,
-}
-
-impl<'rel_comp, Kind, ComponentT> FromLockedOptionalComponent<'rel_comp>
- for Relation<'rel_comp, Kind, ComponentT>
-where
- ComponentT: Component,
-{
- fn from_locked_optional_component(
- optional_component: Option<&'rel_comp Lock<Box<dyn Component>>>,
- world: &'rel_comp World,
- ) -> Result<Self, LockError>
- {
- let relationship_comp_handle_from_locked_opt_comp = ComponentHandle::<
- Relationship<Kind, ComponentT>,
- >::from_locked_optional_component;
-
- let relationship_comp =
- relationship_comp_handle_from_locked_opt_comp(optional_component, world)?;
-
- let component_storage_lock = world
- .data
- .component_storage
- .read_nonblock()
- .expect("Failed to aquire read-only component storage lock");
-
- Ok(Self {
- relationship_comp,
- component_storage_lock,
- })
- }
-}
-
-impl<'rel_comp, Kind, ComponentT> FromLockedOptionalComponent<'rel_comp>
- for Option<Relation<'rel_comp, Kind, ComponentT>>
-where
- ComponentT: Component,
-{
- fn from_locked_optional_component(
- optional_component: Option<&'rel_comp Lock<Box<dyn Component>>>,
- world: &'rel_comp World,
- ) -> Result<Self, crate::lock::Error>
- {
- optional_component
- .map(|component| {
- Relation::from_locked_optional_component(Some(component), world)
- })
- .transpose()
- }
-}
-
-impl<'rel_comp, Kind, ComponentT> Relation<'rel_comp, Kind, ComponentT>
-where
- ComponentT: Component,
-{
- /// Returns the component of the target at the specified index.
- ///
- /// # Panics
- /// Will panic if the entity does not exist in the archetype it belongs to. This
- /// should hopefully never happend.
- #[must_use]
- pub fn get(&self, index: usize) -> Option<ComponentHandle<'_, ComponentT>>
- {
- let target = self.get_target(index)?;
-
- let archetype = self.component_storage_lock.get_entity_archetype(*target)?;
-
- let entity = archetype
- .get_entity_by_id(*target)
- .expect("Target entity is gone from archetype");
-
- let component_index = archetype.get_index_for_component(ComponentT::id())?;
-
- let component = ComponentHandle::new(
- entity
- .components()
- .get(component_index)?
- .component()
- .read_nonblock()
- .unwrap_or_else(|_| {
- panic!(
- "Failed to aquire read-write lock of component {}",
- type_name::<ComponentT>()
- )
- }),
- );
-
- Some(component)
- }
-
- /// Returns a reference to the target at the specified index.
- #[must_use]
- pub fn get_target(&self, index: usize) -> Option<&Uid>
- {
- match &self.relationship_comp.entity_uid {
- SingleOrMultiple::Single(entity_uid) if index == 0 => Some(entity_uid),
- SingleOrMultiple::Multiple(entity_uids) => entity_uids.get(index),
- SingleOrMultiple::Single(_) => None,
- }
- }
-
- #[must_use]
- pub fn target_count(&self) -> usize
- {
- match &self.relationship_comp.entity_uid {
- SingleOrMultiple::Single(_) => 1,
- SingleOrMultiple::Multiple(entity_uids) => entity_uids.len(),
- }
- }
-
- pub fn target_uids(&self) -> impl Iterator<Item = Uid> + '_
- {
- (0..self.target_count())
- .map_while(|target_index| self.get_target(target_index).copied())
- }
-
- /// Returns a iterator of the components of the targets of this relationship.
- #[must_use]
- pub fn iter(&self) -> TargetComponentIter<'_, 'rel_comp, Kind, ComponentT>
- {
- TargetComponentIter { relation: self, index: 0 }
- }
-}
-
-impl<'relationship, 'rel_comp, Kind, ComponentT> IntoIterator
- for &'relationship Relation<'rel_comp, Kind, ComponentT>
-where
- 'relationship: 'rel_comp,
- ComponentT: Component,
-{
- type IntoIter = TargetComponentIter<'relationship, 'rel_comp, Kind, ComponentT>;
- type Item = ComponentHandle<'rel_comp, ComponentT>;
-
- fn into_iter(self) -> Self::IntoIter
- {
- self.iter()
- }
-}
-
-/// Iterator of the components of the targets of a relationship.
-pub struct TargetComponentIter<'relationship, 'rel_comp, Kind, ComponentT>
-where
- Kind: 'static,
- ComponentT: Component,
-{
- relation: &'relationship Relation<'rel_comp, Kind, ComponentT>,
- index: usize,
-}
-
-impl<'relationship, 'rel_comp, Kind, ComponentT> Iterator
- for TargetComponentIter<'relationship, 'rel_comp, Kind, ComponentT>
-where
- 'relationship: 'rel_comp,
- Kind: 'static,
- ComponentT: Component,
-{
- type Item = ComponentHandle<'rel_comp, ComponentT>;
-
- fn next(&mut self) -> Option<Self::Item>
- {
- let index = self.index;
-
- self.index += 1;
-
- self.relation.get(index)
- }
-}
-
-/// Relationship kind denoting a dependency to another entity
-#[derive(Debug, Default, Clone, Copy)]
-pub struct DependsOn;
-
-/// Relationship kind denoting being the child of another entity.
-#[derive(Debug, Default, Clone, Copy)]
-pub struct ChildOf;
diff --git a/ecs/src/sole.rs b/ecs/src/sole.rs
index 5af5ce3..7cfcc24 100644
--- a/ecs/src/sole.rs
+++ b/ecs/src/sole.rs
@@ -5,12 +5,11 @@ use std::ops::{Deref, DerefMut};
use std::sync::{Arc, Weak};
use crate::lock::{Lock, WriteGuard};
-use crate::system::{Param as SystemParam, System};
-use crate::type_name::TypeName;
+use crate::system::{Metadata as SystemMetadata, Param as SystemParam};
use crate::World;
/// A type which has a single instance and is shared globally.
-pub trait Sole: Any + TypeName
+pub trait Sole: Any
{
fn drop_last(&self) -> bool;
@@ -40,14 +39,6 @@ impl Debug for dyn Sole
}
}
-impl TypeName for Box<dyn Sole>
-{
- fn type_name(&self) -> &'static str
- {
- self.as_ref().type_name()
- }
-}
-
/// Holds a reference to a globally shared singleton value.
#[derive(Debug)]
pub struct Single<'world, SoleT: Sole>
@@ -73,7 +64,7 @@ where
}
}
- fn new(sole: &'world Arc<Lock<Box<dyn Sole>>>) -> Self
+ pub(crate) fn new(sole: &'world Arc<Lock<Box<dyn Sole>>>) -> Self
{
Self {
sole: sole.write_nonblock().unwrap_or_else(|_| {
@@ -94,17 +85,7 @@ where
{
type Input = ();
- fn initialize<SystemImpl>(
- _system: &mut impl System<'world, SystemImpl>,
- _input: Self::Input,
- )
- {
- }
-
- fn new<SystemImpl>(
- _system: &'world impl System<'world, SystemImpl>,
- world: &'world World,
- ) -> Self
+ fn new(world: &'world World, _system_metadata: &SystemMetadata) -> Self
{
let sole = world.data.sole_storage.get::<SoleT>().unwrap_or_else(|| {
panic!("Sole {} was not found in world", type_name::<SoleT>())
diff --git a/ecs/src/system.rs b/ecs/src/system.rs
index 603c015..95ab7a8 100644
--- a/ecs/src/system.rs
+++ b/ecs/src/system.rs
@@ -1,37 +1,28 @@
-use std::any::Any;
-use std::convert::Infallible;
use std::fmt::Debug;
use ecs_macros::Component;
use seq_macro::seq;
-use crate::component::{Component, HandleMut as ComponentHandleMut};
-use crate::tuple::{ReduceElement as TupleReduceElement, Tuple};
+use crate::uid::Uid;
use crate::World;
+pub mod initializable;
+pub mod observer;
pub mod stateful;
-pub trait System<'world, Impl>: 'static
+/// Metadata of a system.
+#[derive(Debug)]
+#[non_exhaustive]
+pub struct Metadata
{
- type Input;
-
- #[must_use]
- fn initialize(self, input: Self::Input) -> Self;
-
- fn run<'this>(&'this self, world: &'world World)
- where
- 'this: 'world;
-
- fn into_type_erased(self) -> TypeErased;
+ pub ent_id: Uid,
+}
- fn get_local_component_mut<LocalComponent: Component>(
- &self,
- ) -> Option<ComponentHandleMut<LocalComponent>>;
+pub trait System<'world, Impl>: 'static
+{
+ type Callbacks: Callbacks;
- fn set_local_component<LocalComponent: Component>(
- &mut self,
- local_component: LocalComponent,
- );
+ fn finish(self) -> (TypeErased, Self::Callbacks);
}
macro_rules! impl_system {
@@ -43,58 +34,23 @@ macro_rules! impl_system {
Func: Fn(#(TParam~I,)*) + Copy + 'static,
#(TParam~I: Param<'world, Input = ()>,)*
{
- type Input = Infallible;
-
- fn initialize(self, _input: Self::Input) -> Self
- {
- self
- }
+ type Callbacks = NoCallbacks;
- fn run<'this>(&'this self, world: &'world World)
- where
- 'this: 'world
+ fn finish(self) -> (TypeErased, Self::Callbacks)
{
- let func = *self;
-
- func(#({
- TParam~I::new(self, world)
- },)*);
- }
-
- fn into_type_erased(self) -> TypeErased
- {
- TypeErased {
- data: Box::new(self),
- run: Box::new(|data, world| {
- // SAFETY: The caller of TypeErased::run ensures the lifetime
- // is correct
- let data = unsafe { &*std::ptr::from_ref(data) };
-
- let me = data
- .downcast_ref::<Func>()
- .expect("Function downcast failed");
-
+ let type_erased = TypeErased {
+ run: Box::new(move |world, metadata| {
// SAFETY: The caller of TypeErased::run ensures the lifetime
// is correct
let world = unsafe { &*std::ptr::from_ref(world) };
- me.run(world);
+ self(#({
+ TParam~I::new(world, &metadata)
+ },)*);
}),
- }
- }
+ };
- fn get_local_component_mut<LocalComponent: Component>(
- &self,
- ) -> Option<ComponentHandleMut<LocalComponent>>
- {
- panic!("System does not have any local components");
- }
-
- fn set_local_component<LocalComponent: Component>(
- &mut self,
- _local_component: LocalComponent,
- ) {
- panic!("System does not have any local components");
+ (type_erased, NoCallbacks)
}
}
});
@@ -105,7 +61,7 @@ seq!(C in 1..16 {
impl_system!(C);
});
-pub trait Into<Impl>
+pub trait Into<'world, Impl>
{
type System;
@@ -114,7 +70,6 @@ pub trait Into<Impl>
pub struct TypeErased
{
- data: Box<dyn Any>,
run: Box<TypeErasedRunFn>,
}
@@ -124,12 +79,9 @@ impl TypeErased
///
/// # Safety
/// `world_data` must live at least as long as the [`World`] the system belongs to.
- pub unsafe fn run(&self, world: &World)
+ pub unsafe fn run(&self, world: &World, metadata: Metadata)
{
- // You have to dereference for downcasting to work for some reason
- let data = &*self.data;
-
- (self.run)(data, world);
+ (self.run)(world, metadata);
}
}
@@ -142,41 +94,29 @@ impl Debug for TypeErased
}
/// Function in [`TypeErased`] used to run the system.
-type TypeErasedRunFn = dyn Fn(&dyn Any, &World);
+type TypeErasedRunFn = dyn Fn(&World, Metadata);
/// A parameter to a [`System`].
pub trait Param<'world>
{
type Input;
- fn initialize<SystemImpl>(
- system: &mut impl System<'world, SystemImpl>,
- input: Self::Input,
- );
-
- fn new<SystemImpl>(
- system: &'world impl System<'world, SystemImpl>,
- world: &'world World,
- ) -> Self;
+ fn new(world: &'world World, system_metadata: &Metadata) -> Self;
}
/// A type which can be used as input to a [`System`].
pub trait Input: 'static {}
-/// Component tuple reducing operation to get the parameters that takes input.
-pub struct ParamWithInputFilter;
-
-impl<InputT: Input, Accumulator> TupleReduceElement<Accumulator, ParamWithInputFilter>
- for InputT
-where
- Accumulator: Tuple,
+pub trait Callbacks
{
- type Return = Accumulator::WithElementAtEnd<Self>;
+ fn on_created(&mut self, world: &mut World, metadata: Metadata);
}
-impl<Accumulator> TupleReduceElement<Accumulator, ParamWithInputFilter> for ()
+pub struct NoCallbacks;
+
+impl Callbacks for NoCallbacks
{
- type Return = Accumulator;
+ fn on_created(&mut self, _world: &mut World, _metadata: Metadata) {}
}
#[derive(Debug, Component)]
diff --git a/ecs/src/system/initializable.rs b/ecs/src/system/initializable.rs
new file mode 100644
index 0000000..b6ec8e8
--- /dev/null
+++ b/ecs/src/system/initializable.rs
@@ -0,0 +1,131 @@
+use std::marker::PhantomData;
+
+use seq_macro::seq;
+
+use crate::system::{Input, Param as SystemParam, System};
+use crate::tuple::{Reduce as TupleReduce, ReduceElement as TupleReduceElement, Tuple};
+
+/// A initializable system.
+pub trait Initializable<'world, Impl>: System<'world, Impl>
+{
+ type Inputs;
+
+ #[must_use]
+ fn initialize(self, inputs: Self::Inputs) -> Self;
+}
+
+pub trait Param<'world, SystemT>: SystemParam<'world>
+{
+ fn initialize(system: &mut SystemT, input: Self::Input);
+}
+
+pub struct ParamTupleFilter<'world, SystemT>
+{
+ _pd: PhantomData<(&'world (), SystemT)>,
+}
+
+impl<'world, SystemT, ParamT, Accumulator>
+ TupleReduceElement<Accumulator, ParamTupleFilter<'world, SystemT>> for ParamT
+where
+ ParamT: SystemParam<
+ 'world,
+ Input: AppendInitializableParam<'world, Accumulator, ParamT, SystemT>,
+ >,
+ Accumulator: Tuple,
+{
+ type Return = <ParamT::Input as AppendInitializableParam<
+ 'world,
+ Accumulator,
+ ParamT,
+ SystemT,
+ >>::Return;
+}
+
+pub trait AppendInitializableParam<'world, Accumulator, ParamT, SystemT>
+{
+ type Return;
+}
+
+impl<'world, InputT, ParamT, Accumulator, SystemT>
+ AppendInitializableParam<'world, Accumulator, ParamT, SystemT> for InputT
+where
+ InputT: Input,
+ Accumulator: Tuple,
+ ParamT: Param<'world, SystemT>,
+{
+ type Return = Accumulator::WithElementAtEnd<ParamT>;
+}
+
+impl<ParamT, Accumulator, SystemT>
+ AppendInitializableParam<'_, Accumulator, ParamT, SystemT> for ()
+where
+ Accumulator: Tuple,
+{
+ type Return = Accumulator;
+}
+
+pub trait ParamTuple<'world, SystemT>
+{
+ type Inputs;
+
+ fn initialize_all(system: &mut SystemT, inputs: Self::Inputs);
+}
+
+macro_rules! impl_initializable_param_tuple {
+ ($c: tt) => {
+ seq!(I in 0..$c {
+ impl<'world, SystemT, #(Param~I,)*> ParamTuple<'world, SystemT>
+ for (#(Param~I,)*)
+ where
+ #(Param~I: Param<'world, SystemT>,)*
+ {
+ type Inputs = (#(Param~I::Input,)*);
+
+ fn initialize_all(
+ system: &mut SystemT,
+ inputs: Self::Inputs,
+ ) {
+ #(
+ <Param~I as Param<'world, SystemT>>::initialize(
+ system,
+ inputs.I
+ );
+ )*
+ }
+ }
+ });
+ };
+}
+
+seq!(C in 1..16 {
+ impl_initializable_param_tuple!(C);
+});
+
+impl<SystemT> ParamTuple<'_, SystemT> for ()
+{
+ type Inputs = ();
+
+ fn initialize_all(_system: &mut SystemT, _inputs: Self::Inputs) {}
+}
+
+/// A tuple of system parameters that may or may not be initializable.
+pub trait MaybeInitializableParamTuple<'world, SystemT>
+{
+ /// A tuple of the inputs of the initializable system parameters in this tuple.
+ type Inputs;
+
+ fn init_initializable(system: &mut SystemT, inputs: Self::Inputs);
+}
+
+impl<'world, SystemT, Params> MaybeInitializableParamTuple<'world, SystemT> for Params
+where
+ Params:
+ TupleReduce<ParamTupleFilter<'world, SystemT>, Out: ParamTuple<'world, SystemT>>,
+{
+ type Inputs = <Params::Out as ParamTuple<'world, SystemT>>::Inputs;
+
+ fn init_initializable(system: &mut SystemT, inputs: Self::Inputs)
+ {
+ Params::Out::initialize_all(system, inputs);
+ }
+}
diff --git a/ecs/src/system/observer.rs b/ecs/src/system/observer.rs
new file mode 100644
index 0000000..236420c
--- /dev/null
+++ b/ecs/src/system/observer.rs
@@ -0,0 +1,310 @@
+use std::fmt::Debug;
+use std::marker::PhantomData;
+use std::mem::transmute;
+use std::slice::Iter as SliceIter;
+
+use ecs_macros::Component;
+use seq_macro::seq;
+
+use crate::component::Component;
+use crate::entity::Handle as EntityHandle;
+use crate::event::Emitted as EmittedEvent;
+use crate::pair::Pair;
+use crate::system::{
+ Metadata,
+ NoCallbacks,
+ Param,
+ System,
+ TypeErased as TypeErasedSystem,
+};
+use crate::uid::Uid;
+use crate::util::Array;
+use crate::World;
+
+pub trait Observed
+{
+ type Events: Array<Pair<Uid, Uid>>;
+
+ fn events() -> Self::Events;
+}
+
+impl<Relation, Target> Observed for Pair<Relation, Target>
+where
+ Relation: Component,
+ Target: Component,
+{
+ type Events = [Pair<Uid, Uid>; 1];
+
+ fn events() -> Self::Events
+ {
+ [Pair::builder()
+ .relation::<Relation>()
+ .target::<Target>()
+ .build()]
+ }
+}
+
+/// Observer system.
+pub trait Observer<'world, Impl>: System<'world, Impl>
+{
+ type ObservedEvents: Array<Pair<Uid, Uid>>;
+
+ fn observed_events() -> Self::ObservedEvents;
+
+ fn finish_observer(self) -> (WrapperComponent, Self::Callbacks);
+}
+
+pub struct Observe<'world, ObservedT: Observed>
+{
+ _pd: PhantomData<ObservedT>,
+ world: &'world World,
+ emitted_event: EmittedEvent<'world>,
+}
+
+impl<'world, ObservedT: Observed> Observe<'world, ObservedT>
+{
+ pub fn new(world: &'world World, emitted_event: EmittedEvent<'world>) -> Self
+ {
+ Self {
+ _pd: PhantomData,
+ world,
+ emitted_event,
+ }
+ }
+
+ #[must_use]
+ pub fn event(&self) -> Uid
+ {
+ self.emitted_event.event
+ }
+}
+
+impl<ObservedT: Observed> Observe<'_, ObservedT>
+{
+ #[must_use]
+ pub fn iter(&self) -> ObserveIter<'_, ObservedT>
+ {
+ ObserveIter {
+ world: self.world,
+ inner: self.emitted_event.match_ids.iter(),
+ _pd: PhantomData,
+ }
+ }
+}
+
+impl<'a, ObservedT: Observed> IntoIterator for &'a Observe<'_, ObservedT>
+{
+ type IntoIter = ObserveIter<'a, ObservedT>;
+ type Item = <Self::IntoIter as Iterator>::Item;
+
+ fn into_iter(self) -> Self::IntoIter
+ {
+ self.iter()
+ }
+}
+
+pub struct ObserveIter<'observe, ObservedT: Observed>
+{
+ world: &'observe World,
+ inner: SliceIter<'observe, Uid>,
+ _pd: PhantomData<ObservedT>,
+}
+
+impl<'observe, ObservedT: Observed> Iterator for ObserveIter<'observe, ObservedT>
+{
+ type Item = EventMatch<'observe, ObservedT>;
+
+ fn next(&mut self) -> Option<Self::Item>
+ {
+ let match_id = *self.inner.next()?;
+
+ Some(EventMatch {
+ world: self.world,
+ id: match_id,
+ _pd: PhantomData,
+ })
+ }
+}
+
+/// A event match.
+#[derive(Debug)]
+pub struct EventMatch<'world, ObservedT: Observed>
+{
+ world: &'world World,
+ id: Uid,
+ _pd: PhantomData<ObservedT>,
+}
+
+impl<'world, ObservedT: Observed> EventMatch<'world, ObservedT>
+{
+ #[must_use]
+ pub fn id(&self) -> Uid
+ {
+ self.id
+ }
+
+ /// Attempts to get the entity with the id of this match.
+ #[must_use]
+ pub fn get_entity(&self) -> Option<EntityHandle<'world>>
+ {
+ self.world.get_entity(self.id)
+ }
+}
+
+macro_rules! impl_observer {
+ ($c: tt) => {
+ seq!(I in 0..$c {
+ impl<'world, ObservedT, Func, #(TParam~I,)*> System<
+ 'world,
+ fn(Observe<'world, ObservedT>, #(TParam~I,)*)
+ > for Func
+ where
+ ObservedT: Observed,
+ Func: Fn(Observe<'world, ObservedT>, #(TParam~I,)*) + Copy + 'static,
+ #(TParam~I: Param<'world, Input = ()>,)*
+ {
+ type Callbacks = NoCallbacks;
+
+ fn finish(self) -> (TypeErasedSystem, NoCallbacks)
+ {
+ unimplemented!();
+ }
+ }
+
+ impl<'world, ObservedT, Func, #(TParam~I,)*> Observer<
+ 'world,
+ fn(Observe<'world, ObservedT>, #(TParam~I,)*)
+ > for Func
+ where
+ ObservedT: Observed,
+ Func: Fn(Observe<'world, ObservedT>, #(TParam~I,)*) + Copy + 'static,
+ #(TParam~I: Param<'world, Input = ()>,)*
+ {
+ type ObservedEvents = ObservedT::Events;
+
+ fn observed_events() -> Self::ObservedEvents
+ {
+ ObservedT::events()
+ }
+
+ fn finish_observer(self) -> (WrapperComponent, NoCallbacks)
+ {
+ let wrapper_comp = WrapperComponent {
+ run: Box::new(move |world, metadata, emitted_event| {
+ // SAFETY: The caller of TypeErased::run ensures the lifetime
+ // is correct
+ let world = unsafe { &*std::ptr::from_ref(world) };
+
+ // SAFETY: The caller of TypeErased::run ensures the lifetime
+ // is correct
+ let emitted_event = unsafe {
+ transmute::<EmittedEvent<'_>, EmittedEvent<'_>>(
+ emitted_event
+ )
+ };
+
+ self(Observe::new(world, emitted_event), #({
+ TParam~I::new(world, &metadata)
+ },)*);
+ }),
+ };
+
+ (wrapper_comp, NoCallbacks)
+ }
+ }
+ });
+ };
+}
+
+seq!(C in 1..16 {
+ impl_observer!(C);
+});
+
+impl<'world, ObservedT, Func> System<'world, fn(Observe<'world, ObservedT>)> for Func
+where
+ ObservedT: Observed,
+ Func: Fn(Observe<'world, ObservedT>) + Copy + 'static,
+{
+ type Callbacks = NoCallbacks;
+
+ fn finish(self) -> (TypeErasedSystem, NoCallbacks)
+ {
+ const {
+ panic!("Observers cannot be used as regular systems");
+ }
+ }
+}
+
+impl<'world, ObservedT, Func> Observer<'world, fn(Observe<'world, ObservedT>)> for Func
+where
+ ObservedT: Observed,
+ Func: Fn(Observe<'world, ObservedT>) + Copy + 'static,
+{
+ type ObservedEvents = ObservedT::Events;
+
+ fn observed_events() -> Self::ObservedEvents
+ {
+ ObservedT::events()
+ }
+
+ fn finish_observer(self) -> (WrapperComponent, NoCallbacks)
+ {
+ let wrapper_comp = WrapperComponent {
+ run: Box::new(move |world, _metadata, emitted_event| {
+ // SAFETY: The caller of TypeErased::run ensures the lifetime
+ // is correct
+ let world = unsafe { &*std::ptr::from_ref(world) };
+
+ // SAFETY: The caller of TypeErased::run ensures the lifetime
+ // is correct
+ let emitted_event = unsafe {
+ transmute::<EmittedEvent<'_>, EmittedEvent<'_>>(emitted_event)
+ };
+
+ self(Observe::new(world, emitted_event));
+ }),
+ };
+
+ (wrapper_comp, NoCallbacks)
+ }
+}
+
+#[derive(Component)]
+pub struct WrapperComponent
+{
+ run: Box<RunFn>,
+}
+
+impl WrapperComponent
+{
+ pub fn new(run: impl Fn(&World, Metadata, EmittedEvent<'_>) + 'static) -> Self
+ {
+ Self { run: Box::new(run) }
+ }
+
+ /// Runs the observer system.
+ ///
+ /// # Safety
+ /// `world` must live at least as long as the [`World`] the system belongs to.
+ pub unsafe fn run(
+ &self,
+ world: &World,
+ metadata: Metadata,
+ emitted_event: EmittedEvent<'_>,
+ )
+ {
+ (self.run)(world, metadata, emitted_event);
+ }
+}
+
+impl Debug for WrapperComponent
+{
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
+ {
+ formatter
+ .debug_struct("WrapperComponent")
+ .finish_non_exhaustive()
+ }
+}
+
+type RunFn = dyn Fn(&World, Metadata, EmittedEvent<'_>);
diff --git a/ecs/src/system/stateful.rs b/ecs/src/system/stateful.rs
index 9d911ee..e74ef31 100644
--- a/ecs/src/system/stateful.rs
+++ b/ecs/src/system/stateful.rs
@@ -1,149 +1,243 @@
-use std::any::{Any, TypeId};
+use std::mem::transmute;
use std::panic::{RefUnwindSafe, UnwindSafe};
-use hashbrown::HashMap;
use seq_macro::seq;
-use crate::component::{Component, HandleMut as ComponentHandleMut};
-use crate::lock::Lock;
-use crate::system::{
- Into as IntoSystem,
- Param,
- ParamWithInputFilter,
- System,
- TypeErased,
+use crate::component::local::SystemWithLocalComponents;
+use crate::component::Parts as ComponentParts;
+use crate::event::Emitted as EmittedEvent;
+use crate::system::initializable::{Initializable, MaybeInitializableParamTuple};
+use crate::system::observer::{
+ Observe,
+ Observed,
+ Observer,
+ WrapperComponent as ObserverWrapperComponent,
};
-use crate::tuple::{
- Reduce as TupleReduce,
- Tuple,
- WithAllElemLtStatic as TupleWithAllElemLtStatic,
-};
-use crate::uid::Uid;
+use crate::system::{Into as IntoSystem, Metadata, Param, System, TypeErased};
use crate::World;
/// A stateful system.
pub struct Stateful<Func>
{
func: Func,
- local_components: HashMap<Uid, Lock<Box<dyn Component>>>,
+ local_components: Vec<ComponentParts>,
}
macro_rules! impl_system {
($c: tt) => {
seq!(I in 0..$c {
- impl<'world, Func, #(TParam~I,)*> System<'world, fn(&'world (), #(TParam~I,)*)>
- for Stateful<Func>
+ impl<'world, Func, #(TParam~I,)*>
+ System<'world, fn(&'world (), #(TParam~I,)*)> for Stateful<Func>
where
Func: Fn(#(TParam~I,)*) + Copy + RefUnwindSafe + UnwindSafe + 'static,
- #(TParam~I: Param<'world>,)*
- #(TParam~I::Input: 'static,)*
- (#(TParam~I::Input,)*): TupleReduce<
- ParamWithInputFilter,
- Out: Tuple<InOptions: TupleWithAllElemLtStatic>
- >,
+ #(TParam~I: Param<'world, Input: 'static>,)*
{
- type Input =
- <(#(TParam~I::Input,)*) as TupleReduce<ParamWithInputFilter>>::Out;
+ type Callbacks = Callbacks;
- fn initialize(mut self, input: Self::Input) -> Self
+ fn finish(self) -> (TypeErased, Self::Callbacks)
{
- let mut option_input = input.into_in_options();
-
- let mut index = 0;
-
- #(
- if TypeId::of::<TParam~I::Input>() !=
- TypeId::of::<()>()
- {
- let input = option_input
- .get_mut::<Option<TParam~I::Input>>(index)
- .expect("Input element index out of range")
- .take()
- .expect("Input element is already taken");
-
- TParam~I::initialize(
- &mut self,
- input
- );
-
- #[allow(unused_assignments)]
- {
- index += 1;
- }
- }
- )*
+ let Self { func, local_components } = self;
- self
+ let callbacks = Callbacks { local_components };
+
+ let type_erased = TypeErased {
+ run: Box::new(move |world, metadata| {
+ // SAFETY: The caller of TypeErased::run ensures the lifetime
+ // is correct
+ let world = unsafe { &*std::ptr::from_ref(world) };
+
+ func(#({
+ TParam~I::new(&world, &metadata)
+ },)*);
+ }),
+ };
+
+
+ (type_erased, callbacks)
}
+ }
- fn run<'this>(&'this self, world: &'world World)
- where
- 'this: 'world
+ impl<'world, Func, #(TParam~I,)*>
+ Initializable<'world, fn(&'world (), #(TParam~I,)*)> for Stateful<Func>
+ where
+ Func: Fn(#(TParam~I,)*) + Copy + RefUnwindSafe + UnwindSafe + 'static,
+ #(TParam~I: Param<'world, Input: 'static>,)*
+ (#(TParam~I,)*): MaybeInitializableParamTuple<'world, Self>
+ {
+ type Inputs = <
+ (#(TParam~I,)*) as MaybeInitializableParamTuple<'world, Self>
+ >::Inputs;
+
+ fn initialize(mut self, inputs: Self::Inputs) -> Self
{
- let func = self.func;
+ init_initializable_params::<_, (#(TParam~I,)*)>(&mut self, inputs);
- func(#({
- TParam~I::new(self, &world)
- },)*);
+ self
}
+ }
- fn into_type_erased(self) -> TypeErased
+ impl<'world, Func, #(TParam~I,)*> IntoSystem<'world, fn(#(TParam~I,)*)>
+ for Func
+ where
+ #(TParam~I: Param<'world>,)*
+ Func: Fn(#(TParam~I,)*) + Copy + 'static,
+ {
+ type System = Stateful<Func>;
+
+ fn into_system(self) -> Self::System
{
- TypeErased {
- data: Box::new(self),
- run: Box::new(|data, world| {
- // SAFETY: The caller of TypeErased::run ensures the lifetime
- // is correct
- let data = unsafe { &*std::ptr::from_ref::<dyn Any>(data) };
+ Self::System {
+ func: self,
+ local_components: Vec::new(), // TODO: Use Vec::with_capacity
+ }
+ }
+ }
+ });
+ };
+}
- let me = data.downcast_ref::<Self>().unwrap();
+seq!(C in 1..16 {
+ impl_system!(C);
+});
- // SAFETY: The caller of TypeErased::run ensures the lifetime
- // is correct
- let world = unsafe { &*std::ptr::from_ref(world) };
+impl<Func> SystemWithLocalComponents for Stateful<Func>
+{
+ fn add_local_component(&mut self, component_parts: ComponentParts)
+ {
+ self.local_components.push(component_parts);
+ }
+}
- me.run(world);
- }),
- }
+#[derive(Debug)]
+pub struct Callbacks
+{
+ local_components: Vec<ComponentParts>,
+}
+
+impl crate::system::Callbacks for Callbacks
+{
+ fn on_created(&mut self, world: &mut World, metadata: Metadata)
+ {
+ for local_comp_parts in self.local_components.drain(..) {
+ world.add_component(metadata.ent_id, local_comp_parts);
+ }
+ }
+}
+
+fn init_initializable_params<'world, SystemT, Params>(
+ system: &mut SystemT,
+ inputs: Params::Inputs,
+) where
+ Params: MaybeInitializableParamTuple<'world, SystemT>,
+{
+ Params::init_initializable(system, inputs);
+}
+
+macro_rules! impl_observer {
+ ($c: tt) => {
+ seq!(I in 0..$c {
+ impl<'world, ObservedT, Func, #(TParam~I,)*> System<
+ 'world,
+ fn(Observe<'world, ObservedT>, #(TParam~I,)*)
+ > for Stateful<Func>
+ where
+ ObservedT: Observed,
+ Func: Fn(Observe<'world, ObservedT>, #(TParam~I,)*) + Copy + 'static,
+ #(TParam~I: Param<'world>,)*
+ {
+ type Callbacks = Callbacks;
+
+ fn finish(self) -> (TypeErased, Callbacks)
+ {
+ unimplemented!();
}
+ }
- fn get_local_component_mut<LocalComponent: Component>(
- &self,
- ) -> Option<ComponentHandleMut<LocalComponent>>
+ impl<'world, ObservedT, Func, #(TParam~I,)*> Initializable<
+ 'world,
+ fn(Observe<'world, ObservedT>, #(TParam~I,)*)
+ > for Stateful<Func>
+ where
+ ObservedT: Observed,
+ Func: Fn(Observe<'world, ObservedT>, #(TParam~I,)*) + Copy + 'static,
+ #(TParam~I: Param<'world>,)*
+ (#(TParam~I,)*): MaybeInitializableParamTuple<'world, Self>
+ {
+ type Inputs = <
+ (#(TParam~I,)*) as MaybeInitializableParamTuple<'world, Self>
+ >::Inputs;
+
+ fn initialize(mut self, inputs: Self::Inputs) -> Self
{
- let local_component = self.local_components
- .get(&LocalComponent::id())?
- .write_nonblock()
- .expect("Failed to aquire read-write local component lock");
+ init_initializable_params::<_, (#(TParam~I,)*)>(&mut self, inputs);
- Some(ComponentHandleMut::new(local_component))
+ self
}
+ }
+
+ impl<'world, ObservedT, Func, #(TParam~I,)*> Observer<
+ 'world,
+ fn(Observe<'world, ObservedT>, #(TParam~I,)*)
+ > for Stateful<Func>
+ where
+ ObservedT: Observed,
+ Func: Fn(Observe<'world, ObservedT>, #(TParam~I,)*) + Copy + 'static,
+ #(TParam~I: Param<'world>,)*
+ {
+ type ObservedEvents = ObservedT::Events;
- fn set_local_component<LocalComponent: Component>(
- &mut self,
- local_component: LocalComponent,
- )
+ fn observed_events() -> Self::ObservedEvents
{
- self.local_components
- .insert(
- LocalComponent::id(),
- Lock::new(Box::new(local_component))
- );
+ ObservedT::events()
+ }
+
+ fn finish_observer(self) -> (ObserverWrapperComponent, Callbacks)
+ {
+ let Self { func, local_components } = self;
+
+ let callbacks = Callbacks { local_components };
+
+ let wrapper_comp = ObserverWrapperComponent::new(
+ move |world, metadata, emitted_event| {
+ // SAFETY: The caller of TypeErased::run ensures the lifetime
+ // is correct
+ let world = unsafe { &*std::ptr::from_ref(world) };
+
+ // SAFETY: The caller of TypeErased::run ensures the lifetime
+ // is correct
+ let emitted_event = unsafe {
+ transmute::<EmittedEvent<'_>, EmittedEvent<'_>>(
+ emitted_event
+ )
+ };
+
+ func(Observe::new(world, emitted_event), #({
+ TParam~I::new(world, &metadata)
+ },)*);
+ },
+ );
+
+ (wrapper_comp, callbacks)
}
}
- impl<Func, #(TParam~I,)*> IntoSystem<fn(#(TParam~I,)*)>
- for Func
+ impl<'world, Func, ObservedT, #(TParam~I,)*> IntoSystem<
+ 'world,
+ fn(Observe<'world, ObservedT>,
+ #(TParam~I,)*)
+ > for Func
where
- Func: Fn(#(TParam~I,)*) + Copy + 'static,
+ ObservedT: Observed,
+ #(TParam~I: Param<'world>,)*
+ Func: Fn(Observe<'world, ObservedT>, #(TParam~I,)*) + Copy + 'static,
{
type System = Stateful<Func>;
- fn into_system(self) -> Self::System
+ fn into_system(self) -> Stateful<Func>
{
- Self::System {
+ Stateful {
func: self,
- local_components: HashMap::new(),
+ local_components: Vec::new(), // TODO: Use Vec::with_capacity
}
}
}
@@ -152,5 +246,5 @@ macro_rules! impl_system {
}
seq!(C in 1..16 {
- impl_system!(C);
+ impl_observer!(C);
});
diff --git a/ecs/src/type_name.rs b/ecs/src/type_name.rs
deleted file mode 100644
index 54179be..0000000
--- a/ecs/src/type_name.rs
+++ /dev/null
@@ -1,15 +0,0 @@
-use std::any::type_name;
-
-pub trait TypeName
-{
- /// Returns the name of this type.
- fn type_name(&self) -> &'static str;
-}
-
-impl<Item> TypeName for Vec<Item>
-{
- fn type_name(&self) -> &'static str
- {
- type_name::<Self>()
- }
-}
diff --git a/ecs/src/uid.rs b/ecs/src/uid.rs
index c3ed85b..bb393a1 100644
--- a/ecs/src/uid.rs
+++ b/ecs/src/uid.rs
@@ -1,23 +1,30 @@
-use std::fmt::{Debug, Formatter};
+use std::fmt::{Debug, Display, Formatter};
use std::mem::transmute;
use std::sync::atomic::{AtomicU32, Ordering};
-use crate::util::{gen_mask_64, BitMask, NumberExt};
+use seq_macro::seq;
-static NEXT: AtomicU32 = AtomicU32::new(1);
+use crate::component::Component;
+use crate::util::{gen_mask_64, Array, BitMask, NumberExt};
+
+static NEXT: AtomicU32 = AtomicU32::new(Uid::FIRST_UNIQUE_ID);
+
+static WILDCARD_ID: u32 = 1;
const ID_BITS: BitMask<u64> = BitMask::new(gen_mask_64!(32..=63));
+const RELATION_BITS: BitMask<u64> = BitMask::new(gen_mask_64!(6..=31));
const KIND_BITS: BitMask<u64> = BitMask::new(gen_mask_64!(0..=1));
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[repr(u8)]
pub enum Kind
{
+ Pair = 3,
Entity = 2,
Component = 1,
}
-/// Unique entity/component ID.
+/// A unique identifier.
#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Uid
{
@@ -26,6 +33,10 @@ pub struct Uid
impl Uid
{
+ /// The id part of the first unique `Uid`. The ids `0..Uid::FIRST_UNIQUE_ID` are
+ /// reserved.
+ pub const FIRST_UNIQUE_ID: u32 = 5;
+
/// Returns a new unique entity/component ID.
pub fn new_unique(kind: Kind) -> Self
{
@@ -37,6 +48,41 @@ impl Uid
}
#[must_use]
+ pub fn wildcard() -> Self
+ {
+ Self {
+ inner: ID_BITS.field_prep(u64::from(WILDCARD_ID))
+ | KIND_BITS.field_prep(Kind::Component as u64),
+ }
+ }
+
+ /// Returns a new pair UID.
+ ///
+ /// # Panics
+ /// Will panic if either the given relation or target is a pair UID.
+ #[must_use]
+ pub fn new_pair(params: &PairParams) -> Self
+ {
+ assert_ne!(
+ params.relation.kind(),
+ Kind::Pair,
+ "Pair relation cannot be a pair"
+ );
+
+ assert_ne!(
+ params.target.kind(),
+ Kind::Pair,
+ "Pair target cannot be a pair"
+ );
+
+ Self {
+ inner: ID_BITS.field_prep(u64::from(params.target.id()))
+ | RELATION_BITS.field_prep(u64::from(params.relation.id()))
+ | KIND_BITS.field_prep(Kind::Pair as u64),
+ }
+ }
+
+ #[must_use]
pub fn id(&self) -> u32
{
let Ok(id) = u32::try_from(self.inner.field_get(ID_BITS)) else {
@@ -57,6 +103,81 @@ impl Uid
// in the new_unique function
unsafe { transmute::<u8, Kind>(kind) }
}
+
+ /// If this `Uid` is a pair, returns the relation as a component `Uid`.
+ ///
+ /// # Panics
+ /// Will panic if this `Uid` is not a pair.
+ #[must_use]
+ pub fn relation_component(&self) -> Self
+ {
+ assert_eq!(self.kind(), Kind::Pair, "Uid is not a pair");
+
+ Self {
+ inner: ID_BITS.field_prep(u64::from(self.relation()))
+ | KIND_BITS.field_prep(Kind::Component as u64),
+ }
+ }
+
+ #[must_use]
+ pub fn has_same_relation_as(&self, other: Self) -> bool
+ {
+ self.relation() == other.relation()
+ }
+
+ /// If this `Uid` is a pair, returns the relation as a entity `Uid`.
+ ///
+ /// # Panics
+ /// Will panic if this `Uid` is not a pair.
+ #[must_use]
+ pub fn relation_entity(&self) -> Self
+ {
+ assert_eq!(self.kind(), Kind::Pair, "Uid is not a pair");
+
+ Self {
+ inner: ID_BITS.field_prep(u64::from(self.relation()))
+ | KIND_BITS.field_prep(Kind::Entity as u64),
+ }
+ }
+
+ /// If this `Uid` is a pair, returns the target as a component `Uid`.
+ ///
+ /// # Panics
+ /// Will panic if this `Uid` is not a pair.
+ #[must_use]
+ pub fn target_component(&self) -> Self
+ {
+ assert_eq!(self.kind(), Kind::Pair, "Uid is not a pair");
+
+ Self {
+ inner: ID_BITS.field_prep(u64::from(self.id()))
+ | KIND_BITS.field_prep(Kind::Component as u64),
+ }
+ }
+
+ /// If this `Uid` is a pair, returns the target as a entity `Uid`.
+ ///
+ /// # Panics
+ /// Will panic if this `Uid` is not a pair.
+ #[must_use]
+ pub fn target_entity(&self) -> Self
+ {
+ assert_eq!(self.kind(), Kind::Pair, "Uid is not a pair");
+
+ Self {
+ inner: ID_BITS.field_prep(u64::from(self.id()))
+ | KIND_BITS.field_prep(Kind::Entity as u64),
+ }
+ }
+
+ fn relation(self) -> u32
+ {
+ let Ok(relation) = u32::try_from(self.inner.field_get(RELATION_BITS)) else {
+ unreachable!("Uid relation does not fit in u32");
+ };
+
+ relation
+ }
}
impl Debug for Uid
@@ -70,3 +191,71 @@ impl Debug for Uid
.finish_non_exhaustive()
}
}
+
+impl Display for Uid
+{
+ fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result
+ {
+ if self.kind() == Kind::Pair {
+ return write!(
+ formatter,
+ "({}, {})",
+ self.relation(),
+ self.target_component()
+ );
+ }
+
+ if *self == Uid::wildcard() {
+ return write!(formatter, "*");
+ }
+
+ write!(formatter, "{}", self.id())
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct PairParams
+{
+ pub relation: Uid,
+ pub target: Uid,
+}
+
+pub trait With
+{
+ fn uid() -> Uid;
+}
+
+impl<ComponentT: Component> With for ComponentT
+{
+ fn uid() -> Uid
+ {
+ Self::id()
+ }
+}
+
+pub trait WithUidTuple
+{
+ type UidsArray: Array<Uid>;
+
+ fn uids() -> Self::UidsArray;
+}
+
+macro_rules! impl_with_uid_tuple {
+ ($c: tt) => {
+ seq!(I in 0..=$c {
+ impl<#(WithUid~I: With,)*> WithUidTuple for (#(WithUid~I,)*)
+ {
+ type UidsArray = [Uid; $c + 1];
+
+ fn uids() -> Self::UidsArray
+ {
+ [#(WithUid~I::uid(),)*]
+ }
+ }
+ });
+ };
+}
+
+seq!(C in 0..=16 {
+ impl_with_uid_tuple!(C);
+});
diff --git a/ecs/src/util.rs b/ecs/src/util.rs
index eb06ab4..27e9748 100644
--- a/ecs/src/util.rs
+++ b/ecs/src/util.rs
@@ -4,24 +4,24 @@ use std::ops::{BitAnd, Deref};
use hashbrown::HashMap;
-pub mod array_vec;
+pub(crate) mod array_vec;
pub trait VecExt<Item>
{
- fn insert_at_partition_point_by_key<Key>(
+ fn insert_at_part_pt_by_key<Key>(
&mut self,
item: Item,
- func: impl FnMut(&Item) -> Key,
+ func: impl FnMut(&Item) -> &Key,
) where
Key: Ord;
}
impl<Item> VecExt<Item> for Vec<Item>
{
- fn insert_at_partition_point_by_key<Key>(
+ fn insert_at_part_pt_by_key<Key>(
&mut self,
item: Item,
- mut func: impl FnMut(&Item) -> Key,
+ mut func: impl FnMut(&Item) -> &Key,
) where
Key: Ord,
{
@@ -300,6 +300,88 @@ macro_rules! gen_mask_64 {
pub(crate) use gen_mask_64;
+macro_rules! impl_multiple {
+ (
+ $type: ident,
+ ($(
+ impl$(<$($generic: tt$(: $bound: ident)?),*>)?
+ _<$($lt_param: lifetime),*><$($type_param: ty),*>
+ $(($($extra_cb_arg: expr),*))?
+ ),*)
+ cb=(
+ type_params=($($ty_param_matcher: ident),*)
+ $(, $($extra_matcher: ident),+)?
+ ) => {
+ $($item_tt: tt)*
+ }
+ ) => {
+ const _: () = {
+ $crate::util::impl_multiple!(
+ @(make_gen_item_macro)
+ _gen_multiple_impl_item,
+ ($($ty_param_matcher),*),
+ ($($($extra_matcher),+)?),
+ ($($item_tt)*)
+ );
+
+ $(
+ impl $(<$($generic$(: $bound)?,)*>)? $type<$($lt_param,)* $($type_param),*>
+ {
+ _gen_multiple_impl_item!(
+ type_params=($($type_param),*),
+ $($($extra_cb_arg),*)?
+ );
+ }
+ )*
+ };
+ };
+
+ (
+ @(make_gen_item_macro)
+ $name: ident,
+ ($($ty_param_matcher: ident),*),
+ ($($extra_matcher: ident),*),
+ ($($transcriber: tt)*)
+ ) => {
+ $crate::util::impl_multiple!(
+ @(make_gen_item_macro)
+ ($),
+ $name,
+ ($($ty_param_matcher),*),
+ ($($extra_matcher),*),
+ ($($transcriber)*)
+ );
+ };
+
+ (
+ @(make_gen_item_macro)
+ ($dollar: tt),
+ $name: ident,
+ ($($ty_param_matcher: ident),*),
+ ($($extra_matcher: ident),*),
+ ($($transcriber: tt)*)
+ ) => {
+ $crate::util::impl_multiple!(
+ @(make_gen_item_macro)
+ $name,
+ (
+ type_params=($($dollar$ty_param_matcher: ty),*),
+ $($dollar$extra_matcher: expr),*
+ ) => {
+ $($transcriber)*
+ }
+ );
+ };
+
+ (@(make_gen_item_macro) $name: ident, $($rule: tt)*) => {
+ macro_rules! $name {
+ $($rule)*
+ }
+ };
+}
+
+pub(crate) use impl_multiple;
+
mod sealed
{
pub trait Sealed {}
diff --git a/ecs/src/util/array_vec.rs b/ecs/src/util/array_vec.rs
index 648c976..5d0aac9 100644
--- a/ecs/src/util/array_vec.rs
+++ b/ecs/src/util/array_vec.rs
@@ -1,4 +1,4 @@
-use std::mem::{transmute, MaybeUninit};
+use std::mem::MaybeUninit;
use std::ops::{Deref, DerefMut};
#[derive(Debug)]
@@ -10,16 +10,18 @@ pub struct ArrayVec<Item, const CAPACITY: usize>
impl<Item, const CAPACITY: usize> ArrayVec<Item, CAPACITY>
{
- pub fn new() -> Self
+ #[inline]
+ #[must_use]
+ pub fn len(&self) -> usize
{
- Self::default()
+ self.len
}
#[inline]
#[must_use]
- pub fn len(&self) -> usize
+ pub fn is_empty(&self) -> bool
{
- self.len
+ self.len == 0
}
pub fn push(&mut self, item: Item)
@@ -43,8 +45,8 @@ impl<Item, const CAPACITY: usize> ArrayVec<Item, CAPACITY>
unsafe {
std::ptr::copy(
- &self.items[index],
- &mut self.items[index + 1],
+ &raw const self.items[index],
+ &raw mut self.items[index + 1],
self.len - index,
);
}
@@ -69,7 +71,9 @@ impl<Item, const CAPACITY: usize> AsRef<[Item]> for ArrayVec<Item, CAPACITY>
{
fn as_ref(&self) -> &[Item]
{
- unsafe { transmute::<&[MaybeUninit<Item>], &[Item]>(&self.items[..self.len]) }
+ let ptr = &raw const self.items[..self.len];
+
+ unsafe { &*(ptr as *const [Item]) }
}
}
@@ -77,11 +81,9 @@ impl<Item, const CAPACITY: usize> AsMut<[Item]> for ArrayVec<Item, CAPACITY>
{
fn as_mut(&mut self) -> &mut [Item]
{
- unsafe {
- transmute::<&mut [MaybeUninit<Item>], &mut [Item]>(
- &mut self.items[..self.len],
- )
- }
+ let ptr = &raw mut self.items[..self.len];
+
+ unsafe { &mut *(ptr as *mut [Item]) }
}
}
@@ -113,3 +115,17 @@ impl<Item, const CAPACITY: usize> Default for ArrayVec<Item, CAPACITY>
}
}
}
+
+impl<Item, const CAPACITY: usize> Drop for ArrayVec<Item, CAPACITY>
+{
+ fn drop(&mut self)
+ {
+ for item in &mut self.items[..self.len] {
+ // SAFETY: The items from index 0 to the length index will always be
+ // initialized and satisfy all the invariants of the Item type.
+ unsafe {
+ item.assume_init_drop();
+ }
+ }
+ }
+}
diff --git a/ecs/tests/query.rs b/ecs/tests/query.rs
index 0f02bd3..7b218e3 100644
--- a/ecs/tests/query.rs
+++ b/ecs/tests/query.rs
@@ -1,4 +1,5 @@
use ecs::component::Component;
+use ecs::pair::{Pair, Wildcard};
use ecs::query::term::Without;
use ecs::query::{
TermWithFieldTuple as QueryTermWithFieldTuple,
@@ -36,13 +37,13 @@ struct G;
fn setup()
{
SETUP.call_once_force(|_| {
- assert_eq!(A::id().id(), 1);
- assert_eq!(B::id().id(), 2);
- assert_eq!(C::id().id(), 3);
- assert_eq!(D::id().id(), 4);
- assert_eq!(E::id().id(), 5);
- assert_eq!(F::id().id(), 6);
- assert_eq!(G::id().id(), 7);
+ assert_eq!(A::id().id(), Uid::FIRST_UNIQUE_ID);
+ assert_eq!(B::id().id(), Uid::FIRST_UNIQUE_ID + 1);
+ assert_eq!(C::id().id(), Uid::FIRST_UNIQUE_ID + 2);
+ assert_eq!(D::id().id(), Uid::FIRST_UNIQUE_ID + 3);
+ assert_eq!(E::id().id(), Uid::FIRST_UNIQUE_ID + 4);
+ assert_eq!(F::id().id(), Uid::FIRST_UNIQUE_ID + 5);
+ assert_eq!(G::id().id(), Uid::FIRST_UNIQUE_ID + 6);
});
}
@@ -210,7 +211,7 @@ fn query_archetype_exists_with_4_comps_diff_to_next_archetype_and_opt_comp()
let ent_2_id = world.create_entity((A, B, G));
assert_query_finds_ents(
- world.query::<(&A, &Option<E>, &G), ()>(),
+ world.query::<(&A, Option<&E>, &G), ()>(),
vec![ent_1_id, ent_2_id],
);
}
@@ -249,7 +250,7 @@ fn query_archetype_nonexistant_and_opt_comp()
world.create_entity((A, B, C, G, F));
assert_query_finds_ents(
- world.query::<(&A, &E, &Option<D>), ()>(),
+ world.query::<(&A, &E, Option<&D>), ()>(),
vec![ent_2_id, ent_3_id],
);
}
@@ -320,3 +321,93 @@ fn query_without_comp_and_archetype_nonexistant()
vec![ent_1_id, ent_2_id],
);
}
+
+#[test]
+fn query_with_wildcard_target_pair()
+{
+ setup();
+
+ let _test_lock = TEST_LOCK.lock();
+
+ let mut world = World::new();
+
+ let ent_1_id = world.create_entity((A, C));
+
+ world.create_entity((B,));
+
+ let ent_2_id = world.create_entity((
+ B,
+ Pair::builder().relation::<G>().target_id(ent_1_id).build(),
+ ));
+
+ world.create_entity((
+ B,
+ Pair::builder().relation::<F>().target_id(ent_1_id).build(),
+ ));
+ world.create_entity((
+ B,
+ A,
+ C,
+ Pair::builder().relation::<F>().target_id(ent_1_id).build(),
+ ));
+
+ let ent_3_id = world.create_entity((
+ B,
+ Pair::builder().relation::<G>().target_id(ent_2_id).build(),
+ ));
+
+ let ent_4_id = world.create_entity((
+ B,
+ E,
+ Pair::builder().relation::<G>().target_as_data(D).build(),
+ ));
+
+ assert_query_finds_ents(
+ world.query::<(&B, Pair<G, Wildcard>), ()>(),
+ vec![ent_2_id, ent_3_id, ent_4_id],
+ );
+}
+
+#[test]
+fn query_with_component_target_pair()
+{
+ setup();
+
+ let _test_lock = TEST_LOCK.lock();
+
+ let mut world = World::new();
+
+ let ent_1_id = world.create_entity((A, C));
+
+ world.create_entity((B,));
+
+ world.create_entity((
+ B,
+ Pair::builder().relation::<G>().target_id(ent_1_id).build(),
+ ));
+
+ world.create_entity((
+ B,
+ Pair::builder().relation::<F>().target_id(ent_1_id).build(),
+ ));
+ world.create_entity((
+ B,
+ A,
+ C,
+ Pair::builder().relation::<F>().target_id(ent_1_id).build(),
+ ));
+
+ let ent_2_id = world
+ .create_entity((B, Pair::builder().relation::<G>().target_as_data(F).build()));
+
+ let ent_3_id = world.create_entity((
+ B,
+ E,
+ Pair::builder().relation::<G>().target_as_data(F).build(),
+ ));
+
+ assert_query_finds_ents(
+ world.query::<(&B, Pair<G, &F>), ()>(),
+ vec![ent_2_id, ent_3_id],
+ );
+}
diff --git a/engine/Cargo.toml b/engine/Cargo.toml
index f6cd5cf..a62f458 100644
--- a/engine/Cargo.toml
+++ b/engine/Cargo.toml
@@ -14,7 +14,8 @@ paste = "1.0.14"
ecs = { path = "../ecs" }
util-macros = { path = "../util-macros" }
-[dependencies.image]
+[dependencies.image_rs]
version = "0.24.7"
default-features = false
features = ["png", "jpeg"]
+package = "image"
diff --git a/engine/src/asset.rs b/engine/src/asset.rs
new file mode 100644
index 0000000..db4d23c
--- /dev/null
+++ b/engine/src/asset.rs
@@ -0,0 +1,777 @@
+use std::any::{type_name, Any};
+use std::borrow::Cow;
+use std::cell::RefCell;
+use std::collections::HashMap;
+use std::convert::Infallible;
+use std::ffi::{OsStr, OsString};
+use std::fmt::{Debug, Display};
+use std::hash::{DefaultHasher, Hash, Hasher};
+use std::marker::PhantomData;
+use std::path::{Path, PathBuf};
+use std::sync::mpsc::{
+ channel as mpsc_channel,
+ Receiver as MpscReceiver,
+ Sender as MpscSender,
+};
+use std::sync::Arc;
+
+use ecs::phase::PRE_UPDATE as PRE_UPDATE_PHASE;
+use ecs::sole::Single;
+use ecs::Sole;
+
+use crate::work_queue::{Work, WorkQueue};
+
+/// Asset label.
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct Label<'a>
+{
+ pub path: Cow<'a, Path>,
+ pub name: Option<Cow<'a, str>>,
+}
+
+impl Label<'_>
+{
+ pub fn to_owned(&self) -> LabelOwned
+ {
+ LabelOwned {
+ path: self.path.to_path_buf(),
+ name: self.name.as_ref().map(|name| name.to_string()),
+ }
+ }
+}
+
+impl<'a> From<&'a Path> for Label<'a>
+{
+ fn from(path: &'a Path) -> Self
+ {
+ Self { path: path.into(), name: None }
+ }
+}
+
+impl From<PathBuf> for Label<'_>
+{
+ fn from(path: PathBuf) -> Self
+ {
+ Self { path: path.into(), name: None }
+ }
+}
+
+impl<'a> From<&'a LabelOwned> for Label<'a>
+{
+ fn from(label: &'a LabelOwned) -> Self
+ {
+ Self {
+ path: (&label.path).into(),
+ name: label.name.as_ref().map(|name| Cow::Borrowed(name.as_str())),
+ }
+ }
+}
+
+impl Display for Label<'_>
+{
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
+ {
+ write!(formatter, "{}", self.path.display())?;
+
+ if let Some(name) = &self.name {
+ formatter.write_str("::")?;
+ formatter.write_str(&name)?;
+ }
+
+ Ok(())
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct LabelOwned
+{
+ pub path: PathBuf,
+ pub name: Option<String>,
+}
+
+impl LabelOwned
+{
+ pub fn to_label(&self) -> Label<'_>
+ {
+ Label {
+ path: (&self.path).into(),
+ name: self.name.as_ref().map(|name| Cow::Borrowed(name.as_str())),
+ }
+ }
+}
+
+impl Display for LabelOwned
+{
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
+ {
+ write!(formatter, "{}", self.path.display())?;
+
+ if let Some(name) = &self.name {
+ formatter.write_str("::")?;
+ formatter.write_str(&name)?;
+ }
+
+ Ok(())
+ }
+}
+
+#[derive(Debug, Sole)]
+pub struct Assets
+{
+ assets: Vec<StoredAsset>,
+ asset_lookup: RefCell<HashMap<LabelHash, LookupEntry>>,
+ importers: Vec<WrappedImporterFn>,
+ importer_lookup: HashMap<OsString, usize>,
+ import_work_queue: WorkQueue<ImportWorkUserData>,
+ import_work_msg_receiver: MpscReceiver<ImportWorkMessage>,
+ import_work_msg_sender: MpscSender<ImportWorkMessage>,
+}
+
+impl Assets
+{
+ pub fn with_capacity(capacity: usize) -> Self
+ {
+ let (import_work_msg_sender, import_work_msg_receiver) =
+ mpsc_channel::<ImportWorkMessage>();
+
+ Self {
+ assets: Vec::with_capacity(capacity),
+ asset_lookup: RefCell::new(HashMap::with_capacity(capacity)),
+ importers: Vec::new(),
+ importer_lookup: HashMap::new(),
+ import_work_queue: WorkQueue::new(),
+ import_work_msg_receiver,
+ import_work_msg_sender,
+ }
+ }
+
+ pub fn set_importer<'file_ext, AssetSettings, Err>(
+ &mut self,
+ file_extensions: impl IntoIterator<Item: Into<Cow<'file_ext, str>>>,
+ func: impl Fn(&mut Submitter<'_>, &Path, Option<&AssetSettings>) -> Result<(), Err>,
+ ) where
+ AssetSettings: 'static,
+ Err: std::error::Error + 'static,
+ {
+ self.importers.push(WrappedImporterFn::new(func));
+
+ let importer_index = self.importers.len() - 1;
+
+ self.importer_lookup
+ .extend(file_extensions.into_iter().map(|file_ext| {
+ let file_ext: Cow<str> = file_ext.into();
+
+ (file_ext.into_owned().into(), importer_index)
+ }));
+ }
+
+ #[tracing::instrument(skip_all, fields(asset_type=type_name::<Asset>()))]
+ pub fn get<'this, 'handle, Asset: 'static + Send + Sync>(
+ &'this self,
+ handle: &'handle Handle<Asset>,
+ ) -> Option<&'handle Asset>
+ where
+ 'this: 'handle,
+ {
+ let LookupEntry::Occupied(asset_index) =
+ *self.asset_lookup.borrow().get(&handle.id.label_hash)?
+ else {
+ return None;
+ };
+
+ let stored_asset = self.assets.get(asset_index).expect("Not possible");
+
+ let Some(asset) = stored_asset.strong.downcast_ref::<Asset>() else {
+ tracing::error!("Wrong asset type");
+ return None;
+ };
+
+ Some(asset)
+ }
+
+ #[tracing::instrument(skip(self))]
+ pub fn load<'i, Asset: 'static + Send + Sync>(
+ &self,
+ label: impl Into<Label<'i>> + Debug,
+ ) -> Handle<Asset>
+ {
+ let label = label.into();
+
+ let label_hash = LabelHash::new(&label);
+
+ let mut asset_lookup = self.asset_lookup.borrow_mut();
+
+ if Self::is_pending(&asset_lookup, &label) {
+ return Handle::new(label_hash);
+ }
+
+ let Some(lookup_entry) = asset_lookup.get(&label_hash) else {
+ self.add_import_work::<Infallible>(
+ &label,
+ label_hash,
+ None,
+ &mut asset_lookup,
+ );
+
+ return Handle::new(label_hash);
+ };
+
+ match *lookup_entry {
+ LookupEntry::Occupied(asset_index) => {
+ let stored_asset = self.assets.get(asset_index).expect("Not possible");
+
+ if stored_asset.strong.downcast_ref::<Asset>().is_none() {
+ tracing::error!("Wrong asset type {}", type_name::<Asset>());
+ }
+ }
+ LookupEntry::Pending => {}
+ }
+
+ Handle::new(label_hash)
+ }
+
+ #[tracing::instrument(skip(self))]
+ pub fn load_with_settings<'i, Asset, AssetSettings>(
+ &self,
+ label: impl Into<Label<'i>> + Debug,
+ asset_settings: AssetSettings,
+ ) -> Handle<Asset>
+ where
+ Asset: Send + Sync + 'static,
+ AssetSettings: Send + Sync + Debug + 'static,
+ {
+ let label = label.into();
+
+ let label_hash = LabelHash::new(&label);
+
+ let mut asset_lookup = self.asset_lookup.borrow_mut();
+
+ if Self::is_pending(&asset_lookup, &label) {
+ return Handle::new(label_hash);
+ }
+
+ let Some(lookup_entry) = asset_lookup.get(&label_hash) else {
+ self.add_import_work::<AssetSettings>(
+ &label,
+ label_hash,
+ Some(asset_settings),
+ &mut asset_lookup,
+ );
+
+ return Handle::new(label_hash);
+ };
+
+ match *lookup_entry {
+ LookupEntry::Occupied(asset_index) => {
+ let stored_asset = self.assets.get(asset_index).expect("Not possible");
+
+ if stored_asset.strong.downcast_ref::<Asset>().is_none() {
+ tracing::error!(
+ "Wrong asset type {} for asset",
+ type_name::<Asset>()
+ );
+ }
+ }
+ LookupEntry::Pending => {}
+ }
+
+ Handle::new(label_hash)
+ }
+
+ pub fn store_with_name<'name, Asset: 'static + Send + Sync>(
+ &mut self,
+ name: impl Into<Cow<'name, str>>,
+ asset: Asset,
+ ) -> Handle<Asset>
+ {
+ self.store_with_label(
+ Label {
+ path: Path::new("").into(),
+ name: Some(name.into()),
+ },
+ asset,
+ )
+ }
+
+ #[tracing::instrument(skip(self, asset), fields(asset_type=type_name::<Asset>()))]
+ pub fn store_with_label<'i, Asset: 'static + Send + Sync>(
+ &mut self,
+ label: impl Into<Label<'i>> + Debug,
+ asset: Asset,
+ ) -> Handle<Asset>
+ {
+ let label = label.into();
+
+ let label_hash = LabelHash::new(&label);
+
+ if matches!(
+ self.asset_lookup.get_mut().get(&label_hash),
+ Some(LookupEntry::Occupied(_))
+ ) {
+ tracing::error!("Asset already exists");
+
+ return Handle::new(label_hash);
+ }
+
+ tracing::debug!("Storing asset");
+
+ self.assets.push(StoredAsset::new(asset));
+
+ let index = self.assets.len() - 1;
+
+ self.asset_lookup
+ .get_mut()
+ .insert(label_hash, LookupEntry::Occupied(index));
+
+ if label.name.is_some() {
+ let parent_asset_label_hash =
+ LabelHash::new(&Label { path: label.path, name: None });
+
+ if matches!(
+ self.asset_lookup.get_mut().get(&parent_asset_label_hash),
+ Some(LookupEntry::Pending)
+ ) {
+ self.asset_lookup.get_mut().remove(&parent_asset_label_hash);
+ } else if self
+ .asset_lookup
+ .get_mut()
+ .get(&parent_asset_label_hash)
+ .is_none()
+ {
+ self.assets
+ .push(StoredAsset::new::<Option<Infallible>>(None));
+
+ self.asset_lookup.get_mut().insert(
+ parent_asset_label_hash,
+ LookupEntry::Occupied(self.assets.len() - 1),
+ );
+ }
+ }
+
+ Handle::new(label_hash)
+ }
+
+ fn is_pending(asset_lookup: &HashMap<LabelHash, LookupEntry>, label: &Label) -> bool
+ {
+ if label.name.is_some() {
+ if let Some(LookupEntry::Pending) =
+ asset_lookup.get(&LabelHash::new(&Label {
+ path: label.path.as_ref().into(),
+ name: None,
+ }))
+ {
+ return true;
+ }
+ }
+
+ if let Some(LookupEntry::Pending) = asset_lookup.get(&LabelHash::new(label)) {
+ return true;
+ };
+
+ false
+ }
+
+ fn add_import_work<AssetSettings>(
+ &self,
+ label: &Label<'_>,
+ label_hash: LabelHash,
+ asset_settings: Option<AssetSettings>,
+ asset_lookup: &mut HashMap<LabelHash, LookupEntry>,
+ ) where
+ AssetSettings: Any + Send + Sync,
+ {
+ let Some(file_ext) = label.path.extension() else {
+ tracing::error!("Asset file is missing a file extension");
+ return;
+ };
+
+ let Some(importer) = self.get_importer(file_ext) else {
+ tracing::error!(
+ "No importer exists for asset file extension {}",
+ file_ext.to_string_lossy()
+ );
+ return;
+ };
+
+ self.import_work_queue.add_work(Work {
+ func: |ImportWorkUserData {
+ import_work_msg_sender,
+ asset_path,
+ asset_settings,
+ importer,
+ }| {
+ if let Err(err) = importer.call(
+ import_work_msg_sender,
+ asset_path.as_path(),
+ asset_settings.as_deref(),
+ ) {
+ tracing::error!(
+ "Failed to load asset {}: {err}",
+ asset_path.display()
+ );
+ }
+ },
+ user_data: ImportWorkUserData {
+ import_work_msg_sender: self.import_work_msg_sender.clone(),
+ asset_path: label.path.to_path_buf(),
+ asset_settings: asset_settings.map(|asset_settings| {
+ Box::new(asset_settings) as Box<dyn Any + Send + Sync>
+ }),
+ importer: importer.clone(),
+ },
+ });
+
+ asset_lookup.insert(label_hash, LookupEntry::Pending);
+
+ if label.name.is_some() {
+ asset_lookup.insert(
+ LabelHash::new(&Label {
+ path: label.path.as_ref().into(),
+ name: None,
+ }),
+ LookupEntry::Pending,
+ );
+ }
+ }
+
+ fn get_importer(&self, file_ext: &OsStr) -> Option<&WrappedImporterFn>
+ {
+ let index = *self.importer_lookup.get(file_ext)?;
+
+ Some(self.importers.get(index).expect("Not possible"))
+ }
+}
+
+impl Default for Assets
+{
+ fn default() -> Self
+ {
+ Self::with_capacity(0)
+ }
+}
+
+pub struct Submitter<'path>
+{
+ import_work_msg_sender: MpscSender<ImportWorkMessage>,
+ asset_path: &'path Path,
+}
+
+impl Submitter<'_>
+{
+ pub fn submit_load_other<'label, Asset: Send + Sync + 'static>(
+ &self,
+ label: impl Into<Label<'label>>,
+ ) -> Handle<Asset>
+ {
+ let label = label.into();
+
+ let _ = self.import_work_msg_sender.send(ImportWorkMessage::Load {
+ do_load: |assets, label, _asset_settings| {
+ let _ = assets.load::<Asset>(label);
+ },
+ label: label.to_owned(),
+ asset_settings: None,
+ });
+
+ Handle::new(LabelHash::new(&label))
+ }
+
+ pub fn submit_load_other_with_settings<'label, Asset, AssetSettings>(
+ &self,
+ label: impl Into<Label<'label>>,
+ asset_settings: AssetSettings,
+ ) -> Handle<Asset>
+ where
+ Asset: Send + Sync + 'static,
+ AssetSettings: Send + Sync + Debug + 'static,
+ {
+ let label = label.into();
+
+ let _ = self.import_work_msg_sender.send(ImportWorkMessage::Load {
+ do_load: |assets, label, asset_settings| {
+ let asset_settings = *asset_settings
+ .expect("Not possible")
+ .downcast::<AssetSettings>()
+ .expect("Not possible");
+
+ let _ = assets
+ .load_with_settings::<Asset, AssetSettings>(label, asset_settings);
+ },
+ label: label.to_owned(),
+ asset_settings: Some(Box::new(asset_settings)),
+ });
+
+ Handle::new(LabelHash::new(&label))
+ }
+
+ pub fn submit_store<Asset: Send + Sync + 'static>(
+ &self,
+ asset: Asset,
+ ) -> Handle<Asset>
+ {
+ let label = LabelOwned {
+ path: self.asset_path.into(),
+ name: None,
+ };
+
+ let label_hash = LabelHash::new(&label.to_label());
+
+ let _ = self.import_work_msg_sender.send(ImportWorkMessage::Store {
+ do_store: |assets, label, boxed_asset| {
+ let Ok(asset) = boxed_asset.downcast::<Asset>() else {
+ unreachable!();
+ };
+
+ assets.store_with_label::<Asset>(&label, *asset);
+ },
+ label,
+ asset: Box::new(asset),
+ });
+
+ Handle::new(label_hash)
+ }
+
+ pub fn submit_store_named<Asset: Send + Sync + 'static>(
+ &self,
+ name: impl AsRef<str>,
+ asset: Asset,
+ ) -> Handle<Asset>
+ {
+ let label = LabelOwned {
+ path: self.asset_path.into(),
+ name: Some(name.as_ref().into()),
+ };
+
+ let label_hash = LabelHash::new(&label.to_label());
+
+ let _ = self.import_work_msg_sender.send(ImportWorkMessage::Store {
+ do_store: |assets, label, boxed_asset| {
+ let Ok(asset) = boxed_asset.downcast::<Asset>() else {
+ unreachable!();
+ };
+
+ assets.store_with_label::<Asset>(&label, *asset);
+ },
+ label,
+ asset: Box::new(asset),
+ });
+
+ Handle::new(label_hash)
+ }
+}
+
+/// Asset handle.
+#[derive(Debug)]
+pub struct Handle<Asset: 'static>
+{
+ id: Id,
+ _pd: PhantomData<Asset>,
+}
+
+impl<Asset: 'static> Handle<Asset>
+{
+ pub fn id(&self) -> Id
+ {
+ self.id
+ }
+
+ fn new(label_hash: LabelHash) -> Self
+ {
+ Self {
+ id: Id { label_hash },
+ _pd: PhantomData,
+ }
+ }
+}
+
+impl<Asset: 'static> Clone for Handle<Asset>
+{
+ fn clone(&self) -> Self
+ {
+ Self { id: self.id, _pd: PhantomData }
+ }
+}
+
+/// Asset ID.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct Id
+{
+ label_hash: LabelHash,
+}
+
+#[derive(Debug, thiserror::Error)]
+enum ImporterError
+{
+ #[error("Settings has a incorrect type")]
+ IncorrectAssetSettingsType(PathBuf),
+
+ #[error(transparent)]
+ Other(Box<dyn std::error::Error>),
+}
+
+#[derive(Debug, Clone)]
+struct WrappedImporterFn
+{
+ wrapper_func: fn(
+ MpscSender<ImportWorkMessage>,
+ &Path,
+ Option<&(dyn Any + Send + Sync)>,
+ ) -> Result<(), ImporterError>,
+}
+
+impl WrappedImporterFn
+{
+ fn new<InnerFunc, AssetSettings, Err>(inner_func_param: InnerFunc) -> Self
+ where
+ InnerFunc:
+ Fn(&mut Submitter<'_>, &Path, Option<&AssetSettings>) -> Result<(), Err>,
+ AssetSettings: 'static,
+ Err: std::error::Error + 'static,
+ {
+ assert_eq!(size_of::<InnerFunc>(), 0);
+
+ let wrapper_func =
+ |import_work_msg_sender: MpscSender<ImportWorkMessage>,
+ asset_path: &Path,
+ asset_settings: Option<&(dyn Any + Send + Sync)>| {
+ let inner_func = unsafe { std::mem::zeroed::<InnerFunc>() };
+
+ let asset_settings = asset_settings
+ .map(|asset_settings| {
+ asset_settings
+ .downcast_ref::<AssetSettings>()
+ .ok_or_else(|| {
+ ImporterError::IncorrectAssetSettingsType(
+ asset_path.to_path_buf(),
+ )
+ })
+ })
+ .transpose()?;
+
+ inner_func(
+ &mut Submitter { import_work_msg_sender, asset_path },
+ asset_path,
+ asset_settings,
+ )
+ .map_err(|err| ImporterError::Other(Box::new(err)))?;
+
+ Ok(())
+ };
+
+ std::mem::forget(inner_func_param);
+
+ Self { wrapper_func }
+ }
+
+ fn call(
+ &self,
+ import_work_msg_sender: MpscSender<ImportWorkMessage>,
+ asset_path: &Path,
+ asset_settings: Option<&(dyn Any + Send + Sync)>,
+ ) -> Result<(), ImporterError>
+ {
+ (self.wrapper_func)(import_work_msg_sender, asset_path, asset_settings)
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+struct LabelHash(u64);
+
+impl LabelHash
+{
+ fn new(label: &Label<'_>) -> Self
+ {
+ let mut hasher = DefaultHasher::new();
+
+ label.hash(&mut hasher);
+
+ Self(hasher.finish())
+ }
+}
+
+#[derive(Debug, Default)]
+pub(crate) struct Extension
+{
+ pub assets: Assets,
+}
+
+impl ecs::extension::Extension for Extension
+{
+ fn collect(self, mut collector: ecs::extension::Collector<'_>)
+ {
+ let _ = collector.add_sole(self.assets);
+
+ collector.add_system(*PRE_UPDATE_PHASE, add_received_assets);
+ }
+}
+
+fn add_received_assets(mut assets: Single<Assets>)
+{
+ while let Some(import_work_msg) = assets.import_work_msg_receiver.try_recv().ok() {
+ match import_work_msg {
+ ImportWorkMessage::Store { do_store, label, asset } => {
+ do_store(&mut assets, label, asset);
+ }
+ ImportWorkMessage::Load { do_load, label, asset_settings } => {
+ do_load(
+ &assets,
+ Label {
+ path: label.path.as_path().into(),
+ name: label.name.as_deref().map(|name| name.into()),
+ },
+ asset_settings,
+ );
+ }
+ }
+ }
+}
+
+#[derive(Debug)]
+struct ImportWorkUserData
+{
+ import_work_msg_sender: MpscSender<ImportWorkMessage>,
+ asset_path: PathBuf,
+ asset_settings: Option<Box<dyn Any + Send + Sync>>,
+ importer: WrappedImporterFn,
+}
+
+#[derive(Debug)]
+enum ImportWorkMessage
+{
+ Store
+ {
+ do_store: fn(&mut Assets, LabelOwned, Box<dyn Any + Send + Sync>),
+ label: LabelOwned,
+ asset: Box<dyn Any + Send + Sync>,
+ },
+
+ Load
+ {
+ do_load: fn(&Assets, Label<'_>, Option<Box<dyn Any + Send + Sync>>),
+ label: LabelOwned,
+ asset_settings: Option<Box<dyn Any + Send + Sync>>,
+ },
+}
+
+#[derive(Debug, Clone, Copy)]
+enum LookupEntry
+{
+ Occupied(usize),
+ Pending,
+}
+
+#[derive(Debug)]
+struct StoredAsset
+{
+ strong: Arc<dyn Any + Send + Sync>,
+}
+
+impl StoredAsset
+{
+ fn new<Asset: Any + Send + Sync>(asset: Asset) -> Self
+ {
+ let strong = Arc::new(asset);
+
+ Self { strong }
+ }
+}
diff --git a/engine/src/camera/fly.rs b/engine/src/camera/fly.rs
index 087f727..b1214db 100644
--- a/engine/src/camera/fly.rs
+++ b/engine/src/camera/fly.rs
@@ -1,14 +1,15 @@
use ecs::component::local::Local;
use ecs::phase::UPDATE as UPDATE_PHASE;
use ecs::sole::Single;
-use ecs::system::{Into, System};
+use ecs::system::initializable::Initializable;
+use ecs::system::Into;
use ecs::{Component, Query};
+use crate::builder;
use crate::camera::{Active as ActiveCamera, Camera};
use crate::delta_time::DeltaTime;
use crate::input::{Cursor, CursorFlags, Key, KeyState, Keys};
-use crate::transform::Position;
-use crate::util::builder;
+use crate::transform::WorldPosition;
use crate::vector::{Vec2, Vec3};
builder! {
@@ -75,7 +76,7 @@ pub struct Options
}
fn update(
- camera_query: Query<(&mut Camera, &mut Position, &mut Fly, &ActiveCamera)>,
+ camera_query: Query<(&mut Camera, &mut WorldPosition, &mut Fly, &ActiveCamera)>,
keys: Single<Keys>,
cursor: Single<Cursor>,
cursor_flags: Single<CursorFlags>,
@@ -84,7 +85,7 @@ fn update(
options: Local<Options>,
)
{
- for (mut camera, mut camera_pos, mut fly_camera, _) in &camera_query {
+ for (mut camera, mut camera_world_pos, mut fly_camera, _) in &camera_query {
if cursor.has_moved && cursor_flags.is_first_move.flag {
tracing::debug!("First cursor move");
@@ -122,29 +123,30 @@ fn update(
camera.global_up = cam_right.cross(&direction).normalize();
if keys.get_key_state(Key::W) == KeyState::Pressed {
- camera_pos.position +=
+ camera_world_pos.position +=
direction * fly_camera.speed * delta_time.as_secs_f32();
}
if keys.get_key_state(Key::S) == KeyState::Pressed {
- camera_pos.position -=
+ camera_world_pos.position -=
direction * fly_camera.speed * delta_time.as_secs_f32();
}
if keys.get_key_state(Key::A) == KeyState::Pressed {
let cam_left = -direction.cross(&Vec3::UP).normalize();
- camera_pos.position += cam_left * fly_camera.speed * delta_time.as_secs_f32();
+ camera_world_pos.position +=
+ cam_left * fly_camera.speed * delta_time.as_secs_f32();
}
if keys.get_key_state(Key::D) == KeyState::Pressed {
let cam_right = direction.cross(&Vec3::UP).normalize();
- camera_pos.position +=
+ camera_world_pos.position +=
cam_right * fly_camera.speed * delta_time.as_secs_f32();
}
- camera.target = camera_pos.position + direction;
+ camera.target = camera_world_pos.position + direction;
}
}
diff --git a/engine/src/data_types/dimens.rs b/engine/src/data_types/dimens.rs
index 5002436..d8d0247 100644
--- a/engine/src/data_types/dimens.rs
+++ b/engine/src/data_types/dimens.rs
@@ -6,6 +6,22 @@ pub struct Dimens<Value>
pub height: Value,
}
+impl<Value: Clone> From<Value> for Dimens<Value>
+{
+ fn from(value: Value) -> Self
+ {
+ Self { width: value.clone(), height: value }
+ }
+}
+
+impl<Value> From<(Value, Value)> for Dimens<Value>
+{
+ fn from(value: (Value, Value)) -> Self
+ {
+ Self { width: value.0, height: value.1 }
+ }
+}
+
/// 3D dimensions.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Dimens3<Value>
@@ -14,3 +30,27 @@ pub struct Dimens3<Value>
pub height: Value,
pub depth: Value,
}
+
+impl<Value: Clone> From<Value> for Dimens3<Value>
+{
+ fn from(value: Value) -> Self
+ {
+ Self {
+ width: value.clone(),
+ height: value.clone(),
+ depth: value,
+ }
+ }
+}
+
+impl<Value: Clone> From<(Value, Value, Value)> for Dimens3<Value>
+{
+ fn from(value: (Value, Value, Value)) -> Self
+ {
+ Self {
+ width: value.0,
+ height: value.1,
+ depth: value.2,
+ }
+ }
+}
diff --git a/engine/src/data_types/vector.rs b/engine/src/data_types/vector.rs
index 802a4a7..100c709 100644
--- a/engine/src/data_types/vector.rs
+++ b/engine/src/data_types/vector.rs
@@ -3,6 +3,7 @@ use std::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
use crate::color::Color;
#[derive(Debug, Default, Clone, Copy, PartialEq)]
+#[repr(C)]
pub struct Vec2<Value>
{
pub x: Value,
diff --git a/engine/src/draw_flags.rs b/engine/src/draw_flags.rs
index df5eed1..426f865 100644
--- a/engine/src/draw_flags.rs
+++ b/engine/src/draw_flags.rs
@@ -1,6 +1,6 @@
use ecs::Component;
-use crate::util::builder;
+use crate::builder;
builder! {
/// Flags for how a object should be drawn.
diff --git a/engine/src/file_format/wavefront/mtl.rs b/engine/src/file_format/wavefront/mtl.rs
index d90dbcf..f3c7a64 100644
--- a/engine/src/file_format/wavefront/mtl.rs
+++ b/engine/src/file_format/wavefront/mtl.rs
@@ -2,7 +2,7 @@
//!
//! File format documentation: <https://paulbourke.net/dataformats/mtl>
-use std::path::Path;
+use std::path::{Path, PathBuf};
use crate::color::Color;
use crate::file_format::wavefront::common::{
@@ -11,8 +11,6 @@ use crate::file_format::wavefront::common::{
ParsingError,
Statement,
};
-use crate::material::{Builder as MaterialBuilder, Material};
-use crate::texture::{Error as TextureError, Texture};
/// Parses the content of a Wavefront `.mtl`.
///
@@ -50,18 +48,41 @@ pub fn parse(obj_content: &str) -> Result<Vec<NamedMaterial>, Error>
}
#[derive(Debug, Clone)]
+#[non_exhaustive]
pub struct NamedMaterial
{
pub name: String,
- pub material: Material,
+ pub ambient: Color<f32>,
+ pub diffuse: Color<f32>,
+ pub specular: Color<f32>,
+ pub ambient_map: Option<TextureMap>,
+ pub diffuse_map: Option<TextureMap>,
+ pub specular_map: Option<TextureMap>,
+ pub shininess: f32,
+}
+
+impl Default for NamedMaterial
+{
+ fn default() -> Self
+ {
+ Self {
+ name: String::new(),
+ ambient: Color::WHITE_F32,
+ diffuse: Color::WHITE_F32,
+ specular: Color::WHITE_F32,
+ ambient_map: None,
+ diffuse_map: None,
+ specular_map: None,
+ shininess: 0.0,
+ }
+ }
}
#[derive(Debug, Clone)]
-pub struct UnfinishedNamedMaterial
+#[non_exhaustive]
+pub struct TextureMap
{
- name: String,
- material_builder: MaterialBuilder,
- ready: bool,
+ pub path: PathBuf,
}
#[derive(Debug, thiserror::Error)]
@@ -70,8 +91,14 @@ pub enum Error
#[error(transparent)]
ParsingError(#[from] ParsingError),
- #[error("Failed to open texture")]
- TextureError(#[from] TextureError),
+ #[error(
+ "A material start statement (newmtl) is expected before statement at line {}",
+ line_no
+ )]
+ ExpectedMaterialStartStmtBeforeStmt
+ {
+ line_no: usize
+ },
#[error(
"Unsupported number of arguments ({arg_count}) to {keyword} at line {line_no}"
@@ -100,59 +127,52 @@ fn statements_to_materials(
{
let mut materials = Vec::<NamedMaterial>::with_capacity(material_cnt);
- let mut curr_material = UnfinishedNamedMaterial {
- name: String::new(),
- material_builder: MaterialBuilder::new(),
- ready: false,
- };
-
for (line_no, statement) in statements {
if statement.keyword == Keyword::Newmtl {
- if curr_material.ready {
- tracing::debug!("Building material");
-
- let material = curr_material.material_builder.clone().build();
-
- materials.push(NamedMaterial { name: curr_material.name, material });
- }
-
let name = statement.get_text_arg(0, line_no)?;
- curr_material.name = name.to_string();
- curr_material.ready = true;
+ materials.push(NamedMaterial {
+ name: name.to_string(),
+ ..Default::default()
+ });
continue;
}
- if !curr_material.ready {
- // Discard statements not belonging to a material
- continue;
+ let Some(curr_material) = materials.last_mut() else {
+ return Err(Error::ExpectedMaterialStartStmtBeforeStmt { line_no });
};
match statement.keyword {
Keyword::Ka => {
let color = get_color_from_statement(&statement, line_no)?;
- tracing::debug!("Adding ambient color");
+ tracing::debug!(
+ "Adding ambient color {color:?} to material {}",
+ curr_material.name
+ );
- curr_material.material_builder =
- curr_material.material_builder.ambient(color);
+ curr_material.ambient = color;
}
Keyword::Kd => {
let color = get_color_from_statement(&statement, line_no)?;
- tracing::debug!("Adding diffuse color");
+ tracing::debug!(
+ "Adding diffuse color {color:?} to material {}",
+ curr_material.name
+ );
- curr_material.material_builder =
- curr_material.material_builder.diffuse(color);
+ curr_material.diffuse = color;
}
Keyword::Ks => {
let color = get_color_from_statement(&statement, line_no)?;
- tracing::debug!("Adding specular color");
+ tracing::debug!(
+ "Adding specular color {color:?} to material {}",
+ curr_material.name
+ );
- curr_material.material_builder =
- curr_material.material_builder.specular(color);
+ curr_material.specular = color;
}
Keyword::MapKa => {
if statement.arguments.len() > 1 {
@@ -165,51 +185,75 @@ fn statements_to_materials(
let texture_file_path = statement.get_text_arg(0, line_no)?;
- let texture = Texture::open(Path::new(texture_file_path))?;
-
- tracing::debug!("Adding ambient map");
+ tracing::debug!(
+ "Adding ambient map {texture_file_path} to material {}",
+ curr_material.name
+ );
- let texture_id = texture.id();
-
- curr_material.material_builder = curr_material
- .material_builder
- .texture(texture)
- .ambient_map(texture_id);
+ curr_material.ambient_map = Some(TextureMap {
+ path: Path::new(texture_file_path).to_path_buf(),
+ });
}
Keyword::MapKd => {
- let texture = get_map_from_texture(&statement, line_no)?;
+ if statement.arguments.len() > 1 {
+ return Err(Error::UnsupportedArgumentCount {
+ keyword: statement.keyword.to_string(),
+ arg_count: statement.arguments.len(),
+ line_no,
+ });
+ }
- tracing::debug!("Adding diffuse map");
+ let texture_file_path = statement.get_text_arg(0, line_no)?;
- let texture_id = texture.id();
+ tracing::debug!(
+ "Adding diffuse map {texture_file_path} to material {}",
+ curr_material.name
+ );
- curr_material.material_builder = curr_material
- .material_builder
- .texture(texture)
- .diffuse_map(texture_id);
+ curr_material.diffuse_map = Some(TextureMap {
+ path: Path::new(texture_file_path).to_path_buf(),
+ });
}
Keyword::MapKs => {
- let texture = get_map_from_texture(&statement, line_no)?;
+ if statement.arguments.len() > 1 {
+ return Err(Error::UnsupportedArgumentCount {
+ keyword: statement.keyword.to_string(),
+ arg_count: statement.arguments.len(),
+ line_no,
+ });
+ }
- tracing::debug!("Adding specular map");
+ let texture_file_path = statement.get_text_arg(0, line_no)?;
- let texture_id = texture.id();
+ tracing::debug!(
+ "Adding specular map {texture_file_path} to material {}",
+ curr_material.name
+ );
- curr_material.material_builder = curr_material
- .material_builder
- .texture(texture)
- .specular_map(texture_id);
+ curr_material.specular_map = Some(TextureMap {
+ path: Path::new(texture_file_path).to_path_buf(),
+ });
}
- Keyword::Newmtl => {}
- }
- }
+ Keyword::Ns => {
+ if statement.arguments.len() != 1 {
+ return Err(Error::UnsupportedArgumentCount {
+ keyword: statement.keyword.to_string(),
+ arg_count: statement.arguments.len(),
+ line_no,
+ });
+ }
- if curr_material.ready {
- tracing::debug!("Building last material");
+ let shininess = statement.get_float_arg(0, line_no)?;
- let material = curr_material.material_builder.build();
+ tracing::debug!(
+ "Adding shininess {shininess} to material {}",
+ curr_material.name
+ );
- materials.push(NamedMaterial { name: curr_material.name, material });
+ curr_material.shininess = shininess;
+ }
+ Keyword::Newmtl => {}
+ }
}
Ok(materials)
@@ -235,24 +279,6 @@ fn get_color_from_statement(
Ok(Color { red, green, blue })
}
-fn get_map_from_texture(
- statement: &Statement<Keyword>,
- line_no: usize,
-) -> Result<Texture, Error>
-{
- if statement.arguments.len() > 1 {
- return Err(Error::UnsupportedArgumentCount {
- keyword: statement.keyword.to_string(),
- arg_count: statement.arguments.len(),
- line_no,
- });
- }
-
- let texture_file_path = statement.get_text_arg(0, line_no)?;
-
- Ok(Texture::open(Path::new(texture_file_path))?)
-}
-
keyword! {
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum Keyword {
@@ -271,5 +297,7 @@ keyword! {
#[keyword(rename = "map_Ks")]
MapKs,
+
+ Ns,
}
}
diff --git a/engine/src/file_format/wavefront/obj.rs b/engine/src/file_format/wavefront/obj.rs
index 6ca11c2..88d566c 100644
--- a/engine/src/file_format/wavefront/obj.rs
+++ b/engine/src/file_format/wavefront/obj.rs
@@ -13,10 +13,9 @@ use crate::file_format::wavefront::common::{
Statement,
Triplet,
};
-use crate::mesh::Mesh;
+use crate::mesh::{Mesh, Vertex};
use crate::util::try_option;
use crate::vector::{Vec2, Vec3};
-use crate::vertex::{Builder as VertexBuilder, Vertex};
/// Parses the content of a Wavefront `.obj`.
///
@@ -168,7 +167,7 @@ impl FaceVertex
/// - The face's vertex normal cannot be found in the given [`Obj`]
pub fn to_vertex(&self, obj: &Obj) -> Result<Vertex, Error>
{
- let mut vertex_builder = VertexBuilder::default();
+ let mut vertex_builder = Vertex::builder();
let vertex_pos = *obj.vertex_positions.get(self.position as usize - 1).ok_or(
Error::FaceVertexPositionNotFound { vertex_pos_index: self.position },
diff --git a/engine/src/image.rs b/engine/src/image.rs
new file mode 100644
index 0000000..0e04412
--- /dev/null
+++ b/engine/src/image.rs
@@ -0,0 +1,184 @@
+use std::fs::File;
+use std::io::BufReader;
+use std::path::Path;
+
+use image_rs::GenericImageView as _;
+
+use crate::asset::{Assets, Submitter as AssetSubmitter};
+use crate::color::Color;
+use crate::data_types::dimens::Dimens;
+use crate::builder;
+
+#[derive(Debug)]
+pub struct Image
+{
+ inner: image_rs::DynamicImage,
+}
+
+impl Image
+{
+ pub fn open(path: impl AsRef<Path>) -> Result<Self, Error>
+ {
+ let buffered_reader =
+ BufReader::new(File::open(&path).map_err(Error::ReadFailed)?);
+
+ let image_reader = image_rs::io::Reader::with_format(
+ buffered_reader,
+ image_rs::ImageFormat::from_path(path)
+ .map_err(|_| Error::UnsupportedFormat)?,
+ );
+
+ Ok(Self {
+ inner: image_reader
+ .decode()
+ .map_err(|err| Error::DecodeFailed(DecodeError(err)))?,
+ })
+ }
+
+ pub fn from_color(dimens: impl Into<Dimens<u32>>, color: impl Into<Color<u8>>)
+ -> Self
+ {
+ let dimens: Dimens<u32> = dimens.into();
+
+ let color: Color<u8> = color.into();
+
+ Self {
+ inner: image_rs::RgbImage::from_pixel(
+ dimens.width,
+ dimens.height,
+ image_rs::Rgb([color.red, color.green, color.blue]),
+ )
+ .into(),
+ }
+ }
+
+ pub fn dimensions(&self) -> Dimens<u32>
+ {
+ self.inner.dimensions().into()
+ }
+
+ pub fn color_type(&self) -> ColorType
+ {
+ self.inner.color().into()
+ }
+
+ pub fn as_bytes(&self) -> &[u8]
+ {
+ self.inner.as_bytes()
+ }
+}
+
+builder! {
+#[builder(name = SettingsBuilder, derives=(Debug, Clone))]
+#[derive(Debug, Default, Clone)]
+#[non_exhaustive]
+pub struct Settings {
+}
+}
+
+impl Settings
+{
+ pub fn builder() -> SettingsBuilder
+ {
+ SettingsBuilder::default()
+ }
+}
+
+impl Default for SettingsBuilder
+{
+ fn default() -> Self
+ {
+ Settings::default().into()
+ }
+}
+
+/// An enumeration over supported color types and bit depths
+#[derive(Copy, PartialEq, Eq, Debug, Clone, Hash)]
+#[non_exhaustive]
+pub enum ColorType
+{
+ /// Pixel is 8-bit luminance
+ L8,
+
+ /// Pixel is 8-bit luminance with an alpha channel
+ La8,
+
+ /// Pixel contains 8-bit R, G and B channels
+ Rgb8,
+
+ /// Pixel is 8-bit RGB with an alpha channel
+ Rgba8,
+
+ /// Pixel is 16-bit luminance
+ L16,
+
+ /// Pixel is 16-bit luminance with an alpha channel
+ La16,
+
+ /// Pixel is 16-bit RGB
+ Rgb16,
+
+ /// Pixel is 16-bit RGBA
+ Rgba16,
+
+ /// Pixel is 32-bit float RGB
+ Rgb32F,
+
+ /// Pixel is 32-bit float RGBA
+ Rgba32F,
+}
+
+impl From<image_rs::ColorType> for ColorType
+{
+ fn from(color_type: image_rs::ColorType) -> Self
+ {
+ match color_type {
+ image_rs::ColorType::L8 => Self::L8,
+ image_rs::ColorType::La8 => Self::La8,
+ image_rs::ColorType::Rgb8 => Self::Rgb8,
+ image_rs::ColorType::Rgba8 => Self::Rgba8,
+ image_rs::ColorType::L16 => Self::L16,
+ image_rs::ColorType::La16 => Self::La16,
+ image_rs::ColorType::Rgb16 => Self::Rgb16,
+ image_rs::ColorType::Rgba16 => Self::Rgba16,
+ image_rs::ColorType::Rgb32F => Self::Rgb32F,
+ image_rs::ColorType::Rgba32F => Self::Rgba32F,
+ _ => {
+ panic!("Unrecognized image_rs::ColorType variant");
+ }
+ }
+ }
+}
+
+pub fn set_asset_importers(assets: &mut Assets)
+{
+ assets.set_importer::<_, _>(["png", "jpg"], import_asset);
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum Error
+{
+ #[error("Failed to read image file")]
+ ReadFailed(#[source] std::io::Error),
+
+ #[error("Failed to decode image")]
+ DecodeFailed(DecodeError),
+
+ #[error("Unsupported image format")]
+ UnsupportedFormat,
+}
+
+#[derive(Debug, thiserror::Error)]
+#[error(transparent)]
+pub struct DecodeError(image_rs::ImageError);
+
+fn import_asset(
+ asset_submitter: &mut AssetSubmitter<'_>,
+ path: &Path,
+ _settings: Option<&'_ Settings>,
+) -> Result<(), Error>
+{
+ asset_submitter.submit_store::<Image>(Image::open(path)?);
+
+ Ok(())
+}
diff --git a/engine/src/input.rs b/engine/src/input.rs
index 95de048..c53175e 100644
--- a/engine/src/input.rs
+++ b/engine/src/input.rs
@@ -1,10 +1,10 @@
use std::collections::HashMap;
use ecs::extension::Collector as ExtensionCollector;
+use ecs::pair::{ChildOf, Pair};
use ecs::phase::{Phase, PRE_UPDATE as PRE_UPDATE_PHASE, START as START_PHASE};
-use ecs::relationship::{ChildOf, Relationship};
use ecs::sole::Single;
-use ecs::{static_entity, Sole};
+use ecs::{declare_entity, Sole};
use crate::vector::Vec2;
use crate::window::{Window, UPDATE_PHASE as WINDOW_UPDATE_PHASE};
@@ -16,11 +16,14 @@ mod reexports
pub use reexports::*;
-static_entity!(
+declare_entity!(
SET_PREV_KEY_STATE_PHASE,
(
Phase,
- <Relationship<ChildOf, Phase>>::new(*WINDOW_UPDATE_PHASE)
+ Pair::builder()
+ .relation::<ChildOf>()
+ .target_id(*WINDOW_UPDATE_PHASE)
+ .build()
)
);
@@ -152,6 +155,8 @@ impl ecs::extension::Extension for Extension
{
fn collect(self, mut collector: ExtensionCollector<'_>)
{
+ collector.add_declared_entity(&SET_PREV_KEY_STATE_PHASE);
+
collector.add_system(*START_PHASE, initialize);
collector.add_system(*PRE_UPDATE_PHASE, maybe_clear_cursor_is_first_move);
collector.add_system(*SET_PREV_KEY_STATE_PHASE, set_pending_key_states);
diff --git a/engine/src/lib.rs b/engine/src/lib.rs
index a9a5a97..a18cebb 100644
--- a/engine/src/lib.rs
+++ b/engine/src/lib.rs
@@ -1,35 +1,41 @@
#![deny(clippy::all, clippy::pedantic)]
#![allow(clippy::needless_pass_by_value)]
-use ecs::component::{Component, Sequence as ComponentSequence};
+use ecs::component::Sequence as ComponentSequence;
use ecs::extension::Extension;
use ecs::phase::PRE_UPDATE as PRE_UPDATE_PHASE;
use ecs::sole::Sole;
+use ecs::system::initializable::Initializable;
+use ecs::system::observer::Observer;
use ecs::system::{Into, System};
use ecs::uid::Uid;
use ecs::{SoleAlreadyExistsError, World};
+use crate::asset::{Assets, Extension as AssetExtension};
use crate::delta_time::{update as update_delta_time, DeltaTime, LastUpdate};
mod opengl;
mod util;
+mod work_queue;
+pub mod asset;
pub mod camera;
pub mod collision;
pub mod data_types;
pub mod delta_time;
pub mod draw_flags;
pub mod file_format;
+pub mod image;
pub mod input;
pub mod lighting;
pub mod material;
pub mod math;
pub mod mesh;
+pub mod model;
pub mod projection;
pub mod renderer;
pub mod texture;
pub mod transform;
-pub mod vertex;
pub mod window;
pub extern crate ecs;
@@ -37,6 +43,8 @@ pub extern crate ecs;
pub(crate) use crate::data_types::matrix;
pub use crate::data_types::{color, vector};
+const INITIAL_ASSET_CAPACITY: usize = 128;
+
#[derive(Debug)]
pub struct Engine
{
@@ -60,6 +68,13 @@ impl Engine
.initialize((LastUpdate::default(),)),
);
+ let mut assets = Assets::with_capacity(INITIAL_ASSET_CAPACITY);
+
+ crate::model::set_asset_importers(&mut assets);
+ crate::image::set_asset_importers(&mut assets);
+
+ world.add_extension(AssetExtension { assets });
+
Self { world }
}
@@ -79,14 +94,12 @@ impl Engine
self.world.register_system(phase_euid, system);
}
- pub fn register_observer_system<'this, SystemImpl, Event>(
+ pub fn register_observer<'this, SystemImpl>(
&'this mut self,
- system: impl System<'this, SystemImpl>,
- event: Event,
- ) where
- Event: Component,
+ observer: impl Observer<'this, SystemImpl>,
+ )
{
- self.world.register_observer_system(system, event);
+ self.world.register_observer(observer);
}
/// Adds a globally shared singleton value.
@@ -104,7 +117,7 @@ impl Engine
}
/// Runs the event loop.
- pub fn start(&self)
+ pub fn start(&mut self)
{
self.world.start_loop();
}
diff --git a/engine/src/lighting.rs b/engine/src/lighting.rs
index 48adb0e..9ab2ca8 100644
--- a/engine/src/lighting.rs
+++ b/engine/src/lighting.rs
@@ -1,8 +1,8 @@
use ecs::{Component, Sole};
+use crate::builder;
use crate::color::Color;
use crate::data_types::vector::Vec3;
-use crate::util::builder;
builder! {
#[builder(name = PointLightBuilder, derives = (Debug, Clone))]
@@ -10,7 +10,8 @@ builder! {
#[non_exhaustive]
pub struct PointLight
{
- pub position: Vec3<f32>,
+ /// Position in local space.
+ pub local_position: Vec3<f32>,
pub diffuse: Color<f32>,
pub specular: Color<f32>,
pub attenuation_params: AttenuationParams,
@@ -31,7 +32,7 @@ impl Default for PointLight
fn default() -> Self
{
Self {
- position: Vec3::default(),
+ local_position: Vec3::default(),
diffuse: Color { red: 0.5, green: 0.5, blue: 0.5 },
specular: Color { red: 1.0, green: 1.0, blue: 1.0 },
attenuation_params: AttenuationParams::default(),
@@ -58,7 +59,6 @@ pub struct AttenuationParams
impl Default for AttenuationParams
{
- #[must_use]
fn default() -> Self
{
Self {
diff --git a/engine/src/material.rs b/engine/src/material.rs
index e368519..56ff15f 100644
--- a/engine/src/material.rs
+++ b/engine/src/material.rs
@@ -1,21 +1,19 @@
use ecs::Component;
use crate::color::Color;
-use crate::data_types::dimens::Dimens;
-use crate::texture::{Id as TextureId, Texture};
-use crate::util::builder;
+use crate::texture::Texture;
+use crate::builder;
-#[derive(Debug, Clone, Component)]
+#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Material
{
pub ambient: Color<f32>,
pub diffuse: Color<f32>,
pub specular: Color<f32>,
- pub ambient_map: TextureId,
- pub diffuse_map: TextureId,
- pub specular_map: TextureId,
- pub textures: Vec<Texture>,
+ pub ambient_map: Option<Texture>,
+ pub diffuse_map: Option<Texture>,
+ pub specular_map: Option<Texture>,
pub shininess: f32,
}
@@ -27,17 +25,24 @@ impl Material
}
}
+impl Default for Material
+{
+ fn default() -> Self
+ {
+ Self::builder().build()
+ }
+}
+
/// [`Material`] builder.
#[derive(Debug, Clone)]
pub struct Builder
{
- ambient: Option<Color<f32>>,
- diffuse: Option<Color<f32>>,
- specular: Option<Color<f32>>,
- ambient_map: Option<TextureId>,
- diffuse_map: Option<TextureId>,
- specular_map: Option<TextureId>,
- textures: Vec<Texture>,
+ ambient: Color<f32>,
+ diffuse: Color<f32>,
+ specular: Color<f32>,
+ ambient_map: Option<Texture>,
+ diffuse_map: Option<Texture>,
+ specular_map: Option<Texture>,
shininess: f32,
}
@@ -47,13 +52,12 @@ impl Builder
pub fn new() -> Self
{
Self {
- ambient: None,
- diffuse: None,
- specular: None,
+ ambient: Color::WHITE_F32,
+ diffuse: Color::WHITE_F32,
+ specular: Color::WHITE_F32,
ambient_map: None,
diffuse_map: None,
specular_map: None,
- textures: Vec::new(),
shininess: 32.0,
}
}
@@ -61,7 +65,7 @@ impl Builder
#[must_use]
pub fn ambient(mut self, ambient: Color<f32>) -> Self
{
- self.ambient = Some(ambient);
+ self.ambient = ambient;
self
}
@@ -69,7 +73,7 @@ impl Builder
#[must_use]
pub fn diffuse(mut self, diffuse: Color<f32>) -> Self
{
- self.diffuse = Some(diffuse);
+ self.diffuse = diffuse;
self
}
@@ -77,13 +81,13 @@ impl Builder
#[must_use]
pub fn specular(mut self, specular: Color<f32>) -> Self
{
- self.specular = Some(specular);
+ self.specular = specular;
self
}
#[must_use]
- pub fn ambient_map(mut self, ambient_map: TextureId) -> Self
+ pub fn ambient_map(mut self, ambient_map: Texture) -> Self
{
self.ambient_map = Some(ambient_map);
@@ -91,7 +95,7 @@ impl Builder
}
#[must_use]
- pub fn diffuse_map(mut self, diffuse_map: TextureId) -> Self
+ pub fn diffuse_map(mut self, diffuse_map: Texture) -> Self
{
self.diffuse_map = Some(diffuse_map);
@@ -99,7 +103,7 @@ impl Builder
}
#[must_use]
- pub fn specular_map(mut self, specular_map: TextureId) -> Self
+ pub fn specular_map(mut self, specular_map: Texture) -> Self
{
self.specular_map = Some(specular_map);
@@ -107,22 +111,6 @@ impl Builder
}
#[must_use]
- pub fn textures(mut self, textures: impl IntoIterator<Item = Texture>) -> Self
- {
- self.textures = textures.into_iter().collect();
-
- self
- }
-
- #[must_use]
- pub fn texture(mut self, texture: Texture) -> Self
- {
- self.textures.push(texture);
-
- self
- }
-
- #[must_use]
pub fn shininess(mut self, shininess: f32) -> Self
{
self.shininess = shininess;
@@ -135,43 +123,15 @@ impl Builder
/// # Panics
/// Will panic if no ambient map, diffuse map or specular map is set.
#[must_use]
- pub fn build(mut self) -> Material
+ pub fn build(self) -> Material
{
- let ambient_map = self.ambient_map.unwrap_or_else(|| {
- let texture = create_1x1_white_texture();
- let texture_id = texture.id();
-
- self.textures.push(texture);
-
- texture_id
- });
-
- let diffuse_map = self.diffuse_map.unwrap_or_else(|| {
- let texture = create_1x1_white_texture();
- let texture_id = texture.id();
-
- self.textures.push(texture);
-
- texture_id
- });
-
- let specular_map = self.specular_map.unwrap_or_else(|| {
- let texture = create_1x1_white_texture();
- let texture_id = texture.id();
-
- self.textures.push(texture);
-
- texture_id
- });
-
Material {
- ambient: self.ambient.unwrap_or(Color::WHITE_F32),
- diffuse: self.diffuse.unwrap_or(Color::WHITE_F32),
- specular: self.specular.unwrap_or(Color::WHITE_F32),
- ambient_map,
- diffuse_map,
- specular_map,
- textures: self.textures,
+ ambient: self.ambient,
+ diffuse: self.diffuse,
+ specular: self.specular,
+ ambient_map: self.ambient_map,
+ diffuse_map: self.diffuse_map,
+ specular_map: self.specular_map,
shininess: self.shininess,
}
}
@@ -206,8 +166,3 @@ impl Flags
FlagsBuilder::default()
}
}
-
-fn create_1x1_white_texture() -> Texture
-{
- Texture::new_from_color(&Dimens { width: 1, height: 1 }, &Color::WHITE_U8)
-}
diff --git a/engine/src/mesh.rs b/engine/src/mesh.rs
index 917e7f7..fb977af 100644
--- a/engine/src/mesh.rs
+++ b/engine/src/mesh.rs
@@ -1,11 +1,9 @@
-use ecs::Component;
-
-use crate::vector::Vec3;
-use crate::vertex::Vertex;
+use crate::builder;
+use crate::vector::{Vec2, Vec3};
pub mod cube;
-#[derive(Debug, Clone, Component)]
+#[derive(Debug, Clone, Default)]
pub struct Mesh
{
vertices: Vec<Vertex>,
@@ -77,6 +75,27 @@ impl Mesh
}
}
+builder! {
+#[builder(name = VertexBuilder, derives = (Debug, Default, Clone))]
+#[derive(Debug, Clone, Default, PartialEq)]
+#[non_exhaustive]
+pub struct Vertex
+{
+ pub pos: Vec3<f32>,
+ pub texture_coords: Vec2<f32>,
+ pub normal: Vec3<f32>,
+}
+}
+
+impl Vertex
+{
+ #[must_use]
+ pub fn builder() -> VertexBuilder
+ {
+ VertexBuilder::default()
+ }
+}
+
#[derive(Debug, Clone)]
pub struct DirectionPositions<'mesh>
{
diff --git a/engine/src/mesh/cube.rs b/engine/src/mesh/cube.rs
index c29ce0b..e91cf0e 100644
--- a/engine/src/mesh/cube.rs
+++ b/engine/src/mesh/cube.rs
@@ -1,8 +1,8 @@
+use crate::data_types::dimens::Dimens3;
use crate::math::calc_triangle_surface_normal;
-use crate::mesh::Mesh;
-use crate::util::builder;
+use crate::mesh::{Mesh, Vertex};
+use crate::builder;
use crate::vector::{Vec2, Vec3};
-use crate::vertex::{Builder as VertexBuilder, Vertex};
builder! {
/// Cube mesh creation specification.
@@ -27,6 +27,18 @@ impl CreationSpec
}
}
+impl CreationSpecBuilder
+{
+ pub fn dimens(mut self, dimens: Dimens3<f32>) -> Self
+ {
+ self.width = dimens.width;
+ self.height = dimens.height;
+ self.depth = dimens.depth;
+
+ self
+ }
+}
+
/// Describes a single side of a cube (obviously).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Side
@@ -192,7 +204,7 @@ impl FaceVertices
.expect("Vertex normal index is out of bounds")
.clone();
- VertexBuilder::default()
+ Vertex::builder()
.pos(vertex_pos)
.normal(vertex_normal)
.build()
diff --git a/engine/src/model.rs b/engine/src/model.rs
new file mode 100644
index 0000000..9f5840c
--- /dev/null
+++ b/engine/src/model.rs
@@ -0,0 +1,176 @@
+use std::borrow::Cow;
+use std::collections::HashMap;
+use std::fs::read_to_string;
+use std::path::Path;
+
+use ecs::Component;
+
+use crate::asset::{Assets, Handle as AssetHandle, Submitter as AssetSubmitter};
+use crate::material::Material;
+use crate::mesh::Mesh;
+use crate::texture::Texture;
+
+#[derive(Debug, Clone, Component)]
+#[non_exhaustive]
+pub struct Model
+{
+ pub asset_handle: AssetHandle<Data>,
+}
+
+impl Model
+{
+ pub fn new(asset_handle: AssetHandle<Data>) -> Self
+ {
+ Self { asset_handle }
+ }
+}
+
+#[derive(Debug, Default, Clone)]
+#[non_exhaustive]
+pub struct Data
+{
+ pub mesh: Mesh,
+ pub materials: HashMap<String, Material>,
+}
+
+impl Data
+{
+ pub fn builder() -> DataBuilder
+ {
+ DataBuilder::default()
+ }
+}
+
+#[derive(Debug, Default, Clone)]
+pub struct DataBuilder
+{
+ mesh: Mesh,
+ materials: HashMap<String, Material>,
+}
+
+impl DataBuilder
+{
+ pub fn mesh(mut self, mesh: Mesh) -> Self
+ {
+ self.mesh = mesh;
+
+ self
+ }
+
+ pub fn material<'name>(
+ mut self,
+ name: impl Into<Cow<'name, str>>,
+ material: Material,
+ ) -> Self
+ {
+ self.materials.insert(name.into().into_owned(), material);
+
+ self
+ }
+
+ pub fn build(self) -> Data
+ {
+ Data {
+ mesh: self.mesh,
+ materials: self.materials,
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct Settings {}
+
+#[derive(Debug, thiserror::Error)]
+enum Error
+{
+ #[error("Failed to read model file")]
+ ReadModelFileFailed(#[source] std::io::Error),
+
+ #[error("Failed to read material file")]
+ ReadMaterialFileFailed(#[source] std::io::Error),
+
+ #[error("Failed to parse model file")]
+ ParsingFailed(#[from] ParsingError),
+}
+
+pub fn set_asset_importers(assets: &mut Assets)
+{
+ assets.set_importer(["obj"], import_wavefront_obj_asset);
+}
+
+#[derive(Debug, thiserror::Error)]
+enum ParsingError
+{
+ #[error(transparent)]
+ Obj(#[from] crate::file_format::wavefront::obj::Error),
+
+ #[error(transparent)]
+ Mtl(#[from] crate::file_format::wavefront::mtl::Error),
+}
+
+fn import_wavefront_obj_asset(
+ asset_submitter: &mut AssetSubmitter<'_>,
+ path: &Path,
+ _settings: Option<&'_ Settings>,
+) -> Result<(), Error>
+{
+ let obj = crate::file_format::wavefront::obj::parse(
+ &read_to_string(path).map_err(Error::ReadModelFileFailed)?,
+ )
+ .map_err(|err| Error::ParsingFailed(ParsingError::Obj(err)))?;
+
+ let mesh = obj
+ .to_mesh()
+ .map_err(|err| Error::ParsingFailed(ParsingError::Obj(err)))?;
+
+ let mut materials =
+ HashMap::<String, Material>::with_capacity(obj.mtl_libs.iter().flatten().count());
+
+ for mtl_lib_path in obj.mtl_libs.iter().flatten() {
+ materials.extend(import_mtl(asset_submitter, &mtl_lib_path)?);
+ }
+
+ asset_submitter.submit_store(Data { mesh, materials });
+
+ Ok(())
+}
+
+fn import_mtl<'a>(
+ asset_submitter: &'a AssetSubmitter<'_>,
+ path: &Path,
+) -> Result<impl Iterator<Item = (String, Material)> + 'a, Error>
+{
+ let named_materials = crate::file_format::wavefront::mtl::parse(
+ &read_to_string(path).map_err(Error::ReadMaterialFileFailed)?,
+ )
+ .map_err(|err| Error::ParsingFailed(ParsingError::Mtl(err)))?;
+
+ Ok(named_materials.into_iter().map(|named_material| {
+ let mut material_builder = Material::builder()
+ .ambient(named_material.ambient)
+ .diffuse(named_material.diffuse)
+ .specular(named_material.specular)
+ .shininess(named_material.shininess);
+
+ if let Some(ambient_map) = named_material.ambient_map {
+ material_builder = material_builder.ambient_map(Texture::new(
+ asset_submitter.submit_load_other(ambient_map.path.as_path()),
+ ));
+ }
+
+ if let Some(diffuse_map) = named_material.diffuse_map {
+ material_builder = material_builder.diffuse_map(Texture::new(
+ asset_submitter.submit_load_other(diffuse_map.path.as_path()),
+ ));
+ }
+
+ if let Some(specular_map) = named_material.specular_map {
+ material_builder = material_builder.specular_map(Texture::new(
+ asset_submitter.submit_load_other(specular_map.path.as_path()),
+ ));
+ }
+
+ (named_material.name, material_builder.build())
+ }))
+}
diff --git a/engine/src/opengl/buffer.rs b/engine/src/opengl/buffer.rs
index 68a75fb..eded553 100644
--- a/engine/src/opengl/buffer.rs
+++ b/engine/src/opengl/buffer.rs
@@ -1,5 +1,6 @@
use std::marker::PhantomData;
use std::mem::size_of_val;
+use std::ptr::null;
#[derive(Debug)]
pub struct Buffer<Item>
@@ -35,19 +36,40 @@ impl<Item> Buffer<Item>
}
}
- pub fn object(&self) -> gl::types::GLuint
+ pub fn store_mapped<Value>(
+ &mut self,
+ values: &[Value],
+ usage: Usage,
+ mut map_func: impl FnMut(&Value) -> Item,
+ )
{
- self.buf
+ unsafe {
+ #[allow(clippy::cast_possible_wrap)]
+ gl::NamedBufferData(
+ self.buf,
+ (size_of::<Item>() * values.len()) as gl::types::GLsizeiptr,
+ null(),
+ usage.into_gl(),
+ );
+ }
+
+ for (index, value) in values.iter().enumerate() {
+ let item = map_func(value);
+
+ unsafe {
+ gl::NamedBufferSubData(
+ self.buf,
+ (index * size_of::<Item>()) as gl::types::GLintptr,
+ size_of::<Item>() as gl::types::GLsizeiptr,
+ (&raw const item).cast(),
+ );
+ }
+ }
}
-}
-impl<Item> Drop for Buffer<Item>
-{
- fn drop(&mut self)
+ pub fn object(&self) -> gl::types::GLuint
{
- unsafe {
- gl::DeleteBuffers(1, &self.buf);
- }
+ self.buf
}
}
diff --git a/engine/src/opengl/shader.rs b/engine/src/opengl/shader.rs
index 36dc1a4..a626fc7 100644
--- a/engine/src/opengl/shader.rs
+++ b/engine/src/opengl/shader.rs
@@ -159,82 +159,105 @@ impl Program
}
}
- pub fn set_uniform_matrix_4fv(&mut self, name: &CStr, matrix: &Matrix<f32, 4, 4>)
+ pub fn set_uniform(&mut self, name: &CStr, var: &impl UniformVariable)
{
- let uniform_location =
- unsafe { gl::GetUniformLocation(self.program, name.as_ptr().cast()) };
+ let location = UniformLocation(unsafe {
+ gl::GetUniformLocation(self.program, name.as_ptr().cast())
+ });
+
+ var.set(self, location);
+ }
+
+ fn get_info_log(&self) -> String
+ {
+ let mut buf = vec![gl::types::GLchar::default(); 512];
unsafe {
- gl::ProgramUniformMatrix4fv(
+ #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
+ gl::GetProgramInfoLog(
self.program,
- uniform_location,
- 1,
- gl::FALSE,
- matrix.as_ptr(),
+ buf.len() as gl::types::GLsizei,
+ null_mut(),
+ buf.as_mut_ptr(),
);
}
+
+ let info_log = unsafe { CStr::from_ptr(buf.as_ptr()) };
+
+ unsafe { String::from_utf8_unchecked(info_log.to_bytes().to_vec()) }
}
+}
- pub fn set_uniform_vec_3fv(&mut self, name: &CStr, vec: &Vec3<f32>)
+impl Drop for Program
+{
+ fn drop(&mut self)
{
- let uniform_location =
- unsafe { gl::GetUniformLocation(self.program, name.as_ptr().cast()) };
-
unsafe {
- gl::ProgramUniform3fv(self.program, uniform_location, 1, vec.as_ptr());
+ gl::DeleteProgram(self.program);
}
}
+}
- pub fn set_uniform_1fv(&mut self, name: &CStr, num: f32)
- {
- let uniform_location =
- unsafe { gl::GetUniformLocation(self.program, name.as_ptr().cast()) };
+pub trait UniformVariable
+{
+ fn set(&self, program: &mut Program, uniform_location: UniformLocation);
+}
+impl UniformVariable for f32
+{
+ fn set(&self, program: &mut Program, uniform_location: UniformLocation)
+ {
unsafe {
- gl::ProgramUniform1fv(self.program, uniform_location, 1, &num);
+ gl::ProgramUniform1f(program.program, uniform_location.0, *self);
}
}
+}
- pub fn set_uniform_1i(&mut self, name: &CStr, num: i32)
+impl UniformVariable for i32
+{
+ fn set(&self, program: &mut Program, uniform_location: UniformLocation)
{
- let uniform_location =
- unsafe { gl::GetUniformLocation(self.program, name.as_ptr().cast()) };
-
unsafe {
- gl::ProgramUniform1i(self.program, uniform_location, num);
+ gl::ProgramUniform1i(program.program, uniform_location.0, *self);
}
}
+}
- fn get_info_log(&self) -> String
+impl UniformVariable for Vec3<f32>
+{
+ fn set(&self, program: &mut Program, uniform_location: UniformLocation)
{
- let mut buf = vec![gl::types::GLchar::default(); 512];
-
unsafe {
- #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
- gl::GetProgramInfoLog(
- self.program,
- buf.len() as gl::types::GLsizei,
- null_mut(),
- buf.as_mut_ptr(),
+ gl::ProgramUniform3f(
+ program.program,
+ uniform_location.0,
+ self.x,
+ self.y,
+ self.z,
);
}
-
- let info_log = unsafe { CStr::from_ptr(buf.as_ptr()) };
-
- unsafe { String::from_utf8_unchecked(info_log.to_bytes().to_vec()) }
}
}
-impl Drop for Program
+impl UniformVariable for Matrix<f32, 4, 4>
{
- fn drop(&mut self)
+ fn set(&self, program: &mut Program, uniform_location: UniformLocation)
{
unsafe {
- gl::DeleteProgram(self.program);
+ gl::ProgramUniformMatrix4fv(
+ program.program,
+ uniform_location.0,
+ 1,
+ gl::FALSE,
+ self.as_ptr(),
+ );
}
}
}
+#[derive(Debug)]
+pub struct UniformLocation(gl::types::GLint);
+
/// Shader error.
#[derive(Debug, thiserror::Error)]
pub enum Error
diff --git a/engine/src/opengl/texture.rs b/engine/src/opengl/texture.rs
index 52c8554..80a5f37 100644
--- a/engine/src/opengl/texture.rs
+++ b/engine/src/opengl/texture.rs
@@ -1,5 +1,4 @@
use crate::data_types::dimens::Dimens;
-use crate::texture::Properties;
#[derive(Debug)]
pub struct Texture
@@ -20,10 +19,10 @@ impl Texture
Self { texture }
}
- pub fn bind(&self)
+ pub fn bind_to_texture_unit(&self, texture_unit: u32)
{
unsafe {
- gl::BindTexture(gl::TEXTURE_2D, self.texture);
+ gl::BindTextureUnit(texture_unit, self.texture);
}
}
@@ -41,16 +40,9 @@ impl Texture
}
}
- pub fn apply_properties(&mut self, properties: &Properties)
- {
- self.set_wrap(properties.wrap);
- self.set_magnifying_filter(properties.magnifying_filter);
- self.set_minifying_filter(properties.minifying_filter);
- }
-
pub fn set_wrap(&mut self, wrapping: Wrapping)
{
- let wrapping_gl = wrapping.to_gl();
+ let wrapping_gl = wrapping as gl::types::GLenum;
#[allow(clippy::cast_possible_wrap)]
unsafe {
@@ -61,7 +53,7 @@ impl Texture
pub fn set_magnifying_filter(&mut self, filtering: Filtering)
{
- let filtering_gl = filtering.to_gl();
+ let filtering_gl = filtering as gl::types::GLenum;
#[allow(clippy::cast_possible_wrap)]
unsafe {
@@ -75,7 +67,7 @@ impl Texture
pub fn set_minifying_filter(&mut self, filtering: Filtering)
{
- let filtering_gl = filtering.to_gl();
+ let filtering_gl = filtering as gl::types::GLenum;
#[allow(clippy::cast_possible_wrap)]
unsafe {
@@ -132,43 +124,21 @@ impl Drop for Texture
/// Texture wrapping.
#[derive(Debug, Clone, Copy)]
+#[repr(u32)]
pub enum Wrapping
{
- Repeat,
- MirroredRepeat,
- ClampToEdge,
- ClampToBorder,
-}
-
-impl Wrapping
-{
- fn to_gl(self) -> gl::types::GLenum
- {
- match self {
- Self::Repeat => gl::REPEAT,
- Self::MirroredRepeat => gl::MIRRORED_REPEAT,
- Self::ClampToEdge => gl::CLAMP_TO_EDGE,
- Self::ClampToBorder => gl::CLAMP_TO_BORDER,
- }
- }
+ Repeat = gl::REPEAT,
+ MirroredRepeat = gl::MIRRORED_REPEAT,
+ ClampToEdge = gl::CLAMP_TO_EDGE,
+ ClampToBorder = gl::CLAMP_TO_BORDER,
}
#[derive(Debug, Clone, Copy)]
+#[repr(u32)]
pub enum Filtering
{
- Nearest,
- Linear,
-}
-
-impl Filtering
-{
- fn to_gl(self) -> gl::types::GLenum
- {
- match self {
- Self::Linear => gl::LINEAR,
- Self::Nearest => gl::NEAREST,
- }
- }
+ Nearest = gl::NEAREST,
+ Linear = gl::LINEAR,
}
/// Texture pixel data format.
@@ -197,44 +167,3 @@ impl PixelDataFormat
}
}
}
-
-pub fn set_active_texture_unit(texture_unit: TextureUnit)
-{
- unsafe {
- gl::ActiveTexture(texture_unit.into_gl());
- }
-}
-
-macro_rules! texture_unit_enum {
- (cnt=$cnt: literal) => {
- seq_macro::seq!(N in 0..$cnt {
- #[derive(Debug, Clone, Copy)]
- pub enum TextureUnit {
- #(
- No~N,
- )*
- }
-
- impl TextureUnit {
- fn into_gl(self) -> gl::types::GLenum {
- match self {
- #(
- Self::No~N => gl::TEXTURE~N,
- )*
- }
- }
-
- pub fn from_num(num: usize) -> Option<Self> {
- match num {
- #(
- N => Some(Self::No~N),
- )*
- _ => None
- }
- }
- }
- });
- };
-}
-
-texture_unit_enum!(cnt = 31);
diff --git a/engine/src/opengl/vertex_array.rs b/engine/src/opengl/vertex_array.rs
index e1e1a15..1f8a870 100644
--- a/engine/src/opengl/vertex_array.rs
+++ b/engine/src/opengl/vertex_array.rs
@@ -1,10 +1,6 @@
use std::mem::size_of;
use crate::opengl::buffer::Buffer;
-use crate::vertex::Vertex;
-
-#[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
-const VERTEX_STRIDE: i32 = size_of::<Vertex>() as i32;
#[derive(Debug)]
pub struct VertexArray
@@ -59,10 +55,10 @@ impl VertexArray
}
}
- pub fn bind_vertex_buffer(
+ pub fn bind_vertex_buffer<VertexT>(
&mut self,
binding_index: u32,
- vertex_buffer: &Buffer<Vertex>,
+ vertex_buffer: &Buffer<VertexT>,
offset: isize,
)
{
@@ -72,7 +68,7 @@ impl VertexArray
binding_index,
vertex_buffer.object(),
offset,
- VERTEX_STRIDE,
+ size_of::<VertexT>() as i32,
);
}
}
@@ -127,16 +123,6 @@ impl VertexArray
}
}
-impl Drop for VertexArray
-{
- fn drop(&mut self)
- {
- unsafe {
- gl::DeleteVertexArrays(1, &self.array);
- }
- }
-}
-
#[derive(Debug)]
pub enum PrimitiveKind
{
diff --git a/engine/src/projection.rs b/engine/src/projection.rs
index faa741f..115ca39 100644
--- a/engine/src/projection.rs
+++ b/engine/src/projection.rs
@@ -1,6 +1,6 @@
use crate::data_types::dimens::Dimens3;
use crate::matrix::Matrix;
-use crate::util::builder;
+use crate::builder;
use crate::vector::Vec3;
#[derive(Debug)]
diff --git a/engine/src/renderer.rs b/engine/src/renderer.rs
index 2544919..fcc96cc 100644
--- a/engine/src/renderer.rs
+++ b/engine/src/renderer.rs
@@ -1 +1,16 @@
+use ecs::declare_entity;
+use ecs::pair::{ChildOf, Pair};
+use ecs::phase::{Phase, UPDATE as UPDATE_PHASE};
+
pub mod opengl;
+
+declare_entity!(
+ pub RENDER_PHASE,
+ (
+ Phase,
+ Pair::builder()
+ .relation::<ChildOf>()
+ .target_id(*UPDATE_PHASE)
+ .build()
+ )
+);
diff --git a/engine/src/renderer/opengl.rs b/engine/src/renderer/opengl.rs
index 5665860..b48bac5 100644
--- a/engine/src/renderer/opengl.rs
+++ b/engine/src/renderer/opengl.rs
@@ -3,26 +3,30 @@
use std::collections::HashMap;
use std::ffi::{c_void, CString};
use std::io::{Error as IoError, ErrorKind as IoErrorKind};
-use std::ops::Deref;
use std::path::Path;
use std::process::abort;
use ecs::actions::Actions;
use ecs::component::local::Local;
-use ecs::phase::{PRESENT as PRESENT_PHASE, START as START_PHASE};
+use ecs::component::Handle as ComponentHandle;
+use ecs::phase::START as START_PHASE;
use ecs::query::term::Without;
use ecs::sole::Single;
-use ecs::system::{Into as _, System};
+use ecs::system::initializable::Initializable;
+use ecs::system::Into as _;
use ecs::{Component, Query};
+use crate::asset::{Assets, Id as AssetId};
use crate::camera::{Active as ActiveCamera, Camera};
use crate::color::Color;
use crate::data_types::dimens::Dimens;
use crate::draw_flags::{DrawFlags, NoDraw, PolygonModeConfig};
+use crate::image::{ColorType as ImageColorType, Image};
use crate::lighting::{DirectionalLight, GlobalLight, PointLight};
use crate::material::{Flags as MaterialFlags, Material};
use crate::matrix::Matrix;
use crate::mesh::Mesh;
+use crate::model::Model;
use crate::opengl::buffer::{Buffer, Usage as BufferUsage};
use crate::opengl::debug::{
enable_debug_output,
@@ -44,9 +48,10 @@ use crate::opengl::shader::{
Shader as GlShader,
};
use crate::opengl::texture::{
- set_active_texture_unit,
+ Filtering as GlTextureFiltering,
+ PixelDataFormat as GlTexturePixelDataFormat,
Texture as GlTexture,
- TextureUnit,
+ Wrapping as GlTextureWrapping,
};
use crate::opengl::vertex_array::{
DataType as VertexArrayDataType,
@@ -62,21 +67,31 @@ use crate::opengl::{
ContextFlags,
};
use crate::projection::{ClipVolume, Projection};
-use crate::texture::{Id as TextureId, Texture};
-use crate::transform::{Position, Scale};
+use crate::renderer::opengl::vertex::{AttributeComponentType, Vertex};
+use crate::renderer::RENDER_PHASE;
+use crate::texture::{
+ Filtering as TextureFiltering,
+ Properties as TextureProperties,
+ Wrapping as TextureWrapping,
+};
+use crate::transform::{Scale, WorldPosition};
use crate::util::{defer, Defer, RefOrValue};
use crate::vector::{Vec2, Vec3};
-use crate::vertex::{AttributeComponentType, Vertex};
use crate::window::Window;
+mod vertex;
+
+const AMBIENT_MAP_TEXTURE_UNIT: u32 = 0;
+const DIFFUSE_MAP_TEXTURE_UNIT: u32 = 1;
+const SPECULAR_MAP_TEXTURE_UNIT: u32 = 2;
+
type RenderableEntity<'a> = (
- &'a Mesh,
- &'a Material,
- &'a Option<MaterialFlags>,
- &'a Option<Position>,
- &'a Option<Scale>,
- &'a Option<DrawFlags>,
- &'a Option<GlObjects>,
+ &'a Model,
+ Option<&'a MaterialFlags>,
+ Option<&'a WorldPosition>,
+ Option<&'a Scale>,
+ Option<&'a DrawFlags>,
+ Option<&'a GlObjects>,
);
#[derive(Debug, Default)]
@@ -87,10 +102,12 @@ impl ecs::extension::Extension for Extension
{
fn collect(self, mut collector: ecs::extension::Collector<'_>)
{
+ collector.add_declared_entity(&RENDER_PHASE);
+
collector.add_system(*START_PHASE, initialize);
collector.add_system(
- *PRESENT_PHASE,
+ *RENDER_PHASE,
render
.into_system()
.initialize((GlobalGlObjects::default(),)),
@@ -131,33 +148,31 @@ fn initialize(window: Single<Window>)
enable(Capability::MultiSample);
}
+#[tracing::instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
fn render(
query: Query<RenderableEntity<'_>, (Without<NoDraw>,)>,
- point_light_query: Query<(&PointLight,)>,
+ point_light_query: Query<(&PointLight, &WorldPosition)>,
directional_lights: Query<(&DirectionalLight,)>,
- camera_query: Query<(&Camera, &Position, &ActiveCamera)>,
+ camera_query: Query<(&Camera, &WorldPosition, &ActiveCamera)>,
window: Single<Window>,
global_light: Single<GlobalLight>,
+ assets: Single<Assets>,
mut gl_objects: Local<GlobalGlObjects>,
mut actions: Actions,
)
{
- let Some((camera, camera_pos, _)) = camera_query.iter().next() else {
+ let Some((camera, camera_world_pos, _)) = camera_query.iter().next() else {
tracing::warn!("No current camera. Nothing will be rendered");
return;
};
- let point_lights = point_light_query
- .iter()
- .map(|(point_light,)| point_light)
- .collect::<Vec<_>>();
-
let directional_lights = directional_lights.iter().collect::<Vec<_>>();
let GlobalGlObjects {
shader_program,
textures: gl_textures,
+ default_1x1_texture: default_1x1_gl_texture,
} = &mut *gl_objects;
let shader_program =
@@ -165,18 +180,23 @@ fn render(
clear_buffers(BufferClearMask::COLOR | BufferClearMask::DEPTH);
- for (
+ 'subject_loop: for (
euid,
- (mesh, material, material_flags, position, scale, draw_flags, gl_objects),
+ (model, material_flags, position, scale, draw_flags, gl_objects),
) in query.iter_with_euids()
{
+ let Some(model_data) = assets.get(&model.asset_handle) else {
+ tracing::trace!("Missing model asset");
+ continue;
+ };
+
let material_flags = material_flags
.map(|material_flags| material_flags.clone())
.unwrap_or_default();
let gl_objs = match gl_objects.as_deref() {
Some(gl_objs) => RefOrValue::Ref(gl_objs),
- None => RefOrValue::Value(Some(GlObjects::new(&mesh))),
+ None => RefOrValue::Value(Some(GlObjects::new(&model_data.mesh))),
};
defer!(|gl_objs| {
@@ -192,34 +212,82 @@ fn render(
},
shader_program,
&camera,
- &camera_pos,
+ &camera_world_pos,
window.size().expect("Failed to get window size"),
);
+ if model_data.materials.len() > 1 {
+ tracing::warn!(concat!(
+ "Multiple model materials are not supported ",
+ "so only the first material will be used"
+ ));
+ }
+
+ let material = match model_data.materials.values().next() {
+ Some(material) => material,
+ None => {
+ tracing::warn!("Model has no materials. Using default material");
+
+ &Material::default()
+ }
+ };
+
apply_light(
&material,
&material_flags,
&global_light,
shader_program,
- point_lights.as_slice(),
+ (point_light_query.iter(), point_light_query.iter().count()),
directional_lights
.iter()
.map(|(dir_light,)| &**dir_light)
.collect::<Vec<_>>()
.as_slice(),
- &camera_pos,
+ &camera_world_pos,
);
- for (index, texture) in material.textures.iter().enumerate() {
- let gl_texture = gl_textures
- .entry(texture.id())
- .or_insert_with(|| create_gl_texture(texture));
+ let material_texture_maps = [
+ (&material.ambient_map, AMBIENT_MAP_TEXTURE_UNIT),
+ (&material.diffuse_map, DIFFUSE_MAP_TEXTURE_UNIT),
+ (&material.specular_map, SPECULAR_MAP_TEXTURE_UNIT),
+ ];
+
+ for (texture, texture_unit) in material_texture_maps {
+ let Some(texture) = texture else {
+ let gl_texture = default_1x1_gl_texture.get_or_insert_with(|| {
+ create_gl_texture(
+ &Image::from_color(1, Color::WHITE_U8),
+ &TextureProperties::default(),
+ )
+ });
+
+ gl_texture.bind_to_texture_unit(texture_unit);
- let texture_unit = TextureUnit::from_num(index).expect("Too many textures");
+ continue;
+ };
- set_active_texture_unit(texture_unit);
+ let texture_image_asset_id = texture.asset_handle.id();
+
+ let gl_texture = match gl_textures.get(&texture_image_asset_id) {
+ Some(gl_texture) => gl_texture,
+ None => {
+ let Some(image) = assets.get::<Image>(&texture.asset_handle) else {
+ tracing::trace!("Missing texture asset");
+ continue 'subject_loop;
+ };
+
+ gl_textures.insert(
+ texture_image_asset_id,
+ create_gl_texture(image, &texture.properties),
+ );
+
+ gl_textures
+ .get(&texture.asset_handle.id())
+ .expect("Not possible")
+ }
+ };
- gl_texture.bind();
+ gl_texture.bind_to_texture_unit(texture_unit);
}
shader_program.activate();
@@ -248,7 +316,8 @@ fn render(
struct GlobalGlObjects
{
shader_program: Option<GlShaderProgram>,
- textures: HashMap<TextureId, GlTexture>,
+ textures: HashMap<AssetId, GlTexture>,
+ default_1x1_texture: Option<GlTexture>,
}
fn set_viewport(position: Vec2<u32>, size: Dimens<u32>)
@@ -275,17 +344,31 @@ fn draw_mesh(gl_objects: &GlObjects)
}
}
-fn create_gl_texture(texture: &Texture) -> GlTexture
+fn create_gl_texture(image: &Image, texture_properties: &TextureProperties) -> GlTexture
{
let mut gl_texture = GlTexture::new();
gl_texture.generate(
- *texture.dimensions(),
- texture.image().as_bytes(),
- texture.pixel_data_format(),
+ image.dimensions(),
+ image.as_bytes(),
+ match image.color_type() {
+ ImageColorType::Rgb8 => GlTexturePixelDataFormat::Rgb8,
+ ImageColorType::Rgba8 => GlTexturePixelDataFormat::Rgba8,
+ _ => {
+ unimplemented!();
+ }
+ },
);
- gl_texture.apply_properties(texture.properties());
+ gl_texture.set_wrap(texture_wrapping_to_gl(texture_properties.wrap));
+
+ gl_texture.set_magnifying_filter(texture_filtering_to_gl(
+ texture_properties.magnifying_filter,
+ ));
+
+ gl_texture.set_minifying_filter(texture_filtering_to_gl(
+ texture_properties.minifying_filter,
+ ));
gl_texture
}
@@ -380,7 +463,13 @@ impl GlObjects
let mut vertex_arr = VertexArray::new();
let mut vertex_buffer = Buffer::new();
- vertex_buffer.store(mesh.vertices(), BufferUsage::Static);
+ vertex_buffer.store_mapped(mesh.vertices(), BufferUsage::Static, |vertex| {
+ Vertex {
+ pos: vertex.pos,
+ texture_coords: vertex.texture_coords,
+ normal: vertex.normal,
+ }
+ });
vertex_arr.bind_vertex_buffer(0, &vertex_buffer, 0);
@@ -438,16 +527,16 @@ fn apply_transformation_matrices(
transformation: Transformation,
gl_shader_program: &mut GlShaderProgram,
camera: &Camera,
- camera_pos: &Position,
+ camera_world_pos: &WorldPosition,
window_size: Dimens<u32>,
)
{
gl_shader_program
- .set_uniform_matrix_4fv(c"model", &create_transformation_matrix(transformation));
+ .set_uniform(c"model", &create_transformation_matrix(transformation));
- let view_matrix = create_view_matrix(camera, &camera_pos.position);
+ let view_matrix = create_view_matrix(camera, &camera_world_pos.position);
- gl_shader_program.set_uniform_matrix_4fv(c"view", &view_matrix);
+ gl_shader_program.set_uniform(c"view", &view_matrix);
#[allow(clippy::cast_precision_loss)]
let proj_matrix = match &camera.projection {
@@ -455,27 +544,33 @@ fn apply_transformation_matrices(
window_size.width as f32 / window_size.height as f32,
ClipVolume::NegOneToOne,
),
- Projection::Orthographic(orthographic_proj) => {
- orthographic_proj.to_matrix_rh(&camera_pos.position, ClipVolume::NegOneToOne)
- }
+ Projection::Orthographic(orthographic_proj) => orthographic_proj
+ .to_matrix_rh(&camera_world_pos.position, ClipVolume::NegOneToOne),
};
- gl_shader_program.set_uniform_matrix_4fv(c"projection", &proj_matrix);
+ gl_shader_program.set_uniform(c"projection", &proj_matrix);
}
-fn apply_light<PointLightHolder>(
+fn apply_light<'point_light>(
material: &Material,
material_flags: &MaterialFlags,
global_light: &GlobalLight,
gl_shader_program: &mut GlShaderProgram,
- point_lights: &[PointLightHolder],
+ (point_light_iter, point_light_cnt): (
+ impl Iterator<
+ Item = (
+ ComponentHandle<'point_light, PointLight>,
+ ComponentHandle<'point_light, WorldPosition>,
+ ),
+ >,
+ usize,
+ ),
directional_lights: &[&DirectionalLight],
- camera_pos: &Position,
-) where
- PointLightHolder: Deref<Target = PointLight>,
+ camera_world_pos: &WorldPosition,
+)
{
debug_assert!(
- point_lights.len() < 64,
+ point_light_cnt < 64,
"Shader cannot handle more than 64 point lights"
);
@@ -485,7 +580,7 @@ fn apply_light<PointLightHolder>(
);
for (dir_light_index, dir_light) in directional_lights.iter().enumerate() {
- gl_shader_program.set_uniform_vec_3fv(
+ gl_shader_program.set_uniform(
&create_light_uniform_name(
"directional_lights",
dir_light_index,
@@ -505,78 +600,68 @@ fn apply_light<PointLightHolder>(
// There probably won't be more than 2147483648 directional lights
#[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
gl_shader_program
- .set_uniform_1i(c"directional_light_cnt", directional_lights.len() as i32);
+ .set_uniform(c"directional_light_cnt", &(directional_lights.len() as i32));
- for (point_light_index, point_light) in point_lights.iter().enumerate() {
- gl_shader_program.set_uniform_vec_3fv(
+ for (point_light_index, (point_light, point_light_world_pos)) in
+ point_light_iter.enumerate()
+ {
+ gl_shader_program.set_uniform(
&create_light_uniform_name("point_lights", point_light_index, "position"),
- &point_light.position,
+ &(point_light_world_pos.position + point_light.local_position),
);
set_light_phong_uniforms(
gl_shader_program,
"point_lights",
point_light_index,
- &**point_light,
+ &*point_light,
);
set_light_attenuation_uniforms(
gl_shader_program,
"point_lights",
point_light_index,
- point_light,
+ &*point_light,
);
}
// There probably won't be more than 2147483648 point lights
#[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
- gl_shader_program.set_uniform_1i(c"point_light_cnt", point_lights.len() as i32);
+ gl_shader_program.set_uniform(c"point_light_cnt", &(point_light_cnt as i32));
- gl_shader_program.set_uniform_vec_3fv(
+ gl_shader_program.set_uniform(
c"material.ambient",
- &if material_flags.use_ambient_color {
+ &Vec3::from(if material_flags.use_ambient_color {
material.ambient.clone()
} else {
global_light.ambient.clone()
- }
- .into(),
+ }),
);
gl_shader_program
- .set_uniform_vec_3fv(c"material.diffuse", &material.diffuse.clone().into());
+ .set_uniform(c"material.diffuse", &Vec3::from(material.diffuse.clone()));
#[allow(clippy::cast_possible_wrap)]
gl_shader_program
- .set_uniform_vec_3fv(c"material.specular", &material.specular.clone().into());
-
- let texture_map = material
- .textures
- .iter()
- .enumerate()
- .map(|(index, texture)| (texture.id(), index))
- .collect::<HashMap<_, _>>();
+ .set_uniform(c"material.specular", &Vec3::from(material.specular.clone()));
#[allow(clippy::cast_possible_wrap)]
- gl_shader_program.set_uniform_1i(
- c"material.ambient_map",
- *texture_map.get(&material.ambient_map).unwrap() as i32,
- );
+ gl_shader_program
+ .set_uniform(c"material.ambient_map", &(AMBIENT_MAP_TEXTURE_UNIT as i32));
#[allow(clippy::cast_possible_wrap)]
- gl_shader_program.set_uniform_1i(
- c"material.diffuse_map",
- *texture_map.get(&material.diffuse_map).unwrap() as i32,
- );
+ gl_shader_program
+ .set_uniform(c"material.diffuse_map", &(DIFFUSE_MAP_TEXTURE_UNIT as i32));
#[allow(clippy::cast_possible_wrap)]
- gl_shader_program.set_uniform_1i(
+ gl_shader_program.set_uniform(
c"material.specular_map",
- *texture_map.get(&material.specular_map).unwrap() as i32,
+ &(SPECULAR_MAP_TEXTURE_UNIT as i32),
);
- gl_shader_program.set_uniform_1fv(c"material.shininess", material.shininess);
+ gl_shader_program.set_uniform(c"material.shininess", &material.shininess);
- gl_shader_program.set_uniform_vec_3fv(c"view_pos", &camera_pos.position);
+ gl_shader_program.set_uniform(c"view_pos", &camera_world_pos.position);
}
fn set_light_attenuation_uniforms(
@@ -586,27 +671,27 @@ fn set_light_attenuation_uniforms(
light: &PointLight,
)
{
- gl_shader_program.set_uniform_1fv(
+ gl_shader_program.set_uniform(
&create_light_uniform_name(
light_array,
light_index,
"attenuation_props.constant",
),
- light.attenuation_params.constant,
+ &light.attenuation_params.constant,
);
- gl_shader_program.set_uniform_1fv(
+ gl_shader_program.set_uniform(
&create_light_uniform_name(light_array, light_index, "attenuation_props.linear"),
- light.attenuation_params.linear,
+ &light.attenuation_params.linear,
);
- gl_shader_program.set_uniform_1fv(
+ gl_shader_program.set_uniform(
&create_light_uniform_name(
light_array,
light_index,
"attenuation_props.quadratic",
),
- light.attenuation_params.quadratic,
+ &light.attenuation_params.quadratic,
);
}
@@ -617,14 +702,14 @@ fn set_light_phong_uniforms(
light: &impl Light,
)
{
- gl_shader_program.set_uniform_vec_3fv(
+ gl_shader_program.set_uniform(
&create_light_uniform_name(light_array, light_index, "phong.diffuse"),
- &light.diffuse().clone().into(),
+ &Vec3::from(light.diffuse().clone()),
);
- gl_shader_program.set_uniform_vec_3fv(
+ gl_shader_program.set_uniform(
&create_light_uniform_name(light_array, light_index, "phong.specular"),
- &light.specular().clone().into(),
+ &Vec3::from(light.specular().clone()),
);
}
@@ -740,3 +825,23 @@ fn create_transformation_matrix(transformation: Transformation) -> Matrix<f32, 4
matrix
}
+
+#[inline]
+fn texture_wrapping_to_gl(texture_wrapping: TextureWrapping) -> GlTextureWrapping
+{
+ match texture_wrapping {
+ TextureWrapping::Repeat => GlTextureWrapping::Repeat,
+ TextureWrapping::MirroredRepeat => GlTextureWrapping::MirroredRepeat,
+ TextureWrapping::ClampToEdge => GlTextureWrapping::ClampToEdge,
+ TextureWrapping::ClampToBorder => GlTextureWrapping::ClampToBorder,
+ }
+}
+
+#[inline]
+fn texture_filtering_to_gl(texture_filtering: TextureFiltering) -> GlTextureFiltering
+{
+ match texture_filtering {
+ TextureFiltering::Linear => GlTextureFiltering::Linear,
+ TextureFiltering::Nearest => GlTextureFiltering::Nearest,
+ }
+}
diff --git a/engine/src/vertex.rs b/engine/src/renderer/opengl/vertex.rs
index 30640c4..499b94b 100644
--- a/engine/src/vertex.rs
+++ b/engine/src/renderer/opengl/vertex.rs
@@ -1,24 +1,17 @@
-use std::mem::size_of;
-
-use crate::util::builder;
use crate::vector::{Vec2, Vec3};
-builder! {
-#[builder(name = Builder, derives = (Debug, Default))]
-#[derive(Debug, Clone, Default, PartialEq)]
+#[derive(Debug, Clone)]
#[repr(C)]
-#[non_exhaustive]
pub struct Vertex
{
pub pos: Vec3<f32>,
pub texture_coords: Vec2<f32>,
pub normal: Vec3<f32>,
}
-}
impl Vertex
{
- pub(crate) fn attrs() -> &'static [Attribute]
+ pub fn attrs() -> &'static [Attribute]
{
#[allow(clippy::cast_possible_truncation)]
&[
@@ -44,15 +37,17 @@ impl Vertex
}
}
-pub(crate) struct Attribute
+#[derive(Debug)]
+pub struct Attribute
{
- pub(crate) index: u32,
- pub(crate) component_type: AttributeComponentType,
- pub(crate) component_cnt: AttributeComponentCnt,
- pub(crate) component_size: u32,
+ pub index: u32,
+ pub component_type: AttributeComponentType,
+ pub component_cnt: AttributeComponentCnt,
+ pub component_size: u32,
}
-pub(crate) enum AttributeComponentType
+#[derive(Debug)]
+pub enum AttributeComponentType
{
Float,
}
@@ -60,7 +55,7 @@ pub(crate) enum AttributeComponentType
#[derive(Debug, Clone, Copy)]
#[repr(u32)]
#[allow(dead_code)]
-pub(crate) enum AttributeComponentCnt
+pub enum AttributeComponentCnt
{
One = 1,
Two = 2,
diff --git a/engine/src/texture.rs b/engine/src/texture.rs
index 4a4fe86..d02b9ff 100644
--- a/engine/src/texture.rs
+++ b/engine/src/texture.rs
@@ -1,194 +1,34 @@
-use std::fmt::Display;
-use std::path::Path;
-use std::sync::atomic::{AtomicU32, Ordering};
-
-use image::io::Reader as ImageReader;
-use image::{DynamicImage, ImageError, Rgb, RgbImage};
-
-use crate::color::Color;
-use crate::data_types::dimens::Dimens;
-use crate::opengl::texture::PixelDataFormat;
-use crate::util::builder;
-
-static NEXT_ID: AtomicU32 = AtomicU32::new(0);
-
-mod reexports
-{
- pub use crate::opengl::texture::{Filtering, Wrapping};
-}
-
-pub use reexports::*;
+use crate::asset::Handle as AssetHandle;
+use crate::image::Image;
+use crate::builder;
#[derive(Debug, Clone)]
+#[non_exhaustive]
pub struct Texture
{
- id: Id,
- image: DynamicImage,
- pixel_data_format: PixelDataFormat,
- dimensions: Dimens<u32>,
- properties: Properties,
+ pub asset_handle: AssetHandle<Image>,
+ pub properties: Properties,
}
impl Texture
{
- pub fn builder() -> Builder
- {
- Builder::default()
- }
-
- /// Opens a texture image.
- ///
- /// # Errors
- /// Will return `Err` if:
- /// - Opening the image fails
- /// - The image data is not 8-bit/color RGB
- pub fn open(path: &Path) -> Result<Self, Error>
- {
- Self::builder().open(path)
- }
-
- #[must_use]
- pub fn new_from_color(dimensions: &Dimens<u32>, color: &Color<u8>) -> Self
- {
- Self::builder().build_with_single_color(dimensions, color)
- }
-
- #[must_use]
- pub fn id(&self) -> Id
- {
- self.id
- }
-
- #[must_use]
- pub fn properties(&self) -> &Properties
- {
- &self.properties
- }
-
- pub fn properties_mut(&mut self) -> &mut Properties
- {
- &mut self.properties
- }
-
- #[must_use]
- pub fn dimensions(&self) -> &Dimens<u32>
- {
- &self.dimensions
- }
-
- #[must_use]
- pub fn pixel_data_format(&self) -> PixelDataFormat
- {
- self.pixel_data_format
- }
-
- #[must_use]
- pub fn image(&self) -> &DynamicImage
- {
- &self.image
- }
-}
-
-impl Drop for Texture
-{
- fn drop(&mut self)
- {
- NEXT_ID.fetch_sub(1, Ordering::Relaxed);
- }
-}
-
-/// Texture builder.
-#[derive(Debug, Default, Clone)]
-pub struct Builder
-{
- properties: Properties,
-}
-
-impl Builder
-{
- pub fn properties(mut self, properties: Properties) -> Self
+ pub fn new(asset_handle: AssetHandle<Image>) -> Self
{
- self.properties = properties;
- self
- }
-
- /// Opens a image as a texture.
- ///
- /// # Errors
- /// Will return `Err` if:
- /// - Opening the image fails
- /// - Decoding the image fails
- /// - The image data is in a unsupported format
- pub fn open(&self, path: &(impl AsRef<Path> + ?Sized)) -> Result<Texture, Error>
- {
- let image = ImageReader::open(path)
- .map_err(Error::OpenImageFailed)?
- .decode()
- .map_err(Error::DecodeImageFailed)?;
-
- let pixel_data_format = match &image {
- DynamicImage::ImageRgb8(_) => PixelDataFormat::Rgb8,
- DynamicImage::ImageRgba8(_) => PixelDataFormat::Rgba8,
- _ => {
- return Err(Error::UnsupportedImageDataFormat);
- }
- };
-
- let dimensions = Dimens {
- width: image.width(),
- height: image.height(),
- };
-
- let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
-
- Ok(Texture {
- id: Id::new(id),
- image,
- pixel_data_format,
- dimensions,
- properties: self.properties.clone(),
- })
+ Self {
+ asset_handle,
+ properties: Properties::default(),
+ }
}
- #[must_use]
- pub fn build_with_single_color(
- &self,
- dimensions: &Dimens<u32>,
- color: &Color<u8>,
- ) -> Texture
+ pub fn with_properties(
+ asset_handle: AssetHandle<Image>,
+ properties: Properties,
+ ) -> Self
{
- let image = RgbImage::from_pixel(
- dimensions.width,
- dimensions.height,
- Rgb([color.red, color.green, color.blue]),
- );
-
- let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
-
- Texture {
- id: Id::new(id),
- image: image.into(),
- pixel_data_format: PixelDataFormat::Rgb8,
- dimensions: *dimensions,
- properties: self.properties.clone(),
- }
+ Self { asset_handle, properties }
}
}
-/// Texture error.
-#[derive(Debug, thiserror::Error)]
-pub enum Error
-{
- #[error("Failed to open texture image")]
- OpenImageFailed(#[source] std::io::Error),
-
- #[error("Failed to decode texture image")]
- DecodeImageFailed(#[source] ImageError),
-
- #[error("Unsupported image data format")]
- UnsupportedImageDataFormat,
-}
-
builder! {
/// Texture properties
#[builder(name = PropertiesBuilder, derives=(Debug, Clone))]
@@ -230,25 +70,21 @@ impl Default for PropertiesBuilder
}
}
-/// Texture ID.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
-pub struct Id
-{
- id: u32,
-}
-
-impl Id
+#[non_exhaustive]
+pub enum Filtering
{
- fn new(id: u32) -> Self
- {
- Self { id }
- }
+ Nearest,
+ Linear,
}
-impl Display for Id
+/// Texture wrapping.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+#[non_exhaustive]
+pub enum Wrapping
{
- fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
- {
- self.id.fmt(formatter)
- }
+ Repeat,
+ MirroredRepeat,
+ ClampToEdge,
+ ClampToBorder,
}
diff --git a/engine/src/transform.rs b/engine/src/transform.rs
index 5e5e296..7c0c941 100644
--- a/engine/src/transform.rs
+++ b/engine/src/transform.rs
@@ -2,14 +2,14 @@ use ecs::Component;
use crate::vector::Vec3;
-/// A position in 3D space.
+/// A position in world space.
#[derive(Debug, Default, Clone, Copy, Component)]
-pub struct Position
+pub struct WorldPosition
{
pub position: Vec3<f32>,
}
-impl From<Vec3<f32>> for Position
+impl From<Vec3<f32>> for WorldPosition
{
fn from(position: Vec3<f32>) -> Self
{
diff --git a/engine/src/util.rs b/engine/src/util.rs
index 0f6c78c..cc4677d 100644
--- a/engine/src/util.rs
+++ b/engine/src/util.rs
@@ -25,6 +25,18 @@ macro_rules! or {
pub(crate) use or;
+#[macro_export]
+macro_rules! expand_map_opt {
+ ($in: tt, no_occurance=($($no_occurance: tt)*), occurance=($($occurance: tt)*)) => {
+ $($occurance)*
+ };
+
+ (, no_occurance=($($no_occurance: tt)*), occurance=($($occurance: tt)*)) => {
+ $($no_occurance)*
+ };
+}
+
+#[macro_export]
macro_rules! builder {
(
$(#[doc = $doc: literal])*
@@ -36,7 +48,8 @@ macro_rules! builder {
$visibility: vis struct $name: ident
{
$(
- $(#[$field_attr: meta])*
+ $(#[doc = $field_doc: literal])*
+ $(#[builder(skip_generate_fn$($field_skip_generate_fn: tt)?)])?
$field_visibility: vis $field: ident: $field_type: ty,
)*
}
@@ -46,7 +59,7 @@ macro_rules! builder {
$visibility struct $name
{
$(
- $(#[$field_attr])*
+ $(#[doc = $field_doc])*
$field_visibility $field: $field_type,
)*
}
@@ -62,12 +75,18 @@ macro_rules! builder {
impl $builder_name
{
$(
- #[must_use]
- $visibility fn $field(mut self, $field: $field_type) -> Self
- {
- self.$field = $field;
- self
- }
+ $crate::expand_map_opt!(
+ $(true $($field_skip_generate_fn)?)?,
+ no_occurance=(
+ #[must_use]
+ $visibility fn $field(mut self, $field: $field_type) -> Self
+ {
+ self.$field = $field;
+ self
+ }
+ ),
+ occurance=()
+ );
)*
#[must_use]
@@ -82,6 +101,7 @@ macro_rules! builder {
impl From<$name> for $builder_name
{
+ #[allow(unused_variables)]
fn from(built: $name) -> Self
{
Self {
@@ -94,8 +114,6 @@ macro_rules! builder {
};
}
-pub(crate) use builder;
-
pub enum RefOrValue<'a, T>
{
Ref(&'a T),
diff --git a/engine/src/window.rs b/engine/src/window.rs
index 00c360e..f191c06 100644
--- a/engine/src/window.rs
+++ b/engine/src/window.rs
@@ -4,20 +4,21 @@ use std::ffi::{CStr, CString};
use bitflags::bitflags;
use ecs::actions::Actions;
use ecs::extension::Collector as ExtensionCollector;
-use ecs::phase::{Phase, PRESENT as PRESENT_PHASE, START as START_PHASE};
-use ecs::relationship::{ChildOf, Relationship};
+use ecs::pair::{ChildOf, Pair};
+use ecs::phase::{Phase, START as START_PHASE};
use ecs::sole::Single;
-use ecs::{static_entity, Sole};
+use ecs::{declare_entity, Sole};
use glfw::window::{Hint as WindowCreationHint, HintValue as WindowCreationHintValue};
use glfw::WindowSize;
use util_macros::VariantArr;
use crate::data_types::dimens::Dimens;
+use crate::renderer::RENDER_PHASE;
use crate::vector::Vec2;
-static_entity!(
+declare_entity!(
pub UPDATE_PHASE,
- (Phase, <Relationship<ChildOf, Phase>>::new(*PRESENT_PHASE))
+ (Phase, Pair::builder().relation::<ChildOf>().target_id(*RENDER_PHASE).build())
);
#[derive(Debug, Sole)]
@@ -691,8 +692,10 @@ impl ecs::extension::Extension for Extension
{
fn collect(self, mut collector: ExtensionCollector<'_>)
{
+ collector.add_declared_entity(&self::UPDATE_PHASE);
+
collector.add_system(*START_PHASE, initialize);
- collector.add_system(*UPDATE_PHASE, update);
+ collector.add_system(*self::UPDATE_PHASE, update);
let window = self
.window_builder
diff --git a/engine/src/work_queue.rs b/engine/src/work_queue.rs
new file mode 100644
index 0000000..7226c7d
--- /dev/null
+++ b/engine/src/work_queue.rs
@@ -0,0 +1,44 @@
+use std::marker::PhantomData;
+use std::sync::mpsc::{channel as mpsc_channel, Sender as MpscSender};
+use std::thread::JoinHandle as ThreadHandle;
+
+pub struct Work<UserData: Send + Sync + 'static>
+{
+ pub func: fn(UserData),
+ pub user_data: UserData,
+}
+
+#[derive(Debug)]
+pub struct WorkQueue<UserData: Send + Sync + 'static>
+{
+ work_sender: MpscSender<Work<UserData>>,
+ _thread: ThreadHandle<()>,
+ _pd: PhantomData<UserData>,
+}
+
+impl<UserData: Send + Sync + 'static> WorkQueue<UserData>
+{
+ pub fn new() -> Self
+ {
+ let (work_sender, work_receiver) = mpsc_channel::<Work<UserData>>();
+
+ Self {
+ work_sender,
+ _thread: std::thread::spawn(move || {
+ let work_receiver = work_receiver;
+
+ while let Ok(work) = work_receiver.recv() {
+ (work.func)(work.user_data);
+ }
+ }),
+ _pd: PhantomData,
+ }
+ }
+
+ pub fn add_work(&self, work: Work<UserData>)
+ {
+ if self.work_sender.send(work).is_err() {
+ tracing::error!("Cannot add work to work queue. Work queue thread is dead");
+ }
+ }
+}
diff --git a/opengl-bindings/Cargo.toml b/opengl-bindings/Cargo.toml
new file mode 100644
index 0000000..8251642
--- /dev/null
+++ b/opengl-bindings/Cargo.toml
@@ -0,0 +1,65 @@
+[package]
+name = "opengl-bindings"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+glutin = "0.32.3"
+thiserror = "1.0.49"
+safer-ffi = "0.1.13"
+bitflags = "2.4.0"
+util-macros = { path = "../util-macros" }
+
+[build-dependencies]
+gl_generator = "=0.14.0"
+toml = "0.8.12"
+anyhow = "1.0.100"
+
+[package.metadata.build]
+gl_commands = [
+ "CreateBuffers",
+ "NamedBufferData",
+ "NamedBufferSubData",
+ "CreateVertexArrays",
+ "DrawArrays",
+ "DrawElements",
+ "VertexArrayElementBuffer",
+ "VertexArrayVertexBuffer",
+ "EnableVertexArrayAttrib",
+ "VertexArrayAttribFormat",
+ "VertexArrayAttribBinding",
+ "BindVertexArray",
+ "TextureStorage2D",
+ "TextureSubImage2D",
+ "DeleteTextures",
+ "GenerateTextureMipmap",
+ "TextureParameteri",
+ "CreateTextures",
+ "BindTextureUnit",
+ "DeleteShader",
+ "CreateShader",
+ "ShaderSource",
+ "CompileShader",
+ "GetShaderiv",
+ "GetShaderInfoLog",
+ "LinkProgram",
+ "GetProgramiv",
+ "CreateProgram",
+ "AttachShader",
+ "UseProgram",
+ "GetUniformLocation",
+ "ProgramUniform1f",
+ "ProgramUniform1i",
+ "ProgramUniform3f",
+ "ProgramUniformMatrix4fv",
+ "GetProgramInfoLog",
+ "DeleteProgram",
+ "Viewport",
+ "Clear",
+ "PolygonMode",
+ "Enable",
+ "Disable",
+ "GetIntegerv",
+ "DebugMessageCallback",
+ "DebugMessageControl"
+]
diff --git a/opengl-bindings/build.rs b/opengl-bindings/build.rs
new file mode 100644
index 0000000..060472c
--- /dev/null
+++ b/opengl-bindings/build.rs
@@ -0,0 +1,107 @@
+use std::collections::HashSet;
+use std::env;
+use std::fs::File;
+use std::path::{Path, PathBuf};
+
+use anyhow::anyhow;
+use gl_generator::{Api, Fallbacks, Profile, Registry, StructGenerator};
+
+fn main() -> Result<(), anyhow::Error>
+{
+ println!("cargo::rerun-if-changed=build.rs");
+ println!("cargo::rerun-if-changed=Cargo.toml");
+
+ let dest = env::var("OUT_DIR")?;
+
+ let mut file = File::create(Path::new(&dest).join("bindings.rs"))?;
+
+ let mut registry = Registry::new(Api::Gl, (4, 6), Profile::Core, Fallbacks::All, []);
+
+ let mut build_metadata = get_build_metadata()?;
+
+ filter_gl_commands(&mut registry, &mut build_metadata)?;
+
+ registry.write_bindings(StructGenerator, &mut file)?;
+
+ Ok(())
+}
+
+fn filter_gl_commands(
+ registry: &mut Registry,
+ build_metadata: &mut BuildMetadata,
+) -> Result<(), anyhow::Error>
+{
+ registry
+ .cmds
+ .retain(|command| build_metadata.gl_commands.remove(&command.proto.ident));
+
+ if !build_metadata.gl_commands.is_empty() {
+ return Err(anyhow!(
+ "Invalid GL commands: [{}]",
+ build_metadata
+ .gl_commands
+ .iter()
+ .cloned()
+ .collect::<Vec<_>>()
+ .join(", ")
+ ));
+ }
+
+ Ok(())
+}
+
+fn get_build_metadata() -> Result<BuildMetadata, anyhow::Error>
+{
+ let manifest_path = PathBuf::from(std::env::var("CARGO_MANIFEST_PATH")?);
+
+ let manifest = std::fs::read_to_string(manifest_path)?.parse::<toml::Table>()?;
+
+ let package = match manifest
+ .get("package")
+ .ok_or_else(|| anyhow!("Manifest does not have a package table"))?
+ {
+ toml::Value::Table(package) => Ok(package),
+ _ => Err(anyhow!("Manifest package must be a table")),
+ }?;
+
+ let metadata = match package
+ .get("metadata")
+ .ok_or_else(|| anyhow!("Manifest does not have a package.metadata table"))?
+ {
+ toml::Value::Table(metadata) => Ok(metadata),
+ _ => Err(anyhow!("Manifest package.metadata must be a table")),
+ }?;
+
+ let build_metadata = match metadata
+ .get("build")
+ .ok_or_else(|| anyhow!("Manifest does not have a package.metadata.build table"))?
+ {
+ toml::Value::Table(build_metadata) => Ok(build_metadata),
+ _ => Err(anyhow!("Manifest package.metadata.build must be a table")),
+ }?;
+
+ let gl_command_values = match build_metadata.get("gl_commands").ok_or_else(|| {
+ anyhow!("Manifest does not have a package.metadata.build.gl_commands array")
+ })? {
+ toml::Value::Array(gl_commands) => Ok(gl_commands),
+ _ => Err(anyhow!(
+ "Manifest package.metadata.build.gl_commands must be a array"
+ )),
+ }?;
+
+ let gl_commands = gl_command_values
+ .iter()
+ .map(|gl_command_val| match gl_command_val {
+ toml::Value::String(gl_command) => Ok(gl_command.clone()),
+ _ => Err(anyhow!("GL command must be a string")),
+ })
+ .collect::<Result<HashSet<_>, _>>()?;
+
+ Ok(BuildMetadata { gl_commands })
+}
+
+#[derive(Debug)]
+struct BuildMetadata
+{
+ gl_commands: HashSet<String>,
+}
diff --git a/opengl-bindings/src/buffer.rs b/opengl-bindings/src/buffer.rs
new file mode 100644
index 0000000..c64ec8d
--- /dev/null
+++ b/opengl-bindings/src/buffer.rs
@@ -0,0 +1,167 @@
+use std::marker::PhantomData;
+use std::mem::size_of_val;
+use std::ptr::null;
+
+use safer_ffi::layout::ReprC;
+
+use crate::CurrentContextWithFns;
+
+#[derive(Debug)]
+pub struct Buffer<Item: ReprC>
+{
+ buf: crate::sys::types::GLuint,
+ _pd: PhantomData<Item>,
+}
+
+impl<Item: ReprC> Buffer<Item>
+{
+ #[must_use]
+ pub fn new(current_context: &CurrentContextWithFns<'_>) -> Self
+ {
+ let mut buffer = crate::sys::types::GLuint::default();
+
+ unsafe {
+ current_context.fns().CreateBuffers(1, &raw mut buffer);
+ };
+
+ Self { buf: buffer, _pd: PhantomData }
+ }
+
+ /// Stores items in this buffer.
+ ///
+ /// # Errors
+ /// Returns `Err` if the total size (in bytes) is too large.
+ pub fn store(
+ &self,
+ current_context: &CurrentContextWithFns<'_>,
+ items: &[Item],
+ usage: Usage,
+ ) -> Result<(), Error>
+ {
+ let total_size = size_of_val(items);
+
+ let total_size: crate::sys::types::GLsizeiptr =
+ total_size
+ .try_into()
+ .map_err(|_| Error::TotalItemsSizeTooLarge {
+ total_size,
+ max_total_size: crate::sys::types::GLsizeiptr::MAX as usize,
+ })?;
+
+ unsafe {
+ current_context.fns().NamedBufferData(
+ self.buf,
+ total_size,
+ items.as_ptr().cast(),
+ usage.into_gl(),
+ );
+ }
+
+ Ok(())
+ }
+
+ /// Maps the values in the `values` slice into `Item`s which is stored into this
+ /// buffer.
+ ///
+ /// # Errors
+ /// Returns `Err` if the total size (in bytes) is too large.
+ pub fn store_mapped<Value>(
+ &self,
+ current_context: &CurrentContextWithFns<'_>,
+ values: &[Value],
+ usage: Usage,
+ mut map_func: impl FnMut(&Value) -> Item,
+ ) -> Result<(), Error>
+ {
+ let item_size: crate::sys::types::GLsizeiptr = const {
+ assert!(size_of::<Item>() <= crate::sys::types::GLsizeiptr::MAX as usize);
+
+ size_of::<Item>().cast_signed()
+ };
+
+ let total_size = size_of::<Item>() * values.len();
+
+ let total_size: crate::sys::types::GLsizeiptr =
+ total_size
+ .try_into()
+ .map_err(|_| Error::TotalItemsSizeTooLarge {
+ total_size,
+ max_total_size: crate::sys::types::GLsizeiptr::MAX as usize,
+ })?;
+
+ unsafe {
+ current_context.fns().NamedBufferData(
+ self.buf,
+ total_size,
+ null(),
+ usage.into_gl(),
+ );
+ }
+
+ for (index, value) in values.iter().enumerate() {
+ let item = map_func(value);
+
+ let offset = index * size_of::<Item>();
+
+ let Ok(offset_casted) = crate::sys::types::GLintptr::try_from(offset) else {
+ unreachable!(); // Reason: The total size can be casted to a GLintptr
+ // (done above) so offsets should be castable as well
+ };
+
+ unsafe {
+ current_context.fns().NamedBufferSubData(
+ self.buf,
+ offset_casted,
+ item_size,
+ (&raw const item).cast(),
+ );
+ }
+ }
+
+ Ok(())
+ }
+
+ pub(crate) fn object(&self) -> crate::sys::types::GLuint
+ {
+ self.buf
+ }
+}
+
+/// Buffer usage.
+#[derive(Debug)]
+pub enum Usage
+{
+ /// The buffer data is set only once and used by the GPU at most a few times.
+ Stream,
+
+ /// The buffer data is set only once and used many times.
+ Static,
+
+ /// The buffer data is changed a lot and used many times.
+ Dynamic,
+}
+
+impl Usage
+{
+ fn into_gl(self) -> crate::sys::types::GLenum
+ {
+ match self {
+ Self::Stream => crate::sys::STREAM_DRAW,
+ Self::Static => crate::sys::STATIC_DRAW,
+ Self::Dynamic => crate::sys::DYNAMIC_DRAW,
+ }
+ }
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum Error
+{
+ #[error(
+ "Total size of items ({total_size}) is too large. Must be < {max_total_size}"
+ )]
+ TotalItemsSizeTooLarge
+ {
+ total_size: usize,
+ max_total_size: usize,
+ },
+}
diff --git a/opengl-bindings/src/data_types.rs b/opengl-bindings/src/data_types.rs
new file mode 100644
index 0000000..7ead0ab
--- /dev/null
+++ b/opengl-bindings/src/data_types.rs
@@ -0,0 +1,37 @@
+use safer_ffi::derive_ReprC;
+use safer_ffi::layout::ReprC;
+
+#[derive(Debug, Clone)]
+#[derive_ReprC]
+#[repr(C)]
+pub struct Matrix<Value: ReprC, const ROWS: usize, const COLUMNS: usize>
+{
+ /// Items must be layed out this way for it to work with OpenGL shaders.
+ pub items: [[Value; ROWS]; COLUMNS],
+}
+
+#[derive(Debug, Clone)]
+#[derive_ReprC]
+#[repr(C)]
+pub struct Vec3<Value: ReprC>
+{
+ pub x: Value,
+ pub y: Value,
+ pub z: Value,
+}
+
+#[derive(Debug, Clone)]
+#[derive_ReprC]
+#[repr(C)]
+pub struct Vec2<Value>
+{
+ pub x: Value,
+ pub y: Value,
+}
+
+#[derive(Debug, Clone)]
+pub struct Dimens<Value>
+{
+ pub width: Value,
+ pub height: Value,
+}
diff --git a/opengl-bindings/src/debug.rs b/opengl-bindings/src/debug.rs
new file mode 100644
index 0000000..a9369a4
--- /dev/null
+++ b/opengl-bindings/src/debug.rs
@@ -0,0 +1,161 @@
+use std::ffi::c_void;
+use std::io::{stderr, Write};
+use std::mem::transmute;
+use std::panic::catch_unwind;
+
+use util_macros::FromRepr;
+
+use crate::CurrentContextWithFns;
+
+pub fn set_debug_message_callback(
+ current_context: &CurrentContextWithFns<'_>,
+ cb: MessageCallback,
+)
+{
+ unsafe {
+ current_context
+ .fns()
+ .DebugMessageCallback(Some(debug_message_cb), cb as *mut c_void);
+ }
+}
+
+/// Sets debug message parameters.
+///
+/// # Errors
+/// Returns `Err` if `ids` contains too many ids.
+pub fn set_debug_message_control(
+ current_context: &CurrentContextWithFns<'_>,
+ source: Option<MessageSource>,
+ ty: Option<MessageType>,
+ severity: Option<MessageSeverity>,
+ ids: &[u32],
+ ids_action: MessageIdsAction,
+) -> Result<(), SetDebugMessageControlError>
+{
+ let ids_len: crate::sys::types::GLsizei =
+ ids.len()
+ .try_into()
+ .map_err(|_| SetDebugMessageControlError::TooManyIds {
+ id_cnt: ids.len(),
+ max_id_cnt: crate::sys::types::GLsizei::MAX as usize,
+ })?;
+
+ unsafe {
+ current_context.fns().DebugMessageControl(
+ source.map_or(crate::sys::DONT_CARE, |source| source as u32),
+ ty.map_or(crate::sys::DONT_CARE, |ty| ty as u32),
+ severity.map_or(crate::sys::DONT_CARE, |severity| severity as u32),
+ ids_len,
+ ids.as_ptr(),
+ ids_action as u8,
+ );
+ }
+
+ Ok(())
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum SetDebugMessageControlError
+{
+ #[error("Too many ids provided ({id_cnt}). Must be < {max_id_cnt}")]
+ TooManyIds
+ {
+ id_cnt: usize, max_id_cnt: usize
+ },
+}
+
+pub type MessageCallback = fn(
+ source: MessageSource,
+ ty: MessageType,
+ id: u32,
+ severity: MessageSeverity,
+ message: &str,
+);
+
+#[derive(Debug, Clone, Copy)]
+#[repr(u8)] // GLboolean = u8
+pub enum MessageIdsAction
+{
+ Enable = crate::sys::TRUE,
+ Disable = crate::sys::FALSE,
+}
+
+#[derive(Debug, Clone, Copy, FromRepr)]
+#[repr(u32)] // GLenum = u32
+pub enum MessageSource
+{
+ Api = crate::sys::DEBUG_SOURCE_API,
+ WindowSystem = crate::sys::DEBUG_SOURCE_WINDOW_SYSTEM,
+ ShaderCompiler = crate::sys::DEBUG_SOURCE_SHADER_COMPILER,
+ ThirdParty = crate::sys::DEBUG_SOURCE_THIRD_PARTY,
+ Application = crate::sys::DEBUG_SOURCE_APPLICATION,
+ Other = crate::sys::DEBUG_SOURCE_OTHER,
+}
+
+#[derive(Debug, Clone, Copy, FromRepr)]
+#[repr(u32)] // GLenum = u32
+pub enum MessageType
+{
+ DeprecatedBehavior = crate::sys::DEBUG_TYPE_DEPRECATED_BEHAVIOR,
+ Error = crate::sys::DEBUG_TYPE_ERROR,
+ Marker = crate::sys::DEBUG_TYPE_MARKER,
+ Other = crate::sys::DEBUG_TYPE_OTHER,
+ Performance = crate::sys::DEBUG_TYPE_PERFORMANCE,
+ PopGroup = crate::sys::DEBUG_TYPE_POP_GROUP,
+ PushGroup = crate::sys::DEBUG_TYPE_PUSH_GROUP,
+ Portability = crate::sys::DEBUG_TYPE_PORTABILITY,
+ UndefinedBehavior = crate::sys::DEBUG_TYPE_UNDEFINED_BEHAVIOR,
+}
+
+#[derive(Debug, Clone, Copy, FromRepr)]
+#[repr(u32)] // GLenum = u32
+pub enum MessageSeverity
+{
+ High = crate::sys::DEBUG_SEVERITY_HIGH,
+ Medium = crate::sys::DEBUG_SEVERITY_MEDIUM,
+ Low = crate::sys::DEBUG_SEVERITY_LOW,
+ Notification = crate::sys::DEBUG_SEVERITY_NOTIFICATION,
+}
+
+extern "system" fn debug_message_cb(
+ source: crate::sys::types::GLenum,
+ ty: crate::sys::types::GLenum,
+ id: crate::sys::types::GLuint,
+ severity: crate::sys::types::GLenum,
+ message_length: crate::sys::types::GLsizei,
+ message: *const crate::sys::types::GLchar,
+ user_cb: *mut c_void,
+)
+{
+ let user_cb = unsafe { transmute::<*mut c_void, MessageCallback>(user_cb) };
+
+ let Ok(msg_length) = usize::try_from(message_length) else {
+ return;
+ };
+
+ // Unwinds are catched because unwinding from Rust code into foreign code is UB.
+ let res = catch_unwind(|| {
+ let msg_source = MessageSource::from_repr(source).unwrap();
+ let msg_type = MessageType::from_repr(ty).unwrap();
+ let msg_severity = MessageSeverity::from_repr(severity).unwrap();
+
+ // SAFETY: The received message should be a valid ASCII string
+ let message = unsafe {
+ std::str::from_utf8_unchecked(std::slice::from_raw_parts(
+ message.cast(),
+ msg_length,
+ ))
+ };
+
+ user_cb(msg_source, msg_type, id, msg_severity, message);
+ });
+
+ if res.is_err() {
+ // eprintln is not used since it can panic and unwinds are unwanted because
+ // unwinding from Rust code into foreign code is UB.
+ stderr()
+ .write_all(b"ERROR: Panic in debug message callback")
+ .ok();
+ println!();
+ }
+}
diff --git a/opengl-bindings/src/lib.rs b/opengl-bindings/src/lib.rs
new file mode 100644
index 0000000..7fd9933
--- /dev/null
+++ b/opengl-bindings/src/lib.rs
@@ -0,0 +1,119 @@
+#![deny(clippy::all, clippy::pedantic)]
+use std::ffi::CString;
+use std::process::abort;
+
+use glutin::context::{NotCurrentContext, PossiblyCurrentContext};
+use glutin::display::GetGlDisplay;
+use glutin::prelude::{GlDisplay, NotCurrentGlContext, PossiblyCurrentGlContext};
+use glutin::surface::{Surface, SurfaceTypeTrait};
+
+pub mod buffer;
+pub mod data_types;
+pub mod debug;
+pub mod misc;
+pub mod shader;
+pub mod texture;
+pub mod vertex_array;
+
+pub struct ContextWithFns
+{
+ context: PossiblyCurrentContext,
+ fns: Box<sys::Gl>,
+}
+
+impl ContextWithFns
+{
+ /// Returns a new `ContextWithFns`.
+ ///
+ /// # Errors
+ /// Returns `Err` if making this context current fails.
+ pub fn new<SurfaceType: SurfaceTypeTrait>(
+ context: NotCurrentContext,
+ surface: &Surface<SurfaceType>,
+ ) -> Result<Self, Error>
+ {
+ let context = context
+ .make_current(surface)
+ .map_err(Error::MakeContextCurrentFailed)?;
+
+ let display = context.display();
+
+ let gl = sys::Gl::load_with(|symbol| {
+ let Ok(symbol) = CString::new(symbol) else {
+ eprintln!("GL symbol contains nul byte");
+ abort();
+ };
+
+ display.get_proc_address(&symbol)
+ });
+
+ Ok(Self { context, fns: Box::new(gl) })
+ }
+
+ /// Attempts to make this context current.
+ ///
+ /// # Errors
+ /// Returns `Err` if making this context current fails.
+ pub fn make_current<SurfaceType: SurfaceTypeTrait>(
+ &self,
+ surface: &Surface<SurfaceType>,
+ ) -> Result<CurrentContextWithFns<'_>, Error>
+ {
+ if !self.context.is_current() {
+ self.context
+ .make_current(surface)
+ .map_err(Error::MakeContextCurrentFailed)?;
+ }
+
+ Ok(CurrentContextWithFns { ctx: self })
+ }
+
+ #[must_use]
+ pub fn context(&self) -> &PossiblyCurrentContext
+ {
+ &self.context
+ }
+
+ #[must_use]
+ pub fn context_mut(&mut self) -> &mut PossiblyCurrentContext
+ {
+ &mut self.context
+ }
+}
+
+pub struct CurrentContextWithFns<'ctx>
+{
+ ctx: &'ctx ContextWithFns,
+}
+
+impl CurrentContextWithFns<'_>
+{
+ #[inline]
+ pub(crate) fn fns(&self) -> &sys::Gl
+ {
+ &self.ctx.fns
+ }
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum Error
+{
+ #[error("Failed to make context current")]
+ MakeContextCurrentFailed(#[source] glutin::error::Error),
+}
+
+mod sys
+{
+ #![allow(
+ clippy::missing_safety_doc,
+ clippy::missing_transmute_annotations,
+ clippy::too_many_arguments,
+ clippy::unused_unit,
+ clippy::upper_case_acronyms,
+ clippy::doc_markdown,
+ clippy::unreadable_literal,
+ unsafe_op_in_unsafe_fn
+ )]
+
+ include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
+}
diff --git a/opengl-bindings/src/misc.rs b/opengl-bindings/src/misc.rs
new file mode 100644
index 0000000..bb54c1a
--- /dev/null
+++ b/opengl-bindings/src/misc.rs
@@ -0,0 +1,190 @@
+use bitflags::bitflags;
+
+use crate::data_types::{Dimens, Vec2};
+use crate::CurrentContextWithFns;
+
+/// Sets the viewport.
+///
+/// The `u32` values in `position` and `size` must fit in `i32`s.
+///
+/// # Errors
+/// Returns `Err` if any value in `position` or `size` does not fit into a `i32`.
+pub fn set_viewport(
+ current_context: &CurrentContextWithFns<'_>,
+ position: &Vec2<u32>,
+ size: &Dimens<u32>,
+) -> Result<(), SetViewportError>
+{
+ let position = Vec2::<crate::sys::types::GLint> {
+ x: position.x.try_into().map_err(|_| {
+ SetViewportError::PositionXValueTooLarge {
+ value: position.x,
+ max_value: crate::sys::types::GLint::MAX as u32,
+ }
+ })?,
+ y: position.y.try_into().map_err(|_| {
+ SetViewportError::PositionYValueTooLarge {
+ value: position.y,
+ max_value: crate::sys::types::GLint::MAX as u32,
+ }
+ })?,
+ };
+
+ let size = Dimens::<crate::sys::types::GLsizei> {
+ width: size.width.try_into().map_err(|_| {
+ SetViewportError::SizeWidthValueTooLarge {
+ value: size.width,
+ max_value: crate::sys::types::GLsizei::MAX as u32,
+ }
+ })?,
+ height: size.height.try_into().map_err(|_| {
+ SetViewportError::SizeHeightValueTooLarge {
+ value: size.height,
+ max_value: crate::sys::types::GLsizei::MAX as u32,
+ }
+ })?,
+ };
+
+ unsafe {
+ current_context
+ .fns()
+ .Viewport(position.x, position.y, size.width, size.height);
+ }
+
+ Ok(())
+}
+
+pub fn clear_buffers(current_context: &CurrentContextWithFns<'_>, mask: BufferClearMask)
+{
+ unsafe {
+ current_context.fns().Clear(mask.bits());
+ }
+}
+
+pub fn set_polygon_mode(
+ current_context: &CurrentContextWithFns<'_>,
+ face: impl Into<PolygonModeFace>,
+ mode: impl Into<PolygonMode>,
+)
+{
+ unsafe {
+ current_context
+ .fns()
+ .PolygonMode(face.into() as u32, mode.into() as u32);
+ }
+}
+
+pub fn enable(current_context: &CurrentContextWithFns<'_>, capacity: Capability)
+{
+ unsafe {
+ current_context.fns().Enable(capacity as u32);
+ }
+}
+
+pub fn disable(current_context: &CurrentContextWithFns<'_>, capability: Capability)
+{
+ unsafe {
+ current_context.fns().Disable(capability as u32);
+ }
+}
+
+pub fn set_enabled(
+ current_context: &CurrentContextWithFns<'_>,
+ capability: Capability,
+ enabled: bool,
+)
+{
+ if enabled {
+ enable(current_context, capability);
+ } else {
+ disable(current_context, capability);
+ }
+}
+
+#[must_use]
+pub fn get_context_flags(current_context: &CurrentContextWithFns<'_>) -> ContextFlags
+{
+ let mut context_flags = crate::sys::types::GLint::default();
+
+ unsafe {
+ current_context
+ .fns()
+ .GetIntegerv(crate::sys::CONTEXT_FLAGS, &raw mut context_flags);
+ }
+
+ ContextFlags::from_bits_truncate(context_flags.cast_unsigned())
+}
+
+bitflags! {
+ #[derive(Debug, Clone, Copy)]
+ pub struct BufferClearMask: u32 {
+ const COLOR = crate::sys::COLOR_BUFFER_BIT;
+ const DEPTH = crate::sys::DEPTH_BUFFER_BIT;
+ const STENCIL = crate::sys::STENCIL_BUFFER_BIT;
+ }
+}
+
+#[derive(Debug)]
+#[repr(u32)]
+pub enum Capability
+{
+ DepthTest = crate::sys::DEPTH_TEST,
+ MultiSample = crate::sys::MULTISAMPLE,
+ DebugOutput = crate::sys::DEBUG_OUTPUT,
+ DebugOutputSynchronous = crate::sys::DEBUG_OUTPUT_SYNCHRONOUS,
+}
+
+#[derive(Debug)]
+#[repr(u32)]
+pub enum PolygonMode
+{
+ Point = crate::sys::POINT,
+ Line = crate::sys::LINE,
+ Fill = crate::sys::FILL,
+}
+
+#[derive(Debug)]
+#[repr(u32)]
+pub enum PolygonModeFace
+{
+ Front = crate::sys::FRONT,
+ Back = crate::sys::BACK,
+ FrontAndBack = crate::sys::FRONT_AND_BACK,
+}
+
+bitflags! {
+#[derive(Debug, Clone, Copy)]
+pub struct ContextFlags: u32 {
+ const FORWARD_COMPATIBLE = crate::sys::CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT;
+ const DEBUG = crate::sys::CONTEXT_FLAG_DEBUG_BIT;
+ const ROBUST_ACCESS = crate::sys::CONTEXT_FLAG_ROBUST_ACCESS_BIT;
+}
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum SetViewportError
+{
+ #[error("Position X value ({value}) is too large. Must be < {max_value}")]
+ PositionXValueTooLarge
+ {
+ value: u32, max_value: u32
+ },
+
+ #[error("Position Y value ({value}) is too large. Must be < {max_value}")]
+ PositionYValueTooLarge
+ {
+ value: u32, max_value: u32
+ },
+
+ #[error("Size width value ({value}) is too large. Must be < {max_value}")]
+ SizeWidthValueTooLarge
+ {
+ value: u32, max_value: u32
+ },
+
+ #[error("Size height value ({value}) is too large. Must be < {max_value}")]
+ SizeHeightValueTooLarge
+ {
+ value: u32, max_value: u32
+ },
+}
diff --git a/opengl-bindings/src/shader.rs b/opengl-bindings/src/shader.rs
new file mode 100644
index 0000000..5ed66a2
--- /dev/null
+++ b/opengl-bindings/src/shader.rs
@@ -0,0 +1,366 @@
+use std::ffi::CStr;
+use std::ptr::null_mut;
+
+use safer_ffi::layout::ReprC;
+
+use crate::data_types::{Matrix, Vec3};
+use crate::CurrentContextWithFns;
+
+#[derive(Debug)]
+pub struct Shader
+{
+ shader: crate::sys::types::GLuint,
+}
+
+impl Shader
+{
+ #[must_use]
+ pub fn new(current_context: &CurrentContextWithFns<'_>, kind: Kind) -> Self
+ {
+ let shader = unsafe {
+ current_context
+ .fns()
+ .CreateShader(kind as crate::sys::types::GLenum)
+ };
+
+ Self { shader }
+ }
+
+ /// Sets the source code of this shader.
+ ///
+ /// # Errors
+ /// Returns `Err` if `source` is not ASCII.
+ pub fn set_source(
+ &self,
+ current_context: &CurrentContextWithFns<'_>,
+ source: &str,
+ ) -> Result<(), Error>
+ {
+ if !source.is_ascii() {
+ return Err(Error::SourceNotAscii);
+ }
+
+ let length: crate::sys::types::GLint =
+ source.len().try_into().map_err(|_| Error::SourceTooLarge {
+ length: source.len(),
+ max_length: crate::sys::types::GLint::MAX as usize,
+ })?;
+
+ unsafe {
+ current_context.fns().ShaderSource(
+ self.shader,
+ 1,
+ &source.as_ptr().cast(),
+ &raw const length,
+ );
+ }
+
+ Ok(())
+ }
+
+ /// Compiles this shader.
+ ///
+ /// # Errors
+ /// Returns `Err` if compiling fails.
+ pub fn compile(
+ &self,
+ current_context: &CurrentContextWithFns<'_>,
+ ) -> Result<(), Error>
+ {
+ unsafe {
+ current_context.fns().CompileShader(self.shader);
+ }
+
+ let mut compile_success = crate::sys::types::GLint::default();
+
+ unsafe {
+ current_context.fns().GetShaderiv(
+ self.shader,
+ crate::sys::COMPILE_STATUS,
+ &raw mut compile_success,
+ );
+ }
+
+ if compile_success == 0 {
+ let info_log = self.get_info_log(current_context);
+
+ return Err(Error::CompileFailed { log: info_log });
+ }
+
+ Ok(())
+ }
+
+ pub fn delete(self, current_context: &CurrentContextWithFns<'_>)
+ {
+ unsafe {
+ current_context.fns().DeleteShader(self.shader);
+ }
+ }
+
+ fn get_info_log(&self, current_context: &CurrentContextWithFns<'_>) -> String
+ {
+ const BUF_SIZE: crate::sys::types::GLsizei = 512;
+
+ let mut buf = vec![crate::sys::types::GLchar::default(); BUF_SIZE as usize];
+
+ unsafe {
+ current_context.fns().GetShaderInfoLog(
+ self.shader,
+ BUF_SIZE,
+ null_mut(),
+ buf.as_mut_ptr(),
+ );
+ }
+
+ let info_log = unsafe { CStr::from_ptr(buf.as_ptr()) };
+
+ unsafe { String::from_utf8_unchecked(info_log.to_bytes().to_vec()) }
+ }
+}
+
+/// Shader kind.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+#[repr(u32)]
+pub enum Kind
+{
+ Vertex = crate::sys::VERTEX_SHADER,
+ Fragment = crate::sys::FRAGMENT_SHADER,
+}
+
+/// Shader program
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct Program
+{
+ program: crate::sys::types::GLuint,
+}
+
+impl Program
+{
+ #[must_use]
+ pub fn new(current_context: &CurrentContextWithFns<'_>) -> Self
+ {
+ let program = unsafe { current_context.fns().CreateProgram() };
+
+ Self { program }
+ }
+
+ pub fn attach(&self, current_context: &CurrentContextWithFns<'_>, shader: &Shader)
+ {
+ unsafe {
+ current_context
+ .fns()
+ .AttachShader(self.program, shader.shader);
+ }
+ }
+
+ /// Links this program.
+ ///
+ /// # Errors
+ /// Returns `Err` if linking fails.
+ pub fn link(&self, current_context: &CurrentContextWithFns<'_>) -> Result<(), Error>
+ {
+ unsafe {
+ current_context.fns().LinkProgram(self.program);
+ }
+
+ let mut link_success = crate::sys::types::GLint::default();
+
+ unsafe {
+ current_context.fns().GetProgramiv(
+ self.program,
+ crate::sys::LINK_STATUS,
+ &raw mut link_success,
+ );
+ }
+
+ if link_success == 0 {
+ let info_log = self.get_info_log(current_context);
+
+ return Err(Error::LinkFailed { log: info_log });
+ }
+
+ Ok(())
+ }
+
+ pub fn activate(&self, current_context: &CurrentContextWithFns<'_>)
+ {
+ unsafe {
+ current_context.fns().UseProgram(self.program);
+ }
+ }
+
+ pub fn set_uniform(
+ &self,
+ current_context: &CurrentContextWithFns<'_>,
+ name: &CStr,
+ var: &impl UniformVariable,
+ )
+ {
+ let location = UniformLocation(unsafe {
+ current_context
+ .fns()
+ .GetUniformLocation(self.program, name.as_ptr().cast())
+ });
+
+ var.set(current_context, self, location);
+ }
+
+ pub fn delete(self, current_context: &CurrentContextWithFns<'_>)
+ {
+ unsafe {
+ current_context.fns().DeleteProgram(self.program);
+ }
+ }
+
+ fn get_info_log(&self, current_context: &CurrentContextWithFns<'_>) -> String
+ {
+ const BUF_SIZE: crate::sys::types::GLsizei = 512;
+
+ let mut buf = vec![crate::sys::types::GLchar::default(); BUF_SIZE as usize];
+
+ unsafe {
+ current_context.fns().GetProgramInfoLog(
+ self.program,
+ BUF_SIZE,
+ null_mut(),
+ buf.as_mut_ptr(),
+ );
+ }
+
+ let info_log = unsafe { CStr::from_ptr(buf.as_ptr()) };
+
+ unsafe { String::from_utf8_unchecked(info_log.to_bytes().to_vec()) }
+ }
+}
+
+pub trait UniformVariable: ReprC + sealed::Sealed
+{
+ fn set(
+ &self,
+ current_context: &CurrentContextWithFns<'_>,
+ program: &Program,
+ uniform_location: UniformLocation,
+ );
+}
+
+impl UniformVariable for f32
+{
+ fn set(
+ &self,
+ current_context: &CurrentContextWithFns<'_>,
+ program: &Program,
+ uniform_location: UniformLocation,
+ )
+ {
+ unsafe {
+ current_context.fns().ProgramUniform1f(
+ program.program,
+ uniform_location.0,
+ *self,
+ );
+ }
+ }
+}
+
+impl sealed::Sealed for f32 {}
+
+impl UniformVariable for i32
+{
+ fn set(
+ &self,
+ current_context: &CurrentContextWithFns<'_>,
+ program: &Program,
+ uniform_location: UniformLocation,
+ )
+ {
+ unsafe {
+ current_context.fns().ProgramUniform1i(
+ program.program,
+ uniform_location.0,
+ *self,
+ );
+ }
+ }
+}
+
+impl sealed::Sealed for i32 {}
+
+impl UniformVariable for Vec3<f32>
+{
+ fn set(
+ &self,
+ current_context: &CurrentContextWithFns<'_>,
+ program: &Program,
+ uniform_location: UniformLocation,
+ )
+ {
+ unsafe {
+ current_context.fns().ProgramUniform3f(
+ program.program,
+ uniform_location.0,
+ self.x,
+ self.y,
+ self.z,
+ );
+ }
+ }
+}
+
+impl sealed::Sealed for Vec3<f32> {}
+
+impl UniformVariable for Matrix<f32, 4, 4>
+{
+ fn set(
+ &self,
+ current_context: &CurrentContextWithFns<'_>,
+ program: &Program,
+ uniform_location: UniformLocation,
+ )
+ {
+ unsafe {
+ current_context.fns().ProgramUniformMatrix4fv(
+ program.program,
+ uniform_location.0,
+ 1,
+ crate::sys::FALSE,
+ self.items.as_ptr().cast::<f32>(),
+ );
+ }
+ }
+}
+
+impl sealed::Sealed for Matrix<f32, 4, 4> {}
+
+#[derive(Debug)]
+pub struct UniformLocation(crate::sys::types::GLint);
+
+/// Shader error.
+#[derive(Debug, thiserror::Error)]
+pub enum Error
+{
+ #[error("All characters in source are not within the ASCII range")]
+ SourceNotAscii,
+
+ #[error("Source is too large. Length ({length}) must be < {max_length}")]
+ SourceTooLarge
+ {
+ length: usize, max_length: usize
+ },
+
+ #[error("Failed to compile shader")]
+ CompileFailed
+ {
+ log: String
+ },
+
+ #[error("Failed to link shader program")]
+ LinkFailed
+ {
+ log: String
+ },
+}
+
+mod sealed
+{
+ pub trait Sealed {}
+}
diff --git a/opengl-bindings/src/texture.rs b/opengl-bindings/src/texture.rs
new file mode 100644
index 0000000..1859beb
--- /dev/null
+++ b/opengl-bindings/src/texture.rs
@@ -0,0 +1,236 @@
+use crate::data_types::Dimens;
+use crate::CurrentContextWithFns;
+
+#[derive(Debug)]
+pub struct Texture
+{
+ texture: crate::sys::types::GLuint,
+}
+
+impl Texture
+{
+ #[must_use]
+ pub fn new(current_context: &CurrentContextWithFns<'_>) -> Self
+ {
+ let mut texture = crate::sys::types::GLuint::default();
+
+ unsafe {
+ current_context.fns().CreateTextures(
+ crate::sys::TEXTURE_2D,
+ 1,
+ &raw mut texture,
+ );
+ };
+
+ Self { texture }
+ }
+
+ pub fn bind_to_texture_unit(
+ &self,
+ current_context: &CurrentContextWithFns<'_>,
+ texture_unit: u32,
+ )
+ {
+ unsafe {
+ current_context
+ .fns()
+ .BindTextureUnit(texture_unit, self.texture);
+ }
+ }
+
+ /// Allocates the texture storage, stores pixel data & generates a mipmap.
+ ///
+ /// # Errors
+ /// Returns `Err` if any value in `size` does not fit into a `i32`.
+ pub fn generate(
+ &self,
+ current_context: &CurrentContextWithFns<'_>,
+ size: &Dimens<u32>,
+ data: &[u8],
+ pixel_data_format: PixelDataFormat,
+ ) -> Result<(), GenerateError>
+ {
+ let size = Dimens::<crate::sys::types::GLsizei> {
+ width: size.width.try_into().map_err(|_| {
+ GenerateError::SizeWidthValueTooLarge {
+ value: size.width,
+ max_value: crate::sys::types::GLsizei::MAX as u32,
+ }
+ })?,
+ height: size.height.try_into().map_err(|_| {
+ GenerateError::SizeHeightValueTooLarge {
+ value: size.height,
+ max_value: crate::sys::types::GLsizei::MAX as u32,
+ }
+ })?,
+ };
+
+ self.alloc_image(current_context, pixel_data_format, &size, data);
+
+ unsafe {
+ current_context.fns().GenerateTextureMipmap(self.texture);
+ }
+
+ Ok(())
+ }
+
+ pub fn set_wrap(
+ &self,
+ current_context: &CurrentContextWithFns<'_>,
+ wrapping: Wrapping,
+ )
+ {
+ unsafe {
+ current_context.fns().TextureParameteri(
+ self.texture,
+ crate::sys::TEXTURE_WRAP_S,
+ wrapping as i32,
+ );
+
+ current_context.fns().TextureParameteri(
+ self.texture,
+ crate::sys::TEXTURE_WRAP_T,
+ wrapping as i32,
+ );
+ }
+ }
+
+ pub fn set_magnifying_filter(
+ &self,
+ current_context: &CurrentContextWithFns<'_>,
+ filtering: Filtering,
+ )
+ {
+ unsafe {
+ current_context.fns().TextureParameteri(
+ self.texture,
+ crate::sys::TEXTURE_MAG_FILTER,
+ filtering as i32,
+ );
+ }
+ }
+
+ pub fn set_minifying_filter(
+ &self,
+ current_context: &CurrentContextWithFns<'_>,
+ filtering: Filtering,
+ )
+ {
+ unsafe {
+ current_context.fns().TextureParameteri(
+ self.texture,
+ crate::sys::TEXTURE_MIN_FILTER,
+ filtering as i32,
+ );
+ }
+ }
+
+ pub fn delete(self, current_context: &CurrentContextWithFns<'_>)
+ {
+ unsafe {
+ current_context
+ .fns()
+ .DeleteTextures(1, &raw const self.texture);
+ }
+ }
+
+ fn alloc_image(
+ &self,
+ current_context: &CurrentContextWithFns<'_>,
+ pixel_data_format: PixelDataFormat,
+ size: &Dimens<crate::sys::types::GLsizei>,
+ data: &[u8],
+ )
+ {
+ unsafe {
+ current_context.fns().TextureStorage2D(
+ self.texture,
+ 1,
+ pixel_data_format.to_sized_internal_format(),
+ size.width,
+ size.height,
+ );
+
+ current_context.fns().TextureSubImage2D(
+ self.texture,
+ 0,
+ 0,
+ 0,
+ size.width,
+ size.height,
+ pixel_data_format.to_format(),
+ crate::sys::UNSIGNED_BYTE,
+ data.as_ptr().cast(),
+ );
+ }
+ }
+}
+
+const fn try_cast_u32_to_i32(val: u32) -> i32
+{
+ assert!(val <= i32::MAX as u32);
+
+ val.cast_signed()
+}
+
+/// Texture wrapping.
+#[derive(Debug, Clone, Copy)]
+#[repr(i32)]
+pub enum Wrapping
+{
+ Repeat = const { try_cast_u32_to_i32(crate::sys::REPEAT) },
+ MirroredRepeat = const { try_cast_u32_to_i32(crate::sys::MIRRORED_REPEAT) },
+ ClampToEdge = const { try_cast_u32_to_i32(crate::sys::CLAMP_TO_EDGE) },
+ ClampToBorder = const { try_cast_u32_to_i32(crate::sys::CLAMP_TO_BORDER) },
+}
+
+#[derive(Debug, Clone, Copy)]
+#[repr(i32)]
+pub enum Filtering
+{
+ Nearest = const { try_cast_u32_to_i32(crate::sys::NEAREST) },
+ Linear = const { try_cast_u32_to_i32(crate::sys::LINEAR) },
+}
+
+/// Texture pixel data format.
+#[derive(Debug, Clone, Copy)]
+pub enum PixelDataFormat
+{
+ Rgb8,
+ Rgba8,
+}
+
+impl PixelDataFormat
+{
+ fn to_sized_internal_format(self) -> crate::sys::types::GLenum
+ {
+ match self {
+ Self::Rgb8 => crate::sys::RGB8,
+ Self::Rgba8 => crate::sys::RGBA8,
+ }
+ }
+
+ fn to_format(self) -> crate::sys::types::GLenum
+ {
+ match self {
+ Self::Rgb8 => crate::sys::RGB,
+ Self::Rgba8 => crate::sys::RGBA,
+ }
+ }
+}
+
+/// Error generating texture.
+#[derive(Debug, thiserror::Error)]
+pub enum GenerateError
+{
+ #[error("Size width value ({value}) is too large. Must be < {max_value}")]
+ SizeWidthValueTooLarge
+ {
+ value: u32, max_value: u32
+ },
+ #[error("Size height value ({value}) is too large. Must be < {max_value}")]
+ SizeHeightValueTooLarge
+ {
+ value: u32, max_value: u32
+ },
+}
diff --git a/opengl-bindings/src/vertex_array.rs b/opengl-bindings/src/vertex_array.rs
new file mode 100644
index 0000000..9942fe7
--- /dev/null
+++ b/opengl-bindings/src/vertex_array.rs
@@ -0,0 +1,260 @@
+use std::ffi::{c_int, c_void};
+use std::mem::size_of;
+
+use safer_ffi::layout::ReprC;
+
+use crate::buffer::Buffer;
+use crate::CurrentContextWithFns;
+
+#[derive(Debug)]
+pub struct VertexArray
+{
+ array: crate::sys::types::GLuint,
+}
+
+impl VertexArray
+{
+ #[must_use]
+ pub fn new(current_context: &CurrentContextWithFns<'_>) -> Self
+ {
+ let mut array = 0;
+
+ unsafe {
+ current_context.fns().CreateVertexArrays(1, &raw mut array);
+ }
+
+ Self { array }
+ }
+
+ /// Draws the currently bound vertex array.
+ ///
+ /// # Errors
+ /// Returns `Err` if:
+ /// - `start_index` is too large
+ /// - `cnt` is too large
+ pub fn draw_arrays(
+ current_context: &CurrentContextWithFns<'_>,
+ primitive_kind: PrimitiveKind,
+ start_index: u32,
+ cnt: u32,
+ ) -> Result<(), DrawError>
+ {
+ let start_index: crate::sys::types::GLint =
+ start_index
+ .try_into()
+ .map_err(|_| DrawError::StartIndexValueTooLarge {
+ value: start_index,
+ max_value: crate::sys::types::GLint::MAX as u32,
+ })?;
+
+ let cnt: crate::sys::types::GLsizei =
+ cnt.try_into().map_err(|_| DrawError::CountValueTooLarge {
+ value: cnt,
+ max_value: crate::sys::types::GLsizei::MAX as u32,
+ })?;
+
+ unsafe {
+ current_context
+ .fns()
+ .DrawArrays(primitive_kind.into_gl(), start_index, cnt);
+ }
+
+ Ok(())
+ }
+
+ /// Draws the currently bound vertex array.
+ ///
+ /// # Errors
+ /// Returns `Err` if `cnt` is too large.
+ pub fn draw_elements(
+ current_context: &CurrentContextWithFns<'_>,
+ primitive_kind: PrimitiveKind,
+ start_index: u32,
+ cnt: u32,
+ ) -> Result<(), DrawError>
+ {
+ let cnt: crate::sys::types::GLsizei =
+ cnt.try_into().map_err(|_| DrawError::CountValueTooLarge {
+ value: cnt,
+ max_value: crate::sys::types::GLsizei::MAX as u32,
+ })?;
+
+ unsafe {
+ current_context.fns().DrawElements(
+ primitive_kind.into_gl(),
+ cnt,
+ crate::sys::UNSIGNED_INT,
+ // TODO: Make this not sometimes UB. DrawElements expects a actual
+ // pointer to a memory location when no VBO is bound.
+ // See: https://stackoverflow.com/q/21706113
+ std::ptr::without_provenance::<c_void>(start_index as usize),
+ );
+ }
+
+ Ok(())
+ }
+
+ pub fn bind_element_buffer(
+ &self,
+ current_context: &CurrentContextWithFns<'_>,
+ element_buffer: &Buffer<u32>,
+ )
+ {
+ unsafe {
+ current_context
+ .fns()
+ .VertexArrayElementBuffer(self.array, element_buffer.object());
+ }
+ }
+
+ pub fn bind_vertex_buffer<VertexT: ReprC>(
+ &self,
+ current_context: &CurrentContextWithFns<'_>,
+ binding_index: u32,
+ vertex_buffer: &Buffer<VertexT>,
+ offset: isize,
+ )
+ {
+ let vertex_size = const { cast_usize_to_c_int(size_of::<VertexT>()) };
+
+ unsafe {
+ current_context.fns().VertexArrayVertexBuffer(
+ self.array,
+ binding_index,
+ vertex_buffer.object(),
+ offset,
+ vertex_size,
+ );
+ }
+ }
+
+ pub fn enable_attrib(
+ &self,
+ current_context: &CurrentContextWithFns<'_>,
+ attrib_index: u32,
+ )
+ {
+ unsafe {
+ current_context.fns().EnableVertexArrayAttrib(
+ self.array,
+ attrib_index as crate::sys::types::GLuint,
+ );
+ }
+ }
+
+ pub fn set_attrib_format(
+ &self,
+ current_context: &CurrentContextWithFns<'_>,
+ attrib_index: u32,
+ data_type: DataType,
+ normalized: bool,
+ offset: u32,
+ )
+ {
+ unsafe {
+ current_context.fns().VertexArrayAttribFormat(
+ self.array,
+ attrib_index,
+ data_type.size(),
+ data_type as u32,
+ if normalized {
+ crate::sys::TRUE
+ } else {
+ crate::sys::FALSE
+ },
+ offset,
+ );
+ }
+ }
+
+ /// Associate a vertex attribute and a vertex buffer binding.
+ pub fn set_attrib_vertex_buf_binding(
+ &self,
+ current_context: &CurrentContextWithFns<'_>,
+ attrib_index: u32,
+ vertex_buf_binding_index: u32,
+ )
+ {
+ unsafe {
+ current_context.fns().VertexArrayAttribBinding(
+ self.array,
+ attrib_index,
+ vertex_buf_binding_index,
+ );
+ }
+ }
+
+ pub fn bind(&self, current_context: &CurrentContextWithFns<'_>)
+ {
+ unsafe { current_context.fns().BindVertexArray(self.array) }
+ }
+}
+
+#[derive(Debug)]
+pub enum PrimitiveKind
+{
+ Triangles,
+}
+
+impl PrimitiveKind
+{
+ fn into_gl(self) -> crate::sys::types::GLenum
+ {
+ match self {
+ Self::Triangles => crate::sys::TRIANGLES,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy)]
+#[repr(u32)]
+pub enum DataType
+{
+ Float = crate::sys::FLOAT,
+}
+
+impl DataType
+{
+ fn size(self) -> crate::sys::types::GLint
+ {
+ match self {
+ Self::Float => const { cast_usize_to_c_int(size_of::<f32>()) },
+ }
+ }
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum DrawError
+{
+ #[error("Start index value {value} is too large. Must be < {max_value}")]
+ StartIndexValueTooLarge
+ {
+ value: u32, max_value: u32
+ },
+
+ #[error("Count value {value} is too large. Must be < {max_value}")]
+ CountValueTooLarge
+ {
+ value: u32, max_value: u32
+ },
+}
+
+const fn cast_usize_to_c_int(num: usize) -> c_int
+{
+ assert!(num <= c_int::MAX.cast_unsigned() as usize);
+
+ c_int::from_ne_bytes(shorten_byte_array(num.to_ne_bytes()))
+}
+
+const fn shorten_byte_array<const SRC_LEN: usize, const DST_LEN: usize>(
+ src: [u8; SRC_LEN],
+) -> [u8; DST_LEN]
+{
+ assert!(DST_LEN < SRC_LEN);
+
+ let mut ret = [0; DST_LEN];
+
+ ret.copy_from_slice(src.split_at(DST_LEN).0);
+
+ ret
+}
diff --git a/src/main.rs b/src/main.rs
index 1d0d33a..d5154ae 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,7 +1,7 @@
use std::error::Error;
-use std::fs::read_to_string;
use std::path::Path;
+use engine::asset::Assets;
use engine::camera::fly::{
Extension as FlyCameraExtension,
Fly as FlyCamera,
@@ -9,20 +9,20 @@ use engine::camera::fly::{
};
use engine::camera::{Active as ActiveCamera, Camera};
use engine::color::Color;
-use engine::data_types::dimens::Dimens;
+use engine::data_types::dimens::{Dimens, Dimens3};
+use engine::ecs::actions::Actions;
use engine::ecs::phase::START as START_PHASE;
use engine::ecs::sole::Single;
-use engine::file_format::wavefront::mtl::parse as parse_mtl;
-use engine::file_format::wavefront::obj::parse as parse_obj;
use engine::input::Extension as InputExtension;
use engine::lighting::{AttenuationParams, GlobalLight, PointLight};
-use engine::material::{Builder as MaterialBuilder, Flags as MaterialFlags};
+use engine::material::{Flags as MaterialFlags, Material};
use engine::mesh::cube::{
create as cube_mesh_create,
CreationSpec as CubeMeshCreationSpec,
};
+use engine::model::{Data as ModelData, Model};
use engine::renderer::opengl::Extension as OpenglRendererExtension;
-use engine::transform::Position;
+use engine::transform::WorldPosition;
use engine::vector::Vec3;
use engine::window::{
Builder as WindowBuilder,
@@ -59,53 +59,9 @@ fn main() -> Result<(), Box<dyn Error>>
let mut engine = Engine::new();
- let teapot_obj =
- parse_obj(&read_to_string(Path::new(RESOURCE_DIR).join("teapot.obj"))?)?;
-
- let teapot_mat_name = teapot_obj
- .faces
- .first()
- .and_then(|face| face.material_name.as_ref());
-
- let teapot_mats = teapot_obj.read_and_parse_material_libs(parse_mtl)?;
-
- let teapot_mat = teapot_mats
- .into_iter()
- .find(|mat| Some(&mat.name) == teapot_mat_name)
- .ok_or("Teapot material was not found")?;
-
- engine.spawn((
- teapot_obj.to_mesh()?,
- teapot_mat.material,
- Position::from(Vec3 { x: 1.6, y: 0.0, z: 0.0 }),
- ));
-
- engine.spawn((
- PointLight::builder()
- .position(Vec3 { x: -6.0, y: 3.0, z: 3.0 })
- .diffuse(YELLOW)
- .attenuation_params(AttenuationParams {
- linear: 0.045,
- quadratic: 0.0075,
- ..Default::default()
- })
- .build(),
- Position::from(Vec3 { x: -6.0, y: 3.0, z: 3.0 }),
- cube_mesh_create(
- CubeMeshCreationSpec::builder()
- .width(2.0)
- .height(2.0)
- .depth(2.0)
- .build(),
- |face_verts, _, _| face_verts,
- ),
- MaterialBuilder::new().ambient(YELLOW * 5.0).build(),
- MaterialFlags::builder().use_ambient_color(true).build(),
- ));
-
engine.spawn((
Camera::default(),
- Position {
+ WorldPosition {
position: Vec3 { x: 0.0, y: 0.0, z: 3.0 },
},
ActiveCamera,
@@ -114,7 +70,7 @@ fn main() -> Result<(), Box<dyn Error>>
engine.add_sole(GlobalLight::default())?;
- engine.register_system(*START_PHASE, prepare_window);
+ engine.register_system(*START_PHASE, init);
engine.add_extension(OpenglRendererExtension::default());
@@ -135,7 +91,42 @@ fn main() -> Result<(), Box<dyn Error>>
Ok(())
}
-fn prepare_window(window: Single<Window>)
+fn init(window: Single<Window>, mut assets: Single<Assets>, mut actions: Actions)
{
window.set_cursor_mode(CursorMode::Disabled).unwrap();
+
+ actions.spawn((
+ PointLight::builder()
+ .diffuse(YELLOW)
+ .attenuation_params(AttenuationParams {
+ linear: 0.045,
+ quadratic: 0.0075,
+ ..Default::default()
+ })
+ .build(),
+ WorldPosition::from(Vec3 { x: -6.0, y: 3.0, z: 3.0 }),
+ Model::new(
+ assets.store_with_name(
+ "light_cube",
+ ModelData::builder()
+ .mesh(cube_mesh_create(
+ CubeMeshCreationSpec::builder()
+ .dimens(Dimens3::from(2.0))
+ .build(),
+ |face_verts, _, _| face_verts,
+ ))
+ .material(
+ "surface",
+ Material::builder().ambient(YELLOW * 5.0).build(),
+ )
+ .build(),
+ ),
+ ),
+ MaterialFlags::builder().use_ambient_color(true).build(),
+ ));
+
+ actions.spawn((
+ Model::new(assets.load::<ModelData>(Path::new(RESOURCE_DIR).join("teapot.obj"))),
+ WorldPosition::from(Vec3 { x: 1.6, y: 0.0, z: 0.0 }),
+ ));
}