sebas77 / svelto.ecs Goto Github PK
View Code? Open in Web Editor NEWSvelto ECS C# Entity Component System
Home Page: http://www.sebaslab.com
License: MIT License
Svelto ECS C# Entity Component System
Home Page: http://www.sebaslab.com
License: MIT License
Hi @sebas77,
Thanks for creating the amazing project. I'm the creator of OpenUPM, a public upm registry with automatic build pipelines that publish new package bundle based on valid git tags. You can read the announcement on medium to get the basic idea, so far it hosts 90+ packages as of Jan 2020.
UPM offering better version and dependency management, is the future to delivery reusable component in the Unity Engine. I'd like to help you convert your packages to upm format, to be able to publish on git and the OpenUPM platform.
https://github.com/sebas77/Svelto.ECS
Svelto.ECS
and Svelto.Services
. It will make the GitHub release clean.https://github.com/sebas77/Svelto.Tasks/
https://github.com/sebas77/Svelto.Common
x.y.z
is valid semver, x.y
is not).Create GitHub release for all these repositories. (tag as x.y.z)
The changes will
git subtree
to generate a clean upm branch for git install (optional)Thought?
C# has a static method: Enum.GetNames
which returns an array of entries in the enum. We can use that to reduce boilerplate
for sequential engine groups.
Class(EntityBuilder.CheckFields.cs)
EntityBuilder.CheckFields.Cs on Line 72 describes the error as:
ProcessError("Entity View Structs must hold entity components interfaces", type);
This is incorrect, as the error is thrown when a non-interface is found as a field. This can be confusing, as that's not what the error is checking for. As it was in my case.
I suggest the change to:
ProcessError("Entity View Structs must hold only entity components interfaces", type);
Hi,does it compatible with unity3d please?
This refactoring started as result of a design issue regarding how entity IDs should work. I never really cared much about entityID as svelto uses them exclusively to query indexable entity views.
Because I introduced the RemoveEntity without entity descriptor, it could have worked only if globally unique ID were used.
Unluckily Cardlife was already designed to not use unique IDs which caused some issues. In any case the Svelto code wasn't designed to care much about the IDs.
At the same time I wasn't liking the direction the code was taking so I decided to simplify it and at the same time optimize it:
There is a mistake in the design that I have to fix, because of the nature of the structs, structs saved in groups and in the global DB are of course copies, so that if values are changed in one are not changed in the other. I wonder if I could get away with it storing the structs only in the groups, but then again it won't be possible to write an engine that would act globally on all the structs of the same type.
Considering Svelto.ECS 2.0 is still in development, I thought now might be a good time to offer my opinions on some of the terminology used in the framework, before anything gets set in stone.
First of all, I agree that EntityView
is a better name than Node
, but I still think it is very problematic. I haven't studied your source code yet and I know you plan to write more about it on your blog, but to me "view" could be easily confused with other existing concepts associated with that word.
For example, the Model–view–controller (MVC) pattern uses "view" to mean components that are displayed to the user (graphics) and other ECS frameworks like Entitas refer to any visual representation (Sprites, Models) of entities as views. This all makes a lot of sense to me. There is also the issue of naming; what if I want to call my actual visual representations of entities, like Unity game objects, views? (e.g. PlayerView
)
I never looked very deep into your framework before, but I really didn't understand what a Node
was at first. However, when I heard the term EntityView
I was immediately confused because I thought of the concepts mentioned above.
I also think there are many alternative names that would work much better at representing the concept. Here are a few ideas:
I also believe Unity's new ECS is using "Archetype" for a similar system. What are your thoughts on this? Am I just not understanding the concept correctly?
What about IEntitiesSink? I actually use that name in each engine that needs IEntityFunctions.
among the other things, I am simplifying the code even more, removing the concept of global entities pool (I need to explain this in depth), introducing EntityViewStructs (They are like the entity view, so they will still need the implementors, but with zero allocation cost).
There are still some pieces that must click in place, but I am getting there.
Hey, your nuget-release github action pushs non optimized binaries as the dotnet pack
command use the default configuration Debug, you should pass -c Release
as argument (same for Svelto.Common).
Also you reference the package System.Runtime.CompilerServices.Unsafe version 4.6.0-preview8.19405.3 when there is newer non-prerelease versions available.
Probably not your priority as this is outside of Unity scope but I thought I would let you know :) Tried to make a benchmark of your framework with other ECS solution and BenchmarkDotNet complained about it.
client send message to server
and server run the framework
In the Survival Example I use just one EntityDescriptor to create three different types of enemies which is actually good because entities are specialized through data and not code. As matter of fact, this is how ECS should be actually used to take proper advantage of meaningful data iterations.
However, while refactoring the example using Svelto ECS 2.6, I had the chance to see the code under a different point of view and realize that some design decisions could take some advanced reasoning to be understood properly.
Specifically I am talking about what happened to me while refactoring the EnemyDeathEngine CheckIfDead method.
Inside the Svelto ECS database, EntityViewStruct and EntityStructs are not grouped per entity descriptor, this means that if multiple entity descriptors generate the same shared entity view, the array returned by QueryEntities will return all the entity views generated and not just the ones of that specific entity descriptor.
Because entity views can be shared over multiple EntityDescriptors, when an iteration needs to work on different array of different entity views, it's not guaranteed that these arrays can be indexed in the same way.
if I do
- entitiesDB.QueryEntities<EnemyEntityStruct>(out count);
- entitiesDB.QueryEntities<HealthEntityStruct>(out count);
- entitiesDB.QueryEntities<EnemyEntityViewStruct>(out count);
the HealthEntityStruct and the EnemyEntityStruct arrays won't have the same size and won't be indexable in the same way as HealthEntityStruct is generated both by the EnemyEntityDescriptor and the PlayerEntityDescriptor. This is why the QueryMappedEntities function exists, that is to have a way to find entity views through EGID.
On the other hand, since EnemyEntityStruct and EnemyEntityViewStruct are generated exclusively by the EnemyEntityDescriptor, I can guarantee by specification that the two arrays are indexable in the same way. Look at the code
IEnumerator CheckIfDead()
{
var enemyIterationInfo = new FasterList<EnemyIterationInfo>();
//this struct will allow use zero allocation lambdas. When c# 7 will be available in Unity
//this will be less awkward thanks to the new local functions feature
var valueTuple = new LambdaParameters {Item1 = enemyIterationInfo};
while (true)
{
//wait for enemies to be created
while (entitiesDB.HasAny<EnemyEntityStruct>() == false) yield return null;
valueTuple.Item2 = entitiesDB.QueryMappedEntities<EnemyEntityViewStruct>();
entitiesDB.ExecuteOnEntities(ref valueTuple,
(ref EnemyEntityStruct enemyStruct,
ref HealthEntityStruct healthEntityStruct,
ref LambdaParameters _parameters) => //this lambda doesn't capture any external variable
{
if (healthEntityStruct.dead != true) return;
uint index;
SetParametersForDeath(ref _parameters.Item2.entities(healthEntityStruct.ID, out index)[index]);
_parameters.Item1.Add(new EnemyIterationInfo(healthEntityStruct.ID,
(int) ECSGroups.EnemyDisabledGroups + (int) enemyStruct.enemyType));
});
...
}
The QueryMappedEntities and the way I use the EGIDMapper to pass the parameters to the SetParametersForDeath is not intuitive neither is as fast as indexing directly the array of entity views.
However since performance is not an issue here I can decide to leave it as it is. Leaving as it is in the example could have the unwanted consequence to lead people to think that it's just fine to use this method, although it shouldn't be. Indexing directly should be preferred and in this case EnemyEntityViewStruct can actually be indexed directly. The code could become:
while (true)
{
//wait for enemies to be created
while (entitiesDB.HasAny<EnemyEntityStruct>() == false) yield return null;
//fetch the current EnemyEntityViewStruct array, avoid to do it inside the iteration
//to be faster
int count;
valueTuple.Item2 = entitiesDB.QueryEntities<EnemyEntityViewStruct>(out count);
//iterate over the EnemyEntityStruct and use the healthEntityStruct that are generated by the
//same entities. Use lambda without catching any external variable so that it won't allocate (which is
//very important! this will be less awkward when c# 7 is out)
entitiesDB.ExecuteOnEntities(ref valueTuple,
(ref EnemyEntityStruct enemyStruct,
ref HealthEntityStruct healthEntityStruct,
ref LambdaParameters _parameters, int iterationIndex) =>
{
if (healthEntityStruct.dead == false) return;
SetParametersForDeath(ref _parameters.Item2[iterationIndex]);
_parameters.Item1.Add(new EnemyIterationInfo(healthEntityStruct.ID,
(int) ECSGroups.EnemyDisabledGroups + (int) enemyStruct.enemyType));
});
...
yield return null;
}
For example in ApplyingDamageToTargetEntitiesEngine ApplyDamage function, DamageableEntityStruct and HealthEntityStruct can be iterated with the same for-loop, because they are generated by the same entity descriptors and there is no entity descriptor that generates just one or the other.
ExecuteOnEntities make the code more awkward, especially with version of c# prior 7 as local functions cannot be exploited. However ExecuteOnEntities can ensure that Swap and Remove won't happen inside the iteration by mistake.
To conclude, I could change the database and introduce functions like entitiesDB.QueryEntities<EnemyEntityDescriptor, EnemyEntityViewStruct> and entitiesDB.QueryEntities<EnemyEntityDescriptor, HealthEntityStruct> so that the returning buffers are guaranteed to be indexable in the same way. It would make also the coder intention clearer, so it wouldn't be bad.
On the other hand it would make engines like ApplyingDamageToTargetEntitiesEngine slower, but probably not as slower as mapping an index for each EGID like it happens in the specialized engines.
If specialized engines are more common than abstract ones it could make sense to move toward this direction.
Since it's a big decision as it would break the current existing Svelto application, I need to know your point of view. If I change it, the QueryEntities function coudn't be used anymore without an EntityDescriptor parameter and for abstract engines it would be necessary to use ExecuteOnEntities to delegate to the framework the task to find the arrays that contains the entity view to iterate on
Svelto.ECS/ECS/Profiler/EngineProfiler.cs
Line 37 in ed9e073
INodeEngine.Remove called twice, in removeFunc(engine,node)
and engine.Remove(node)
Are planning on developing something Unity inspector functionality in order to view engines, entities, and components?
It would be even more useful if we could add/remove and pause/resume them at runtime, too, just like with Entitas.
currently
Common/Components/ECSRect.cs
Extensions/Unity/GenericEntityDescriptorHolder.cs
have the 'Using UnityEngine' namespace requirements. I am trying to use the library with monogame and ran into this issue.
Ciao Sebastiano:)
I've been following Svelto(both IOC and now ECS too) for a while and I found it really interesting and I hope to see soon the next version.
I really like your decision to put events inside components. As long as events are setup in a deterministic way from Engines there's no problem in having events in components, in your ECS example there's a 1to1 relationship between caller and callback (enemy in range triggered by Unity physics, and 1 engine is listening the event).
However, how much freedom do we have in using events that way? How do you see using multiple triggerers and multiple subscribers for the same event?
Let's consider following cases:
* Case 1 (1to1)*
IEnemyTrigger
setup an event, PhysicsEngine
trigger it (assume I implemented a custom physics engine in c#)
There's 1 to 1 caller/callee corrispondence => could we use instead 2 different interfaces? One is used with an Action setter and the other one is used to call the Action, both interfaces are used each 1 by one engine for the same Entity:
public interface IEnemyTrigger{
System.Action<GameObject, bool> entityInRange{set;}
}
public interface IPhysTrigger{
void triggerEntityInRange( GameObject go, bool inRange);
}
public class EnemyTrigger : IEnemyTrigger, IPhysRangeTrigger{
private PhysAction _entityInRange;
public PhysAction IEnemyTrigger.entityInRange { set{ _entityInRange += value;}}
public void IPhysTrigger.TriggerEntityInRange( GameObject go, bool inRange){
_entityInRange( go, inRange);
}
}
* Case 2 (X to Y)*
However what confuses me is what we should do when events are in Y to X correspondondence. How should I design around that? (in example think to an enemy with an Health bar, when enemy dies we should get rid of bar and enemy sprite too, so we have 2 pieces of code that needs to be notified: the enemy sprite and the health bar).
http://www.sebaslab.com/svelto-ecs-2-5-and-allocation-0-code/
it comes together with Svelto 2.5 :)
It will take time to clean it up and test everything properly, but I am ready for feedback!
Because SubmitEntityViews is not called immediately. Delete the entity just created before the SubmitEntityViews call, it will throw an exception.
PreconditionException: from group not found
DBC.ECS.Check.Require (Boolean assertion, System.String message) (at Assets/Plugins/Svelto.ECS/DBC.cs:70)
Svelto.ECS.EnginesRoot.MoveEntity (Svelto.ECS.IEntityBuilder[] entityBuilders, EGID entityGID, Int32 toGroupID, System.Collections.Generic.Dictionary`2 toGroup) (at Assets/Plugins/Svelto.ECS/Svelto.ECS/EnginesRoot.Entities.cs:144)
Svelto.ECS.EnginesRoot.SubmitEntityViews () (at Assets/Plugins/Svelto.ECS/Svelto.ECS/EnginesRoot.Submission.cs:28)
System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:222)
I have a case about entity relations using EGID.
public interface IPlayerTroopComponent
{
IList <EGID> Troops {get; } // EGID is the troop entity id
}
The problem is: Since EGID is a struct, IPlayerTroopComponent will contains inconsistent groupIds.
What do you think about this?
Svelto.ECS can't be used by itself because it uses the updated DBC
1 2 3 namespace while the included Svelto.Common submodule is still using the old DesignByContract
namespace. From my testing updating Svelto.Common from its current state to the latest commit clears this particular bug.
Note:
For me it's a bit of a problem using submodules because I can't find a way to prevent submodule recursion in GitKraken. I don't know what the solution to this would be - apart from switching git clients - but for now I will stick to only learning Svelto.ECS and leave Svelto.Tasks for later.
Line 52 in ed9e073
When enable engine profiler, it show error
Svelto-ECS/ECS/EnginesRoot.cs(52,4): error CS0246: The type or namespace name
GameObject' could not be found. Are you missing
UnityEngine' using directive?
It should changed to this
UnityEngine.GameObject debugEngineObject = new UnityEngine.GameObject ("Engine Debugger");
Hello Thank for Svelto.ECS i am a newbie.
I tried to with Photon,Yeah it so excellent but I don't know solve problem "Cannot restart an IEnumerator without a valid Reset function, use SetEnumeratorProvider instead" Occurs when player host room disconnected already other players will get this error
my code adapt from Svelto.ECS.Examples.Survival What should i do to solve this problem?
Thanks
I want to open a channel to discuss features with you, do you prefer Discord or Slack?
I created an entity with specific id and group, and then remove the entity. But when i was creating same entity id and group, it threw this error
ArgumentException: An item with the same key has already been added.
System.ThrowHelper.ThrowArgumentException (System.ExceptionResource resource) (at /Users/builduser/buildslave/mono/build/mcs/class/referencesource/mscorlib/system/throwhelper.cs:72)
System.Collections.Generic.Dictionary`2[TKey,TValue].Insert (TKey key, TValue value, System.Boolean add) (at /Users/builduser/buildslave/mono/build/mcs/class/referencesource/mscorlib/system/collections/generic/dictionary.cs:336)
System.Collections.Generic.Dictionary`2[TKey,TValue].Add (TKey key, TValue value) (at /Users/builduser/buildslave/mono/build/mcs/class/referencesource/mscorlib/system/collections/generic/dictionary.cs:192)
Svelto.ECS.EnginesRoot.AddEntityViewsToGroupDB (System.Collections.Generic.Dictionary`2[TKey,TValue] groupEntityViewsDB, System.Collections.Generic.KeyValuePair`2[TKey,TValue] group) (at Assets/Extension/Svelto.ECS/EnginesRootSubmission.cs:106)
Svelto.ECS.EnginesRoot.AddGroupEntityViewsToTheDBAndSuitableEngines (System.Collections.Generic.Dictionary`2[TKey,TValue] groupedEntityViewsToAdd, System.Collections.Generic.Dictionary`2[TKey,TValue] groupEntityViewsDB, System.Collections.Generic.Dictionary`2[TKey,TValue] entityViewsDB) (at Assets/Extension/Svelto.ECS/EnginesRootSubmission.cs:90)
Svelto.ECS.EnginesRoot.SubmitEntityViews () (at Assets/Extension/Svelto.ECS/EnginesRootSubmission.cs:39)
System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:305)
Rethrow as TargetInvocationException: Exception has been thrown by the target of an invocation.
System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:313)
System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) (at /Users/builduser/buildslave/mono/build/mcs/class/referencesource/mscorlib/system/reflection/methodbase.cs:229)
Svelto.WeakEvents.WeakActionBase.Invoke_Internal (System.Object[] data) (at Assets/Extension/Svelto.Common/WeakEvents/WeakAction.cs:91)
Svelto.WeakEvents.WeakAction.Invoke () (at Assets/Extension/Svelto.Common/WeakEvents/WeakAction.cs:50)
Svelto.ECS.Schedulers.Unity.UnitySumbmissionEntityViewScheduler+Scheduler+<Start>c__Iterator0.MoveNext () (at Assets/Extension/Svelto.ECS/Extensions/Unity/UnitySumbmissionEntityViewScheduler .cs:39)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at /Users/builduser/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)
Does this mean that the entity is not removed from its group?
Hello @sebas77,
I just get started using your framework. I like it.
I have question in my mind why are you using C# Reflection?
As we know, reflection is slow.
The latest release zip (2.0 beta 2) doesn't have a .git folder so git doesn't recognize it as a git repository. Therefore I can't initialize submodules.
After updating SECS and Common from 3.0.2 to 3.1.0 I got these error messages
Library\PackageCache\[email protected]\Core\CheckEntityUtilities.cs(17,10): error CS0246: The type or namespace name 'ConditionalAttribute' could not be found (are you missing a using directive or an assembly reference?)
I added using System.Diagnostics; into the CheckEntityUtilities class and it works now
I really not understand why nodes are there and how can I keep into account them when designin the game, I feel like I'm missing something really important. There are some obscure points that probably are handled in automatic by Svelto:
Hi,
A problem recently arose regarding the use of the Swap and Remove entity related functions. Since I give the possibility to work directly with arrays to get maximum performance, these functions cannot currently be used inside an iteration because they immediately alter the arrays that store the entities. This means that an array will change while iterating, which would lead to unexpected behaviors. Leaving the responsibility of managing this situation to the user is too much, therefore we need to find a solution and your help would be appreciated.
My current idea is to copy the entity to the new group during a swap, but never remove immediately in any case. I will just mark the item as not valid anymore.
I am not sure which datastructure to use to mark it yet, as it depends if I want to give you some tools to check if an entity is valid or not. These tool would be under the form of different ways of iteration, i.e.: use ExecuteOnEntity would always skip not valid cells.
The real remove then would happen in the next frame, like it happens when submit entities.
The concept of frame is a weird one tho, but that's why you can customize when the entities are submitted overloading the Submission Scheduler behaviour.
In a not too far feature, I want to give the chance to create hierarchical Enginesroot, so that you can encapsulate the code even more and also customize the way entities are submitted.
This could be very helpful in a 100% multithreaded environment.
This is an example entity descriptor:
https://cdn.discordapp.com/attachments/459727475287654401/856964598652731392/unknown.png
And this exception:
https://cdn.discordapp.com/attachments/459727475287654401/856964651114692618/unknown.png
My factory goes like this:
https://cdn.discordapp.com/attachments/459727475287654401/856964728613503056/unknown.png
In Example2-Unity Hybrid-Survival, if player dies, RestartGameOnPlayerDeathEngine fires SceneManager.LoadScene, and UnityContext.Awake adds Application.wantsToQuit delegate again. And when I stop the game, then above error occurs.
public class UnityContext<T> : UnityContext where T : class, ICompositionRoot, new()
{
void Awake()
{
_applicationRoot = new T();
_applicationRoot.OnContextCreated(this);
Application.wantsToQuit += IsQuitting;
}
bool IsQuitting()
{
_isQuitting = true;
_applicationRoot.OnContextDestroyed();
return true;
}
}
I guess the problem is removing IsQuitting function delegate when UnityContext.OnDestroy is called I guess.
Profiling has moved to UnityEngine.Profiling
namespace, as result
GameObjectFactory.cs, Line 51
do not compile because it can't find the "Profiler" name.
give me feedback and I am also filling this page so if you have questions let me know:
Svelto.ECS/Svelto.ECS/EnginesRootEntities.cs
Line 364 in 292e5e5
GenericEntityFunctions.RemoveEntityFromGroup<>()
call EnginesRoot.RemoveEntity<T>()
instead of EnginesRoot.RemoveEntityFromGroup<T>()
Svelto.ECS/Svelto.ECS/EnginesRootEntities.cs
Line 359 in 292e5e5
GenericEntityFunctions.RemoveMetaEntity<T>()
call EnginesRoot.RemoveEntity<T>()
instead of EnginesRoot.RemoveMetaEntity<T>()
Are they bugs?
I don't understand exactly how the internal framework work, but GenericEntityFunctions.RemoveEntityFromGroup<T>
seemed to be calling EnginesRoot.RemoveEntityFromGroup<T>
.
Hi!
We're currently working on a pure C# Authoritative Server for a mobile game, and we're considering the possibility of switching to an ECS architecture. In short: the server is in charge of simulating the game rules. It does that in discrete ticks, which we run via a single entry point function (i.e. an "Update" function that the server infrastructure calls every X milliseconds). The match status is sent over the network with a certain frequency, and it's used by the clients to display the status.
"Pure C#" means that there's no Unity code whatsoever in the server. We do use third-party libraries (the lighter they are in CPU and memory load, the better).
Do you think Svelto would work for us? If I understand correctly, it can be used without Unity. Is that correct? Would we need to do something "special" or to use any workaround for it to work?
Thanks!
Hello.
I want to use the ECS concept described in your articles in my indie game.
But there are some questions I can not solve by myself and asking for your help.
I want to divide the whole game logic into contexts (Svelto.Context) with the maximum encapsulation.
Each context will have its own EnginesRoot.
For example, the context of the quests logic, the context of a player control, the context of the enemies control, the context of the UI control, the context of data working, etc.
But there is a little problem.
I do not see the possibility of achieving the full encapsulation.
For example, quests can turn off enemy spawn in the course of their work because that would not interfere with the player.
But to do this, I need an access to the context of the enemies from the context of the quests. And it breaks the encapsulation and is impossible in the current logic because the contexts use different EnginesRoot.
Or, it will be needed an access to the context of the player from the context of the enemies in order to know about the target to attack.
Could you advise the correct way to exchange data between Context with different EnginesRoot?
We considered an option with a variety of Context and one basic EngineRoot for all entities.
But we didn’t like this option for a number of reasons.
I will be very grateful for your advice and help!
eg.
public class Test : MonoBehaviour
{
public void A()
{
Debug.LogError("A" + name);
}
public static void B()
{
Debug.LogError("B");
}
private void OnDestroy()
{
Debug.LogError("B OnDestroy");
}
}
var go = new GameObject();
var test = go.AddComponent<Test>();
var t = new WeakReference<Test>(test);
var weakAction = new WeakAction(Test.B);
DestroyImmediate(go);
GC.Collect();
Debug.LogError(t.IsValid);
weakAction.Invoke()
for My way
using System;
using Object = UnityEngine.Object;
public class WeakReference<T> : WeakReference where T : class
{
private readonly bool _isUnityObject;
private static readonly Type ObjectType = typeof(Object);
public bool IsValid
{
get { return _isUnityObject ? (Object) base.Target : IsAlive; }
}
/// <summary>
/// Gets or sets the object (the target) referenced by the
/// current WeakReference{T} object.
/// </summary>
public new T Target
{
get { return (T) base.Target; }
}
/// <summary>
/// Initializes a new instance of the WeakReference{T} class, referencing
/// the specified object.
/// </summary>
/// <param name="target">The object to reference.</param>
public WeakReference(T target) : base(target)
{
_isUnityObject = typeof(T).IsSubclassOf(ObjectType); // assumption T isn’t the UnityEngine.Object
}
public WeakReference(T target, bool isUnityObject) : base(target)
{
_isUnityObject = isUnityObject;
}
}
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
public class WeakAction<T1, T2> : WeakActionBase
{
public WeakAction(Action<T1, T2> listener) : base(null)
{
var method = listener.Method;
var isStatic = Method.IsStatic;
if (!isStatic)
{
ActionBase(listener.Target, method, false);
}
else
{
ActionBase(null, method, true);
}
}
public void Invoke(T1 data1, T2 data2)
{
_data[0] = data1;
_data[1] = data2;
Invoke_Internal(_data);
}
readonly object[] _data = new object[2];
}
public class WeakAction<T> : WeakActionBase
{
public WeakAction(Action<T> listener) : base(null)
{
var method = listener.Method;
var isStatic = Method.IsStatic;
if (!isStatic)
{
ActionBase(listener.Target, method, false);
}
else
{
ActionBase(null, method, true);
}
}
public void Invoke(T data)
{
_data[0] = data;
Invoke_Internal(_data);
}
readonly object[] _data = new object[1];
}
public class WeakAction : WeakActionBase
{
public WeakAction(Action listener) : base(listener)
{
}
public WeakAction(object listener, MethodInfo method) : base(null)
{
ActionBase(listener, method, method.IsStatic);
}
public void Invoke()
{
Invoke_Internal(null);
}
}
public abstract class WeakActionBase
{
protected WeakReference<object> ObjectRef;
protected MethodInfo Method;
private static readonly Type ObjectType = typeof(UnityEngine.Object);
private bool _isStatic;
public bool IsValid
{
get { return ObjectRef.IsValid; }
}
protected WeakActionBase(Action listener)
{
if (listener != null)
{
var method = listener.Method;
var isStatic = method.IsStatic;
if (!isStatic)
{
ActionBase(listener.Target, method, false);
}
else
{
ActionBase(null, method, true);
}
}
}
protected void ActionBase(object listener, MethodInfo method, bool isStatic)
{
Method = method;
_isStatic = isStatic;
if (!isStatic)
{
var isUnityObject = listener.GetType().IsSubclassOf(ObjectType);
ObjectRef = new WeakReference<object>(listener, isUnityObject);
}
if (Method.DeclaringType.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Length != 0)
{
throw new ArgumentException("Cannot create weak event to anonymous method with closure.");
}
}
protected void Invoke_Internal(object[] data)
{
if (_isStatic)
{
Method.Invoke(null, data);
}
else if (ObjectRef.IsValid)
{
Method.Invoke(ObjectRef.Target, data);
}
}
}
Hey there,
I am not sure if you are familiar with UnrealCLR but I was playing around with it today and was quite impressed. Being a big fan of Unitys new DOTS implementations, it made me wonder if an ECS platform that is engine agnostic might be able to be used with UnrealCLR? While it might be a bit unfortunate to not have the ease of use that the Job system can provide, having a well established ECS framework in Unreal using C# sounds pretty exciting to me!
Thanks,
-MH
As was shown in your example, I'm using GO.GetInstanceID() to obtain IDs for my entities.
I find it's logical and convenient.
Unity often will return a negative GO ID's, which will result in a problem in cases when the non-default groupId was used to create a new EGID instance.
The problem is in the following code:
static long MAKE_GLOBAL_ID(int entityId, int groupId)
{
return entityId | (long)groupId << 32;
}
Here , if entityId is negative, it's sign bit will be extended during explicit cast of entityId to long, effectively masking group ID completely. As a result, trying to get back group ID from such EGID instance will always return -1.
Note that C# compiler issues warning about sign bit extension on that line as well:
warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first
Here is a fix which works for me:
static long MAKE_GLOBAL_ID(int entityId, int groupId)
{
return entityId & 0xFFFFFFFF | (long)groupId << 32;
}
I want to start to use c# 7 features, but Unity doesn't support it yet, so I wonder if it would be a problem to distribute the library as dll , maybe inside an unity package. Thoughts?
Svelto.ECS/Svelto.ECS/EntityViewsDB.cs
Line 39 in d37c91e
This casting causing FasterReadOnlyList has null FasterList (_list field).
_entityFactory.BuildEntity<HouseBuildingEntityDescriptor>(101, null);
yield return new WaitForSecondsEnumerator(2);
_entityFunctions.RemoveEntity(101);
yield return new WaitForSecondsEnumerator(2);
_entityFactory.BuildEntity<HouseBuildingEntityDescriptor>(101, null);
i have error, FasterDictionaryException: Key already present.
Why i can't recreate entity with same id?
Ok I found a really minor bug, but maybe it can be useful, maybe it was just a undocumented behaviour
Reproducing the bug:
int count;
var views = entityViewsDB.QueryEntityViewsAsArray< GeometrySourceView>(out count);
for( int i=0; i< count; i++)
{
entitiesSink.RemoveEntity( views[i].id.ID); // null reference at some point
}
When iterating a array of entities taken from the entityViewsDB if I remove them in a loop I get a null reference exception. I didn't investigated yed but I assume the array is resized as long as entities are removed. I expected this kind of stuff to happen only during "SubmitEntityViews" phase.
How I fixed it (basically copying the array locally)
var views = entityViewsDB.QueryEntityViews< GeometrySourceView>().ToArray(); // linq copy
for( int i=0; i< views.Count(); i++)
{
entitiesSink.RemoveEntity( views[i].id.ID);
}
Also what's the difference between QueryEntityViews and QueryEntityViewsAsArray? when I should prefer one to the other?
In both cases the array is resized dynamically. Now, using "AsArray" allowed me to find the bug early because of null reference (but in the second code snippet, if I remove the ".ToArray()" I will stop getting the error (of course because "view.Count" changed accordingly) and noticing the bug become harder.
Now that I have your attention :D
the change is big, but not a breaking one. I am allowing the support of EntityView as structs. Maybe eventually I will be able to merge EntityView and EntityStruct. When EntityView as structs are used like EntityView as class, you have their flexibility but also 0 allocations (well except for the implementors which is the real difference between the two cases).
EntityView as classes will be still supported, but their use strongly discouraged
I am trying to test out this ECS with a simple monogame demo but ran into a problem.
Monogame's Game Class has the Update and Draw methods for the game.
The Update method contains the logic that should be run every frame. The Draw method is run sequentially after the Update is called unless TargetElapsedTime has passed, then it will be skipped.
When setting up a Monogame project to use with Svelto.ECS I would create an EngineRoot with a IEntitySubmissionScheduler that would call a WeakAction's .Invoke() in the Game's Update method. How should I handle the Game's Draw method?
Does anyone have any experience using this library with Monogame?
I found out that when I use Svelto, Debug.Log doesnt show any StackTrace log. Turns out in SlowLoggerUnity class, stacktraceLog is turn off.
It seems there is no way I could override this feature outside of svelto library.
is there a way I could show StackTrace without editting svelto code?
When Update from 3.0.3 to 3.1.0 get error, cannot detect assembly form DOT\Job
Library\PackageCache\[email protected]\Extensions\Unity\DOTS\UECS\IUECSSubmissionEngine.cs(8,58): error CS0246: The type or namespace name 'IJobifiedEngine' could not be found (are you missing a using directive or an assembly reference?)
Library\PackageCache\[email protected]\Extensions\Unity\DOTS\UECS\SveltoOverUECSEnginesGroup.cs(26,46): error CS0246: The type or namespace name 'IJobifiedEngine' could not be found (are you missing a using directive or an assembly reference?)
Library\PackageCache\[email protected]\Extensions\Unity\DOTS\UECS\SyncSveltoToUECSGroup.cs(7,42): error CS0246: The type or namespace name 'JobifiedEnginesGroup<>' could not be found (are you missing a using directive or an assembly reference?)
Library\PackageCache\[email protected]\Extensions\Unity\DOTS\UECS\SyncSveltoToUECSGroup.cs(11,64): error CS0246: The type or namespace name 'IJobifiedEngine' could not be found (are you missing a using directive or an assembly reference?)
Library\PackageCache\[email protected]\Extensions\Unity\DOTS\UECS\SyncUECSToSveltoGroup.cs(7,42): error CS0246: The type or namespace name 'JobifiedEnginesGroup<>' could not be found (are you missing a using directive or an assembly reference?)
Library\PackageCache\[email protected]\Extensions\Unity\DOTS\UECS\SyncUECSToSveltoGroup.cs(12,64): error CS0246: The type or namespace name 'IJobifiedEngine' could not be found (are you missing a using directive or an assembly reference?)
I'm trying to build an entity pool using SwapEntityGroup method.
The 3rd step will fail deep inside during lookup in one of the internal entityview lists.
Here is a pseudo code of my scenario
var entityId = 1
var activeEntitesGroup = 101;
var pooledEntitesGroup = 102;
entityFactory.BuildEntityInGroup(entityId, activeEntitiesGroup, ...);
entityFunctions.SwapEntityGroup(entityId, activeEntitiesGroup, pooledEntitesGroup);
entityFunctions.SwapEntityGroup(entityId, pooledEntitesGroup, activeEntitiesGroup);
As far as I can see this is the conceptual problem with the way how the EGID.GID is used and fact that group ID of the entity does not change after the swap into another group (apparently in attempt to keep GID stable).
I was able to make the above scenario to work by making EGID.GID independent from group ID. I simply made GID to return value of entityID (assuming that entityID should be globally unique) and added groupID as a standalone member variable in EGID struct. This allows to keep EGID.GID stable even if the group of entity has been changed.
The second step I did is to change the group ID of the swapped entity during the swap.
Admittedly, this is not very clean way as it requires to change EGID of the entity. But I think it's important to keep group ID in sync with the group it belongs.
Perhaps it's worth considering to decouple groupID from EGID altogether which will allow it's clean change during the group swap operations?
I really love this project.
Are there any plans for Svelto.ECS to be released as a NuGet package?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.