-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSplineGenerator.cs
More file actions
347 lines (286 loc) · 11.5 KB
/
SplineGenerator.cs
File metadata and controls
347 lines (286 loc) · 11.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
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(LineRenderer))]
[ExecuteInEditMode]
public class SplineGenerator : MonoBehaviour
{
public GameObject splinePrefab;
public LineRenderer controlPointsLineRenderer; // Source LineRenderer for control points
public LineRenderer splineLineRenderer; // Destination LineRenderer for displaying the spline
//[SerializeField] //uncomment this to show in the inspector
private bool showLines = true;
[Header("Disable script when finished.")]
public bool updateSpline = false;
public bool loop = false;
private bool spawnPerpendicularSpline = false;
private int moveChild = 0;
[Range(-1,1)]
private int setPosition = 0;
private int childLine = 0;
private List<GameObject> instance;
private List<int> instancePos = new List<int>();
[Header("Spline Controls")]
[Range(1,30)]
public int sampleRate = 10; // Determines the number of interpolated points
[Range(0, 1)]
public float smoothness = 0.5f;
public bool equaldistant = false;
[Range(-1, 1)]
//[SerializeField] //uncomment this to show in the inspector
private float tension = 0; //makes the line ugly
[Header("Click the edit icon in Line Renderer > Scene Tools to edit point positions.")]
[Min(3)]
public int positions = 3;
private void OnValidate()
{
if(positions < controlPointsLineRenderer.positionCount)
{
controlPointsLineRenderer.positionCount = positions;
clearSpline();
}
if(positions > controlPointsLineRenderer.positionCount)
{
addPosition();
}
DrawSpline();
if (updateSpline)
{
updateSpline = false;
}
if (spawnPerpendicularSpline)
{
createTheChild();
}
else
{
for (int i = 0; i < instance.Count; i++)
{
Debug.Log("setPos");
if (instancePos[i] > 0 && instancePos[i] <= positions)
{
instance[i].transform.position = getPosition(instancePos[i]);
}
else if (instancePos[i] <= 0)
{
instancePos[i] = 0;
}
else
{
instancePos[i] = positions;
}
}
}
}
void createTheChild()
{
Vector3 newPos = getPosition(setPosition);
instance.Add(Instantiate(splinePrefab, newPos, Quaternion.identity));
Debug.Log(instance.Count);
instance[instance.Count - 1].transform.parent = gameObject.transform;
instance[instance.Count - 1].transform.Rotate(0, 90, 0, Space.Self);
instancePos.Add(setPosition);
spawnPerpendicularSpline = false;
}
void OnEnable()
{
if (controlPointsLineRenderer.enabled != true)
{
controlPointsLineRenderer.enabled = true;
}
if (splineLineRenderer.enabled != true)
{
splineLineRenderer.enabled = true;
}
DrawSpline();
}
private void OnDisable()
{
controlPointsLineRenderer.enabled = false;
splineLineRenderer.enabled = false;
}
[ContextMenu("Add Point")]
private void addPosition()
{
// Ensure the LineRenderer component is retrieved.
controlPointsLineRenderer = GetComponent<LineRenderer>();
if (controlPointsLineRenderer == null)
{
Debug.LogError("LineRenderer component not found on the object!");
return;
}
// Get the current number of points in the LineRenderer.
positions = controlPointsLineRenderer.positionCount;
var location = controlPointsLineRenderer.GetPosition(positions - 1);
location = calculatePosition(positions);
var newPoint = positions + 1;
controlPointsLineRenderer.positionCount = newPoint;
controlPointsLineRenderer.SetPosition(positions, location);
positions = newPoint;
}
private Vector3 getPosition(int pos)
{
// Ensure the LineRenderer component is retrieved.
controlPointsLineRenderer = GetComponent<LineRenderer>();
if (controlPointsLineRenderer == null)
{
Debug.LogError("LineRenderer component not found on the object!");
return Vector3.zero;
}
// Get the current number of points in the LineRenderer.
positions = controlPointsLineRenderer.positionCount;
var location = controlPointsLineRenderer.GetPosition(pos - 1);
return location;
}
private Vector3 calculatePosition(int currentPositionsCount)
{
if (currentPositionsCount < 3)
{
return controlPointsLineRenderer.GetPosition(currentPositionsCount - 1);
}
Vector3 a = controlPointsLineRenderer.GetPosition(currentPositionsCount - 1);
Vector3 b = controlPointsLineRenderer.GetPosition(currentPositionsCount - 2);
Vector3 location = a - (b - a);
return location;
}
[ContextMenu("Clear Spline")]
private void clearSpline()
{
splineLineRenderer.GetComponent<LineRenderer>().positionCount = 1;
}
[ContextMenu("RenderSpline")]
void DrawSpline()
{
if (controlPointsLineRenderer == null)
controlPointsLineRenderer = GetComponent<LineRenderer>();
// Ensure the spline LineRenderer is assigned, otherwise disable the script
if (splineLineRenderer == null)
{
Debug.LogError("Please assign a second LineRenderer for the spline output.");
enabled = false;
return;
}
if (controlPointsLineRenderer.positionCount < 2) return;
Vector3[] controlPoints = new Vector3[controlPointsLineRenderer.positionCount];
controlPointsLineRenderer.GetPositions(controlPoints);
if (loop)
{
List<Vector3> controlVectors = convertToList(controlPoints);
controlVectors.Add(controlPoints[0]);
controlPoints = controlVectors.ToArray();
}
Vector3[] splinePoints = bestFit(controlPoints, smoothness);
if (equaldistant) { splinePoints = CatmullRomInterpolateEqually(controlPoints, sampleRate, tension); } else
{
splinePoints = CatmullRomInterpolate(controlPoints, sampleRate, tension);
}
splineLineRenderer.positionCount = splinePoints.Length;
splineLineRenderer.SetPositions(splinePoints);
}
private List<Vector3> convertToList(Vector3[] vectorArray)
{
List<Vector3> pos = new List<Vector3>();
for (int i = 0; i < vectorArray.Length; i++)
{
pos.Add(vectorArray[i]);
}
return pos;
}
private Vector3[] CatmullRomInterpolate(Vector3[] pts, int sampleRate, float tension = 0.0f)
{
int numPoints = (pts.Length - 1) * sampleRate + 1; // Ensure we include last point
Vector3[] res = new Vector3[numPoints];
int resIndex = 0;
for (int j = 0; j < pts.Length - 1; j++)
{
for (int i = 0; i < sampleRate; i++)
{
float t = (float)i / sampleRate;
Vector3 p0 = pts[j == 0 ? 0 : j - 1];
Vector3 p1 = pts[j];
Vector3 p2 = pts[j + 1];
Vector3 p3 = (j + 2 < pts.Length) ? pts[j + 2] : pts[j + 1];
Vector3 position = CatmullRomPosition(p0, p1, p2, p3, t, tension);
res[resIndex++] = position;
}
}
// Explicitly set the last position to the last point for accuracy
res[resIndex] = pts[pts.Length - 1];
return res;
}
private Vector3[] CatmullRomInterpolateEqually(Vector3[] pts, int sampleRate, float tension = 0.0f)
{
// 1. Sample spline at high resolution for arc length approx
int highSampleRate = 50; // You can tweak this (the higher, the more accurate)
List<Vector3> highResPoints = new List<Vector3>();
for (int j = 0; j < pts.Length - 1; j++)
{
for (int i = 0; i < highSampleRate; i++)
{
float t = (float)i / highSampleRate;
Vector3 p0 = pts[j == 0 ? 0 : j - 1];
Vector3 p1 = pts[j];
Vector3 p2 = pts[j + 1];
Vector3 p3 = (j + 2 < pts.Length) ? pts[j + 2] : pts[j + 1];
highResPoints.Add(CatmullRomPosition(p0, p1, p2, p3, t, tension));
}
}
highResPoints.Add(pts[pts.Length - 1]); // Ensure last point
// 2. Compute cumulative length along the highResPoints
float[] cumLength = new float[highResPoints.Count];
cumLength[0] = 0f;
for (int i = 1; i < highResPoints.Count; i++)
{
cumLength[i] = cumLength[i - 1] + Vector3.Distance(highResPoints[i - 1], highResPoints[i]);
}
float totalLength = cumLength[cumLength.Length - 1];
if (totalLength < 0.0001f) return highResPoints.ToArray();
// 3. Re-sample at uniformly spaced length intervals
Vector3[] result = new Vector3[sampleRate];
for (int i = 0; i < sampleRate; i++)
{
float targetLen = ((float)i / (sampleRate - 1)) * totalLength; // desired distance
// Find where this length fits in cumulative array
int k = Array.FindIndex(cumLength, l => l >= targetLen);
if (k == -1) // Shouldnt occur, but for safety
result[i] = highResPoints[highResPoints.Count - 1];
else if (k == 0)
result[i] = highResPoints[0];
else
{
// Interpolate between highResPoints[k-1] and highResPoints[k]
float segmentLen = cumLength[k] - cumLength[k - 1];
if (segmentLen <= 0.0001f)
result[i] = highResPoints[k];
else
{
float segmentT = (targetLen - cumLength[k - 1]) / segmentLen;
result[i] = Vector3.Lerp(highResPoints[k - 1], highResPoints[k], segmentT);
}
}
}
return result;
}
// Calculate the Catmull-Rom position
private Vector3 CatmullRomPosition(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t, float tension)
{
float tau = 0.5f * (1.0f - tension); // Adjust tau based on tension; default Catmull-Rom has tau=0.5
Vector3 a = -tau * p0 + (2.0f - tau) * p1 + (tau - 2.0f) * p2 + tau * p3;
Vector3 b = 2.0f * tau * p0 + (tau - 3.0f) * p1 + (3.0f - 2.0f * tau) * p2 - tau * p3;
Vector3 c = -tau * p0 + tau * p2;
Vector3 d = p1;
return a * t * t * t + b * t * t + c * t + d;
}
private Vector3[] bestFit(Vector3[] pts, float smoothness)
{
Vector3[] avg = pts;
for(int i = 1; i < pts.Length-1; i++)
{
Vector3 a = Vector3.Lerp(pts[i - 1], pts[i], smoothness);
Vector3 b = Vector3.Lerp(pts[i + 1], pts[i], smoothness);
avg[i] = Vector3.Lerp(a, b, smoothness);
}
return avg;
}
}