1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
use lua::Variadic;

use crate::prelude::bindings::schema::WithoutSchema;

use super::*;

pub fn entities_metatable(ctx: Context) -> Table {
    let metatable = Table::new(&ctx);
    metatable
        .set(
            ctx,
            "__tostring",
            Callback::from_fn(&ctx, |ctx, _fuel, mut stack| {
                stack.push_front(
                    piccolo::String::from_static(&ctx, "Entities { create, kill, iter_with }")
                        .into(),
                );
                Ok(CallbackReturn::Return)
            }),
        )
        .unwrap();
    metatable
        .set(ctx, "__newindex", ctx.singletons().get(ctx, no_newindex))
        .unwrap();

    let create_callback = ctx.registry().stash(
        &ctx,
        Callback::from_fn(&ctx, move |ctx, _fuel, mut stack| {
            let this: &EcsRef = stack.consume(ctx)?;

            let mut b = this.borrow_mut();
            let entities = b.schema_ref_mut()?.cast_into_mut::<Entities>();

            let entity = entities.create();
            let newecsref = EcsRef {
                data: EcsRefData::Free(Rc::new(AtomicCell::new(SchemaBox::new(entity)))),
                path: default(),
            }
            .into_value(ctx);
            stack.push_front(newecsref);

            Ok(CallbackReturn::Return)
        }),
    );
    let kill_callback = ctx.registry().stash(
        &ctx,
        Callback::from_fn(&ctx, move |ctx, _fuel, mut stack| {
            let (this, entity_ecsref): (&EcsRef, &EcsRef) = stack.consume(ctx)?;
            let mut b = this.borrow_mut();
            let entities = b.schema_ref_mut()?.cast_into_mut::<Entities>();

            let b = entity_ecsref.borrow();
            let entity = b.schema_ref()?.cast::<Entity>();
            entities.kill(*entity);

            Ok(CallbackReturn::Return)
        }),
    );
    let iter_with_callback = ctx.registry().stash(
        &ctx,
        Callback::from_fn(&ctx, move |ctx, _fuel, mut stack| {
            let (this, schema_args): (&EcsRef, Variadic<Vec<UserData>>) = stack.consume(ctx)?;
            let mut b = this.borrow_mut();
            let entities = b.schema_ref_mut()?.cast_into_mut::<Entities>();
            let world = ctx
                .globals()
                .get(ctx, "world")
                .as_static_user_data::<WorldRef>()?;
            let mut bitset = entities.bitset().clone();

            let mut schemas = Vec::with_capacity(schema_args.len());
            world.with(|world| {
                for schema_arg in &schema_args {
                    if let Ok(schema) = schema_arg.downcast_static::<&Schema>() {
                        let components = world.components.get_by_schema(schema);
                        let components = components.borrow();
                        bitset.bit_and(components.bitset());
                        schemas.push(*schema);
                    } else if let Ok(without_schema) = schema_arg.downcast_static::<WithoutSchema>()
                    {
                        let components = world.components.get_by_schema(without_schema.0);
                        let components = components.borrow();
                        bitset.bit_and(components.bitset().clone().bit_not());
                    } else {
                        return Err(anyhow::format_err!(
                            "Invalid type for argument to `entities:iter_with()`: {schema_arg:?}"
                        ));
                    }
                }
                Ok::<_, anyhow::Error>(())
            })?;
            let entities = entities
                .iter_with_bitset(&bitset)
                .collect::<Vec<_>>()
                .into_iter();

            struct IteratorState {
                pub entities: std::vec::IntoIter<Entity>,
                schemas: Vec<&'static Schema>,
            }

            let iter_fn = Callback::from_fn(&ctx, |ctx, _fuel, mut stack| {
                let state: UserData = stack.consume(ctx)?;
                let state = state.downcast_static::<AtomicCell<IteratorState>>()?;
                let mut state = state.borrow_mut();
                let next_ent = state.entities.next();

                if let Some(entity) = next_ent {
                    let world = ctx
                        .globals()
                        .get(ctx, "world")
                        .as_static_user_data::<WorldRef>()?;

                    let ecsref = EcsRef {
                        data: EcsRefData::Free(Rc::new(AtomicCell::new(SchemaBox::new(entity)))),
                        path: default(),
                    }
                    .into_value(ctx);
                    stack.push_back(ecsref);

                    world.with(|world| {
                        for schema in &state.schemas {
                            let store = world.components.get_cell_by_schema(schema);
                            let ecsref = EcsRef {
                                data: EcsRefData::Component(ComponentRef { store, entity }),
                                path: default(),
                            }
                            .into_value(ctx);
                            stack.push_back(ecsref);
                        }

                        Ok::<_, anyhow::Error>(())
                    })?;
                }

                Ok(CallbackReturn::Return)
            });

            let iterator_state =
                UserData::new_static(&ctx, AtomicCell::new(IteratorState { entities, schemas }));

            stack.replace(ctx, (iter_fn, iterator_state));

            Ok(CallbackReturn::Return)
        }),
    );

    metatable
        .set(
            ctx,
            "__index",
            Callback::from_fn(&ctx, move |ctx, _fuel, mut stack| {
                let (_this, key): (lua::Value, lua::String) = stack.consume(ctx)?;

                #[allow(clippy::single_match)]
                match key.as_bytes() {
                    b"create" => {
                        stack.push_front(ctx.registry().fetch(&create_callback).into());
                    }
                    b"kill" => {
                        stack.push_front(ctx.registry().fetch(&kill_callback).into());
                    }
                    b"iter_with" => {
                        stack.push_front(ctx.registry().fetch(&iter_with_callback).into());
                    }
                    _ => (),
                }

                Ok(CallbackReturn::Return)
            }),
        )
        .unwrap();

    metatable
}