{"id":13662528,"url":"https://github.com/scellecs/morpeh","last_synced_at":"2025-09-07T07:12:55.324Z","repository":{"id":40412619,"uuid":"235087834","full_name":"scellecs/morpeh","owner":"scellecs","description":"🎲 ECS Framework for Unity Game Engine and .Net Platform","archived":false,"fork":false,"pushed_at":"2025-08-09T17:09:25.000Z","size":5826,"stargazers_count":611,"open_issues_count":7,"forks_count":49,"subscribers_count":17,"default_branch":"main","last_synced_at":"2025-08-31T16:54:04.543Z","etag":null,"topics":["csharp","ecs","ecs-framework","entity-component-system","game-development","unity","unity3d","unity3d-framework","unity3d-npm-package"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/scellecs.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.MD","contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-01-20T11:38:34.000Z","updated_at":"2025-08-30T11:05:08.000Z","dependencies_parsed_at":"2023-09-26T14:34:23.524Z","dependency_job_id":"2088e76e-f30b-4202-a2b8-4afc34744c12","html_url":"https://github.com/scellecs/morpeh","commit_stats":null,"previous_names":["x-crew/morpeh"],"tags_count":278,"template":false,"template_full_name":null,"purl":"pkg:github/scellecs/morpeh","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scellecs%2Fmorpeh","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scellecs%2Fmorpeh/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scellecs%2Fmorpeh/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scellecs%2Fmorpeh/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/scellecs","download_url":"https://codeload.github.com/scellecs/morpeh/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scellecs%2Fmorpeh/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":274006636,"owners_count":25206184,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-07T02:00:09.463Z","response_time":67,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["csharp","ecs","ecs-framework","entity-component-system","game-development","unity","unity3d","unity3d-framework","unity3d-npm-package"],"created_at":"2024-08-02T05:02:01.220Z","updated_at":"2025-09-07T07:12:55.307Z","avatar_url":"https://github.com/scellecs.png","language":"C#","readme":"\u003cp align=\"center\"\u003e\n    \u003cimg src=\"Scellecs.Morpeh/Unity/Utils/Editor/Resources/logo.png\" width=\"260\" height=\"260\" alt=\"Morpeh\"\u003e\n\u003c/p\u003e\n\n# Morpeh [![License](https://img.shields.io/github/license/scellecs/morpeh?color=3750c1\u0026style=flat-square)](LICENSE.md) [![Unity](https://img.shields.io/badge/Unity-2020.3+-2296F3.svg?color=3750c1\u0026style=flat-square)](https://unity.com/) [![Version](https://img.shields.io/github/package-json/v/scellecs/morpeh?color=3750c1\u0026style=flat-square\u0026filename=Scellecs.Morpeh/package.json)](Scellecs.Morpeh/package.json)\n🎲 **ECS Framework for Unity Game Engine and .Net Platform**  \n\n* Simple Syntax.  \n* Plug \u0026 Play Installation.  \n* No code generation (*yet*).  \n* Structure-Based and Cache-Friendly.\n\nKey points for people familiar with other ECS frameworks:\n\n* Archetype-based, but stores data separately from archetypes.\n Archetypes are used only for filtering, and there's no archetype transition graph,\n which means you should not worry about performance degradation over time for lots of \n chaotically changing entities.\n* Components are stored in \"stashes\", which are also known as \"pools\" in other frameworks.\n* Filters are used to select entities based on component types, but unlike\n other frameworks they should not be used in-place, and should rather be declared\n in the system OnAwake and stored in a variable.\n* Filters directly store archetypes, and you can know if the filter is empty\n or not without iterating over it, possibly reducing systems idle time, especially\n in the case of a large number of systems, which is generally useful for Unity's IL2CPP.\n* Designed to work well with a large quantity of different component types\n and systems in a single world (several thousands of component types and systems), but\n not necessarily with a large number of entities.\n* Designed to work well in a large team with a large codebase, reducing the amount\n of things a typical developer should remember and account for. You are free\n to migrate entities by doing structural changes even if an entity contains tens of\n different components without a significant performance impact.\n\n## 📖 Table of Contents\n\n* [Migration](#-migration-to-new-version)\n* [How To Install](#-how-to-install)\n  * [Unity Engine](#unity-engine)\n  * [.Net Platform](#net-platform)\n* [Introduction](#-introduction)\n  * [Base concept of ECS pattern](#-base-concept-of-ecs-pattern)\n  * [Getting Started](#-getting-started)\n  * [Advanced](#-advanced)\n    * [Filter Extensions](#-filter-extensions)\n    * [Filter Disposing](#-filter-disposing)\n    * [Aspects](#-aspects)\n    * [Component Disposing](#-component-disposing)\n    * [Unity Jobs And Burst](#-unity-jobs-and-burst)\n    * [Defines](#%EF%B8%8F-defines)\n    * [World Plugins](#%EF%B8%8F-world-plugins)\n    * [World Browser](#-world-browser)\n    * [Metrics](#-metrics)\n    * [Stash size](#-stash-size)\n    * [Collections](#%EF%B8%8F-collections)\n* [Plugins](#-plugins)\n* [Examples](#-examples)\n* [Games](#-games)\n* [License](#-license)\n* [Contacts](#-contacts)\n\n## 🛸 Migration To New Version \n\nEnglish version: [Migration Guide](MIGRATION.md)  \nRussian version: [Гайд по миграции](MIGRATION_RU.md)\n\n## 📖 How To Install \n\n### Unity Engine \n\nMinimal required Unity Version is 2020.3.*  \nRequires [Git](https://git-scm.com/) for installing package.  \nRequires [Tri Inspector](https://github.com/codewriter-packages/Tri-Inspector) for drawing the inspector.\n\n\u003cdetails\u003e\n    \u003csummary\u003eOpen Unity Package Manager and add Morpeh URL.  \u003c/summary\u003e\n\n![installation_step1.png](Gifs~/installation_step1.png)  \n![installation_step2.png](Gifs~/installation_step2.png)\n\u003c/details\u003e\n\n\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;⭐ Master: https://github.com/scellecs/morpeh.git?path=Scellecs.Morpeh  \n\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;🚧 Stage:  https://github.com/scellecs/morpeh.git?path=Scellecs.Morpeh#stage-2024.1  \n\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;🏷️ Tag:  https://github.com/scellecs/morpeh.git?path=Scellecs.Morpeh#2024.1.1  \n\n### .Net Platform\n\nNuGet package URL: https://www.nuget.org/packages/Scellecs.Morpeh\n\n## 📖 Introduction\n### 📘 Base concept of ECS pattern\n\n#### 🔖 Entity\nAn identifier for components, which does not store any data but can be used to\naccess components. Logically, it is similar to a GameObject in Unity, but\nan Entity does not store any data itself.\n\nIt is a value type, and is trivially copyable. Underlying identifiers (IDs) are\nreused, but each reused ID is guaranteed to have a new generation, making each new\nEntity unique.\n\n```c#\nvar healthStash = this.World.GetStash\u003cHealthComponent\u003e();\nvar entity = this.World.CreateEntity();\n\nref var addedHealthComponent  = ref healthStash.Add(entity);\nref var gottenHealthComponent = ref healthStash.Get(entity);\n\n//if you remove the last entity component, it will be destroyed during the next world.Commit() call\nbool removed = healthStash.Remove(entity);\nhealthStash.Set(entity, new HealthComponent {healthPoints = 100});\n\nbool hasHealthComponent = healthStash.Has(entity);\n\nvar debugString = entity.ToString();\n\n//remove entity\nthis.World.RemoveEntity(entity);\n\n//check disposal\nbool isDisposed = this.World.IsDisposed(entity);\n\n//alternatively\nbool has = this.World.Has(entity);\n```\n\n\n#### 🔖 Component\nComponents are types which store components data.\nIn Morpeh, components are value types for performance purposes.\n```c#\npublic struct HealthComponent : IComponent {\n    public int healthPoints;\n}\n```\n\n#### 🔖 System\n\nTypes that process entities with a specific set of components.  \nEntities are selected using a filter.\n\nAll systems are represented by interfaces.\n\n```c#\npublic class HealthSystem : ISystem {\n    public World World { get; set; }\n\n    private Filter filter;\n    private Stash\u003cHealthComponent\u003e healthStash;\n\n    public void OnAwake() {\n        this.filter = this.World.Filter.With\u003cHealthComponent\u003e().Build();\n        this.healthStash = this.World.GetStash\u003cHealthComponent\u003e();\n    }\n\n    public void OnUpdate(float deltaTime) {\n        foreach (var entity in this.filter) {\n            ref var healthComponent = ref healthStash.Get(entity);\n            healthComponent.healthPoints += 1;\n        }\n    }\n\n    public void Dispose() {\n    }\n}\n```\n\nAll systems types:  \n* `IInitializer` - has OnAwake and Dispose methods only, which is convenient for executing startup logic\n* `ISystem` - main system that executes every frame in Update. Used for main game logic and data processing\n* `IFixedSystem` - system that executes in FixedUpdate with fixed time step\n* `ILateSystem` - system that executes in LateUpdate, after all Updates. Useful for logic that should run after main updates\n* `ICleanupSystem` - system that executes after ILateSystem. Designed for cleanup operations, resetting states, and handling end-of-frame tasks\n\nBeware that ScriptableObject-based systems do still exist in 2024 version, but they are deprecated and will be removed in the future.\n\n#### 🔖 SystemsGroup\n\nThe type that contains the systems. Consider them as a \"feature\" to group the systems by their common purpose.\n\n```c#\nvar newWorld = World.Create();\n\nvar newSystem = new HealthSystem();\nvar newInitializer = new HealthInitializer();\n\nvar systemsGroup = newWorld.CreateSystemsGroup();\nsystemsGroup.AddSystem(newSystem);\nsystemsGroup.AddInitializer(newInitializer);\n\n//it is a bad practice to turn systems off and on, but sometimes it is very necessary for debugging\nsystemsGroup.DisableSystem(newSystem);\nsystemsGroup.EnableSystem(newSystem);\n\nsystemsGroup.RemoveSystem(newSystem);\nsystemsGroup.RemoveInitializer(newInitializer);\n\nnewWorld.AddSystemsGroup(order: 0, systemsGroup);\nnewWorld.RemoveSystemsGroup(systemsGroup);\n```\n\n#### 🔖 World\nA type that contains entities, components stashes, systems and root filter.\n```c#\nvar newWorld = World.Create();\n//a variable that specifies whether the world should be updated automatically by the game engine.\n//if set to false, then you can update the world manually.\n//and can also be used for game pauses by changing the value of this variable.\nnewWorld.UpdateByUnity = true;\n\nvar newEntity = newWorld.CreateEntity();\nnewWorld.RemoveEntity(newEntity);\n\nvar systemsGroup = newWorld.CreateSystemsGroup();\nsystemsGroup.AddSystem(new HealthSystem());\n\nnewWorld.AddSystemsGroup(order: 0, systemsGroup);\nnewWorld.RemoveSystemsGroup(systemsGroup);\n\nvar filter = newWorld.Filter.With\u003cHealthComponent\u003e();\n\nvar healthStash = newWorld.GetStash\u003cHealthComponent\u003e();\nvar reflectionHealthStash = newWorld.GetReflectionStash(typeof(HealthComponent));\n\n//manually world updates\nnewWorld.Update(Time.deltaTime);\nnewWorld.FixedUpdate(Time.fixedDeltaTime);\nnewWorld.LateUpdate(Time.deltaTime);\nnewWorld.CleanupUpdate(Time.deltaTime);\n\n//apply all entity changes, filters will be updated.\n//automatically invoked between systems\nnewWorld.Commit();\n```\n\n#### 🔖 Filter\nA type that allows filtering entities constrained by conditions With and/or Without.  \nYou can chain them in any order and quantity.  \nCall `Build()` to finalize the filter for further use.\n```c#\nvar filter = this.World.Filter.With\u003cHealthComponent\u003e()\n                              .With\u003cBooComponent\u003e()\n                              .Without\u003cDummyComponent\u003e()\n                              .Build();\n\nvar firstEntityOrException = filter.First();\nvar firstEntityOrNull = filter.FirstOrDefault();\n\nbool filterIsEmpty = filter.IsEmpty();\nbool filterIsNotEmpty = filter.IsNotEmpty();\nint filterLengthCalculatedOnCall = filter.GetLengthSlow();\n\n```\n\n#### 🔖 Stash\nA type that stores components data.\n\n```c#\nvar healthStash = this.World.GetStash\u003cHealthComponent\u003e();\nvar entity = this.World.CreateEntity();\n\nref var addedHealthComponent  = ref healthStash.Add(entity);\nref var gottenHealthComponent = ref healthStash.Get(entity);\n\nbool removed = healthStash.Remove(entity);\n\nhealthStash.Set(entity, new HealthComponent {healthPoints = 100});\n\nbool hasHealthComponent = healthStash.Has(entity);\n\n//delete all HealthComponent from the world (affects all entities)\nhealthStash.RemoveAll();\n\nbool healthStashIsEmpty = healthStash.IsEmpty();\nbool healthStashIsNotEmpty = healthStash.IsNotEmpty();\n\nvar newEntity = this.World.CreateEntity();\n//transfers a component from one entity to another\nhealthStash.Migrate(from: entity, to: newEntity);\n\n//not a generic variation of stash, so we can only do a limited set of operations\nvar reflectionHealthCache = newWorld.GetReflectionStash(typeof(HealthComponent));\n\n//set default(HealthComponent) to entity\nreflectionHealthCache.Set(entity);\n\nbool removed = reflectionHealthCache.Remove(entity);\n\nbool hasHealthComponent = reflectionHealthCache.Has(entity);\n```\n\n#### 🅿️ Providers\n\nMorpeh has providers for integration with Unity game engine.  \nThis is a `MonoBehaviour` that allows you to create associations between GameObject and Entity.  \nFor each ECS component, you can create a provider; it will allow you to change the component values directly through the inspector, use prefabs and use the workflow as close as possible to classic Unity development.  \n\nThere are two main types of providers.  \n* **EntityProvider**. It automatically creates an associated entity and allows you to access it.  \n* **MonoProvider**. It is an inheritor of EntityProvider, and adds a component to the entity. Allows you to view and change component values directly in the playmode.\n\n\u003e [!NOTE]  \n\u003e Precisely because providers allow you to work with component values directly from the kernel, because components are not stored in the provider, it only renders them;  \n\u003e We use third-party solutions for rendering inspectors like Tri Inspector or Odin Inspector.  \n\u003e It's a difficult task to render the completely different data that you can put into a component.\n\nAll providers do their work in the `OnEnable()` and `OnDisable()` methods.  \nThis allows you to emulate turning components on and off, although the kernel does not have such a feature.  \n\nAll providers are synchronized with each other, so if you attach several providers to one GameObject, they will be associated with one entity, and will not create several different ones.  \n\nProviders can be inherited and logic can be overridden in the `Initialize()` and `Deinitialize()` methods.  \nWe do not use methods like `Awake()`, `Start()` and others, because the provider needs to control the creation of the entity and synchronize with other providers.  \nAt the time of calling `Initialize()`, the entity is definitely created.  \n\nAPI:\n```c#\nvar entityProvider = someGameObject.GetComponent\u003cEntityProvider\u003e();\nvar entity = entityProvider.Entity;\n```\n\n```c#\nvar monoProvider = someGameObject.GetComponent\u003cMyCustomMonoProvider\u003e();\n\nvar entity = monoProvider.Entity;\n//returns serialized data or direct value of component\nref var data = ref monoProvider.GetData();\nref var data = ref monoProvider.GetData(out bool existOnEntity);\nref var serializedData = ref monoProvider.GetSerializedData();\n\nvar stash = monoProvider.Stash;\n```\n\nWe also have one additional provider that allows you to destroy an entity when a GameObject is removed from the scene.  \nYou can simply hang it on a GameObject and no matter how many components are left on the entity, it will be deleted.  \nThe provider is called `RemoveEntityOnDestroy`.  \n\n---\n\n### 📘 Getting Started\n\u003e [!IMPORTANT]  \n\u003e All GIFs are hidden under spoilers. Press ➤ to open it.\n\nFirst step: install [Tri Inspector](https://github.com/codewriter-packages/Tri-Inspector).  \nSecond step: install Morpeh.\n\n\u003cdetails\u003e\n    \u003csummary\u003eAfter installation import ScriptTemplates and Restart Unity.  \u003c/summary\u003e\n\n![import_script_templates.gif](Gifs~/import_script_templates.gif)\n\u003c/details\u003e\n\nLet's create our first component and open it.\n\u003cdetails\u003e\n    \u003csummary\u003eRight click in project window and select \u003ccode\u003eCreate/ECS/Component\u003c/code\u003e.  \u003c/summary\u003e\n\n![create_component.gif](Gifs~/create_component.gif)\n\u003c/details\u003e\n\n\nAfter it, you will see something like this.\n```c#  \nusing Scellecs.Morpeh;\nusing UnityEngine;\nusing Unity.IL2CPP.CompilerServices;\n\n[Il2CppSetOption(Option.NullChecks, false)]\n[Il2CppSetOption(Option.ArrayBoundsChecks, false)]\n[Il2CppSetOption(Option.DivideByZeroChecks, false)]\n[System.Serializable]\npublic struct HealthComponent : IComponent {\n}\n```\n\u003e [!NOTE]  \n\u003e Don't care about attributes.  \n\u003e Il2CppSetOption attribute can give you better performance.  \n\u003e It is important to understand that this disables any checks for null, so in the release build any calls to a null object will lead to a hard crash.  \n\u003e We recommend that in places where you are in doubt about using this attribute, you check everything for null yourself.  \n\nAdd health points field to the component.\n\n```c#  \npublic struct HealthComponent : IComponent {\n    public int healthPoints;\n}\n```\n\nIt is okay.\n\nNow let's create our first system.\n\nCreate a new C# class somewhere in your project and give it a name.\n\n\u003e [!NOTE]\n\u003e You can also create IFixedSystem, ILateSystem and ICleanupSystem.  \n\u003e They are similar to MonoBehaviour's Update, FixedUpdate, LateUpdate. \n\u003e ICleanupSystem is called after all ILateSystem.\n\nA system looks like this:\n```c#  \nusing Scellecs.Morpeh;\nusing UnityEngine;\nusing Unity.IL2CPP.CompilerServices;\n\n[Il2CppSetOption(Option.NullChecks, false)]\n[Il2CppSetOption(Option.ArrayBoundsChecks, false)]\n[Il2CppSetOption(Option.DivideByZeroChecks, false)]\npublic sealed class HealthSystem : ISystem {\n    public World World { get; set; }\n    \n    public void OnAwake() {\n    }\n\n    public void OnUpdate(float deltaTime) {\n    }\n    \n    public void Dispose() {\n    }\n}\n```\n\nWe have to add a filter to find all the entities with `HealthComponent`.\n```c#  \npublic sealed class HealthSystem : ISystem {\n    private Filter filter;\n    \n    public World World { get; set; }\n    \n    public void OnAwake() {\n        this.filter = this.World.Filter.With\u003cHealthComponent\u003e().Build();\n    }\n\n    public void OnUpdate(float deltaTime) {\n    }\n    \n    public void Dispose() {\n    }\n}\n```\n\n\u003e [!NOTE]  \n\u003e You can chain filters by using `With\u003c\u003e` and `Without\u003c\u003e` in any order.  \n\u003e For example `this.World.Filter.With\u003cFooComponent\u003e().With\u003cBarComponent\u003e().Without\u003cBeeComponent\u003e().Build();`\n\n\u003e [!IMPORTANT]  \n\u003e Components are structs and if you want to change their values, then you must use `ref`.\n\u003e It is recommended to always use `ref` unless you specifically need a copy of the component.\n\nNow we can iterate over our entities.\n```c#  \npublic sealed class HealthSystem : ISystem {\n    public World World { get; set; }\n    \n    private Filter filter;\n    private Stash\u003cHealthComponent\u003e healthStash;\n    \n    public void OnAwake() {\n        this.filter = this.World.Filter.With\u003cHealthComponent\u003e().Build();\n        this.healthStash = this.World.GetStash\u003cHealthComponent\u003e();\n    }\n\n    public void OnUpdate(float deltaTime) {\n        foreach (var entity in this.filter) {\n            ref var healthComponent = ref healthStash.Get(entity);\n            Debug.Log(healthComponent.healthPoints);\n        }\n    }\n    \n    public void Dispose() {\n    }\n}\n```\n\nNow we need to add our newly created system to the world. We can do it by creating a `SystemGroup` and adding the system to it,\nand then adding the `SystemGroup` to the world.\n\nWorld.Default is created for you by default, but you can create your own worlds if you need to separate the logic.\nBeware that World.Default is updated automatically by the game engine, but you can disable it and update it manually.\nCustom worlds are not updated automatically, so you need to update them manually.\n\n```c#\npublic class Startup : MonoBehaviour {\n    private World world;\n    \n    private void Start() {\n        this.world = World.Default;\n        \n        var systemsGroup = this.world.CreateSystemsGroup();\n        systemsGroup.AddSystem(new HealthSystem());\n        \n        this.world.AddSystemsGroup(order: 0, systemsGroup);\n    }\n}\n```\n\nAttach the script to any GameObject and press play.\n\nNothing happened because we did not create our entities.  \n\nWe will focus on `GameObject`-based API because otherwise all you need to do is create an entity with `World.CreateEntity()`.\nTo do this, we need a provider that associates a `GameObject` with an entity.\n\nCreate a new provider.\n\n\u003cdetails\u003e\n    \u003csummary\u003eRight click the project window and select \u003ccode\u003eCreate/ECS/Provider\u003c/code\u003e.  \u003c/summary\u003e\n\n![create_provider.gif](Gifs~/create_provider.gif)\n\u003c/details\u003e\n\n```c#  \nusing Scellecs.Morpeh.Providers;\nusing Unity.IL2CPP.CompilerServices;\n\n[Il2CppSetOption(Option.NullChecks, false)]\n[Il2CppSetOption(Option.ArrayBoundsChecks, false)]\n[Il2CppSetOption(Option.DivideByZeroChecks, false)]\npublic sealed class HealthProvider : MonoProvider\u003c{YOUR_COMPONENT}\u003e {\n}\n```\n\nWe need to specify a component for the provider.\n```c#  \npublic sealed class HealthProvider : MonoProvider\u003cHealthComponent\u003e {\n}\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003eCreate new GameObject and add \u003ccode\u003eHealthProvider\u003c/code\u003e.  \u003c/summary\u003e\n\n![add_provider.gif](Gifs~/add_provider.gif)\n\u003c/details\u003e\n\nNow press play button, and you will see Debug.Log with healthPoints.  \nNice!\n\n---\n\n### 📖 Advanced\n\n#### 🧩 Filter Extensions\n\nFilter extensions are a way to reuse queries or their parts.\nLet's look at an example:  \n\nCreate a struct and implement the IFilterExtension interface.\n\n```c#  \npublic struct SomeExtension : IFilterExtension {\n    public FilterBuilder Extend(FilterBuilder rootFilter) =\u003e rootFilter.With\u003cTranslation\u003e().With\u003cRotation\u003e();\n}\n```\n\nThe next step is to call the Extend method in any order when requesting a filter.  \nThe Extend method continues query.\n\n```c#  \nprivate Filter filter;\n\npublic void OnAwake() {\n    this.filter = this.World.Filter.With\u003cTestA\u003e()\n                                   .Extend\u003cSomeExtension\u003e()\n                                   .With\u003cTestC\u003e()\n                                   .Build();\n}\n```\n\n#### 🧹 Filter Disposing\n`Filter.Dispose` allows you to completely remove the filter from the world, as if it never existed there.\n\n\u003e [!IMPORTANT]\n\u003e `Filter.Dispose` removes all filter instances across all systems where it was used, not just the instance on which `Dispose` was called.\n\n#### 🔍 Aspects\nAn aspect is an object-like wrapper that you can use to group a subset of an entity's components together into a single C# struct.\nAspects are useful for organizing components code and simplifying queries in your systems.  \n\nFor example, the Transform aspect groups together the position, rotation, and scale of components and enables you to access these components from a query that includes the Transform.\nYou can also define your own aspects with the IAspect interface.  \n\nComponents:\n```c#  \n    public struct Translation : IComponent {\n        public float x;\n        public float y;\n        public float z;\n    }\n    \n    public struct Rotation : IComponent {\n        public float x;\n        public float y;\n        public float z;\n        public float w;\n    }\n\n    public struct Scale : IComponent {\n        public float x;\n        public float y;\n        public float z;\n    }\n```\n\nLet's group them in an aspect:\n\n```c#  \npublic struct Transform : IAspect {\n    //Set on each call of AspectFactory.Get(Entity entity)\n    public Entity Entity { get; set; }\n    \n    private Stash\u003cTranslation\u003e translation;\n    private Stash\u003cRotation\u003e rotation;\n    private Stash\u003cScale\u003e scale;\n    \n    public ref Translation Translation =\u003e ref this.translation.Get(this.Entity);\n    public ref Rotation Rotation =\u003e ref this.rotation.Get(this.Entity);\n    public ref Scale Scale =\u003e ref this.scale.Get(this.Entity);\n\n    //Called once on world.GetAspectFactory\u003cT\u003e\n    public void OnGetAspectFactory(World world) {\n        this.translation = world.GetStash\u003cTranslation\u003e();\n        this.rotation = world.GetStash\u003cRotation\u003e();\n        this.scale = world.GetStash\u003cScale\u003e();\n    }\n}\n```\n\nLet's add an IFilterExtension implementation to always have a query.\n\n```c#  \npublic struct Transform : IAspect, IFilterExtension {\n    public Entity Entity { get; set;}\n    \n    public ref Translation Translation =\u003e ref this.translation.Get(this.Entity);\n    public ref Rotation Rotation =\u003e ref this.rotation.Get(this.Entity);\n    public ref Scale Scale =\u003e ref this.scale.Get(this.Entity);\n    \n    private Stash\u003cTranslation\u003e translation;\n    private Stash\u003cRotation\u003e rotation;\n    private Stash\u003cScale\u003e scale;\n\n    public void OnGetAspectFactory(World world) {\n        this.translation = world.GetStash\u003cTranslation\u003e();\n        this.rotation = world.GetStash\u003cRotation\u003e();\n        this.scale = world.GetStash\u003cScale\u003e();\n    }\n    public FilterBuilder Extend(FilterBuilder rootFilter) =\u003e rootFilter.With\u003cTranslation\u003e().With\u003cRotation\u003e().With\u003cScale\u003e();\n}\n```\n\nNow we write a system that uses our aspect.\n\n```c#  \npublic class TransformAspectSystem : ISystem {\n    public World World { get; set; }\n\n    private Filter filter;\n    private AspectFactory\u003cTransform\u003e transform;\n    \n    private Stash\u003cTranslation\u003e translation;\n    private Stash\u003cRotation\u003e rotation;\n    private Stash\u003cScale\u003e scale;\n    \n    public void OnAwake() {\n        //Extend filter with ready query from Transform\n        this.filter = this.World.Filter.Extend\u003cTransform\u003e().Build();\n        //Get aspect factory AspectFactory\u003cTransform\u003e\n        this.transform = this.World.GetAspectFactory\u003cTransform\u003e();\n\n        \n        for (int i = 0, length = 100; i \u003c length; i++) {\n            var entity = this.World.CreateEntity();\n            \n            ref var translationComponent = ref this.translation.Set(entity);\n            ref var rotationComponent = ref this.rotation.Set(entity);\n            ref var scaleComponent = ref this.scale.Set(entity);\n        }\n    }\n    public void OnUpdate(float deltaTime) {\n        foreach (var entity in this.filter) {\n            //Getting aspect copy for current entity\n            var trs = this.transform.Get(entity);\n\n            ref var trans = ref trs.Translation;\n            trans.x += 1;\n\n            ref var rot = ref trs.Rotation;\n            rot.x += 1;\n            \n            ref var scale = ref trs.Scale;\n            scale.x += 1;\n        }\n    }\n    \n    public void Dispose() {\n    }\n}\n```\n\n#### 🧹 Component Disposing\n\n\u003e [!IMPORTANT]  \n\u003e Make sure you don't have the `MORPEH_DISABLE_COMPONENT_DISPOSE` define enabled.  \n\nSometimes it becomes necessary to clear component values.\nFor this, it is enough that a component implements `IDisposable`. For example:\n\n```c#  \npublic struct PlayerView : IComponent, IDisposable {\n    public GameObject value;\n    \n    public void Dispose() {\n        Object.Destroy(value);\n    }\n}\n```\n\nAn initializer or a system needs to mark the stash as disposable. For example:\n\n```c# \npublic class PlayerViewDisposeInitializer : IInitializer {\n    public void OnAwake() {\n        this.World.GetStash\u003cPlayerView\u003e().AsDisposable();\n    }\n    \n    public void Dispose() {\n    }\n}\n```\n\nor\n\n```c# \npublic class PlayerViewSystem : ISystem {\n    public void OnAwake() {\n        this.World.GetStash\u003cPlayerView\u003e().AsDisposable();\n    }\n    \n    public void OnUpdate(float deltaTime) {\n        ...\n    }\n    \n    public void Dispose() {\n    }\n}\n```\n\nNow, when the component is removed from an entity, the `Dispose()` method\nwill be called on the `PlayerView` component.  \n\n####  🧨 Unity Jobs And Burst\n\n\u003e [!IMPORTANT]  \n\u003e Supported only in Unity. Subjected to further improvements and modifications.\n\nYou can convert `Filter` to `NativeFilter` which allows you to do component-based manipulations inside a Job.  \nConversion of `Stash\u003cT\u003e` to `NativeStash\u003cTNative\u003e` allows you to operate on components based on entity ids.  \n\nCurrent limitations:\n* `NativeFilter` and `NativeStash` and their contents should never be re-used outside of single system tick.\n* `NativeFilter` and `NativeStash` cannot be used in-between `World.Commit()` calls inside Morpeh.\n\nExample job scheduling:\n```c#  \npublic sealed class SomeSystem : ISystem {\n    private Filter filter;\n    private Stash\u003cHealthComponent\u003e stash;\n    ...\n    public void OnUpdate(float deltaTime) {\n        var nativeFilter = this.filter.AsNative();\n        var parallelJob = new ExampleParallelJob {\n            entities = nativeFilter,\n            healthComponents = stash.AsNative(),\n            // Add more native stashes if needed\n        };\n        var parallelJobHandle = parallelJob.Schedule(nativeFilter.length, 64);\n        parallelJobHandle.Complete();\n    }\n}\n```\n\nExample job:\n```c#\n[BurstCompile]\npublic struct TestParallelJobReference : IJobParallelFor {\n    [ReadOnly]\n    public NativeFilter entities;\n    public NativeStash\u003cHealthComponent\u003e healthComponents;\n        \n    public void Execute(int index) {\n        var entity = this.entities[index];\n        \n        ref var component = ref this.healthComponents.Get(entity, out var exists);\n        if (exists) {\n            component.Value += 1;\n        }\n        \n        // Alternatively, you can avoid checking existance of the component\n        // if the filter includes said component anyway\n        \n        ref var component = ref this.healthComponents.Get(entity);\n        component.Value += 1;\n    }\n}\n```\n\nFor flexible Job scheduling, you can use `World.JobHandle`.  \nIt allows you to schedule Jobs within one SystemsGroup, rather than calling `.Complete()` directly on the system.  \nPlanning between SystemsGroup is impossible because in Morpeh, unlike Entities or other frameworks, there is no dependency graph that would allow Jobs to be planned among all systems, taking into account dependencies.  \n\n\nExample scheduling:\n```c#  \npublic sealed class SomeSystem : ISystem {\n    private Filter filter;\n    private Stash\u003cHealthComponent\u003e stash;\n    ...\n    public void OnUpdate(float deltaTime) {\n        var nativeFilter = this.filter.AsNative();\n        var parallelJob = new ExampleParallelJob {\n            entities = nativeFilter,\n            healthComponents = stash.AsNative()\n        };\n        World.JobHandle = parallelJob.Schedule(nativeFilter.length, 64, World.JobHandle);\n    }\n}\n```\n\n`World.JobHandle.Complete()` is called automatically after each Update type.\nFor example:\n* Call OnUpdate() on all systems within the SystemsGroup.\n* Call World.JobHandle.Complete().\n* Call OnFixedUpdate() on all systems within the SystemsGroup.\n* Call World.JobHandle.Complete().\n\n\u003e [!WARNING]  \n\u003e You cannot change the set of components on any entities if you have scheduled Jobs.  \n\u003e Any addition or deletion of components is considered a change.  \n\u003e The kernel will warn you at World.Commit() that you cannot do this.  \n\nYou can manually control `World.JobHandle`, assign it, and call `.Complete()` on systems if you need to.  \nCurrently Morpeh uses some additional temporary collections for the native part, so instead of just calling `World.JobHandle.Complete()` we recommend using `World.JobsComplete()`.  \nThis method is optional; the kernel will clear these collections one way or another, it will simply do it later.\n\n####  🗒️ Defines\n\nCan be set by user:\n* `MORPEH_DEBUG` Define if you need debug in application build. In editor it works automatically.\n* `MORPEH_EXTERNAL_IL2CPP_ATTRS` If you have conflicts with attributes, you can set this define and Morpeh core will be use internal version of attributes.\n* `MORPEH_PROFILING` Define for systems profiling in Unity Profiling Window.\n* `MORPEH_METRICS` Define for additional Morpeh Metrics in Unity Profiling Window.\n* `MORPEH_NON_SERIALIZED` Define to avoid serialization of Morpeh core parts.\n* `MORPEH_THREAD_SAFETY` Define that forces the kernel to validate that all calls come from the same thread the world was created on. The binding to a thread can be changed using the `World.GetThreadId()`, `World.SetThreadId()` methods.\n* `MORPEH_DISABLE_SET_ICONS` Define for disabling set icons in Project Window.\n* `MORPEH_DISABLE_AUTOINITIALIZATION` Define for disable default world creation and creating Morpeh Runner GameObject.\n* `MORPEH_DISABLE_COMPILATION_REPORT` Define for disable compilation report in Editor Console.\n* `MORPEH_DISABLE_COMPONENT_DISPOSE` Define to disable component disposing feature.\nWill be set by framework:\n* `MORPEH_BURST` Determine if Burst is enabled, and framework has enabled Native API.\n* `MORPEH_GENERATE_ALL_EXTENDED_IDS` to generate `ExtendedComponentId` for all components even outside of Unity Editor.\n\n####  🌍️ World Plugins\n\nSometimes you need to make an automatic plugin for the world.  \nAdd some systems, make a custom game loop, or create your own automatic serialization.  \nWorld plugins are great for this.  \n\nTo do this, you need to declare a class that implements the IWorldPlugin interface.  \nAfter that, create a static method with an attribute and register the plugin in the kernel.  \n\nFor example:\n```c#\nclass GlobalsWorldPlugin : IWorldPlugin {\n\n    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]\n    public static void RuntimeInitialize() {\n        WorldExtensions.AddWorldPlugin(new GlobalsWorldPlugin());\n    }\n    \n    public void Initialize(World world) {\n        var sg = world.CreateSystemsGroup();\n        sg.AddSystem(new ECS.ProcessEventsSystem());\n        world.AddPluginSystemsGroup(sg);\n    }\n    \n    public void Deinitialize(World world) {\n        \n    }\n}\n```\n#### 🌐 World Browser\n\nThe WorldBrowser tool enables real-time tracking and searching of entities and their components. Also provides functionality to add and remove components. Works in both Unity Editor playmode and can connect remotely to builds runtime.\nSupports the same filtering logic as the core ``Filter``, allowing complex queries using ``With`` and ``Without`` conditions.\n\nAccess it via Tools -\u003e Morpeh -\u003e WorldBrowser.\n\n**To declare a query:**\n- Enter the full component name in the search bar for ``With`` conditions.\n- Use ``!`` before the component name for ``Without`` conditions (e.g. ``!ComponentName``).\n- You can paste a complete regular expression directly into the search bar, and it will automatically synchronize with the list of available components.\n\n**Alternatively:**\n- Choose from a synchronized list of available components instead of typing them manually.\n- Suggestions appear as you type in the search bar. When you start typing a component name, a list of available components is displayed. You can click on a suggestion to automatically complete the name.\n\n**ID search:**\n- Search by one or multiple entity IDs by entering ``id:`` (e.g. ``id:25 id:145``).\n- ID-based search overrides any component-based query.\n\n\u003e [!NOTE]\n\u003e ``Entity`` with ID 0 cannot exist, as it's reserved as an invalid entity in the framework.\n\n**World Selection:**\n- Use the top toolbar (with the **W** icon) to choose worlds to search.\n- By default, ``World.Default`` is pre-selected.\n\n**Remote Connection:**\n\nThe feature is currently in experimental stage and works only in development builds. It has several limitations compared to Unity Editor playmode:\n- Components containing `Unity.Object` are displayed in read-only mode.\n- Cannot inspect `Unity.Object fields` in components, but provides `Type`, `Name`, and `InstanceID` information.\n- Some components may fail serialization, will be marked with [NotSerialized] tag and won't be rendered. You'll need to modify the component structure manually if serialization is required.\n\nSetup:\n- Install [Unity.Serialization package](https://docs.unity3d.com/Packages/com.unity.serialization@3.1/manual/index.html) via Package Manager.\n- Add `MORPEH_REMOTE_BROWSER` directive to *ProjectSettings -\u003e Player -\u003e Scripting Define Symbols*.\n- Restart Unity Editor.\n- After restart, the `WorldBrowser` will display a \"Connect To Remote\" button.\n\n\u003e [!IMPORTANT]  \n\u003e You must build your application after enabling remote mode. Previous builds will not support remote debugging.\n\nStarting Remote Debug:\n- Launch the application on your target device.\n- Open WorldBrowser in Unity Editor.\n- Enter the device's IP address (and optional port) as specified below.\n- Click \"Connect To Remote\" button.\n\nAndroid \u0026 iOS:\n- Connect to the same WiFi network as your device.\n- Get the device's IP address from Settings -\u003e WiFi -\u003e Network details.\n- Enter the IP address in the connection dialog (e.g., `192.168.1.100`).\n- Optionally specify a custom port (e.g., `192.168.1.100:22005`).\n\nWindows \u0026 macOS \u0026 Linux:\n- Use localhost (e.g., `127.0.0.1`).\n- Optionally specify a custom port (e.g., `127.0.0.1:22005`).\n\n####  📊 Metrics\nTo debug the game, you may need statistics on basic data in the ECS framework, such as:\n\n1. Number of entities\n2. Number of archetypes\n3. Number of filters\n4. Number of systems\n5. Number of commits in the world\n6. Number of entity migrations\n7. Number of stash resizes\n\nYou can find all this in the profiler window.  \nTo do this, you need to add the official **Unity Profiling Core API** package to your project.  \nIts quick name to search is: `com.unity.profiling.core`  \n\nAfter this, specify the `MORPEH_METRICS` definition in the project.  \nNow you can observe all the statistics for the kernel.  \n\nOpen the profiler window.  \nOn the top left, click the Profiler Modules button and find Morpeh there.  \nWe turn it on with a checkmark and can move it higher or lower. \n\nMetrics work the same way in debug builds, so you can see the whole picture directly from the device.\n\n\u003cdetails\u003e\n    \u003csummary\u003eIt will be look like this in playmode. \u003c/summary\u003e\n\n![metrics.png](Gifs~/metrics.png)\n\u003c/details\u003e\n\n\n#### 📏 Stash size\n\nIf you know the expected number of components in a stash, you have the option to set a base size to prevent resizing and avoid unnecessary allocations.\n\n```c#\nComponentId\u003cT\u003e.StashSize = 1024;\n```\n\nThis value is not tied to a specific ``World``, so it needs to be set before starting ECS, so that all newly created stashes of this type in any ``World`` have the specified capacity.\n\n#### ⚙️ Collections\n\nMorpeh provides a small set of custom lightweight collections that perform faster under IL2CPP compared to standard library collections.\n\n**FastList**\n\nIdentical to List\u003cT\u003e, additionally supports RemoveSwapBack operations and provides more control over the internal list structure. Also includes methods that allow bypassing array bounds checking.\n\n**IntHashMap \u0026 LongHashMap**\n\nIdentical to Dictionary\u003cint, T\u003e and Dictionary\u003clong, T\u003e respectively, but only supports positive range of keys. Significantly outperforms the dictionary in terms of performance. Allows getting elements by ref. Use combination of ``foreach`` and ``GetValueByIndex/GetValueRefByIndex`` to iterate over the map.\n\n**IntHashSet**\n\nLightweight version of HashSet\u003cint\u003e. Has similar optimizations to IntHashMap but without value storage overhead. Supports only positive range of keys.\n\n**BitSet**\n\nOptimized lightweight implementation of a bit array, resizes significantly faster.\n\n---\n\n## 🔌 Plugins\n\n* [**Morpeh Helpers**](https://github.com/SH42913/morpeh.helpers)\n* [**Morpeh.Events**](https://github.com/codewriter-packages/Morpeh.Events)\n* [**Morpeh.SystemStateProcessor**](https://github.com/codewriter-packages/Morpeh.SystemStateProcessor)\n* [**Morpeh.Queries**](https://github.com/actionk/Morpeh.Queries)\n* [**Morpeh.SourceGenerator**](https://github.com/kandreyc/Scellecs.Morpeh.SourceGenerator)\n* [**Morpeh.Addons**](https://github.com/MexicanMan/morpeh.addons)\n* [**PlayerLoopAPI Runner Morpeh plugin**](https://github.com/skelitheprogrammer/PlayerLoopCustomizationAPI.Runner.Morpeh-Plugin)\n\n---\n\n## 📚 Examples\n\n* [**Tanks**](https://github.com/scellecs/morpeh.examples.tanks) by *SH42913*  \n* [**Ping Pong**](https://github.com/scellecs/morpeh.examples.pong) by *SH42913*  \n* [**Flappy Bird**](https://github.com/R1nge/MorpehECS_FlappyBird) by *R1nge*        \n* [**3D Asteroids**](https://github.com/R1nge/MorpehECS_3D_Asteroids) by *R1nge*    \n* [**Mobile Runner Hypercasual**](https://github.com/StinkySteak/unity-morpeh-hypercasual) by *StinkySteak*\n* [**First Person Shooter**](https://github.com/mixadze1/morpeh.example.shooter) by *mixadze1*\n\n---\n\n## 🔥 Games\n\n* **One State RP - Life Simulator** by *Chillbase*  \n  [Android](https://play.google.com/store/apps/details?id=com.Chillgaming.oneState) [iOS](https://apps.apple.com/us/app/one-state-rp-online/id1597760047)\n\n\n* **Survival Arena** by *OAZIS GAMES*  \n  [Android](https://play.google.com/store/apps/details?id=tower.defense.survival.arena) [iOS](https://apps.apple.com/by/app/survival-arena-tower-defense/id6720725666)\n\n\n* **Zombie City** by *GreenButtonGames*  \n  [Android](https://play.google.com/store/apps/details?id=com.greenbuttongames.zombiecity) [iOS](https://apps.apple.com/us/app/zombie-city-master/id1543420906)\n\n\n* **Fish Idle** by *GreenButtonGames*  \n  [Android](https://play.google.com/store/apps/details?id=com.greenbuttongames.FishIdle) [iOS](https://apps.apple.com/us/app/fish-idle-hooked-tycoon/id1534396279)\n\n\n* **Stickman of Wars: RPG Shooters** by *Multicast Games*  \n  [Android](https://play.google.com/store/apps/details?id=com.multicastgames.sow3) [iOS](https://apps.apple.com/us/app/stickman-of-wars-rpg-shooters/id1620422798)\n\n\n* **Alien Invasion: RPG Idle Space** by *Multicast Games*  \n  [Android](https://play.google.com/store/apps/details?id=com.multicastgames.venomSurvive) [iOS](https://apps.apple.com/tr/app/alien-invasion-rpg-idle-space/id6443697602)\n\n\n* **FatalZone** by *Midhard Games*  \n  [Steam](https://store.steampowered.com/app/2488510/FatalZone/)\n\n---\n\n## 📘 License\n\n📄 [MIT License](LICENSE.md)\n\n---\n\n## 💬 Contacts\n\n✉️ Telegram: [olegmrzv](https://t.me/olegmrzv)  \n📧 E-Mail: [benjminmoore@gmail.com](mailto:benjminmoore@gmail.com)  \n👥 Telegram Community RU: [Morpeh ECS Development](https://t.me/morpeh_development_chat)\n","funding_links":[],"categories":["[ECS Libraries](#contents)","ECS Libraries","C\\#"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fscellecs%2Fmorpeh","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fscellecs%2Fmorpeh","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fscellecs%2Fmorpeh/lists"}