Skip to content

Commit

Permalink
work with singletons without new_entity
Browse files Browse the repository at this point in the history
  • Loading branch information
konovod committed Aug 22, 2023
1 parent 6d70b91 commit 5ffbc8d
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 3 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,9 @@ class InitConfigSystem < ECS::System
def init
config = ...some config initializatio
@world.new_entity.add(Config.new(config))
# another way
@world.add(Config.new(config)) unless @world.component_exists?(Config)
end
end
Expand Down
11 changes: 11 additions & 0 deletions spec/myecs_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,17 @@ describe ECS::Singleton do
world.getConfig.value.should eq 100
world.getConfig_ptr.value.value.should eq 100
end

it "can be added and deleted from a world" do
world = ECS::World.new
expect_raises(Exception) { world.getConfig }
world.getConfig?.should be_nil
world.add(Config.new(100))
world.getConfig?.should be_truthy
world.getConfig.value.should eq 100
world.remove(Config)
world.getConfig?.should be_nil
end
end

class SystemGenerateEvent(Event) < ECS::System
Expand Down
23 changes: 20 additions & 3 deletions src/myecs.cr
Original file line number Diff line number Diff line change
Expand Up @@ -635,16 +635,33 @@ module ECS
{% if obj.annotation(ECS::Singleton) %}
{% obj_name = obj.id.split("::").last.id %}
def get{{obj_name}}
@pools[{{COMP_INDICES[obj]}}].as(Pool({{obj}})).get_component?(Entity.new(self, NO_ENTITY)) || raise "{{obj}} was not created"
@pools[{{COMP_INDICES[obj]}}].as(Pool({{obj}})).get_component?(NO_ENTITY) || raise "{{obj}} was not created"
end

def get{{obj_name}}?
@pools[{{COMP_INDICES[obj]}}].as(Pool({{obj}})).get_component?(Entity.new(self, NO_ENTITY))
@pools[{{COMP_INDICES[obj]}}].as(Pool({{obj}})).get_component?(NO_ENTITY)
end

def get{{obj_name}}_ptr
@pools[{{COMP_INDICES[obj]}}].as(Pool({{obj}})).get_component_ptr(Entity.new(self, NO_ENTITY))
@pools[{{COMP_INDICES[obj]}}].as(Pool({{obj}})).get_component_ptr(NO_ENTITY)
end

def add(comp : {{obj}})
@pools[{{COMP_INDICES[obj]}}].as(Pool({{obj}})).add_component(NO_ENTITY, comp)
end

def set(comp : {{obj}})
@pools[{{COMP_INDICES[obj]}}].as(Pool({{obj}})).add_or_update_component(NO_ENTITY, comp)
end

def remove(typ : {{obj}}.class)
@pools[{{COMP_INDICES[obj]}}].remove_component(NO_ENTITY)
end

def remove_if_present(typ : {{obj}}.class)
@pools[{{COMP_INDICES[obj]}}].try_remove_component(NO_ENTITY)
end

{% end %}

{% end %}
Expand Down

0 comments on commit 5ffbc8d

Please sign in to comment.