Skip to content

Felid-Force-Studios/StaticEcs-Unity

Repository files navigation

Version

LANGUAGE

RU EN


Static ECS - C# Entity component system framework - Unity module

Limitations and Features:

  • Not thread safe
  • There may be minor API changes

Table of Contents

Contacts

Installation

Must also be installed StaticEcs

  • As source code

    From the release page or as an archive from the branch. In the master branch there is a stable tested version
  • Installation for Unity

    • As a git module in Unity PackageManager
      https://github.com/Felid-Force-Studios/StaticEcs-Unity.git
    • Or adding to the manifest Packages/manifest.json
      "com.felid-force-studios.static-ecs-unity": "https://github.com/Felid-Force-Studios/StaticEcs-Unity.git"

Guide

The module provides additional integration options with the Unity engine:

Connection:

ECS runtime data monitoring and management window
To connect worlds and systems to the editor window it is necessary to call a special method when initializing the world and systems
specifying the world or systems required

        ClientWorld.Create(WorldConfig.Default());
        //...
        EcsDebug<ClientWorldType>.AddWorld(); // Between creation and initialization
        //...
        ClientWorld.Initialize();
        
        ClientSystems.Create();
        //...
        ClientSystems.Initialize();
        EcsDebug<ClientWorldType>.AddSystem<ClientSystemsType>(); // After initialization

Entity providers:

A script that adds the ability to configure an entity in the Unity editor and automatically create it in the ECS world
Add the StaticEcsEntityProvider script to an object in the scene:

EntityProvider.png

Usage type - creation type, automatically when Start(), Awake() is called, or manually
On create type - action after creating the provider, delete the StaticEcsEntityProvider component from the object, delete the entire object, or nothing
On destroy type - action when destroying the provider, destroy the entity or nothing
Prefab - allows referring to the provider prefab, while changing component data will be blocked
Wotld - the type of world in which the entity will be created
Entity ID - entity identifier in runtime
Entity GID - global entity identifier in runtime
Standard components - standard component data Components - component data Tags - entity tags
Masks - entity masks

Event providers:

A script that adds the ability to configure an event in the Unity editor and automatically send it to the ECS world
Add the StaticEcsEventProvider script to an object in the scene:

EventProvider.png

Usage type - creation type, automatically when Start(), Awake() is called, or manually
On create type - action after creation, delete the StaticEcsEventProvider component from the object, delete the entire object, or nothing
Wotld - type of world in which the event will be sent
Type - event type

Templates:

Class generators are optionally available in the Assets/Create/Static ECS/ asset creation menu

Burst

For highly optimized iterations, you can use special Burst-compatible systems.

  • Install Burst in your project.
  • Allow unsafe code in the project
  • Generate a system using Assets/Create/Static ECS/Burst system.

As a result, you will get the following system:
You need to describe the InvokeOne function for the logic of processing a single entity.
You can also optionally configure the following parameters:

  • entityStatusType - type of iterated entity
  • componentStatus - type of iterated components
  • clusters - clusters, all active by default.
  • with - additional filter (tags, components, etc.).
  • parallel - whether iteration will be run in parallel.
  • minEntitiesPerThread - minimum number of entities per thread, 64 by default.
  • workersLimit - maximum number of threads, default is all available
  • InvokeBlock function - you can override the entity block processing function for special optimizations such as SIMD, etc. (does not override the InvokeOne function)
public unsafe struct UpdateEntitiesBurstSystem : IUpdateSystem {
    private const EntityStatusType entityStatusType = EntityStatusType.Enabled;
    private const ComponentStatus componentStatus = ComponentStatus.Enabled;
    private static readonly ushort[] clusters = Array.Empty<ushort>(); // Empty == all clusters
    private static readonly WithNothing with = default;

    private static bool parallel;
    private static uint minEntitiesPerThread; // default - 64
    private static uint workersLimit;         // default - max threads

    [MethodImpl(AggressiveInlining)]
    public void BeforeUpdate() { }

    [MethodImpl(AggressiveInlining)]
    public void AfterUpdate() { }

    [MethodImpl(AggressiveInlining)]
    private void InvokeOne(ref Position position, ref Direction direction, int worker) {
        // TODO Write a function for processing a single entity here"
    }

    [MethodImpl(AggressiveInlining)]
    private void InvokeBlock(Position* positions, Direction* directions, int worker, uint dataOffest) {
        // Here, custom optimization of the entire entity block is possible. (SIMD, unroll, etc.)
        for (var i = 0; i < Const.ENTITIES_IN_BLOCK; i++) {
            var dIdx = i + dataOffest;
            InvokeOne(ref positions[dIdx], ref directions[dIdx], worker);
        }
    }

