Skip to content

Commit 7354d6b

Browse files
author
CookieSalad
committed
Update UnityPhysicsSamples
Compatible with Unity Physics 0.5.1-preview.2
1 parent f571a65 commit 7354d6b

79 files changed

Lines changed: 2186 additions & 2900 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

UnityPhysicsSamples/Assets/Common/Scripts/CameraSmoothTrack.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,7 @@ protected override void OnUpdate()
8585

8686
PhysicsWorld world = m_BuildPhysicsWorld.PhysicsWorld;
8787

88-
var timestep = (float)m_RecordMostRecentFixedTime.MostRecentDeltaTime;
89-
var timeAhead = Time.DeltaTime / timestep;
88+
var timeAhead = (float)(Time.ElapsedTime - m_RecordMostRecentFixedTime.MostRecentElapsedTime);
9089

9190
Entities
9291
.WithName("SmoothlyTrackCameraTargetsJob")
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
using Unity.Entities;
2+
using UnityEngine;
3+
4+
// This class sets the upper limit of FPS of a demo that is being run.
5+
// It is used as a workaround for JobTempAlloc issues on CI and to make
6+
// measuring performance easier.
7+
public class InitializeSamplesSystem : SystemBase
8+
{
9+
protected override void OnCreate()
10+
{
11+
// Currently, JobTempAlloc is raised also when a job takes more than 4 frames to complete, independent of allocation.
12+
// Setting the target frame rate to 60 means giving each frame more time to complete, therefore the jobs would complete in less than 4 frames.
13+
// Also, since FPS will be lower, there will be more frames with physics in them making perf measurements easier.
14+
Application.targetFrameRate = 60;
15+
16+
// Disabling updates because the system has nothing to do in OnUpdate method
17+
Enabled = false;
18+
}
19+
20+
protected override void OnUpdate() {}
21+
}

UnityPhysicsSamples/Assets/Tests/JointTest/AngLimitDemo.cs.meta renamed to UnityPhysicsSamples/Assets/Common/Scripts/InitializeSamples.cs.meta

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

UnityPhysicsSamples/Assets/Common/Scripts/LifeTimeAuthoring.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using Unity.Collections;
22
using Unity.Entities;
3+
using Unity.Physics.Systems;
34
using UnityEngine;
45

56
public struct LifeTime : IComponentData
@@ -16,6 +17,8 @@ public void Convert(Entity entity, EntityManager dstManager, GameObjectConversio
1617
dstManager.AddComponentData(entity, new LifeTime { Value = Value });
1718
}
1819

20+
[UpdateInGroup(typeof(FixedStepSimulationSystemGroup))]
21+
[UpdateBefore(typeof(BuildPhysicsWorld))]
1922
public class LifeTimeSystem : SystemBase
2023
{
2124
protected override void OnUpdate()

UnityPhysicsSamples/Assets/Common/Scripts/RandomMotionAuthoring.cs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,11 @@ public void Convert(Entity entity, EntityManager dstManager, GameObjectConversio
4242
[UpdateBefore(typeof(BuildPhysicsWorld))]
4343
public class RandomMotionSystem : SystemBase
4444
{
45+
private BuildPhysicsWorld m_BuildPhysicsWorld;
46+
4547
protected override void OnCreate()
4648
{
49+
m_BuildPhysicsWorld = World.GetExistingSystem<BuildPhysicsWorld>();
4750
RequireForUpdate(GetEntityQuery(new EntityQueryDesc
4851
{
4952
All = new ComponentType[]
@@ -85,5 +88,6 @@ protected override void OnUpdate()
8588
velocity.Linear -= stepComponent.Gravity * deltaTime;
8689
}
8790
}).Schedule();
91+
m_BuildPhysicsWorld.AddInputDependency(Dependency);
8892
}
8993
}

UnityPhysicsSamples/Assets/Common/Scripts/RayTracer/RayTracer.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,12 +90,12 @@ void Update()
9090
ExpectingResults = false;
9191
}
9292

93-
if (BasePhysicsDemo.DefaultWorld == null)
93+
if (World.DefaultGameObjectInjectionWorld == null)
9494
{
9595
return;
9696
}
9797

98-
RayTracerSystem rbs = BasePhysicsDemo.DefaultWorld.GetExistingSystem<RayTracerSystem>();
98+
RayTracerSystem rbs = World.DefaultGameObjectInjectionWorld.GetExistingSystem<RayTracerSystem>();
9999
if (rbs == null || !rbs.IsEnabled)
100100
{
101101
return;

UnityPhysicsSamples/Assets/Common/Scripts/RayTracer/RayTracerSystem.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,9 @@ public unsafe void Execute(int index)
185185
}
186186
}
187187

