#archived-dots

1 messages · Page 77 of 1

safe lintel
#

no you would need the specific entity or to loop though all entities with that component to find x

#

i mean you could add another component to signify that special case though

sharp blaze
#

Alternatively i tried to append to a dictionary with the data value as a lookup key such as

public Dictionary<vector3, Entity> entityDict= new Dictionary<vector3, Entity>();
if (entityDict.ContainsKey(vector3))        //    Error occurs

if (animalAreaDict.TryGetValue(pos, out Entity retVal));    //    Alternative lookup also causes error

but im constantly getting a Object reference not set to an instance of an object and cannot figure out why. I have other dictionaries of the same structure except they dont cache Entity types.

zenith wyvern
#

@odd bay There needs to be a LinkedEntityGroup referencing the children on the parent for it to work like you expect. There's a function to create a linked entity group from the hierarchy during conversion. ConversionSystem.AddLinkedGroup or something. Call it on the parent GameObject and it creates a proper link with children.

#

If it has a LinkedEntityGroup it will automatically destroy/insantiate the children when you destroy or instantiate the parent

odd bay
#

Ok so if I instantiate an entity through script it deletes the children when you delete the parent, but it doesn't if you do attach a convert to entity monobehavior in the gameobject view

golden heron
#

@low tangle are you about?

golden heron
#

@me if you see, i tookvyour advice and rebuilt it into four systems wondered if you'd mind having a look for me?

#

RELEASES EXCLAMATION OF EXTREME RELIEF!!!!!!!!

#

