Giter Club home page Giter Club logo

ecsts's Introduction

ECS-TS

A simple to use entity component system library written in TypeScript.

It is meant to be used for any use case. So you will not find any game specific logic in this library.

Install

npm install @trixt0r/ecs

Examples

Checkout the examples.

Check the rectangles example out, if you do not want to checkout the code.

Usage

The main parts of this library are

Component

A Component is defined as an interface with no specific methods or properties.
I highly suggest you to implement your components as classes, since the systems will rely on those.

For example, you could define a position like this:

import { Component } from '@trixt0r/ecs';

class Position implements Component {
  constructor(public x = 0, public y = 0) {}
}

Entity

Entities are the elements, your systems will work with and have an unique identifier.

Since this library doesn't want you to tell, how to generate your ids, the base class AbstractEntity is abstract.
This means your entity implementation should extend AbstractEntity.

For example, you could do something like this:

import { AbstractEntity } from '@trixt0r/ecs';

class MyEntity extends AbstractEntity {
  constructor() {
    super(makeId());
  }
}

Adding components is just as simple as:

myComponent.components.add(new Position(10, 20));

An entity, is a Dispatcher, which means, you can register an EntityListener on it, to check whether a component has been added, removed, the components have been sorted or cleared.

System

Systems implement the actual behavior of your entities, based on which components they own.

For programming your own systems, you should implement the abstract class System.
This base class provides basic functionalities, such as

  • an updating flag, which indicates whether a system is still updating.
  • an active flag, which tells the engine to either run the system in the next update call or not.
  • an engine property, which will be set/unset, as soon as the system gets added/removed to/from an engine.

A system is also a Dispatcher, which means, you can react to any actions happening to a system, by registering a SystemListener.

Here is a minimal example of a system, which obtains a list of entities with the component type Position.

import { System, Aspect } from '@trixt0r/ecs';

class MySystem extends System {
  private aspect: Aspect;

  constructor() {
    super(/* optional priority here */);
  }

  onAddedToEngine(engine: Engine): void {
    // get entities by component 'Position'
    this.aspect = Aspect.for(engine).all(Position);
  }

  async process(): void {
    const entities = this.aspect.entities;
    entities.forEach(entity => {
      const position = entity.components.get(Position);
      //... do your logic here
    });
  }
}

Note that process can be async.
If your systems need to do asynchronous tasks, you can implement them as those. Your engine can then run them as such.
This might be useful, if you do not have data which needs to be processed every frame.

In order to keep your focus on the actual system and not the boilerplate code around, you can use the AbstractEntitySystem.

The class will help you by providing component types for directly defining an aspect for your system. The above code would become:

import { System, Aspect } from '@trixt0r/ecs';

class MySystem extends AbstractEntitySystem<MyEntity> {

  constructor() {
    super(/* optional priority here */, [Position]);
  }

  processEntity(entity: MyEntity): void {
    const position = entity.components.get(Position);
    //... do your logic here
  }
}

Engine

An Engine ties systems and entities together.
It holds collections of both types, to which you can register listeners. But you could also register an EngineListener, to listen for actions happening inside an engine.

Here is a minimal example on how to initialize an engine and add systems and/or entities to it:

import { Engine, EngineMode } from '@trixt0r/ecs';

// Init the engine
const engine = new Engine();

engine.systems.add(new MySystem());
engine.entities.add(new MyEntity());

// anywhere in your business logic or main loop
engine.run(delta);

// if you want to perform your tasks asynchronously
engine.run(delta, EngineMode.SUCCESSIVE); // Wait for a task to finish
// or...
engine.run(delta, EngineMode.PARALLEL); // Run all systems asynchronously in parallel

Support

If you find any odd behavior or other improvements, feel free to create issues. Pull requests are also welcome!

Otherwise you can help me out by buying me a coffee.

paypal

Buy Me A Coffee

ecsts's People

Contributors

dependabot[bot] avatar trixt0r avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

ecsts's Issues

Multiple components added does not trigger

  let loginButtonEntity = new Entity();
    this.engine.entities.add(loginButtonEntity);
    loginButtonEntity.components.add(
      new RectangleComponent(50, 100, 400, 100, 0xffe800),
      new ClickableComponent()
    );

