#archived-dots
1 messages Β· Page 243 of 1
This will sound dumb, but can I use an EntityCommandBufferSystem in a monobehavior? Seems cromulent except won't let me end it.
why not just run EntityManager directly?
I assume monos get to run somewhere separated from systems
yeah, use EM directly
easier for batch commands
has anyone looked into creating stats for achievements in Entities? Seems somewhat painful
Does DOTs questions include questions about Jobs?
sure
this is basically the only channel about anything related to ecs kek
I guess I'll live here for a while
Okay, I'm having trouble Dipose()ing of my native arrays. I call Dispose() at the end of Awake (the only time I schedule the job) and I still get a error about a collection not being disposed
I've eyeballed my code like 10 times and can't figure it out
send us code?
everything is in player loop but MBs have their own update
Here's the job:
struct PerCubeDataJob: IJobParallelFor
{
[ReadOnly]public NativeArray<float> _density;
[ReadOnly]public float _surface;
[ReadOnly]public int _resolution;
public NativeArray<Vector3> _vertices;
public NativeArray<int> _triangles;
public void Execute(int index){
int vec2int = index % (_resolution * _resolution);
int x = Mathf.FloorToInt(vec2int % _resolution);
int y = (vec2int - x) / _resolution;
int z = (index - (x + y)) / (_resolution * _resolution);
float[] cube = new float[8];
for(int i = 0; i < 8; i++){
Vector3Int corner = new Vector3Int(x, y, z) + MarchingTables.CornerTable[i];
cube[i] = _density[x + (y * _resolution) + (z * _resolution * _resolution)];
}
MarchCube(new Vector3(x, y, z), cube);
float point_density = _density[index];
}
void MarchCube(Vector3 position, float[] cube){
int config = GetCubeConfig(cube);
if (config == 0 || config == 255)
return;
int edge_index = 0;
for (int i = 0; i < 5; i++)
{
for (int p = 0; p < 3; p++)
{
int indice = MarchingTables.TriangleTable[config, edge_index];
if (indice == -1){
return;
}
Vector3 vert1 = position + MarchingTables.EdgeTable[indice, 0];
Vector3 vert2 = position + MarchingTables.EdgeTable[indice, 1];
Vector3 vert_pos = (vert1 + vert2) / 2;
int index = (i * 3) + p;
_vertices[index] = vert_pos;
_triangles[index] = index - 1;
edge_index++;
}
}
}
int GetCubeConfig(float[] cube)
{
int config = 0;
for (int i = 0; i < 8; i++)
{
if (cube[i] > _surface)
config |= 1 << i;
}
return config;
}
}
but they probably get called seprately from systems, so as I think, no mono update will be called between 2 systems
thus no need for buffer
yeah, that's what i meant by "their own update"
Do you have leak detection set to full stack trace?
And here's Awake(): ```
void Awake()
{
filter = GetComponent<MeshFilter>();
scale = 1 / Mathf.RoundToInt(Mathf.Pow(2, tree_depth));
//density1d = new float[8 * 8 * 8];
NativeArray<float> density_array = new NativeArray<float>( GenerateDensity(8), Allocator.TempJob);
NativeArray<Vector3> vertices = new NativeList<Vector3>(8 * 8 * 8, Allocator.TempJob);
NativeArray<int> triangles = new NativeList<int>(8 * 8 * 8, Allocator.TempJob);
PerCubeDataJob cubeDataJob = new PerCubeDataJob
{
_resolution = 8,
_surface = surface,
_density = density_array,
_vertices = vertices,
_triangles = triangles
};
JobHandle testHandler = cubeDataJob.Schedule(8 * 8 * 8, 8);
testHandler.Complete();
Mesh mesh = new Mesh();
mesh.SetVertices(vertices);
mesh.SetTriangles(triangles.ToArray(), 0);
filter.mesh.Clear();
filter.mesh = mesh;
density_array.Dispose();
vertices.Dispose();
triangles.Dispose();
}
MBs run before system if I remember correctly
Yeah, it just points to the collection's definition
density_array.Dispose(testHandler); here
you are using job handle but never .Complete() it afterwards
afterwards
density_array.Dispose(testHandler); returns a jobhandle but you don't use it
replace with density_array.Dispose(); and it will work
no need to let it run in a job I think
Well, I did that, and nothing changed
if you made the code change just recently the error msg could be thrown from your previous leak
It's pointing to triangles and vertices
Could it have something to do with the arrays not being big enough or something?
Why wouldn't Dispose() work?
no, you'd get an out of bounds exception if that is the case
is it hitting the dispose lines? does it run multiple times?
I'll change it to Start() and see
It's not throwing up anything about the dispose lines, and it's only running once
insert some debug.logs to confirm π
I can't see anything wrong with the code so the error must be somewhere else I think. Never had any issues with Dispose unless I forget it π
How would I use debug logs to check?
I know to use them, but what would I print in this case?
insert a Debug.Log("Disposing ...") to see if the line is hit and one after. it's really just for confirmation that nothing is going wrong up until that point
Well, I just put debugs in Execute() and in Start() and the code runs all the way through
Is this an actual Unity bug?
I don't understand
I don't think so. Would have seen more reports by now. Which Unity version are you using?
hehe, sometimes the most obvious mistakes are the hardest to spot
I didn't even know initializing a list to an array can even compile
Now I just have to make my code work
the arguments to my methods involved EntityComponentBuffers, so I didn't want to recode. I guess I can recode em if it is impossible
I know work around, but seeing what is possible. Ty
... do work
commandBuffer.Playback(EntityManager);
commandBuffer.Dispose(); ```
Hey, you can see that _vertices and _triangles are both arrays, but in the tutorial I followed, he used lists, and this is how he added vertices and triangles:
vertices.Add(vertPosition);
triangles.Add(vertices.Count - 1);
Since I can't modify lists with multithreading, how can I add the same values in a manner that doesn't use lists? The current way doesn't work.
Since I also can't get a _vertices.Count value, since it's size is predefined
you could use dynamicbuffer but im not sure its a good way or not
The threads don't complete in order, so if it expands dynamically then it probably won't work for mesh generation
that's how you get spagett
ive used it before in a run parallell, each mesh was its own entity with its own buffers and ran in parallell but no idea if it was performing well or not π
Huh, I could try it in the meantime
How do you pass a null for a EntityCommandBuffer.ParallelWriter parameter to a method?
Aka how do you set: EntityCommandBuffer.ParallelWriter = null ?
im not sure if theres some faster thing you can just use in a job that doesnt need to save it as component at all
Use mesh.SetIndexBufferData and mesh.SetVertexBufferData instead, then you can use your native containers directly and there's no allocations
wait, I'm noob, how would I do that?
With lots of reading https://docs.unity3d.com/ScriptReference/Mesh.SetVertexBufferData.html
You can see how I did it here, the API was pretty hard for me to get used to https://github.com/sarkahn/dots-roguelike/blob/master/Assets/Lib/Terminals/Runtime/Rendering/TerminalRenderMeshSystems.cs
I see. Anything simpler in the meantime?
Copy your native arrays into lists?
the problem is that _triangles value depends on the index of _vertices
That's not my issue
My issue is with the structures used to generate data. I just need to figure out how to keep the data clean while moving from single thread to multithread
You'll have to describe your problem a bit more. The triangle indices point to the indices of your vertices. This is how meshes work
Not sure what the issue is
I need to find the indice to add to the triangle independently of the length of the _vertices array. This is what I'm trying to translate from single thread to multithread.
I really have no idea what you're doing then. Any time I make a mesh I fill the vertices and triangles at the same time. I'm not sure how it makes sense to do it otherwise
I'm following a tutorial for beginners, they don't jump the gun to multithreading usually
It doesn't matter if it's multithreaded or single threaded. Verts and tris have a 1-1 relationship. Or a 1-3 relationship I guess. You shouldn't be filling one without filling the other at the same time
Yeah, just saying that doesn't magically make me understand how to do it
My code is all above, feel free to take a look
Yeah I'm not going to try to piece together whatever that is doing. But the way you're describing your problem doesn't really make sense to me. The indices for a given triangle should always be the same given that they're derived from the index of the vertex/quad. It shouldn't matter if it's multithreaded or not, it should still be giving you the same indices in order
My advice would be to try to tackle something simpler to start with and work your way up to whatever that is
you can't, they're structs
I've got this far, I'm too close to give up
That is a huge pain in the ass but I've done it
You need to pre allocate the arrays you've decided to fill with data
And then write them in parallel, disabling the native parallelism safetys
@spiral flint
if you know how many triangles/quads to generate before, you know the minimum # of vertices & indices you need
If the sizes of the meshes you are building is unknown at the time, just run the code twice. First round get the count, finish those jobs, allocate and then write to the jobs in the second round. It'll take two frames but it means you don't have to estimate how large your arrays will be
Not perfect for performance but better because memory bandwidth is the bottoeneck in ECS and DOTS
for 50,000 vertices and counting ahead of time in my imgui framework - it took around 0.04ms - which isn't bad when you iterate twice
just to jump in here you may not necessarily need to take two frames.. for example you can schedule a job to run and then another, if need be using a later sync point within the frame ie a later ECB system
Yeah great point. But you do need to complete the count job before the write job. I tried to think of a way to do it in one pass but I am not enough of a master of pointers to figure that out.
Yeah for sure i don't know the specifics of the situation tbh, but i did spend quite a bit of time figuring out how to use the existing ecb systems / sync points to get multiple-stage workloads to complete within the frame.. so just saying it is possible, and quite nice actually when you kinda learn how it's all structured
I'm not entirely sure what that means
Know of any examples I could look at? It's not easy for me to imagine how it would work
Unfortunately I have no examples on hand. I kind of stumbled into this with a lot of frustration.
I don't entirely understand the problem either. Are you generating a mesh at runtime and want to multi thread it?
Yep, it'll be in an octree with varying resolution with view distance
A user did a marching cubes thing that built a mesh and posted some source, not sure if it has anything useful to you:
#archived-dots message
Digging time
I swear, GitHub is like a giant code textbook
I just get intimidated with large repos because there's too many parts for my smol brain
Yeah i mean it might be possible to find parts that are relevant.. or even scroll through the discussion he was having on here as i think some of it was similar, trying to init arrays of unknown size and also some issues with doing it in parallel.. worth a quick read maybe π€·
Looks like a different issue. I think I can just solve this with math. With the information given, namely vertex index.
I feel like my solution is staring me in the face
I also have the edge index and the iterations of the array
I'm trying to keep it as simple as possible because it's just a demo. I think I have all the variables I need to calculate the _triangle values.
I can get the "index" of the triangle int tri_index = (int)math.floor( value_index /3);
Tell us the final problem.
I think you are trying to find a solution without telling us what you need to do
A mesh is just a list of points
And the the triangles are indexes to each point
(Just making sure we are on the same page)
So in the single-threaded code, in this loop, he adds the index of the vertex to the list of triangles.
void MarchCube (Vector3 position, float[] cube) {
// Get the configuration index of this cube.
int configIndex = GetCubeConfiguration(cube);
// If the configuration of this cube is 0 or 255 (completely inside the terrain or completely outside of it) we don't need to do anything.
if (configIndex == 0 || configIndex == 255)
return;
// Loop through the triangles. There are never more than 5 triangles to a cube and only three vertices to a triangle.
int edgeIndex = 0;
for(int i = 0; i < 5; i++) {
for(int p = 0; p < 3; p++) {
// Get the current indice. We increment triangleIndex through each loop.
int indice = TriangleTable[configIndex, edgeIndex];
// If the current edgeIndex is -1, there are no more indices and we can exit the function.
if (indice == -1)
return;
// Get the vertices for the start and end of this edge.
Vector3 vert1 = position + EdgeTable[indice, 0];
Vector3 vert2 = position + EdgeTable[indice, 1];
// Get the midpoint of this edge.
Vector3 vertPosition = (vert1 + vert2) / 2f;
// Add to our vertices and triangles list and incremement the edgeIndex.
vertices.Add(vertPosition);
triangles.Add(vertices.Count - 1);
edgeIndex++;
}
}
}
My problem is that I can't modify a list in parallel, so I need to do it a little different. I'll post my current code ...
Okay what you need to do is first count the size of list you need
So run the code once's figuring out the final array list length
In my code, I can still reference the index of the vertex, but I need to know what triangle to assign.
void MarchCube(Vector3 position, float[] cube, int value_index)
{
int config = GetCubeConfig(cube);
if (config == 0 || config == 255)
return;
int edge_index = 0;
for (int i = 0; i < 5; i++)
{
for (int p = 0; p < 3; p++)
{
int indice = MarchingTables.TriangleTable[config, edge_index];
if (indice == -1)
{
return;
}
Vector3 vert1 = position + MarchingTables.EdgeTable[indice, 0];
Vector3 vert2 = position + MarchingTables.EdgeTable[indice, 1];
Vector3 vert_pos = (vert1 + vert2) / 2;
int index = (i * 3) + p;
int tri_index = (int)math.floor( value_index /3); // index of the current triangle being added to _triangles
_vertices[value_index] = vert_pos;
_triangles[(3 * tri_index) + p] = value_index - 1;
//_triangles[value_index] = index - 1;
edge_index++;
}
}
}
Then read that info from your job
Then do the same stuff again but this time writing it
A list is an array with a wrapper in it
So when you add something to a list, you are changing the underlying array and increasing the count of the list
So a list may appear to have 5 items in it, but the underlying array has 64 items in it, 59 of the which are junk data
So you need to find the size of your array to fill first
It's fixed size, I have it scale with resolution, if that's what you mean?
I gotta go do something so I can't explain it right now. But look up how C# lists work and that will help you crack it.
You are close, you just gotta figure out how to add things to an array as if it were a list
oh you are so close
Edge_index is the point right?
So just use that to reference the triangle
the index of the triangle you are using is the index of the vert you have just written
and now I really gotta go, good luck!
How are you guys handling conditional write backs in an IJobChunk? Like, always getting a write handle sometimes makes no sense when nothing is written back. Getting a write handle alone bumps up the chunk version. My naive solution is to handle it with bools that determine if something is written back and if it's true, only then a write handle will be acquired. It "works" but it's so suboptimal.
I've never really run into a situation this is a problem. For the most part anything that I use changefiltering on is only updated occasionally so ComponentFromEntity is used on these components.
Is there any advantage to use IJobChunk?
never used it as well as IJobEntityBatch, seems very specific
well you shouldn't use IJobChunk as it's deprecated in favor of IJobEntityBatch
as for if you should use them, up to you
I actually write most of my backend code in IJobEntityBatch (or other jobs)
The main advantage (compared to lambdas) is you can more easily do chunk level optimisations. Eg if(HasComponent(blah)) once per chunk rather than per entity
how does it work? you shouldn't be able to assume that if one entity has component every other also has it. EntityQueries provide such feature.
Sometimes you donβt want to write a foreach for every combination of query (code duplication, performance and complex state/tag stuff) and other reasons (eg check chunk version before processing etc) but yes, in a lot of cases, it can be better to do multiple jobs across specific archetypes instead.
sooo, this is my player prefab.
How do I get camera entitiy from it during runtime?
You can tag it
Doesn't camera already has a tag?
Are there any well tested and used solutions for event systems yet?
events are not really something that should be used in data oriented design
For best performance and up-to-date results, it is recommended that static bodies do not have a Parent.
Hmm
How do you set up world like that then?
What is the way to destroy all dummy parents upon conversion?
For example if you have smth like Environment{ FirstRoom {wall wall... door} ... LastRoom {} }
What is the alternative then? Say I have one system that handles the execution of abilities, and another system that applies damage. How would these two systems communicate in a reusable way?
they wouldn't because they are not related
yes
by processing all entities with component
But would I keep a component with a "currentFrameDamageValue", or add a component to the entity, or create an entity?
if applying damage is done frequently you'd not want to add a component whenever you need it but have an already available component on your entity. you would not create an entity. and the first one 'currentFrameDamageValue' i don't understand
Basically have a component with an e.g. integer that stores the damage that should be applied that frame, and is then set to 0
Which is never removed or added
yes
Alright. I think I like the "creating event entities" approach more, but there seem to be performance issues with it
Does the scheduling system ever become a bottleneck if these systems always run, or is it not an issue?
that is oop thinking. try to get away form it
I'm just a newbie, so take it with a grain of salt, but I think of it this way:
upon casting ability (system that reads input), let's say fireball, you create entity by your fireball prefab. Then whatever movement system you have will move that fireball in world space. And other system will check for collisions of this fireball. Once collision happened you destroy entity, add component to collider. And then the other system applies damage to that collider enitity.
not really
iirc is was what joachim recommended a few years ago
its also the way NetCode handles RPCs
The problem with this is the structural change accompanied with that
Adding components is very slow
there is no structural change in that example
How so? He is adding a component
well....sure adding the component is not good. you'd just have the component already. then there's no structural change
Well yeah, but his example mentions "add component to collider"...
is adding component that bad tho?
From what I'v read structural changes are basis of ECS
It will copy the entire memory block of all components on the entity iirc
Yes, but if you have thousands then it can become an issue
that doesn't happen more than 1 times per second probably
you want to have that as little as possible
oh well
Dealing damage won't happen more than once per second?
hm
What if you have thousands of actors, shooting tens of thousands of bullets?
I guess you do need a tricky way to process it then
even if it's once per frame it's still okish
@haughty rampart do you know if systems will process disabled components once that's a thing?
if there are thousands of actors, then it would happen way more than once per frame
Or will the iterating code just skip those
that is not yet decided
I see
Is there some info on that? I also read about entirely unmanaged systems using an interface called ISystem, but I have no idea where people are getting this info
Maybe just have component
damagable
and write to it upon impact
and write it back to 0 once damage is done
Yeah that's what I mentioned as a solution earlier and @haughty rampart also said is probably the preferred way
bad thing is that system will iterate through it for nothing
but I guess that's not as bad as structural changes
only what is available on the forums. ISystem is pretty much finished, well in 0.50 it'll be, but disabling components is not in 0.50
Interesting that disabling components is so complicated
you can use chunk changed property to know if any entities have a changed value in that chunk and only iterate over those
Yeah but that can still cause it to run almost every frame if the archetype is small
it's more like: we don't yet know how / what exactly we want it to do. rather than complicated
I see
cause there are many different ways in how this could be implemented
Is there an ETA on 0.50?
it's multiple magnitudes lighter than a structural change
Q1 2022
I guess that depends on how fast the systems early exits
But it would probably always be faster
Unless you have a massive amount of entities
yes
even then
Do you think that DOTS will make Unity's current object oriented systems obsolete? It seems like there's already a lot of advantages to using DOTS instead
that is not true
mostly
It wont in the immediate future.
It'll probably live along side GameObjects approach just like any other ECS in Unity (there's lots of them if you browse through github or openupm) out there.
In the far future? Well we'll see...
to an extend. lot's of unity's underlying systems will be dotsified anyway but OOP will probably continue to exist, even though it may be mostly because of backwards compatibility at some point
So maybe. I think it's likely that OOP will stick around for people to ignore DOTS like I have for the last 2 years until it's in the way.
I was a total main-threader until last week lol
also, even with 1.0 there will only be a hybrid workflow supported with dots so at least for a while.....oop will still exist
I can't wait to use DOTS 1.0 in my RPG game with just 1-3 entities moving around
that's a perfectly fine use case
when you start with dots you quite literally need to "forget all you know about oop programming"
I know Joachim said "that not everything should in fact be solved with ECS."
but F that. I want it in my RPG XD
Quick question: Is Physics.IgnoreCollision contained in Dots/ECS or do I need to roll my own homebrew version.
OOP has been used since the 80s. And most programmers learned how to program during the OOP days. It's also easier to understand because it's how our brain works. So OOP is probably going to be with us forever. But DOD is way better for the computer so it's gonna be used when speed is an issue.
Oh yeah OOP is great, but DOTS is greater
I also found once I got my brain into the ECS mindset things became simpler and better to pull apart.
Its like when you have to start coding microcontrollers, different rules for different paradigms
Or like driving a boat vs driving a rocket ship.
I am pretty sure you fly a rocket ship π
boats can be comfortable and familiar with all your amenities there.
I command a fleet of them π
It's also hard to get away from it.
I find myself cringing writing monobehaviour code.
when at the back of my mind is like
"this could be way better"
But rocket ships go zoooom
if you're writing monobehavior, you're not writing dots right
It's so much faster to do monobehaviours. Sometimes I know what I need to program but my fingers get tired thinking of it
I meant when I have to do work lmao.
'it's so much faster [...]' i wouldn't really say that. especially when lots of interaction happens between monobehaviours
is there a workaround so subscene gameobject can have gizmos?
Maybe with some custom editors. That's the only way I got some gizmos/handles being drawn in the scene view
can also use aline(though its a paid asset)
I mean to write
As do i
ah okay, yeah depends. I find I can write monobehaviours faster for prototyping but after a while it becomes a convoluted mess
prototyping what for example?
Any old thing.
Yo, this code should make it so stuff isn't rendered: https://pastebin.com/eBH4V0MV & bastian is my tag for stuff to be deleted at a clean cycle
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
But somehow lasers shoot my main guy, and still apparently bounce off me
.
is there a way to make the GameObjectConversionSystem execute after mono awake / start ?
in that system I'm trying to add data form a mono that is being populated on the MonoBehavior : Awake() method
no. they are independent. you can see that when using subscenes. awake will not even be called then
i mean on a separate mono
2 game objects , one is converted , the other is not
i want to fetch data from the none-converted gameobject that defines that data on Awake/Start
and only then allow the gameobject which is flagged for conversion to start the process
why can't you just obtain that data in your system?
i thing i got it - used a similar method to this https://forum.unity.com/threads/suggestion-delay-iconvertgameobjecttoentity-convert-to-after-monobehaviour-start.684451/
How do I make an object look (aka rotate forward towards) another position?
In unity it was:
UnityEngine.Vector3 newDir = UnityEngine.Vector3.RotateTowards(pos2, pos, 1, 0.0f);
rotation.Value = UnityEngine.Quaternion.LookRotation(newDir);
pos2 = my position
pos = aimed at position
That does not seem to work in DOTS ECS
I just spent 2 hours wondering why my laser "lead target" to hit moving target code was failing
I reduced it down to... Literally I can't get an entity rotating properly to look at a point.
It always looks off to the side like a derp
@remote crater I THINK that buried somewhere in this github repo is the code for look towards
I had to write my own math functions to replace some of the ones missing from Unity.Mathimatics. I ended up calling it mathf (instead of Mathf. If you find where those functions are, let me know. Its frustrating that Unity wouldn't completely reproduce the functions we've used for many years. I think it has something to do with SIMD functionality.
I think it has something todo with SIMD functionality
that's exactly the reason why.
Hello everyone, I am facing a dilemma, I have created my own hashtable of component etc...
for 65536 int
NativeArray take 11237 ticks ~= 1.1ms
OwnHashtable take 3456 ticks ~= 0.3 ms
Anyway, I wanted to know if burst compiler and ijob was so powerful that from scratch we can't do faster?
namely it is for the management of chunks.
I would like to be as optimized as possible!
also is it possible to execute a compute shader in a job ?
is there a more optimized way ?
what are the timings? adding?
and does the code run bursted? nativecontainers are slow in normal C#
ok ok I was testing with ecs, when all of a sudden I had a problem with the meshes not having the colors anymore, possible to set mesh.colors on ecs ?
URP btw
@viral sonnet my question is it's better after build then "object []" ?
what's the issue?
I'm guessing there is no "character controller" for dots as of now
and I haven't worked with rigid body characters yet
There is one in the physics samples and one on the asset store called rival
and now that I work with dots physics I feel lost
just make the controller yourself like you'd do in monobehaviours and then sync the input from a monobehaviour
Well, I used Unity's character controller
with it's built in colliders feature
Move(Vector3) thingy
actually I think I figured it out, velocity seems pretty responsive when you directly assign to input movement vector
there is always asset store π
well, I'm trying to learn how to do it, not just use it
Anyone here worked with Dots physics collision trigger event system?
TriggerEventConversionSystem
from sample
I read through it's code several times but I just lack some clarification about it
The most I could (which might be absolutely wrong) understand:
It creates entity with some kind of list of StatefulTriggerEvent struct which looks like this (screenshot)
And then you just query with your systems through entities with data component
Is any of it correct?
here sample itself
yeah basically after solving contact pairs for triggers it stores them in a buffer with a state of ENTER/STAY/EXIT
did you browse the sample scenes too, or only the code ?
they show a lot of use cases
but triggers/collisions is still a verbose hell
For example the query on this file&line https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/UnityPhysicsSamples/Assets/Demos/2. Setup/2d. Events/2d1. Triggers/Scripts/TriggerVolumeForceFieldAuthoring.cs#L141
You can see teh buffer is queried then checked against one of the 3 states
it's just a simple "force field" trigger zone which applies velocity, but there's an even simpler sample with color change
IIRC there are also dedicated collision jobs, which are even worse on boilerplate
so, it stores it in only 1 entity?
meaning you can't thread it with native jobs interfaces
I also having trouble to understand what exact collision does it get from physics
only collisions that are defined by layers?
eg: entity X belong to layer 1 and collides with layer 2,3.
So will that buffer store collision of entity X with entity that belongs only to layer 4?
There are dedicated physics jobs to access the collisions and trigger events
if you implement this interface ^
what about the second question?
sorry it's a very incomplete answer but you can find example in the samples
I mean that part
eg: entity X belong to layer 1 and collides with layer 2,3.
So will that buffer store collision of entity X with entity that belongs only to layer 4?
for layers ? I don't remember π€
So will that buffer store collision of entity X with entity that belongs only to layer 4?
-> wait, what ?
It looks for collisions in the same physicsWorld, I just can't remember if there's a collision layers matrix like in PhysX Unity
But you're wondering if the buffer is the list of events for entities that DID NOT collide ? Sounds weird to me, not sure I understand π
Oh I get it now, you're asking if the CollisionFilter is absolute ?
I ask what collisions will be included in buffer
literally all entities with physics body?
or only those that go along with collision filter
I don't remember seeing the filter used to solve collisions/triggers. It would make sense but I'm only sure for ray/shape casts.
Can be quickly tested in a new scene though
Sorry I don't want to tell you a mistake
welp, looks like collision filter indeed applies
If it's not used, you would have to check layers yourself in the job
Oh well great then π
access it on the mainthread like any other managed type in dots
so you mean
I need GameObjects for this
that are responsible to UI and then just send data from dots systems?
yeah theres no dots native ui
no reason you need to use GameObjects for UI Toolkit
(except to store the UI Document script)
i have a UISystemBase for my UI and I'd recommend you build something similar
for example my (currently very simple) menu UI system looks like this
{
/// <inheritdoc/>
public override uint StateKey => Keys<UIStates>.NameToKey("menu");
/// <inheritdoc/>
public override ComponentType StateInstanceComponent { get; } = typeof(UIMenu);
/// <inheritdoc/>
protected override void OnLoad(VisualElement panel)
{
var playButton = panel.Q<Button>("play");
playButton.clicked += this.PlayButtonOnClicked;
}
private void PlayButtonOnClicked()
{
var uiState = this.GetSingleton<ClientState>();
uiState.Value = new BitArray256 { [Keys<ClientStates>.NameToKey("go-in-game")] = true };
this.SetSingleton(uiState);
}
private struct UIMenu : IComponentData
{
}
}```
(This combines like half a dozen concepts in my project so probably doesn't make a lot of sense what's going on)
uiState.Value = new BitArray256 { [Keys<ClientStates>.NameToKey("go-in-game")] = true }; neat
I'm not really familliar how can you call UI to appear without game objects tbh
I do get the part when you can just call UI (menu for eg)
by clicking button
which is processed by system
but part of opening window itself
seems like relies on game object
UI Toolkit doesn't use gameobjects except for the root UI Document script
so yeah keys is kind of just kind of my attempt at a similar api as LayerMask that work like enums that can be driven by data not code
it's just a singleton?
i guess in a way?
under the hood it's really just a Dictionary<Type, Dictionary<string, uint>>
it's only something i recently added so haven't completely fleshed it out yet
i've been doing a lot of experimental work on the concept of application/game level states
and trying to find a really nice flow for an entity based project
(pretty happy with how it's turned out now)
I was wondering about something similar but for data and assets
as a mean to connect DOTS pure data and artist/designer GO with easiness of authoring
yeah that's pretty much the majority of work i do at the moment
developing in a way to empower artists/designers
i.e. no point* in developing this high performance AI, skill system, game manager etc library if your designers can't use it
(*only relevant to professionals, hobbyist should develop the fastest way they can if they want any hope of releasing their game)
just started using your eventsystem(v2) and it works wonderfully so thanks @rotund token though I have a question, is there a particular reason 1.5.1 of burst is used? getting some annoying warnings on build and im fairly certain they didnt occur in the previous version I was using
it's just min dependency
you can use any version after that you like
you should definitely update it to at least 1.5.7 or 1.6.3
unless you want to downgrade. i can't remember why it was 1.5.1 min, i believe it was related to V1 and I haven't tested V2 in 1.4.X
so feel free to test it, it might work fine
yeah seems like dspgraph doesnt play well with 1.6.3, wasnt really relying on it but annoying
anyway let me know if you find any issues with V2
i've been using it in my own libraries but not at work
and haven't found any issues, but i don't consider it tested enough to mark as production ready
will do!
(also it kills a few features found in v1 which i'm hesitant to nuke for existing users as i have no intention of adding them)
will probably push V2 to master when 0.5 is out
as V2 supports ISystem
I did notice the mention of at least no mixing of fixedrate but I dont think thats a requirement for me
can't remember what i wrote, but writing from fixed update should be fine if you're readers are in the regular update
but not vice versa
@rotund token one thing I wasnt sure of - I havent yet gotten around to this part but
var myEventWriter = eventProducer.CreateWriter();
Entities.ForEach(({
myEventWriter.Write(new MyEvent);}
.Run();
eventProducer.AddJobHandle(Dependency);
Entities.ForEach(({
myEventWriter.Write(new MyEvent);}
.Run();
eventProducer.AddJobHandle(Dependency);
do I need both AddJobHandles or just the second (or should I be making a new writer in this instance)?
hi, how can I ignore a specific collider when Raycast (ECS).
My situation: I have lots of same object moving around, I use raycast to detect if they will hit other, but everytime, they hit themselves
Hi guys, i hope the beginning of the year turned out to be successful for you. π
I have a problem with which i break my head for a whole day!
Imagine i have N sprites with different sets of shader properties. Properties stored as IComponentData, so to render N sprites i gather theirs position data for sorting -> then sort them -> then gather properties data and reorder this data according to position order -> and finally writes data in correct order to ComputeBuffer -> and finally render all this N sprites.
The problem appears when i want to replicate unity's sorting groups, when your sprites can be nested. I want to remain approach with linear accessing to properties data, that's because i don't want to have DynamicBuffer with entity links on parent sprites, instead i want to have some struct ParentSprite : IComponentData { public Entity link ;} (enities which has no parent will link themselves or Entity.null).
So with ParentID component i have arbitrary sequence of N entities which might have parents and i need to account it while sorting. After sorting all sprites which has parent should goes after parent and be sorted only with other children.
The naive solution for me is to firstly sort whole N elements by parent -> then find groups -> then sort groups depending on root parent sorting data -> then restore whole array with childrens using copy/paste of groups. But this solution look very inefficient, because even without sorting groups sorting process is the biggest consumer of time, and with this solution i get extra sorting in worst case with the same N elements.
What you think about it? Can you advise some smart algorithms, or point me on that whole this approach is bad?
What do people recommend doing in lieu of the hybrid renderer in order to render dots entities in deferred renderers? Allocate game-objects for each one and hope for the best?
To boil this down, it sounds like you want the equivalent of OrderBy and then ThenBy, for some sort of nested sort; does that sound right to you?
Sorry for pause, i looking for what is ThenBy in LINQ π
If your sort key was:
let p = f(Parent) in
case f(Child) of
c if c == p -> p * 3
c if c < p -> (p * 3) - 1
c -> (p * 3) + 1
then it'd make sure that parents with lower children sort lower than parents with higher children but equal parent value
it assumes that each entity has exactly one child; you can make the c == p case also consider "if c is null" as an option, or slot that wherever is appropriate
i need to parent can have any count of children
and also i can't understand code example π¬
"any number of children" is hard to even represent in dots, from what I'm seeing, due to the lack of reference types or pointers
that is why i'm asking advice π
I suspect it might need database-style thinking- a collection of entities which contain an ID, a collection of entities for the child types, and a collection of (parentId, childId) tuples saying which ones are related.
But that seems way more complicated than just writing this sort of thing in Rust...
So I'm pretty sure Unity would've tried to come up with something better, somewhere
https://docs.unity3d.com/Packages/com.unity.entities@0.17/api/Unity.Entities.LinkedEntityGroup.html?q=link looks like it's intended to handle this sort of relationship in an automated manner, but I have no idea how to use it.
Honestly, I'm thinking I might actually consider native plugins in Rust instead of using DOTS
Has anyone had luck rendering something that cant be rendered with hybrid renderer by using AddHybridComponent?
Everything seems to work, companion link is set up, companion game object exists but no bueno on the rendering.
I mean, there are ways to do it https://www.youtube.com/watch?v=L7M_vbo1N2g
But really you might as well just go pure Rust if you wanna endure that pain
I added Rust support for the Unity game engine.
Is it really possible? YES it is!
I managed to make a game 100% coded in Rust, but using Unity as editor and runtime.
This has to be one of my craziest projects yet!
I utilized a library called Bevy game framework/engine, to handle the gameplay programming. Utilizing Bevy systems I was able to hid...
LinkedEntityGroup is just DynamicBuffer which links to other entities, and destroying and instantiating goes cascadly
@gilded palm you need to use an ICollector, the physics samples have examples of it but heres one simple one I use
[BurstCompile]
public struct IgnoreSpecificEntityCollector : ICollector<RaycastHit>
{
private readonly Entity ignoreEntity;
public bool EarlyOutOnFirstHit => false;
public float MaxFraction { get; private set; }
public int NumHits { get; private set; }
public RaycastHit Hit { get; private set; }
public IgnoreSpecificEntityCollector(Entity ignoreEntity, float maxFraction)
{
this.ignoreEntity = ignoreEntity;
Hit = default(RaycastHit);
MaxFraction = maxFraction;
NumHits = 0;
}
public bool AddHit(RaycastHit hit)
{
if (hit.Entity.Equals(ignoreEntity))
return false;
MaxFraction = hit.Fraction;
Hit = hit;
NumHits = 1;
return true;
}
}
var collector = new IgnoreSpecificEntityCollector(instigator.Value, 1.0f);
var hit = CollisionWorld.CastRay(rayInput, ref collector);
var hitBody = CollisionWorld.Bodies[collector.Hit.RigidBodyIndex];
var hitentity = hitBody.Entity;
var rayHit = collector.Hit;
Ty so much, I found another overloading of raycast where it accepts a NativeList
@molten flame they will be making companion gameobjects(and I think AddHybridComponent) internal in 0.50 so I wouldnt rely on it. can you not just keep some relationship in a class IComponentData via AddComponentObject?
There is a child parent system in ECS already
Do you have a link to something that describes it / how to use it?
Nice! okay, that makes things better
Ugh, hybrid components seems like a pretty good workflow if only it was workn'
Yeah I can probably do that. I was hoping I wouldn't have to manage it.
WTB hybrid rendering for 2022 π
sorry for slow reply. you just need to match your CreateWriter/AddJobHandle calls 1:1
np, thanks
technically with the code you're doing on mainthread you don't even need AddJobHandle
it's just a requirement of the libraries internal safety system though
How to properly write Unit Test to system using EntityCommandBufferSystem? I have problem that code which should be done by EntityCommandBufferSystem has no effect. Doing it like this
var system = World.GetOrCreateSystem<CreateBlockViewSystem>();
var syncSystem = World.GetOrCreateSystem<CreateBlockViewSyncSystem>();
m_Manager.CompleteAllJobs();
system.Update();
syncSystem.Update();
Is there a way to get singleton from monobehaviour (UI)?
I'm trying to think of a way to get input from UI into ECS
Assets\UI\MainMenu\MainMenuUISystem.cs(17,78): error CS0246: The type or namespace name 'UIDocument' could not be found (are you missing a using directive or an assembly reference?)
What
you need to get the ECBS and update it as well
what version of unity?
2020
runtime ui elements does not work well in 2020
i would advice against ui toolkit unless you are willing to risk 2021 (what i'm doing)
you mean Dots + 2021?
yes
I had trouble even installing it, how did you do it?
i have no issue with dots in 2021
what's the problem?
(be warned, there is a good chance 0.5 breaks it though they have confirmed support for it but maybe not straight away so you may have to delay an upgrade if you use it)
well, last time I tried it just started straight with errors (after installing packages)
but im doing it. in my example thats it var syncSystem = World.GetOrCreateSystem<CreateBlockViewSyncSystem>();
Is there any way to delay when my system runs?
delay I mean
gets created in the first place
I want to initialize only after UI game object is created
sorry i'm blind, so you are
that should work from memory, let me check my tests
Why is your
m_Manager.CompleteAllJobs();
before
system.Update();
if you're only testing output of the ECBS it shouldn't matter, just a random observation
use your own custom bootstrap and create the world whenever you want
any tip where can I find example of this?
I mean, I do find stuff in google
but it's mostly from 2019
and most guides from this year use deprecated stuff
There's 2 parts, implementation of ICustomBootstrap let's you define what systems go into world
Defining UNITY_DISABLE_AUTOMATIC_SYSTEM_BOOTSTRAP let's you control when the worlds are initialized
Unity's implementation is just htis
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void Initialize()
{
DefaultWorldInitialization.Initialize("Default World", false);
GameObjectSceneUtility.AddGameObjectSceneReferences();
}
}```
so before the first scene loads, it creates your default world
so if you implement this yourself, you can wait till whenever you want (e.g. after you create gameobjects)
you mean this is what loads DOTS by default?
i did
m_Manager.CompleteAllJobs();
because inside system im work with collection inside this system. When at the end of updates im checking collection and this require me CompleteAllJobs
yeah but you completed all jobs before the system ran
so you're not completing anything?
unless there's more code that isn't shown
yes thats copied from the entities source, if you define UNITY_DISABLE_AUTOMATIC_SYSTEM_BOOTSTRAP then this code no longer runs and no world will be created until you do it
so, to implement my own bootstrap I use ICustomBootstrap interface or [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] attribute?
ICustomBootstrap is used to control what systems go in each world
i.e. say you have server/client worlds you don't want the same systems to exist in both
so you can implement ICustomBootstrap on a class and unity will call this during world setup
this isn't your problem, you're problem is just timing
so you just need to define UNITY_DISABLE_AUTOMATIC_SYSTEM_BOOTSTRAP
and then call
GameObjectSceneUtility.AddGameObjectSceneReferences();```
at some point in the app when you're ready for your entity worlds to be created
you don't need RuntimeInitializeOnLoadMethod
you could put it in Start in a monobehaviour or whatever you want
whatever framework works for you
ah, I see
I kind of see the way I can load my main menu scene
with this
and then load game world from it
so, world is entity related thing, right?
I'm guessing game objects exist in scene
not in world
Something i've never messed with in dots/hybrid-renderer is materials - i want to spawn a bunch of entities from prefab entities, but i'd like some to use a different material..
when you instantiate your prefab you can simply set component data to smth else
So my first thought would be i could either manually change the material of the entity or generate prefab entities variations and spawn those directly
well, if you only want to change material, just use AuthoringComponent in your prefab
and in Convert method
assign different components of materials
assuming you're using SharedData comps
it's just that simple
well my prefabs are inside a subscene so authoring component would of course run during conversion of the subscene, and i guess i could apply a shared component to the prefab with a list of mats, is that kinda what you mean?
and then when i instantiate the prefab, grab one of the mats and apply it to the entity
ie literally set the Material of the RenderMesh component after instantiate
just wondering if it is that simple, or if there's any chance it could break optimization of archetypes or material instancing or something, is this the best approach
oh wait, it's prefab
in that case just set random comp data
upon instantiation of your entities
just like you set data of your entitiy positon for example
yeahh
Are you aware of Material Overrides ? https://docs.unity3d.com/Packages/com.unity.rendering.hybrid@0.11/manual/material-overrides.html
I'm not sure if I define it correctly
I keep getting these errors
GameObjectConversionSystem
Any idea what assembly is it?
I decided to split my project into assemblies
and I can't figure out what reference this system belongs to
Looks like Hybrid it seems
I'd say entities
Put it in the textfield group above
Add another field with the camera one
Translation
what about this one
I know for sure
it's from physics
but what exact assembly
a lot of stuff actually missing
that is base dots
using Unity.Transforms;
hmmm, so when I press Play with that definition
I still get all my entities and etc
I guess it didn't work?
has anyone else had any problems they've had where componentdatas not updating in the inspector
Hey, I've got a question about the EntityCommandBuffer:
Is it possible to create entities via an ecb inside one job, and use references to these entities in a job scheduled after that?
I tried it, afaik an entity is just an int type of data really (not an actual int but similar), so yes you can store a reference to an entity and use it. However, until the ecb is played, its just an int, and has no components π
Whats the consensus on Schedule vs ScheduleParallel? Use the latter wherever possible?
(assuming many entities)
(or lots of work to be done)
Well, not every job is safe to perform in parallel. Also, if your job does a lot of calculation over many frames, it might be better to just schedule it so that it doesn't hog all the worker threads.
But which entity is created and the integer for it won't be known until the command buffer is run. I think there is some strange stuff around that you'll need to test to figure out.
Out of curiosity, are there any places to read up on the performance differences between these two approaches somewhere?
Is it possible to have an "Ignore collision" component with data of entities it ignores collision with? If not, maybe in the future.
Idk. It is also based on knowing how very low level features itself work
The reason I ask is because it kind of ties into my question above (Schedule vs ScheduleParallel). I was planning on rewriting a few systems to use what you mentioned (not adding / removing components but using e.g. a boolean to signal change), but this means that the system will iterate over many more entities each frame. Would ScheduleParallel (almost) always be there correct way to go for something like this?
In my opinion yes. I'm rarely using .schedule
Hello, I have a 2d racing game which I am converting to 3d (bound to X/Z) and I wanted to convert it to **DOTS **as well.
I attempted to use **TinyRacing **as a base (I only have Start->Finish) but I can't figure out how to keep my prefabs in a Conversion World, so I don't have the originals existing in my actual World.
I could not figure out how to isolate the original prefabs, as **TinyRacing **is setup with everything pre-instantiated in the subscene.
Combine this with DOTS 1.0 coming "soon", I decided to disable the ECS/DOTS libraries for the time being and do 2d-3d work but I still want to reach out for help on the world conversion thing.
Thank you kindly!
what's wrong with keeping them as a prefabbed entity?
maybe I'm confused, why do you need the prefab in a conversion world?
I have a zoo of multiple types of cars, Player, Enemy, Drone, etc.
I instantiate each of them then I customize them a little with some random and player customizations.
I want the originals unchanged somewhere and outside my system's reach
as long as you don't query the entities with the prefab component you don't have to touch the original ones
instantiate a copy of the prefab entity and modify away
and colliders
I'm pretty sure Tiny has been shleved so I'm only speaking from experience with plain old entities package
EntityQueries typically ignore entities that are prefabs/disabled, unless you provide the option to query for them
so if it's rendering and interacting with your systems, then it might not be a prefab entity or your systems are querying for prefabs
https://docs.unity3d.com/Packages/com.unity.entities@0.17/manual/conversion.html#scene-conversion
For reference on scene conversion
Do you have a simple project (like the tiny ones) with this setup? It's hard to wrap my brain around it
the entity component system samples are pinned on this discord channel
I tried to find one but somebody had the good idea to name it DOTS and google is uncooperative at finding me results
dots 1.0 isnt coming soon, 0.50 might(but im still skeptical)
you can also look at the pinned messages here for docs and sample links
Oh so the "conversion world" is something MYSELF have to create and provide to the GameObject -> Entity
and it just appears you need to implement interface for custom initialization
besides constraints
@tranquil jay no it happens automatically unless you are doing some sort of custom world initialization in which case I have no idea what happens with the conversion world
then im back to digging lol
digging for what specifically?
it seems that default world gen is done by just this
DefaultWorldInitialization.Initialize("Default World", false);
GameObjectSceneUtility.AddGameObjectSceneReferences();
I hope at least
have you seen this tutorial?
it actually a really helpful one
I'v been digging it for a week now
Barely had any questions after most things I done
I only started Dots since last Monday, it's a bit overwhelming and there's lots of dead stuff to sift through
ECS in general is completely new way of thinking
I did not come across this π
I am familiar with ECS from my Flash days
yeah, you can just go through beginning if you'd like
it goes through things that are used like 90% times (I think)
will finish eating then go through it, it has potential, thanks @rustic rain
I am assuming there's an asteroid prefab to be instantiated, but the original asteroid is not present in the world, neither render or collision. It's exactly what I need, if so
yeah
public class NewSystem : ICustomBootstrap
{
public bool Initialize(string defaultWorldName)
{
DefaultWorldInitialization.Initialize("Default World", false);
GameObjectSceneUtility.AddGameObjectSceneReferences();
return true;
}
}
Am I doing smth wrong? I get funny exception here
you are definitely doing something wrong here
DefaultWorldInitialization.Initialize("Default World", false);
Calls ICustomBootstrap.Initialize
so you're basically looping over and over
oh well
ooooh
I get it now
this method is for custom DefaultWorldInitialization
ok
{
RegisterUnloadOrPlayModeChangeShutdown();
if (!editorWorld)
{
var bootStrap = CreateBootStrap();
if (bootStrap != null && bootStrap.Initialize(defaultWorldName))```
it's for subscene stuff
// This can be used in custom Entity Bootstrap code to ensure currently loaded Game Object Scenes are added as references to the GameObjectSceneSystem
// for cases where these scenes were loaded without the GameObjectSceneSystem (eg in the Editor and pressing Play).
public static void AddGameObjectSceneReferences()```
how did you find it
basically adds all scenes in the build config to the subscene list
i hit f12 in my ide
and i can see the entities source
IDE is Unity or?
(visual studios for most, but that's the issue. visual studios doesn't do this by default)
unity documents their packages very well and the best resource for learning is to just read it
yeah, I actually tried to dig into code
but my VS was only able to get inside of default world class
this static I ask about was white and wasn't expandable
main reason i ditched VS
resharper adds support to VS and there might be a way to tell VS to actually show the source now natively i just don't know it as it's been too long
i'm not confident there is
VS is capable of decompilation natively
doubt it won't be able to dig into source files
well there is 1 way to do it
but it's via unity
and it causes problems
and that is to generate project files for all packages
me: Rider enjoyer
@rustic rain if you are a student, you can probably get a student Rider licence
yeah unfortunately pricing is not hobbyist friendly though i do appreciate all the groups they give it away for free to
but that's what employers are for
i use ILSpy and look at the dll files to browse the source
yeah, I used ILspy as well
but mostly for decompilation
not looking through sources
yea
@rustic rain that project is incredible
@rustic rain It answered my question, quite strange though, there is a MeshRenderer and MeshFilter that LOOKS LIKE to me like it's automatically converted internally
https://docs.unity3d.com/Packages/com.unity.rendering.hybrid@0.11/manual/index.html this is the additional dots package that should be responsible for converting it (MeshRenderer/MeshFilter)
@coarse turtle it is indeed in this project (and was not in my testing proj) This is hella good news
thanks
some more info dropped in
cant wait to see the breaking changes π
going to be a fun day of refactoring π
and then they forgot to drop the migration guide from 0.17 -> 0.5 XD
@rustic rain if you download the EAP you can evaluate them for free, they usually have a good number of them so i think that you could probably use rider for free for the majority of time although there would be interruptions
still no accurate date except Q1 2022 -.-
alpha versions of 1.0
now that's funny π
Probably in 2 or 3 weeks, given the frequency of LaurentGibert's responses on that thread.
And none of my requests were answered. So sad.
Top notch communication. We waited so long, with the frequency we are answering things 0.50 will be released by then. I'm half joking. The guys probably had a well deserved vacation.
I wonder what the breaking changes will be. Hopefully none too breaking π
From the training github, it doesnt look like any changes on the ForEach lambda frontend. So I'm actually quite concerned. That means the breaking changes are going to be on the IJobChunk side.
Archetype API may be changing. Hopefully with greater access though to the underlying unsafe pointers
what IJobChunk π¬
i suspect the removal of IJobChunk will be one of the changes
(obviously with the replacements IJobEntityBatch/IJobEntityBatchWithIndex)
Hrm, replacing with IJobEntityBatch probably. If they quickly nailed down why the scheduling couldnt be bursted, it's a no brainer.
you mean for ISystem[base]?
Yea. Only IJobChunk works with bursted OnUpdate
pretty sure they just hadn't implemented by 0.17
as far as i hear all jobs should (hopefully) schedule fine in ISystem now
Its strange basic IJob didnt schedule under burst strangely. I didnt really dig into it myself but I could possibly fix it. Maybe
But given 0.50 is releasing in a month or two, ehhh
ill take major breaking changes over the current stagnation
It is. Some components have native ecs alternative that applied itself on conversion. Sometimes you actually want to remove those. For example not all entities need transform.
I'm not really interested in using paid software anyway. I don't want to depend on smth I can't even afford
Do you guys know how worlds are initilized?
If you load another scene. What happens to existing worlds?
do they stay or new world is generated and old is discarded?
Is there basically some kind of example how to do loads from one level to another in dots?
ok, with some decompilation digging, it is Cleaning up all worlds before loading next scene
that makes things way easier
sooo
if I want only certain systems to work
do I just remove them after game initialized?
or is there some way to prevent systems to be loaded in the first place
for example:
I want main menu scene only to contain some visual and UI systems.
While some game scene not to contain main menu related scenes
assuming list is not small
What is the way to achieve smth like this?
I fixed IJob and IJobEntityBatch not scheduling from burst by myself
It's not that difficult
But IJob requires to to define a new job type because it's in the main unity core assembly
worlds are not linked to scenes
changing scenes never really made much sense to me in an entities project. both my project at work and my personal projects only have 1 scene
(that's not to say you can't have many subscenes)
it's about keeping things clean
luckily by default worlds do get removed upon scene change
I just want to be able to swap between scenes nice and easy
without some useless system overhea
if you like this workflow
highly recommend looking into latios framework
at least for ideas/inspiration
does it appear when use unity's mono renderer?
doubtful
btw. you should not build up rendered entities with code. it is recommended to convert a gameobject and reassign changed components to that because unity adds many more components when converting a rendered gameobject to entity
yeah i see, will try to see the differencies
"you should not build up rendered entities with code" i know that is why i want to find solution
x)
i just told you
hybrid renderer docs has the runtime api usage
@tulip robin
you are basically missing some components I think maybe chunk bounds and some other one, if you just convert a gameobject primitive you can see for yourself in the debugger, but id recommend just using the hybrid renderer api as any future changes to the components will then be taken care of by them instead of you
@safe lintel so i need to create my render system ?
yeah that's !
i m going to try to add WorldRenderBounds And ChunkWorldRenderBounds
ok ok the problem is vertex shader of material i think
so it doesn't work
No body ? :/
what's your problem?
what about the default material?
wait it is working here?
try changing the Render Face to both
is dots at all helpful for say a RPG with conversations unique per charecter??
I cant imagine it is trying to think what code you could write for it π
the way I can think of it from the top of my head, as long as you have the dialogue (whether it's a tree or something linear) you can easily map it into indices and control how indices jump
i only know dots all my learning has been with dots, all my games are entirely created in scripts π now wanna try a point and click adventure style but I think I will learn mono for that
the text can pretty much live at a pointer since strings are just char pointers
@stone spoke not that
Seriously DOTS can manage URP ?
Or just make it from scratch ?
Dialogues shouldn't be limited to struct comps
pretty sure
dialogues should be kept as managed data
after all , it's not really per update process
DOTS for dialogues ?
feels like using Hz frequencies for notes lul
UP
dots for dialogues can be good as well. depends on how
NANI guys
if you find cool but i stay on my position why use dots for dialogue
he was talking to someone else, mr. impatient
ooh fack
will try thanks
no rotation?
did you try different material?
so, does it work when you convert from game obj?
nop
nothing work at all x)
URP ?
yeah it's urp
I FOUND IT
thanks all for your replies !
did you set your project to linear colour space?
nop
But the entire purpose is to schedule it from burst... if you dont schedule it from Burst, why even use ISystemBase? Which is why I'm using just standard SystemBase
New question how manage clipping mesh of entities because when my camera is too closest that's disappear
Yes? That's why I patched the IJobEntityBatch scheduling code to be burst compatible
so what was it?
ok, one thing I realised
there is no point doing UI with UI toolkit with dots rn
absolutely no compatibility in mind
I switched into 2021 too but
that's not what I mean
I just mean, that it's way too easier and better just do Monos
to control UI
rather than figuring out systems
how so?
like you are removing the need for monobehaviours and doing the exact same thing just better
I don't see any good solution for controlling UI through systems rn
you either need a lot of systems
or god system
yeah, and how do you avoid overhead of unnecessary systems?
why do you consider them unncessary
do you use 1 monobehaviour for all your UI panels?
or do you not have a Monobehaviour for inventory, a monobehaviour for menu etc
no
What I mean is that when you are in game
your main menu
is just not here
meanwhile system will check for it's query every time unless you override it somehow
i add up every single non-running UI system
and it adds to 0.00ms
on the profiler
like literally unprofilable
why is this an issue?
my entire UISystemGroup comes in at 0.01ms
where do you put it? near end of frame?
in presentationsystemgroup
uuugh, I don't quite remember where is it
ah
found it
hmm
could you share any example of your UI system?
pretty sure i posted it here the other day but
{
/// <inheritdoc/>
public override uint StateKey => Keys<UIStates>.NameToKey("menu");
/// <inheritdoc/>
public override ComponentType StateInstanceComponent { get; } = typeof(UIMenu);
/// <inheritdoc/>
protected override void OnLoad(VisualElement panel)
{
var playButton = panel.Q<Button>("play");
playButton.clicked += this.PlayButtonOnClicked;
}
private void PlayButtonOnClicked()
{
var uiState = this.GetSingleton<ClientState>();
uiState.Value = new BitArray256 { [Keys<ClientStates>.NameToKey("go-in-game")] = true };
this.SetSingleton(uiState);
}
private struct UIMenu : IComponentData
{
}
}```
Layer filters?
yah
Not too important, I know GameObject Land Unity has it
I think it might not be entities land
I can deny a trigger event with my own stuff, but denying the physics is trickier
Dots had extremely versatile layer filters in physics module
Two 32 size arrayd
To choose to what layer your entity belongs
And with what collides
Sometimes you want to collide with one layer but not a specific guy.
Its okay, I'll make do, ain't that big.
I was just inquiring.
and you can do that with dots
thats one of the huge advantage of dots physics
You have the BelongsTo, CollidesWith
but also
GroupIndex
GroupIndex int An override for the bit mask checks. If the value in both objects is equal and positive, the objects always collide. If the value in both objects is equal and negative, the objects never collide.
you can force certain colliders to always collide or never collide
regardless of the layers
looks handy, what's UISystemBase handling?
is this for MB or UIElements?
ah cool, I'm still on UnityUI. I'm thinking about making a jump to UIElements, thing is, I've even written a mobile app in UnityUI and I never had any issues really. Previously worked with NGUI and that had it's problems with scaling. What do you think are some huge pros of UIElements over UnityUI?
or, what do you like more about the approach?
much more performant for starters
(if you've ever tried to run ugui on consoles or even a lot of it on mobile you'll know how bad layouts are)
it's certainly draining too much battery for what it's doing, true
apart from that, it's just a much better framework to use imo
(obviously it's a bit rough atm)
(but just conceptually)
I need to look into it at some point how fast I can do a switch. It took quite a while to bring the whole app to UnityUI from NGUI and now I'd need a rewrite to UIElements. lol π
yeah it'd be pretty painful to rewrite
i'm mostly using it because i decided to use it from the start
what's the official state of UIElements for runtime? You say it works for 2021+?
it's called UIToolkit now and is built in to unity engine from 2021+
ah i see, totally not up-to-date π
are you using any UI designers?
UIToolkit seems like a generic layout, right?
thanks
Thanks guys, only about 5 hrs left on the ECS/DOTS then 10-30 hours finishin networking for my MMORPG engine to be tested via MOBA: https://www.youtube.com/watch?v=nAkNxFiGzKA
I Didn't Start the Baron & Other Music Video Disasters I Made! https://www.youtube.com/playlist?list=PLOQ-J23AJUfTlLHkmqqFQIS8_ewaSaCqx
StarfighterGeneral.com Bloopers, Bugs and Outtakes: https://www.youtube.com/playlist?list=PLOQ-J23AJUfSCeuHkKQtL1Al70iAWnbSO
Been #1 in the world at every online ladder video game I played even the highest sk...
Funniest shit I've ever seen!
ahah
well there's still a lot of stuff that UIElements needs to catch up
https://docs.unity3d.com/2021.2/Documentation/Manual/UI-system-compare.html
looks pretty good already, having no SDF texts is a breaking point though
guys i have question for "fun", compute shader in ECS not possible ?
what do you mean exactly? Like you can't use a Compute Shader in ecs?
Yeah
i tried
FindKernel in main thread
for me in my head "possible wrong",
ECS/DOTS Optimization CPU Multi-thread Parallelism etc...
Compute shader GPU calcul usage..
i know we can Instantiate(ComputeShader)
so why we cannot use it in jobs π’
When the compute shader executes, you're likely waiting for the compute shader to finish if you're trying to read the data back from the GPU
And i don't really want to do it on CPU with multi-thread it's useless in my case
@coarse turtle +1 yes exact
so unity's bindings probably don't have a good way to have a job thread wait on the GPU
No
F.A.C.K
real ?
I can to use the CPU or the GPU but not both?
whoaaa, no no i think we have solution
Are you dispatching the work via a command buffer?
yeah you are thinking for DispatchIndirect ?
i can try it in coroutines "DIRTY time"
thinking more GraphicsFence instead π€
of dispatch
it's been a while since I used those commands, so my memory is a bit fuzzy
ok ok not bad not bad
EntityCommandBuffers we are close but thanks you give me a way !
ExecuteCommandBufferAsync.
ah, i meant more CommandBuffer from the UnityRendering API. You can create a graphics fence and poll whether or not the operation has been "passed" in the GPU
OH will learn about this thanks *10 billion
Async? Just check whether it's finished instead
@rustic rain i was searching so i was out what i found at this time π
but thanks β€οΈ
How would you write sorting groups for sprites in custom sprite rendering system if sprites are entities and theirs shader properties are components? I am out of ideas of how to do it without dramatic sort timings. Please help, any advices π₯²
sorting for what?
Any tip on how to implement "settings"?
Persistent data basically
Should I hussle with entities or?
i personally bind all my settings to an entity but i'm not that opinionated on the best way to do, just how i do it
But this is my entire settings authoring setup.
{
[SerializeField]
private Settings[] settings;
void IDeclareReferencedPrefabs.DeclareReferencedPrefabs(List<GameObject> referencedPrefabs)
{
if (this.settings == null)
{
return;
}
foreach (var setting in this.settings)
{
if (setting == null)
{
Debug.LogWarning("Setting is null");
continue;
}
setting.DeclareReferencedPrefabs(referencedPrefabs);
}
}
/// <inheritdoc/>
void IConvertGameObjectToEntity.Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
if (this.settings == null)
{
return;
}
foreach (var setting in this.settings)
{
if (setting == null)
{
Debug.LogWarning("Setting is null");
continue;
}
conversionSystem.DeclareAssetDependency(this.gameObject, setting);
setting.Convert(entity, dstManager, conversionSystem);
}
}
}```
``` public abstract class Settings : ScriptableObject, ISettings
{
public virtual void DeclareReferencedPrefabs(List<GameObject> referencedPrefabs)
{
}
public abstract void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem);
}```
basically just a collection of scriptable objects that self convert themselves to their various representation
but i have a few tools on top like a single searchable UI window that auto populates itself from these ISettings
making them entities has some advantage though - some of my settings are marked as Ghosts in netcode so I can send them from server to client if the server wants to make changes or player want to load mods etc
I need the amount of entities, CalculateEntityCount(), but I need a query for that. I have a Entities.WithAll<RandomComponents>().ForEach() and need the amount right before the ForEach - how can I achieve this?
I made it now like this, I hope this is right?
var entityCount = GetEntityQuery(ComponentType.ReadOnly<ReplayIdentifier>()).CalculateEntityCount();
Entities.ForEach
(
(
Entity entity,
in ReplayIdentifier replayIdentifier
) =>
{
}
)
that would work fine as long as you're queries matched. it's a bit safer if you just get your query out from the entities foreach though
this.Entities.ForEach(() => {}).WithStoreEntityQueryInField(ref _query).ScheduleParallel()
thank you π
on the side note... who does that with brackets?! for the moment I thought that wasn't even c#
at work this is the style guide, we need to split it up like this for better readability - don't ask me why it is like this, it was decided before my time:)
yeah I was wondering if that's a company issue because it's look so ridiculous that no sane human wouldn't subject himself to this π
Do you consider it a help in readability?
I'm asking because of course all style guides are just learned and are subjective
I mean, I am already used to it and know exactly where I have to look at what, so yes it is a help since everyone at work uses this style guide (obv thats what they are used for). this would be a bigger example:
Entities
.WithoutBurst()
.WithAll<ABC>()
.WithAll<BCD>()
.WithNone<XYZ>()
.ForEach
(
(
Entity entity,
in Stuff stuff,
ref OtherStuff otherStuff,
ref NoStuff noStuff
) =>
{
// stuff
// very much code
}
)
.Run();
But it is ||a pain in the ass|| (tedious) to format it like that xD
can't you setup your IDE to do that for you?
Probably yes, never done this before π€·ββοΈ
sorting sprites to render in proper order. Most commonly sprites with greater y and x coordinates renders first. But there is also sorting groups in unity, when sprites can be nested, so they goes with it's parent and only sorts with other children.
uuugh, there's render queue for shaders for this kind of thing
render queue is only for whole shader, but not for particular entity, isn't it?
you have your own renderer?
yes
you might want to just add property for render order
instead of sorting
some comp that defines what render layer this entity belongs to
this is not what i'm talking about. I'm about case when N of your sprites has same order value and needed to be sorted by it's positions, like N characters, you want to sort your characters depending on it's positions on screen every frame
how many entities are you sorting?
since we are in dots i want to sort as many as possible, but talking realistically without "sorting groups" problem i'm able to render ~60k sprites with 60fps, but after i've implemented sorting groups with simple SelectionSort O(n^2) then performance is terrible. obviously.
also for my needs it is about few thousands of sprites, not more
im thinking spatial queries and determining which entity is in view of the camera would help limit the sort space
