summaryrefslogtreecommitdiff
path: root/2d/softbody/softbody_1.html
blob: 576b9c4b3f0d309a2d2e1102cdf864288fa0e529 (plain)
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
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<link rel="stylesheet" href="/index.css">
		<title>Physics for Games</title>
		<link rel="shortcut icon" href="/favicon/favicon.ico" type="image/x-icon">
		<meta name="description" content="A place to learn all about real-time physics simulations through descriptions, code snippets, and example programs all written in C++ and OpenGL.">
		<meta name="og:description" content="A place to learn all about real-time physics simulations through descriptions, code snippets, and example programs all written in C++ and OpenGL.">
	</head>
	<body>
		<header>
			<h1><a title="physicsforgames.com" href="/">Physics for Games</a></h1>
		</header>
		<main>
		<nav>
		<ul class="outer-tree">
			<li><a href="/">Introduction</a></li>
			<li>
				<span>&#127936;<span>2D</span></span>
				<ul class="inner-tree">
					<li><label>Rigidbody</label></li>
					<li><a title="/2d/rigidbody/rigidbody_1.html" href="/2d/rigidbody/rigidbody_1.html">Linear Forces</a></li>
					<li><a title="/2d/rigidbody/rigidbody_2.html" href="/2d/rigidbody/rigidbody_2.html">Rotational Forces</a></li>
					<li><a title="/2d/rigidbody/rigidbody_3.html" href="/2d/rigidbody/rigidbody_3.html">Collisions</a></li>
					<li><label>Collisions</label></li>
					<li><a title="/2d/_collisions/rectangle_rectangle.html" href="/2d/_collisions/rectangle_rectangle.html">Rectangle-Rectangle</a></li>
					<li><a title="/2d/_collisions/polygon_polygon.html" href="/2d/_collisions/polygon_polygon.html">Separating Axis Theorem</a></li>
					<li><label>Softbody</label></li>
					<li><a title="/2d/softbody/softbody_1.html" href="/2d/softbody/softbody_1.html">Springs</a></li>
					<li><a title="/2d/softbody/softbody_2.html" href="/2d/softbody/softbody_2.html">Springy Rectangle</a></li>
				</ul>
			</li>
			<li>
				<span>&#127776;<span>3D</span></span>
				<ul class="inner-tree">
					<li><label>Rigidbody</label></li>
					<li><a title="/3d/rigidbody.html" href="/3d/rigidbody.html">Rigidbody in 3D</a></li>
				</ul>
			</li>
			<li>
				<span>&#128295;<span>WebAssembly</span></span>
				<ul class="inner-tree">
					<li><a title="/intro/intro.html" href="/intro/intro.html">Introduction</a></li>
				</ul>
			</li>
			<li>
				<span>&#128712;<span>About</span></span>
				<ul class="inner-tree">
					<li><a title="/roadmap.html" href="/roadmap.html">Roadmap</a></li>
				</ul>
			</li>
		</ul>
		</nav>