188+
if (sphere.IsCreated)
189+
sphere.Dispose();
190+
188191
Results.EndForEachIndex();
189192
}
190193
}

UnityPhysicsSamples/Assets/Common/Scripts/BasePhysicsDemo.cs renamed to UnityPhysicsSamples/Assets/Common/Scripts/SceneCreationSystem.cs

Lines changed: 75 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -2,81 +2,100 @@
22
using System.Collections;
33
using System.Collections.Generic;
44
using System.Reflection;
5+
using Unity.Collections;
56
using Unity.Entities;
67
using Unity.Mathematics;
78
using Unity.Physics;
8-
using Unity.Physics.Authoring;
9-
using Unity.Physics.Extensions;
10-
using Unity.Physics.Systems;
119
using Unity.Rendering;
1210
using Unity.Transforms;
1311
using UnityEngine;
1412
using Collider = Unity.Physics.Collider;
1513
using Material = UnityEngine.Material;
1614
using Mesh = UnityEngine.Mesh;
1715

18-
/// <summary>
19-
/// Helper for demos set up in C# rather than in the editor
20-
/// </summary>
21-
public class BasePhysicsDemo : MonoBehaviour
16+
public abstract class SceneCreationSettings : IComponentData
2217
{
23-
public static World DefaultWorld => World.DefaultGameObjectInjectionWorld;
18+
public Material DynamicMaterial;
19+
public Material StaticMaterial;
20+
}
2421

25-
public static void ResetDefaultWorld()
26-
{
27-
DefaultWorld.EntityManager.CompleteAllJobs();
28-
foreach (var system in DefaultWorld.Systems)
29-
{
30-
system.Enabled = false;
31-
}
22+
public class SceneCreatedTag : IComponentData {};
3223

33-
DefaultWorld.Dispose();
34-
DefaultWorldInitialization.Initialize("Default World", false);
35-
}
3624

