forked from oculus-samples/Unity-CrypticCabinet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRope.cs
More file actions
444 lines (360 loc) · 15.6 KB
/
Rope.cs
File metadata and controls
444 lines (360 loc) · 15.6 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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
// Copyright (c) Meta Platforms, Inc. and affiliates.
using System;
using CrypticCabinet.Utils;
using Fusion;
using UnityEngine;
namespace CrypticCabinet.Puzzles.SandPuzzle
{
/// <summary>
/// Describes the rope for the sand puzzle.
/// Based on: https://github.com/GaryMcWhorter/Verlet-Chain-Unity
/// </summary>
public class Rope : NetworkBehaviour
{
[Header("Verlet Parameters")]
[SerializeField, Tooltip("The distance between each link in the chain")]
private float m_nodeDistance = 0.35f;
[SerializeField, Tooltip("The radius of the sphere collider used for each chain link")]
private float m_nodeColliderRadius = 0.2f;
[SerializeField, Tooltip("Works best with a lower value")]
private float m_gravityStrength = 2;
[SerializeField, Tooltip("The number of chain links. Decreases performance with high values and high iteration")]
private int m_totalNodes = 100;
[SerializeField, Range(0, 1), Tooltip("Modifier to dampen velocity so the simulation can stabilize")]
private float m_velocityDampen = 0.95f;
[SerializeField, Range(0, 0.99f),
Tooltip("The stiffness of the simulation. Set to lower values for more elasticity")]
private float m_stiffness = 0.8f;
[SerializeField,
Tooltip("Setting this will test collisions for every n iterations. Possibly more performance but less stable collisions")]
private int m_iterateCollisionsEvery = 1;
[SerializeField, Tooltip("Iterations for the simulation. More iterations is more expensive but more stable")]
private int m_iterations = 100;
[SerializeField, Tooltip("How many colliders to test against for every node.")]
private int m_colliderBufferSize = 1;
[SerializeField] private LayerMask m_layerMask;
[SerializeField] private Transform m_startHandle;
private Collider[] m_colliderHitBuffer;
private Vector3 m_gravity;
private Vector3 m_startLock;
private Vector3 m_endLock;
[Space]
private Vector3[] m_previousNodePositions;
private Vector3[] m_currentNodePositions;
private Quaternion[] m_currentNodeRotations;
private SphereCollider m_nodeCollider;
private GameObject m_nodeTester;
[SerializeField] private Transform[] m_meshNodes = Array.Empty<Transform>();
[SerializeField] private float m_ropeFlutterMultiplier = 0.01f;
[SerializeField] private float m_ropeFlutterChangeSpeed = 0.5f;
[SerializeField] private float m_meshNodeGap = 0.2f;
private Vector3[] m_evenlySpacedLocations;
[SerializeField] private int m_evenlySpacedBufferSized = 100;
private int m_spacedLocationCount;
[Networked]
public bool AddWeightToEnd { get; set; }
[SerializeField] private float m_weightValue = 2;
[SerializeField] private float m_interpolationSpeed = 10f;
[Serializable]
private struct GrabData : INetworkStruct
{
public int Index;
public Vector3 WorldPos;
}
private const int MAX_GRABS = 2;
[Networked, Capacity(2)]
private NetworkArray<GrabData> Grabs { get; } = MakeInitializer(new GrabData[MAX_GRABS]);
public override void Spawned()
{
base.Spawned();
for (var i = 0; i < Grabs.Length; i++)
{
var grabData = Grabs[i];
grabData.Index = -1;
_ = Grabs.Set(i, grabData);
}
m_evenlySpacedLocations = new Vector3[m_evenlySpacedBufferSized];
m_currentNodePositions = new Vector3[m_totalNodes];
m_previousNodePositions = new Vector3[m_totalNodes];
m_currentNodeRotations = new Quaternion[m_totalNodes];
m_colliderHitBuffer = new Collider[m_colliderBufferSize];
m_gravity = new Vector3(0, -m_gravityStrength, 0);
// using a single dynamically created GameObject to test collisions on every node
m_nodeTester = new GameObject { name = "Node Tester", layer = 8 };
m_nodeCollider = m_nodeTester.AddComponent<SphereCollider>();
m_nodeCollider.radius = m_nodeColliderRadius;
m_meshNodeGap = Mathf.Max(m_meshNodeGap, 0.001f);
Reset();
}
public void Reset()
{
m_startLock = m_startHandle.position;
var stiffnessDiff = (1 - m_stiffness) * m_nodeDistance * m_totalNodes;
var position = m_startLock + Vector3.down * stiffnessDiff;
for (var i = 0; i < m_totalNodes; i++)
{
m_currentNodePositions[i] = position;
m_currentNodeRotations[i] = Quaternion.identity;
m_previousNodePositions[i] = position;
position.y -= m_nodeDistance;
}
UpdateMeshVisuals(1);
}
private void Update()
{
m_startLock = m_startHandle.position;
m_gravity = new Vector3(0, -m_gravityStrength, 0);
m_meshNodeGap = Mathf.Max(m_meshNodeGap, 0.001f);
UpdateMeshVisuals(Time.deltaTime * m_interpolationSpeed);
}
private void UpdateMeshVisuals(float interpRatio)
{
m_spacedLocationCount = 0;
m_evenlySpacedLocations[m_spacedLocationCount] = m_startLock;
m_spacedLocationCount++;
float rollOver = 0;
for (var i = -1; i < m_currentNodePositions.Length - 1; i++)
{
var start = m_startLock;
if (i >= 0)
{
start = m_currentNodePositions[i];
}
var end = m_currentNodePositions[i + 1];
var dist = Vector3.Distance(start, end);
var totalDist = dist + rollOver;
if (totalDist < m_meshNodeGap)
{
rollOver = totalDist;
continue;
}
var direction = (end - start).normalized;
var current = m_meshNodeGap - rollOver;
m_evenlySpacedLocations[m_spacedLocationCount] = Vector3.Lerp(m_evenlySpacedLocations[m_spacedLocationCount], start + direction * current, interpRatio);
m_spacedLocationCount++;
while (current + m_meshNodeGap < dist)
{
current += m_meshNodeGap;
m_evenlySpacedLocations[m_spacedLocationCount] = Vector3.Lerp(m_evenlySpacedLocations[m_spacedLocationCount], start + direction * current, interpRatio);
m_spacedLocationCount++;
}
rollOver = dist - current;
}
var loopCount = Mathf.Min(m_meshNodes.Length, m_spacedLocationCount);
for (var i = 0; i < loopCount; i++)
{
m_meshNodes[i].position = Vector3.Lerp(m_meshNodes[i].position, m_evenlySpacedLocations[m_spacedLocationCount - i - 1], interpRatio);
}
if (m_meshNodes.Length > m_spacedLocationCount)
{
for (var i = m_spacedLocationCount; i < m_meshNodes.Length; i++)
{
m_meshNodes[i].position = Vector3.Lerp(m_meshNodes[i].position, m_evenlySpacedLocations[0], interpRatio);
}
}
for (var i = 0; i < loopCount - 2; i++)
{
m_meshNodes[i].LookAt(m_meshNodes[i + 1]);
m_meshNodes[i].RotateAround(m_meshNodes[i].position, m_meshNodes[i].right, 270);
}
m_meshNodes[^1].rotation = m_meshNodes[^2].rotation = m_meshNodes[^3].rotation;
}
private void FixedUpdate()
{
Simulate();
for (var i = 0; i < m_iterations; i++)
{
ApplyConstraint();
if (i % m_iterateCollisionsEvery == 0)
{
AdjustCollisions();
}
}
SetAngles();
}
public Vector3 NearestPointOnRope(Vector3 queryPoint)
{
var currentMax = float.MaxValue;
var currentPoint = Vector3.zero;
for (var i = 0; i < m_currentNodePositions.Length - 1; i++)
{
var calculatedPoint = MathsUtils.NearestPointOnLineSegment(
m_currentNodePositions[i], m_currentNodePositions[i + 1], queryPoint);
var calculatedDistSquare = (calculatedPoint - queryPoint).sqrMagnitude;
if (calculatedDistSquare < currentMax)
{
currentMax = calculatedDistSquare;
currentPoint = calculatedPoint;
}
}
return currentPoint;
}
public int GrabRopeAtPoint(Vector3 queryPoint)
{
var currentMax = float.MaxValue;
var currentIndex = -1;
for (var i = 0; i < m_currentNodePositions.Length - 1; i++)
{
var calculatedPoint = MathsUtils.NearestPointOnLineSegment(
m_currentNodePositions[i], m_currentNodePositions[i + 1], queryPoint);
var calculatedDistSquare = (calculatedPoint - queryPoint).sqrMagnitude;
if (calculatedDistSquare < currentMax)
{
currentMax = calculatedDistSquare;
currentIndex = i;
}
}
for (var i = 0; i < Grabs.Length; i++)
{
var grabData = Grabs[i];
if (grabData.Index == -1)
{
grabData.Index = currentIndex;
grabData.WorldPos = queryPoint;
_ = Grabs.Set(i, grabData);
return currentIndex;
}
}
// failed to save the grab information so should return as failed.
return -1;
}
public void ReleaseRope(int index)
{
for (var i = 0; i < Grabs.Length; i++)
{
var grabData = Grabs[i];
if (grabData.Index == index)
{
grabData.Index = -1;
_ = Grabs.Set(i, grabData);
return;
}
}
}
public void UpdateGrabbedRope(int index, Vector3 pos)
{
for (var i = 0; i < Grabs.Length; i++)
{
var grabData = Grabs[i];
if (grabData.Index == index)
{
grabData.WorldPos = pos;
_ = Grabs.Set(i, grabData);
return;
}
}
}
private void Simulate()
{
var fixedDt = Time.fixedDeltaTime;
for (var i = 0; i < m_totalNodes; i++)
{
var velocity = m_currentNodePositions[i] - m_previousNodePositions[i];
velocity *= m_velocityDampen;
m_previousNodePositions[i] = m_currentNodePositions[i];
// calculate new position
var newPos = m_currentNodePositions[i] + velocity;
newPos += m_gravity * fixedDt;
newPos.x += (Mathf.PerlinNoise(0, Time.time * m_ropeFlutterChangeSpeed) - 0.5f) *
m_ropeFlutterMultiplier;
newPos.z += (Mathf.PerlinNoise(Time.time * m_ropeFlutterChangeSpeed, 0) - 0.5f) *
m_ropeFlutterMultiplier;
m_currentNodePositions[i] = newPos;
}
if (AddWeightToEnd)
{
for (var i = 0; i < m_totalNodes - 1; i++)
{
var pos = m_currentNodePositions[i];
var direction = m_currentNodePositions[i + 1] - m_previousNodePositions[i];
pos += direction.normalized * (m_weightValue * fixedDt);
m_currentNodePositions[i] = pos;
}
}
}
private void AdjustCollisions()
{
for (var i = 0; i < m_totalNodes; i++)
{
if (i % 2 == 0) continue;
var result = Physics.OverlapSphereNonAlloc(
m_currentNodePositions[i], m_nodeColliderRadius + 0.01f, m_colliderHitBuffer, m_layerMask.value,
QueryTriggerInteraction.Ignore);
for (var n = 0; n < result; n++)
{
var colliderPosition = m_colliderHitBuffer[n].transform.position;
var colliderRotation = m_colliderHitBuffer[n].gameObject.transform.rotation;
_ = Physics.ComputePenetration(
m_nodeCollider, m_currentNodePositions[i], Quaternion.identity, m_colliderHitBuffer[n],
colliderPosition, colliderRotation, out var dir, out var distance);
m_currentNodePositions[i] += dir * distance;
}
}
}
private void ApplyConstraint()
{
m_currentNodePositions[0] = m_startLock;
foreach (var grabData in Grabs)
{
if (grabData.Index >= 0)
{
m_currentNodePositions[grabData.Index] = grabData.WorldPos;
}
}
for (var i = 0; i < m_totalNodes - 1; i++)
{
var node1 = m_currentNodePositions[i];
var node2 = m_currentNodePositions[i + 1];
// Get the current distance between rope nodes
var currentDistance = (node1 - node2).magnitude;
var difference = Mathf.Abs(currentDistance - m_nodeDistance);
var direction = Vector3.zero;
// determine what direction we need to adjust our nodes
if (currentDistance > m_nodeDistance)
{
direction = (node1 - node2).normalized;
}
else if (currentDistance < m_nodeDistance)
{
direction = (node2 - node1).normalized;
}
// calculate the movement vector
var movement = direction * difference;
// apply correction
m_currentNodePositions[i] -= movement * m_stiffness;
m_currentNodePositions[i + 1] += movement * m_stiffness;
}
}
private void SetAngles()
{
for (var i = 0; i < m_totalNodes - 1; i++)
{
var node1 = m_currentNodePositions[i];
var node2 = m_currentNodePositions[i + 1];
var dir = (node2 - node1).normalized;
if (dir != Vector3.zero)
{
if (i > 0)
{
var desiredRotation = Quaternion.LookRotation(dir, Vector3.right);
m_currentNodeRotations[i + 1] = desiredRotation;
}
else if (i < m_totalNodes - 1)
{
var desiredRotation = Quaternion.LookRotation(dir, Vector3.right);
m_currentNodeRotations[i + 1] = desiredRotation;
}
else
{
var desiredRotation = Quaternion.LookRotation(dir, Vector3.right);
m_currentNodeRotations[i] = desiredRotation;
}
}
if (i % 2 == 0 && i != 0)
{
m_currentNodeRotations[i + 1] *= Quaternion.Euler(0, 0, 90);
}
}
}
}
}