<script src="./softbody_1/dist/output.js"></script>
<script>
  window.onload = function() {
      // -- Play/Stop Logic
      function addButtonListener(pPlay, pStop, pDisableElementList) {
          var lPlayElement = document.getElementById(pPlay),
              lStopElement = document.getElementById(pStop);
          lPlayElement.addEventListener('click', function() {
              lPlayElement.style.display = 'none';
              lStopElement.style.display = 'block';

              pDisableElementList.forEach(function(element) {
                  element.disabled = true;
              });
          });
          lStopElement.addEventListener('click', function() {
              lStopElement.style.display = 'none';
              lPlayElement.style.display = 'block';

              pDisableElementList.forEach(function(element) {
                  element.disabled = false;
              });
          });
      }

      addButtonListener('gl_canvas_play_undamped', 'gl_canvas_stop_undamped', [
          document.getElementById('undamped_spring_length'),
          document.getElementById('undamped_start_position'),
		  document.getElementById('undamped_spring_constant'),
          document.getElementById('undamped_spring_mass')
      ]);
      addButtonListener('gl_canvas_play_damped', 'gl_canvas_stop_damped', [
		  document.getElementById('damped_spring_length'),
          document.getElementById('damped_start_position'),
		  document.getElementById('damped_spring_constant'),
		  document.getElementById('damped_viscous_constant'),
          document.getElementById('damped_spring_mass')
      ]);

      // -- Slider logic
      var sliderList = document.querySelectorAll('input[type=range]'),
          attachListener = function(element) {
              var output = element.nextElementSibling;
              var updateOutput = function() {
                  var value = Number(element.value);
                  output.innerHTML = value;
              }
              
              element.addEventListener('input', updateOutput);
              element.addEventListener('change', updateOutput);
              updateOutput();
          };

      for(var i = 0; i < sliderList.length; i++) {
          attachListener(sliderList[i]);
      }

      // -- Add callbacks for sliders
      Module.onRuntimeInitialized = function() {
          var Undamped_SetLength = Module.cwrap('Undamped_SetLength', 'void', ['number']),
              Undamped_SetDisplacement = Module.cwrap('Undamped_SetDisplacement', 'void', ['number']),
              Undamped_SetK = Module.cwrap('Undamped_SetK', 'void', ['number']),
              Undamped_SetMass = Module.cwrap('Undamped_SetMass', 'void', ['number']),

			  Damped_SetLength = Module.cwrap('Damped_SetLength', 'void', ['number']),
              Damped_SetDisplacement = Module.cwrap('Damped_SetDisplacement', 'void', ['number']),
              Damped_SetK = Module.cwrap('Damped_SetK', 'void', ['number']),
              Damped_SetMass = Module.cwrap('Damped_SetMass', 'void', ['number']),
			  Damped_SetC = Module.cwrap('Damped_SetC', 'void', ['number']),
			  
              Undamped_lengthSlider = document.getElementById('undamped_spring_length'),
              Undamped_displacementSlider = document.getElementById('undamped_start_position'),
              Undamped_kSlider = document.getElementById('undamped_spring_constant'),
              Undamped_massSlider = document.getElementById('undamped_spring_mass'),

			  Damped_lengthSlider = document.getElementById('damped_spring_length'),
              Damped_displacementSlider = document.getElementById('damped_start_position'),
              Damped_kSlider = document.getElementById('damped_spring_constant'),
              Damped_massSlider = document.getElementById('damped_spring_mass'),
			  Damped_cSlider = document.getElementById('damped_viscous_constant'),
			  
              undampedSetLength = function(value) {
                  value = Number(value);
                  Undamped_SetLength(value);

                  var currentDisplacementValue = Undamped_displacementSlider.value;
                  var bound = value;
                  Undamped_displacementSlider.setAttribute('max', bound);
                  Undamped_displacementSlider.setAttribute('min', -bound);

                  if (currentDisplacementValue < -bound) currentDisplacementValue = -bound;
                  else if (currentDisplacementValue > bound) currentDisplacementValue = bound;

                  var event = new Event('change');  
                  Undamped_displacementSlider.value = currentDisplacementValue;
                  Undamped_displacementSlider.dispatchEvent(event);
              },
			  dampedSetLength = function(value) {
                  value = Number(value);
                  Damped_SetLength(value);

                  var currentDisplacementValue = Damped_displacementSlider.value;
                  var bound = value;
                  Damped_displacementSlider.setAttribute('max', bound);
                  Damped_displacementSlider.setAttribute('min', -bound);

                  if (currentDisplacementValue < -bound) currentDisplacementValue = -bound;
                  else if (currentDisplacementValue > bound) currentDisplacementValue = bound;

                  var event = new Event('change');  
                  Damped_displacementSlider.value = currentDisplacementValue;
                  Damped_displacementSlider.dispatchEvent(event);
              };

          Undamped_lengthSlider.addEventListener('change', function(event) { undampedSetLength(Number(event.target.value)); });
          Undamped_displacementSlider.addEventListener('change', function(event) { Undamped_SetDisplacement(Number(event.target.value)); });
          Undamped_kSlider.addEventListener('change', function(event) { Undamped_SetK(Number(event.target.value)); });
          Undamped_massSlider.addEventListener('change', function(event) { Undamped_SetMass(Number(event.target.value)); });

		  Damped_lengthSlider.addEventListener('change', function(event) { dampedSetLength(Number(event.target.value)); });
          Damped_displacementSlider.addEventListener('change', function(event) { Damped_SetDisplacement(Number(event.target.value)); });
          Damped_kSlider.addEventListener('change', function(event) { Damped_SetK(Number(event.target.value)); });
          Damped_massSlider.addEventListener('change', function(event) { Damped_SetMass(Number(event.target.value)); });
		  Damped_cSlider.addEventListener('change', function(event) { Damped_SetC(Number(event.target.value)); });
      };
  }
  