37-
public Material dynamicMaterial;
38-
public Material staticMaterial;
25+
// Base class of authoring components that create scene from code, using SceneCreationSystem
26+
public abstract class SceneCreationAuthoring<T> : MonoBehaviour, IConvertGameObjectToEntity
27+
where T : SceneCreationSettings, new()
28+
{
29+
public Material DynamicMaterial;
30+
public Material StaticMaterial;
3931

40-
protected void init()
32+
public virtual void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
4133
{
42-
// Load assets
43-
//dynamicMaterial = (Material)Resources.Load("Materials/PhysicsDynamicMaterial");
44-
//staticMaterial = (Material)Resources.Load("Materials/PhysicsStaticMaterial");
34+
T sceneSettings = new T
35+
{
36+
DynamicMaterial = DynamicMaterial,
37+
StaticMaterial = StaticMaterial
38+
};
39+
dstManager.AddComponentData(entity, sceneSettings);
4540
}
41+
}
42+
43+
[UpdateInGroup(typeof(InitializationSystemGroup))]
44+
public abstract class SceneCreationSystem<T> : SystemBase
45+
where T : SceneCreationSettings
46+
{
47+
private EntityQuery m_ScenesToCreateQuery;
48+
49+
protected Material DynamicMaterial;
50+
protected Material StaticMaterial;
51+
52+
public NativeList<BlobAssetReference<Collider>> CreatedColliders;
4653

47-
#if !UNITY_EDITOR
48-
void OnEnable()
54+
protected override void OnCreate()
4955
{
50-
Application.logMessageReceivedThreaded += HandleLogEntry;
56+
CreatedColliders = new NativeList<BlobAssetReference<Collider>>(Allocator.Persistent);
57+
58+
m_ScenesToCreateQuery = GetEntityQuery(new EntityQueryDesc
59+
{
60+
All = new ComponentType[] { typeof(T) },
61+
None = new ComponentType[] { typeof(SceneCreatedTag) },
62+
});
63+
RequireForUpdate(GetEntityQuery(new ComponentType[] { typeof(T) }));
5164
}
5265

53-
void HandleLogEntry(string logEntry, string stackTrace, LogType logType)
66+
protected override void OnUpdate()
5467
{
55-
if (logType == LogType.Exception)
68+
if (m_ScenesToCreateQuery.CalculateEntityCount() == 0) return;
69+
70+
using (var entities = m_ScenesToCreateQuery.ToEntityArray(Allocator.TempJob))
5671
{
57-
// Log exception and exit with non-zero error code
58-
UnityEngine.Debug.Log($"Caught an exception, exiting... \n {logEntry} \n {stackTrace}");
59-
Application.Quit(1);
72+
foreach (Entity entity in entities)
73+
{
74+
T settings = EntityManager.GetComponentObject<T>(entity);
75+
DynamicMaterial = settings.DynamicMaterial;
76+
StaticMaterial = settings.StaticMaterial;
77+
78+
CreateScene(settings);
79+
EntityManager.AddComponentData(entity, new SceneCreatedTag());
80+
}
6081
}
6182
}
6283

63-
void OnDisable()
84+
protected override void OnDestroy()
6485
{
65-
Application.logMessageReceivedThreaded -= HandleLogEntry;
66-
}
67-
68-
#endif
86+
foreach (var collider in CreatedColliders)
87+
{
88+
if (collider.IsCreated)
89+
collider.Dispose();
90+
}
6991

70-
protected virtual void Start()
71-
{
72-
init();
92+
CreatedColliders.Dispose();
7393
}
7494

75-
//
76-
// Object creation
77-
//
95+
public abstract void CreateScene(T sceneSettings);
96+
97+
#region Utilities
7898

79-
// TODO: add proper utility APIs for converting Collider into buffers usable for UnityEngine.Mesh and for drawing lines
8099
static readonly Type k_DrawComponent = typeof(Unity.Physics.Authoring.DisplayBodyColliders)
81100
.GetNestedType("DrawComponent", BindingFlags.NonPublic);
82101

@@ -88,7 +107,7 @@ protected virtual void Start()
88107
static readonly FieldInfo k_DisplayResultsMesh = k_DisplayResult.GetField("Mesh");
89108
static readonly PropertyInfo k_DisplayResultsTransform = k_DisplayResult.GetProperty("Transform");
90109

91-
internal static void CreateRenderMeshForCollider(
110+
public static void CreateRenderMeshForCollider(
92111
EntityManager entityManager, Entity entity, BlobAssetReference<Collider> collider, Material material
93112
)
94113
{
@@ -117,10 +136,10 @@ internal static void CreateRenderMeshForCollider(
117136
entityManager.AddComponentData(entity, new RenderBounds { Value = mesh.bounds.ToAABB() });
118137
}
119138

120-
Entity CreateBody(float3 position, quaternion orientation, BlobAssetReference<Collider> collider,
139+
public Entity CreateBody(float3 position, quaternion orientation, BlobAssetReference<Collider> collider,
121140
float3 linearVelocity, float3 angularVelocity, float mass, bool isDynamic)
122141
{
123-
var entityManager = DefaultWorld.EntityManager;
142+
var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
124143

125144
Entity entity = entityManager.CreateEntity(new ComponentType[] {});
126145

@@ -131,7 +150,7 @@ Entity CreateBody(float3 position, quaternion orientation, BlobAssetReference<Co
131150
var colliderComponent = new PhysicsCollider { Value = collider };
132151
entityManager.AddComponentData(entity, colliderComponent);
133152

134-
CreateRenderMeshForCollider(entityManager, entity, collider, isDynamic ? dynamicMaterial : staticMaterial);
153+
CreateRenderMeshForCollider(entityManager, entity, collider, isDynamic ? DynamicMaterial : StaticMaterial);
135154

136155
if (isDynamic)
137156
{
@@ -153,20 +172,20 @@ Entity CreateBody(float3 position, quaternion orientation, BlobAssetReference<Co
153172
return entity;
154173
}
155174

156-
protected Entity CreateStaticBody(float3 position, quaternion orientation, BlobAssetReference<Collider> collider)
175+
public Entity CreateStaticBody(float3 position, quaternion orientation, BlobAssetReference<Collider> collider)
157176
{
158177
return CreateBody(position, orientation, collider, float3.zero, float3.zero, 0.0f, false);
159178
}
160179

161-
protected Entity CreateDynamicBody(float3 position, quaternion orientation, BlobAssetReference<Collider> collider,
180+
public Entity CreateDynamicBody(float3 position, quaternion orientation, BlobAssetReference<Collider> collider,
162181
float3 linearVelocity, float3 angularVelocity, float mass)
163182
{
164183
return CreateBody(position, orientation, collider, linearVelocity, angularVelocity, mass, true);
165184
}
166185

167-
protected Entity CreateJoint(PhysicsJoint joint, Entity entityA, Entity entityB, bool enableCollision = false)
186+
public Entity CreateJoint(PhysicsJoint joint, Entity entityA, Entity entityB, bool enableCollision = false)
168187
{
169-
var entityManager = DefaultWorld.EntityManager;
188+
var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
170189
ComponentType[] componentTypes =
171190
{
172191
typeof(PhysicsConstrainedBodyPair),
@@ -180,11 +199,13 @@ protected Entity CreateJoint(PhysicsJoint joint, Entity entityA, Entity entityB,
180199
return jointEntity;
181200
}
182201

183-
protected RigidTransform GetBodyTransform(Entity entity)
202+
public static RigidTransform GetBodyTransform(Entity entity)
184203
{
185-
var entityManager = DefaultWorld.EntityManager;
204+
var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
186205
return new RigidTransform(
187206
entityManager.GetComponentData<Rotation>(entity).Value,
188207
entityManager.GetComponentData<Translation>(entity).Value);
189208
}
209+
210+
#endregion
190211
}

UnityPhysicsSamples/Assets/Common/Scripts/BasePhysicsDemo.cs.meta renamed to UnityPhysicsSamples/Assets/Common/Scripts/SceneCreationSystem.cs.meta

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

UnityPhysicsSamples/Assets/Common/Scripts/SpawnRandomObjectsAuthoring.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
using Unity.Collections;
33
using Unity.Entities;
44
using Unity.Mathematics;
5+
using Unity.Physics.Systems;
56
using Unity.Transforms;
67
using UnityEngine;
78

@@ -59,6 +60,8 @@ class SpawnRandomObjectsSystem : SpawnRandomObjectsSystemBase<SpawnSettings>
5960
{
6061
}
6162

63+
[UpdateInGroup(typeof(FixedStepSimulationSystemGroup))]
64+
[UpdateBefore(typeof(BuildPhysicsWorld))]
6265
abstract class SpawnRandomObjectsSystemBase<T> : SystemBase where T : struct, IComponentData, ISpawnSettings
6366
{
6467
internal virtual int GetRandomSeed(T spawnSettings)

0 commit comments

Comments
 (0)