Does not get an onAddedComponents event triggered however...

   loginButtonEntity.components.add(
      new RectangleComponent(50, 100, 400, 100, 0xffe800),
    );
    loginButtonEntity.components.add(new ClickableComponent());
    this.engine.addListener({
      onAddedEntities: e => {
        const id = e.id as number;

        e.addListener({
          onAddedComponents: c => {``` the `onAddedComponents` appears to be a singular component but not named as such.  Could this be the problem?  Same for `onAddedEntities` only having a single entity.

Bad return in the readme

async processEntity(entity: MyEntity): void {
    const position = entity.components.get(Position);
    //... do your logic here
}

Would return a Promise<void>, or just don't include the return as its inferred.

Type 'MyComponent' has no properties in common with type 'Component'.

When you implement a Component with extra properties, typescript gets mad because those new properties don't match to the strict Component interface contract. Thus the error Type 'MyComponent' has no properties in common with type 'Component'.

Screenshot from 2020-07-01 10-51-20

A solution might be to add an index property such as shown below, although I'm not sure it's the best solution.
Screenshot from 2020-07-01 10-47-51

Web workers?

Have you tried/considered using something like https://threads.js.org for the asynchronous case? Curious if the messaging passing between system would be too high to be valuable.

Type error when getting component in a system

I think there is something funny with the Component interface type and my specific TypeScript version.

I defined a component of HasLifeforce and a LifeforceSystem system.

In my system, when I try to get components by their types, I get the following error:

// system
      const lifeforce = entity.components.get<HasLifeforce>(HasLifeforce);
    // the (HasLifeforce) in parenthesis is marked
Argument of type 'typeof HasLifeforce' is not assignable to parameter of type 'string | ComponentClass<HasLifeforce>'.
  Type 'typeof HasLifeforce' is not assignable to type 'ComponentClass<HasLifeforce>'.
    Types of parameters 'lifeforce' and 'args' are incompatible.
      Type 'unknown' is not assignable to type 'number | undefined'.
        Type 'unknown' is not assignable to type 'number'.

I'm using:

    "typescript": "^4.5.3"

I define my component similar to your example with and get the error:

import { Component } from "@trixt0r/ecs";

export class HasLifeforce implements Component {
  constructor(public lifeforce: number = 0) {}
}

Yet if I write it as the following, the error in the system does not pop up and the typing is fine.

import { Component } from "@trixt0r/ecs";

export class HasLifeforce implements Component {
  lifeforce = 0;
}

image

Any ideas? I'll try to make a reproducible example.
The transpiled code works either way.

Adding a component to an Entity inside the System's processEntity step doesn't propogate

Love this library <3

Problem

I've tried to add a Component to an Entity during the processEntity method of a System like entity.components.add(new components.CameraFollow());, but it seems like that component never gets added. In other Systems, this entity will not have that component attached, even after this process tick.

Expected Behavior

I expect that I can add a new component directly to the entity using entity.components.add(newComponent) during the processEntity step, and have that component persist in the entity

Workaround

As a work around, I've had to clone the entity, remove the old entity, add the new component, and add the new entity into the engine. This seems to trigger whatever events are required to keep the entity persistent in the system.

Screenshot from 2020-06-29 10-08-22

Rename Entity to AbstractEntity?

Since you have to extend anyways (<3 that) it would be cleaner to be able to write

export default class Entity extends AbstractEntity {
  constructor(id?: number) {
   ...
  }

Spatial/geo/area separation of entities, am I doing it right?

Hi. I want to make some kind of 'spatial' separation of my entities and wondering if my approach is sane.

Background: my game is set in space with multiple star systems, where in each star you have planet and ship entities. I have a system for telling ships where to fly next and I want their destinations to only be planets of the same star system.

I created a class called MappedEntitiesAspectListener implementing AspectListener that listens to additions and removals of entities from the engine. The class is given a custom mapper function for mapping entities to different keys based on whatever. Additionally, you can get the entities collected by this class given the mapped key.

This is an example demonstrating the functionality, please let me know if it's sane. If it is, and you wish, I will create a PR with a cleaner example for your examples folder.

import { nanoid } from "nanoid";
import {
  Component,
  Engine,
  AbstractEntity,
  EntityCollection,
  AspectListener,
  EntityListener,
} from "@trixt0r/ecs";

class InStar implements Component {
  constructor(public starId: number) {}
}

class MyEntity extends AbstractEntity {
  constructor() {
    super(nanoid(6));
  }
}

class PlanetEntity extends MyEntity {
  constructor(starId: number) {
    super();
    this.components.add(new InStar(starId));
  }
}

const engine = new Engine();

class MappedEntitiesAspectListener<Key> implements AspectListener {
  constructor(protected mapperFn: (entity: AbstractEntity) => Key) {}

  private mapping = new Map<Key, EntityCollection>();

  getByKey(key: Key): EntityCollection | undefined {
    return this.mapping.get(key);
  }

  onAddedEntities(
    ...entities: AbstractEntity<Component, EntityListener<Component>>[]
  ): void {
    entities.forEach((entity) => {
      const key = this.mapperFn(entity);
      if (this.mapping.has(key)) {
        this.mapping.get(key)!.add(entity);
      } else {
        this.mapping.set(key, new EntityCollection([entity]));
      }
    });
  }

  onRemovedEntities(
    ...entities: AbstractEntity<Component, EntityListener<Component>>[]
  ): void {
    entities.forEach((entity) => {
      const key = this.mapperFn(entity);
      this.mapping.get(key)?.remove(entity);
    });
  }
}

const entitiesByStarId = new MappedEntitiesAspectListener((entity) => {
  const inStar = entity.components.get(InStar);
  return inStar ? inStar.starId : undefined;
});

engine.addListener(entitiesByStarId);
const somePlanet = new PlanetEntity(1);

engine.entities.add(somePlanet);
engine.entities.add(new PlanetEntity(1));
engine.entities.add(new PlanetEntity(1));
engine.entities.add(new PlanetEntity(2));
engine.entities.add(new PlanetEntity(2));
engine.entities.add(new PlanetEntity(3));
engine.entities.add(new PlanetEntity(4));
engine.entities.add(new PlanetEntity(4));
engine.entities.add(new PlanetEntity(4));
engine.entities.add(new PlanetEntity(4));

function showPlanetsForStarId(starId: number) {
  const planets = entitiesByStarId.getByKey(starId);
  console.log(
    `Star ${starId} has ${planets?.length} planets`,
    planets?.map((entity) => {
      return entity.id;
    })
  );
}

showPlanetsForStarId(1);
showPlanetsForStarId(2);
showPlanetsForStarId(3);
showPlanetsForStarId(4);
console.log("removing some planet");
engine.entities.remove(somePlanet);
showPlanetsForStarId(1);

Example output:
image

Question: Aspects as Dispatcher?

As previously talked about now that all Systems have an aspect could you have lifecycle events on the Aspect? Stuff like added/removed component/entity.

OnComponentAdded/Removed at the system level?

I have a situation where I have init and cleanup at the system level when a component is added to an entity. Can do in process but it gets run every frame. Would be ideal to have as a dispatched event at the engine &&|| system level.

Consider using integer for ID

Starting a bigger project and constantly casting the id: to string|number. The id is suppose to be more like a primary key and used for fast lookups. Especially in es6 maps the lookup speed of integers versus string when used constantly is dramatic. If strings are needed they are better placed in Tag/Debug components.

Getting an entity directly by its id

Hello. How do you feel about getting entities by ids?
I have something like this when I want to find a planet in my game with a specific id.

this.engine.entities.find((x) => x.id === planetId) ?? null;

I looked at your code for Collection and it's rather type-agnostic and keeps the elements in an array. If it "knew" it holds elements with an id, like entities, it could store them in a map/dict and we could fetch those instantly instead of .finding through the entire collection.

Thinking about this, I thought maybe listening to an "onAdded" event somewhere and track id->entity somehow in my own code, but it would be nice to have this in the library-level.

Is that possible? Does it accidentally break the data-driven nature of ECS possible optimizations?
I'd be happy to hear your input. Thanks for the cool library.

Consider changing Filter to Aspect

Its wonderful that you have component filtering. Usually in ECS parlance this is called an Aspect. Unfortunately filter is super overloaded in games for effects especially.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.