JimYuan's Blog

Sharing the things I learned

0%

PhysicalSitmulationExample2

Physical Sitmalation

One big idea behind the physical simualtion is all the things inside computer is discrete. We should tranfer the smooth/ continuous real world into digit/ discrete/ finite computer language. Instead of having infinite elements(or atoms) in one rope, we are have finite amount of element.

rope

Code

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
private void RunScript(bool reset, Point3d anchor0, Point3d anchor1, int nodeCount, double mass, Vector3d gravity, double stiffness, double friction, ref object P, ref object V, ref object C)
{
if(reset){
nodes.Clear();
vels.Clear();

Line line = new Line(anchor0, anchor1);
NurbsCurve lineCurve = line.ToNurbsCurve();

Point3d[] pts;
lineCurve.DivideByCount(nodeCount - 1, true, out pts);

nodes.AddRange(pts);

for (int i = 0; i < nodeCount; i++)
{
vels.Add(new Vector3d(0, 0, 0));
}
}

// Update the location of the anchors
nodes[0] = anchor0;
nodes[nodes.Count - 1] = anchor1;



// Simulation forces for each node
for (int i = 1; i < nodes.Count - 1; i++)
{
Point3d n = nodes[i];
Vector3d v = vels[i];

// Calculating all the forces
Vector3d gravityForce = mass * gravity;
Vector3d prevSpring = -stiffness * (n - nodes[i - 1]);
Vector3d nextSpring = -stiffness * (n - nodes[i + 1]);

// Aggregate all the forces
Vector3d totalForce = gravityForce + prevSpring + nextSpring;

// Update velocity
v += totalForce;

// Add friction
v *= friction;

// Update location of the node
n += v;

// Update values on the original lists
nodes[i] = n;
vels[i] = v;

}

P = nodes;
V = vels;
C = new Polyline(nodes);
}

// <Custom additional code>
List<Point3d> nodes = new List<Point3d>();
List<Vector3d> vels = new List<Vector3d>();
// </Custom additional code>