</script>
<article>
  <h1>Springs</h1>
  <section>
	<p>
    It is time to investigate what it means to have a deformation in our physics system. By deformation, I mean that the
    vertices of our shapes are no longer fixed to one point within the model. Towards this end, we will begin by investigating
    springs.
	</p>
  </section>
  <section>
	  <h2>Undamped Spring Explanation</h2>
    <p>
      An <b>undamped spring</b> is one that never stops oscillating. Once an undamped spring starts moving back and forth,
      it moves back and forth forever.
    </p>
    <p>
      From Newton's second law, we know that the sum of all the forces acting on an object will equal zero. We know that one
      of these forces is mass times acceleration, but for a spring we will add another force which uses the <i>spring constant</i>.
      This force grows in proportion to the displacment that spring is currently set at. So, if the spring is currently displaced
      10m, the effect of this force will be greater than if the spring was at <i>equlibrium</i>, which means that it is displaced by
      0m. This should make sense intuitively.
    </p>
    <p>
      One thing to note is that a damped spring has three cases:
      <ul>
        <li><b>Overdamped</b>: the spring will decompress immediately to the equlibrium position</li>
        <li><b>Underdamped</b>: the spring will do one oscillation before returning to the equlibrium position</li>
        <li><b>Critically damped: the spring will oscilate, but each oscillation will bring it closer and closer to the equlibrium position</b></li>
      </ul>
      I will not go into the mathematical details as to why this happens, as the links at the end of this video can very easily tell you. Just know
      that they are dependent on your values of <i>c</i> and <i>k</i>, so choose wisely for your use case.
    </p>
    <p>
      The equation is given as such:
      <div class="formula">
        <math class="formula">
          ma + kx = 0
        </math>
      </div>
      where <i>m</i> is the mass, <i>a</i> is acceleration, <i>k</i> is the spring constant, and <i>x</i> is the current displacement
      from the rest position.
    </p>
    <p>
      We can define an undamped 1D spring in code like so:
      <pre><code><span class="code_keyword">struct</span> Spring {
    <span class="code_keyword">float</span> mass = 1.f;       <span class="code_comment">// Mass of the weight on the end of the spring</span>
    <span class="code_keyword">float</span> k = 4;            <span class="code_comment">// Spring Constant, in N / m</span>
    <span class="code_keyword">float</span> force = 0.f;
    <span class="code_keyword">float</span> velocity = 0.f;
    <span class="code_keyword">float</span> position = 0.f;
};

<span class="code_keyword">void</span> updateSpring(Spring* spring, <span class="code_keyword">float</span> dtSeconds) {
    spring->force = spring->k * spring->position;
    <span class="code_keyword">float</span> acceleration = spring->force / spring->mass;  <span class="code_comment">// F = ma</span>
    spring->velocity = spring->velocity + acceleration * dtSeconds;
    spring->position = spring->position + spring->velocity * dtSeconds;
}
</code></pre>
      Note that we are just using Euler Integration here.
    </p>
  </section>
  <section>
    <h2>
      Undamped Springs Example
    </h2>
    <p>
      <span class='widget_container'>
        <label for='undamped_spring_length'>Spring Length (m)</label>
        <input type='range' id='undamped_spring_length' min="50" max="300" value="150"/>
        <span></span>
      </span>
      
      <span class='widget_container'>
        <label for='undamped_start_position'>Start Displacement (m)</label>
        <input type='range' id='undamped_start_position' min='-150' max='150' value='0'/>
        <span></span>
      </span>

      <span class='widget_container'>
        <label for='undamped_spring_constant'>Spring Constant (N / m)</label>
        <input type='range' id='undamped_spring_constant' min='0' max='1000.0' value='1.0' step='0.1'/>
        <span></span>
      </span>

      <span class='widget_container'>
        <label for='undamped_spring_mass'>Mass (kg)</label>
        <input type='range' id='undamped_spring_mass' min='0' max='10.0' value='1.0' step='0.1'/>
        <span></span>
      </span>
      
    </p>
    <div class="opengl_canvas_container">
      <canvas id="gl_canvas_undamped" width="800" height="600"></canvas>
      <button id="gl_canvas_play_undamped" class="play_button">
        Play
      </button>
      <button id="gl_canvas_stop_undamped" class="stop_button">
        Stop
      </button>
    </div>
  </section>

  <section>
	  <h2>Damped Spring Explanation</h2>
    <p>
      Undamped springs are loads of fun, but if we want to make a softbody physics system, we're going to want
      our simulation to stop oscillating at some point. That is where the <b>viscous damping constant</b> (<i>c</i>) force
      comes in. The damping force grows in proportion to the velocity. The equation is given as such:

      <div class="formula">
        <math class="formula">
          ma + cv + kx = 0
        </math>
      </div>

      where <i>m</i> is the mass, <i>a</i> is acceleration, <i>c</i> is the damping constant, <i>v</i> is the velocity
      <i>k</i> is the spring constant, and <i>x</i> is the current displacement from the rest position.
    </p>
    <p>
      This force produces the most effect when the velocity is largest. Let's try to intuit exactly what this means. When
      our spring is extended downward, it will want to move upward to return to its equlibrium position. At this point, 
      the displacement (<i>x</i>) will be negative and the velocity (<i>v</i>) will be positive. Since the signs are different,
      we can see that our spring force will be mitigated by the damping force. Hence, we damp!
    </p>

    <p>
      We can define a damped 1D spring in code like so:
      <pre><code><span class="code_keyword">struct</span> Spring {
    <span class="code_keyword">float</span> mass = 1.f;       <span class="code_comment">// Mass of the weight on the end of the spring</span>
    <span class="code_keyword">float</span> k = 4;            <span class="code_comment">// Spring Constant, in N / m</span>
    <span class="code_keyword">float</span> c = 1;            <span class="code_comment">// Viscous damping constant, in N / m/s</span>
    <span class="code_keyword">float</span> force = 0.f;
    <span class="code_keyword">float</span> velocity = 0.f;
    <span class="code_keyword">float</span> position = 0.f;
};