    #region GENERATED
    // ...
    #endregion
}

Static ECS view window:

WindowMenu.png

Entities/Table - entity view table

EntitiesTable.png

  • Filter allows select the necessary entities
  • Entity GID allows to find an entity by its global identifier
  • Select allows to select the columns to be displayed
  • Show data allows to select the data to be displayed in the columns
  • Max entities result maximum number of displayed entities

To display component data in a table, you must: set the StaticEcsEditorTableValue attribute in the component for field or property

public struct Position : IComponent {
    [StaticEcsEditorTableValue]
    public Vector3 Val;
}

To display a different component name, you must set the StaticEcsEditorName attribute on the component

[StaticEcsEditorName("My velocity")]
public struct Velocity : IComponent {
    [StaticEcsEditorTableValue]
    public float Val;
}

To set the color of the component, you must set the StaticEcsEditorColor attribute in the component (you can set RGB or HEX color)

[StaticEcsEditorColor("f7796a")]
public struct Velocity : IComponent {
    [StaticEcsEditorTableValue]
    public float Val;
}

entity control buttons are also available

  • eye icon - open the entity for viewing
  • lock - lock the entity in the table
  • trash - destroy the entity in the world

Viewer - entity view window

Displays all entity data with the ability to modify, add and delete components

EntitiesViewer.png

By default, only public object fields marked with the attribute [Serializable]

  • To display a private field, you must mark it with the attribute [StaticEcsEditorShow]
  • To hide a public field, you must mark it with the attribute [StaticEcsEditorHide]
  • To disable value editing in play mode, you can mark it with the attribute [StaticEcsEditorRuntimeReadOnly]
public struct SomeComponent : IComponent {
    [StaticEcsEditorShow]
    [StaticEcsEditorRuntimeReadOnly]
    private int _showData;
    
    [StaticEcsEditorHide]
    public int HideData;
}

Entities/Builder - entity constructor

Allows you to customize and create a new entity at runtime (Similar to entity provider)

EntitiesBuilder.png

Stats - statistics window

Displays all world, component and event data

Stats.png

Events/Table - event table

Displays recent events, their details and the number of subscribers who have not read the event

EventsTable.png

Events marked in yellow mean they are suppressed
Events marked in gray mean that they have been read by all subscribers

To display these components in a table, you must set the StaticEcsEditorTableValue attribute in the event for field or property

public struct DamageEvent : IEvent {
    public float Val;

    [StaticEcsEditorTableValue]
    public string ShowData => $"Damage {Val}";
}

The StaticEcsEditorColor attribute must be set to set the event color (can be set to RGB or HEX color)

[StaticEcsEditorColor("f7796a")]
public struct DamageEvent : IEvent {

}

The StaticEcsIgnoreEvent attribute must be set to ignore the event in the editor

[StaticEcsIgnoreEvent]
public struct DamageEvent : IEvent {

}

Viewer - event viewer

Allows you to view and modify (unread only) event data

EventsViewer.png

Events/Builder - event constructor

Allows you to configure and create a new event at runtime

EventsBuilder.png

Systems

Displays all systems in the order in which they are executed
Allows turning systems on and off during runtime
Displays the average execution time of each system

Systems.png

Settings - editor settings

Settings.png

Update per second - allows to define how many times per second the data of an open tab should be updated

Questions

How to create a custom drawing method for a type?

To implement your own editor for a specific type or component, you need in the Editor folder of your project
Create a class that implements IStaticEcsValueDrawer or IStaticEcsValueDrawer<T>
method DrawValue displays information on tabs Entity viever, Event viever и StaticEcsEntityProvider, StaticEcsEventProvider
method DrawTableValue displays information on tabs Entity table, Event table

Example:

public sealed class IntDrawer : IStaticEcsValueDrawer<int> {
    public override bool DrawValue(ref DrawContext ctx, string label, ref int value) {
        BeginHorizontal();
        PrefixLabel(label);
        var newValue = IntField(GUIContent.none, value);
        EndHorizontal();
        if (newValue == value) {
            return false;
        }

        value = newValue;
        return true;
    }

    public override void DrawTableValue(ref int value, GUIStyle style, GUILayoutOption[] layoutOptions) {
        SelectableLabel(value.ToString(CultureInfo.InvariantCulture), style, layoutOptions);
    }
}

How to use attributes without having a dependency on this module?

It is necessary to copy the attributes by saving the namespace from \Runtime\Attributes.cs, after that the attributes will be correctly detected by the editor.

License

MIT license

About

C# Hierarchical Inverted Bitmap ECS framework - Unity module

Topics

Resources

License

Stars

Watchers

Forks

Languages