Its working... Turns out... it was working all along. beats head against wall The problem was an incorrectly set hardcoded forward vector. It was giving up, not forwards... now its working. i think... it jsut started being wierd again >:(

golden heron
#

Anyone know how to draw a debug line in ecs? Im trying to do it in a component system, but isnt working....

#

my bad being dumb again hehe

low tangle
#

That's excellent

safe gate
#

I think I'm blind but I couldn't find a way to have collision callbacks like OnCollisionEnter

#

How do I do that?

golden heron
#

@low tangle not so great, it seems itruns fine, then it goes haywire :(

#

It makes it to the first position, then it just begins to go crazy.

#

Crazy... whilst i was watching it flew to the first point, then went off on a wander... then out of the blue went back to moving around properly...

#

i think someone has sneaked some booze on board the lil spaceship.

low tangle
#

lol

#

can you show me what it does, then show me some of the code for turning?

#

sounds like its getting close but trying to go very small tolerances

golden heron
#

ok

low tangle
#

so if you boosted the radius of close enough to target it might calm down

#

or snap when close enough to exact target which is roughly the same

golden heron
#

trying to get a good video a sec

#

Atm, its seeming to get to the first one then failing to turn around, but i cant see why cos its reading the angles and it should be setting the thrusts to max to turn around... but it doesnt.

#

I had a kind of forced turn put in there, which then managed to get it to turn around after going nuts for a while but then it seemed to spot the target again and go after it, even turned around to a third target, but then went back to the craziness.

low tangle
#

maybe negatives in thrust, or maybe euler angle gimble lock?

golden heron
#

Not sure, ill show now.

#

please take note you may wish to turn the sound off

#

i didnt remember i had music going till after id recorded hehe

#

This video has the dot product related manual 180 turned off

#

this one has it turned back on.

#

Its recalculating the eulers from the quaternions each frame - in all this, there should never be a euler more than about 30 degrees in play, the eulers are used to create a quaternion that represents this frames rotational velocity

zenith wyvern
safe gate
#

I mean, I just want to know if the bullet has collided with something

#

And if it has, which entity was it

#

So I can damage the enemy/player or destroy the bullet if it is a wall

#

Maybe then each bullet could be constantly raycasting to see if it hits something?

golden heron
#

Thats a common method, gregorio. You can raycast to the intended move position for this frames bullet movement, and if it hits, move the bullet into contact instead, a good way to avoid misses due to going right through the target in one frame.

#

Im not sure how easily it can be done in ecs tho

safe gate
#

I took a glance at raycasting and it looks straight forward

#

All I want to do is constantly raycast and if it is really close, like 0.01 close, I consider it collided

#

Because bullets are going to be triggers they can overlap enemy colliders, is there any way to know if they are overlapping?

safe gate
#

@zenith wyvern how are you check the spheres collision on the example you posted the other day?

zenith wyvern
#

I think all the relevant code is in the post I made

#

It's just a system that runs through entites with a "collider" component and does a sphere-sphere collision check based on a radius value

#

In my case the collider component is literally just:

#
public struct ECSCollider : IComponentData
{
    public float radius;
}
safe gate
#

So you are doing all by yourself, not using UnityPhysics?

zenith wyvern
#

Yes

#

And all the code for actual collision checking is in that system I posted

safe gate
#

I saw it now. I think that for my case raycasting would be easier

zenith wyvern
#

Here's a post with an actual practical example of someone doing collision response with UnityPhysics

#

But like I said it's very awkward right now

#

They are working on making it better

safe gate
#

I guess I'll stay with raycasting. I don't need complex collision detection right now

#

How optimized and lightwheight are raycasts?

zenith wyvern
safe gate
#

But I'm using the new ECS physics

minor sapphire
#

Entities 33 just released

safe lintel
#

Is it a hotfix for 32 or big release?

minor sapphire
#
We released a new version of the dots core packages. This release was mainly focused on fixes and stabilisations, so no new Samples this time. Available via the Package Manager for Unity 2019.1 (and newer).
tawdry tree
#

Well that was a painless upgrade

dry nymph
#

@zenith wyvern Did you get your collision system working? I think I saw some code from you but had to go away and did not comment

zenith wyvern
#

Nope, I'm still working on it. I think I'm misunderstanding how NativeMultiHashMap works, I'm just writing up some tests now so I can get a better understanding of it

dry nymph
#

If you need help, I did this a few months back (with AABB instead of Sphere)

#

same thing, spatial grid as broadphase and then brute force

zenith wyvern
#

You used nativemultihashmap?

dry nymph
#

I ended up using dynamic buffers, but I tested about 10 different approaches including NMHM

#

dynamic buffers were faster (in particular for many entities, as NMHM takes time to clear + values not accessible by index)

zenith wyvern
#

I thought about using it, it just seemed weird to try to apply what should be a fairly straightforward data structure problem and force it into ECS, but maybe it's the better solution since I'm not having much luck with MultiHashMap

dry nymph
#

I can help you with NMHM, but Dynamic Buffer is really the same thing, just more convenient. What is your problem with NMHM?

#

My only warning is that I did not use DOTS for the last 3 months and I am only familar with a now outdated API, but for NMHM nothing changed as far as I can tell

zenith wyvern
#

I insert like this:

struct BuildSpatialMap : IJobForEachWithEntity<Translation, ECSCollider>
    {
        public NativeMultiHashMap<int, Entity>.Concurrent spatialMap;

        public void Execute(Entity e, int chunkIndex, [ReadOnly] ref Translation translation, [ReadOnly] ref ECSCollider coll)
        {
            float2 p = translation.Value.xy;
            
            Utils.VisitGridIndices(p, coll.radius, e, spatialMap.Add, CellSize);
        }
    }```

And do checks like this:
```csharp
        public void Execute(int index)
        {
            NativeMultiHashMapIterator<int> it;

            Entity curr;
            if( spatialMap.TryGetFirstValue(keys[index], out curr, out it ))
            {
                Entity next;
                while( spatialMap.TryGetNextValue(out next, ref it))
                {
                    var aColl = colliderFromEntity[curr];
                    var bColl = colliderFromEntity[next];
                    var a = posFromEntity[curr].Value;
                    var b = posFromEntity[next].Value;

                    // TODO: Collision flags
                    if( CircleOverlap(a, aColl.radius, b, bColl.radius ))
                    {
                        commandBuffer.AddComponent(index, curr, new CollisionTag());
                        commandBuffer.AddComponent(index, next, new CollisionTag());
                    }
                }
            }```

And somehow it misses entities. As far as I can tell all my entities are being properly inserted
#

VisitGridIndices:

public static void VisitGridIndices<TValue>(
    float2 pos, float radius, TValue val,
    System.Action<int, TValue> callback, int cellSize)
    {
        float2 p = pos;
        int2 min = (int2)math.floor((p - radius) / cellSize);
        int2 max = (int2)math.ceil((p + radius) / cellSize);
        int count = max.x - min.x;

        //Debug.LogFormat("Calling visit grid for entity {0}. Pos {1}, Radius {2}. Min {3}, Max {4}. CellSize {5}", val, pos, radius, min, max, cellSize);

        for (int x = min.x; x < max.x; ++x)
        {
            for (int y = min.y; y < max.y; ++y)
            {
                int2 cell = new int2(x, y);
                int hash = cell.GetHashCode();

                //Debug.LogFormat("Inserting entity {0} at {1} hash {2}", val, cell, hash);
                callback(hash, val);
            }
        }
    }```
#

I think I might be iterating the cells incorrectly but I'm not sure

dry nymph
#

hang on a minute, I will take a look shortly --- or PM you later

zenith wyvern
dry nymph
#

Ok great - I stumbled across System.Action callback & commandBuffer - without checking any logic, I dont thing you need this

zenith wyvern
#

How can I tag entities from a job without a command buffer?

dry nymph
#

I think my question is why would you tag them? But we can figure this out later - this might be required for your design

safe gate
#

I think you can't add components without a command buffer on a job

#

Add component must be on the main thread

zenith wyvern
#

I tag them so another system can handle the actual collisions later, but yeah not really relevant to the my problem atm I think

dry nymph
#

Correct, but you could i.e. change a value of an ICD instead of tagging. As I said this can be dealt with later. Also all the colliding entities could be in a container, but that works better if it is processed in the same system. Tags might be legitimate

zenith wyvern
#

And regarding the System.Action, funnily enough that was less verbose than passing in the actual data structure

dry nymph
#

I will need to check the forum post to see full context. But can you assure that you assign to the spatial grid correctly?

zenith wyvern
#

And since I call that in a few places I need it in a function

#

As far as I know yes, I just divide the positions by the cellsize and do GetHashCode on the int2

dry nymph
#

what is the hash function? did you check?

zenith wyvern
#

No, but for testing purposes my cell size is large enough to encompass everything in a single cell anyways. I've verified from Debug.Log that everything is in the same cell

#

Although I did see that when I do GetKeys it returns a list with a copy of the same hash for every insert I've done

#

Which seems not right

#

That is what I'm working on figuring out right now

dry nymph
#

Let me dig out my function, using a NMHM

#
    [BurstCompile]
    [RequireComponentTag (typeof(SpriteTag))]                                                                    // required, not scheduled with a component group
    public struct SpriteToGridMultiHashMapJob : IJobProcessComponentDataWithEntity<Box>
    {
        [ReadOnly] public ColGrid grid;
        [WriteOnly]    public NativeMultiHashMap<int, CollisionInfo>.Concurrent entitiesPerGridMultiHashMap;
            
        public void Execute(Entity e, int i, [ReadOnly] ref Box box)
        {    
            var boxMinGrid = (int2) ((box.Center - box.Extends - grid.Min) * grid.OneOverCellSize);
            var boxMaxGrid = (int2) ((box.Center + box.Extends - grid.Min) * grid.OneOverCellSize);
                
            for (int x = boxMinGrid.x; x <= boxMaxGrid.x; x++)
            {
                if (x >= 0 && x < grid.Dim.x)
                {
                    for (int y = boxMinGrid.y; y <= boxMaxGrid.y; y++)
                    {
                        if (y >= 0 && y < grid.Dim.y)
                        {
                            var key = x + y * grid.Dim.x;
                            entitiesPerGridMultiHashMap.Add(key, new CollisionInfo {entity = e, box = box});
                        }
                    }
                }
            }
        }
    }
#

note: my grid is flexible, that's why it's parameters are passed into the job

    public struct ColGrid
    {
        public float2        Min;
        public float2        Max;
        public int2            Dim;
        public int             CellCount;
        public float2        CellSize;
        public float2        OneOverCellSize;
        
        public ColGrid(float2 Min, float2 Max, int2 Dim)
        {
            this.Min = Min;
            this.Max = Max;
            this.Dim = Dim;
            this.CellCount = Dim.x * Dim.y;
            this.CellSize = (Max - Min) / Dim;
            this.OneOverCellSize = 1f / this.CellSize;
        }
    }

from the look of it, I don't check collisions that are off screen | the check if x>=0 & y>=0

zenith wyvern
#

Looks like the same way I'm inserting my circles as far as I can see

dry nymph
#

yes, but look at my "hash" --- yours might be ok, but it's something I would check

zenith wyvern
#

I've verified all my entities are in the same cell so the hash isn't relevant - atm every collider is being inserted into the same cell. I believe I'm making a mistake in how I'm iterating the hashmap

dry nymph
#

That's what I will look at next, I need to see forum, as here I only see the Execute

#

want to see which job type you use

#

offline for 5 min sorry

zenith wyvern
#

No worries

#

Also since I made that post I followed Joachim's advice and I'm now running all my jobs with .Run like he suggested, and it's still giving me the same results

dry nymph
#

Ok, back again

#

Yes, seems strange...you are iterating in a parallelfor job

zenith wyvern
#

The idea was that I would do a parallelfor for each cell, I'm starting to see where I'm messing up though. I'm only testing the first entity in the cell against the rest and then bailing out. I want to test the first entity against the rest, then do the same for the next until I reach the end.

dry nymph
#

You are only testing the first value of a

#

...yes exactly

zenith wyvern
#

And the reason it appears to work in my other example is I guess by pure chance the "bigcollider" is always ending up as the first entity in teh cell

dry nymph
#

There are different approaches to overcome this, I guess I have tested them all

#

Here one example, but as I mentioned, Dynamic Buffers were most performant and I think I even have a better one for NMHM...it's just a long time and I forgot which one was better

#
    public struct AABBCollisionNMHMtoNMHMJob : IJobNativeMultiHashMapVisitKeyValue<int, CollisionInfo>
    {
        [ReadOnly] public NativeMultiHashMap<int, CollisionInfo> entitiesPerGridMultiHashMap;
        [WriteOnly] public NativeHashMap<int,CollisionPair>.Concurrent DistinctCollisionPairHashMap;
        [WriteOnly] public NativeHashMap<Entity,int>.Concurrent DistinctCollisionEntityHashMap;
        
        public void ExecuteNext(int key, CollisionInfo candidateA)
        {
            NativeMultiHashMapIterator<int> it;
            CollisionInfo candidateB;
            
            if (entitiesPerGridMultiHashMap.TryGetFirstValue(key, out candidateB, out it))
            {
                // advance to own position
                while ( (entitiesPerGridMultiHashMap.TryGetNextValue(out candidateB, ref it)) && (candidateA.entity.Index != candidateB.entity.Index) );
                // check all following for collision
                while (entitiesPerGridMultiHashMap.TryGetNextValue(out candidateB, ref it))
                {
                    var entityA = candidateA.entity;
                    var entityB = candidateB.entity;
                    var hash = Util.GetCollisionHash(entityA.Index, entityB.Index);
                    {
                        if (Util.IsColliding4(candidateA.box, candidateB.box))
                        {
                            var cp = new CollisionPair {EntityA = entityA, EntityB = entityB};
                            if (DistinctCollisionPairHashMap.TryAdd(hash,cp))
                            {
                                DistinctCollisionEntityHashMap.TryAdd(entityA, 1);
                                DistinctCollisionEntityHashMap.TryAdd(entityB, 1);
                            }
                        }
                    }
                }
            }
        }
    }
zenith wyvern
#

Ahh, I was wondering how you would reset the iterator, that is good to know

#

Also incredibly awkward

dry nymph
#

The output of this is

  • NMHM with all unique collision pairs
  • NMHM with all unique colliding entities (i.e. only counted once, even if involved in various collisions)
zenith wyvern
#

I will have to parse this to figure out how I can apply it in my case, it should save me a ton of trial and error though

#

Thank you very much for your help

dry nymph
#

My advise is dump it 😃 Create one entity for each grid cell (this becomes your "key") and attach to each of them a DynamicBuffer (this becomes your "Values). The nice thing is that you can clear very fast & interpret the buffer as an array (.AsNativeArray) at no cost.

zenith wyvern
#

If I do this again I probably will, I think it's valuable to learn the syntax and how to solve these problems with the NMHM as well though

dry nymph
#

Sure...good luck with it. NMHM is a valid approach, if you run in performance issues you can look into Dynamic Buffers

zenith wyvern
#

No worries, I will fix up my code and update my post at some point, thanks again for your help

dry nymph
#

Another approach is to just read out the NMHM in a job and save to list... (schedule various Ijobs in parallel)...i think they also introduced new API functions that allow you to extract all keys and values from NMHM (basically what i did manually before this existed) --- bye

sharp blaze
#

Hi all, trying to do a IJobParallelFor job for a batched raycast. Its running but my results are returning all elements of 0,0,0 vector3 points. Any ideas?

    [BurstCompile]
    struct PrepareRaycastCommandsJob : IJobParallelFor
    {
        public NativeArray<RaycastCommand> raycastCommmands;
        [Unity.Collections.ReadOnly] public NativeArray<Vector3> originPoints;
        [Unity.Collections.ReadOnly] public Vector3 direction;
        [Unity.Collections.ReadOnly] public int length;
        [Unity.Collections.ReadOnly] public int layerMask;

        public void Execute(int i)
        {
            raycastCommmands[i] = new RaycastCommand(originPoints[i], direction, length, layerMask);
        }
    }
        var raycastCommands = new NativeArray<RaycastCommand>(origins.Length, Allocator.TempJob);
        var raycastHits = new NativeArray<RaycastHit>(origins.Length, Allocator.TempJob);

        PrepareRaycastCommandsJob prepareRaycastCommandsJob = new PrepareRaycastCommandsJob()
        {
            raycastCommmands = raycastCommands,
            originPoints = origins,
            direction = direction,
            length = length,
            layerMask = layerMask
        };

        JobHandle jobHandle = RaycastCommand.ScheduleBatch(raycastCommands, raycastHits, 1, default(JobHandle));

        jobHandle.Complete();

        RaycastHit[] raycastHitsResults = raycastHits.ToArray();    //    BUG: elements have point of 0,0,0

Was trying to follow the example: https://github.com/LotteMakesStuff/SimplePhysicsDemo/blob/master/Assets/SimpleJobifiedPhysics.cs

Thanks

sonic oyster
#

Guys, EntityManager em = World.Active.GetOrCreateManager<EntityManager>(); is deprecated, what should i use instead? Almost every tutorial on IComponentData and ISharedComponentData is outdated :/

safe gate
#

@sharp blaze this example is one year old, it's really outdated

sharp blaze
#

@sonic oyster Try EntityManager entityManager = World.Active.EntityManager;
@safe gate unfortunately there isnt any examples of using raycastcommand + jobs together so im kind of stumped on documentation. It runs as intended, just doesnt return the correct values, so maybe im missing a step?

sonic oyster
#

thanks @sharp blaze

safe gate
#

Can you make raycastcommand work without jobs?

tawdry tree
sharp blaze
safe gate
#

I know, but if you try to replicate the behaviour without jobs, does it work?

#

You need to know if the problem is on the job or the raycastcommand

sharp blaze
#

i replicated what unity's documentation for raycastcommand has and it didnt change in performance compared vs when I used normal looped raycasting

safe gate
#

But can raycastcommands work on the main thread?

sharp blaze
#

before i tried adding it to a job, what i replicated with unity's example for raycast command felt like it was running on the mainthread. So I guess it is running on main thread? im not sure how to check that but the performance was definitely not multithreaded compared the the github example

safe gate
#

And it gave you actual results? Not just 0,0,0

sharp blaze
#

the results were all 0,0,0

#

so it ran as expected just not correct result

#

oh if you meant before the jobs, then yeah the results were correct, 0,0,0 was after i tried adding jobs

safe gate
#

And all the values you are passing to the job are correct?

sonic oyster
#

@sharp blaze Member 'World.Active' cannot be accessed with an instance reference; qualify it with a type name instead using your EntityManager entityManager = World.Active.EntityManager;

sharp blaze
#

yeah, you can take my pasted code and try it out with your own points, direction, length and see what you get. let me double check if its initial values on my side

coarse turtle
#

Looks like preview-0.33 is out for Entities, fixes quite a few issues on preview-0.32

#

especially with the type manager ptr restrictions

fickle sapphire
#

How do you access the entity object from a monobehaviour using IConvertGameObjectToEntity?
something like this:

private void OnTriggerEnter2D(Collider2D collider)
        {
         
                    var sender = GetComponent<GameObjectEntity>().Entity;
                    var other = collider.GetComponent<GameObjectEntity>().Entity;               
         }
coarse turtle
#

if you're using the IConvertGameObjectToEntity, and you really need the entity

#

in your MonoBehaviour you'd do

Entity e;
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem) {
  e = entity;
}

As long as you don't destroy your game object. GameObjectEntities will eventually be deprecated

safe gate
#

What do you mean by GameObjectEntities will eventually be deprecated? FML

coarse turtle
#

The Conversion API is the recommended way to go

low tangle
#

make sure you keep the two seprate

#

convert is the new api and will not be depricated

#

GameObjectEntity (A component you can put onto a gameobject) is the old api

#

it will be removed because it was deemed bad practice and they came up with a better long term plan that is converting to entities removing the game object representation

safe gate
#

Oh, I never worked with GameObjectEntities, only with Convert

low tangle
#

GameObjectEntity is part of the older 'Proxy' api

coarse turtle
#

yep - it linked gameObjects way too much with entities and caused a massive slowdown on the inspector

fickle sapphire
#

@coarse turtle do you suggest a different approach to handle collision?

low tangle
#

tbh it depends on how complex of collision you want

coarse turtle
#

Erm, you can do basic AABB collision if it's really simple

low tangle
#

^ naïve brute force if your only looking at sub 10k collisions

#

sphere or aabb

#

2d 100% just roll your own in passes

#

either passes for ease of dev and debug

coarse turtle
#

^ yes

low tangle
#

or single pass collision world like unity.physics and have the components brought in all at once during the pass start of jobs

minor sapphire
#

omg this ai is finally somewhat coming along
everything is just twice as hard in ecs lol

low tangle
#

new way of thinking of things

#

data oriented ai is pretty intresting

minor sapphire
#

lol indeed

coarse turtle
#

it works quite well with utility theory

#

so you can evaluate things all at once and then decide based on a high benefit decision

minor sapphire
#

well it's been keeping me up to 5:30am lol

#

better sleep 😪

stuck saffron
#

@sharp blaze I had the same issue with batch raycast but I didn't try to solve it. Let me know if you figure it out

fickle sapphire
#

psuong thanks! i'll try out

vagrant surge
#

@minor sapphire in case you didnt know, you can actually do a state machine for AI, or even a task thing, by adding a task/state component

#

its a great way to do AI stuff

sharp blaze
#

@stuck saffron its driving my crazy man

stuck saffron
#

For sure, we pretty much have the same code as eachother so it probably is something I should look into it if its a possible bug or implementation thing

tawdry tree
#

Hmm, have anyone played with ISystemStateComponentData or its shared variant?

#

Bah, looks like it's basically just a system-private component, not something I need

low tangle
#

its not private

#

I've used them quite a bit

#

they are for event systems that need to hold internal data that has a lifetime

#

I use them for hybrid setups to hold onto a dontdestroyonload gameobject, and in voice systems to hold onto native memory buffers so they always exist and cleanup proper

vagrant surge
#

its also for stuff like acceleration structure links

low tangle
#

yep that works too

#

regular component is fine as well, the main thing with those is you get a chance to cleanup them after everything else has been deleted on that component

odd bay
#

How do you instantiate a light during runtime in ECS

#

I understand that a light needs to be a gameobject and that its corresponding entity needs a CopyTransformToGameobject, but I don't know how to do this in script

safe lintel
#

something like

            var go = new GameObject();
            var light = go.AddComponent<Light>();
            var lightEntity = EntityManager.CreateEntity();
            EntityManager.AddComponentObject(lightEntity, light);
odd bay
#

I instantiate my entity from a prefab in a job, I can't access the entity manager there and the command buffer does not have AddComponentObject

tawdry tree
#

You need a gameobject, meaning something has to stick out of ECS and do that

odd bay
#

I know I need a gameobject, I'm trying to figure out how to make a gameobject with the light from the jobsystem the entity is instantiating from

safe gate
#

@odd bay you need a gameObject with the ConvertToEntity script

#

But you set to create entity and inject

#

Then you manually add a CopyTransformToGameObject if you are moving the entity

#

And you are all set!

odd bay
#

I'm instantiating it as an entity through script

safe gate
#

If you are moving the gameObject, you need the CopyTransformFromGameObject

#

You need to instantiate the gameObject

#

I think it would be better to have a gameObject prefab that gets converted to an entity

#

Much simpler

odd bay
#

I use a gameobject prefab that gets instantiated as an entity in a job

safe gate
#

The gameObject prefab has the ConvertToEntity script?

odd bay
#

No, the system itself instantiates an entity from the gameobject prefab

safe lintel
#

if you are dead set on having it from a job maybe you need to pool the lights beforehand

odd bay
#

I'm just going by the example in the ECS samples

safe gate
#

I don't really know how to inject the gameobject when you are spawning from script

safe gate
#

I just discovered that you can add ConvertToEntity to a prefab, I will test if Inject works

#

It doesn't seems to work

#

It is on Unity.Transforms.CopyTransformToGameObjectSystem.OnCreate

#

How can you create a query for components that aren't really components?

safe lintel
#

use a ComponentSystem for monobehaviour components

#

you can still query monobehaviour stuff in entity queries

safe gate
#

How can you add the transform reference to the entity?

safe lintel
#

something like EntityManager.AddComponentObject(lightEntity, myTransform);

safe gate
#

Yeah, I found it

#

It's so good that you can see literally all the code

safe lintel
#

yeah

safe gate
#

@odd bay there is your answer

#

Add the transform reference to the entity

#

And add the CopyTransformToGameObject component

odd bay
#

I got it to work somewhat, but it seems like I'm doing it completely wrong. The light is also really weak until I click on the gameobject in the inspector, then it becomes its full brightness. This might just be an editor bug

#
public class InstantiateWithGameObjectSystem : ComponentSystem
{
    EntityQuery entityQuery;

    protected override void OnCreate()
    {
        entityQuery = GetEntityQuery(typeof(InstantiateWithGameObject));
    }

    protected override void OnUpdate()
    {
        NativeArray<Entity> entities = entityQuery.ToEntityArray(Allocator.TempJob);
        for (int i = 0; i < entities.Length; i++)
        {
            GameObject gameObjectInstance = new GameObject();
            Light light = gameObjectInstance.AddComponent<Light>();
            //Entity instance = EntityManager.CreateEntity();
            EntityManager.AddComponent(entities[i], typeof(CopyTransformToGameObject));
            EntityManager.AddComponentObject(entities[i], gameObjectInstance.transform);
            EntityManager.RemoveComponent(entities[i], typeof(InstantiateWithGameObject));
        }
        entities.Dispose();
    }
}
#

I also haven't figured out how to pass in a prefab for it to instantiate since IComponentData doesn't hold GameObjects

junior fjord
#

is there a way to have one job per shared component value? my shared component is the village the humans live in and a lot of tasks can be parallized very well in a "for each village" sense, since there is no communication between the villages

tawdry tree
#

So jobs on chunks?

junior fjord
#

in my case I need to determine a price for a good in each village. This needs a few arrays where I keep track of current offers etc. which are local to each village. If I could have a job per village it would be perfect and just each job would have these few arrays and calculate the price for the current village

#

yeah but one shared component can span multiple chunks

tawdry tree
#

Sounds like you will need to engineer around it, then

junior fjord
#

Could I do it like this or does it sound bad:

#

Use IJobChunk and give it a NativeHashMap<Village, SharedDataStuff> stuff; and then let each chunk write to stuff[village]

#

and just hope that it won't happen to often that two different chunks with the same sharedcomponentvalue run at the same time and slow each other down

tawdry tree
#

Was about to suggest that'd be the way to do it. It really depends on what you need to write and when

junior fjord
#

hmm to this shared data the jobs will be writing very heavily

#

what the job actually does is just write down for each human if he wants to buy/sell and keep track of "order books" with bids and asks

tawdry tree
#

It might be good to have multiple hashmaps during the collection phase, one for each type of information, to spread things out, then you have a job to collate all of that to one hashmap before you run the final job which does the calculations for the good

junior fjord
#

so if two jobs would run at the same time they would probably have a hard time getting write/read access to the order books since the other job just uses it all the time

tawdry tree
#

Is it binary whether the want to buy/sell? (well, trinary, I guess: Buy/Nothing/sell)

junior fjord
#

it is actually a price at which they would sell and a price at which they would buy

twin raven
#

Is there a way to do sprite animations using ECS?

tawdry tree
#

So essentially, you need to grab each person, and check all(?) goods and both(?) their demand and supply price, and collate all of this?

junior fjord
#

yeah in some sense that is what I need to do

#

I don't really know how economists model this and it is surprisingly hard to research (I think they just don't), but it is actually a quite nice thought experiment of how one can arrive at trades when there are many different ask and bid prices

#

how they are matched etc

#

I think I'll just try to come up with a concept that plays nicely with parallelization

tawdry tree
#

@junior fjord You could use a hashmap where the hash is a village+good combination, that holds a collection of some sort.
Job1: for each person, for each good they have, insert their prices*1 into the collection.
Job2: take that hashmap, and do whatever magic you need to end up with each village's overall supply/demand prices *1 (in another hashmap of the same format?)
*1 If you store buy and sell prices together as negative and positive you can easily find out if demand is higher than supply and stuff.

fickle sapphire
#

how do you get a component from a wrapped entity? e.g:

public struct EventPayload : IComponentData {
 public Entity entity;
}

now i would like to check if entity has a specific component but I don't know how to access it.

stuck saffron
#

To check if it has a certain component you can do:

if (EntityManager.HasComponent<ComponentType>(entity)
{
    // do logic here
    EntityManager.GetComponentData<ComponentType>(entity);
    EntityManager.SetComponentData(entity, new ComponentType { });
}```
fickle sapphire
#

thanks @stuck saffron !

dry nymph
#

@junior fjord you could google: order book matching algorithm

stable fog
#

can you use Linq in jobs?

junior fjord
#

@dry nymph thanks 😃

#

it gets way easier when you know the name of what you want to know

untold night
#

@stable fog you cannot use LINQ in jobs as most LINQ functions allocate temp managed objects and that not safe in normal jobs and not allowed in burst

simple wren
#

For some reason when I try to change the color of my trail renderer the trail always just stays at the default pink color

stuck saffron
#

Default pink or the "no material" material?

simple wren
#

um probably the "no material" material

#

oh wait do I just have to add a material

#

Yep I did that it works now

#

thx

spiral cairn
#

I wonder if it is possible to serialize and deserialize entities and their components?

simple wren
#

Does anyone know if it is possible to make a break in a trail via code? I want the trail of a character to not show in the part where it dashes, but I still want it to show in the space before the dash.

#

This is using the trail renderer btw

eternal dune
#

Does anyone know about the future of the Hybrid Rendering package (MeshInstanceRenderer, etc.)?

#

Does anyone know about the future of the Hybrid Rendering package (MeshInstanceRenderer, etc.)?

dull copper
#

@eternal dune see the pinned message on this channel

#

also refer to dots sample repo readme for upgrade notes (there's no mesh instance renderer anymore, it's called RenderMesh now etc)

#

oh right, there's no real docs for hybrid atm (this is why I didn't list it on the pinned message), sorry about that

eternal dune
#

Thank you!

mystic mountain
#

cries why they destroyed inheriting [DisableAutoCreation] ._.

potent cape
#

Is there a way to clone an entity?

potent cape
#

oh... yeah

#

seems legit 😄

#

Thanks anyway 😃

stuck saffron
#

"Clones an entity."

#

I gotchu bro

tawdry tree
#

I highly suggest playing with intellisense and see what each of the major parts of ECS (EntityManager, World, the various built-in classes/structs) can do; I feel like I got a pretty good overview of what can be done and how from that.
And then you have cases like this where you want to, I dunno, manage entities, so EntityManager.(intellisense completion) and just start writing entity will get you at least some options, if not an answer.

solar hill
#

hey so im having a bit of super strange ecs weirdness. my "convert entity" is not working, it just gives the warning (convert entity failed because there was no active world) does anyone have any advice

solar hill
#

i was able to fix my last problem by rolling back to an older version of the ecs package. however now i am having another problem that i have been fighting against for ages. for some reason when i have a shared component that contains an array, even if another shared component has the exact same data in the array it treats it as being a unique shared component configuration. does anyone have any idea how to fix this?

minor sapphire
#

Has anyone got any information about the effect of hyperthreading on an ECS project?

#

Hyperthreading optimises CPU uptime while it's waiting for memory access or something right? with efficient memory structures I wonder how it will perform

#

or maybe it gives you a little bit of leniency for some random mem accessing or something lol

#

I really wanna see a threadripper chew through a highly parallel ECS game haha

flat talon
#

@fickle sapphire You use GetComponentDataFromEntity<T>() to get an array of those components, pass it into a job and then index into it with the Entity reference in your component.

golden heron
#

So... Just wanna check im doing this right... With regards to local and world coordinates, using the inbuilt unmodified localToWorld component...
Firstly, If i use LocalToWorld.Forward, it should be the world coordinates of the entities forward vector? So, quaternion.LookRotation(LocalToWorld.Forward,LocalToWorld.Up) should be a similar rotation to the Rotation component quaternion? I say similar rather than equal due to rounding differences.
Secondly, If i have a direction vector in world space, and i multiply it by the local.value matrix, i should then have the direction vector in local space, and this would be the same in both local and world coordinates, if my entity is pointing along 0,0,1 and its up is 0,1,0. Is that right?
Thirdly, if i calculate a rotation based on euler angles as numbers all read from the local coordinates, and build up a float3 that contains the axis rotations required to turn the requested amounts, on each of the three axes, the result doesnt need to be done in local space, if you multiply its output quaternion by the current rotation quaternion?

minor sapphire
#

Firstly, If i use LocalToWorld.Forward, it should be the world coordinates of the entities forward vectoryes

So, quaternion.LookRotation(LocalToWorld.Forward,LocalToWorld.Up) should be a similar rotation to the Rotation component quaternion?should be

If i have a direction vector in world space, and i multiply it by the local.value matrix, i should then have the direction vector in local space, and this would be the same in both local and world coordinates, if my entity is pointing along 0,0,1 and its up is 0,1,0. Is that right?I don't know about this ^^; local.value matrix seems to provide position AND rotation information. sounds like you just want to do something with the entity's rotation only?
Got lost in that 'thirdly' bit.

#

does what you want to do boil down to "I want to go over there. Over there is to my left. I need to engage thrusters to rotate me left."?

golden heron
#

Exactly that, except during the process of turning left it need to take into account the maximum rotational acceleration and speed.

#

Which is potentially different for each axis.

minor sapphire
#

right

golden heron
#

I can handle it in two dimensions, it just seems to be getting confused, i've tracked it down to it's seeming to use the values on the wrong axes sometimes, it basically seems to be rolling when it should be turning.

minor sapphire
#

and you do want to just 'rotate left' because...? is there something special about the placement of thrusters?

#

this per axis thing...

#

different thrust power per axis or something?

#

if you want to 'rotate left' you have to 'rotate around up axis'. that part is understood right?

golden heron
#

Yeah, its because the game includes a ship editor, which enables you to place your distribution of weight and thrust, so its gonna generate the simplified data into constraints on rotation speeds in each axis, but for now im just using hardcoded numbers to get the system going.

minor sapphire
#

right

golden heron
#

Yeah, its a case of x axis = pitch, y axis = yaw, and z axis = roll

minor sapphire
#

I am not good at rotations tbh

#

they confuse the shit out of me lol

golden heron
#

Where the amount of pitch, for example, can be read from the y/z coordinates whilst the yaw can be read from x and z

#

Its a pain hehe

minor sapphire
#

this whole per axis thing is the hard part

golden heron
#

Yeah, i know, buts its a very important part of the game.

minor sapphire
#

I mean in theory, you get your rotation delta... it has x/y/z components...

#

then you apply your 'rotate around z' thrusters, then your y, and then your x or something (I think is the order of rotation??)

#

but I guess you're doing that much already

#

but you can't apply all thrusters at full strength because then you will be rotating in the wrong direciton right?

golden heron
#

Well it basically runs it through a check, if the result of normalisation would result in a larger magnitude, it doesnt normalise, so it scales for small values, but then will keep it from exceeding maximums.

minor sapphire
#

set your thrust force high, max rotation speed low, and and rotation drag high

#

so basically there is no 'drift'

#

then you'll be able to visually understand what your ship is doing

#

without any of the wobble

golden heron
#

Yeah, ive been doing that already

minor sapphire
#

so it came down to "it's rotating around z in stead of y" or something?

golden heron
#

Still doesnt help, ive manually forced it to only turn on one axis at a time for testing, and its coming up with a value in the x coordinate, but turning in z.

#

Sorry, a va;ue in the y coordinate, but turning in z

#

its visible when it gets stuck and then starts going back and forth - only y values show, but it rolls.

minor sapphire
#

so like 'delta rotation is (1, 0, 0) and it turns around z axis?

golden heron
#

(0,1,0) but otherwise yeah

minor sapphire
#

that sounds like you have everything but this one last bit...

#

apply the other thrusters!

#

lol

golden heron
#

other? hehe

#

the point is its constrained to only use one at a time, its pushing thruster a but getting thruster b hehe

minor sapphire
#

the yaw(?) thrusters for (0,1,0)

golden heron
#

yeah

minor sapphire
#

you have reduced all of this to two dimensions?

golden heron
#

everything seems correct, otherwise, numbers, angles, orientations. Ima try fiddling with rotation order again.

#

Yeah, works fine then

#

Which kinda suggests the rotation order again i suppose

minor sapphire
#

remove everyhthing from the equation except for this thrust translation issue

#

feed in a constant destination of "to the left of me"

#

and see if you can get the ship to yaw left

#

just hard code destination to localToWorld.Position - localToWorld.right * 10 or something like that

#

or wait

#

if you are working in local space it's different

golden heron
#

I did that, sitting there going in circles to make sure all the right angle settings worked on thrust

minor sapphire
#

and does it?

golden heron
#

yes

minor sapphire
#

so your thrusters can be passed like, (0, 1, 0) and it will yaw right or something?

golden heron
#

yeah

minor sapphire
#

so now try to hard code a destination that will always result in (0,1,0) in thurster

#

and see if that destination translates correctly to (0,1,0)

#

if the destination is local, set it to (1, 0, 0) (to the right I guess is how your thing works?)

golden heron
#

yeah i think so

minor sapphire
#

if it's a world destination use localToWorld.Position/Right

#

so hard code the output of your destination system to (1,0,0) and see what happens

golden heron
#

ok, gimme a sec

#

OutPut Speed Quaternion reads as float3(360f, 0.1054123f, 359.9313f) and constructed from float3(0f, 0.1054123f, -0.06865695f)

#

359.9313f is roughly equal to -0.06865695f

#

in eulers

minor sapphire
#

I don't know how all these numbers apply to your situation, but is this expected?

golden heron
#

it means its doing what im asking it to, thats right before the quat is made, and itscorrect

minor sapphire
#

so with this hard coded value, it's turning as wanted?

#

just keep hard coding the step before until it isn't as expected

golden heron
#

Its still not doing as expected, cant figure out why its swapping the axes

minor sapphire
#

so you want A -> process -> B
but you're getting A -> process -> C?

#

and it's between these two seemingly close steps?

#

maybe paste the code for this A to B transformation now that it's narrowed down to this

#

but if I see like a ton of maths I'll just be like "I dunno" lol

golden heron
#

thats the trouble, its all extensive maths

golden heron
#

I've decided to go with a mathematical implementation of how i overcame this problem in the oldschool monobehaviours, with a slight tweak. Before, I wrote an "Ai rig" type setup, where there were gameobjects at each corner of the ships position, it actually had one in each cubic corner and one in the middle of each line and face, totaling 20 nodes, which to do with entities would be annoyingly complex not to mention it really doesnt like running child objects around. Also, the nodes were each calculating their data every frame. So, i know ive gotten the local to world rotation translations working properly on the normal directional vectors - ive been using it to run a coloured coded set of local axes for visual debugging - so im gonna do a few positional transformations and derive the required pitch/turn movements from that, then, instead of constructing a quaternion directly from eulers, ill construct a new direction vector and then use quaternion.lookrotation. Direction vectors are sooooo much easier, they can be debugged visually with minimum effort too. Im gonna use some basic trig to work that out, aside from the vector itself, ill be using high school maths instead of crazy degree maths :D

#

Oh, and the tweak will be to arrange the node checks into a kind of hierachy, so it will discern from previous checks which checks to proceed with, but also it should be able to half the number of nodes anyways, cos its gonna return yes/no to the queries, and every node has a second node to which the opposite bool condition will apply.

next kiln
#

Are there any examples of using RenderMesh from the new pure ECS HybridRenderer? Everything I've found uses a game object conversion, I want to create a new mesh purely from code.

stuck saffron
#
EntityManager.SetSharedComponentData(entity, new RenderMesh { mesh = data.mesh, material = data.material }); 
||
EntityManager.AddSharedComponentData(entity, new RenderMesh { mesh = data.mesh, material = data.material }); 
#

@next kiln

#

Or do you mean like generating vertex data?

next kiln
#

Thank you! I was getting confused based on the API page for RenderMeshSystemV2, but it looks like the Hybrid Renderer takes up that entire namespace and RenderMesh!

#

That’s perfect, I’m assuming the vertex data is like any other.

stuck saffron
#

Gotcha, some documentation is messy. I mostly get through it with intellisense, definition/exploring, and alt+enter haha

next kiln
#

I might start doing the same hahah. Appreciated!

stuck saffron
#

Anytime! Alright now to my question

#

I am trying to generate entities based off a scriptable object's data. I have a couple approaches: use bools or unity events but they can get messy. I can't seem to use a IComponentData[] directly. Is there any good way of creating a set of different IComponentData types and storing them in one array using the inspector?

amber flicker
#

@stuck saffron I may be missing something but don't you just need a monobehaviour to add those components to an entity? You can create a scriptableobject that has an array or list of IComponentData's right? I'm sure it's obvious but you'll also need to check you're not adding the same component twice

#

wait maybe I misunderstood - are you wanting to use reflection or something to find all IComponentData's in a project?

stuck saffron
#

You cant serialize an interface. IComponentData is an interface so you can't have an array of them on a scriptable object @amber flicker

safe gate
#

You can create an entirely set of "inspector components" that carry inside of them the component itself

#

If you have a RotationSpeed component that has the attribute System.Serializable you can create a RotationSpeedInspector that contains a [SerializeField] private RotationSpeed _rotationSpeed

#

Then your SO would have RotationSpeedInspector[]

#

But if you want a single array for all your components, then you need to create a custom inspector

#

So you could have RotationSpeedInspector inherit from ComponentInspector, and the SO would have a ComponentInspector[]

#

But then you would need a custom inspector so you can choose which type each ComponentInspector should be

#

Or you can create multiple SOs, one for each component and they have the specific array

#

But why you are creating from an scriptable object? You could just use a prefab

#

It seems like you want the SO to be the prefab

#

And I just realized that if you are creating a custom inspector, you could just use a IComponentData[]. There is no need to create a ComponentInspector

stuck saffron
#

Well I have a bunch of different projectiles so I have a singleton scriptable object that contains a ProjectileData[] (SO) where I currently pull the data from to intantiate a projectile entity. However, I am trying to allow designers to pick additional components to attach to the entity

#

Can you? I must doing something dumb if you can actually use IComponentData[] in an SO

safe gate
#

Unity doesn't serialize interfaces

#

You have to create a custom drawer for that

#

It sounds like that you will need a custom inspector or at least custom drawer for that

#

Or just buy odin inspector

stuck saffron
#

I came to that conclusion last night haha but I would need to do the serialization myself too, right?

safe gate
#

Yes, Unity doesn't like interfaces 😑

#

Unless you create the ComponentInspector class to hold the component data

#

Then you just have to worry about the inspector, not the serialization as well

stuck saffron
#

So I was trying something like this earlier:

public abstract class ComponentProxy
{
    public abstract IComponentData GetComponentData();
}

[System.Serializable]
public class HeadshotProxy : ComponentProxy
{
    public float multiplier;
    public override IComponentData GetComponentData()
    {
        return new HeadShotMultiplier { Value = multiplier };
    }
}
safe gate
#

The SO can have a ComponentProxy[]

#

But then you need a custom drawer so the user can select which specialization they want

#

And internally, the ComponentProxy works well with the GetComponentData

#

The only problem is that Unity doesn't know how to show the ComponentProxy[], thats why you need to create a custom drawer for that

stuck saffron
#

Oh, gotcha. Well I have never written a custom drawer before so this should be fun

safe gate
#

It is really fun to work with the editor UI, too bad I don't have always get the chance to

stuck saffron
#

Any suggestions before I jump into it?

safe gate
#

As soon as you learn how to do it, don't let the power turn you into a custom inspector/drawer maniac. You will want that, but you have to be strong and resist the urge

stuck saffron
#

I lack impulse control so may god help me.

#

Also thanks for the help! I appreciate it a bunch

low tangle
#

Can't find the post I remember that was IComponentData storing using Odin but this did come up

twin raven
#

I am trying to get simple 2d animations using ECS. In gameobject world I would have SpriteRenderer and animator, but I couldn't find any information on how to do it with ecs.

#

Is the only way to use hybrid ecs?

urban rivet
#

"hybrid" is just a stop gap really, so if a certain thing isn't supported yet best just use that but IMHO if serious about using DOTS for rendering, it's best to figure out how to animate sprites in shader (such as flipbook etc)

#

(for 2D context and perf oriented)

#

for example 20,000 enemies using sprite renderer is a needless amount of data being pushed to gpu, you could have it so it does generic shader based anims at distance and hero ones close up

#

just spitballing

twin raven
#

Thanks. I was thinking that was the case. I think I will go for the hybrid road and update it later or when they update it. Unity ecs samples repositories doesn't have anything related to hybrid. Is there any documentation how it is supposed to be done?

I used GameObjectEntity.AddToEntity(EntityManager, go, entity) and can see SpriteRenderer & Animator in the entity debugger, but the Transform positions are not being updated. Do I need to make a system for that?

safe gate
#

To update the transform that the entity references, you have to add the component CopyTransformToGameObject

stuck saffron
#

Turns out I have no idea what I am doing with property drawing

twin raven
#

Thanks! that worked

runic moth
#

My current theory is that when DOTS Runtime (C# Tiny) is released, it won't have a garbage collector. Can somebody tell me I'm wrong?

rancid geode
#

DOTS and Tiny are different things (they do have similarities, but are not the same)

runic moth
#

Thanks! I meant to reference Tiny.

tropic cove
#

when ecs will be procution ready ?

safe gate
#

About 2022 I think

rancid geode
#

Hybrid should be somewhat production ready this year yet, but pure ECS only 2021-2022 according to their roadmap

zenith geode
#

If I have a person entity with a health component, and a healthbar entity to display that health, how should I design this? At first I accomplished it by

Health parentHealth = World.Active.EntityManager.GetComponentData<Health>(parent.Value);``` but this seems anti-pattern. Should I use ISharedComponentData? The docs say it should change rarely, so I guess not.
dull copper
#

I wouldn't even call hybrid production ready before we get DOTS editor

#

you can use ECS but it's not a nice and productive until we get that editor

#

having to rely on conversion tools for everything is just hacky, I'd never call that production ready myself

odd bay
#

I don't see ECS as production ready until you can do purely pure ECS

sonic oyster
#

So ECS is unstable and shouldn't be used atm?

dull copper
#

it's more of the experience you get right now

#

it has barely any tooling right now, it's API changes for almost every minor release even

#

it's just horrible equation all around if you think how things work in production

#

and since it's still so early days with it, freezing to one version can work to some extent but it's then pain to upgrade it if needed

#

think of all people who built their game using Unity ECS injection API

#

that stuff doesn't exist anymore, so you have to rewrite pretty much all code now if you want to use the recent developments

#

of course there are occasionally versions that are just bugged, like preview.32

#

I dunno if p33 fixed all the issues yet

#

but that's what you get on any preview, you can't expect it to be fully stable, especially when the framework is rapidly evolving

#

@sonic oyster

sonic oyster
#

Damn

#

So I have to scrap my idea of using Entities for map chunks then

#

How do i store map chunk data then if I can't inherit/refference classes in job system?

#

I need burst compiler to make it work smooth, without it, framerate drops real hard, because every voxel update makes a heavy math to regenerate meshes

dull copper
#

job system and burst are more production ready

#

neither is in beta/preview either

#

and just for sake of clarity, you can use burst on jobs without using entities

sonic oyster
#

I know that, @dull copper, but I'm having a trouble implementing blockdata to job

#

Previously I had a class that was inherited per blocktype

#

Every block had special voids in them that returned values

#

I can't really do that in structs

#

I.e. Block : BlockGrass

It had values for texture, mesh, being solid on every face and onplace/ondelete events

vagrant surge
#

@sonic oyster you use different arrays per layer, including hashmaps or other structures

#

so for example you start with an array per chunk (dense) of NNN int8s, and those are your general blocks per chunk

#

and then, for special blocks (maybe extra data), you have a hashmap where the key is the coordinate

#

with the int block types, you just have number 2 = blockgrass. If you then want, you can implement an array (maybe outside of ECS), where you index with the block type, and it holds the logic for that block type

sonic oyster
#

Hmm 🤔

#

Thanks!

vagrant surge
#

@sonic oyster think of it as adding functionality in "layers"

#

you can access a block on its X,Y,Z coordinate index, so you can have multiple arrays-hashmaps-whatever with extra information that you can access from the index

sonic oyster
#

I use NativeArray for coordinates

#

1D

#

I just do a calculation to get xyz from 1D array

#

Since map chunks have fixed size

vagrant surge
#

yes

#

but in cases where you only want extra data for maybe 10 out of 256 blocks in a chunk, you should use hashmaps

#

another option is to use sorted arrays

#

instead of hashmap

#

you have an array where yo have index + extradata in a srtuct

#

and its allways sorted

#

and you use binary search to find the key you want, or just straight bruteforce if its less than 20 items or so

muted flare
#

guys , anyone got link to megacity code on github ? Im just wondering if it's avaialbe there, cant find. I just need to look at the code 😉

safe lintel
#

its only officially available through that link from unity

golden heron
#

Anyone able to direct me to a good quick tutorial or something for making a camera follow an entity? Or, offer directions :D

safe gate
#

I suggest searching for a tutorial on a camera following a game object, then you just CopyTransformToGameObject

#

I suggest searching for a tutorial on a camera following a game object, then you just CopyTransformToGameObject

#

I suggest searching for a tutorial on a camera following a game object, then you just CopyTransformToGameObject

stuck saffron
#

Gregorio suggests searching for a tutorial on a camera following a game object, then you just CopyTransformToGameObject

golden heron
#

Hehe i dun it

#

i wrote my own setup

#

Its actuslly working nice

#

Thanks for the help tho :)

junior fjord
#

how can I access a dynamic buffer from an IJobChunk?

safe lintel
#

use GetArchetypeChunkBufferType instead of GetArchetypeChunkComponentType

junior fjord
#

@safe lintel thank you

twin raven
#

I wanted to take advantage of gpu instancing with texture2darray, but unitys ecs rendering does not support materialblockproperty. So I made a simple system that renders my entities. However when I get the texture data to texture2darray, something goes wrong

#

The alpha channel is broken. I am not sure if it is how I copy the texture or the shader doesnt support transparency. Probably very easy to fix but I don't know what I am doing 😄

dull copper
#
## [0.15.1] - 2019-05-30
* First Tiny C# preview release. This release is **not backward-compatible** with previous releases.
* Must use Unity 2019.2.0b3 and above
  
### [Editor]
* Added the ability for the editor to change context when working in a DOTS project
* Added the Searcher when adding a component in the Inspector window
* Added a new Open DOTS C# 
* Relocated build options to the top
* Removed Physics2D, Tilemaps, and Particles
* Removed Component type creation
* Removed live-link
* Removed QR Code
* Removed the build report
* Removed Component Families
  
### [Samples]
* Removed all previous samples and replaced them with new sample projects
* Samples are now imported from the Package Manager'

### [Scripting]
* Now supports the DOTS API and C#
* Removed support for Typescript

### [Hierarchy]
* Renamed EntityGroups to Scenes
* Added a new Configuration Scene

### [Project Settings]
* Renamed "Tiny" settings to "DOTS"
* Removed most settings from the Project Settings

### [Prefabs]
* Removed Prefabs

### [Runtime]
* C#
* New build platform options are now available: Dotnet, IL2CPP, AsmJS, and WASM (known issues on certain browsers)
* Removed TypeScript
#

C# tiny on staging now 😃

stuck saffron
#

Freak yeah

dull copper
#

apparently they don't ship with the old fancy examples tho

#

this on the new package

#

they have *.project file here now

#

scene itself uses *.scene

stuck saffron
#

Where do you see the staging?

dull copper
#

you get staging packages if you put staging url to your projects packages/manifest.json:

{
  "registry": "https://staging-packages.unity.com",
  "dependencies": {
    "com.unity.tiny": "0.15.2-preview",
stuck saffron
#

That is nifty. So we should expect this to be officially added hopefully today?

dull copper
#

I'd expect tomorrow earliest

#

depends on what timezone you are at

stuck saffron
#

Ah gotcha, I remember you have talked about this before and turnaround times during the staging phase. Couldn't remember the typical range though

dull copper
#

well, if you saw me talking about it, I probably mentioned staging packages aren't cleared for release yet

#

a lot of things that get to staging don't get released

#

but next version or version after that etc

#

DOTS packages tend to move fairly quickly tho

#

hmmmm, when you double-click .project, whole editor goes into DOTS mode

#

this also only works on 2019.2 betas atm

#

I tried first on 2019.3 alpha and it didn't launch at all

#

can't build and run this tho

#

Error opening for writing the file: C:\Unity\Unity Projects\TinyTest\Library\PackageCache\com.unity.tiny@0.15.0-preview\DotsPlayer\bee~\BuildProgramBuildProgramSources\buildprogrambuildprogram.gen.csproj, error: Permission denied

#

and that path is only 169 chars long for those who wonder if it's too long

#

this also is still a dedicated mode

odd bay
#

DOTS editor for ECS now please

dull copper
#

and I'm afraid it'll stay this way

#

I'd really really want to have both monobehavior and DOTS editor side by side on hybrid

#

but I'm afraid that's not going to happen, it just would make so much sense while we have hybrid here

#

would immediately see both worlds

#

add component menu is pretty funky now too, but it could be because early preview

knotty radish
#

The fact that Tiny is not exactly the same as usual DOTS makes me think it's less performant and may be doing some black magic in the background

#

They removed a lot of things, is there any new or old sample working ?

#

I mean they removed Physics2D, Tilemaps, and Particles which aren't small useless modules (I know they will be back, just asking about your thought on the current version)

rancid geode
#

@knotty radish it is not about performance, it is about size. Project Tiny is meant to deliver very small executables, this is why they removed so many things

#

You can think of Default Unity and Tiny Unity as equal engines with different frameworks

low tangle
#

Love the look of the dots editor

rancid geode
#

I mean, this is how I see the Project Tiny so far, they are being very vague still about it

low tangle
#

Wish I had that for my hybrid project though

#

Tiny is pretty interesting. They have more info on the forums in a sticky

rancid geode
#

Yes, but they don't update it as often as DOTS, so there is many things with incomplete or outdated info

worn stag
#

so how to add custom component to the entity now?

#

i cant get it

#

ah i got it

vagrant surge
#

holy shit at last

#

ive been waiting for Tiny csharp for quite a while

#

time to actually get going now

#

@rancid geode now that tiny uses DOTS C# framework,they should merge

#

Tiny essentially being a "mode" of unity

#

where you have no old crap, but you get great perf + tiny install size

#

Tiny modules will likely work on normal DOTS mode. But i think eventually they will let people choose

#

do you run the DOTS Sprite renderer? with sprite lighting and batching

#

or you run the Tiny sprite renderer, with less perf but has very smal space

rancid geode
#

In the Tiny forums it was mentioned that things like Physics would still be separated (there will be Unity Physics and Tiny Physcs 2D, for example), so while the core framework will be the same, they are still going to be different things

#

I mean, seems like there will be like 4 different ways to develop with Unity

MonoBehaviours
Hybrid (Mono + ECS)
DOTS
Tiny DOTS

vagrant surge
#

it will likely be like unity phisics vs havok physics

#

both use the same components

#

the same API

#

but the backend is different

#

i also expect everything to work everywhere too

rancid geode
#

hopefully it will be that way, but there is no official comment about that yet

vagrant surge
#

no reason not to, really. If you only use basic 2d, then use the Tiny systems even if its a desktop app

dull copper
#

DOTS is going to have it's own 2D physics

#

I dunno if there will be tinier variant for 2D and 3D physics but I don't think even current 3D DOTS physics is super bloated

#

btw, Tiny got a bump to 0.15.1-preview on staging

#

I think they changed the min engine version from b1 to b3

safe lintel
#

man i just cant imagine the final goal for dots editor is going to be the same kind of disparate way tiny is

sonic oyster
#

Hey! Trying to get non-ecs jobs to work. I made a readonly struct with data to use in job.

Editor throws that I can't use managed structs. What I can do about that?

#

I want a struct that doesn't copy itself in memory when I allocate something as it.

#

Struct itself looks like this:

	public Block(int value1, bool value2) {
		this.val1 = value1;
		this.val2 = value2;
	} 

	public int val1 { get; } 
	public bool val2 { get; } 
} ```
golden heron
#

Anyone got any suggestions about the order of collisions systems with relation to movement systems? I have my movements, my rotations, and both systems ready to receive responses from the collisions, and, i have the collisions being detected. So, whats the best order? My aabb system currently doesnt have a defined position in the order of things.

#

Im good with code on this one - this is the fun bit ive been looking forwards too :D

#

Mostly just considering ideas :)

vagrant surge
#

0.15.2 too

#

i wonder if they are doing the blogpost+ official today

dull copper
#

package manager got funky on 0.15.2

#

it tells me 0.15.0 is installed but peek in library shows 0.15.2

#

it also don't let me install samples as those links are now hidden 😃

#

I just copied the samples manually as that's what PM would do anyway

#

ah, now the PM updated to show the right data

vagrant surge
#

are there any links to docs

#

or samples

#

or github

dull copper
#

well, the sample projects are on the package itself

#

they should show up on package manager (WHEN it works like it's designed)

#

well, it built now for the first time

#

I dunno if it's 15.2 or just that I had one folder shorter path when I manually copied the samples

#

I kinda wished they would have ported the old tiny samples here

#

but there's probably stuff missing

#

getting to play mode is basically just build and run

#

I kinda wished you could play the old way in editor

#

as waiting for half a minute to test your changes isn't that great workflow

#

there's quite huge difference if you use debug or release 😃

vagrant surge
#

unity 19.3, no?

#

so i download it

dull copper
#

this only works on 2019.2.0b3 and b4

#

latest 2019.3 alpha can't even load the new DOTS .project file

#

or well, I haven't tried with the 0.15.2, but 2019.3 alpha failed to load 0.15.0 at least

#

you can add regular ecs components here but there's like only 2D camera

#

also, the initial setup for this is tedious as you need to add the custom packages in the asmdef manually

#

but that's expected as these aren't supposed to be used yet

#

it does have all tiny and base entities refs in place

#

@vagrant surge tested 0.15.2 on 2019.3 alpha and it still fails, no surpises there

#

it's similar case with megacity demo

#

you can only run it on 2019.1 as it's the only one that has dsp graph in the binaries 😄

vagrant surge
#

how do i download it?

dull copper
#

2019.2?

#

you can use Unity Hub for it

#

oh you probably meant tiny

#

it will not show normally in the package manager, you have to open your projects packages/manifest.json and put this on top:

{
  "registry": "https://staging-packages.unity.com",
  "dependencies": {
    "com.unity.tiny": "0.15.2-preview",```
#

it'll force it to use more experimental staging repo where the new tiny package is atm

#

you may need to put entities p33 manually from package manager as well

#

it's a dependency for tiny but some package (at least on 0.15.0) forced some older jobs or collections etc there that caused issues

#

this is my package list for tiny test:

{
  "registry": "https://staging-packages.unity.com",
  "dependencies": {
    "com.unity.entities": "0.0.12-preview.33",
    "com.unity.ext.nunit": "1.0.0",
    "com.unity.ide.visualstudio": "1.0.11",
    "com.unity.package-manager-ui": "2.2.0",
    "com.unity.test-framework": "1.0.14",
    "com.unity.textmeshpro": "2.0.1",
    "com.unity.timeline": "1.1.0",
    "com.unity.tiny": "0.15.2-preview",
    "com.unity.ugui": "1.0.0",
    "com.unity.modules.ai": "1.0.0",
...
#

basically just put that in place of the things that are there up to modules.ai, leave all the modules as they are unless you really know what are not needed by the editor

vagrant surge
#

ok, how do i do that

#

create new project, find the manifest json, and add it?

dull copper
#

create a new project using 2019.2

#

if you use hub 2.0.0, unity version selection for new projects is really stupidly hidden

#

but it does default to newest installed unity version

#

(but then again, almost everyhing on hub 2 is designed backwards)

#

if you have hub 2, this lets you pick the engine version for ne project

#

after you got new project, find the packages folder and swap that thing to the beginning of the manifest

#

it should update everything (even if you have the editor running on the background)

#

@vagrant surge

vagrant surge
#

what project type?

#

2d-3d -lwrp?

dull copper
#

2D and 3D are fine I suppose

#

don't put LWRP or HDRP

#

basically these are just templates

#

I usually use 3D as it's basically equivalent of empty project

vagrant surge
#

@dull copper where are the samples/tests?

#

haveit running

dull copper
#

open package manager (from windows menu), select Project Tiny (or whatever it's called there) and you should see buttons to install specific samples

vagrant surge
#

@dull copper kinda meh that it opens standalone

dull copper
#

yeah, original tiny was like that too I think?

#

well, it launched browser

#

now you at least have option for mono build too which is tad faster due to lack of IL2CPP in the middle

#

tbh I expected you would be able to just play immediately when they get c# version

#

but apparently not

vagrant surge
#

this thing leaks like crazy

#

the spawndestroy sample

dull copper
#

my biggest disappointment is really that it's still full editor replacement

#

I'd want to swap between monobehavior world and ecs world in the editor while playing

#

or even editing

#

it would be super useful as long as hybrid is a thing

#

there's also no prefabs on DOTS mode

#

I hope they can add them back

#

or come up with something equivalent

vagrant surge
#

come on

#

imean you can use the very classic ECS pattern of spawner component

#

that holds all the variables needed, and then on first execution it "unpacks"

low tangle
#

I think I'm just going to build more ecs editor tooling as I need it

#

starting to feel a need for a runtime inspector for debugging my networking entities

vagrant surge
#

@dull copper no prefabs, its loadign Scenes

#

thats literally how godot rolls

#

instead of having a separation beetween a scene and a prefab, it loads scenes all the time

#

as it can load scenes in scenes and scenes attached in a scene node

vagrant surge
#

@dull copper you can see the sources of the packages, no?

#

how?

#

i cant do " go to definition" in vs

dull copper
#

@vagrant surge yeah, that's what I meant by "or come up with something equivalent", I know how godot does this 😃

#

the package source thing is bit dumb

#

you can get the VS see the sources but you need to manually move the packages you want to examine from your project folder/library/packagecache into packages folder

#

basically what happens then is that Unity will no longer cache those packages internally but uses the local versions on your packages folder (you also can't update these with package manager then)

#

but when you have local packages and you open any c# file from Unity, it generates a solution that has all files from local packages as well

#

it's hacky but at least you get full sources in VS for those packages

#

I personally deal with that so that I have separate project which I use to update the packages and then just copy the new ones on my working projects packages

minor sapphire
#

@dull copper you can go into preferences and check "generage all .csproj files"

dull copper
#

really? 😄

minor sapphire
#

however, this is buggy on VS 2019

dull copper
#

man, I've been doing this the hard way for a long time then

minor sapphire
#

but a workaround is...

#

unselect, it, then reselect it

#

then open project

dull copper
#

let me try this (I'm on VS2017)

minor sapphire
#

2017 should work I think

dull copper
#

@minor sapphire is that VS preferences or Unity?

minor sapphire
#

unity

#

external tools

dull copper
#

ah, I know the place

#

well just enabling it and launching VS didn't work

#

I'll try toggling it off and on again

#

also wipe the current files

vagrant surge
#

@minor sapphire where?

minor sapphire
#

in your project folder you should see a lot of csproj files

dull copper
#

edit->preferences->external tools

minor sapphire
#

👆

dull copper
#

but it definitely doesn't work for me

#

I tried doing it from scratch

minor sapphire
#

it's temperamental from what I can tell lol

dull copper
#

it only gives csprojects for same things I've always got

minor sapphire
#

I have to uncheck and recheck every sessions if I want to debug package code and see source in VS

dull copper
#

well, I tried toggling it

#

nothing change

minor sapphire
#

d you have another vs version installed?

dull copper
#

nah

#

but I see the csproj files here

minor sapphire
#

one time I had to switch to 2017 then back to 2019 lol

vagrant surge
dull copper
#

they are the same that Unity uses by default

vagrant surge
#

nothing

minor sapphire
#

maybe in a new versio nblanco

dull copper
#

@vagrant surge swap the first value to visual studio

#

you have it set to internal

#

so.. I guess I keep using my hacky workaround :/

minor sapphire
#

damn that's a shame

dull copper
#

you'd see the entities csproj on your projects root folder if it works

minor sapphire
#

yes

vagrant surge
dull copper
#

heh

#

tough luck

minor sapphire
#

I'm on the beta

#

maybe it's a newish thing?

dull copper
#

I think he has to be too

#

because new Tiny only runs on 2019.2 b3 and b4

minor sapphire
#

oh right

vagrant surge
#

im n 19.2 b3

#

well,latest

#

b4

dull copper
#

anyway, if that fails, what I told does work

#

it's just bit tedious when you update packages

minor sapphire
#

I'm 19.2b2

dull copper
#

other it's just cut and paste from one folder to another

#

that option exists on my b4

minor sapphire
#

maybe the VS editor package is related. I have 1.0.10

#

0Lento try updating

dull copper
#

I have 1.0.11

#

I doubt I can go to the future=D

minor sapphire
#

lol, try downgrading 😄

#

haha

dull copper
#

it's no big deal

minor sapphire
#

for some reason... I am not on 11 deliberately

dull copper
#

just would have been fancy if it had worked

minor sapphire
#

and I can't remember why

#

maybe this is it

#

I was on 11, then downgraded

#

I forgot the reason hahaah

dull copper
#

hmmm

#

looking at the recent roadmap slides, they plan to release Tiny at second half this year

#

that sounds quite optimistic

minor sapphire
#

I want physics update 😐

dull copper
#

me too 😃

minor sapphire
#

I'm on the fence about trying to implement physics myself for 2d, or waiting to see how they go in unity physics

#

but like, I don't really want to implement everything myself lol

dull copper
#

it's kinda pity that they don't give estimate for 2D DOTS physics

#

I know they are working on it

minor sapphire
#

2d physics is confirmed?

#

I read some forum post that suggested it was not planned

dull copper
#

not officially I think

minor sapphire
#

but it wasn't unity saying that

dull copper
#

Burst's determinism is still marked only "Future" on this roadmap :/

#

it sounds very much it's going to get postponed to 2020 at this point

#

at least they finally are working on DOTS integration for addressables

minor sapphire
#

what is addressable assets

dull copper
#

it's the new thing that will replace asset bundles

worn stag
#

has anyone build successfully in tiny? i keep getting this error

dull copper
#

yes

#

I kept getting that first too

#

are you on latest?

#

0.15.2?

worn stag
#

yes

#

2019.2.b4

dull copper
#

if you click on the message, it tells the actual error

#

but it could be too long path

#

when I manually moved the samples to the project root, I could build it

#

but I also updated to 0.15.2 at the same time

#

so it was either one of those things

worn stag
#

it was

dull copper
#

@minor sapphire I wiped the whole library and now I get all csproj's with that setting

minor sapphire
#

nice 😃

dull copper
#

the reason why I don't do that lightly on this project is mainly HDRP

#

I'm running custom version which means I compile all shaders from scratch

#

which means on my dev computer that first build on fresh library takes few hours

tawdry tree
#

Ouch

urban rivet
#

cinemachine seems to currently do more harm than good for game cameras

#

janky behaviour, lots of little issues you need to know about etc etc, its good for film I guess?

knotty radish
#

It should improve when it will be ecs/jobified

#

But yeah at the moment I prefer not to use it anymore and just handle my own camera

safe lintel
#

new physics package 0.1.0-preview

#

and samples on the github updated

dull copper
#

ooo

#

about time 😃

#
We've just pushed 0.1.0-preview of Unity Physics and this contains many things discussed on this very forum, with more to come

* The new Joint for 2d use cases is there
* Sync points have gone - more to do there.
* Bounding Volume Hierarchy improvements should help performance
* The RaycastInput struct is tweaked to remove `direction` confusion
* Runtime CollisionFilter members now match the editor PhysicsShape component
* Physics Body and Shape ConversionSystem improvements are many
* Trigger events are now raised between kinematic && (kinematic || static) bodies
* Dynamic bodies with `PhysicsMass` components only are now integrated
* Trigger and Collision events demos were added```
vagrant surge
#

no unity tiny post

dull copper
#

@vagrant surge it's not yet at regular registry yet

#

either they are not ready to release current one from staging or they just didn't have time to prepare the announcement etc

#

it's possible they still want to change something etc

dull copper
#

oh wow, Unity Physics 0.1.0 doesn't crash anymore on IL2CPP build

#

and it actually simulates physics now (0.0.2 just did random things)

tawdry tree
#

Isn't that a bit harsh?

dull copper
#

what is?

#

and btw, it does still crash on master and release settings (just not on debug where you'd actually see the error :p) but I think it's just the hacky try/catch tracker script again

#

I dunno if IL2CPP even supports try/catch

vagrant surge
#

lmao

#

quality code

dull copper
#

well, it's hacky script to begin with

#

basically the idea is to give entity id to monobehavior tracker script WHEN the entity sender script runs conversion to ECS side for the entity whose transform you want to track from the old side

#

then the tracker script just polls the entity manager to get the transform data from that entity id each frame

#

it's wrapped in try/catch which is so far from ideal

#

basically if it fails and catch occurs, it just stops tracking the entity after that, meaning the entity has been removed

#

but why this crashes on IL2CPP build is that sometimes the tracker runs before entity is properly initialized and it can't get the component data + IL2CPP can't handle the try there

#

last time I just put small delay there to avoid this but obviously it's not the proper solution

#

I wonder if there's a way to check if there's entity with given index in a safe manner

#

I haven't really checked either

#

as that would let one fix this setup better

minor sapphire
#

3 cheers for physics update wooo

#

now just have to figure out new way to interact with trigger/collision data

#

I can't see any demos related to this hmm

dull copper
#

hmmmm, the master crash isn't about the tracker script

#

in fact I have zero clue what crashes it

#

it doesn't crash on IL2CPP debug build, only with release and master

#

and crash is access violation on UnityPlayer

#

for the crash, disassembly pointed the crash to this: cpp // System.Boolean Unity.Jobs.LowLevel.Unsafe.JobsUtility::GetWorkStealingRange(Unity.Jobs.LowLevel.Unsafe.JobRanges&,System.Int32,System.Int32&,System.Int32&)

#

I guess I just have to do a repro and send a report

minor sapphire
#

do you typically see much performance gain on IL2CPP?

#

I've never been able to get it to work lol

dull copper
#

it's not about that, I have my other reasons to use it

#

IL2CPP seems to have a lot of issues with DOTS now

#

I've reported bunch, worked around some

#

for Unity Physics, that's almost expected as it's a new package but you'd still think Unity would test it on all build confs, considering you have to use IL2CPP on some platforms without any other alternatives

#

I think it's the unsafe stuff that's the issue now, I had instant crash on debug build too if I had unsafe enabled on the build settings

#

and the master crash got traced back to unsafe call too

minor sapphire
#

The new ITriggerEvents job and ICollisionEventsJob seem good at first, but I feel like maybe I can't parallelise them well hmm

#

oh man and it's missing ScheduleSingle so I can't even get around the problems

#

basically means command buffer is useless here

#

god I hate having to know the size of native collections before you use them, I don't know how many elements there are lol

dull copper
#

I'm getting totally another issue on 2019.1 while trying to repro the IL2CPP issue

#

when I use convert to entity, none of the meshes render anymore on HDRP 5.16

#

I've had this for some meshes before too even on latest experimental engine versions

dull copper
#

it's also purely IL2CPP issue, on mono build these all render fine

tawdry tree
#

So... you tried to repro one bug and accidentally repro'd another?

dull copper
#

yeah, I guess

#

still having trouble getting the repro for the original issue but I'm getting there

#

it doesn't help that DOTS physics samples build and run just fine with IL2CPP 😃

#

I mean, that's probably what they test these things with

#

well, moving that super simplified sample from HDRP to LWPR now triggers some crash at least

#

it's not at the same point in UnityPlayer but it's still in job system

low tangle
#

@dull copper in monobehaviour land why cant you just do enititymanger.exists then hascomponent on entity? has worked great for my ui systems up till now

dull copper
#

@low tangle that's actually what I ended up doing yesterday

#

but it turned out the crash wasn't from that script this time around

low tangle
#

one of my proxy's is basically just this for a voice plugin system

#

        public Vector3 Position
        {
            get
            {
                if (ECS.EntityManager.Exists(Head) && ECS.EntityManager.HasComponent<CopyPositionRotation>(Head))
                    return ECS.EntityManager.GetComponentData<CopyPositionRotation>(Head).Position;

                return new Vector3();
            }
        }
dull copper
#

or well, I just used component count thing but I dunno if it's safe if the entity with that ID doesn't exist

#

there isn't really any way to poll if entity itself exists

low tangle
#

exists is safe with invalid id's

dull copper
#

ah

low tangle
#

that method is

#

its a bit harder in a job, you would have to open a exclusive entity transaction to use that method, but thankfully I never have to check for existance in jobs often

#

think buffer/component from entity structs support exist or something like that for those cases

dull copper
#

anyway, thanks for the snippet, I'll try it if I still have issues with that script

low tangle
#

works great for my proxys to my voice player tracker for dissonance

#

FromEntity structs have a exists method on them

dull copper
#

ah, so it exists 😁

low tangle
#

bodybuffer being a entity inside of a component data

#

should add a check there instead of assuming its always there

#

but its always there

#

one of the best parts of dots is you can forgo some checks because you know for a fact that entity will always be created with a valid x

#

unless you change logic way later to break that absolute it works great

#

but you do run into the fact that thats now encoded hidden logic and assumptions about the code you wont see months later

dull copper
#

well, filed two reports now, one for the convert to entity issue with IL2CPP, another for Unity Physics crashing on master and release confs with IL2CPP

#

will see how this goes

#

while at it, could file that one issue report again that got lost in the way like month ago :p

low tangle
#

👌🏻

twin raven
#

Can I use materialpropertyblock with ecs rendering?

#

I started doing my own rendering and calling drawmeshinstanced but quickly realized i would have to deal all sorts of stuff like z ordering and culling ans gave up 😂

#

I found some projects on github but they were outdated

minor sapphire
#

anyone know where I would go to permanently edit a package cs file?

tawdry tree
#

Package cs file? You mean a file in a package? That should be under packages, if you actually get it in source form instead of a dll or something

minor sapphire
#

It's under packages in the unity project, but that is the package cache and changes are overwritten when loading unity

#

it's all good though I think I don't need to modify atm

#

now I have a new question though! is writing to a dynamic buffer thread safe??

tawdry tree
#

If it lets you do it at all, then it should at least be threadsafe enough that thread1 can write to [x] and thread 2 can write to [y] where y != x

minor sapphire
#

I mean I just want to do buffer.Add(element) from multiple threads

#

where it's the same entity's buffer

tawdry tree
#

It's when you (potentially) want multiple threads to write to the same location, or mix read and write stuff gets weird

#

I don't know what buffer's .Add does under the hood, but I reckon it is implemented to be threadsafe

minor sapphire
#

I'll see if I can see in the source

tawdry tree
#

And going back to permanently editing a package's cs file... you'd need to make your own version of the package, really

minor sapphire
#

right, thanks

#
        public void Add(T elem)
        {
            CheckWriteAccess();
            int length = Length;
            ResizeUninitialized(length + 1);
            this[length] = elem;
        }
#

this doesn't look threadsafe to me

#

hmm

tawdry tree
#

Depends on what CheckWriteAccess() does

minor sapphire
#
        [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
        void CheckWriteAccess()
        {
#if ENABLE_UNITY_COLLECTIONS_CHECKS
            AtomicSafetyHandle.CheckWriteAndThrow(m_Safety0);
            AtomicSafetyHandle.CheckWriteAndThrow(m_Safety1);
#endif
        }
tawdry tree
#

Oh yeah, would you see

minor sapphire
#
        //
        // Summary:
        //     Checks if the handle can be written to. Throws an exception if already destroyed
        //     or a job is currently reading or writing to the data.
        //
        // Parameters:
        //   handle:
        //     Safety handle.
        [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
        public static void CheckWriteAndThrow(AtomicSafetyHandle handle);
tawdry tree
#

So not safe, but there's a framework for a proper safety

minor sapphire
#

wish I could just make a thraedsafe version of it...

#

can't lock a struct though lol

#

and I have a feel burst might not like lock

#

they have atomic writes on multihashmap

dull copper
minor sapphire
#

saw that from a tweet aras did a few days ago

#

pretty cool for people doing mesh manipulations 😄

junior fjord
#

if I want something to just crash with an error, how would I do that from a jobsystem?

junior fjord
#

how would I read an Isharedcomponentdata in a job?

minor sapphire
#

holy crap native multi hash maps are a PITA

#

@junior fjord maybe just try accessing a non-concurrent array in a parallel job

junior fjord
#

😄

#

I thought there would maybe be a planned way to let it fail

#

I mean something like Exception("this and that happened")

minor sapphire
#

oh lol

#

right um

#

try throwing exception?

junior fjord
#

but it is a very funny way to misinterpret the question haha

minor sapphire
#

god I better sleep

#

I'm going to have nightmares about these ridiculous multi hash maps

junior fjord
#

😄 haha yeah but at some point when you're really tired you also can get in a really nice flow

minor sapphire
#

usually sure... until NMHM is required

#

then it will just be throwing up brick walls everywhere

#

making you want to tear your teeth out as a distraction from their stupidity.

#

night

golden heron
#

Anyone able to help me get my head around the NativeMultiHashMap container?

#

As far as i see, it is an array whose entry values could be more than one per index?

#
public NativeArray<TValue> GetValueArray(Allocator allocator)

With this being used to recall multiple values from the hashmap in a standard nativearray?

Would i be right in thinking it can be thought of as a multidimensional array?

#

So, like each index of the hashmap can hold a little list of values, with the inner list having only a numbered 0+ index?

#

And, it also appears that an access via directly indexing first the hashmap then the inner list would not work, you'd index the hashmap, then the value returned would be the native array which you'd index independently for an actual value

#

Also, the capacity, is it limited to only what was set when it was initialised? And the indexes it can be referenced with, does that include a float3?

tawdry tree
golden heron
#

Ah, i see, thanks

#

It would then appear it is also possible to generate my own hashcodes

tawdry tree
#

Yup. Just FYI, it's considered best practice to override .Equals() if you override .GetHashCode() (return a.GetHashCode() == b.GetHashCode())

golden heron
#

If im honest, im a self taught coder and, until now, had not encountered nor used hashes - it seems that their own function will suffice.

#

I didnt really fully understand what it was, but it seems intrinsic to their definition that, within the realms of possibility, the hash code should return a unique identifier, and in the case of spatial mapping intended to break the large space into smaller units, the 4 billion potential combinations should suffice hehehe

#

I mean, even if i wrote a test case where every spatial unit was containing an entity for association to the grid, i expect my use wouldnt pass even into millions let alone billions hehe

#

likelyhood is approximately 1000 maximum.

#

at least, 1000 maximum active

vagrant surge
#

@golden heron hashes arent unique. Its perfectly possible to have "hash collisions", where you have the same hash for 2 different objects. They tend to be fairly bad tho

#

@golden heron hashmaps are one of the most useful data structures. There are TONS of versions of hashmap. Their general idea is something of the sort of:
You have an array Data[], size doesnt matter, but its common to have the size as prime number or power-of-two.
When you add a element to the array, you calculate its hash, and then you calculate the final index by doing modulo of size

#

essentialy

#
void hash_add(Object obj){
int hash = obj.getHash();
Data[ hash % Data.Size  ] = obj
}
#

of course, its very possible to have 2 different objects collide into the same index. Thats where shit gets hard. For those cases there are TONS of different hashmaps implementations. Everyone does it differently

#

i dont know how unity hashmap deals with that case 🤔

sonic oyster
#

can i somehow declare meshdata inside an IJob?

#

i want to build procedural mesh inside a job, and i'm getting this:
InvalidOperationException: Job_RenderChunk.meshdata is not a value type. Job structs may not contain any reference types.

#

and i've seen people doing this before

#

and it WAS working for them

sonic oyster
#

okay i got it

#

not exaclty declaring meshdata

#

but NativeList<Vector3>, NativeList<int> and NativeList<Vector2>

#

it works

#

gonna switch the channels tho, because i have literally no idea how triangles work here

golden heron
#

@vagrant surge im currently encoding a replacement gethash function (not an override tho) that can return a value which IS unique, and, as a side effect, can be translated back into the original float3 it was made from. This does limit me to a range of +-500 on each of the three axes, but im also using the entire 4 billion or so available values of an in32 to do it hehe

low tangle
#

but was that really needed or are you just making busy work for something that might be helpful in the future?

golden heron
#

Its for a spatial partitioning system.

#

An effective hashing system providing unique hashes with minimal calculation will improve the ability to avoid unnecesary calculation in the collision systems

#

the +- 500 is fine for that, and im gonna make it so if you go outside of that basic range your position will read asif you were at the edge of the box.

vagrant surge
#

for spatial partitioning you do not want unique ids

#

you want the id to just be the "grid coordinate"

#

that way you can easily get the objects inside a grid location

golden heron
#

But if the ids are not unique, the resulting boxes wont be unique, either. Surely that results in grouping together grid locations that are not, in fact, in the same place.

vagrant surge
#

thats the point

#

you can use that to find objects near you

#

its useful for boids or physics

golden heron
#

How is it used for that?

low tangle
#

if you check inside the boid sample the do exactly that

#

they use the mutli bucket feature of the hashmaps to put all fish in this cell of space

#

they all have real unique actual positions but only need coarse ones to hash with so you can get all the cells around you quickly

#

think of a oct tree but just one size leaf for everything

golden heron
#

Is there something i could read that talks about using hashmaps this way? I tried looking for general info earlier but seemed impossoble to get a definition even

#

i already know some ways my own system can easily find adjacent cells and stuff anyways ;)

#

Its laid out in such a way if you want the cell exactly four cells to the left, one down, and three forward... easy.

low tangle
#

or you could just hash the target cell and get all from the hash map :^)

#

the memory fetch is the slow part, iterating more things in a cell isn't a bad thing when part of them would be checked anyways

#

not sure if theres a single source

#

but I'd look at the boids demo

#

public NativeMultiHashMap<int, int> hashMap;

#
[BurstCompile]
        [RequireComponentTag(typeof(Boid))]
        struct HashPositions : IJobForEachWithEntity<LocalToWorld>
        {
            public NativeMultiHashMap<int, int>.Concurrent hashMap;
            public float                                   cellRadius;

            public void Execute(Entity entity, int index, [ReadOnly]ref LocalToWorld localToWorld)
            {
                var hash = (int)math.hash(new int3(math.floor(localToWorld.Position / cellRadius)));
                hashMap.Add(hash, index);
            }
        }
low tangle
#

theres systems for all the stages of updating bits on all transforms

#

but if you want to get stuff from it theres a child entity buffer array attached to the parent

#

buffers are stored in seprate chunks

#

smaller ones iirc but yeah

#

chunks are basically just linear byte arrays at a fixed size

#

and unity does the work of reinterpeting them as whatever

dull copper
vagrant surge
#

so its about to pop