DragonECS-AutoInjections/README.md

234 lines
8.0 KiB
Markdown
Raw Normal View History

2023-05-28 19:41:33 +08:00
<p align="center">
2024-03-11 01:50:41 +08:00
<img width="400" src="https://github.com/DCFApixels/DragonECS-AutoInjections/assets/99481254/11868b2e-21f7-4f47-8970-03ad6329cf0e">
2023-05-28 19:41:33 +08:00
</p>
2023-05-29 04:07:37 +08:00
<p align="center">
<img alt="Version" src="https://img.shields.io/github/package-json/v/DCFApixels/DragonECS-AutoInjections?color=%23ff4e85&style=for-the-badge">
2023-05-31 04:50:35 +08:00
<img alt="License" src="https://img.shields.io/github/license/DCFApixels/DragonECS-AutoInjections?color=ff4e85&style=for-the-badge">
2024-06-16 01:10:11 +08:00
<a href="https://discord.gg/kqmJjExuCf"><img alt="Discord" src="https://img.shields.io/badge/Discord-JOIN-00b269?logo=discord&logoColor=%23ffffff&style=for-the-badge"></a>
<a href="http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=IbDcH43vhfArb30luGMP1TMXB3GCHzxm&authKey=s%2FJfqvv46PswFq68irnGhkLrMR6y9tf%2FUn2mogYizSOGiS%2BmB%2B8Ar9I%2Fnr%2Bs4oS%2B&noverify=0&group_code=949562781"><img alt="QQ" src="https://img.shields.io/badge/QQ-JOIN-00b269?logo=tencentqq&logoColor=%23ffffff&style=for-the-badge"></a>
2023-05-29 04:07:37 +08:00
</p>
2023-05-29 22:41:26 +08:00
# Auto Injections for [DragonECS](https://github.com/DCFApixels/DragonECS)
2023-05-28 20:45:07 +08:00
2024-11-12 13:26:21 +08:00
<table>
<tr></tr>
<tr>
<td colspan="3">Readme Languages:</td>
</tr>
<tr></tr>
<tr>
<td nowrap width="100">
<a href="https://github.com/DCFApixels/DragonECS-AutoInjections/blob/main/README-RU.md">
<img src="https://github.com/user-attachments/assets/7bc29394-46d6-44a3-bace-0a3bae65d755"></br>
<span>Русский</span>
</a>
</td>
<td nowrap width="100">
<a href="https://github.com/DCFApixels/DragonECS-AutoInjections">
<img src="https://github.com/user-attachments/assets/3c699094-f8e6-471d-a7c1-6d2e9530e721"></br>
<span>English(WIP)</span>
</a>
</td>
</tr>
</table>
</br>
2023-05-28 20:45:07 +08:00
2023-05-31 04:20:54 +08:00
The extension is designed to reduce the amount of code by simplifying dependency injection by doing injections automatically.
2024-11-12 13:30:34 +08:00
> [!WARNING]
> The project is a work in progress, API may change.
>
2023-06-12 15:08:11 +08:00
> While the English version of the README is incomplete, you can view the [Russian version](https://github.com/DCFApixels/DragonECS-AutoInjections/blob/main/README-RU.md).
2023-05-28 20:29:42 +08:00
2026-03-29 13:15:33 +08:00
# Оглавление
- [Installation](#Installation)
- [Integration](#Integration)
- [Dependency Injection](#Dependency-Injection)
- [Auto Builder for aspects](#Auto-Builder-for-aspects)
- [Auto Runners](#Auto-Runners)
- [Code Example](#Code-Example)
- [Non-null injections](#Non-null-injections)
2024-03-11 00:37:32 +08:00
</br>
# Installation
2026-03-29 01:49:14 +08:00
Versioning semantics - [Open](https://gist.github.com/DCFApixels/af79284955bf40e9476cdcac79d7b098#file-dcfapixels_versioning-md)
2024-03-11 00:37:32 +08:00
## Environment
Requirements:
+ Dependency: [DragonECS](https://github.com/DCFApixels/DragonECS)
+ Minimum version of C# 7.3;
Optional:
2026-03-29 01:49:14 +08:00
* Game engines with C#: Unity, Godot, MonoGame, etc.
2024-03-11 00:37:32 +08:00
Tested with:
2026-03-29 01:49:14 +08:00
* **Unity:** Minimum version 2021.2.0.
2024-03-11 00:37:32 +08:00
## Unity Installation
* ### Unity Package
2026-03-29 01:49:14 +08:00
The package supports installation as a Unity package by adding the Git URL [in the PackageManager](https://docs.unity3d.com/2023.2/Documentation/Manual/upm-ui-giturl.html):
2024-03-11 00:37:32 +08:00
```
https://github.com/DCFApixels/DragonECS-AutoInjections.git
```
2026-03-29 01:49:14 +08:00
Or add the package entry to `Packages/manifest.json`:
```
"com.dcfa_pixels.dragonecs-auto_injections": "https://github.com/DCFApixels/DragonECS-AutoInjections.git",
```
2024-03-11 00:37:32 +08:00
* ### Source Code
2026-03-29 01:49:14 +08:00
The package source code can also be copied directly into the project.
2024-03-11 00:37:32 +08:00
</br>
2023-05-31 04:23:11 +08:00
2026-03-29 01:49:14 +08:00
# Integration
Add the AutoInject() call to the pipeline Builder. Example:
```c#
_pipeline = EcsPipeline.New()
.Inject(world)
.Inject(_timeService)
.Add(new TestSystem())
.Add(new VelocitySystem())
.Add(new ViewSystem())
.AutoInject() // Done — automatic injections enabled
.BuildAndInit();
```
> [!IMPORTANT]
> Ensure AutoInject() is called during initialization; otherwise nothing will work.
# Dependency Injection
The `[DI]` attribute replaces the `IEcsInject<T>` interface. Fields marked with this attribute automatically receive dependencies injected into the pipeline. Example
```c#
[DI] EcsDefaultWorld _world;
```
Injection can also be done via a property or method:
```c#
EcsDefaultWorld _world;
//Обязательно наличие set блока.
[DI] EcsDefaultWorld World { set => _world = value; }
//Количество аргументов должно быть равно 1.
[DI] void InjectWorld(EcsDefaultWorld world) => _world = world;
```
> Aggressive injection (without the `[DI]` attribute) is enabled by calling `.AutoInject(true)`.
2026-03-29 13:15:33 +08:00
</br>
# Auto Builder for aspects
AutoInjections also simplifies building aspects. The following attributes are available:
Attributes for initializing pool fields:
* `[Inc]` - caches the pool and adds the component type to the include constraint of the aspect (equivalent to `Include<T>()`);
* `[Exc]` - caches the pool and adds the component type to the exclude constraint (equivalent to `Exclude<T>()`);
* `[Opt]` - only caches the pool (equivalent to `Optional<T>`);
*
Attribute for combining aspects:
* `[Combine(order)]` - caches the aspect and merges constraints from aspects (equivalent to `Combine<TOtherAspect>(int)`); order sets combine order (default 0);
Additional attributes for specifying aspect constraints. They can be applied to the aspect itself or any field inside:
* `[IncImplicit(type)]` - adds Type from the constructor to the include constraint (equivalent to `Include<T>()`);
* `[ExcImplicit(type)]` - adds Type from the constructor to the exclude constraint (equivalent to `Exclude<T>()`);
</br>
# Auto Runners
To obtain runners without adding them manually, use `[BindWithRunner(type)]` and `GetRunnerAuto<T>()`.
```c#
[BindWithRunner(typeof(DoSomethingProcessRunner))]
interface IDoSomethingProcess : IEcsProcess
{
void Do();
}
//Реализация раннера. Пример реализации можно так же посмотреть в встроенных процессах
sealed class DoSomethingProcessRunner : EcsRunner<IDoSomethingProcess>, IDoSomethingProcess
{
public void Do()
{
foreach (var item in Process) item.Do();
}
}
//...
// Если в пайплайн не был добавлен раннер, то GetRunnerAuto автоматически добавит экземпляр DoSomethingProcessRunner.
_pipeline.GetRunnerAuto<IDoSomethingProcess>().Do();
```
</br>
2023-05-31 04:20:54 +08:00
# Code Example
2026-03-29 13:15:33 +08:00
2026-03-29 01:49:14 +08:00
```c#
2024-04-11 01:20:09 +08:00
class VelocitySystemDI : IEcsRun
2023-05-28 15:44:29 +08:00
{
2023-06-22 23:20:13 +08:00
class Aspect : EcsAspectAuto
2023-05-28 15:44:29 +08:00
{
2023-05-28 22:10:54 +08:00
[ExcImplicit(typeof(FreezedTag))]
2023-05-28 15:44:29 +08:00
[Inc] public EcsPool<Pose> poses;
[Inc] public EcsPool<Velocity> velocities;
}
2026-03-29 01:49:14 +08:00
[DI] EcsDefaultWorld _world;
[DI] TimeService _time;
2023-05-28 15:44:29 +08:00
2023-12-31 23:55:42 +08:00
public void Run()
2023-05-28 15:44:29 +08:00
{
2024-04-11 01:20:09 +08:00
foreach (var e in _world.Where(out Aspect a))
2023-05-28 15:44:29 +08:00
{
2024-04-11 01:20:09 +08:00
a.poses.Get(e).position += a.velocities.Read(e).value * _time.DeltaTime;
2023-05-28 15:44:29 +08:00
}
}
}
```
2026-03-29 13:15:33 +08:00
2023-05-28 20:45:07 +08:00
<details>
2023-05-31 04:20:54 +08:00
<summary>Same code but without AutoInjections</summary>
2026-03-29 13:15:33 +08:00
2023-05-28 20:45:07 +08:00
2026-03-29 01:49:14 +08:00
```c#
2024-04-11 01:20:09 +08:00
class VelocitySystem : IEcsRun, IEcsInject<EcsDefaultWorld>, IEcsInject<TimeService>
2023-05-28 15:44:29 +08:00
{
2023-06-22 23:20:13 +08:00
class Aspect : EcsAspect
2023-05-28 15:44:29 +08:00
{
public EcsPool<Pose> poses;
public EcsPool<Velocity> velocities;
2023-06-22 23:20:13 +08:00
public Aspect(Builder b)
2023-05-28 15:44:29 +08:00
{
2023-05-28 22:10:54 +08:00
b.Exclude<FreezedTag>();
2023-05-28 15:44:29 +08:00
poses = b.Include<Pose>();
velocities = b.Include<Velocity>();
}
}
EcsDefaultWorld _world;
TimeService _time;
public void Inject(EcsDefaultWorld obj) => _world = obj;
public void Inject(TimeService obj) => _time = obj;
2023-12-31 23:55:42 +08:00
public void Run()
2023-05-28 15:44:29 +08:00
{
2024-04-11 01:20:09 +08:00
foreach (var e in _world.Where(out Aspect a))
2023-05-28 15:44:29 +08:00
{
2024-04-11 01:20:09 +08:00
a.poses.Get(e).position += a.velocities.Read(e).value * _time.DeltaTime;
2023-05-28 15:44:29 +08:00
}
}
}
```
2023-05-28 20:45:07 +08:00
2026-03-29 13:15:33 +08:00
2023-05-28 20:45:07 +08:00
</details>
2026-03-29 13:15:33 +08:00
# Non-null injections
To ensure a field marked with `[DI]` is initialized even if injection does not occur, pass a fallback type to the attribute constructor. In the example below the field `Foo` will receive the injected `Foo` instance or an instance of `FooDummy : Foo` if injection was not performed.
> The provided type must have a parameterless constructor and be either the same type as the field or derived from it.
The extension will also report if any `[DI]`-marked fields remain uninitialized after the pre-injection phase.