#archived-dots
1 messages ยท Page 114 of 1
but I then remembered that foreach only iterates componentdata with actual content in it
my guess is WithAll is just for entityQuery and foreach creates iterators๐ค
ForEach is just IJobChunk in the end
ah, so it's potentially cheaper that way
but it is just my guess๐
Well i use WithAll to have those tags in my component but i am not interested in reading them, i just want them to exist in my entity. It also lowers burden to 6 limit of ForEach lambda components
has there been any official word on what's the deal with readonly (or lack of it) on Entities.ForEach
they didn't feel it was needed?
im not sure i follow, you can use in for readonly
there is already readonly components in ForEach, you have to put "in" instead of "ref"
if thats what you mean
can you put PhysicsWorld to "in"? ๐
that was actually where I remembered this
but it wasn't really because of the foreach, but the different structure otherwise
i am waiting this beauty๐
that's coming on some future physics package?
that code seems very odd to me
why is that WithAll needed there?
@mint iron entire lambda stuff seems pretty odd to me
pretty sure lambdas arrived specifically to reduce the boilerplate
@dull copper WithAll (and WithAny and WithNone) are cheaper, because they just have to check if they exist, they don't have to go and get the data.
we didn't have them initially
@bright sentinel but in that example snippet, would it really benefit to do both WithAll and ForEach for the same Health component?
nope it doesnt, and yes i think thats just a concept
just checking ๐
Ah right, no it doesn't make sense to have them in both
Not sure if it actually double queries them tho
Hopefully not
oh snap
"Unfortunately, this year, after much thought and deliberation, we have made the difficult decision to pull out of GDC 2020."
sorry, not related to this channel, look more in #497866432277643275
and it actually gives error to have them both on ForEach and WithAll
"EntityQueryDescValidationException: EntityQuery contains a filter with duplicate component type name CampaignEntityTag. Queries can only contain a single component of a given type in a filter."
this is what i got when i put CampaignEntityTag to both ForEach and WithAll
Well there you go
Also i managed to do collider cast after i inspected unity's entity physics samples, i am so proud of myself \o/
so to get back to the thing I remembered wrong... you can't set [ReadOnly] anymore for structs that exists already that you want to feed into Entities.ForEach... that physics collision world is one good example of it
physics collision world is not a component tho ๐ค
right now there is no way to get read only physics collision world, but there is a hack for it so you can do your raycasts in peace
i bet they will do CollisionWorld.ToReadOnly() in future
readonly thing was for IJobForEach structs
you'd think it's not just physics that is potentially affected
[BurstCompile]
public struct RaycastJob : IJob
{
public RaycastInput RaycastInput;
public NativeList<RaycastHit> RaycastHits;
public bool CollectAllHits;
[ReadOnly] public PhysicsWorld World;
public void Execute()
{
if (CollectAllHits)
{
World.CastRay(RaycastInput, ref RaycastHits);
}
else if (World.CastRay(RaycastInput, out RaycastHit hit))
{
RaycastHits.Add(hit);
}
}
}```
that's again physics related example
Yeah, i tried that putting "WithReadOnly(collisionWorld)" but it gives an error
in future i hope ๐
Is there a reason you want to get a readonly version of the physics world?
that would be the logical place for it
I'm pretty new to DOTS Physics, so I don't really know that much about it yet
to raycast in peace ๐
it breaks without, unless you do the ForEach on main thread
when you do a raycast you have to get collision world, and Unity thinks that when we get collision world we are modifying it so it gives errors
Ah I see
so you have to do read only hack to do raycast for the time being, until they introduce read only collision world
Is that on their radar?
no idea ๐
i dont think so ๐
the hack:
public struct CollisionWorldReadOnly
{
[ReadOnly]
public CollisionWorld collisionWorld;
}```
```cs
var collisionWorldReadOnly = new CollisionWorldReadOnly
{
collisionWorld = buildPhysicsWorld.PhysicsWorld.CollisionWorld
};```
and then cs if (collisionWorldReadOnly.collisionWorld.CastRay(input, out hit))
just feels dirty
but this does not work woth physicsWorld๐
oh?
at least if i did everything right๐ค
yeah, both physics world and collision world has raycast methods, not sure which one we suppose to use, but collision world is fine for now ๐
physicsworld just cals collisionWorld.CastRay
but there is no motion data in collisionworld, it is in dynamicsWorld
just tried it here, no dice
did you use FinalJobHandle?
yes
when setting PhysWorld to readonly with that hack it says
InvalidOperationException: The previously scheduled job TestSystem:<>c__DisplayClass_OnUpdate_LambdaJob0 reads from the NativeArray<MotionData><>c__DisplayClass_OnUpdate_LambdaJob0.Data.physicsWorldReadOnly.physicsWorld.DynamicsWorld.m_MotionDatas.
You are trying to schedule a new job Solver:ApplyGravityAndCopyInputVelocitiesJob, which writes to the same NativeArray<MotionData> (via ApplyGravityAndCopyInputVelocitiesJob.MotionDatas)
did you also add update after buildphysicsworld?
collisionWorld works in my project
[UpdateAfter(typeof(BuildPhysicsWorld))
yeah, collisionWorld works
just not the physicsWorld
what you need that motion data for?
If a ForEach query has a ReadOnly component, how will that change how that job dependency is handled?
Compared to a ReadWrite component
strange, my raycasts haven't been effected by recent changes
you probably use the traditional job structures still
ahh yes, thats it im just doing an IJob
yes, that still works the same
also Unity Physics samples on the sample repo still use IJobs
so, it's not like we couldn't work around this
just need to do more of that boilerplate code again
@bright sentinel It will allow other systems that schedule a foreach over that read-only component to potentially have the job run in parallel
If the lambda took the component as ref instead of in it would be forced to run in sequence instead
Hi, do you know how can I change a material from an entity? I've tried with a foreach, with an EntityCommandBuffer, I can't find the correct way to change it...
@zenith wyvern Okay, but what if those jobs modify the component? Won't that bring some issues?
Like I said Unity will force them to run in sequence so there's no possibility of a race condition. That's the promise of the safety system
Okay, so if I schedule two jobs, one with ReadOnly and one with ReadWrite at the same time, they will still be sequenced?
I mean right after each other*
@gusty comet
var renderMesh = EntityManager.GetSharedComponentData<RenderMesh>(entity);
renderMesh.Material = newMat;
EntityManager.SetSharedComponentData(entity, renderMesh);
There are performance implications for this, read up on how SharedComponentData works
@bright sentinel Yes, Unity won't let a ForEach job read from a component while it's being written to
You can only read in parallel
Ah okay, thanks.
yeah, thats why its important to properly mark components with ref or in, so they can be scheduled in most efficient manner
Mike Acton (senior DOTS guy) is really big about thinking about data modification patterns and that's an example
not just 'can I change this to readonly' but 'can I arrange so this is unnecessary to begin with'
since it often makes things simpler to understand (can't read or write data you never see, etc.)
awww rip DOTS stuff in GDC ๐ฆ
they are not dead๐
i was pretty excited tho ๐
I wonder how they're going to do the keynotes now. Just a dude in front of a camera or something
but yeah totally understandable
thank you @zenith wyvern, where do you do that?
I imagine they just produce some limited amount of content now
is there a difference between doing Run and doing Schedule and do Complete right after that ?
Run is on main thread, schedule is single job that can run at worker thread
There would definitely be some overhead from scheduling a job
i just see some people scheduling a job and do Complete right after that, was just wondering if it is better to just do Run
It depends. If they're scheduling a ForEach it could potentially benefit from being able to run parallel across multiple chunks. That will only happen if you schedule a job. So if your entity count is high enough to potentially cross chunks then it could be faster to schedule and immediately complete the job
I don't know exactly how much overhead there is for scheduling a job compared to doing .Run so hard to say when you would want to schedule vs run
but Schedule is not parallel or am i wrong?๐ค
Hahah, I guess it depends if we're talking about SystemBase or JobComponentSystem
Thanks Unity
I'm specifically talking about a parallel ForEach vs the same ForEach using .Run
oh, i already got used to SystemBase๐
Yeah it's funny if you write a foreach in SystemBase using .Schedule and look in the burst inspector you see that the job struct is compiles to gets called with "ScheduleSingle". Not sure why they did it that way
tbh, i wish both were explicit, ScheduleSingle and ScheduleParallel ๐
That would be much better imo
oh god, I finally update that material !!! In fact you should use a ComponentSystem (not a Job) and use the PostUpdateCommands (not the EntityManager)
You really shouldn't, ComponentSystem is going to be deprecated at some point.
great !
Or SystemBase class ๐
@opaque ledge I'm pretty sure I've tried it already and get error like can't set shared component at this time or something like this
hmm ๐ค
well i never tried to do anything with shared component, but it should be doable ๐ค
@opaque ledge right, it's not a big change, I'll try it and let you know
๐
@opaque ledge InvalidOperationException: Structural changes are not allowed during Entities.ForEach. Please use EntityCommandBuffer instead.
@gusty comet you can do cs var commanBuffer = new EntityCommanBuffer(Allocator.TempJob); Entities .WithStructralChanges() .ForEach(() { commandBuffer.SomthingSomething(); }).Run() commandBuffer.Playback(EntityManager); commandBuffer.Dispose()
add .WithStructralChanges to lambda
You can also use entity command buffer later on when you get more experience
https://docs.unity3d.com/Packages/com.unity.entities@0.6/manual/entity_command_buffer.html
i think this thing with commandbuffer is equivalent to PostUpdateCommands ๐ค
Yeah its kinda of a pain, you have to explicitly say what you are intending to do by making those methods, WithStructralChanges if you want to use entity manager, WithParallelDisabled for parallel writing, WithReadOnly for read only variables etc..
but it gets much easier once you get used to it
oh, with commandbuffer you don't need .WithStructralChanges() i guess๐ค
and you can use Burst maybe?๐คทโโ๏ธ
but not with shared components i guess๐
ahah
Using the Entity manager is faster than a command buffer. The command buffer just uses the entity manager indirectly so there's no point unless you're doing a lot of other work in the job that you would need to be bursted
yeah but still, you are not creating a sync point, shouldnt that be more beneficial in the long run ?
there is sync point at playback
Well the sync point is the playback
its pretty unfortunate, i continually hope that they will burst the playback portion of the ECB at some point soon.
I mean.. if you dont use entity manager and use command buffer instead, you will be avoiding sync point ?
or rather, command buffer will be using default sync point, so that way you would avoid extra sync point
the command buffer will be using the 'barrier system's' sync point effectively
and the playbacks are executed there
I've got a problem I'm trying to see how I can apply Burst to - is it acceptable to ask that here, or is this more for API q's?
yeah please do ask CodePoke
Burst is in in DOTS๐
@opaque ledge yeah a sync point is only a problem if its interrupting jobs, if all your sync point code happens together than its fine.
So I outlined the problem here: https://gist.github.com/gjroelofs/07bb300a43b2076c89c493f9476654f0
(Too large to post in here)
Essentially it's how to apply Burst to grid datastructures, and where to draw the line.
if you make it line limit to 80 it would be much better to read, so we wont have to horizontally scroll
With the grid datastructure both being a spatial datastructure and a cache for int-driven bitsets of various gameplay characteristics
i think, even if you ignore ecs completely, using burst over c# for querying grid structures (e.g collect node flags @ radius around xyz or pathfinding) will be at least twice as fast.
@opaque ledge Updated, although I'd imagine that you'd normally resolve that client side ๐
today I found out that GameObjectConversionUtility works only on prefabs
I am thinking about another solution to solve my problem, which is deleting empty entities. For Empty entities I mean, in my case, Entities that have ONLY the translation, rotation and localtworld components
I guess the simplest solution would be to delete these entities after they are created, is there a way to make a query of entities that have ONLY those components?
@mint iron There'd be a tipping point surely, no? As in, every Job has overhead and if I back everything with native arrays a small (3x3) grid comparison would probably not save me time, but cost me on Job overhead?
@scarlet inlet i guess you can play with writing groups๐ค
yeah? No clue what they are I have just read about them once and didn't understand the use case
@gusty comet mean just that if you're doing the same thing in c# vs hpc# hpc wins (as long as the size of work is large enough per call - obviously setting a single property is or something trivial will be slower in hpc because of the extra jumps to get into the burst code); simply because one has an IL layer and the other doesn't. You could do it with a manually allocated arrays and burst with touch points into unity ecs if nessesary or you could try to structure your data into unity ecs properly and but it gets difficult to sidestep all the overheads and potential performance hurdles.
there is good video with Mike Acton explaining them, wait a little bit i will find it๐
Mike Acton works in Unity ?
he is the main guy behind DOTS, i think๐ค
oh, i thought main guy was Joachim
Yea he used to work at Insomniac Games
I never understood what he does, but yeah he should be one of the main guy in SF
working on dots
@mint iron Can in someway have arrays which have little/no access overhead from both IL and hpc#? I.e. that way I can decide based on size whether I'll use one over the other.
To my understanding HPC# use would always go through the Jobs system and therefore have way more overhead - or overhead in the point where you transition.
@scarlet inlet ive used GameObjectConversionUtility for scene objects without problem
@safe lintel maybe, but in the way I have done it, it goes through DeclareReferencedPrefab
I don't know why, it's a GameObjectConversionMappingSystem.cs method
it's called by DeclareReferencedObjects(conversionWorld, conversion.MappingSystem);
that is called by the method Convert()
that is the main one
@gusty comet you can call pure burst functions without anything to do with job scheduling. On my machine from testing if the work should take more than about 0.0040 ms is the breakpoint. a normal c# property access taking 0.0002, the fastest a burst method could run at 0.0004-0.0009 (if it was previously just run, otherwise 0.0040 uncached). In reality its not that much work, doing any sort of calculation in a loop probably breaks the threshold.
yeah in my experience with DeclareReferencedPrefabs - i've only been able to do it on asset project files (scriptable objects, prefabs)
i think im ignorant on what the problem is
@mint iron That... sounds weird to me.. HPC# is native compiled, it's managed interopping then into native - there has to be some overhead.
But alright, I'll take that into account, thanks!
But essentially you're saying then that it's best to do the whole backing datastructure natively.
yeah i think so; it will also be native obviously if you put it into Unity ECS somehow as components etc, but then you have other issues to contend with in exchange for convenience. Here's some comparisons i did about a year ago: https://github.com/jeffvella/UnityBurstFunctions but if i would do it again now i think they've fixed all the bugs with declaring burst methods and calling them directly - since they're doign exactly that in the EntityManager for many of the key methods . See also https://jacksondunstan.com/articles/5211
@safe lintel I think it's something to do with the IDeclareReferencedPrefabs pattern, when this is used, prefabs must be used. In other cases I think you are right
@scarlet inlet yeah prefabs must be used, unity accepted a bug of mine a few weeks ago that was basically "unity throws confusing exception when non-prefab is used"
How to reproduce: 1. Open 'SampleScene' from "NonPrefabWarning.zip" 2. In Hierarchy select 'PrefabConstructor' 3. Drag 'Sphere' or a...
I don't understand why this limitation honestly
especially since you could probably just create an entity, load it with components and add the prefab tag.
exactly what I wanted to do ๐
@mint iron So another aspect is that I access the grid based on arbitrary lengths (could be 1x1x1). It's hard to pour that mould into a Vector3/4.
If I use a NativeArray<float>, is there anyway I can check whether SIMD/vectorization is kicking in properly?
if you can read assembly you can check in the jobs inspector
there is good video with Mike Acton explaining them, wait a little bit i will find it๐
@warped trail
Huh, this talk is really interesting. It finally explains why the insane transform system page in the manual is the way it is
Yeah it is, but it was kinda boring ๐
speaking of great videos, if you can get through it, this one by Scott Meyers has exceptional content on caches/cachelines/false sharing etc https://youtu.be/WDIkqP4JbkE?t=1630
code::dive conference 2014 - Nokia Wrocลaw
http://codedive.pl/
I have to admit I still have no idea what write groups are for after watching it, I'm going to rewatch it I think, hahah
๐
As a a "casual" developer should i really care about cpu cachelines and stuff ? i mean i know how they work, why they matter etc. but in the context of ECS, i dont think there is a way for me to use cacheline in a efficient manner, no ?
i got the same feeling from dod book, i mean sure great i can understand the reasoning, but i have trouble make that knowledge into ECS context
no you would't need to know know it unless you're trying to write your own low level systems or containers.
personally i'd heard a lot of stuff about cachelines, like the mike acton talks etc but its always glossed over, its just "cacheslines are the reason why we do xyz" - if you want to actually know wtf is going on its not all that easy to find the info.
Yeah i can understand that.
i am still going to watch it tho ๐ ๐
thanks for sharing
@zenith wyvern You have entity with components A and B. B is in A's writegroup. You have EntityQuery with All = component<A>. This entity will not be in this query, unless you explicitly include B.๐ง
Ahh, that's if you include WriteGroupFilter in the query, gotcha. I'm still not clear on why you would want that though, what he benefit is
Oh there is actually a nice manual page for it, I have some reading to do
Same here - looks like write groups are something I might want to be explicit in my UI system...
cool thing, i use it to exclude my interpolated entities from default TransformSystem๐
I think I get it, it lets you force a system to ignore an entity it would otherwise process by adding your own component to it. Almost like overriding the original system. Interesting
i think this is how prefab and disabled components works under the hood๐ค
Right that would make sense
So I think something like that would be interesting for a text generating system - you can imagine replacing a single character and updating the mesh, instead of tagging/untagging an entity to rebuild the mesh - you can simply force the vertex buffer to update its values ๐ค
lol i guess so ๐
for a quick more detailed explanation:
memory is very fucking slow
so cpus cache it at different levels
whenever you try to load some memory adress, it will search in this caches first, and if its not there, it will go back to RAM (slow), and copy it to the caches
the data will stay in the caches for a while, until it gets overriden by other data
so what you need to try to do is:
- Have predecible memory access patterns (array), as the cpu sees you are accesing stuff in an array, and will preload memory
- Whenever you load memory, make sure that you use as much of its "nearby stuff" as possible
memory will allways load 64 bytes of stuff, 12 floats, whenever you load anything. Mostly useful when desigining your structs. If you allways use some variables together, then put them together in your struct
๐
there are many other things on the whole "data oriented desing"
just read the book
Sooooo, you cannot use NativeList for TempJob stuff ? .WithDeallocateOnJobCompletion doesnt seem to work on it
Use Dispose(jobHandle)
ah ok thanks, i didnt know that exist
@vagrant surge ram is slow AF
keep in mind the L3 cache is like 30something mb on normal cpus
and 200 mbs on threadripper cuz amd are lunatics
a lot of stuff will be at least on L3 on normal game loops
unless you have absurd counts of objects
woah, I didn't expect ryzens to have that much cache
I thought 8mb was the norm for L3 cache
I am assuming Unity.Physics use random solvers since collision trajectories are not aligned to the plane even though i align the objects in that plane
Do you think these random seeds are acquired from system time or positions of objects?
If it's not something like positions of the objects, i'll need to sync this time to improve determinism
Why is my Raycast not pointing down when I move? Been looking at this for hours but I don't see my mistake:
Entities.WithAll<PlayerTag>().ForEach((in LocalToWorld localToWorld) =>
{
var fromPosition = localToWorld.Position;
var toPosition = fromPosition - new float3(0, 1.1f, 0);
Raycast(fromPosition, toPosition);
}).WithoutBurst().Run();
@formal scaffold
try this
var toPosition = - new float3(0, 1.1f, 0)
I saw in rollaball with ecs tutorial that toPosition is i think as direction
naming is misleading i believe
(i might be wrong though)
WOW ๐ Makes no sense to me since it's called toPosition and not relativePosition ๐ง but it works thanks alot
oh yeah, great
@formal scaffold var fromPosition = localToWorld.Position;
is this how you get world position?
Yeah or translation.Value which might be better since it only has the position stored. But I thought maybe I need LocalToWorld which I don't
It sounded to me like it would maybe store a local position since world pos is already stored in translation
nut i dont know
maybe translation component contains the local pos
i don't know anything
it depends, LocalToWorld gives you forward, right and up directions relative to entity, the code above raycasts to 'down' relative to world and not relative to entity
I am assuming Unity.Physics use random solvers since collision trajectories are not aligned to the plane even though i initially aligned the objects in that plane
Do you think these random seeds are acquired from system time? or positions of objects?
If it's not something like positions of the objects, i'll need to sync this time to improve determinism
@round summit
anyone know about this?
i don't understand "trajectories are not aligned to the plane" part๐ค
2 boxes, first one dynamic, second one kinematic
i drop first one and initially, it's z position is 0
second one also is z = 0
after collision dynamic body has velocity in z direction
@warped trail
And thats why assume there is a random force added to the collision forces (or something like that)
sorry, still don't get it๐
oh
cube should've only rotated in z axis i mean
and its position should've stayed at z = 0 plane
i don't experience this behavior ๐ค
Outcome is much different if i move them in z plane keeping their z positions same
cube goes somewhere else, collision call counts are different because it's not bouncing the same way
@warped trail what do you mean by that?
is this not how your cubes are behaving?
no
my cubes maintain their z position
are you sure your cube don't have any rotation?
yes
only keep their z position same and their rotations uniform then try? @warped trail
also move them in z
keeping the z same
how do you make this gif?
what happens if you lift the cube higher
hmm, mine is random even with small distance
hmm
Maybe this is a dumb suggestion but I think right now physics is semi-tied to framerate, it seems like @round summit example is running a lot slower (could just be gif compression), could that be why?
this is at 1/24 timestep
@zenith wyvern i press space to run the frames, i was handling frame update myself
i am trying now with clean project
oh, try to disable jobdebugger and leak detection
in my project physics is very unstable with those thing turned on๐ค
I tried it on a clean project
As soon as the collision happens, i see velocity on z axis in entity debugger
But it looks like just your gifs
looks as if z = 0 with no x,y rotation
look at linear.z
in PhysicsVelocity
@warped trail
this is top down view
up in screen is z axis in unity
this is clean project
i have this too
i am very confused
but same input = same result, determinism ๐ ๐
yeah
it is the same with havok
I can understand it may generate random forces to make it look more natural
But why is it not affecting position after it has affected the velocity?
I'm too stupid to answer that question. I think source code is there and you can look at it ๐
I disabled burst compilation here
Now the collision looks like yours in standalone
but in scene its the same as my first gif
with my weird time step code
This file popped up after i built the first standalone, EnableBurstCompilation was true initially
but in the clean projects standalone, burst compilation is on and it still looks right
Any info on the uint CollidesWith from Unity.Physics? I know that ~0u means all 1's, so all Layers. But I want to exclude the player. How do I do that?
oh, try to disable jobdebugger and leak detection
in my project physics is very unstable with those thing turned on๐ค
@warped trail
Where are these settings may i ask?
This is Layer 0: 0000u
This is Layer 1: 0010u
This is Layer 2: 0100u
This is Layer 3, 2, and 1: 1110u
Kinda cool had to learn this in School and never thought I'd need it ๐
Anything to watch out for when migrating from JobComponentSystem to SystemBase?
Hmm I'd say inputDeps is now Dependency - which is just a property in SystemBase
If you're already familiar with JCS, the "HelloCube" samples have all been updated with SystemBase, should tell you everything you need to know
Okay thanks both.
hm, anyone else having issues in Unity.Entities.PerformanceTests after updating to their 0.6 version?
In particular I get that this does no longer exist:
SampleGroupDefinition
I used it for a couple of simple tests in 0.6, I never had to use that keyword I guess
[Test,Performance]
public void EndSimBufferRemove()
{
Entity e = m_Manager.CreateEntity();
var endSim = World.GetOrCreateSystem<EndSimulationEntityCommandBufferSystem>();
Measure.Method(() =>
{
var b = endSim.CreateCommandBuffer();
b.RemoveComponent<IntComponent>(e);
endSim.Update();
})
.WarmupCount(20)
.MeasurementCount(9)
.IterationsPerMeasurement(10000)
.SetUp(() =>
{
m_Manager.AddComponent<IntComponent>(e);
})
.Run();
}
I'm only getting warnings of the two test dlls not existing ever since moving to 0.6 ๐
I dunno if it's Unity Physics package issue or something else, but there's been very little reason for me to test without the physics package so can't tell for sure
if people remember my issues with profiler getting unusable with high core count cpu... turned out there's a command-line parameter for limiting the worker threads as well which also caps the total worker amount in the editor
this is way better now:
if you only limit the workercount from c# script, it could still place those 3 workers to random worker threads in the editor, so could have gotten worker 10, worker 20 and worker 23 and then had to scroll down to actually see them - hiding the topmost data at the same time
what is nice is that Unity Hub lets you pass those parameters automatically if you launch the project via hub:
does hybrid renderer crash unity for everyone? i created a basic plane and cube scene with unity physics, installed hybrid renderer, played the scene and unity crashed
these things can be quite crash happy
if it does it every time, then there's something wrong
I'd also make sure you are using these on supported engine versions
unity 2019.3 is supported, isn't it
if it's released version and not beta or RC, then yes
oh ok yeah i used 2019.3.2f1
but next hybrid renderer will not support 19.3 ๐
that's true as well
or well, I dunno if they've said it's not going to be supported but definitely will at least have functionality that only works on 2020
why do platform packages not have hybrid renderer as their dependency
you don't need hybrid renderer for all things
like, I use platform package to get the build tools but I don't necessarily want hybrid rendering if I build for hybrid conf
in other words, you can still use new build tools along with old renderer
ok imma restrain from dots for now cuz i dont understand it at all lol
lets hope all the juicy DOTS news will not be canceled because of the GDC thing
yeah hope so as well
I'm fairly confident we'll still get some updates on it, but it's quite likely that they compact the thing now
We will no longer have a physical presence with a booth, but will instead showcase the great GDC content weโve been working towards online. Expect more details in the coming weeks.
I wonโt be attending GDC. Weโll figure out how to share the talk and work we were hoping to present. https://t.co/c1wNtt1OZv
118
oh, there will be talk from Mike Acton๐
this was the talk that was supposed to be there: https://schedule.gdconf.com/session/so-you-want-to-make-an-entity-component-system/869219
Programmers that haven't yet built an ECS, or fix their existing solution, or throw away what they have and fix things this time.```
throw away what they have and fix things this time.
typical Acton
haha
Unity.Entities.PerformanceTests\Diff\EntityDifferPerformanceTests.cs(31,21): error CS1061: 'MethodMeasurement' does not contain a definition for 'Definition'
com.unity.entities@0.6.0-preview.24\
This is mildly frustrating
i think you need to downgrade performance testing package to 1.3.x
if you are using 2.x
ah, that might be it then, thank you, I'll try that
ajajaj, that was it. Thank you!
also ๐
I do wonder if they have anything else but new Hybrid Renderer to show
because of the Unite's there's usually not that big major things announced on GDC, last year it was mostly presenting what they showed on previous Unite already, like MegaCity
they just updated https://github.com/Unity-Technologies/DOTSSample
but it was just a package version update: https://github.com/Unity-Technologies/DOTSSample/commit/fb4a669371aa9a15d7f461f478690267d85bf8f7
weird that they upgraded to HDRP 7.1.8 instead of 7.2.1
i wonder if GDC will be cancelled, MS, Unity, EPIC, Sony, lots have pulled out.
EA and Facebook/Oculus as well
if they still keep the event, it probably boils down on not having to refund the prepaid tickets :p
[UpdateAfter(typeof(BuildPhysicsWorld))]
[UpdateBefore(typeof(StepPhysicsWorld))]
[UpdateBefore(typeof(ExportPhysicsWorld))]
[AlwaysSynchronizeSystem]
public class AddForcesSystem : JobComponentSystem
{
private BuildPhysicsWorld buildPhysicsWorld;
private StepPhysicsWorld stepPhysicsWorld;
protected override void OnCreate()
{
buildPhysicsWorld = World.GetOrCreateSystem<BuildPhysicsWorld>();
stepPhysicsWorld = World.GetOrCreateSystem<StepPhysicsWorld>();
}
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
EntityCommandBuffer commandBuffer = new EntityCommandBuffer(Allocator.TempJob);
Entities.WithoutBurst().ForEach((Entity entity, ref PhysicsVelocity physicsVelocity, ref AddedForces addedForces) =>
{
PhysicsWorld physicsWorld = buildPhysicsWorld.PhysicsWorld;
int rigidbodyIndex = physicsWorld.GetRigidBodyIndex(entity);
Debug.Log("adding force: " + addedForces.addedForce + ", " + addedForces.addedTorque);
PhysicsWorldExtensions.ApplyLinearImpulse(physicsWorld, rigidbodyIndex, addedForces.addedForce);
PhysicsWorldExtensions.ApplyAngularImpulse(physicsWorld, rigidbodyIndex, addedForces.addedTorque);
addedForces.addedForce = Vector3.zero;
addedForces.addedTorque = Vector3.zero;
commandBuffer.RemoveComponent<AddedForces>(entity); // this line *
}).Run();
commandBuffer.Playback(EntityManager);
commandBuffer.Dispose();
return default;
}
}
I remove " this line * " and it works correctly
If i keep it, all the entities are applied force somehow, the one's i never add the AddedForcesComponent
Why is this?
If i remove "ref PhysicsVelocity physicsVelocity" parameter (also "this line * "), i don't see effects of the force on any object
(I only add the AddedForces component to rigidbodies)
.
This is what i do in monobehaviour:
public void AddForce(Vector3 force)
{
AddedForces addF = new AddedForces();
if (entityManager.HasComponent<AddedForces>(entity))
{
addF = entityManager.GetComponentData<AddedForces>(entity);
}
else
{
entityManager.AddComponentData(entity, addF);
}
addF.addedForce += force;
entityManager.SetComponentData(entity, addF);
}
I wanted to create something like a tag datacomponent
I would add the tag in mono, force would get applied in system and tag would be destroyed
.
The line just after the dubug.log gets a previously scheduled job Jobs:CreateMotions writes to the NativeArray... error
try moving this before your lambdacs PhysicsWorld physicsWorld = buildPhysicsWorld.PhysicsWorld;
That doesn't change the result
do you really need to apply those forces via physicsworld?๐ค
why don't you just apply those forces to PhysicsVelocity before BuildPhysicsWorld?
i guess i'll try a little longer and then do that
Yeah i did it the way you said it @warped trail
I won't touch PhysicsWorldExtensions ever again
I dont suppose anyone knows how I change the colour of an entity?
this does not seem to be working csharp ecb.AddComponent(entity, new MaterialColor { Value = new float4(x / gridresolve,y / gridresolve,z / gridresolve,1) });
@pliant pike do setcomponentdata* instead?
no it just says the component has not been added
Hm, from the docs it kind of seems like you have to change the material from the RenderMesh SharedComponent
That would of course change the color for all entities with that archetype
RenderMesh.Material.Color
@pliant pike
yeah that's true I want an individual color for each
do getcomponentdata to get Rendermesh
But that would change everything for that archetype no?
so how do I change to non sharedcomponent ๐ค
i have no idea, it's not adding anything extra though i believe so why would it change archetype
I agree that MaterialColor should do the trick
A sort of hacky way to do it is to just not have them use the same shared RenderMesh, but then you have to set that up manually..
materialcolor isnt working for the whole of them so I don't know what I'm doing wrong
entityManager.GetComponentData<RenderMesh>(entity)
@pliant pike you do this right?
but watch out for structs though
watch out for pass-by-value stuff i mean
nope I'm just instantiating a prefab so I cant getcomponentdata
in IConvertGameObjectToEntity class
if your Convert method
dstManager.SetComponentData
@pliant pike
are you using HDRP and thishttps://forum.unity.com/threads/per-instance-material-params-support-in-entities-0-2.782207 ?
I'm just using the hybridrenderer
urp?
I think just the built-in renderer ๐
oh, then you can only change sharedcomponentdata๐คทโโ๏ธ
yeah just the standard Rendermesh thingy I don't know ๐
Can I check if 2 colliders hit eachother even if none of them is a trigger?
it doesn't really matter anyway I only needed the colour change for debug purposes and to see things better
@formal scaffold I have code for that
I watched Codemonkey's tutorial and it looks simple enough
you can make component like ChangeColor and than make some system which will change RenderMesh on main thread
The thing is also, when you access the material in GameObject world, Unity actually instantiates a new Material at runtime, which is a copy of the sharedMaterial
So you could implement a similar behavior
if you change material on RenderMesh you will move this entity to different chunk
well I checked the forum and the above code seemed the most basic way to do it so I dont know ๐คทโโ๏ธ
and i believe you can do this only on main thread๐ค
maybe why I was getting errors
var renderMesh = EntityManager.GetSharedComponentData<RenderMesh>(entity);
renderMesh .material = material;
EntityManager.SetSharedComponent<RenderMesh>(entity, renderMesh);``` this is basically the way you do it๐ค
as i said before, you can create tag component for that๐
IWantChangeColorOfThisEntityInTheBeginingOfNextFrameComponentTag ๐
as in ChangeColorTag? ^^
and you can create some tags for prefab entities, like ThisEntityWithRedMaterial, then query for this entity and get material from it and apply it to your desired entity
hacky af, but it simple and it works๐
@pliant pike https://github.com/Unity-Technologies/ScriptableRenderPipeline/pull/5963 Hopefully this will be added soon, that might fix your problem
yeah, we need much simpler straightforward ways of doing things
@pliant pike For now, I'd recommend doing something similar to what I described earlier, by making a system that will instantiate a new material if you want to change the color.
And thus also changing the MeshRenderer shared component
According to Jaochim we should have some hybrid renderer news within a couple weeks
Yeah, as you can see from the PR I posted, V2 seems to be around the corner
But also seems to be for SRP only, so you need either URP or HDRP
Or custom of course
re hybrid renderer, I guess around gdc time - Sebastian on the forums also recently said "I will give you release time estimate in the following weeks." also "Current profiling results are highly positive." ๐ค
i was greedily hoping they would just release their gdc stuff early if theyre skipping it ๐
What do you guys think of what they are going to improve anyway ? core entities seems solid now, maybe some physics improvements ? But does anyone expect a "revolutionary" update to ECS or DOTS in general ?
For anyone else looking to run integration tests that involve Netcode ghosts, we need to invoke the conversion process for Ghosts by applying GameObjectConversionUtility.ConvertGameObjectHierarchy to all root objects in the scene holding the GhostCollectionAuthoringComponent.
i guess im not expecting anything revolutionary, but support for lightmaps would make quite a big difference for my own uses
I think they're solidifying the ecs core well enough but just need to do some general widening of the support for dots integration. How is UI supposed to work and how will dots integrate with runtime UIElements? The new Audio package last i tried was shall we say, very very experimental. Physics is shaky. Sub-scenes are not that great right now imo. URP/HybridRenderer has been buggy to the point everyone is writing their own rendering systems. The input system has no integration with dots. They want the editor to be able to used to create games, so all of the other areas need to be addressed for that to happen or we end up just back coding in notepad like we are now.
๐
so it probably will be more about getting existing systems integrated to DOTS rather than introducing new stuff to ECS in general
yeah, and maybe going more towards the graph based stuff / blueprints with the dots visual scripting UI. Im curious to see how that side pans out.
whats the alternative for a visual scripting ui?
there are many for Monobehaviour, none for ECS i think
i mean, i doubt anyone would bother to work on it tbh
given its preview
wasnt unity working on the visual scripting dots package?
like it was a very early preview?
yeah they are, latest is "6th drop", they stated that 7th drop will come next month, probably near GDC time
ah - I never took a look at it yet haha
yeah it gave me errors so i didnt want to deal with it ๐
Also, this ECS made me learn LOTs about Structs, i am scared
Well how much is there to learn about structs? ๐ค It's basically just a value-type container of more value-types
https://twitter.com/SebAaltonen/status/1233459427057061890 - think we can guess where
100k additions, wow
indeed.. ๐คจ
Something that large feels more likely to be engine related than ECS related, but who knows
I'm strongly assuming it's just the V2 hybrid renderer
Considering that it has SRP support
and considering Sebastian's the person that I quoted earlier talking about specifying hybrid renderer v2 release date soon..
Exactly
Exciting!
maybe they wrote some documentation
i hope they wrote some code examples in documentation
Hey,I want to make 2 Entities collide with each other and raise a CollisionEvent. When testing I found that I need a Physics Body attached to one Entity to make it work. But I don't want to do it with a Physics Body. Checked "Raises Collisions" in both Physics Shapes.
@formal scaffold The PhysicsBody is exactly what tells the physics system that an object can collide with another object
Otherwise it's thought of as static
you can change it to Kinematic if you want to move it with only translation and not with physics
But then you don't get collisions ๐
Hmm really? Only with a body? Feels like alot of useless stuff I don't need. But yeah Kinematic works
Well how else is the physics system supposed to know that it should iterate on that?
ah yeah sorry, i only used trigger so far ๐
I don't know I have two shapes that are probably defined somehow. Shouldn't a shape know if something is hitting it?
you should have a shape too ๐ค
No, a shape will only tell the physics system about the, well, shape of the collider
No kinematic raises collisions aswell @opaque ledge
at least for me it did ๐ค lemme check real quick
But the body will tell the physics system how it should collide with other colliders
ah good then, well it makes sense, kinematic means this particular entity wont be affected by physics
Weird, last I tried with kinematic it didn't raise collisions
Looking at the Physics sample character controller, they kind of write their own collision stuff
Well that means every NPC and every creature would need a body. Or otherwise every Object and Ground would need a body .... thats just for collision
Oh yeah, definitely
It's wierd because I can Raycast and hit anything without a body. What do you think about this post?
https://forum.unity.com/threads/how-to-detect-collisions-with-unity-physics.743534/
If you want them to collide with the environment (aka static colliders), you need some dynamic collider (aka physics body)
This guy seems to not use a body
It's the same with the old physics
You needed a rigidbody and collider for moving objects
Or well, you didn't need it, but it was really bad for performance to move colliders without a rigidbody, or moving the transform at least
Why is that? Don't you just add some floats?
No I mean why is moving the transform bad for performance? Don't you juts add some floats for the direction and you are done? Thats what I do
That's very bad, because then the physics have to rebuild the static collider, and it does a lot of optimizations when only dealing with static colliders
But moving it means having to rebuild it, which is very expensive
Compared to moving a dynamic rigidbody. Because then the physics system knows to not build it as a static collider, and skip that expensive step
why aren't my ECS converted entities being batched? in regular, I see in my stats "1000 draw calls, 1000 saved by batching". in ECS "2000 draw calls, 0 saved by batching"
But then of course actually detecting collision will be a bit more expensive. But it's a lot less than building the actual static collider
@odd ridge I don't really know the specifics, but I'm guessing that it's just because the Hybrid Renderer is not very optimized. It's just something that works with the bare necessities
But you're probably in luck https://twitter.com/SebAaltonen/status/1233459427057061890 Hybrid Renderer V2 seems to be right around the corner
oh cool cool
@bright sentinel what about skipping any Physics Shapes and just using Raycasts ๐ค currently I use one cast down to check for the ground and I wanted to make a sphereCast to check for grounding which let's me use the ray down to set my Y position.
A full raycast system can also handle slopes very well that's why I'm using it atm.
@formal scaffold You still need physics shapes for that though, or the raycasts wont be able to hit anything ๐ But THEN you don't need any physics body
Hmm, what if all physics shapes are static objects and only the Player and the NPC's cast rays ๐ At least NPC's and the Player wil all have the same height for now so setting up rays for one means having it for all, so one system should be enough
Yes, that's definitely a possibility. I remember I once saw a third-person game where you controlled an ant that could crawl on trees and stuff. This of course required very specific control over each leg and how it interacts with the environment. It was all done with a LOT of raycasts
Like 50+ just for that single character
So definitely a possibility, but not sure why you're so against using a PhysicsBody..
I would use a SphereCast for collision and about 4 Rays
1 Ray for slopes
1 Ray for higher slopes like stairs
1 Ray for jumping
1 Ray for the ground
Hmm I tried it and couldn't get my character to stop sliding across the screen. I guess slopes and collision detection is trivial then ๐ค
I mean, it can definitely be done with physics body, and is a better solution in the long run
there is distance query ๐ค
I'd recommend that you check the physics sample with their character controller, they have done it there with slopes
This one ? EntityComponentSystemSamples/UnityPhysicsSamples/
Yes, specifically this one: https://github.com/Unity-Technologies/EntityComponentSystemSamples/tree/master/UnityPhysicsSamples/Assets/Demos/6. Use Cases/CharacterController
Not sure if it's the same one but theres also a physics based character controller in the Dots Network sample
Currently Physics is running on Update right? Unless I use a CusomBootstrap to change that, why is it like this anyways? I remember reading a post about it a while ago but back then It didn't make much sense to me since I was just starting out
@formal scaffold Yeah, it is dependant on the framerate for some reason. I'm pretty sure they're working on it though
// internal for now, until we figure out proper API``` from ComponentSystemGroup.cs๐
fixed rate support is like my least expected change for upcoming gdc related announcements/changes ๐
I mean, it seems like it's pretty essential for any physics system for games, no?
just making SimulationSystemGroup update in fixed steps not enough. You will encounter a lot of problems that way. Like movement will not be smooth, Transform system also updates in simulationsystemgroup๐
In this day and age with devices that can be anywhere from 10-300 FPS
lots of workarounds floating on the forums, its been like that forever
Yeah, it's just weird
they moved simulationsystemgroup to update almost a year ago๐
Has anyone played around with the IL post processor yet?
I've been adding ProfileMarkers around the core bits of my code to get some better performance data. I was wondering if it would be interesting to have the IL processor generate the code for this in the cases where I want to profile an entire function.
@bright sentinel The character controller in the Demo is quite nice apart from the camera movement. But the code is a mess sadly. I found where they handle moving around and it makes sense. How would I go about freezing rotaiton along the X and Z Axis then? This is not very inviting as a starting point ๐
@formal scaffold If you look at some of the other demos in there, they have some axis locking with joints, you can look at those
And I agree, the code is a big mess.
As for the camera, that's not good, but that's not really the point of this sample ๐
Yeah ๐ well and running down slopes makes the character fly sometimes, which makes sense but disables movement for a slight second which is more annoying than realistic in a game I feel.
@formal scaffold Yes but again, the point isn't to make an amazing character controller. The point is mostly just to show how you can achieve the basics, and how you can interact with the API. Then you can expand on it yourself
You are right thanks alot for your help ๐ It's worth looking into
Hello, i am writing server. i want index shooted Bullets for each of players in jobs. Whos can help me?
GetHashCode has an accessable error at burst compile.
ok thanks guys i found a solution
Is there a tool that makes entity prefabs easily accessible from code to instantiate. So I could just reference those by name when I want to instantiate new entity prefab
Drag and dropping to a window and it would generate the script or something
@twin raven There's the resources folder, but you'd still have to convert those to entities at the start of the game like you would any other prefab
But I don't think there's a premade tool for that
could try looking into addressables
Does anyone have a better Code example of how to lock the rotation of a Physics Body than the one supplied in the UnityPhysicsSamples? Any simplified example would suffice, I just don't understand what they do there.
Entity spawnedBullet = commandBuffer.Instantiate(entityInQueryIndex, bullet);
commandBuffer.SetComponent(entityInQueryIndex, spawnedBullet, _pos);
commandBuffer.SetComponent(entityInQueryIndex, spawnedBullet, new DirectionData { Value = direction });
Is this Unity bug? I am spawning bullets from Entities.ForEach with EndSimulationEntityCommandBufferSystem and for one frame the position is the default position. It feels like the commandbuffer sets position 1 frame after initializing.
@twin raven Can you show the whole code?
var positions = GetComponentDataFromEntity<Translation2D>();
var commandBuffer = commandBufferSystem.CreateCommandBuffer().ToConcurrent();
var bullet = bulletEntity;
return Entities.ForEach((int entityInQueryIndex, ref GunComponent gunComponent, in DynamicBuffer<ActiveTarget> _target, in Translation2D _pos) =>
{
if (_target.Length > 0)
{
var targetPos = positions[_target[0].Target];
var direction = targetPos.Value - _pos.Value;
Entity spawnedBullet = commandBuffer.Instantiate(entityInQueryIndex, bullet);
commandBuffer.SetComponent(entityInQueryIndex, spawnedBullet, _pos);
commandBuffer.SetComponent(entityInQueryIndex, spawnedBullet, new DirectionData { Value = direction });
gunComponent = new GunComponent { Load = 0.2f };
}
}
}).WithReadOnly(positions).Schedule(inputDeps);
I don't think it's a Unity bug. The thing is that you're setting the Translation2D data in the EndSimulationGroup, but Unity's TRS systems will run before that, so the rendering systems won't know about the new position
What is TRS?
Translation, Rotation, Scale
It looks like you're using a custom position component so whatever system updates your entity positions needs to run after EndSim but before rendering.
Basically how ECS handles those things to feed to the rendering system
sark, yeah you are right, totally overlooked that
Isn't Translation2D just part of the Entities 2D package?
No its my custom
Ah then there's your real problem
๐คฆ๐ผโโ๏ธ yeah ๐
Alternatively you can run the buffer on BeginSim and update positions before you spawn
Yeah, that will be 1 frame later of course. If you really cannot live with that, you probably need to create your own ECB that runs right before the TRS system
alright thanks for the help ๐ I was totally blind to that as I have been using my own translation for quite some time now. I realize I might have had other problems because of this before. I can solve it now
I have a bunch of sphere entities and I want to destroy all of them at once, how would you do that?
thanks
I have a bunch of balls which I'm currently spawning with the hybrid conversion, but I would like to replace it all with pure dots to see how much performance I can get
one problem is I made a box prefab to contain those balls, but I don't know how I would spawn that box in pure without the visual editor part to make it
any hint?
@odd ridge i never tried that except for very simple entities, but you could create an entity and just add/set your components one by one, and i dont think creating an archetype would be necessary because archetype doesnt contain any values, just types of components.
Is there a specific reason why you dont want to use conversion ?
UnityException: ToString can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Hmmm, I wanted to print some collision information
I can print stuff, but it doesn't let me use .ToString i guess?
public void OnEntityCollision(SimpleECSCollision simpleECSCollision)
{
Debug.Log("other : " + simpleECSCollision.other);
}
Just trying to make my own easy collision system
Where this is called:
||```cs
struct CollisionJob : ICollisionEventsJob
{
public ComponentDataFromEntity<MonoReference> rbEntities;
public PhysicsWorld physicsWorld;
public void Execute(CollisionEvent collisionEvent)
{
Entity entityA = collisionEvent.Entities.EntityA;
Entity entityB = collisionEvent.Entities.EntityB;
if (rbEntities.HasComponent(entityA) && rbEntities.HasComponent(entityB))
{
int monoIdA = rbEntities[entityA].monoId;
SimpleECSRigidbody rigidbodyMonoA = SimpleECSRigidbody.idTable.GetObj(monoIdA);
int monoIdB = rbEntities[entityB].monoId;
SimpleECSRigidbody rigidbodyMonoB = SimpleECSRigidbody.idTable.GetObj(monoIdB);
CollisionEvent.Details details = collisionEvent.CalculateDetails(ref physicsWorld);
SimpleECSCollision collisionA = new SimpleECSCollision();
SimpleECSCollision collisionB = new SimpleECSCollision();
collisionA.other = rigidbodyMonoB;
collisionB.other = rigidbodyMonoA;
collisionA.normal = collisionEvent.Normal;
collisionB.normal = collisionEvent.Normal;
collisionA.impulse = details.EstimatedImpulse;
collisionB.impulse = details.EstimatedImpulse;
collisionA.point = details.AverageContactPointPosition;
collisionB.point = details.AverageContactPointPosition;
rigidbodyMonoA.OnEntityCollision(collisionA);
rigidbodyMonoB.OnEntityCollision(collisionB);
}
Debug.Log("collision");
}
}
.
.
System OnUpdate
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
var jh = new CollisionJob()
{
physicsWorld = m_BuildPhysicsWorldSystem.PhysicsWorld,
rbEntities = GetComponentDataFromEntity<MonoReference>()
}.Schedule(m_StepPhysicsWorldSystem.Simulation,
ref m_BuildPhysicsWorldSystem.PhysicsWorld, inputDeps);
jh.Complete();
return inputDeps;
}
If you are wrapping from job/burst to normal monobehavior i would tag them instead of calling their functions directly, so you can make sure that all your collision code is bursted etc
And call their stuff functions from the main thread later
ah, i see makes sense
i need to collect collisions in one system
and i need to call callbacks in another
which runs on main thread
and runs after collision callback tagging system
That's how i would approach it
I guess there's no way to make a collision events detecting system in main thread
So there's no other way other than tagging
@north bay What if multiple collisions occured in same frame though?
I don't think ecs will let me add multiple ComponentData tags on the entity?
dynamic buffers?
yes, i think i can work with dynamic buffers
I guess there's no way to make a collision events detecting system in main thread
@round summit Why is there no way to do that? Shouldn't the real question be why would you want to do that?
i assume i still cannot have any class references though right?
You don't work with any class references
Only the system that calls the callbacks has references
@north bay because physics collision callbacks are generated in parallel i think
no they are single threaded
you can use simple command buffer. not concurent one
my naรฏve approach would be store mb refs in some array and store index of that array in some component on corresponding entity, then in collision job i would spawn simple entity typeof(ComponentWithIndexToArray), then in some system i would just iterate over this simple entities and call something like arrayOfRefs[ComponentWithIndexToArray.inex].OnCollisionEnter()
hmmm, command buffers, right
yeah i get it
i'll generate and collect all info in command buffer in the collision trigger jobs
when that system is done, i use the command buffer on another system to iterate and call the callbacks in my monobehaviours
You don't use the command buffer directly on the other system but the entities + stuff you modify with it
im creating this eventEntities and dealing with them in the next frame๐
I think i'll just store the generated
public struct SimpleECSCollision
{
public Vector3 point;
public Vector3 normal;
public int selfId;
public int otherId;
public float impulse;
}
In some list and access that list in next system
Can i not simply do that?
or i need to create an entity for each SimpleECSCollision?
Make that struct an IBufferElementData
Than you can create DynamicBuffers with this at it's type
Can i not simply share data between systems without creating extra ComponentData or Entities?
If you are using DynamicBuffers to store the collisions you are not going to create any extra entities or component datas, all you are doing is attaching a buffer to every entity that listens for collision events
@round summit its highly common to have some sort of "singletons" that are IN the ecs, but instead of being individual entities, its more like a chunk of data, like a entire octree
sadly unity ECS still doesnt have native support for singletons of this sort....
so yeah, you would have a native-array of those collision events stored in some singleton
I think NativeList is the only option to store data that can be accessed by other systems
and store it in system
I'm trying dynamic buffers now, i'll see how it goes
yes, has to be those native structures, no normal C# stuff
dynamic buffers arent really made for that, but they would work
i find weird that unity hasnt added a proper way to do this sort of singleton entities
singleton systems you mean?
ah i see yeah
or an event bus of some sort
some systems write to this singleton, others read from it
if i had something like that i'd store the callision callback infos in there
some guys in the forum implemented it themselves
so basically just some abstraction but it just stores an actual entity with the data
Is this supposed to be something like this:
public struct CollisionCallbacks : IBufferElementData
{
public DynamicBuffer<SimpleECSPreCollision> Value;
}
public struct SimpleECSPreCollision
{
public Vector3 point;
public Vector3 normal;
public int selfId;
public int otherId;
public float impulse;
}
I access this and add my elements in .Value
or like this:
public struct CollisionCallback : IBufferElementData
{
public Vector3 point;
public Vector3 normal;
public int selfId;
public int otherId;
public float impulse;
}
And i do commandBuffer.AddBuffer<CollisionCallbacks>(entityA, collisionCallback)
and these will stack?
the first, i think
public BufferFromEntity<CollisionCallbacks> collisionCallbackEntities;
But i can't get anything this way
collisionCallbackEntities.GetBuffer.Get
@vagrant surge
I can only check if buffer exists on an entity or not
you are doing it wrong ๐
I cant access .Value and add my new structs
public struct SimpleECSPreCollision : IBufferElementData
{
public Vector3 point;
public Vector3 normal;
public int selfId;
public int otherId;
public float impulse;
}```
@warped trail If i do
commandBuffer.AddBuffer<SimpleECSPreCollision >(entityA, collisionInfo);
Will these components stack then?
So it's pretty much the second thing i said above?
yes they will stack
oh, thats nice
but i guess you have to clean them every update๐ค
ill have a system that iterates over these components and delete them
that system will run after the system i'm moking now is done
all these systems will be in SimulationSystemGroup so it will be fine i believe
Unity Physics: how do I constrain a rigidbody movement on the XZ plane?
@torpid lintel If you look in the physics samples, there is an example of them using joints to do that, I recommend you look at how they do it
@torpid lintel Or add a ComponentData for it
Iterate over that and set y positions and y velocities
In a system
@bright sentinel oh thanks. Do you mean the samples project on GitHub or an example in the docs?
The samples project ๐
Gotcha! Thanks a lot โบ๏ธ
I ended up using native lists for my issue, seemed to be the easiest way
Magnitude on a vector3 returns the vector length right? Is there an equivalent in DOTS for a float3?
Thanks ๐ง
Hey, I am trying to build a movement system where my object has a destination and it moves towards it by accelerating to the max speed and deaccelerating when it comes close to the destination. Acceleration and deacceleration are represented by a force and not a distance. I want to avoid solving this with physics (this is how most examples I found do it in โnormalโ Unity).
My current system looks like this for a reference (I know that it is not close to the solution I want):
[BurstCompile]
private struct MoveDestinationJob : IJobForEach<Move, MoveAcceleration, MoveDestination, Translation>
{
private const float DistanceOffset = 0.5f;
public float DeltaTime;
public void Execute(ref Move move, [ReadOnly] ref MoveAcceleration moveAcceleration, [ReadOnly] ref MoveDestination moveDestination, [ReadOnly] ref Translation translation)
{
var distance = math.distance(moveDestination.Value, translation.Value);
var direction = math.normalize(moveDestination.Value - translation.Value);
if(!(distance < DistanceOffset))
{
//move.Value represents the currenty velocity
move.Value += direction * moveAcceleration.Acceleration * DeltaTime;
}
}
}
protected override JobHandle OnUpdate(JobHandle inputDependencies)
{
var job = new MoveDestinationJob
{
DeltaTime = Time.DeltaTime
};
return job.Schedule(this, inputDependencies);
}
My issue is the math for getting the velocity ... this is not my strength ๐
well, velocity is basically means, position changed divided by time.delta, sooo.. if you make a component like this:
public struct MoveVelocity : IComponentData{
public Translation previousTranslation;
public float currentVelocity;
}
And have a system that updates this:
private struct CalculateVelocityJob: IJobForEach<MoveVelocity, Translation>
{
public float deltaTime;
public void Execute(ref MoveVelocity velocity, [ReadOnly] ref Translation translation)
{
var distance = math.distance(velocity.previousTranslation.Value, translation.Value)
velocity.currentVelocity = distane / timeDelta;
velocity.previousTranslation = translation;
}
}
I am not expert on vector math either, something like this should be fine.
he wants to accelerate and deaccelerate๐ค
he asked how to get current velocity ๐
so i guess reading from current velocity he can accelarate/deaccelerate with his current code
@storm current Sounds like you want a simple PID controller to me
Vector3 pos;
Vector3 velocity;
Vector3 targetPos;
void Update(){
Vector3 delta = targetPos - pos;
Vector3 pForce = delta * pMultiplier * deltaTime;
Vector3 dForce = -velocity * dMultiplier * deltaTime;
velocity += pForce + dForce;
pos += velocity * deltaTime;
}
I used Matf because i'm not very familiar with Unity.Math
This will accelerate, decelerate until pos is at targetPos
@storm current
you configure your p and d multipliers
if p is too big, it will overshoot
if d is too big, it will move slow
you will tune those variables yourself
This is a simple PD controller
you just set those numbers to your tastes @warped trail
@warped trail there are ways to auto-tune this but i never needed to learn about it
i tune them once and this pd controller will do it's job for every possible distances?
also on top that
you should limit the max value sum of pForce and dForce can get
you might want that in %90 of the cases
limit the max acceleraton
if this were a rocket, max thrust force is limited you know
.
you can also use this in physics bodies
and move them just by Adding force
or += velocity
@round summit But can I not calculate the distance I need to accelerate/decelerate?
For example if I would use Unity NavMesh it has the same behavior with the acceleration I want without tweaking values.
does unity navmesh output target positions?
in a way that once you reach one, next one is the new target?
@storm current I don't think PD controller may be what you want if you can directly set position of this unit
You can use it as simple A to B movement and ignore all the fancy pathfinding and obstacle stuff
PD controller is needed in situations where you don't want to directly modify transform because you want to use physics
Actually you can use it
Basically it would look like a RTS movement, I have the destination and instead of moving toward this with a constant speed is uses acceleration -> max -> deacceleration
PD controller will do it anyways
you can use this
you just need to limit the velocity on top of everything
Vector3 pos;
Vector3 velocity;
float maxVelocity;
float maxForce;
Vector3 targetPos;
void Update(){
Vector3 delta = targetPos - pos;
Vector3 pForce = delta * pMultiplier * deltaTime;
Vector3 dForce = -velocity * dMultiplier * deltaTime;
Vector3 finalForce = Vector3.Clamp(pForce + dForce, maxForce);
velocity += finalForce;
velocity = Vector3.ClampMagnitude(velocity, maxVelocity);
pos += velocity * deltaTime;
}
@round summit I am looking into it, thanks
Hey how can I scale a vector to make it's length be exactly some value? Maybe this is better asked somewehre else? I have a very short vector, like Vector.length = [0.1, 0.5] and I want to scale this vector to the length of 0.5 if it's length is shorter than 0.5
@formal scaffold
float len = myVector.lenght;
Vector3 normalized = myVector / len;
Vector3 result = normalized * yourNewLenght;
wait
If you normalize your vector it's leght will become 1
You can then decide on what the leght is supposed to be
And then do normalized * yourNewLenght
these are physics questions though
OHHH nice I always thought normalize will just do value/maxFloat
normalize is vector/len
So if I make 0.5/somethingBig = 0.00000... something smaller
nope
Hmm im dump thanks ๐
if your vector is zero initially though
you will still get a vector with length 1
That may cause issues depending on your case
If I use normalizesave then the default of 0 should fix that right
thats an ecs method?
yeah math.normalizesave(vector, default);
ah, neat
Indneat ๐
badumtss
Why does this need to be unsafe? https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/UnityPhysicsSamples/Assets/Demos/4. Joints/Scripts/Creators/LimitDOFJoint.cs#L53
yeah, seems extra
There was a Collision Trigger example with a single unsafe
(it was modifying the velocity on collision, so balls jump)
i removed the unsafe and balls stopped jumping
did it not give you an error when you removed unsafe ?
no
huh weird, but perhaps an internal called needed that unsafe even tho you are not doing any pointer stuff, who knows
i mean normally it should give an error like "in order to be able to do pointer arithmatic you need to put unsafe context" or smth like that
I might be wrong about what i said
I need something like a system global constant that I set once in the beginning, how do I do that?
(for example stepwidth parameter, I only want to set it when the game starts up and I can then leave it constant forever)
just add a public variable to the system and set it from a monobehaviour?
is that better in some sense?
Yeah, since its static you can just do ClassName.StaticVariable
do you know singleton pattern in Unity ?
why not create singleton entity?
@opaque ledge you mean it makes setting the variable easier?
because for using the variable I can just do variableName either way right?
for setting I would have to do entitymanager getsystem some stuff probably if I don't make it static?
and how does the singleton pattern in unity differ from normal singleton?
as i heard a lot on forums storing data in systems is not good๐ง
even if its just a constant float?
imo yeah, static class helps on global settings, and no you dont need to hold data in your system, you can simply reach out to variable in OnUpdate
void OnUpdate(){
var myFloat = MyStaticClass.myFloatStatic;
}
ah ok so you guys would just create a static class with my configuration settings and then reach out to that from the system instead of having the variable on the system itself?
and you can use "myFloat" in your jobs
ok I can also do that, is there an obvious reason why that is better?
systems are supposed to change data not store it๐
well i mean if you like to then go ahead, there is nothing wrong to it, but with many extra steps, if you make it a static variable you can just do it like the way i did
quite handy
yeah I mean I believe you guys if you say this is the best practice, I just would like to understand why
and if you change your mind one day and want to change that float in runtime you dont need to do anything extra
I mean i am no expert, its just thats what i would do, thats all ๐
and you can do it in Druid's way as well, you can make a singleton Component, and call GetSingletonComponentData<T> to retrieve that data
your call^^
the whole purpose of components is to store data๐
and you want to store it somewhere else๐
haha you don't need to take any concept to the extreme if it makes your life way harder
just wanted to understand the reasoning between the different ways to store this system data
well its more of a global data than a system's data, singletons are great for that
many experts coder sees singletons as evil things, but i never had problem with it
i am not experienced enough to hate singletons just yet ๐
hmmmmm...
Raycasts seem to not ignore backfaces in Unity.Physics
But i want to ignore backfaces like in default physx
Can i simply do that?
Make it ignore backfaces?
I don't want my grounded raycasts hitting my characters bottom
Ignoring backfaces would be a clean way to fix that
basically you want to ignore selfcollision?๐ค
on raycast yes
there is no out of the box solution for that ๐
I could start the ray with a little distance but i'm just wondering if theres a better option
Or do two raycasts
cast the first one to hit the edge
second will start from the edge
there is custom SelfFilteringAllHitsCollector and SelfFilteringClosestHitCollector in here https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/UnityPhysicsSamples/Assets/Demos/6. Use Cases/CharacterController/Scripts/CharacterControllerUtilities.cs
trying to find out what method is this based on
It seems to reference to character's collider and cast with that
I guess ill do with double raycast and save myself from the extra spaghet
Hah, i think i'm done with dots :D
public class RigidbodyTests : MonoBehaviour
{
SimpleECSRigidbody rb;
void Start()
{
rb = GetComponent<SimpleECSRigidbody>();
}
void Update()
{
// raycast example
SimpleECSRaycastHit hit;
Debug.DrawRay(rb.Position, Vector3.down);
if (SimpleECSPhysics.Raycast(rb.Position + Vector3.down * 2, Vector3.down, out hit))
{
Debug.Log(hit.rigidbodyMono.gameObject);
}
// other examples
rb.AddTorque(Vector3.right * 0.1f);
rb.AddForce(Vector3.up * 1.1f);
rb.Rotation = Quaternion.LookRotation(Vector3.forward + Vector3.right);
rb.Velocity = Vector3.right;
}
}
public class SimulationControlTests : MonoBehaviour
{
void Update()
{
if (Input.GetKey(KeyCode.Space) == true)
{
SimpleECSPhysics.Simulate();
}
}
}
how and where do I add dependencies?
if I want one system to run after another?
this jobhandle thing is somehow gone but I can access dependencies right?
do I do it in Oncreate and how do I add it?
you want job dependencies, or you want to make one system update after another?
Dependency = Entities.ForEach().ScheduleParallel(Dependency)
is the same as Entities.ForEach().ScheduleParallel()
basically Dependency is inputDeps, instead of returning inputDeps you just writing to Dependency property
thank you, and how would I add one system to the dependency of the other? I think I never did thaat before
[UpdateAfter(typeof(YourSystem))]
public class YourOtherSystem : SystemBase{}```
yeah thanks ๐
I searched through the system order update part but did not see code boxes
if I want to create a texture every frame from a system, what is the way to go?
I have a entitiy for every pixel and know therefore that it won't write to the same location from two different jobs for sure
but the unity texture type still won't work probably right?
this is too advanced for me๐
make most of the work in jobs, store it in native array, then copy from native array to texture on main thread?๐คทโโ๏ธ
yeah the work is basically done already
I mean I could have a job that copies from entities to nativearray and then make a texture out of it
yeah I'll just go with main thread for now
Ok one last question for now I hope:
Can I access components from other entities in ForEach (if I use ScheduleParallel) or do I have to use one of the more complicated versions and this ComponentDataFromEntity?
yes you need to use ComponentDataFromEntity, or EntityQuery has ToComponentDataArray<T>() and ToComponentDataArrayAsync<T>() methods
wasn't there something that is more complicated then foreach but less complicated than IJobChunk?
ComponentDataFromEntity is not complicated ๐
@warped trail and I cannot use that in foreach right?
you can use it in foreach
ah I can? ok perfect thanks ๐
I just remembered that earlier there where 3 type of jobs:
- Foreach
- something else
- IJobChunk
and IJobChunk was the most manual one
now I only find Foreach and IJobChunk in the samples somehow
erm not 3 types of jobs but three type of systems
var cdfe = GetComponentDataFromEntity<Translation>(isReadOnly = false)
Entities.Foreach((...)=>
{
var translation = cdfe[entity];
})```
ToComponentDataArray gives you copy of components in NativeArray
ah can't I just set the public ComponentDataFromEntity<LocalToWorld> LocalToWorldFromEntity; as property of the system object?
should I better do it in each onUpdate?
@warped trail thank you for all the friendly help
i think you supposed to use GetComponentDataFromEntity every update ๐
EntityQuery query;// This is property or field of system
var array = query.ToComponentDataArray<T>(Allocator.TempJob, out var jobHandle);
Dependency = JobHandle.CombineDependency(Dependency,jobHandle);
Entities
.WithStoreEntityQueryInField(ref query)
.Foreach((...)=>
{
array[someIndex]
})``` or something like this
is anyone around who could check this post? https://forum.unity.com/threads/solved-how-automatic-is-systembases-dependency-management-really.830223/#post-5536738 I am looking for answers
Basically the question is: do SystemBase systems that do not use components at all, but only jobs running on other data structures, make any sense at all?
and if they don't how will I handle the dependency in such a way I can mix them with proper systembase systems?
Yeah it does makes sense, not every job has to be about entities/components, you can use Job.WithCode() for that
@junior fjord afaik, 3 job types are: ForEach, IJobChunk, IJobForEntity<>
thanks but I don't think that answer my question
OnUpdate(JobHandle inputDeps)
{
//your work here
return inputDeps;
}```
```cs
OnUpdate()
{
JobHandle inputDeps = Dependency;
//your work here
Dependency = inputDeps;
}```
nothing changed
but how does the next job in the queue know about the dependencies of the previous job?
JobScheduler handles that
you are giving your job dependencies
and is this true for job that do not work on components too? IF so this code should be correct:
var handle1 = CreateJobForDoofusesAndFood(Dependency, GroupCompound<GameGroups.FOOD, GameGroups.RED>.Groups,
GroupCompound<GameGroups.DOOFUSES, GameGroups.RED, GameGroups.NOTEATING>.Groups);
var handle2 = CreateJobForDoofusesAndFood(Dependency, GroupCompound<GameGroups.FOOD, GameGroups.BLUE>.Groups,
GroupCompound<GameGroups.DOOFUSES, GameGroups.BLUE, GameGroups.NOTEATING>.Groups);
this.Dependency = JobHandle.CombineDependencies(Dependency, handle1, handle2);
note that the jobs are scheduled with Dependency
like:
var deps =
new LookingForFoodDoofusesJob(doofusesBuffer, foodBuffer).Schedule((int) doofusesBuffer.count,
(int) (doofusesBuffer.count / 8), Dependency);
Yep basically
so Dependency can be used as input as well
yes
Dependency is just a JobHandle, so yeah
I thought that the JobScheduler would combine dependencies ONLY for components data
Dependency is your inputDeps from JobComponentSystem
yeah
Great thank you! And what's the point of CompleteDependency ?
but only if its in system, not sure about the jobs you schedule in Monobehaviour world
(yes I use only systems)
I never tried that but probably makes your main thread wait for dependency jobs to be completed
why ๐
because otherwise I needed to handle the dependency myself
in fact I still don't understand why the physic ECS needs the final job handle
btw did you solve your problem with the hiearchy conversion thingie, where you didnt want children to be converted ?
did you destroy them or prevent them being converted ?
this code works on instantiated prefabs, so I can actually delete the gameobjects before the conversion
awkward part, I had to create a scene, because they don't provide a version with an array of objects
i hope they will make physics stuff easy to work with๐
yeah tbh ๐
But.. its kinda understandable, i mean if you try to do physics stuff before physics stuff for that frame is created then bad things will happen
I may understand the job handles for the things that happens in the middle of the physic frame
but I am not sure why the end of simulation final job handle exists
I need to discuss this one
i haven't figure out the way to make ICollisionEventsJob work without .Complete(), but ITriggerEventsJob works just fine๐
if you are talking about error outputed by the JobDebugger, their code may have bugs in this sense
it's something that we are still figuring out as well;
its kinda weird that i dont see anything related to job handles in dots physics forums
there is some posts
if you see the CollisionEventsJob override schedule, it combines the job with a final handle anyway
i saw that too
that makes sense because triggers and collision events jobs happen in the middle of the physic frame
also you may want to start raycast before the end of the physic frame, once the collisions are all updated
that's why these handles exist
raycast is also weird in that regard, like.. if you dont do final job handle combine, it will give you errors, but if you disable job debugger then everything simply works
Dependency = JobHandle.CombineDependencies(m_ExportPhysicsWorld.FinalJobHandle, Dependency);
// my work
m_EndFramePhysicsSystem.HandlesToWaitFor.Add(Dependency);```
the fact that it works it doesn't mean that works all right unluckily
this what i do to make my raycasts work๐ง
I am not sure what you need the HandlesToWaitFor
without it there is erorrs
i hope that they will make physics version of SystemBase so we dont need to do all these stuff ๐
hmm interesting
i never needed handlesToWait for as well
just combining with final job handle was enough for me
and this is what Unity.Physics folks recommend on forums
it shouldn't be needed as far as I understand it
Hmm what are these errors?
I made my code into a package and opened in my previous project
I imported the dots packages the same way (entities, hybrid renderer, unity.physics)
right click the code choose quick actions, if it shows you a namespace choose that
i never saw that error before ๐ค
i hope there will be new physics package update soon๐
probably in 1 month ๐
are there any big changes in the general ecs package that everyone waits for?
i asked the same question ๐
general thinking is that they will 'intergrate' current systems to DOTS basically
like ui etc.
by general thinking.. 2-3 people said this ๐
@opaque ledge
using Unity.Entities;
namespace is already included
Tbh, there is only 1 thing i am wondering about, i wonder if they will make a special TagComponents that wont trigger a chunk recalculation ๐ค
no๐
Hey how do you instantiate your Entities?
Do you create a GameObject with a Transfrom and maybe some other stuff,
then add the Convert to Entity Script and make it a prefab.
After which you instantiate this prefab within a GameManager mono where you add some more components to it?
I'm wondering about the workflow here from creating to instantiating ๐ค
I'm wondering about the workflow, I mean you could create your own entities completely from code. But what makes more sense in the long run?
Do you know how to convert a gameobject to an entity ? you basically instantiate that entity with that method
If you want to build a scene, using the subscene is the way to go I think
if you want to create them dynamically then you don't need gameobjects, unless you want physic/mesh stuff setup in a prefab
we don't use subscenes, but we have prefabs setup from our artists
i never could find a situation that i wanted to create a blob asset ๐ค
bye bye see you next time
tc^^
sounds like some assembly issue
What do you think is better:
- A generic prefab in the scene with a single authoring script for special components,
- The same prefab with a script for each component attached.
I don't like the second one because my inspector get's too long then.
@round summit I had the same issue once, did you reastart Unity? Don't remember if that fixed it for me back then. I also removed alot of code
Oh and I removed and added all packages
Sorry can't really remember ๐ค
@formal scaffold tbh i would go for 2nd option, it gives it more modularity, assuming behaviour of authoring wont change depending on what components that entity will have
- instantiate game object
(instantiated object's Convert() isn't called instantly)
- i want to do stuff on it right away but Conert isn't called and object is not ready for that
I tested that, that's how it is
How can i make the convert work instantly?
IConvertGameObjectToEntity's Convert called from a system?
That would make sense
What can i do about this?
Can i force the conversion so it's instant?
It looks pretty much like IConvertGameObjectToEntity' Convert() is called from a system outside.
Any idea what system this might be?
@round summit I don't think it's possible to instantly convert it, because it happens sometime at the start of runtime
But why do you need it instantly?
I was able to instantiate them in after the start of the game
I get the entity, it works
But not at the same frame
Not after just calling the instantiation
@bright sentinel I need it
I instantiate the gameobject, and i immidently want to do stuff with it and its entity?
Yes, but why? Because that shouldn't be a necessessity
What are you trying to achieve?
There's probably another way to do it
And you need to do that the instant the game is run?
or making the scene load a servers state
Well if you want to load something from a server, then you need to wait for the server anyways, so not sure why you can't just wait 1 frame for that to start
this is how i do it:
-state comes from server
-a new object appeared in the state that i dont have
-instantiate prefab
-set its velocity among other things
if i wait one frame, determinism is ruined
That shouldn't have anything to do with conversion though
.
server constantly sends state
client does this immidently as he recieves a state
its not like request and reply
But this doesn't have anything to do with conversion
As conversion happens as you enter the game
comversion happens when a convertible enters the scene
you can Instantiate() them
and they will convert
in regular runtime
but they will convert the next frame
But if you're loading a new scene, then can't you just wait 1 frame on all clients?
i want to wait one conversion frame only
imstead of waiting a mono frame + ecs physics frame
I bet the convert is called fram a system,
I think i can call that systems update after instantiating stuff
Well you could always just convert them when you run the game instead of when loading the scene, and then save that converted prefab somewhere
I am not loading scenes btw
my "loading states to scene" is just instantiate,destroy, position, velocity assigns
what are converting?๐ค
Gameobject's companion entity
shouldn't you just convert once and than just spawn entities?๐ค
So if you're not loading any scenes, I don't understand why you can't just convert them as soon as you enter the game
I am instatiating a gameobject anyways though
Isn't that already the main bottleneck?
But if you're working with ECS, why are you instantiating a gameobject?
