├── .gitignore ├── bors.toml ├── demos └── cubes │ ├── cube-ception.png │ ├── src │ ├── frag.glsl │ ├── vert.glsl │ └── main.rs │ ├── Cargo.toml │ └── README.md ├── .travis.yml ├── benches ├── bench_setup.rs ├── sc_graph_aligned.rs ├── sc_graph_spread.rs ├── ecs_pos_vel_aligned.rs └── ecs_pos_vel_spread.rs ├── examples ├── iter.rs ├── weak.rs └── cursor.rs ├── LICENSE-MIT ├── Cargo.toml ├── CHANGELOG.md ├── README.md ├── src ├── bitfield.rs ├── lib.rs ├── cursor.rs ├── pointer.rs └── storage.rs ├── tests └── tests.rs └── LICENSE-APACHE /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /bors.toml: -------------------------------------------------------------------------------- 1 | status = ["continuous-integration/travis-ci/push"] 2 | -------------------------------------------------------------------------------- /demos/cubes/cube-ception.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kvark/froggy/HEAD/demos/cubes/cube-ception.png -------------------------------------------------------------------------------- /demos/cubes/src/frag.glsl: -------------------------------------------------------------------------------- 1 | #version 150 core 2 | 3 | in vec4 v_Color; 4 | in vec3 v_Normal; 5 | in vec3 v_HalfDir; 6 | 7 | out vec4 Target0; 8 | 9 | void main() { 10 | float diffuse = max(0.0, dot(normalize(v_Normal), normalize(v_HalfDir))); 11 | Target0 = diffuse * v_Color; 12 | } 13 | -------------------------------------------------------------------------------- /demos/cubes/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "froggy_demo_cubes" 3 | version = "0.1.0" 4 | authors = ["Dzmitry Malyshau "] 5 | workspace = "../../" 6 | 7 | [dependencies] 8 | cgmath = "0.14" 9 | froggy = { path = "../../" } 10 | gfx = "0.16" 11 | gfx_window_glutin = "0.16" 12 | glutin = "0.8" 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - nightly 4 | - stable 5 | cache: cargo 6 | 7 | branches: 8 | only: 9 | - staging 10 | - trying 11 | - master 12 | 13 | notifications: 14 | webhooks: 15 | urls: 16 | - https://webhooks.gitter.im/e/0b69c3f09cd78b94d40d 17 | on_success: change 18 | on_failure: always 19 | on_start: never 20 | 21 | script: 22 | - cargo test --all 23 | -------------------------------------------------------------------------------- /benches/bench_setup.rs: -------------------------------------------------------------------------------- 1 | use froggy::Pointer; 2 | 3 | /// Entities with velocity and position component. 4 | pub const N_POS_VEL: usize = 5_000; 5 | 6 | /// Entities with position component only. 7 | pub const N_POS: usize = 15_000; 8 | 9 | pub struct Position { 10 | pub x: f32, 11 | pub y: f32, 12 | } 13 | 14 | #[allow(dead_code)] 15 | pub struct Velocity { 16 | pub dx: f32, 17 | pub dy: f32, 18 | pub writes: Pointer, 19 | } 20 | -------------------------------------------------------------------------------- /demos/cubes/README.md: -------------------------------------------------------------------------------- 1 | screenshot 2 | 3 | This demo shows a simple recursive animated cube. Aside from stealing hours of staring at it, the code can showcase a few concepts: 4 | 5 | - Creating multiple `froggy::Storage` containers and processing them on the same thread. 6 | - Working with a scene graph mapped to _froggy_. 7 | - Drawing fancy cubes with _gfx-rs_ instancing. It uses glutin/GL and even handles resizing properly. 8 | - Composing `cgmath::Decomposed` transforms and working with quaternions in the shaders. 9 | -------------------------------------------------------------------------------- /examples/iter.rs: -------------------------------------------------------------------------------- 1 | extern crate froggy; 2 | 3 | fn main() { 4 | let mut storage: froggy::Storage = [5, 7, 4, 6, 7].iter().cloned().collect(); 5 | println!("Initial array:"); 6 | for value in storage.iter_all() { 7 | println!("Value {}", *value); 8 | } 9 | let ptr = { 10 | let item = storage.iter_all().find(|v| **v == 4).unwrap(); 11 | storage.pin(&item) 12 | }; 13 | storage[&ptr] = 350; 14 | println!("Array after change:"); 15 | for value in storage.iter_all() { 16 | println!("Value {}", *value); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /demos/cubes/src/vert.glsl: -------------------------------------------------------------------------------- 1 | #version 150 core 2 | 3 | vec3 rotate_vector(vec4 quat, vec3 vec) { 4 | return vec + 2.0 * cross(cross(vec, quat.xyz) - quat.w * vec, quat.xyz); 5 | } 6 | 7 | in vec4 a_Pos; 8 | in ivec4 a_Normal; 9 | in vec4 a_OffsetScale; 10 | in vec4 a_Rotation; 11 | in vec4 a_Color; 12 | 13 | out vec4 v_Color; 14 | out vec3 v_Normal; 15 | out vec3 v_HalfDir; 16 | 17 | uniform b_Globals { 18 | mat4 u_Projection; 19 | vec4 u_CameraPos; 20 | vec4 u_LightPos; 21 | vec4 u_LightColor; 22 | }; 23 | 24 | void main() { 25 | v_Color = a_Color * u_LightColor; 26 | v_Normal = rotate_vector(a_Rotation, vec3(a_Normal.xyz)); 27 | vec3 world_pos = rotate_vector(a_Rotation, a_Pos.xyz) * a_OffsetScale.w + a_OffsetScale.xyz; 28 | vec3 light_dir = normalize(u_LightPos.xyz - world_pos); 29 | vec3 camera_dir = normalize(u_CameraPos.xyz - world_pos); 30 | v_HalfDir = normalize(light_dir + camera_dir); 31 | gl_Position = u_Projection * vec4(world_pos, 1.0); 32 | } 33 | -------------------------------------------------------------------------------- /examples/weak.rs: -------------------------------------------------------------------------------- 1 | extern crate froggy; 2 | use froggy::{Storage, WeakPointer}; 3 | 4 | struct Node { 5 | value: String, 6 | next: Option>, 7 | } 8 | 9 | impl Drop for Node { 10 | fn drop(&mut self) { 11 | println!("{} destroyed", &self.value); 12 | } 13 | } 14 | 15 | fn main() { 16 | let mut storage = Storage::new(); 17 | let node1 = storage.create(Node { 18 | value: "Node 1".to_string(), 19 | next: None, 20 | }); 21 | let node2 = storage.create(Node { 22 | value: "Node 2".to_string(), 23 | next: None, 24 | }); 25 | 26 | storage[&node1].next = Some(node2.downgrade()); 27 | storage[&node2].next = Some(node1.downgrade()); 28 | 29 | for node in &storage { 30 | let value = node.next.as_ref().map_or("None".into(), |next| { 31 | let ptr = next.upgrade().unwrap(); 32 | storage[&ptr].value.clone() 33 | }); 34 | println!("{} has `next` field with value {}", node.value, value); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017 Dzmitry Malyshau 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /examples/cursor.rs: -------------------------------------------------------------------------------- 1 | extern crate froggy; 2 | 3 | struct Fibbo { 4 | prev: Vec>, 5 | value: i32, 6 | } 7 | 8 | fn main() { 9 | let mut storage = froggy::Storage::new(); 10 | // initialize the first two Fibbo numbers 11 | let mut first = storage.create(Fibbo { 12 | prev: Vec::new(), 13 | value: 1, 14 | }); 15 | let mut second = storage.create(Fibbo { 16 | prev: vec![first.clone()], 17 | value: 0, 18 | }); 19 | // initialize the other ones 20 | for _ in 0..10 { 21 | let next = storage.create(Fibbo { 22 | prev: vec![first, second.clone()], 23 | value: 0, 24 | }); 25 | first = second; 26 | second = next; 27 | } 28 | // compute them with look-back 29 | let mut cursor = storage.cursor(); 30 | cursor.next().unwrap(); //skip first 31 | while let Some((left, mut item, _)) = cursor.next() { 32 | item.value = item 33 | .prev 34 | .iter() 35 | .map(|prev| left.get(prev).unwrap().value) 36 | .sum(); 37 | println!("{}", item.value); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "froggy" 3 | version = "0.4.4" 4 | # Attention: when modifying, also modify html_root_url in lib.rs 5 | authors = ["Dzmitry Malyshau ", 6 | "Ilya Bogdanov ", 7 | "Anton Makarow "] 8 | documentation = "https://docs.rs/froggy/" 9 | repository = "https://github.com/kvark/froggy" 10 | keywords = ["gamedev", "ecs"] 11 | license = "MIT/Apache-2.0" 12 | categories = ["data-structures"] 13 | exclude = ["doc", "bors.toml", ".travis.yml"] 14 | description = """ 15 | Froggy is a prototype for the Component Graph System programming model. 16 | It aims to combine the convenience of composition-style Object-Oriented Programming 17 | with the performance close to Entity-Component Systems. 18 | """ 19 | readme = "README.md" 20 | edition = "2018" 21 | 22 | [workspace] 23 | members = ["demos/cubes"] 24 | 25 | [dependencies] 26 | spin = { version="0.5", default-features=false } 27 | 28 | [dev-dependencies] 29 | criterion = "0.2" 30 | 31 | [[bench]] 32 | name = "ecs_pos_vel_aligned" 33 | harness = false 34 | 35 | [[bench]] 36 | name = "ecs_pos_vel_spread" 37 | harness = false 38 | 39 | [[bench]] 40 | name = "sc_graph_aligned" 41 | harness = false 42 | 43 | [[bench]] 44 | name = "sc_graph_spread" 45 | harness = false 46 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## Change Log 2 | 3 | ### v0.4 (2017-08-28) 4 | - crate now follows almost all points from Rust API Guidelines ([#52](https://github.com/kvark/froggy/pull/52) [#62](https://github.com/kvark/froggy/pull/62)) 5 | - `iter` and `iter_mut` methods now return only alive components ([#55](https://github.com/kvark/froggy/pull/55)) 6 | - Cursor concept has been changed a lot to provide more power ([#58](https://github.com/kvark/froggy/pull/58) [#59](https://github.com/kvark/froggy/pull/59) [#60](https://github.com/kvark/froggy/pull/60)) 7 | - serious bug on 32-bit machines has been fixed ([#64](https://github.com/kvark/froggy/pull/64)) 8 | 9 | ### v0.3 (2017-05-15) 10 | - removed storage locks ([#32](https://github.com/kvark/froggy/pull/32) [#33](https://github.com/kvark/froggy/pull/33)) 11 | - optimized epoch initialization ([#37](https://github.com/kvark/froggy/pull/37)) 12 | - implemented `FromIterator` and `IntoIterator` ([#39](https://github.com/kvark/froggy/pull/39)) 13 | - got internal benchmarks ([#36](https://github.com/kvark/froggy/pull/36)) 14 | - compacted pointer data ([#40](https://github.com/kvark/froggy/pull/40)) 15 | 16 | ### v0.2 (2017-05-12) 17 | - fast index operators ([#18](https://github.com/kvark/froggy/pull/18)) 18 | - weak pointers ([#14](https://github.com/kvark/froggy/pull/14)) 19 | - storage iterators ([#12](https://github.com/kvark/froggy/pull/12)) 20 | - cube-ception demo ([#1](https://github.com/kvark/froggy/pull/1)) 21 | 22 | ### v0.1 (2017-02-11) 23 | - basic component pointers 24 | - read/write storage locking 25 | - slice dereferences and index pinning 26 | - deferred refcount updates 27 | -------------------------------------------------------------------------------- /benches/sc_graph_aligned.rs: -------------------------------------------------------------------------------- 1 | use criterion::{criterion_group, criterion_main, Criterion}; 2 | use froggy::{Pointer, Storage}; 3 | 4 | mod bench_setup; 5 | use bench_setup::{Position, Velocity, N_POS, N_POS_VEL}; 6 | 7 | struct Movement { 8 | pub vel_comp: Vec>, 9 | } 10 | 11 | struct World { 12 | pub pos: Storage, 13 | pub vel: Storage, 14 | pub movement: Movement, 15 | } 16 | 17 | fn build() -> World { 18 | let mut world = World { 19 | pos: Storage::with_capacity(N_POS_VEL + N_POS), 20 | vel: Storage::with_capacity(N_POS_VEL), 21 | movement: Movement { 22 | vel_comp: Vec::new(), 23 | }, 24 | }; 25 | 26 | { 27 | for _ in 0..N_POS_VEL { 28 | let pos_ptr = world.pos.create(Position { x: 0.0, y: 0.0 }); 29 | let v = Velocity { 30 | dx: 0.0, 31 | dy: 0.0, 32 | writes: pos_ptr, 33 | }; 34 | world.movement.vel_comp.push(world.vel.create(v)); 35 | } 36 | 37 | for _ in 0..N_POS { 38 | world.pos.create(Position { x: 0.0, y: 0.0 }); 39 | } 40 | } 41 | 42 | world 43 | } 44 | 45 | fn bench_build(c: &mut Criterion) { 46 | c.bench_function("build-graph-aligned", |b| b.iter(|| build())); 47 | } 48 | 49 | fn bench_update(c: &mut Criterion) { 50 | let mut world = build(); 51 | 52 | c.bench_function("update-graph-aligned", move |b| { 53 | b.iter(|| { 54 | for vel in world.vel.iter() { 55 | let mut p = &mut world.pos[&vel.writes]; 56 | p.x += vel.dx; 57 | p.y += vel.dy; 58 | } 59 | }) 60 | }); 61 | } 62 | 63 | criterion_group!(benches, bench_build, bench_update); 64 | criterion_main!(benches); 65 | -------------------------------------------------------------------------------- /benches/sc_graph_spread.rs: -------------------------------------------------------------------------------- 1 | use criterion::{criterion_group, criterion_main, Criterion}; 2 | use froggy::{Pointer, Storage}; 3 | 4 | mod bench_setup; 5 | use bench_setup::{Position, Velocity, N_POS, N_POS_VEL}; 6 | 7 | struct Movement { 8 | pub vel_comp: Vec>, 9 | } 10 | 11 | struct World { 12 | pub pos: Storage, 13 | pub vel: Storage, 14 | pub movement: Movement, 15 | } 16 | 17 | fn build() -> World { 18 | let mut world = World { 19 | pos: Storage::with_capacity(N_POS_VEL + N_POS), 20 | vel: Storage::with_capacity(N_POS_VEL), 21 | movement: Movement { 22 | vel_comp: Vec::new(), 23 | }, 24 | }; 25 | 26 | { 27 | let pos_spread = (N_POS + N_POS_VEL) / N_POS_VEL; 28 | 29 | for fx in 1..(N_POS_VEL + N_POS + 1) { 30 | let pos_ptr = world.pos.create(Position { x: 0.0, y: 0.0 }); 31 | 32 | if fx % pos_spread == 0 { 33 | let v = Velocity { 34 | dx: 0.0, 35 | dy: 0.0, 36 | writes: pos_ptr, 37 | }; 38 | world.movement.vel_comp.push(world.vel.create(v)); 39 | } 40 | } 41 | } 42 | 43 | world 44 | } 45 | 46 | fn bench_build(c: &mut Criterion) { 47 | c.bench_function("build-graph-spread", |b| b.iter(|| build())); 48 | } 49 | 50 | fn bench_update(c: &mut Criterion) { 51 | let mut world = build(); 52 | 53 | c.bench_function("update-graph-spread", move |b| { 54 | b.iter(|| { 55 | for vel in world.vel.iter() { 56 | let mut p = &mut world.pos[&vel.writes]; 57 | p.x += vel.dx; 58 | p.y += vel.dy; 59 | } 60 | }) 61 | }); 62 | } 63 | 64 | criterion_group!(benches, bench_build, bench_update); 65 | criterion_main!(benches); 66 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # froggy 2 | [![Build Status](https://travis-ci.org/kvark/froggy.svg?branch=master)](https://travis-ci.org/kvark/froggy) 3 | [![Docs](https://docs.rs/froggy/badge.svg)](https://docs.rs/froggy) 4 | [![Crates.io](https://img.shields.io/crates/v/froggy.svg)](https://crates.io/crates/froggy) 5 | [![Gitter](https://badges.gitter.im/kvark/froggy.svg)](https://gitter.im/almost-ecs/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) 6 | 7 | Froggy is a prototype for [Component Graph System](https://github.com/kvark/froggy/wiki/Component-Graph-System). Froggy is not an ECS (it could as well be named "finecs" but then it would have "ecs" in the name... yikes)! Give it a try if: 8 | - you are open to new paradigms and programming models 9 | - you are tired of being forced to think in terms of ECS 10 | - you like simple composable things 11 | 12 | Check [ecs_bench](https://github.com/lschmierer/ecs_bench) for performance comparisons with actual ECS systems. 13 | 14 | ## Example 15 | 16 | ```rust 17 | extern crate froggy; 18 | 19 | fn main() { 20 | let mut positions = froggy::Storage::new(); 21 | // create entities 22 | let entities = vec![ 23 | positions.create(1u8), positions.create(4u8), positions.create(9u8) 24 | ]; 25 | // update positions 26 | for e in &entities { 27 | positions[e] += 1; 28 | } 29 | } 30 | ``` 31 | ## License 32 | 33 | Licensed under either of 34 | 35 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 36 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 37 | 38 | at your option. 39 | 40 | ### Contribution 41 | 42 | Unless you explicitly state otherwise, any contribution intentionally submitted 43 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 44 | dual licensed as above, without any additional terms or conditions. 45 | -------------------------------------------------------------------------------- /benches/ecs_pos_vel_aligned.rs: -------------------------------------------------------------------------------- 1 | use criterion::{criterion_group, criterion_main, Criterion}; 2 | use froggy::{Pointer, Storage}; 3 | 4 | mod bench_setup; 5 | use bench_setup::{Position, N_POS, N_POS_VEL}; 6 | 7 | // Since component linking is not used in this bench, 8 | // it has a custom Velocity component 9 | struct Velocity { 10 | pub dx: f32, 11 | pub dy: f32, 12 | } 13 | 14 | struct Entity { 15 | pos: Pointer, 16 | vel: Option>, 17 | } 18 | 19 | struct World { 20 | pos: Storage, 21 | vel: Storage, 22 | entities: Vec, 23 | } 24 | 25 | fn build() -> World { 26 | let mut world = World { 27 | pos: Storage::with_capacity(N_POS_VEL + N_POS), 28 | vel: Storage::with_capacity(N_POS_VEL), 29 | entities: Vec::with_capacity(N_POS_VEL + N_POS), 30 | }; 31 | 32 | // setup entities 33 | { 34 | for _ in 0..N_POS_VEL { 35 | world.entities.push(Entity { 36 | pos: world.pos.create(Position { x: 0.0, y: 0.0 }), 37 | vel: Some(world.vel.create(Velocity { dx: 0.0, dy: 0.0 })), 38 | }); 39 | } 40 | for _ in 0..N_POS { 41 | world.entities.push(Entity { 42 | pos: world.pos.create(Position { x: 0.0, y: 0.0 }), 43 | vel: None, 44 | }); 45 | } 46 | } 47 | 48 | world 49 | } 50 | 51 | fn bench_build(c: &mut Criterion) { 52 | c.bench_function("build-ecs-aligned", |b| b.iter(|| build())); 53 | } 54 | 55 | fn bench_update(c: &mut Criterion) { 56 | let mut world = build(); 57 | 58 | c.bench_function("update-ecs-aligned", move |b| { 59 | b.iter(|| { 60 | for e in &world.entities { 61 | if let Some(ref vel) = e.vel { 62 | let mut p = &mut world.pos[&e.pos]; 63 | let v = &world.vel[vel]; 64 | p.x += v.dx; 65 | p.y += v.dy; 66 | } 67 | } 68 | }) 69 | }); 70 | } 71 | 72 | criterion_group!(benches, bench_build, bench_update); 73 | criterion_main!(benches); 74 | -------------------------------------------------------------------------------- /benches/ecs_pos_vel_spread.rs: -------------------------------------------------------------------------------- 1 | use criterion::{criterion_group, criterion_main, Criterion}; 2 | use froggy::{Pointer, Storage}; 3 | 4 | mod bench_setup; 5 | use bench_setup::{Position, N_POS, N_POS_VEL}; 6 | 7 | // Since component linking is not used in this bench, 8 | // it has a custom Velocity component 9 | struct Velocity { 10 | pub dx: f32, 11 | pub dy: f32, 12 | } 13 | 14 | struct Entity { 15 | pos: Pointer, 16 | vel: Option>, 17 | } 18 | 19 | struct World { 20 | pos: Storage, 21 | vel: Storage, 22 | entities: Vec, 23 | } 24 | 25 | fn build() -> World { 26 | let mut world = World { 27 | pos: Storage::with_capacity(N_POS_VEL + N_POS), 28 | vel: Storage::with_capacity(N_POS_VEL), 29 | entities: Vec::with_capacity(N_POS_VEL + N_POS), 30 | }; 31 | 32 | // setup entities 33 | { 34 | let pos_spread = (N_POS + N_POS_VEL) / N_POS_VEL; 35 | 36 | for fx in 1..(N_POS_VEL + N_POS + 1) { 37 | world.entities.push(Entity { 38 | pos: world.pos.create(Position { x: 0.0, y: 0.0 }), 39 | vel: None, 40 | }); 41 | if fx % pos_spread == 0 { 42 | world.entities.push(Entity { 43 | pos: world.pos.create(Position { x: 0.0, y: 0.0 }), 44 | vel: Some(world.vel.create(Velocity { dx: 0.0, dy: 0.0 })), 45 | }); 46 | } 47 | } 48 | } 49 | 50 | world 51 | } 52 | 53 | fn bench_build(c: &mut Criterion) { 54 | c.bench_function("build-ecs-spread", |b| b.iter(|| build())); 55 | } 56 | 57 | fn bench_update(c: &mut Criterion) { 58 | let mut world = build(); 59 | 60 | c.bench_function("update-ecs-spread", move |b| { 61 | b.iter(|| { 62 | for e in &world.entities { 63 | if let Some(ref vel) = e.vel { 64 | let mut p = &mut world.pos[&e.pos]; 65 | let v = &world.vel[vel]; 66 | p.x += v.dx; 67 | p.y += v.dy; 68 | } 69 | } 70 | }) 71 | }); 72 | } 73 | 74 | criterion_group!(benches, bench_build, bench_update); 75 | criterion_main!(benches); 76 | -------------------------------------------------------------------------------- /src/bitfield.rs: -------------------------------------------------------------------------------- 1 | use crate::{Epoch, Index, StorageId}; 2 | 3 | #[derive(Copy, Clone, Debug, PartialEq, Hash)] 4 | pub(crate) struct PointerData(u64); 5 | 6 | #[cfg(target_pointer_width = "32")] 7 | const INDEX_BITS: u8 = 20; 8 | #[cfg(target_pointer_width = "32")] 9 | const EPOCH_BITS: u8 = 8; 10 | #[cfg(target_pointer_width = "32")] 11 | const STORAGE_ID_BITS: u8 = 4; 12 | 13 | #[cfg(target_pointer_width = "64")] 14 | const INDEX_BITS: u8 = 40; 15 | #[cfg(target_pointer_width = "64")] 16 | const EPOCH_BITS: u8 = 16; 17 | #[cfg(target_pointer_width = "64")] 18 | const STORAGE_ID_BITS: u8 = 8; 19 | 20 | const INDEX_MASK: u64 = (1 << INDEX_BITS) - 1; 21 | const EPOCH_OFFSET: u8 = INDEX_BITS; 22 | const EPOCH_MASK: u64 = ((1 << EPOCH_BITS) - 1) << EPOCH_OFFSET; 23 | const STORAGE_ID_OFFSET: u8 = EPOCH_OFFSET + EPOCH_BITS; 24 | const STORAGE_ID_MASK: u64 = ((1 << STORAGE_ID_BITS) - 1) << STORAGE_ID_OFFSET; 25 | 26 | impl PointerData { 27 | #[inline] 28 | pub fn new(index: Index, epoch: Epoch, storage: StorageId) -> Self { 29 | debug_assert_eq!(index >> INDEX_BITS, 0); 30 | PointerData( 31 | index as u64 32 | + ((u64::from(epoch)) << EPOCH_OFFSET) 33 | + ((u64::from(storage)) << STORAGE_ID_OFFSET), 34 | ) 35 | } 36 | 37 | #[inline] 38 | pub fn get_index(self) -> Index { 39 | (self.0 & INDEX_MASK) as Index 40 | } 41 | 42 | #[inline] 43 | pub fn get_epoch(self) -> Epoch { 44 | ((self.0 & EPOCH_MASK) >> EPOCH_OFFSET) as Epoch 45 | } 46 | 47 | #[inline] 48 | pub fn get_storage_id(self) -> StorageId { 49 | ((self.0 & STORAGE_ID_MASK) >> STORAGE_ID_OFFSET) as StorageId 50 | } 51 | 52 | #[inline] 53 | pub fn with_epoch(self, epoch: Epoch) -> PointerData { 54 | PointerData((self.0 & !EPOCH_MASK) + ((u64::from(epoch)) << EPOCH_OFFSET)) 55 | } 56 | } 57 | 58 | #[cfg(test)] 59 | mod tests { 60 | use super::*; 61 | use std::mem::size_of; 62 | 63 | #[test] 64 | fn sizes() { 65 | #[cfg(target_pointer_width = "32")] 66 | assert_eq!(INDEX_BITS + EPOCH_BITS + STORAGE_ID_BITS, 32); 67 | #[cfg(target_pointer_width = "64")] 68 | assert_eq!(INDEX_BITS + EPOCH_BITS + STORAGE_ID_BITS, 64); 69 | assert!(size_of::() * 8 >= INDEX_BITS as usize); 70 | assert!(size_of::() * 8 >= EPOCH_BITS as usize); 71 | assert!(size_of::() * 8 >= STORAGE_ID_BITS as usize); 72 | } 73 | 74 | #[test] 75 | fn new() { 76 | let pd = PointerData::new(1, 2, 3); 77 | assert_eq!(pd.get_index(), 1); 78 | assert_eq!(pd.get_epoch(), 2); 79 | assert_eq!(pd.get_storage_id(), 3); 80 | assert_eq!(pd.with_epoch(5).get_epoch(), 5); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | /*! 2 | Component Graph System prototype. 3 | 4 | Froggy is all about the smart component storage, unambiguously called `Storage`. 5 | Components inside it are automatically reference-counted, and could be referenced by a `Pointer`. 6 | The components are stored linearly, allowing for the efficient bulk data processing. 7 | `Storage` has to be locked temporarily for either read or write before any usage. 8 | 9 | You can find more information about Component Graph System concept on the [wiki](https://github.com/kvark/froggy/wiki/Component-Graph-System). 10 | Comparing to Entity-Component Systems (ECS), CGS doesn't have the backwards relation of components to entities. 11 | Thus, it can't process all "entities" by just selecting a subset of components to work on, besides not having the whole "entity" concept. 12 | However, CGS has a number of advantages: 13 | 14 | - you can share components naturally 15 | - you don't need to care about the component lifetime, it is managed automatically 16 | - you can have deeper hierarchies of components, with one component referencing the others 17 | - you can have user structures referencing components freely 18 | - there are no restrictions on the component types, and no need to implement any traits 19 | 20 | */ 21 | #![warn(missing_docs)] 22 | #![doc(html_root_url = "https://docs.rs/froggy/0.4.4")] 23 | 24 | use spin::Mutex; 25 | use std::{ 26 | sync::{atomic::AtomicUsize, Arc}, 27 | vec::Drain, 28 | }; 29 | 30 | mod bitfield; 31 | mod cursor; 32 | mod pointer; 33 | mod storage; 34 | 35 | use crate::bitfield::PointerData; 36 | use crate::storage::StorageInner; 37 | 38 | pub use crate::cursor::{Cursor, CursorItem, Slice}; 39 | pub use crate::pointer::{DeadComponentError, Pointer, WeakPointer}; 40 | pub use crate::storage::{Item, Iter, IterMut, Storage}; 41 | 42 | type Index = usize; 43 | 44 | /// Reference counter type. It doesn't make sense to allocate too much bit for it in regular applications. 45 | // TODO: control by a cargo feature 46 | type RefCount = u16; 47 | 48 | /// Epoch type determines the number of overwrites of components in storage. 49 | // TODO: control by a cargo feature 50 | type Epoch = u16; 51 | 52 | type StorageId = u8; 53 | static STORAGE_UID: AtomicUsize = AtomicUsize::new(0); 54 | 55 | /// Pending reference counts updates. 56 | #[derive(Debug)] 57 | struct Pending { 58 | add_ref: Vec, 59 | sub_ref: Vec, 60 | epoch: Vec, 61 | } 62 | 63 | impl Pending { 64 | #[inline] 65 | fn drain_sub(&mut self) -> (Drain, &mut [Epoch]) { 66 | (self.sub_ref.drain(..), self.epoch.as_mut_slice()) 67 | } 68 | 69 | #[inline] 70 | fn get_epoch(&self, index: usize) -> Epoch { 71 | *self.epoch.get(index).unwrap_or(&0) 72 | } 73 | } 74 | 75 | /// Shared pointer to the pending updates. 76 | type PendingRef = Arc>; 77 | -------------------------------------------------------------------------------- /tests/tests.rs: -------------------------------------------------------------------------------- 1 | use froggy::{Pointer, Storage, WeakPointer}; 2 | 3 | #[test] 4 | fn sizes() { 5 | use std::mem::size_of; 6 | assert_eq!(size_of::>(), 16); 7 | assert_eq!(size_of::>>(), 16); 8 | } 9 | 10 | #[test] 11 | fn change_by_pointer() { 12 | let mut storage = Storage::new(); 13 | storage.create(4 as i32); 14 | let ptr = { 15 | let item = storage.iter().next().unwrap(); 16 | storage.pin(&item) 17 | }; 18 | assert_eq!(storage[&ptr], 4); 19 | storage[&ptr] = 350 as i32; 20 | assert_eq!(storage[&ptr], 350); 21 | } 22 | 23 | #[test] 24 | fn iterating() { 25 | let storage: Storage<_> = [5 as i32, 7, 4, 6, 7].iter().cloned().collect(); 26 | assert_eq!(storage.iter_all().count(), 5); 27 | assert_eq!(*storage.iter_all().nth(0).unwrap(), 5); 28 | assert_eq!(*storage.iter_all().nth(1).unwrap(), 7); 29 | assert!(storage.iter_all().any(|v| *v == 4)); 30 | } 31 | 32 | #[test] 33 | fn iter_zombies() { 34 | let storage: Storage<_> = (0..5).map(|i| i * 3 as i32).collect(); 35 | assert_eq!(storage.iter().count(), 0); 36 | assert_eq!(storage.iter_all().count(), 5); 37 | } 38 | 39 | #[test] 40 | fn weak_upgrade_downgrade() { 41 | let mut storage = Storage::new(); 42 | let ptr = storage.create(1 as i32); 43 | let weak = ptr.downgrade(); 44 | assert_eq!(weak.upgrade().is_ok(), true); 45 | } 46 | 47 | #[test] 48 | fn weak_epoch() { 49 | let mut storage = Storage::new(); 50 | let weak = { 51 | let node1 = storage.create(1 as i32); 52 | assert_eq!(storage.iter().count(), 1); 53 | node1.downgrade() 54 | }; 55 | storage.sync_pending(); 56 | assert_eq!(storage.iter_mut().count(), 0); 57 | assert_eq!(weak.upgrade(), Err(froggy::DeadComponentError)); 58 | let _ptr = storage.create(1 as i32); 59 | storage.sync_pending(); 60 | assert_eq!(storage.iter_mut().count(), 1); 61 | assert_eq!(weak.upgrade(), Err(froggy::DeadComponentError)); 62 | } 63 | 64 | #[test] 65 | fn cursor() { 66 | let data = vec![5 as i32, 7, 4, 6, 7]; 67 | let mut storage: Storage<_> = data.iter().cloned().collect(); 68 | 69 | let mut cursor = storage.cursor(); 70 | let mut iter = data.iter(); 71 | while let Some((_, item, _)) = cursor.next() { 72 | assert_eq!(iter.next(), Some(&*item)); 73 | let _ptr = item.pin(); 74 | } 75 | 76 | while let Some((_, item, _)) = cursor.prev() { 77 | assert_eq!(iter.next_back(), Some(&*item)); 78 | } 79 | } 80 | 81 | #[test] 82 | fn partial_ord() { 83 | use std::cmp::Ordering; 84 | let mut storage = Storage::new(); 85 | let a = storage.create(1u32); 86 | let b = storage.create(1u32); 87 | let c = storage.create(1u32); 88 | assert_eq!(a.partial_cmp(&b), Some(Ordering::Less)); 89 | assert_eq!(c.partial_cmp(&b), Some(Ordering::Greater)); 90 | let a2 = storage.pin(&storage.iter().next().unwrap()); 91 | assert_eq!(a.partial_cmp(&a2), Some(Ordering::Equal)); 92 | let mut storage2 = Storage::new(); 93 | let a3 = storage2.create(1u32); 94 | // Different storages 95 | assert_eq!(a.partial_cmp(&a3), None); 96 | } 97 | 98 | #[test] 99 | fn slice() { 100 | let mut storage = Storage::new(); 101 | let a = storage.create(1u32); 102 | let b = storage.create(2u32); 103 | let c = storage.create(3u32); 104 | let (left, mid, right) = storage.split(&b); 105 | assert_eq!(*mid, 2); 106 | assert_eq!(left.get(&a), Some(&1)); 107 | assert_eq!(right.get(&c), Some(&3)); 108 | assert!(left.get(&b).is_none() && left.get(&c).is_none()); 109 | assert!(right.get(&a).is_none() && right.get(&b).is_none()); 110 | } 111 | 112 | #[test] 113 | fn storage_default() { 114 | let mut storage = Storage::default(); 115 | storage.create(1u32); 116 | } 117 | 118 | #[test] 119 | fn pointer_eq() { 120 | let mut storage = Storage::new(); 121 | storage.create(1u32); 122 | storage.create(2u32); 123 | let ptr1 = storage.pin(&storage.iter().next().unwrap()); 124 | let ptr2 = storage.pin(&storage.iter().nth(1).unwrap()); 125 | let ptr3 = storage.pin(&storage.iter().nth(1).unwrap()); 126 | // PartialEq 127 | assert_eq!(ptr2, ptr3); 128 | assert_ne!(ptr1, ptr2); 129 | assert_ne!(ptr1, ptr3); 130 | // Reflexive 131 | assert_eq!(ptr1, ptr1); 132 | assert_eq!(ptr2, ptr2.clone()); 133 | } 134 | 135 | #[test] 136 | fn weak_pointer_eq() { 137 | let mut storage = Storage::new(); 138 | storage.create(1u32); 139 | storage.create(2u32); 140 | let weak_ptr1 = storage.pin(&storage.iter().next().unwrap()).downgrade(); 141 | let ptr2 = storage.pin(&storage.iter().nth(1).unwrap()); 142 | let weak_ptr2 = ptr2.downgrade(); 143 | let weak_ptr3 = ptr2.downgrade(); 144 | // PartialEq 145 | assert_eq!(weak_ptr2, weak_ptr3); 146 | assert_ne!(weak_ptr1, weak_ptr2); 147 | assert_ne!(weak_ptr1, weak_ptr3); 148 | // Reflexive 149 | assert_eq!(weak_ptr1, weak_ptr1); 150 | assert_eq!(weak_ptr2, weak_ptr2.clone()); 151 | assert_eq!(weak_ptr3.upgrade().unwrap(), weak_ptr2.upgrade().unwrap()); 152 | } 153 | 154 | #[test] 155 | fn test_send() { 156 | fn assert_send() {} 157 | assert_send::>(); 158 | assert_send::>(); 159 | assert_send::>(); 160 | assert_send::(); 161 | } 162 | 163 | #[test] 164 | fn test_sync() { 165 | fn assert_sync() {} 166 | assert_sync::>(); 167 | assert_sync::>(); 168 | assert_sync::>(); 169 | assert_sync::(); 170 | } 171 | 172 | #[test] 173 | fn test_hash() { 174 | use std::collections::HashMap; 175 | let mut hash_map = HashMap::new(); 176 | let mut storage = Storage::new(); 177 | let ptr = storage.create(1u8); 178 | hash_map.insert(ptr.clone(), 23u8); 179 | assert_eq!(hash_map.get(&ptr), Some(&23u8)); 180 | } 181 | -------------------------------------------------------------------------------- /src/cursor.rs: -------------------------------------------------------------------------------- 1 | use std::{marker::PhantomData, ops}; 2 | 3 | use crate::{Index, PendingRef, Pointer, PointerData, StorageId, StorageInner}; 4 | 5 | /// A slice of a storage. Useful for cursor iteration. 6 | #[derive(Debug)] 7 | pub struct Slice<'a, T: 'a> { 8 | pub(crate) slice: &'a mut [T], 9 | pub(crate) offset: PointerData, 10 | } 11 | 12 | impl<'a, T> Slice<'a, T> { 13 | /// Check if the slice contains no elements. 14 | pub fn is_empty(&self) -> bool { 15 | self.slice.is_empty() 16 | } 17 | 18 | /// Get a reference by pointer. Returns None if an element 19 | /// is outside of the slice. 20 | pub fn get(&'a self, pointer: &Pointer) -> Option<&'a T> { 21 | debug_assert_eq!(pointer.data.get_storage_id(), self.offset.get_storage_id()); 22 | let index = pointer 23 | .data 24 | .get_index() 25 | .wrapping_sub(self.offset.get_index()); 26 | self.slice.get(index as usize) 27 | } 28 | 29 | /// Get a mutable reference by pointer. Returns None if an element 30 | /// is outside of the slice. 31 | pub fn get_mut(&'a mut self, pointer: &Pointer) -> Option<&'a mut T> { 32 | debug_assert_eq!(pointer.data.get_storage_id(), self.offset.get_storage_id()); 33 | let index = pointer 34 | .data 35 | .get_index() 36 | .wrapping_sub(self.offset.get_index()); 37 | self.slice.get_mut(index as usize) 38 | } 39 | } 40 | 41 | /// Item of the streaming iterator. 42 | /// 43 | /// [`Cursor`](struct.Cursor.html) and `CursorItem` are extremely useful 44 | /// when you need to iterate over [`Pointers`](struct.Pointer.html) in storage 45 | /// with ability to get other component in the same storage during iterating. 46 | /// 47 | /// # Examples 48 | /// Unfortunately, you can't use common `for` loop, 49 | /// but you can use `while let` statement: 50 | /// 51 | /// ```rust 52 | /// # let mut storage: froggy::Storage = froggy::Storage::new(); 53 | /// let mut cursor = storage.cursor(); 54 | /// while let Some(item) = cursor.next() { 55 | /// // ... your code 56 | /// } 57 | /// 58 | /// ``` 59 | /// While iterating, you can [`pin`](struct.CursorItem.html#method.pin) item 60 | /// with Pointer. 61 | /// 62 | /// ```rust 63 | /// # use froggy::WeakPointer; 64 | /// #[derive(Debug, PartialEq)] 65 | /// struct Node { 66 | /// pointer: Option>, 67 | /// } 68 | /// //... 69 | /// # fn do_something(_: &Node) {} 70 | /// # fn try_main() -> Result<(), froggy::DeadComponentError> { 71 | /// # let mut storage = froggy::Storage::new(); 72 | /// # let ptr1 = storage.create(Node { pointer: None }); 73 | /// # let ptr2 = storage.create(Node { pointer: None }); 74 | /// # storage[&ptr1].pointer = Some(ptr2.downgrade()); 75 | /// # storage[&ptr2].pointer = Some(ptr1.downgrade()); 76 | /// let mut cursor = storage.cursor(); 77 | /// while let Some((left, mut item, _)) = cursor.next() { 78 | /// // let's look for the other Node 79 | /// match item.pointer { 80 | /// Some(ref pointer) => { 81 | /// let ref pointer = pointer.upgrade()?; 82 | /// if let Some(ref other_node) = left.get(pointer) { 83 | /// do_something(other_node); 84 | /// } 85 | /// }, 86 | /// None => {}, 87 | /// } 88 | /// } 89 | /// # Ok(()) 90 | /// # } 91 | /// # fn main() { try_main(); } 92 | /// ``` 93 | #[derive(Debug)] 94 | pub struct CursorItem<'a, T: 'a> { 95 | item: &'a mut T, 96 | pending: &'a PendingRef, 97 | data: PointerData, 98 | } 99 | 100 | impl<'a, T> ops::Deref for CursorItem<'a, T> { 101 | type Target = T; 102 | fn deref(&self) -> &T { 103 | self.item 104 | } 105 | } 106 | 107 | impl<'a, T> ops::DerefMut for CursorItem<'a, T> { 108 | fn deref_mut(&mut self) -> &mut T { 109 | self.item 110 | } 111 | } 112 | 113 | impl<'a, T> CursorItem<'a, T> { 114 | /// Pin the item with a strong pointer. 115 | pub fn pin(&self) -> Pointer { 116 | let epoch = { 117 | let mut pending = self.pending.lock(); 118 | pending.add_ref.push(self.data.get_index()); 119 | pending.get_epoch(self.data.get_index()) 120 | }; 121 | Pointer { 122 | data: self.data.with_epoch(epoch), 123 | pending: self.pending.clone(), 124 | marker: PhantomData, 125 | } 126 | } 127 | } 128 | 129 | /// Streaming iterator providing mutable components 130 | /// and a capability to look back/ahead. 131 | /// 132 | /// See documentation of [`CursorItem`](struct.CursorItem.html). 133 | #[derive(Debug)] 134 | pub struct Cursor<'a, T: 'a> { 135 | pub(crate) storage: &'a mut StorageInner, 136 | pub(crate) pending: &'a PendingRef, 137 | pub(crate) index: Index, 138 | pub(crate) storage_id: StorageId, 139 | } 140 | 141 | impl<'a, T> Cursor<'a, T> { 142 | fn split(&mut self, index: usize) -> (Slice, CursorItem, Slice) { 143 | let data = PointerData::new(index, 0, self.storage_id); 144 | let (left, item, right) = self.storage.split(data); 145 | let item = CursorItem { 146 | item, 147 | data, 148 | pending: self.pending, 149 | }; 150 | (left, item, right) 151 | } 152 | 153 | /// Advance the stream to the next item. 154 | pub fn next(&mut self) -> Option<(Slice, CursorItem, Slice)> { 155 | loop { 156 | let id = self.index; 157 | self.index += 1; 158 | match self.storage.meta.get(id) { 159 | None => { 160 | self.index = id; // prevent the bump of the index 161 | return None; 162 | } 163 | Some(&0) => (), 164 | Some(_) => return Some(self.split(id)), 165 | } 166 | } 167 | } 168 | 169 | /// Advance the stream to the previous item. 170 | pub fn prev(&mut self) -> Option<(Slice, CursorItem, Slice)> { 171 | loop { 172 | if self.index == 0 { 173 | return None; 174 | } 175 | self.index -= 1; 176 | let id = self.index; 177 | debug_assert!(id < self.storage.meta.len()); 178 | if *unsafe { self.storage.meta.get_unchecked(id) } != 0 { 179 | return Some(self.split(id)); 180 | } 181 | } 182 | } 183 | } 184 | -------------------------------------------------------------------------------- /src/pointer.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | fmt, 3 | hash::{Hash, Hasher}, 4 | marker::PhantomData, 5 | }; 6 | 7 | use crate::{Pending, PendingRef, PointerData}; 8 | 9 | /// The error type which is returned from upgrading 10 | /// [`WeakPointer`](struct.WeakPointer.html). 11 | #[derive(Debug, PartialEq)] 12 | pub struct DeadComponentError; 13 | 14 | /// A pointer to a component of type `T`. 15 | /// The component is guaranteed to be accessible for as long as this pointer is alive. 16 | /// You'd need a storage to access the data. 17 | /// # Examples 18 | /// ```rust 19 | /// # let mut storage = froggy::Storage::new(); 20 | /// // you can create pointer by creating component in storage 21 | /// let ptr1 = storage.create(1i32); 22 | /// // later you can change component in storage 23 | /// storage[&ptr1] = 2i32; 24 | /// ``` 25 | /// Also you can use [`Storage::pin`](struct.Storage.html#method.pin) to pin component with `Pointer` 26 | /// 27 | /// ```rust 28 | /// # let mut storage = froggy::Storage::new(); 29 | /// # let ptr1 = storage.create(1i32); 30 | /// let item = storage.iter().next().unwrap(); 31 | /// let ptr2 = storage.pin(&item); 32 | /// // Pointers to the same component are equal 33 | /// assert_eq!(ptr1, ptr2); 34 | /// ``` 35 | pub struct Pointer { 36 | pub(crate) data: PointerData, 37 | pub(crate) pending: PendingRef, 38 | pub(crate) marker: PhantomData, 39 | } 40 | 41 | impl fmt::Debug for Pointer { 42 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 43 | /// Debug output type for `Self`. 44 | #[derive(Debug)] 45 | pub struct Pointer<'a> { 46 | /// All integer entries are `usize` for future-proofing. 47 | index: usize, 48 | epoch: usize, 49 | storage_id: usize, 50 | pending: &'a Pending, 51 | } 52 | 53 | fmt::Debug::fmt( 54 | &Pointer { 55 | index: self.data.get_index() as usize, 56 | epoch: self.data.get_epoch() as usize, 57 | storage_id: self.data.get_storage_id() as usize, 58 | pending: &self.pending.lock(), 59 | }, 60 | f, 61 | ) 62 | } 63 | } 64 | 65 | impl Pointer { 66 | /// Creates a new `WeakPointer` to this component. 67 | /// See [`WeakPointer`](pointer/struct.WeakPointer.html) 68 | #[inline] 69 | pub fn downgrade(&self) -> WeakPointer { 70 | WeakPointer { 71 | data: self.data, 72 | pending: self.pending.clone(), 73 | marker: PhantomData, 74 | } 75 | } 76 | } 77 | 78 | impl PartialOrd for Pointer { 79 | fn partial_cmp(&self, other: &Pointer) -> Option { 80 | if self.data.get_storage_id() == other.data.get_storage_id() { 81 | debug_assert!( 82 | self.data.get_index() != other.data.get_index() 83 | || self.data.get_epoch() == self.data.get_epoch() 84 | ); 85 | self.data.get_index().partial_cmp(&other.data.get_index()) 86 | } else { 87 | None 88 | } 89 | } 90 | } 91 | 92 | impl Clone for Pointer { 93 | #[inline] 94 | fn clone(&self) -> Pointer { 95 | self.pending.lock().add_ref.push(self.data.get_index()); 96 | Pointer { 97 | data: self.data, 98 | pending: self.pending.clone(), 99 | marker: PhantomData, 100 | } 101 | } 102 | } 103 | 104 | impl PartialEq for Pointer { 105 | #[inline] 106 | fn eq(&self, other: &Pointer) -> bool { 107 | self.data == other.data 108 | } 109 | } 110 | 111 | impl Eq for Pointer {} 112 | 113 | impl Hash for Pointer { 114 | fn hash(&self, state: &mut H) { 115 | self.data.hash(state); 116 | } 117 | } 118 | 119 | impl Drop for Pointer { 120 | #[inline] 121 | fn drop(&mut self) { 122 | self.pending.lock().sub_ref.push(self.data.get_index()); 123 | } 124 | } 125 | 126 | /// Weak variant of `Pointer`. 127 | /// `WeakPointer`s are used to avoid deadlocking when dropping structures with cycled references to each other. 128 | /// In the following example `Storage` will stand in memory even after going out of scope, because there is cyclic referencing between `Node`s 129 | /// 130 | /// ```rust 131 | /// # use froggy::{Pointer, Storage}; 132 | /// struct Node { 133 | /// next: Option>, 134 | /// } 135 | /// # let mut storage = Storage::new(); 136 | /// let ptr1 = storage.create(Node { next: None }); 137 | /// let ptr2 = storage.create(Node { next: Some(ptr1.clone()) }); 138 | /// storage[&ptr1].next = Some(ptr2.clone()); 139 | /// ``` 140 | /// 141 | /// To avoid such situations, just replace `Option>` with `Option>` 142 | /// # Example 143 | /// 144 | /// ```rust 145 | /// # let mut storage = froggy::Storage::new(); 146 | /// let pointer = storage.create(1i32); 147 | /// // create WeakPointer to this component 148 | /// let weak = pointer.downgrade(); 149 | /// ``` 150 | /// 151 | /// You will need to [`upgrade`](struct.WeakPointer.html#method.upgrade) `WeakPointer` to access component in storage 152 | /// 153 | /// ```rust 154 | /// # fn try_main() -> Result<(), froggy::DeadComponentError> { 155 | /// # let mut storage = froggy::Storage::new(); 156 | /// # let _pointer = storage.create(1i32); 157 | /// # let weak = _pointer.downgrade(); 158 | /// let pointer = weak.upgrade()?; 159 | /// storage[&pointer] = 20; 160 | /// # Ok(()) } 161 | /// # fn main() { try_main().unwrap(); } 162 | /// ``` 163 | #[derive(Debug)] 164 | pub struct WeakPointer { 165 | data: PointerData, 166 | pending: PendingRef, 167 | marker: PhantomData, 168 | } 169 | 170 | impl WeakPointer { 171 | /// Upgrades the `WeakPointer` to a `Pointer`, if possible. 172 | /// # Errors 173 | /// Returns [`DeadComponentError`](struct.DeadComponentError.html) if the related component in storage was destroyed. 174 | pub fn upgrade(&self) -> Result, DeadComponentError> { 175 | let mut pending = self.pending.lock(); 176 | if pending.get_epoch(self.data.get_index()) != self.data.get_epoch() { 177 | return Err(DeadComponentError); 178 | } 179 | pending.add_ref.push(self.data.get_index()); 180 | Ok(Pointer { 181 | data: self.data, 182 | pending: self.pending.clone(), 183 | marker: PhantomData, 184 | }) 185 | } 186 | } 187 | 188 | impl Clone for WeakPointer { 189 | #[inline] 190 | fn clone(&self) -> WeakPointer { 191 | WeakPointer { 192 | data: self.data, 193 | pending: self.pending.clone(), 194 | marker: PhantomData, 195 | } 196 | } 197 | } 198 | 199 | impl PartialEq for WeakPointer { 200 | #[inline] 201 | fn eq(&self, other: &WeakPointer) -> bool { 202 | self.data == other.data 203 | } 204 | } 205 | 206 | impl Eq for WeakPointer {} 207 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/storage.rs: -------------------------------------------------------------------------------- 1 | use spin::Mutex; 2 | 3 | use std::{ 4 | iter::FromIterator, 5 | marker::PhantomData, 6 | ops, slice, 7 | sync::{atomic::Ordering, Arc}, 8 | }; 9 | 10 | use crate::{ 11 | Cursor, Epoch, Index, Pending, PendingRef, Pointer, PointerData, RefCount, Slice, StorageId, 12 | STORAGE_UID, 13 | }; 14 | 15 | /// Inner storage data that is locked by `RwLock`. 16 | #[derive(Debug)] 17 | pub(crate) struct StorageInner { 18 | pub(crate) data: Vec, 19 | pub(crate) meta: Vec, 20 | free_list: Vec, 21 | } 22 | 23 | impl StorageInner { 24 | pub(crate) fn split(&mut self, offset: PointerData) -> (Slice, &mut T, Slice) { 25 | let sid = offset.get_storage_id(); 26 | let index = offset.get_index(); 27 | let (left, temp) = self.data.split_at_mut(index as usize); 28 | let (cur, right) = temp.split_at_mut(1); 29 | ( 30 | Slice { 31 | slice: left, 32 | offset: PointerData::new(0, 0, sid), 33 | }, 34 | unsafe { cur.get_unchecked_mut(0) }, 35 | Slice { 36 | slice: right, 37 | offset: PointerData::new(index + 1, 0, sid), 38 | }, 39 | ) 40 | } 41 | } 42 | 43 | /// Component storage type. 44 | /// Manages the components and allows for efficient processing. 45 | /// See also: [Pointer](struct.Pointer.html) 46 | /// # Examples 47 | /// ```rust 48 | /// # use froggy::Storage; 49 | /// let mut storage = Storage::new(); 50 | /// // add component to storage 51 | /// let pointer = storage.create(1u32); 52 | /// // change component by pointer 53 | /// storage[&pointer] = 30; 54 | /// ``` 55 | #[derive(Debug)] 56 | pub struct Storage { 57 | inner: StorageInner, 58 | pending: PendingRef, 59 | id: StorageId, 60 | } 61 | 62 | impl<'a, T> ops::Index<&'a Pointer> for Storage { 63 | type Output = T; 64 | #[inline] 65 | fn index(&self, pointer: &'a Pointer) -> &T { 66 | debug_assert_eq!(pointer.data.get_storage_id(), self.id); 67 | debug_assert!(pointer.data.get_index() < self.inner.data.len()); 68 | unsafe { self.inner.data.get_unchecked(pointer.data.get_index()) } 69 | } 70 | } 71 | 72 | impl<'a, T> ops::IndexMut<&'a Pointer> for Storage { 73 | #[inline] 74 | fn index_mut(&mut self, pointer: &'a Pointer) -> &mut T { 75 | debug_assert_eq!(pointer.data.get_storage_id(), self.id); 76 | debug_assert!(pointer.data.get_index() < self.inner.data.len()); 77 | unsafe { self.inner.data.get_unchecked_mut(pointer.data.get_index()) } 78 | } 79 | } 80 | 81 | impl FromIterator for Storage { 82 | fn from_iter(iter: I) -> Self 83 | where 84 | I: IntoIterator, 85 | { 86 | let data: Vec = iter.into_iter().collect(); 87 | let count = data.len(); 88 | Storage::new_impl(data, vec![0; count], vec![0; count]) 89 | } 90 | } 91 | 92 | impl<'a, T> IntoIterator for &'a Storage { 93 | type Item = Item<'a, T>; 94 | type IntoIter = Iter<'a, T>; 95 | fn into_iter(self) -> Self::IntoIter { 96 | Iter { 97 | storage: &self.inner, 98 | skip_lost: true, 99 | index: 0, 100 | } 101 | } 102 | } 103 | 104 | impl<'a, T> IntoIterator for &'a mut Storage { 105 | type Item = &'a mut T; 106 | type IntoIter = IterMut<'a, T>; 107 | fn into_iter(self) -> Self::IntoIter { 108 | self.iter_mut() 109 | } 110 | } 111 | 112 | impl Storage { 113 | fn new_impl(data: Vec, meta: Vec, epoch: Vec) -> Storage { 114 | assert_eq!(data.len(), meta.len()); 115 | assert!(epoch.len() <= meta.len()); 116 | let uid = STORAGE_UID.fetch_add(1, Ordering::Relaxed) as StorageId; 117 | Storage { 118 | inner: StorageInner { 119 | data, 120 | meta, 121 | free_list: Vec::new(), 122 | }, 123 | pending: Arc::new(Mutex::new(Pending { 124 | add_ref: Vec::new(), 125 | sub_ref: Vec::new(), 126 | epoch, 127 | })), 128 | id: uid, 129 | } 130 | } 131 | 132 | /// Create a new empty storage. 133 | pub fn new() -> Storage { 134 | Self::new_impl(Vec::new(), Vec::new(), Vec::new()) 135 | } 136 | 137 | /// Create a new empty storage with specified capacity. 138 | pub fn with_capacity(capacity: usize) -> Storage { 139 | Self::new_impl( 140 | Vec::with_capacity(capacity), 141 | Vec::with_capacity(capacity), 142 | Vec::with_capacity(capacity), 143 | ) 144 | } 145 | 146 | /// Synchronize for all the pending updates. 147 | /// It will update all reference counters in Storage, so 148 | /// [`iter_alive`](struct.Storage.html#method.iter_alive) and 149 | /// [`iter_alive_mut`](struct.Storage.html#method.iter_alive_mut) will return actual information. 150 | /// 151 | /// Use this function only if necessary, because it needs to block Storage. 152 | pub fn sync_pending(&mut self) { 153 | let mut pending = self.pending.lock(); 154 | // missing epochs 155 | while pending.epoch.len() < self.inner.data.len() { 156 | pending.epoch.push(0); 157 | } 158 | // pending reference adds 159 | for index in pending.add_ref.drain(..) { 160 | self.inner.meta[index] += 1; 161 | } 162 | // pending reference subs 163 | { 164 | let (refs, epoch) = pending.drain_sub(); 165 | for index in refs { 166 | self.inner.meta[index] -= 1; 167 | if self.inner.meta[index] == 0 { 168 | epoch[index] += 1; 169 | let data = PointerData::new(index, epoch[index], self.id); 170 | self.inner.free_list.push(data); 171 | } 172 | } 173 | } 174 | } 175 | 176 | /// Iterate all components in this storage that are still referenced from outside. 177 | /// ### Attention 178 | /// Information about live components is updated not for all changes, but 179 | /// only when you explicitly call [`sync_pending`](struct.Storage.html#method.sync_pending). 180 | /// It means, you can get wrong results when calling this function before updating pending. 181 | #[inline] 182 | pub fn iter(&self) -> Iter { 183 | Iter { 184 | storage: &self.inner, 185 | skip_lost: true, 186 | index: 0, 187 | } 188 | } 189 | 190 | /// Iterate all components that are stored, even if not referenced. 191 | /// This can be faster than the regular `iter` for the lack of refcount checks. 192 | #[inline] 193 | pub fn iter_all(&self) -> Iter { 194 | Iter { 195 | storage: &self.inner, 196 | skip_lost: false, 197 | index: 0, 198 | } 199 | } 200 | 201 | /// Iterate all components in this storage that are still referenced from outside, mutably. 202 | /// ### Attention 203 | /// Information about live components is updated not for all changes, but 204 | /// only when you explicitly call [`sync_pending`](struct.Storage.html#method.sync_pending). 205 | /// It means, you can get wrong results when calling this function before updating pending. 206 | #[inline] 207 | pub fn iter_mut(&mut self) -> IterMut { 208 | IterMut { 209 | data: self.inner.data.iter_mut(), 210 | meta: self.inner.meta.iter(), 211 | } 212 | } 213 | 214 | /// Iterate all components that are stored, even if not referenced, mutably. 215 | /// This can be faster than the regular `iter_mut` for the lack of refcount checks. 216 | #[inline] 217 | pub fn iter_all_mut(&mut self) -> slice::IterMut { 218 | self.inner.data.iter_mut() 219 | } 220 | 221 | /// Pin an iterated item with a newly created `Pointer`. 222 | pub fn pin(&self, item: &Item) -> Pointer { 223 | let mut pending = self.pending.lock(); 224 | pending.add_ref.push(item.index); 225 | Pointer { 226 | data: PointerData::new(item.index, pending.get_epoch(item.index), self.id), 227 | pending: self.pending.clone(), 228 | marker: PhantomData, 229 | } 230 | } 231 | 232 | /// Split the storage according to the provided pointer, returning 233 | /// the (left slice, pointed data, right slice) triple, where: 234 | /// left slice contains all the elements that would be iterated prior to the given one, 235 | /// right slice contains all the elements that would be iterated after the given one 236 | pub fn split(&mut self, pointer: &Pointer) -> (Slice, &mut T, Slice) { 237 | debug_assert_eq!(pointer.data.get_storage_id(), self.id); 238 | self.inner.split(pointer.data) 239 | } 240 | 241 | /// Produce a streaming mutable iterator over components that are still referenced. 242 | /// ### Attention 243 | /// Information about live components is updated not for all changes, but 244 | /// only when you explicitly call [`sync_pending`](struct.Storage.html#method.sync_pending). 245 | /// It means, you can get wrong results when calling this function before updating pending. 246 | #[inline] 247 | pub fn cursor(&mut self) -> Cursor { 248 | Cursor { 249 | storage: &mut self.inner, 250 | pending: &self.pending, 251 | index: 0, 252 | storage_id: self.id, 253 | } 254 | } 255 | 256 | /// Returns a cursor to the end of the storage, for backwards streaming iteration. 257 | #[inline] 258 | pub fn cursor_end(&mut self) -> Cursor { 259 | let total = self.inner.data.len(); 260 | Cursor { 261 | storage: &mut self.inner, 262 | pending: &self.pending, 263 | index: total, 264 | storage_id: self.id, 265 | } 266 | } 267 | 268 | /// Add a new component to the storage, returning the `Pointer` to it. 269 | pub fn create(&mut self, value: T) -> Pointer { 270 | let data = match self.inner.free_list.pop() { 271 | Some(data) => { 272 | let i = data.get_index(); 273 | debug_assert_eq!(self.inner.meta[i], 0); 274 | self.inner.data[i] = value; 275 | self.inner.meta[i] = 1; 276 | data 277 | } 278 | None => { 279 | let i = self.inner.meta.len(); 280 | debug_assert_eq!(self.inner.data.len(), i); 281 | self.inner.data.push(value); 282 | self.inner.meta.push(1); 283 | PointerData::new(i, 0, self.id) 284 | } 285 | }; 286 | Pointer { 287 | data, 288 | pending: self.pending.clone(), 289 | marker: PhantomData, 290 | } 291 | } 292 | } 293 | 294 | impl Default for Storage { 295 | fn default() -> Self { 296 | Self::new() 297 | } 298 | } 299 | 300 | /// The item of `Iter`. 301 | #[derive(Debug, Clone, Copy)] 302 | pub struct Item<'a, T: 'a> { 303 | value: &'a T, 304 | index: Index, 305 | } 306 | 307 | impl<'a, T> ops::Deref for Item<'a, T> { 308 | type Target = T; 309 | fn deref(&self) -> &T { 310 | self.value 311 | } 312 | } 313 | 314 | /// Iterator for reading components. 315 | #[derive(Debug)] 316 | pub struct Iter<'a, T: 'a> { 317 | storage: &'a StorageInner, 318 | skip_lost: bool, 319 | index: Index, 320 | } 321 | 322 | impl<'a, T> Iterator for Iter<'a, T> { 323 | type Item = Item<'a, T>; 324 | fn next(&mut self) -> Option { 325 | loop { 326 | let id = self.index; 327 | if id >= self.storage.data.len() { 328 | return None; 329 | } 330 | self.index += 1; 331 | if !self.skip_lost || unsafe { *self.storage.meta.get_unchecked(id) } != 0 { 332 | return Some(Item { 333 | value: unsafe { self.storage.data.get_unchecked(id) }, 334 | index: id, 335 | }); 336 | } 337 | } 338 | } 339 | } 340 | 341 | impl<'a, T> Clone for Iter<'a, T> { 342 | fn clone(&self) -> Self { 343 | Iter { 344 | storage: self.storage, 345 | skip_lost: self.skip_lost, 346 | index: self.index, 347 | } 348 | } 349 | } 350 | 351 | /// Iterator for writing components. 352 | #[derive(Debug)] 353 | pub struct IterMut<'a, T: 'a> { 354 | data: slice::IterMut<'a, T>, 355 | meta: slice::Iter<'a, RefCount>, 356 | } 357 | 358 | impl<'a, T> Iterator for IterMut<'a, T> { 359 | type Item = &'a mut T; 360 | fn next(&mut self) -> Option { 361 | while let Some(&0) = self.meta.next() { 362 | self.data.next(); 363 | } 364 | self.data.next() 365 | } 366 | } 367 | 368 | impl<'a, T> DoubleEndedIterator for IterMut<'a, T> { 369 | fn next_back(&mut self) -> Option { 370 | while let Some(&0) = self.meta.next_back() { 371 | self.data.next_back(); 372 | } 373 | self.data.next_back() 374 | } 375 | } 376 | -------------------------------------------------------------------------------- /demos/cubes/src/main.rs: -------------------------------------------------------------------------------- 1 | extern crate cgmath; 2 | extern crate froggy; 3 | #[macro_use] 4 | extern crate gfx; 5 | extern crate gfx_window_glutin; 6 | extern crate glutin; 7 | 8 | use cgmath::{Angle, EuclideanSpace, One, Rotation3, Transform, Zero}; 9 | use gfx::traits::{Device, Factory, FactoryExt}; 10 | use std::time; 11 | 12 | pub type ColorFormat = gfx::format::Srgba8; 13 | pub type DepthFormat = gfx::format::DepthStencil; 14 | 15 | gfx_defines! { 16 | vertex Vertex { 17 | pos: [f32; 4] = "a_Pos", 18 | normal: [i8; 4] = "a_Normal", 19 | } 20 | 21 | vertex Instance { 22 | offset_scale: [f32; 4] = "a_OffsetScale", 23 | rotation: [f32; 4] = "a_Rotation", 24 | color: [f32; 4] = "a_Color", 25 | } 26 | 27 | constant Globals { 28 | projection: [[f32; 4]; 4] = "u_Projection", 29 | camera_pos: [f32; 4] = "u_CameraPos", 30 | light_pos: [f32; 4] = "u_LightPos", 31 | light_color: [f32; 4] = "u_LightColor", 32 | } 33 | 34 | pipeline pipe { 35 | vert_buf: gfx::VertexBuffer = (), 36 | inst_buf: gfx::InstanceBuffer = (), 37 | globals: gfx::ConstantBuffer = "b_Globals", 38 | out_color: gfx::RenderTarget = "Target0", 39 | out_depth: gfx::DepthTarget = gfx::preset::depth::LESS_EQUAL_WRITE, 40 | } 41 | } 42 | 43 | fn vertex(x: i8, y: i8, z: i8, nx: i8, ny: i8, nz: i8) -> Vertex { 44 | Vertex { 45 | pos: [x as f32, y as f32, z as f32, 1.0], 46 | normal: [nx, ny, nz, 0], 47 | } 48 | } 49 | 50 | fn create_geometry>( 51 | factory: &mut F, 52 | ) -> (gfx::handle::Buffer, gfx::Slice) { 53 | let vertices = [ 54 | // bottom 55 | vertex(1, 1, 0, 0, 0, -1), 56 | vertex(1, -1, 0, 0, 0, -1), 57 | vertex(-1, -1, 0, 0, 0, -1), 58 | vertex(-1, 1, 0, 0, 0, -1), 59 | // top 60 | vertex(1, 1, 2, 0, 0, 1), 61 | vertex(1, -1, 2, 0, 0, 1), 62 | vertex(-1, -1, 2, 0, 0, 1), 63 | vertex(-1, 1, 2, 0, 0, 1), 64 | // left 65 | vertex(-1, 1, 2, -1, 0, 0), 66 | vertex(-1, 1, 0, -1, 0, 0), 67 | vertex(-1, -1, 0, -1, 0, 0), 68 | vertex(-1, -1, 2, -1, 0, 0), 69 | // right 70 | vertex(1, 1, 2, 1, 0, 0), 71 | vertex(1, 1, 0, 1, 0, 0), 72 | vertex(1, -1, 0, 1, 0, 0), 73 | vertex(1, -1, 2, 1, 0, 0), 74 | // front 75 | vertex(1, -1, 2, 0, -1, 0), 76 | vertex(1, -1, 0, 0, -1, 0), 77 | vertex(-1, -1, 0, 0, -1, 0), 78 | vertex(-1, -1, 2, 0, -1, 0), 79 | // back 80 | vertex(1, 1, 2, 0, 1, 0), 81 | vertex(1, 1, 0, 0, 1, 0), 82 | vertex(-1, 1, 0, 0, 1, 0), 83 | vertex(-1, 1, 2, 0, 1, 0), 84 | ]; 85 | 86 | let indices = [ 87 | 0u16, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11, 12, 13, 14, 12, 14, 15, 16, 17, 88 | 18, 16, 18, 19, 20, 21, 22, 20, 22, 23, 89 | ]; 90 | 91 | factory.create_vertex_buffer_with_slice(&vertices, &indices[..]) 92 | } 93 | 94 | type Space = cgmath::Decomposed, cgmath::Quaternion>; 95 | 96 | struct Level { 97 | speed: f32, 98 | } 99 | 100 | struct Material { 101 | color: [f32; 4], 102 | } 103 | 104 | struct Node { 105 | local: Space, 106 | world: Space, 107 | parent: Option>, 108 | } 109 | 110 | struct Cube { 111 | node: froggy::Pointer, 112 | material: froggy::Pointer, 113 | level: froggy::Pointer, 114 | } 115 | 116 | fn create_cubes( 117 | nodes: &mut froggy::Storage, 118 | materials: &froggy::Storage, 119 | levels: &froggy::Storage, 120 | ) -> Vec { 121 | let mut mat_iter = materials.iter_all(); 122 | let mut lev_iter = levels.iter_all(); 123 | let root_mat = mat_iter.next().unwrap(); 124 | let root_lev = lev_iter.next().unwrap(); 125 | let mut list = vec![Cube { 126 | node: nodes.create(Node { 127 | local: Space { 128 | disp: cgmath::Vector3::zero(), 129 | rot: cgmath::Quaternion::one(), 130 | scale: 2.0, 131 | }, 132 | world: Space::one(), 133 | parent: None, 134 | }), 135 | material: materials.pin(&root_mat), 136 | level: levels.pin(&root_lev), 137 | }]; 138 | struct Stack<'a> { 139 | parent: froggy::Pointer, 140 | mat_iter: froggy::Iter<'a, Material>, 141 | lev_iter: froggy::Iter<'a, Level>, 142 | } 143 | let mut stack = vec![Stack { 144 | parent: list[0].node.clone(), 145 | mat_iter, 146 | lev_iter, 147 | }]; 148 | 149 | let axis = [ 150 | cgmath::Vector3::unit_z(), 151 | cgmath::Vector3::unit_x(), 152 | -cgmath::Vector3::unit_x(), 153 | cgmath::Vector3::unit_y(), 154 | -cgmath::Vector3::unit_y(), 155 | ]; 156 | let children: Vec<_> = axis 157 | .iter() 158 | .map(|&axe| { 159 | Space { 160 | disp: cgmath::vec3(0.0, 0.0, 1.0), 161 | rot: cgmath::Quaternion::from_axis_angle(axe, cgmath::Rad::turn_div_4()), 162 | scale: 1.0, 163 | } 164 | .concat(&Space { 165 | disp: cgmath::vec3(0.0, 0.0, 1.0), 166 | rot: cgmath::Quaternion::one(), 167 | scale: 0.4, 168 | }) 169 | }) 170 | .collect(); 171 | 172 | while let Some(mut next) = stack.pop() { 173 | //HACK: materials are indexed the same way as levels 174 | // it's fine for demostration purposes 175 | let material = match next.mat_iter.next() { 176 | Some(item) => materials.pin(&item), 177 | None => continue, 178 | }; 179 | let level = match next.lev_iter.next() { 180 | Some(item) => levels.pin(&item), 181 | None => continue, 182 | }; 183 | for child in &children { 184 | let cube = Cube { 185 | node: nodes.create(Node { 186 | local: child.clone(), 187 | world: Space::one(), 188 | parent: Some(next.parent.clone()), 189 | }), 190 | material: material.clone(), 191 | level: level.clone(), 192 | }; 193 | stack.push(Stack { 194 | parent: cube.node.clone(), 195 | mat_iter: next.mat_iter.clone(), 196 | lev_iter: next.lev_iter.clone(), 197 | }); 198 | list.push(cube); 199 | } 200 | } 201 | 202 | list 203 | } 204 | 205 | fn make_globals(camera_pos: cgmath::Point3, aspect: f32) -> Globals { 206 | let mx_proj = { 207 | let fovy = cgmath::Deg(60.0); 208 | let perspective = cgmath::perspective(fovy, aspect, 1.0, 100.0); 209 | let focus = cgmath::Point3::new(0.0, 0.0, 3.0); 210 | let view = cgmath::Matrix4::look_at(camera_pos, focus, cgmath::Vector3::unit_z()); 211 | perspective * view 212 | }; 213 | Globals { 214 | projection: mx_proj.into(), 215 | camera_pos: camera_pos.to_vec().extend(1.0).into(), 216 | light_pos: [0.0, -10.0, 10.0, 1.0], 217 | light_color: [1.0, 1.0, 1.0, 1.0], 218 | } 219 | } 220 | 221 | const COLORS: [[f32; 4]; 6] = [ 222 | [1.0, 1.0, 0.5, 1.0], 223 | [0.5, 0.5, 1.0, 1.0], 224 | [0.5, 1.0, 0.5, 1.0], 225 | [1.0, 0.5, 0.5, 1.0], 226 | [0.5, 1.0, 1.0, 1.0], 227 | [1.0, 0.5, 1.0, 1.0], 228 | ]; 229 | 230 | const SPEEDS: [f32; 6] = [0.7, -1.0, 1.3, -1.6, 1.9, -2.2]; 231 | 232 | fn main() { 233 | // feed Froggy 234 | let mut node_store = froggy::Storage::new(); 235 | let material_store: froggy::Storage<_> = COLORS 236 | .iter() 237 | .map(|&color| Material { color: color }) 238 | .collect(); 239 | let level_store: froggy::Storage<_> = 240 | SPEEDS.iter().map(|&speed| Level { speed: speed }).collect(); 241 | 242 | //Note: we populated the storages, but the returned pointers are already dropped. 243 | // Thus, all will be lost if we lock for writing now, but locking for reading retains the 244 | // contents, and cube creation will add references to them, so they will stay alive. 245 | let mut cubes = create_cubes(&mut node_store, &material_store, &level_store); 246 | println!( 247 | "Initialized {} cubes on {} levels", 248 | cubes.len(), 249 | SPEEDS.len() 250 | ); 251 | 252 | // init window and graphics 253 | let builder = glutin::WindowBuilder::new() 254 | .with_title("Froggy Cube-ception".to_string()) 255 | .with_vsync(); 256 | let event_loop = glutin::EventsLoop::new(); 257 | let (window, mut device, mut factory, main_color, main_depth) = 258 | gfx_window_glutin::init::(builder, &event_loop); 259 | let mut encoder = gfx::Encoder::from(factory.create_command_buffer()); 260 | 261 | let (cube_vbuf, mut cube_slice) = create_geometry(&mut factory); 262 | let cube_ibuf = factory 263 | .create_buffer( 264 | cubes.len(), 265 | gfx::buffer::Role::Vertex, 266 | gfx::memory::Usage::Dynamic, 267 | gfx::Bind::empty(), 268 | ) 269 | .unwrap(); 270 | 271 | // init global parameters 272 | let camera_pos = cgmath::Point3::new(-1.8, -8.0, 3.0); 273 | let globals = { 274 | let (w, h, _, _) = main_color.get_dimensions(); 275 | make_globals(camera_pos, w as f32 / h as f32) 276 | }; 277 | let global_buf = factory.create_constant_buffer(1); 278 | encoder.update_constant_buffer(&global_buf, &globals); 279 | 280 | // init pipeline states 281 | let pso = factory 282 | .create_pipeline_simple( 283 | include_bytes!("vert.glsl"), 284 | include_bytes!("frag.glsl"), 285 | pipe::new(), 286 | ) 287 | .unwrap(); 288 | let mut data = pipe::Data { 289 | vert_buf: cube_vbuf, 290 | inst_buf: cube_ibuf, 291 | globals: global_buf, 292 | out_color: main_color, 293 | out_depth: main_depth, 294 | }; 295 | 296 | let mut instances = Vec::new(); 297 | let mut moment = time::Instant::now(); 298 | let mut running = true; 299 | 300 | while running { 301 | // process events 302 | event_loop.poll_events(|glutin::Event::WindowEvent { event, .. }| { 303 | use glutin::WindowEvent as Event; 304 | match event { 305 | Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape), _) 306 | | Event::Closed => running = false, 307 | Event::Resized(width, height) => { 308 | gfx_window_glutin::update_views( 309 | &window, 310 | &mut data.out_color, 311 | &mut data.out_depth, 312 | ); 313 | let globals = make_globals(camera_pos, width as f32 / height as f32); 314 | encoder.update_constant_buffer(&data.globals, &globals); 315 | } 316 | _ => (), 317 | } 318 | }); 319 | 320 | // get time delta 321 | let duration = moment.elapsed(); 322 | let delta = duration.as_secs() as f32 + (duration.subsec_nanos() as f32 * 1.0e-9); 323 | moment = time::Instant::now(); 324 | 325 | // Note: the following 3 passes could be combined into one for efficiency. 326 | // This is not the goal of the demo though. It is made with an assuption that 327 | // the scenegraph and its logic is separate from the main game, and that 328 | // more processing is done in parallel. 329 | 330 | // animate local spaces 331 | for cube in cubes.iter_mut() { 332 | let level = &level_store[&cube.level]; 333 | let angle = cgmath::Rad(delta * level.speed); 334 | node_store[&cube.node].local.concat_self(&Space { 335 | disp: cgmath::Vector3::zero(), 336 | rot: cgmath::Quaternion::from_angle_z(angle), 337 | scale: 1.0, 338 | }); 339 | } 340 | 341 | // re-compute world spaces, using streaming iteration 342 | { 343 | let mut cursor = node_store.cursor(); 344 | while let Some((left, mut item, _)) = cursor.next() { 345 | item.world = match item.parent { 346 | Some(ref parent) => left.get(parent).unwrap().world.concat(&item.local), 347 | None => item.local, 348 | }; 349 | } 350 | } 351 | 352 | // update instancing CPU info 353 | instances.clear(); 354 | for cube in cubes.iter_mut() { 355 | let material = &material_store[&cube.material]; 356 | let space = &node_store[&cube.node].world; 357 | instances.push(Instance { 358 | offset_scale: space.disp.extend(space.scale).into(), 359 | rotation: space.rot.v.extend(space.rot.s).into(), 360 | color: material.color, 361 | }); 362 | } 363 | 364 | // update instancing GPU info 365 | cube_slice.instances = Some((instances.len() as gfx::InstanceCount, 0)); 366 | encoder 367 | .update_buffer(&data.inst_buf, &instances, 0) 368 | .unwrap(); 369 | 370 | // draw -- start 371 | encoder.clear_depth(&data.out_depth, 1.0); 372 | encoder.clear(&data.out_color, [0.1, 0.2, 0.3, 1.0]); 373 | encoder.draw(&cube_slice, &pso, &data); 374 | // draw -- end 375 | encoder.flush(&mut device); 376 | window.swap_buffers().unwrap(); 377 | device.cleanup(); 378 | } 379 | } 380 | --------------------------------------------------------------------------------