-
Notifications
You must be signed in to change notification settings - Fork 1
/
TimeSmoothing.html
2430 lines (2138 loc) · 95.1 KB
/
TimeSmoothing.html
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Time Smoothing</title>
<meta name="description" content="Various ways to smooth and sharpen in Houdini.">
<meta name="keywords" content="Lerp, Interpolation, Convolution, Kernel, Lowpass, Highpass, Bandpass, Allpass, Biquad, Filter, Smooth, Sharp">
<meta property="og:title" content="Time Smoothing">
<meta property="og:type" content="website">
<meta property="og:url" content="https://mysterypancake.github.io/Houdini-Fun/TimeSmoothing">
<meta property="og:site_name" content="Time Smoothing">
<meta property="og:description" content="Various ways to smooth and sharpen in Houdini.">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./scripts/highlight.min.css">
<script src="./scripts/highlight.min.js"></script>
<link href="./scripts/bootstrap.min.css" rel="stylesheet">
<link href="./scripts/bootstrap-icons.min.css" rel="stylesheet">
<script>
// This uses requestFrame(), some browsers name it differently so this finds the best alternative
const requestFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(e) { return window.setTimeout(e, 1000 / 60); };
function lerp(a, b, factor) {
return (1 - factor) * a + factor * b;
}
function invlerp(a, min, max) {
return (a - min) / (max - min);
}
function clamp(x, min, max) {
return Math.min(Math.max(x, min), max);
}
function gainTodB(gain) {
// Clamp to prevent 0 gain
gain = Math.max(gain, Number.MIN_VALUE);
return 20.0 * Math.log10(gain);
}
function dbToGain(db) {
return Math.pow(10.0, db / 20.0);
}
let lastX = 0, lastY = 0;
function mouseClickData(e, canv, data, scale) {
const key = Math.floor(e.offsetX / canv.width * (data.length - 1));
data[key] = (0.5 - e.offsetY / canv.height) / scale;
lastX = e.offsetX;
lastY = e.offsetY;
}
// When drawing, replace entries which were drawn over between frames
function mouseMoveData(e, canv, data, scale) {
let lastKey = Math.floor(lastX / canv.width * (data.length - 1));
let currentKey = Math.floor(e.offsetX / canv.width * (data.length - 1));
const start = Math.min(lastKey, currentKey);
const end = clamp(currentKey, lastKey, data.length - 1);
for (let i = start; i <= end; ++i) {
const line = start === end ? e.offsetY : lerp(lastY, e.offsetY, invlerp(i, lastKey, currentKey));
data[i] = (0.5 - line / canv.height) / scale;
}
lastX = e.offsetX;
lastY = e.offsetY;
}
// Structured sine wave data
function generateData(numPoints) {
const data = new Float32Array(numPoints);
for (let i = 0; i < numPoints; ++i) {
const factor = i / numPoints;
const sin = Math.sin(factor * 10) * 0.3;
const noiseAmount = (Math.cos(factor * 15) + 1) * 0.2;
const rand = Math.random() - 0.5;
data[i] = sin + rand * noiseAmount;
}
return data;
}
// Completely random data
function generateRandomData(numPoints) {
const data = new Float32Array(numPoints);
for (let i = 0; i < numPoints; ++i) {
data[i] = Math.random();
}
return data;
}
// Gaussian kernel, not optimized for symmetry
function gaussianKernel(numPoints) {
// Dividing by 3 seems to scale the kernel the best
let size = numPoints / 3;
size *= size;
let sum = 0;
const kernel = new Float32Array(numPoints);
const center = (numPoints - 1) * 0.5;
for (let i = 0; i < numPoints; i++) {
const x = i - center;
kernel[i] = Math.exp(-x * x / size);
sum += kernel[i];
}
// Normalize manually, no need for sqrt
for (let i = 0; i < numPoints; i++) {
kernel[i] /= sum;
}
return kernel;
}
function resizeCanvasWidth(elem) {
elem.width = elem.parentElement.clientWidth;
}
function drawBackground(canv, ctx) {
ctx.fillStyle = "#404040";
ctx.fillRect(0, 0, canv.width, canv.height);
}
function drawLine(ctx, x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
function drawConvolution(canv, ctx, data, kernelPos, weights, convAll) {
const columnWidth = canv.width / (data.length - 1);
const heightSplit = canv.height / 3;
const middleWeight = Math.floor(weights.length * 0.5);
ctx.fillStyle = "#505050";
ctx.fillRect(kernelPos / (data.length - 1) * canv.width, 0, columnWidth * weights.length, canv.height)
for (let i = 0; i < data.length; ++i) {
const xPos = i / (data.length - 1) * canv.width;
const height = data[i] * heightSplit * 0.5;
// Draw top bars
const topColor = `hsl(${i * 64}, 100%, 70%)`;
ctx.fillStyle = topColor;
ctx.fillRect(xPos, canv.height - heightSplit * 2 - height, columnWidth, height);
// Draw middle bars
ctx.fillStyle = "white";
const offset = i - kernelPos;
if (offset >= 0 && offset < weights.length) {
ctx.fillStyle = "#707070";
const height2 = weights[offset] * heightSplit * 0.5;
ctx.fillRect(xPos, canv.height - heightSplit - height2, columnWidth, height2);
ctx.fillStyle = topColor;
const height3 = height2 * data[i];
ctx.fillRect(xPos, canv.height - heightSplit - height3, columnWidth, height3);
}
// Draw bottom bars
if (convAll || kernelPos + middleWeight === i) {
let heightSum = canv.height;
for (let j = 0; j < weights.length; ++j) {
const height = data[clamp(i + j - middleWeight, 0, data.length - 1)] * weights[j] * heightSplit * 0.5;
heightSum -= height;
ctx.fillStyle = `hsl(${(i + j - middleWeight) * 64}, 100%, 70%)`;
ctx.fillRect(xPos, heightSum, columnWidth, height);
}
}
}
}
function drawData(canv, ctx, data, scale) {
ctx.beginPath();
for (let i = 0; i < data.length; ++i) {
ctx.lineTo(i / (data.length - 1) * canv.width, (0.5 - data[i] * scale) * canv.height);
}
ctx.stroke();
}
function setup() {
let list = document.getElementById("toc");
const content = document.getElementById("content");
const headings = content.querySelectorAll('h1, h2, h3, h4, h5, h6');
const hash = window.location.hash.slice(1);
let lastLevel = 0;
let headingItems = [];
headings.forEach(function(heading, index) {
const level = parseInt(heading.tagName.slice(1));
if (index === 0) {
// First element, make a new list
const childList = document.createElement("ul");
list.appendChild(childList);
list = childList;
} else if (level > lastLevel) {
// More indentation, make a new list per level
for (let i = 0; i < level - lastLevel; ++i) {
const childList = document.createElement("ul");
list.appendChild(childList);
list = childList;
}
} else if (level < lastLevel) {
// Less indentation, move back a few levels
for (let i = 0; i < lastLevel - level; ++i) {
list = list.parentNode;
}
}
let ref = `toc${index}`;
if (heading.hasAttribute("id")) {
ref = heading.getAttribute("id");
} else {
heading.setAttribute("id", ref);
}
const item = document.createElement("li");
const link = document.createElement("a");
link.setAttribute("href", `#${ref}`);
link.textContent = heading.textContent;
item.appendChild(link);
list.appendChild(item);
lastLevel = level;
headingItems.push({ "link": link, "header": heading });
// Scroll to linked heading
if (ref === hash) {
heading.scrollIntoView(true);
}
});
const blurry = document.getElementById("blurryTitle");
const title = blurry.textContent;
blurry.textContent = "";
const blurryLetters = [];
for (let i = 0; i < title.length; ++i) {
const span = document.createElement("span");
span.textContent = title.charAt(i);
const blurPixels = 4 - (i / title.length) * 4;
span.style = `filter: blur(${blurPixels}px);`;
blurry.appendChild(span);
blurryLetters.push(span);
}
const intro = document.getElementById("intro");
intro.addEventListener("mousemove", function(e) {
for (let i = 0; i < blurryLetters.length; ++i) {
const letter = blurryLetters[i];
const bounds = letter.getBoundingClientRect();
const blurPixels = Math.abs(bounds.x - e.clientX) * 0.01;
letter.style = `filter: blur(${blurPixels}px);`;
}
});
function updateNavigation() {
let latestElem;
headingItems.forEach(function(item) {
item.link.classList.remove("active");
if (item.header.getBoundingClientRect().top < 40) {
latestElem = item;
}
});
if (latestElem) {
latestElem.link.classList.add("active");
}
}
if (window.innerWidth >= 768) {
window.addEventListener("scroll", updateNavigation);
updateNavigation();
}
hljs.highlightAll();
}
</script>
<style>
#toc li a {
color: black;
display: block;
text-decoration: none;
transition: font-weight, padding 0.05s linear;
width: 100%;
}
#toc li a:hover, #toc li a.active {
padding-left: 0.5rem;
}
#toc li a.active {
font-weight: bold;
border-left: 2px solid black;
}
#toc ul {
padding-left: 1rem;
list-style-type: none;
}
#toc li {
padding: 0.2rem 0rem;
}
#toc a.active {
font-weight: bold;
}
h2, h3, h4, h5, h6 {
margin-top: 1.5rem;
margin-bottom: 1rem;
}
.biquad-filter > div, .biquad-filter select, .biquad-filter input {
width: 100%;
}
.biquad-filter {
background-color: #404040;
column-gap: 1rem;
row-gap: 0.5rem;
padding: 1.2rem;
}
.biquad-filter select {
border-radius: 0.5rem;
padding: 0.2rem;
}
/* Prevent annoying selection issues */
div:has(> input) {
user-select: none;
}
</style>
</head>
<body onload="setup();">
<div class="container mt-5">
<div class="row">
<div class="col-md-3 d-none d-md-block">
<nav id="toc" class="sticky-top pt-3"></nav>
</div>
<div class="col-md-9">
<section id="intro">
<h1 id="blurryTitle" class="mb-4">Smoothing and sharpening in time</h1>
<p>This was inspired by a talk by Catherine Williams at SydHUG. Catherine looked into a bunch of equations to smooth data, then used them to smooth jittery cloth sims over time.</p>
<p>I never looked into smoothing and sharpening in depth, so I went down a rabbithole researching all the methods I could find and dumping them into Houdini. If you're Catherine this is probably old news, but hopefully it's fun anyway!</p>
<p>Houdini has a few built-in tools for time smoothing, but they're hard to find. Matt Estela mentioned the <a href="https://www.sidefx.com/docs/houdini/nodes/sop/kinefx--smoothmotion.html" target="_blank">Smooth Motion</a> node, which can run on points too. Harrison Molling mentioned CHOPs, which have <a href="https://www.sidefx.com/docs/houdini/nodes/chop/filter.html" target="_blank">Filter</a> and <a href="https://www.sidefx.com/docs/houdini/nodes/chop/pass.html" target="_blank">Pass Filter</a> nodes. Catherine also mentioned <a href="https://www.sidefx.com/docs/houdini/nodes/sop/pca.html" target="_blank">Principle Component Analysis</a>, which has a great <a href="https://momme.gumroad.com/l/pcadejitter">dejitter node by Momme Carl</a>.</p>
<p>The standard nodes are OK, but not as controllable or fun as doing it manually. So let's begin!</p>
<ol>
<li>
<a href="#method-1-lerp">Lerp</a> (simplest lowpass, used for games)
</li>
<li>
<a href="#method-2-convolution">Convolution</a> (gaussian blur, box blur, sharpening, used for images)
</li>
<li>
<a href="#method-3-biquad-filters">Biquad filters</a> (low pass, high pass, butterworth... used for audio EQs)
</li>
<li>
<a href="#method-4-fir-filters">FIR filters</a> (convolution with a special kernel)
</li>
</ol>
</section>
<div id="content">
<h2 id="method-1-lerp">Method 1: Lerp</h2>
<p>The easiest way to smooth stuff is with lerp, <a href="./Lerp" target="_blank">which I wrote about here</a>. It's really popular for games, especially in Unity. It's not the best method, but it's a nice intro to the topic.</p>
<p>The idea is you start at some value, then pick a target value. Each frame you move a little bit closer to the target by some percentage. The slower you move, the smoother your path becomes.</p>
<pre><code class="language-js">current = lerp(current, target, factor);</code></pre>
<p>Here's a demo with the smooth version in white. Click and drag to draw your own data.</p>
<div>
<canvas id="lerpCanvas" width="640" height="200" style="cursor: pointer;"></canvas>
</div>
<div>
<canvas id="lerpLiveCanvas" width="640" height="32"></canvas>
</div>
<div class="mb-3">
<label for="lerpFactor">Factor</label>
<input id="lerpFactor" type="range" min="0" max="1" step="0.01" value="0.1">
<span id="lerpFactorValue"></span>
</div>
<script>
(function(){
const canv = document.getElementById("lerpCanvas");
const ctx = canv.getContext("2d", { alpha: false });
resizeCanvasWidth(canv);
const lerpSlider = document.getElementById("lerpFactor");
let lerpFac = parseFloat(lerpSlider.value);
const lerpValue = document.getElementById("lerpFactorValue");
lerpValue.textContent = lerpFac;
const data = generateData(Math.floor(canv.width * 0.5));
function draw() {
drawBackground(canv, ctx);
ctx.lineWidth = 1.5;
ctx.strokeStyle = "#DD2020";
drawData(canv, ctx, data, 1);
ctx.strokeStyle = "white";
ctx.beginPath();
let current = data[0];
for (let i = 0; i < data.length; ++i) {
// The magic formula
current = lerp(current, data[i], lerpFac);
ctx.lineTo(i / (data.length - 1) * canv.width, (0.5 - current) * canv.height);
}
ctx.stroke();
}
draw();
lerpSlider.addEventListener("input", function(e) {
lerpFac = parseFloat(e.target.value);
lerpValue.textContent = lerpFac;
draw();
});
canv.addEventListener("mousedown", function(e) {
mouseClickData(e, canv, data, 1);
draw();
});
canv.addEventListener("mousemove", function(e) {
if (e.which !== 1) return;
mouseMoveData(e, canv, data, 1);
draw();
});
const canv2 = document.getElementById("lerpLiveCanvas");
const ctx2 = canv2.getContext("2d", { alpha: false });
resizeCanvasWidth(canv2);
let target = Math.random() * (canv2.width - canv2.height);
let current = 0;
function drawLive() {
drawBackground(canv2, ctx2);
const blockSize = canv2.height * 0.5;
// Draw target value
ctx2.fillStyle = "#FF0000";
ctx2.fillRect(target, blockSize * 0.5, blockSize, blockSize);
// Draw current value
ctx2.fillStyle = "white";
ctx2.fillRect(current, blockSize * 0.5, blockSize, blockSize);
// The magic formula
current = lerp(current, target, lerpFac);
requestFrame(drawLive);
}
requestFrame(drawLive);
let hovering = false;
canv2.addEventListener("mouseenter", function(e) {
hovering = true;
});
canv2.addEventListener("mouseleave", function(e) {
hovering = false;
});
// Move target to new position
window.setInterval(function() {
if (hovering) return;
target = Math.random() * (canv2.width - canv2.height);
}, 1000);
canv2.addEventListener("mousemove", function(e) {
target = e.offsetX;
});
})();
</script>
<p>There's 3 big problems with this method, which all smoothing methods suffer from.</p>
<h3>Problem 1: Phase shift</h3>
<p>If you set the slider really low, it looks like the graph moves to the right. This is called <b>phase shift</b>.</p>
<p>It happens since the value is too lazy in moving to the target, so it sticks near the previous value and smears out the graph.</p>
<p>Phase shift is a popular topic in music, you'll find many audio engineers rambling about it online (<a href="https://www.youtube.com/@DanWorrall" target="_blank">Dan Worrall</a> is my favourite). When you use an equalizer on music (for example to boost the bass), it usually adds a bit of phase shift. Some plugins (like <a href="https://ddmf.eu/plugindoctor/" target="_blank">Plugindoctor</a>) even show you the exact phase shift you'll get. This is called the <b>phase response</b>.</p>
<p>Phase shift is a natural part of the universe so there's nothing wrong with it, but it's annoying if you want stuff to line up. The lazy way is shifting over the graph. The proper way is using <b>linear phase</b> filters. Linear phase filters always need values forwards in time as well as backwards.</p>
<p>The simplest way is smoothing forwards, then smoothing backwards. This cancels out the phase shift and makes a linear phase filter. Here's a demo with the original version in red, and the linear phase version in green.</p>
<div>
<canvas id="lerp3Canvas" width="640" height="200" style="cursor: pointer;"></canvas>
</div>
<div class="mb-3">
<label for="lerp3Factor">Factor</label>
<input id="lerp3Factor" type="range" min="0" max="1" step="0.01" value="0.02">
<span id="lerp3FactorValue"></span>
</div>
<script>
(function(){
const canv = document.getElementById("lerp3Canvas");
const ctx = canv.getContext("2d", { alpha: false });
resizeCanvasWidth(canv);
const lerpSlider = document.getElementById("lerp3Factor");
let lerpFac = parseFloat(lerpSlider.value);
const lerpValue = document.getElementById("lerp3FactorValue");
lerpValue.textContent = lerpFac;
const data = generateData(Math.floor(canv.width * 0.5));
function draw() {
drawBackground(canv, ctx);
ctx.lineWidth = 1.5;
ctx.strokeStyle = "#808080";
drawData(canv, ctx, data, 1);
// Lerp forwards in time
ctx.strokeStyle = "#FF0000";
ctx.beginPath();
const dataCopy = data.slice();
let current = dataCopy[0];
for (let i = 0; i < dataCopy.length; ++i) {
// The magic formula
current = lerp(current, dataCopy[i], lerpFac);
ctx.lineTo(i / (dataCopy.length - 1) * canv.width, (0.5 - current) * canv.height);
dataCopy[i] = current;
}
ctx.stroke();
// Lerp backwards in time
ctx.strokeStyle = "#00FF00";
ctx.beginPath();
current = dataCopy[dataCopy.length - 1];
for (let i = dataCopy.length - 1; i >= 0; --i) {
// The magic formula
current = lerp(current, dataCopy[i], lerpFac);
ctx.lineTo(i / (dataCopy.length - 1) * canv.width, (0.5 - current) * canv.height);
}
ctx.stroke();
}
draw();
lerpSlider.addEventListener("input", function(e) {
lerpFac = parseFloat(e.target.value);
lerpValue.textContent = lerpFac;
draw();
});
canv.addEventListener("mousedown", function(e) {
mouseClickData(e, canv, data, 1);
draw();
});
canv.addEventListener("mousemove", function(e) {
if (e.which !== 1) return;
mouseMoveData(e, canv, data, 1);
draw();
});
})();
</script>
<h3>Problem 2: Oversmoothing</h3>
<p>You'll find this method is hard to control. It tends to smooth everything too much or not enough.</p>
<p>This is because of the <b>order</b> of the filter. The order basically means how sharp and precise a filter is. Here's a nice diagram from <a href="https://www.electronics-tutorials.ws/filter/filter_8.html" target="_blank">Electronics Tutorials</a>. You can see as the order increases the curve gets steeper, meaning it cuts precisely and doesn't smudge everything.</p>
<img src="./images/smoothing/filterorder.png" class="mb-3 mw-100">
<p>The lerp method is a <a href="https://tomroelandts.com/articles/low-pass-single-pole-iir-filter" target="_blank">first order IIR lowpass</a>, so it's pretty blunt and tends to smudge everything out.</p>
<p>Turns out there's a cool trick to improve it. If you stack a bunch of low order filters, you approximate a high order filter. This works surprisingly well, though it's much slower and smudgier than doing it properly.</p>
<p>Here's a demo with the original filter in red, and the layered filters coloured towards purple. Try drawing some data and watch it move!</p>
<div>
<canvas id="lerp2Canvas" width="640" height="200" style="cursor: pointer;"></canvas>
</div>
<div class="d-flex flex-column flex-sm-row mb-3 gap-3">
<div>
<div>
<label for="lerp2Factor">Factor:</label>
<span id="lerp2FactorValue"></span>
</div>
<input id="lerp2Factor" type="range" min="0" max="1" step="0.01" value="0.1">
</div>
<div>
<div>
<label for="lerp2Layers">Layers:</label>
<span id="lerp2LayersValue"></span>
</div>
<input id="lerp2Layers" type="range" min="1" max="50" step="1" value="10">
</div>
<div>
<input id="lerp2Linear" type="checkbox">
<label for="lerp2Linear">Linear Phase</label>
</div>
</div>
<script>
(function(){
const canv = document.getElementById("lerp2Canvas");
const ctx = canv.getContext("2d", { alpha: false });
resizeCanvasWidth(canv);
const lerpSlider = document.getElementById("lerp2Factor");
let lerpFac = parseFloat(lerpSlider.value);
const lerpValue = document.getElementById("lerp2FactorValue");
lerpValue.textContent = lerpFac;
const layersSlider = document.getElementById("lerp2Layers");
let lerpLayers = parseFloat(layersSlider.value);
const layersValue = document.getElementById("lerp2LayersValue");
layersValue.textContent = lerpLayers;
const linearToggle = document.getElementById("lerp2Linear");
let linearPhase = linearToggle.checked;
const data = generateData(Math.floor(canv.width * 0.5));
function draw() {
drawBackground(canv, ctx);
ctx.lineWidth = 1.5;
ctx.strokeStyle = "#808080";
drawData(canv, ctx, data, 1);
// Chain the crappy lowpass filter to approximate a higher order lowpass filter
const dataCopy = data.slice();
for (let j = 0; j < lerpLayers; ++j) {
ctx.strokeStyle = `hsl(${j / lerpLayers * 360}, 100%, 70%)`;
ctx.beginPath();
// Lerp forwards in time
let current = dataCopy[0];
for (let i = 0; i < dataCopy.length; ++i) {
// The magic formula
current = lerp(current, dataCopy[i], lerpFac);
if (!linearPhase) {
ctx.lineTo(i / (dataCopy.length - 1) * canv.width, (0.5 - current) * canv.height);
}
dataCopy[i] = current;
}
// Lerp backwards in time
if (linearPhase) {
current = dataCopy[dataCopy.length - 1];
for (let i = dataCopy.length - 1; i >= 0; --i) {
// The magic formula
current = lerp(current, dataCopy[i], lerpFac);
ctx.lineTo(i / (dataCopy.length - 1) * canv.width, (0.5 - current) * canv.height);
dataCopy[i] = current;
}
}
ctx.stroke();
}
}
draw();
lerpSlider.addEventListener("input", function(e) {
lerpFac = parseFloat(e.target.value);
lerpValue.textContent = lerpFac;
draw();
});
layersSlider.addEventListener("input", function(e) {
lerpLayers = parseFloat(e.target.value);
layersValue.textContent = lerpLayers;
draw();
});
linearToggle.addEventListener("input", function(e) {
linearPhase = e.target.checked;
draw();
});
canv.addEventListener("mousedown", function(e) {
mouseClickData(e, canv, data, 1);
draw();
});
canv.addEventListener("mousemove", function(e) {
if (e.which !== 1) return;
mouseMoveData(e, canv, data, 1);
draw();
});
})();
</script>
<h3>Problem 3: Undershooting</h3>
<p>When the slider is below 1, it never actually reaches the target.</p>
<p>You can tell from the formula. Lerp takes a percentage of two values and adds them together <a href="./Lerp" target="_blank">as described here</a>. For example if the factor is 0.9, it takes 10% of the current value and adds on 90% of the target value. That means you never get 100% of the target.</p>
<p>Here's a demo where the white line targets the red line. Though it may appear to, it always lies below the red line until the factor is 1.</p>
<div>
<canvas id="undershootCanvas" width="640" height="200"></canvas>
</div>
<div class="mb-3">
<label for="undershootFactor">Factor</label>
<input id="undershootFactor" type="range" min="0" max="1" step="0.01" value="0.1">
<span id="undershootFactorValue"></span>
</div>
<script>
(function(){
const canv = document.getElementById("undershootCanvas");
const ctx = canv.getContext("2d", { alpha: false });
resizeCanvasWidth(canv);
const lerpSlider = document.getElementById("undershootFactor");
let lerpFac = parseFloat(lerpSlider.value);
const lerpValue = document.getElementById("undershootFactorValue");
lerpValue.textContent = lerpFac;
function draw() {
drawBackground(canv, ctx);
ctx.lineWidth = 1.5;
ctx.strokeStyle = "#FF0000";
drawLine(ctx, 0, canv.height * 0.2, canv.width, canv.height * 0.2);
ctx.strokeStyle = "white";
ctx.beginPath();
let current = 0.8;
for (let i = 0; i <= canv.width; i += 8) {
// The magic formula
current = lerp(current, 0.2, lerpFac);
ctx.lineTo(i, current * canv.height);
}
ctx.stroke();
}
draw();
lerpSlider.addEventListener("input", function(e) {
lerpFac = parseFloat(e.target.value);
lerpValue.textContent = lerpFac;
draw();
});
})();
</script>
<h3>Running this in Houdini</h3>
<p>To get this into Houdini, we need a way to access the previous frame. Luckily there's many ways to do this.</p>
<h4>Option 1: Solver</h4>
<p>Solvers are the most accurate and robust for this method. They run in sequence and never skip any frames, so if we had a huge jolt it continues smoothing out the impact forever. However they can't be run in parallel, so they're not ideal for farms.</p>
<p>First add a Solver node, then a Point Wrangle inside. Plug the the current animation (Input_1) into the second wrangle input.</p>
<img src="./images/smoothing/lerpwrangle.PNG" width="540" class="mb-3 mw-100">
<p>Now we can write the formula in VEX. In solvers, <code>@P</code> is the current position. The second input we connected <code>@opinput1_P</code> is the latest animation, which is our target position.</p>
<pre><code class="language-js">v@P = lerp(v@P, v@opinput1_P, chf("factor"));</code></pre>
<p>Here's before and after. It smooths out most of the noise, but reduces the range of motion too much.</p>
<img src="./images/smoothing/lerpsmoothsolver.webp" width="640" class="mw-100">
<div class="my-2">
<a href="./hips/smoothing/lerp_smooth_solver.hipnc?raw=true" target="_blank">
<button class="btn btn-primary"><i class="bi bi-download"></i> Download HIP file</button>
</a>
</div>
<p>Although solvers are ideal, we can get a decent approximation with Trail.</p>
<h4 id="option-2-trail">Option 2: Trail</h4>
<p>Instead of sampling all past frames, it's faster to sample a handful of past frames and try to guess the future from them. This is called a <b>sliding window</b> technique, which Catherine used for her demo. It's good for production since it can be batch processed and run in parallel. However it's bad news for lerp, since lerp <a href="#method-4-fir-filters">can't react to jolts</a> if it doesn't know they happened.</p>
<p>To try it anyway, add a Trail node and a Point Wrangle. Plug Trail into the second wrangle input.</p>
<img src="./images/smoothing/trailwrangle.PNG" width="540" class="mb-3 mw-100">
<p>For dense meshes, it helps to cache Trail for better performance.</p>
<p>Now we need to extract positions from different frames. This is done using <code>point()</code>. It has 3 arguments, but we only care about the last one.</p>
<pre><code class="language-js">vector pos = point(0, "P", point_number);</code></pre>
<p>Given the current point number <code>@ptnum</code>, we need to find the matching point number on the previous frame. Assuming the topology stays the same, you'll find a pattern. Let's say your <code>@ptnum</code> is 0. If the mesh has 5 points, your <code>@ptnum</code> on the previous frame will be 5, 10, 15, 20 and so on. This happens since the Trail node merges batches of 5 points per frame.</p>
<p>Using <code>npoints(0)</code> to get the number of points in the mesh, the general formula is <code>@ptnum + npoints(0) * frame</code></p>
<img src="./images/smoothing/trailframes.png" class="mb-3 w-100">
<p>Using this idea we can lerp through the positions from past to present, just like with the solver. No dictionaries or maps required!</p>
<pre><code class="language-js">// Make sure this matches your trail node
int trail_length = chi("../trail1/length");
int point_count = npoints(0);
// Start at the last frame's position (the oldest frame)
v@P = point(1, "P", i@ptnum + point_count * (trail_length - 1));
// Lerp from the past to the present, like the solver except manually
for (int frame = 1; frame < trail_length; ++frame) {
// Get the corresponding point position on the next frame
vector target_pos = point(1, "P", i@ptnum + point_count * (trail_length - 1 - frame));
// The magic formula
v@P = lerp(v@P, target_pos, chf("factor"));
}</code></pre>
<p>Here's before and after. It looks pretty similar, but jitters more since it keeps forgetting past samples.</p>
<img src="./images/smoothing/lerpsmoothtrail.webp" width="640" class="mw-100">
<div class="my-2">
<a href="./hips/smoothing/lerp_smooth_trail.hipnc?raw=true" target="_blank">
<button class="btn btn-primary"><i class="bi bi-download"></i> Download HIP file</button>
</a>
</div>
<p>Sadly this version suffers from phase shift, just like the solver. The great thing with Trail is it doesn't have to. We can make linear phase filters and stack them too!</p>
<h5 id="lerp-linear">Linear phase version</h5>
<p>First we need a way to get frames forwards in time as well as backwards. This is as easy as adding a Time Shift node after Trail.</p>
<img src="./images/smoothing/trailtimeshift.png" width="540" class="mb-3 mw-100">
<p>Set the frame offset to <code>$F + (ch("../trail1/length") - 1) / 2</code>. This centers the current frame, so we have the same number of frames forwards and backwards in time.</p>
<img src="./images/smoothing/trailframeoffset.png" width="860" class="mb-3 mw-100">
<p>Next we can reuse the same frame offset idea from before, except this time filtering in both directions.</p>
<pre><code class="language-js">// Make sure this matches your trail node
int trail_length = chi("../trail1/length");
int point_count = npoints(0);
float factor = chf("factor");
int layers = chi("layers");
// Build an array of all positions on all frames
// For optimization, you could do a forward lerp in here
vector pos[];
resize(pos, trail_length);
for (int frame = 0; frame < trail_length; ++frame) {
pos[frame] = point(1, "P", i@ptnum + point_count * (trail_length - 1 - frame));
}
// Smooth a bunch of times in a row (if you want)
for (int i = 0; i < layers; ++i) {
// Smooth forwards in time
vector current_pos = pos[0];
for (int frame = 1; frame < trail_length; ++frame) {
// The magic formula
pos[frame] = lerp(current_pos, pos[frame], factor);
current_pos = pos[frame];
}
// Smooth backwards in time
current_pos = pos[trail_length - 1];
for (int frame = trail_length - 2; frame >= 0; --frame) {
// The magic formula
pos[frame] = lerp(current_pos, pos[frame], factor);
current_pos = pos[frame];
}
}
// Get the center frame, which is our frame
v@P = pos[trail_length / 2];</code></pre>
<p>Thanks to looking into the future, we can anticipate motion before it even happens. Here's a demo with the linear phase version in green and the original version in red.</p>
<img src="./images/smoothing/lerpsmoothtraillinear.webp" width="480" class="mw-100">
<div class="my-2">
<a href="./hips/smoothing/lerp_smooth_trail_linear.hipnc?raw=true" target="_blank">
<button class="btn btn-primary"><i class="bi bi-download"></i> Download HIP file</button>
</a>
</div>
<p>While lerp works OK, there's plenty of fancier methods of smoothing out stuff. Let's learn about convolution!</p>
<h2 id="method-2-convolution">Method 2: Convolution</h2>
<p>
<b>Note Houdini's built-in <a href="https://www.sidefx.com/docs/houdini/nodes/chop/filter.html" target="_blank">Filter node</a> works for convolution, but not with custom kernels! <a href="https://www.youtube.com/watch?v=_Zw61uJ79_k">See Mark Fancher's tutorial</a>.</b>
</p>
<p>Convolution solves many problems we were having before. It's linear phase and only needs a handful of frames, making it perfect for batch processing. It's a weighted sum just like lerp, but it's much more powerful than you'd expect. It works for smoothing, sharpening, embossing and all kinds of cool filters.</p>
<p>It works by picking a value, sampling the neighbours around it, multiplying them and adding them together. It's like what we did with lerp, except now we have precise control over how much each neighbour contributes to the final result. We can totally ignore neighbours or even flip their influence.</p>
<p>For example, say you want each value to be the average of its 2 neighbours. For that you can use the kernel <code>[0.5, 0, 0.5]</code>.</p>
<img src="./images/smoothing/convolution.png" width="640" class="mb-3 mw-100">
<p>Here we sample 9's neighbours (4 and 6), then calculate <code>4 * 0.5 + 9 * 0 + 6 * 0.5 = 5</code>. In other words, ignore 9 and average 4 and 6 together.</p>
<p>The key idea of convolution is you can slide the kernel up and down. Click and drag to see what I mean!</p>
<div>
<canvas id="convCanvas" width="720" height="360" style="cursor: pointer;"></canvas>
</div>
<table class="mb-3 user-select-none">
<tr class="text-center">
<td class="pe-3">
<span id="convXWeightValue"></span>
</td>
<td class="pe-3">
<span id="convYWeightValue"></span>
</td>
<td class="pe-3">
<span id="convZWeightValue"></span>
</td>
<td>
<input id="convAll" type="checkbox">
<label for="convAll">Convolve All</label>
</td>
</tr>
<tr>
<td class="pe-3">
<input id="convXWeight" type="range" min="0" max="1" step="0.1" value="0.5">
</td>
<td class="pe-3">
<input id="convYWeight" type="range" min="0" max="1" step="0.1" value="0">
</td>
<td class="pe-3">
<input id="convZWeight" type="range" min="0" max="1" step="0.1" value="0.5">
</td>
</tr>
</table>
<script>
(function(){
const canv = document.getElementById("convCanvas");
const ctx = canv.getContext("2d", { alpha: false });
resizeCanvasWidth(canv);
const xSlider = document.getElementById("convXWeight");
let xWeight = parseFloat(xSlider.value);
const xValue = document.getElementById("convXWeightValue");
xValue.textContent = xWeight;
const ySlider = document.getElementById("convYWeight");
let yWeight = parseFloat(ySlider.value);
const yValue = document.getElementById("convYWeightValue");
yValue.textContent = yWeight;
const zSlider = document.getElementById("convZWeight");
let zWeight = parseFloat(zSlider.value);
const zValue = document.getElementById("convZWeightValue");
zValue.textContent = zWeight;
const convToggle = document.getElementById("convAll");
let convAll = convToggle.checked;
const data = generateRandomData(Math.floor(canv.width / 16));
let kernelPos = Math.floor(data.length * 0.5);
let weights;
function updateWeights() {
weights = [xWeight, yWeight, zWeight];
}
updateWeights();
function draw() {
drawBackground(canv, ctx);
drawConvolution(canv, ctx, data, kernelPos, weights, convAll);
}
draw();
xSlider.addEventListener("input", function(e) {
xWeight = parseFloat(e.target.value);
xValue.textContent = xWeight;
updateWeights();
draw();
});
ySlider.addEventListener("input", function(e) {
yWeight = parseFloat(e.target.value);
yValue.textContent = yWeight;
updateWeights();
draw();
});
zSlider.addEventListener("input", function(e) {
zWeight = parseFloat(e.target.value);
zValue.textContent = zWeight;
updateWeights();
draw();
});
convToggle.addEventListener("input", function(e) {
convAll = e.target.checked;
draw();
});
function moveKernel(e) {
kernelPos = Math.round(e.offsetX / canv.width * (data.length - 1) - weights.length * 0.5);
draw();
}
canv.addEventListener("mousedown", moveKernel);
canv.addEventListener("mousemove", function(e) {
if (e.which !== 1) return;
moveKernel(e);
});
})();
</script>
<p>Tick "Convolve All" to see the full convolution, then mess with the weights to see what you find! Here's a few you can try:</p>
<ul>
<li>The kernel <code>[1, 0, 0]</code> shifts everything 1 unit to the right.</li>
<li>The kernel <code>[0, 0, 1]</code> shifts everything 1 unit to the left.</li>
<li>The kernel <code>[0, 1, 0]</code> keeps everything the same.</li>
<li>The kernel <code>[1, 1, 1]</code> sums all 3 values together.</li>
<li>The kernel <code>[1, 1, 0]</code> sums the previous and current value.</li>
<li>The kernel <code>[0, 1, 1]</code> sums the current and next value.</li>
<li>The kernel <code>[1, 0, 1]</code> sums both neighbours.</li>
<li>The kernel <code>[0.5, 0, 0.5]</code> averages the two neighbours together.</li>
<li>The kernel <code>[0.5, 0.5, 0]</code> averages the previous and current value.</li>
<li>The kernel <code>[0, 0.5, 0.5]</code> averages the current and next value.</li>
</ul>
<p>With a tiny size 3 kernel, we can already do so many things. Hopefully this gives you an idea of how powerful and versatile convolution is.</p>
<h3>Gaussian blur</h3>
<p>Gaussian blur is one of the many things we can do with convolution. We just need to replace our kernel with a gaussian kernel. It looks like this.</p>
<img src="./images/smoothing/gaussiankernel.png" width="512" class="mb-3 mw-100">
<p>Stripping the formula to the bones, you can write it as <code>exp(-x * x / (size * size))</code>, where <code>x</code> is the value and <code>size</code> is the width of the shape. It extends infinitely, so you need to pick a size that fits most of it between -1 and 1. I found dividing <code>size</code> by 3 works pretty well, or in other words <code>exp(-9 * x * x / (size * size))</code>. Then we normalize it so all values add to 1.</p>
<p>And just like that we have gaussian blur! Change the kernel size to set the intensity.</p>
<div>
<canvas id="gaussianCanvas" width="720" height="360" style="cursor: pointer;"></canvas>
</div>
<table class="mb-3">
<tr>
<td class="pe-3">
<label for="gaussSize">Kernel Size:</label>
<span id="gaussSizeValue"></span>
</td>
<td>
<input id="gaussConvAll" type="checkbox" checked>
<label for="gaussConvAll">Convolve All</label>
</td>
</tr>
<tr>
<td class="pe-3">
<input id="gaussSize" type="range" min="1" max="65" step="2" value="5">
</td>
</tr>
</table>
<script>
(function(){
const canv = document.getElementById("gaussianCanvas");