<span class="code_keyword">void</span> updateSpring(Spring* spring, <span class="code_keyword">float</span> dtSeconds) {
    spring->force = spring->c * spring->velocity + spring->k * spring->position;
    <span class="code_keyword">float</span> acceleration = spring->force / spring->mass;  <span class="code_comment">// F = ma</span>
    spring->velocity = spring->velocity + acceleration * dtSeconds;
    spring->position = spring->position + spring->velocity * dtSeconds;
}
</code></pre>
      Note that we are just using Euler Integration here.
    </p>
  </section>

  <section>
	<h2>
	  Damped Springs Example
	</h2>
    <p>
      <span class='widget_container'>
        <label for='damped_spring_length'>Spring Length (m)</label>
        <input type='range' id='damped_spring_length' min="50" max="300" value="150"/>
        <span></span>
      </span>
      
      <span class='widget_container'>
        <label for='damped_start_position'>Start Displacement (m)</label>
        <input type='range' id='damped_start_position' min='-150' max='150' value='0'/>
        <span></span>
      </span>

      <span class='widget_container'>
        <label for='damped_spring_constant'>Spring Constant (N / m)</label>
        <input type='range' id='damped_spring_constant' min='0' max='1000.0' value='1.0' step='0.1'/>
        <span></span>
      </span>

	  <span class='widget_container'>
        <label for='damped_viscous_constant'>Viscous Damping Constant (N / m)</label>
        <input type='range' id='damped_viscous_constant' min='0' max='100.0' value='1.0' step='0.1'/>
        <span></span>
      </span>

      <span class='widget_container'>
        <label for='damped_spring_mass'>Mass (kg)</label>
        <input type='range' id='damped_spring_mass' min='0.1' max='10.0' value='1.0' step='0.1'/>
        <span></span>
      </span>
      
    </p>
    <div class="opengl_canvas_container">
      <canvas id="gl_canvas_damped" width="800" height="600"></canvas>
      <button id="gl_canvas_play_damped" class="play_button">
        Play
      </button>
      <button id="gl_canvas_stop_damped" class="stop_button">
        Stop
      </button>
    </div>
  </section>

  <footer id='references'>
    <h2>References</h2>
    <ul>
      <li>
        <a href='https://www.youtube.com/watch?v=Z52emur7Rko'>Wonderful Undamped Resource</a>
      </li>
      <li>
        <a href='https://www.youtube.com/watch?v=CTd1uVq5-l8'>Wonderful Damped Resource</a>
      </li>
      <li>
        <a href='http://ambrsoft.com/CalcPhysics/Spring/SpringData.htm'>List of Equations for Spring Motion</a>
      </li>
    </ul>
  </footer>
</article>
		</main>
	</body>
</html>