forked from Unity-Technologies/EntityComponentSystemSamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMousePickBehaviour.cs
More file actions
349 lines (291 loc) · 13.5 KB
/
Copy pathMousePickBehaviour.cs
File metadata and controls
349 lines (291 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
using System;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Physics;
using Unity.Physics.Systems;
using Unity.Transforms;
using UnityEngine;
using UnityEngine.Assertions;
using static Unity.Physics.Math;
namespace Unity.Physics.Extensions
{
// A mouse pick collector which stores every hit. Based off the ClosestHitCollector
[BurstCompile]
public struct MousePickCollector : ICollector<RaycastHit>
{
public bool IgnoreTriggers;
public NativeArray<RigidBody> Bodies;
public int NumDynamicBodies;
public bool EarlyOutOnFirstHit => false;
public float MaxFraction { get; private set; }
public int NumHits { get; private set; }
private RaycastHit m_ClosestHit;
public RaycastHit Hit => m_ClosestHit;
public MousePickCollector(float maxFraction, NativeArray<RigidBody> rigidBodies, int numDynamicBodies)
{
m_ClosestHit = default(RaycastHit);
MaxFraction = maxFraction;
NumHits = 0;
IgnoreTriggers = true;
Bodies = rigidBodies;
NumDynamicBodies = numDynamicBodies;
}
#region ICollector
public bool AddHit(RaycastHit hit)
{
Assert.IsTrue(hit.Fraction < MaxFraction);
var isAcceptable = (hit.RigidBodyIndex >= 0) && (hit.RigidBodyIndex < NumDynamicBodies);
if (IgnoreTriggers)
{
isAcceptable = isAcceptable && hit.Material.CollisionResponse != CollisionResponsePolicy.RaiseTriggerEvents;
}
if (!isAcceptable)
{
return false;
}
MaxFraction = hit.Fraction;
m_ClosestHit = hit;
NumHits = 1;
return true;
}
#endregion
}
public struct MousePick : IComponentData
{
public int IgnoreTriggers;
}
public class MousePickBehaviour : MonoBehaviour, IConvertGameObjectToEntity
{
public bool IgnoreTriggers = true;
void IConvertGameObjectToEntity.Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
dstManager.AddComponentData(entity, new MousePick()
{
IgnoreTriggers = IgnoreTriggers ? 1 : 0,
});
}
}
// Attaches a virtual spring to the picked entity
[UpdateInGroup(typeof(SimulationSystemGroup))]
public class MousePickSystem : SystemBase
{
const float k_MaxDistance = 100.0f;
EntityQuery m_MouseGroup;
BuildPhysicsWorld m_BuildPhysicsWorldSystem;
public NativeArray<SpringData> SpringDatas;
public JobHandle? PickJobHandle;
public struct SpringData
{
public Entity Entity;
public int Dragging; // bool isn't blittable
public float3 PointOnBody;
public float MouseDepth;
}
[BurstCompile]
struct Pick : IJob
{
[ReadOnly] public CollisionWorld CollisionWorld;
[ReadOnly] public int NumDynamicBodies;
public NativeArray<SpringData> SpringData;
public RaycastInput RayInput;
public float Near;
public float3 Forward;
[ReadOnly] public bool IgnoreTriggers;
public void Execute()
{
var mousePickCollector = new MousePickCollector(1.0f, CollisionWorld.Bodies, NumDynamicBodies);
mousePickCollector.IgnoreTriggers = IgnoreTriggers;
CollisionWorld.CastRay(RayInput, ref mousePickCollector);
if (mousePickCollector.MaxFraction < 1.0f)
{
float fraction = mousePickCollector.Hit.Fraction;
RigidBody hitBody = CollisionWorld.Bodies[mousePickCollector.Hit.RigidBodyIndex];
MTransform bodyFromWorld = Inverse(new MTransform(hitBody.WorldFromBody));
float3 pointOnBody = Mul(bodyFromWorld, mousePickCollector.Hit.Position);
SpringData[0] = new SpringData
{
Entity = hitBody.Entity,
Dragging = 1,
PointOnBody = pointOnBody,
MouseDepth = Near + math.dot(math.normalize(RayInput.End - RayInput.Start), Forward) * fraction * k_MaxDistance,
};
}
else
{
SpringData[0] = new SpringData
{
Dragging = 0
};
}
}
}
public MousePickSystem()
{
SpringDatas = new NativeArray<SpringData>(1, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
SpringDatas[0] = new SpringData();
}
protected override void OnCreate()
{
m_BuildPhysicsWorldSystem = World.GetOrCreateSystem<BuildPhysicsWorld>();
m_MouseGroup = GetEntityQuery(new EntityQueryDesc
{
All = new ComponentType[] { typeof(MousePick) }
});
}
protected override void OnDestroy()
{
SpringDatas.Dispose();
}
protected override void OnUpdate()
{
if (m_MouseGroup.CalculateEntityCount() == 0)
{
return;
}
var handle = JobHandle.CombineDependencies(Dependency, m_BuildPhysicsWorldSystem.GetOutputDependency());
if (Input.GetMouseButtonDown(0) && (Camera.main != null))
{
Vector2 mousePosition = Input.mousePosition;
UnityEngine.Ray unityRay = Camera.main.ScreenPointToRay(mousePosition);
var mice = m_MouseGroup.ToComponentDataArray<MousePick>(Allocator.TempJob);
var IgnoreTriggers = mice[0].IgnoreTriggers != 0;
mice.Dispose();
// Schedule picking job, after the collision world has been built
handle = new Pick
{
CollisionWorld = m_BuildPhysicsWorldSystem.PhysicsWorld.CollisionWorld,
NumDynamicBodies = m_BuildPhysicsWorldSystem.PhysicsWorld.NumDynamicBodies,
SpringData = SpringDatas,
RayInput = new RaycastInput
{
Start = unityRay.origin,
End = unityRay.origin + unityRay.direction * k_MaxDistance,
Filter = CollisionFilter.Default,
},
Near = Camera.main.nearClipPlane,
Forward = Camera.main.transform.forward,
IgnoreTriggers = IgnoreTriggers,
}.Schedule(handle);
PickJobHandle = handle;
handle.Complete(); // TODO.ma figure out how to do this properly...we need a way to make physics sync wait for
// any user jobs that touch the component data, maybe a JobHandle LastUserJob or something that the user has to set
}
if (Input.GetMouseButtonUp(0))
{
SpringDatas[0] = new SpringData();
}
Dependency = handle;
}
}
// Applies any mouse spring as a change in velocity on the entity's motion component
[UpdateInGroup(typeof(FixedStepSimulationSystemGroup))]
[UpdateBefore(typeof(BuildPhysicsWorld))]
public class MouseSpringSystem : SystemBase
{
EntityQuery m_MouseGroup;
MousePickSystem m_PickSystem;
protected override void OnCreate()
{
m_PickSystem = World.GetOrCreateSystem<MousePickSystem>();
m_MouseGroup = GetEntityQuery(new EntityQueryDesc
{
All = new ComponentType[] { typeof(MousePick) }
});
}
protected override void OnUpdate()
{
if (m_MouseGroup.CalculateEntityCount() == 0)
{
return;
}
ComponentDataFromEntity<Translation> Positions = GetComponentDataFromEntity<Translation>(true);
ComponentDataFromEntity<Rotation> Rotations = GetComponentDataFromEntity<Rotation>(true);
ComponentDataFromEntity<PhysicsVelocity> Velocities = GetComponentDataFromEntity<PhysicsVelocity>();
ComponentDataFromEntity<PhysicsMass> Masses = GetComponentDataFromEntity<PhysicsMass>(true);
// If there's a pick job, wait for it to finish
if (m_PickSystem.PickJobHandle != null)
{
JobHandle.CombineDependencies(Dependency, m_PickSystem.PickJobHandle.Value).Complete();
}
// If there's a picked entity, drag it
MousePickSystem.SpringData springData = m_PickSystem.SpringDatas[0];
if (springData.Dragging != 0)
{
Entity entity = m_PickSystem.SpringDatas[0].Entity;
if (!EntityManager.HasComponent<PhysicsMass>(entity))
{
return;
}
PhysicsMass massComponent = Masses[entity];
PhysicsVelocity velocityComponent = Velocities[entity];
if (massComponent.InverseMass == 0)
{
return;
}
var worldFromBody = new MTransform(Rotations[entity].Value, Positions[entity].Value);
// Body to motion transform
var bodyFromMotion = new MTransform(Masses[entity].InertiaOrientation, Masses[entity].CenterOfMass);
MTransform worldFromMotion = Mul(worldFromBody, bodyFromMotion);
// Damp the current velocity
const float gain = 0.95f;
velocityComponent.Linear *= gain;
velocityComponent.Angular *= gain;
// Get the body and mouse points in world space
float3 pointBodyWs = Mul(worldFromBody, springData.PointOnBody);
float3 pointSpringWs = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, springData.MouseDepth));
// Calculate the required change in velocity
float3 pointBodyLs = Mul(Inverse(bodyFromMotion), springData.PointOnBody);
float3 deltaVelocity;
{
float3 pointDiff = pointBodyWs - pointSpringWs;
float3 relativeVelocityInWorld = velocityComponent.Linear + math.mul(worldFromMotion.Rotation, math.cross(velocityComponent.Angular, pointBodyLs));
const float elasticity = 0.1f;
const float damping = 0.5f;
deltaVelocity = -pointDiff * (elasticity / Time.DeltaTime) - damping * relativeVelocityInWorld;
}
// Build effective mass matrix in world space
// TODO how are bodies with inf inertia and finite mass represented
// TODO the aggressive damping is hiding something wrong in this code if dragging non-uniform shapes
float3x3 effectiveMassMatrix;
{
float3 arm = pointBodyWs - worldFromMotion.Translation;
var skew = new float3x3(
new float3(0.0f, arm.z, -arm.y),
new float3(-arm.z, 0.0f, arm.x),
new float3(arm.y, -arm.x, 0.0f)
);
// world space inertia = worldFromMotion * inertiaInMotionSpace * motionFromWorld
var invInertiaWs = new float3x3(
massComponent.InverseInertia.x * worldFromMotion.Rotation.c0,
massComponent.InverseInertia.y * worldFromMotion.Rotation.c1,
massComponent.InverseInertia.z * worldFromMotion.Rotation.c2
);
invInertiaWs = math.mul(invInertiaWs, math.transpose(worldFromMotion.Rotation));
float3x3 invEffMassMatrix = math.mul(math.mul(skew, invInertiaWs), skew);
invEffMassMatrix.c0 = new float3(massComponent.InverseMass, 0.0f, 0.0f) - invEffMassMatrix.c0;
invEffMassMatrix.c1 = new float3(0.0f, massComponent.InverseMass, 0.0f) - invEffMassMatrix.c1;
invEffMassMatrix.c2 = new float3(0.0f, 0.0f, massComponent.InverseMass) - invEffMassMatrix.c2;
effectiveMassMatrix = math.inverse(invEffMassMatrix);
}
// Calculate impulse to cause the desired change in velocity
float3 impulse = math.mul(effectiveMassMatrix, deltaVelocity);
// Clip the impulse
const float maxAcceleration = 250.0f;
float maxImpulse = math.rcp(massComponent.InverseMass) * Time.DeltaTime * maxAcceleration;
impulse *= math.min(1.0f, math.sqrt((maxImpulse * maxImpulse) / math.lengthsq(impulse)));
// Apply the impulse
{
velocityComponent.Linear += impulse * massComponent.InverseMass;
float3 impulseLs = math.mul(math.transpose(worldFromMotion.Rotation), impulse);
float3 angularImpulseLs = math.cross(pointBodyLs, impulseLs);
velocityComponent.Angular += angularImpulseLs * massComponent.InverseInertia;
}
// Write back velocity
Velocities[entity] = velocityComponent;
}
}
}
}