-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathComplexBlur.cpp
More file actions
2076 lines (1777 loc) · 94.1 KB
/
ComplexBlur.cpp
File metadata and controls
2076 lines (1777 loc) · 94.1 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
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
#include "PCH.h"
#include "ComplexBlur.h"
namespace ComplexBlur
{
////////////////////////////////////////////////////////////////////////////////
// Define the component
DEFINE_COMPONENT(COMPLEX_BLUR);
DEFINE_OBJECT(COMPLEX_BLUR);
REGISTER_OBJECT_UPDATE_CALLBACK(COMPLEX_BLUR, AFTER, INPUT);
REGISTER_OBJECT_RENDER_CALLBACK(COMPLEX_BLUR, "Complex Blur", OpenGL, AFTER, "Effects (LDR) [Begin]", 1,
&ComplexBlur::renderObjectOpenGL, &RenderSettings::firstCallTypeCondition,
&RenderSettings::firstCallObjectCondition, nullptr, nullptr);
////////////////////////////////////////////////////////////////////////////////
namespace Psfs
{
////////////////////////////////////////////////////////////////////////////////
Aberration::WavefrontAberration& getAberration(Scene::Scene& scene, Scene::Object* object)
{
return object->component<ComplexBlurComponent>().m_aberration;
}
////////////////////////////////////////////////////////////////////////////////
Aberration::PSFStack& getPsfStack(Scene::Scene& scene, Scene::Object* object)
{
return object->component<ComplexBlurComponent>().m_aberration.m_psfStack;
}
////////////////////////////////////////////////////////////////////////////////
Aberration::WavefrontAberrationPresets& getAberrationPresets(Scene::Scene& scene, Scene::Object* object)
{
return object->component<ComplexBlurComponent>().m_aberrationPresets;
}
////////////////////////////////////////////////////////////////////////////////
// Find the PSF with the smallest defocus
Aberration::PsfIndex findMinDefocusPsfIndex(Scene::Scene& scene, Scene::Object* object)
{
Aberration::PsfIndex minPsfIndex;
float minDefocus = FLT_MAX;
Aberration::forEachPsfStackIndex(scene, Psfs::getAberration(scene, object),
[&](auto& scene, auto& aberration, Aberration::PsfIndex const& psfIndex)
{
auto const& psfEntry = Aberration::getPsfEntryParameters(scene, aberration, psfIndex);
const float defocusParam = psfEntry.m_focus.m_defocusParam;
if (defocusParam < minDefocus)
{
minDefocus = defocusParam;
minPsfIndex = psfIndex;
}
});
return minPsfIndex;
}
////////////////////////////////////////////////////////////////////////////////
// Find the PSF with the largest blur size
Aberration::PsfIndex findMaxDefocusPsfIndex(Scene::Scene& scene, Scene::Object* object)
{
Aberration::PsfIndex maxPsfIndex;
float maxDefocusParam = 0.0f;
Aberration::forEachPsfStackIndex(scene, Psfs::getAberration(scene, object),
[&](auto& scene, auto& aberration, Aberration::PsfIndex const& psfIndex)
{
auto const& psfEntry = Aberration::getPsfEntryParameters(scene, aberration, psfIndex);
const float defocusParam = psfEntry.m_focus.m_defocusParam;
if (defocusParam > maxDefocusParam)
{
maxDefocusParam = defocusParam;
maxPsfIndex = psfIndex;
}
});
return maxPsfIndex;
}
////////////////////////////////////////////////////////////////////////////////
// Find the PSF with the smallest defocus
Aberration::PsfIndex findMinBlurSizePsfIndex(Scene::Scene& scene, Scene::Object* object)
{
Aberration::PsfIndex minPsfIndex;
float minBlurSize = FLT_MAX;
Aberration::forEachPsfStackIndex(scene, Psfs::getAberration(scene, object),
[&](auto& scene, auto& aberration, Aberration::PsfIndex const& psfIndex)
{
auto const& psfEntry = Aberration::getPsfEntry(scene, aberration, psfIndex);
const float blurSize = psfEntry.m_blurSizeMuM;
if (blurSize < minBlurSize)
{
minBlurSize = blurSize;
minPsfIndex = psfIndex;
}
});
return minPsfIndex;
}
////////////////////////////////////////////////////////////////////////////////
// Find the PSF with the largest blur size
Aberration::PsfIndex findMaxBlurSizePsfIndex(Scene::Scene& scene, Scene::Object* object)
{
Aberration::PsfIndex maxPsfIndex;
float maxBlurSize = 0.0f;
Aberration::forEachPsfStackIndex(scene, Psfs::getAberration(scene, object),
[&](auto& scene, auto& aberration, Aberration::PsfIndex const& psfIndex)
{
auto const& psfEntry = Aberration::getPsfEntry(scene, aberration, psfIndex);
const float blurSize = psfEntry.m_blurSizeMuM;
if (blurSize > maxBlurSize)
{
maxBlurSize = blurSize;
maxPsfIndex = psfIndex;
}
});
return maxPsfIndex;
}
////////////////////////////////////////////////////////////////////////////////
// Find the PSF with the closest defocus param
Aberration::PsfIndex findTargetDefocusPsfIndex(Scene::Scene& scene, Scene::Object* object, const float targetDefocus)
{
Aberration::PsfIndex targetPsfIndex;
float targetDefocusDiff = FLT_MAX;
Aberration::forEachPsfStackIndex(scene, Psfs::getAberration(scene, object),
[&](auto& scene, auto& aberration, Aberration::PsfIndex const& psfIndex)
{
auto const& psfEntryParameters = Aberration::getPsfEntryParameters(scene, aberration, psfIndex);
const float defocusDiff = glm::abs(psfEntryParameters.m_focus.m_defocusParam - targetDefocus);
if (defocusDiff < targetDefocusDiff)
{
targetDefocusDiff = defocusDiff;
targetPsfIndex = psfIndex;
}
});
return targetPsfIndex;
}
////////////////////////////////////////////////////////////////////////////////
void initPsfStack(Scene::Scene& scene, Scene::Object* object)
{
const Aberration::PsfStackComputation computationFlags =
Aberration::PsfStackComputation_RelaxedEyeParameters |
Aberration::PsfStackComputation_FocusedEyeParameters |
Aberration::PsfStackComputation_PsfUnits |
Aberration::PsfStackComputation_PsfBesselTerms |
Aberration::PsfStackComputation_PsfEnzCoefficients;
Aberration::computePSFStack(scene, getAberration(scene, object), computationFlags);
}
////////////////////////////////////////////////////////////////////////////////
void computePsfs(Scene::Scene& scene, Scene::Object* object)
{
Aberration::computePSFStack(scene, getAberration(scene, object), Aberration::PsfStackComputation_Everything);
}
}
////////////////////////////////////////////////////////////////////////////////
namespace Dilation
{
////////////////////////////////////////////////////////////////////////////////
int getDilatedTileSize(int searchRadius, int passes)
{
return glm::pow(searchRadius, passes);
}
////////////////////////////////////////////////////////////////////////////////
int getDilatedTileSize(Scene::Scene& scene, Scene::Object* object, int passes)
{
return getDilatedTileSize(object->component<ComplexBlur::ComplexBlurComponent>().m_dilationSearchRadius, passes);
}
////////////////////////////////////////////////////////////////////////////////
int getDilatedTileSize(Scene::Scene& scene, Scene::Object* object)
{
return getDilatedTileSize(
object->component<ComplexBlur::ComplexBlurComponent>().m_dilationSearchRadius,
object->component<ComplexBlur::ComplexBlurComponent>().m_dilationPasses);
}
////////////////////////////////////////////////////////////////////////////////
glm::vec2 getDilatedResolution(glm::vec2 renderResolution, int dilatedTileSize)
{
return (renderResolution + glm::vec2(dilatedTileSize - 1)) / glm::vec2(dilatedTileSize);
}
////////////////////////////////////////////////////////////////////////////////
glm::vec2 getDilatedResolution(glm::vec2 renderResolution, int searchRadius, int passes)
{
return getDilatedResolution(renderResolution, getDilatedTileSize(searchRadius, passes));
}
////////////////////////////////////////////////////////////////////////////////
glm::vec2 getDilatedResolution(Scene::Scene& scene, Scene::Object* object, glm::vec2 renderResolution)
{
return getDilatedResolution(renderResolution, getDilatedTileSize(scene, object));
}
}
////////////////////////////////////////////////////////////////////////////////
namespace Kernel
{
////////////////////////////////////////////////////////////////////////////////
ComplexBlurKernelParameters& getKernel(Scene::Scene& scene, Scene::Object* object)
{
return object->component<ComplexBlurComponent>().m_kernels[object->component<ComplexBlurComponent>().m_numComponents];
}
////////////////////////////////////////////////////////////////////////////////
float getBlurRadiusPixels(Scene::Scene& scene, Scene::Object* object, const glm::ivec2 resolution, const float fovy, const float blurSize)
{
return Aberration::blurRadiusPixels(Aberration::blurRadiusAngle(blurSize), resolution, fovy);
}
////////////////////////////////////////////////////////////////////////////////
float getBlurRadiusPixels(Scene::Scene& scene, Scene::Object* object, Scene::Object* renderSettings, Scene::Object* camera, const float blurSize)
{
return getBlurRadiusPixels(scene, object,
RenderSettings::getResolution(scene, renderSettings),
camera->component<Camera::CameraComponent>().m_fovy,
blurSize);
}
////////////////////////////////////////////////////////////////////////////////
float getBlurRadiusPixels(Scene::Scene& scene, Scene::Object* object, Scene::Object* renderSettings, Scene::Object* camera, const size_t psfId)
{
return getBlurRadiusPixels(scene, object,
RenderSettings::getResolution(scene, renderSettings),
camera->component<Camera::CameraComponent>().m_fovy,
Psfs::getAberration(scene, object).m_psfStack.m_psfs[psfId][0][0][0][0][0].m_blurRadiusMuM);
}
////////////////////////////////////////////////////////////////////////////////
float getBlurRadiusPixels(Scene::Scene& scene, Scene::Object* object, Scene::Object* renderSettings, Scene::Object* camera)
{
return getBlurRadiusPixels(scene, object,
RenderSettings::getResolution(scene, renderSettings),
camera->component<Camera::CameraComponent>().m_fovy,
object->component<ComplexBlur::ComplexBlurComponent>().m_blurSize);
}
////////////////////////////////////////////////////////////////////////////////
glm::vec2 getBlurDirection(Scene::Scene& scene, Scene::Object* object, const float offset)
{
return glm::vec2(
glm::cos(offset + object->component<ComplexBlur::ComplexBlurComponent>().m_ellipseRotation),
glm::sin(offset + object->component<ComplexBlur::ComplexBlurComponent>().m_ellipseRotation));
}
////////////////////////////////////////////////////////////////////////////////
glm::vec2 getBlurDirection(Scene::Scene& scene, Scene::Object* object, const float offset, const glm::ivec2 resolution, const int numTapsRadius)
{
return (getBlurDirection(scene, object, offset) / float(numTapsRadius)) / (glm::vec2(resolution));
}
////////////////////////////////////////////////////////////////////////////////
glm::vec2 getBlurDirection(Scene::Scene& scene, Scene::Object* object, Scene::Object* renderSettings, const float offset, const int numTapsRadius)
{
return getBlurDirection(scene, object, offset, RenderSettings::getResolution(scene, renderSettings), numTapsRadius);
}
////////////////////////////////////////////////////////////////////////////////
ComplexBlurKernelComponent kernelFunction(ComplexBlurKernelComponent const& component, const float x)
{
return
{
glm::exp(x * x * -component.m_a) * glm::cos(x * x * component.m_b), // real
glm::exp(x * x * -component.m_a) * glm::sin(x * x * component.m_b), // imaginary
component.m_A, // real weight
component.m_B, // imaginary weight
};
}
////////////////////////////////////////////////////////////////////////////////
std::vector<ComplexBlurKernelComponents> kernelFunction(ComplexBlurKernelParameters const& kernelParameters, const int radius)
{
std::vector<ComplexBlurKernelComponents> output(kernelParameters.m_components.size(), ComplexBlurKernelComponents(2 * radius + 1));
for (int k = 0; k < kernelParameters.m_components.size(); ++k)
for (int i = -radius, s = 0; i <= radius; ++i, ++s)
{
const float x = kernelParameters.m_radius * (i / float(radius));
output[k][s] = kernelFunction(kernelParameters.m_components[k], x);
}
return output;
}
////////////////////////////////////////////////////////////////////////////////
ComplexBlurConvolutionKernel computeKernel(ComplexBlurKernelParameters const& kernelParameters,
const int radiusHorizontal, const int radiusVertical)
{
// Resulting object
ComplexBlurConvolutionKernel output;
// Compute the horizontal and vertical kernel values
output.m_horizontal = kernelFunction(kernelParameters, radiusHorizontal);
output.m_vertical = kernelFunction(kernelParameters, radiusVertical);
// Compute the kernel normalization factor
float accum = 0.0f;
for (int k = 0; k < kernelParameters.m_components.size(); ++k)
for (auto v : output.m_horizontal[k])
for (auto w : output.m_vertical[k])
{
accum += +v.m_A * (v.m_a * w.m_a - v.m_b * w.m_b) + v.m_B * (v.m_a * w.m_b + v.m_b * w.m_a);
}
// Normalize the kernel
float normalizationFactor = 1.0f / glm::sqrt(accum);
for (int k = 0; k < kernelParameters.m_components.size(); ++k)
{
std::transform(output.m_horizontal[k].begin(), output.m_horizontal[k].end(),
output.m_horizontal[k].begin(), [=](ComplexBlurKernelComponent c)
{ return ComplexBlurKernelComponent{ c.m_a * normalizationFactor, c.m_b * normalizationFactor, 0.0f, 0.0f }; });
std::transform(output.m_vertical[k].begin(), output.m_vertical[k].end(),
output.m_vertical[k].begin(), [=](ComplexBlurKernelComponent c)
{ return ComplexBlurKernelComponent{ c.m_a * normalizationFactor, c.m_b * normalizationFactor, 0.0f, 0.0f }; });
}
// Compute the offsets for bracketing
output.m_offsets = std::vector<glm::vec4>(kernelParameters.m_components.size());
for (size_t k = 0; k < kernelParameters.m_components.size(); ++k)
{
glm::vec4 offset{ output.m_horizontal[k][0].m_a, output.m_horizontal[k][0].m_b, output.m_vertical[k][0].m_a, output.m_vertical[k][0].m_b };
for (auto v : output.m_horizontal[k])
{
offset.x = glm::min(offset.x, v.m_a);
offset.y = glm::min(offset.y, v.m_b);
}
for (auto v : output.m_vertical[k])
{
offset.z = glm::min(offset.z, v.m_a);
offset.w = glm::min(offset.w, v.m_b);
}
output.m_offsets[k] = offset;
}
// Compute the scales for bracketing
output.m_scales = std::vector<glm::vec4>(kernelParameters.m_components.size());
for (size_t k = 0; k < kernelParameters.m_components.size(); ++k)
{
glm::vec4 scale{ 0.0f, 0.0f, 0.0f, 0.0f };
for (auto v : output.m_horizontal[k])
{
scale.x += v.m_a - output.m_offsets[k].x;
scale.y += v.m_b - output.m_offsets[k].y;
}
for (auto v : output.m_vertical[k])
{
scale.z += v.m_a - output.m_offsets[k].z;
scale.w += v.m_b - output.m_offsets[k].w;
}
output.m_scales[k] = scale;
}
// Compute the bracketed kernels
for (size_t k = 0; k < kernelParameters.m_components.size(); ++k)
{
for (size_t i = 0; i < output.m_horizontal[k].size(); ++i)
{
output.m_horizontal[k][i].m_A = (output.m_horizontal[k][i].m_a - output.m_offsets[k].x) / output.m_scales[k].x;
output.m_horizontal[k][i].m_B = (output.m_horizontal[k][i].m_b - output.m_offsets[k].y) / output.m_scales[k].y;
}
for (size_t i = 0; i < output.m_vertical[k].size(); ++i)
{
output.m_vertical[k][i].m_A = (output.m_vertical[k][i].m_a - output.m_offsets[k].z) / output.m_scales[k].z;
output.m_vertical[k][i].m_B = (output.m_vertical[k][i].m_b - output.m_offsets[k].w) / output.m_scales[k].w;
}
}
// Return the result
return output;
}
////////////////////////////////////////////////////////////////////////////////
ComplexBlurConvolutionKernel computeKernel(Scene::Scene& scene, Scene::Object* object,
const int radiusHorizontal, const int radiusVertical)
{
return computeKernel(getKernel(scene, object), radiusHorizontal, radiusVertical);
}
////////////////////////////////////////////////////////////////////////////////
ComplexBlurKernelComponent computeGaussianKernelParameters(Scene::Scene& scene, Scene::Object* object, const float sigma)
{
return ComplexBlurKernelComponent
{
/*a*/ 1.0f / (2.0f * sigma * sigma),
/*b*/ 1e-5f,
/*A*/ glm::sqrt(glm::two_pi<float>() * sigma * sigma),
/*B*/ 0.0f
};
}
////////////////////////////////////////////////////////////////////////////////
void loadGaussianKernelSettings(Scene::Scene& scene, Scene::Object* object)
{
object->component<ComplexBlur::ComplexBlurComponent>().m_numComponents = 1;
object->component<ComplexBlur::ComplexBlurComponent>().m_alignKernelToPsf = false;
object->component<ComplexBlur::ComplexBlurComponent>().m_fitKernelToPsf = false;
object->component<ComplexBlur::ComplexBlurComponent>().m_ellipseRotation = 0.0f;
object->component<ComplexBlur::ComplexBlurComponent>().m_ellipseRatio = 1.0f;
object->component<ComplexBlur::ComplexBlurComponent>().m_ellipseContraction = 1.0f;
object->component<ComplexBlur::ComplexBlurComponent>().m_kernels[1].m_radius = 2.5f;
object->component<ComplexBlur::ComplexBlurComponent>().m_kernels[1].m_components = { computeGaussianKernelParameters(scene, object, 1.0f) };
}
////////////////////////////////////////////////////////////////////////////////
void loadGarciaKernelSettings(Scene::Scene& scene, Scene::Object* object)
{
object->component<ComplexBlur::ComplexBlurComponent>().m_numComponents = 1;
object->component<ComplexBlur::ComplexBlurComponent>().m_kernels =
{
// 0 components
ComplexBlurKernelParameters
{
1.25f,
ComplexBlurKernelComponents
{},
},
// 1 component
ComplexBlurKernelParameters
{
1.25f,
ComplexBlurKernelComponents
{
ComplexBlurKernelComponent{ 0.862325f, 1.624835f, 0.767583f, 1.862321f },
},
},
// 2 components
ComplexBlurKernelParameters
{
1.25f,
ComplexBlurKernelComponents
{
ComplexBlurKernelComponent{ 0.886528f, 5.268909f, 0.411259f, -0.548794f },
ComplexBlurKernelComponent{ 1.960518f, 1.558213f, 0.513282f, 4.561110f },
},
},
// 3 components
ComplexBlurKernelParameters
{
1.25f,
ComplexBlurKernelComponents
{
ComplexBlurKernelComponent{ 2.176490f, 5.043495f, 1.621035f, -2.105439f },
ComplexBlurKernelComponent{ 1.019306f, 9.027613f, -0.280860f, -0.162882f },
ComplexBlurKernelComponent{ 2.815110f, 1.597273f, -0.366471f, 10.300301f },
},
},
};
}
////////////////////////////////////////////////////////////////////////////////
std::vector<float> generate2DKernel(ComplexBlurKernelParameters const& kernelParameters, const int radiusHorizontal, const int radiusVertical)
{
// Compute the hight resolution kernel
const ComplexBlurConvolutionKernel kernelHiRes = computeKernel(kernelParameters, radiusHorizontal, radiusVertical);
// Generate the weights
std::vector<float> weights(kernelHiRes.m_horizontal[0].size() * kernelHiRes.m_vertical[0].size(), 0.0f);
for (int row = 0; row < kernelHiRes.m_vertical[0].size(); ++row)
{
for (int col = 0; col < kernelHiRes.m_horizontal[0].size(); ++col)
{
float weight = 0.0f;
for (int c = 0; c < kernelParameters.m_components.size(); ++c)
{
auto v = kernelHiRes.m_vertical[c][row], w = kernelHiRes.m_horizontal[c][col];
weight +=
kernelParameters.m_components[c].m_A * (v.m_a * w.m_a - v.m_b * w.m_b) +
kernelParameters.m_components[c].m_B * (v.m_a * w.m_b + v.m_b * w.m_a);
}
int pixelId = row * kernelHiRes.m_horizontal[0].size() + col;
weights[pixelId] = weight;
}
}
return weights;
}
////////////////////////////////////////////////////////////////////////////////
std::vector<float> generate2DKernel(Scene::Scene& scene, Scene::Object* object, const int radiusHorizontal, const int radiusVertical)
{
return generate2DKernel(getKernel(scene, object), radiusHorizontal, radiusVertical);
}
////////////////////////////////////////////////////////////////////////////////
std::string getDebugImageFname(Scene::Scene& scene, Scene::Object* object, std::string const& exportPrefix, std::string const& fname)
{
return (exportPrefix + "_" + fname + "_" + DateTime::getDateStringUtf8(DateTime::dateFormatFilename()) + ".png");
}
////////////////////////////////////////////////////////////////////////////////
std::string getDebugImageFullpath(Scene::Scene& scene, Scene::Object* object, std::string const& exportPrefix, std::string const& fname)
{
return (EnginePaths::generatedFilesFolder() / "ComplexBlur" / getDebugImageFname(scene, object, exportPrefix, fname)).string();
}
////////////////////////////////////////////////////////////////////////////////
template<typename Img>
void saveDebugImage(Scene::Scene& scene, Scene::Object* object, std::string const& exportPrefix, std::string const& fname, Img const& image)
{
Asset::saveImage(scene, getDebugImageFullpath(scene, object, exportPrefix, fname), image, true);
}
////////////////////////////////////////////////////////////////////////////////
namespace FitEllipse
{
////////////////////////////////////////////////////////////////////////////////
using Ellipse = std::pair<glm::vec2, float>;
////////////////////////////////////////////////////////////////////////////////
Ellipse fitEllipseToPsf(Scene::Scene& scene, Scene::Object* object,
Aberration::Psf const& targetPsf,
const float threshold, const bool exportImages, std::string const& exportPrefix)
{
Debug::log_debug() << "Fitting ellipse to PSF" << Debug::end;
Debug::log_debug() << " > PSF size: " << targetPsf.rows() << "x" << targetPsf.cols() << Debug::end;
// Normalize the PSF
Aberration::Psf psf = targetPsf / targetPsf.maxCoeff();
// Convert the PSF to binary
cv::Mat cvPsf;
cv::eigen2cv(psf, cvPsf);
cv::Mat psfBinaryF;
cv::threshold(cvPsf, psfBinaryF, threshold, 1.0f, cv::THRESH_BINARY);
cv::Mat psfBinary;
psfBinaryF.convertTo(psfBinary, CV_8UC1);
// Save the target PSF
if (exportImages)
{
cv::Mat psfSave;
psfBinary.convertTo(psfSave, CV_32FC1);
saveDebugImage(scene, object, exportPrefix, "ell_thr", psfSave);
}
// Fit a rect around the binary image
std::vector<cv::Point> pts;
for (int j = 0; j < psfBinary.rows; ++j)
for (int i = 0; i < psfBinary.cols; ++i)
if (psfBinary.at<unsigned char>(j, i))
pts.push_back(cv::Point(i, j));
// Find the convex hull of the points
std::vector<cv::Point> convexHull;
cv::convexHull(pts, convexHull);
if (exportImages)
{
std::vector<std::vector<cv::Point>> convexHulls(1, convexHull);
cv::Mat psfSave;
cvPsf.convertTo(psfSave, CV_32FC1);
cv::drawContours(psfSave, convexHulls, -1, 0.5f, 2, cv::LINE_8);
saveDebugImage(scene, object, exportPrefix, "ell_chull", psfSave);
}
if (exportImages)
{
std::vector<std::vector<cv::Point>> convexHulls(1, convexHull);
cv::Mat psfSave;
psfBinary.convertTo(psfSave, CV_32FC1);
cv::drawContours(psfSave, convexHulls, -1, 0.5f, 2, cv::LINE_8);
saveDebugImage(scene, object, exportPrefix, "ell_chull_bin", psfSave);
}
// Fit an ellipse around the convex hull
cv::RotatedRect e = cv::fitEllipse(convexHull);
if (exportImages)
{
cv::Mat psfSave;
cvPsf.convertTo(psfSave, CV_32FC1);
cv::ellipse(psfSave, e, 0.5f, 2, cv::LINE_8);
saveDebugImage(scene, object, exportPrefix, "ell_fit", psfSave);
}
if (exportImages)
{
cv::Mat psfSave;
psfBinary.convertTo(psfSave, CV_32FC1);
cv::ellipse(psfSave, e, 0.5f, 2, cv::LINE_8);
saveDebugImage(scene, object, exportPrefix, "ell_fit_bin", psfSave);
}
// Construct the result
Ellipse result{ glm::vec2(e.size.width, e.size.height), e.angle };
Debug::log_debug() << " > Fit ellipse" << ": " <<
"radius[" << result.first << "]" << ", "
"angle[" << glm::degrees(result.second) << "]" <<
Debug::end;
return result;
}
}
////////////////////////////////////////////////////////////////////////////////
namespace KernelAlign
{
////////////////////////////////////////////////////////////////////////////////
Aberration::Psf constructTargetPsf(Scene::Scene& scene, Scene::Object* object,
ComplexBlurComponent::AlignKernelSettings const& alignSettings,
Aberration::PsfStackElements::PsfEntry const& targetPsf)
{
// Normalize the PSF
Aberration::Psf psf = targetPsf.m_psf / targetPsf.m_psf.maxCoeff();
// Save the target PSF
if (alignSettings.m_exportPsf)
{
saveDebugImage(scene, object, "align_psf", "full", psf);
}
// Return the final result
return psf;
}
////////////////////////////////////////////////////////////////////////////////
void alignKernel(Scene::Scene& scene, Scene::Object* object, ComplexBlurComponent::AlignKernelSettings const& alignSettings)
{
// Find the necessary PSFs
const Aberration::PsfIndex maxPsfIndex = Psfs::findMaxBlurSizePsfIndex(scene, object);
Aberration::PsfStackElements::PsfEntry const& maxPsf = getPsfEntry(scene, Psfs::getAberration(scene, object), maxPsfIndex);
const Aberration::PsfIndex targetPsfIndex = Psfs::findTargetDefocusPsfIndex(scene, object, alignSettings.m_targetDefocus);
Aberration::PsfStackElements::PsfEntry const& targetPsf = getPsfEntry(scene, Psfs::getAberration(scene, object), targetPsfIndex);
// Construct the target PSF
Aberration::Psf psf = constructTargetPsf(scene, object, alignSettings, targetPsf);
// Fit an ellipse over the PSF
FitEllipse::Ellipse ellipse = FitEllipse::fitEllipseToPsf(scene, object, psf, alignSettings.m_ellipseThreshold,
alignSettings.m_exportPsf, "align");
// Set the blur parameters
object->component<ComplexBlur::ComplexBlurComponent>().m_blurSize = maxPsf.m_blurRadiusMuM;
object->component<ComplexBlur::ComplexBlurComponent>().m_ellipseRotation = glm::radians(ellipse.second) - glm::half_pi<float>();
object->component<ComplexBlur::ComplexBlurComponent>().m_ellipseRatio = (ellipse.first.x / float(targetPsf.m_kernelSizePx));
object->component<ComplexBlur::ComplexBlurComponent>().m_ellipseContraction = ellipse.first.x / ellipse.first.y;
}
////////////////////////////////////////////////////////////////////////////////
void alignKernel(Scene::Scene& scene, Scene::Object* object)
{
alignKernel(scene, object, object->component<ComplexBlur::ComplexBlurComponent>().m_alignKernelSettings);
}
}
////////////////////////////////////////////////////////////////////////////////
namespace KernelFit
{
////////////////////////////////////////////////////////////////////////////////
struct CostFunctor
{
////////////////////////////////////////////////////////////////////////////////
CostFunctor(const Aberration::Psf target, const size_t numComponents, const size_t radiusHorizontal, const size_t radiusVertical) :
m_target(target),
m_numComponents(numComponents),
m_radiusHorizontal(radiusHorizontal),
m_radiusVertical(radiusVertical)
{}
////////////////////////////////////////////////////////////////////////////////
static ComplexBlurKernelParameters toKernelParameters(const size_t numComponents, const double* x0)
{
ComplexBlurKernelParameters result;
result.m_radius = float(x0[0]);
result.m_components.resize(numComponents);
for (size_t i = 0; i < numComponents; ++i)
{
result.m_components[i].m_a = float(x0[1 + i * 4 + 0]);
result.m_components[i].m_b = float(x0[1 + i * 4 + 1]);
result.m_components[i].m_A = float(x0[1 + i * 4 + 2]);
result.m_components[i].m_B = float(x0[1 + i * 4 + 3]);
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
bool operator()(const double* parameters, double* residuals) const
{
// Extract the kernel parameters
ComplexBlurKernelParameters kernelParameters = toKernelParameters(m_numComponents, parameters);
// Generate the kernel image
std::vector<float> kernelImage = generate2DKernel(kernelParameters, m_radiusHorizontal, m_radiusVertical);
// Turn to the corresponding Eigen object
using Kernel = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
Aberration::Psf kernel = Eigen::Map<Kernel>(kernelImage.data(), m_radiusVertical * 2 + 1, m_radiusHorizontal * 2 + 1);
kernel /= kernel.sum();
// Calculate the mean difference
residuals[0] = double((kernel - m_target).cwiseAbs2().mean()) * 1e6f;
/*
Debug::log_info() <<
std::vector<double>(parameters, parameters + m_numComponents * 4 + 1) << ": " <<
//m_target << ", " <<
//kernel << ", " <<
residuals[0] <<
Debug::end;
*/
// Whether the loss was tractable or not
bool tractable = !isinf(residuals[0]) && !isnan(residuals[0]);
//for (int c = 0; c < m_numComponents; ++c)
// tractable &= (kernelParameters.m_components[c].m_a != 0.0f && kernelParameters.m_components[c].m_b);
return tractable;
}
// The target PSF to estimate
Aberration::Psf m_target;
// Kernel settings
size_t m_numComponents;
size_t m_radiusHorizontal;
size_t m_radiusVertical;
};
////////////////////////////////////////////////////////////////////////////////
ceres::CostFunction* makeCostFunction(ComplexBlurComponent::FitKernelSettings const& fitSettings, CostFunctor* cost, const size_t numComponents)
{
// Create differentation options
ceres::NumericDiffOptions diffOptions;
diffOptions.relative_step_size = fitSettings.m_diffStepSize;
switch (numComponents)
{
case 1: return new ceres::NumericDiffCostFunction<CostFunctor, ceres::CENTRAL, 1, 5>(cost, ceres::TAKE_OWNERSHIP, 1, diffOptions);
case 2: return new ceres::NumericDiffCostFunction<CostFunctor, ceres::CENTRAL, 1, 9>(cost, ceres::TAKE_OWNERSHIP, 1, diffOptions);
case 3: return new ceres::NumericDiffCostFunction<CostFunctor, ceres::CENTRAL, 1, 13>(cost, ceres::TAKE_OWNERSHIP, 1, diffOptions);
}
Debug::log_error() << "Unsupported number of kernel components: " << numComponents << Debug::end;
return nullptr;
}
////////////////////////////////////////////////////////////////////////////////
Aberration::Psf constructTargetPsf(Scene::Scene& scene, Scene::Object* object,
ComplexBlurComponent::FitKernelSettings const& fitSettings,
Aberration::PsfStackElements::PsfEntry const& targetPsf,
const size_t radiusHorizontal, const size_t radiusVertical)
{
// Project the PSF
Aberration::Psf psf = targetPsf.m_psf;
if (fitSettings.m_projectPsf)
{
Scene::Object* renderSettings = Scene::findFirstObject(scene, Scene::OBJECT_TYPE_RENDER_SETTINGS);
Scene::Object* camera = RenderSettings::getMainCamera(scene, renderSettings);
const glm::vec2 renderResolution = RenderSettings::getResolutionById(scene, object->component<ComplexBlur::ComplexBlurComponent>().m_renderResolutionId);
const float fovy = camera->component<Camera::CameraComponent>().m_fovy;
psf = Aberration::getProjectedPsf(scene, Psfs::getAberration(scene, object), targetPsf, glm::ivec2(renderResolution), fovy);
}
// Fit the ellipse to the PSF
FitEllipse::Ellipse ellipse = FitEllipse::fitEllipseToPsf(scene, object, psf, fitSettings.m_ellipseThreshold, fitSettings.m_exportPsf, "fit_psf");
// Normalize the PSF
psf = psf / psf.maxCoeff();
// Convert the PSF to CV format
cv::Mat psfCV;
cv::eigen2cv(psf, psfCV);
// Unwarp the ellipse
cv::Mat psfUnwarped;
const int ellSize = int(std::ceil(std::max(ellipse.first.x, ellipse.first.y)));
const cv::Point2f pc(psfCV.cols / 2.0f, psfCV.rows / 2.0f);
const glm::mat4 t0 = glm::translate(glm::vec3(-pc.x, -pc.y, 0.0f));
const glm::mat4 r = glm::rotate(-glm::radians(ellipse.second), glm::vec3(0.0f, 0.0f, 1.0f));
const glm::mat4 s = glm::scale(glm::vec3(1.0f, ellipse.first.x / ellipse.first.y, 1.0f));
const glm::mat4 t1 = glm::translate(glm::vec3(pc.x, pc.y, 0.0f));
const glm::mat4 t = t1 * s * r * t0;
const cv::Mat tcv = cv::Mat(cv::Matx23d(t[0][0], t[1][0], t[3][0], t[0][1], t[1][1], t[3][1]));
cv::warpAffine(psfCV, psfUnwarped, tcv, psfCV.size());
// Crop the image
const int numRowsFull = psfUnwarped.rows;
const int numRowsEll = int(std::ceil(ellipse.first.x));
const int startRows = std::max((numRowsFull / 2) - (numRowsEll / 2), 0);
const int endRows = std::min((numRowsFull / 2) + (numRowsEll / 2) + 1, psfUnwarped.rows);
cv::Mat psfCropped = psfUnwarped(cv::Range(startRows, endRows), cv::Range(startRows, endRows));
// Resize the PSF to the final size
cv::Mat psfResized;
cv::resize(psfCropped, psfResized, cv::Size(radiusHorizontal * 2 + 1, radiusVertical * 2 + 1), 0, 0, cv::INTER_AREA);
//cv::resize(psfCropped, psfResized, cv::Size(radiusHorizontal * 2 + 1, radiusVertical * 2 + 1), 0, 0, cv::INTER_LANCZOS4);
// Save the target PSF
if (fitSettings.m_exportPsf)
{
saveDebugImage(scene, object, "fit_psf", "unwarped", psfUnwarped);
saveDebugImage(scene, object, "fit_psf", "full", psfCropped);
saveDebugImage(scene, object, "fit_psf", "resized", psfResized);
}
// Convert back to Eigen and return
Aberration::Psf result;
cv::cv2eigen(psfResized, result);
// Normalize the result
result = result / psf.sum();
return result;
}
////////////////////////////////////////////////////////////////////////////////
Aberration::Psf constructTargetPsf(Scene::Scene& scene, Scene::Object* object,
ComplexBlurComponent::FitKernelSettings const& fitSettings,
Aberration::PsfStackElements::PsfEntry const& targetPsf)
{
// Common kernel settings
const size_t numComponents = object->component<ComplexBlur::ComplexBlurComponent>().m_numComponents;
const int kernelTaps = object->component<ComplexBlur::ComplexBlurComponent>().m_kernelTapsRadius * fitSettings.m_fitScale;
// Construct the target PSF
return constructTargetPsf(scene, object, fitSettings, targetPsf, kernelTaps, kernelTaps);
}
////////////////////////////////////////////////////////////////////////////////
std::vector<double> createFitResult(Scene::Scene& scene, Scene::Object* object,
ComplexBlurComponent::FitKernelSettings const& fitSettings)
{
// Common kernel settings
const size_t numComponents = object->component<ComplexBlur::ComplexBlurComponent>().m_numComponents;
// Create the resulting structure
std::vector<double> fitResult(numComponents * 4 + 1, 0.0);
// Init the radius and the components
fitResult[0] = 1.5f;
for (size_t i = 0; i < numComponents; ++i)
for (size_t c = 0; c < 4; ++c)
fitResult[1 + i * 4 + c] = fitSettings.m_initialComponents[c];
// Return the result
return fitResult;
}
////////////////////////////////////////////////////////////////////////////////
ComplexBlurKernelParameters fitKernel(Scene::Scene& scene, Scene::Object* object,
Aberration::PsfStackElements::PsfEntry const& psf,
ComplexBlurComponent::FitKernelSettings const& fitSettings)
{
// Common kernel settings
const size_t numComponents = object->component<ComplexBlur::ComplexBlurComponent>().m_numComponents;
const int kernelTaps = object->component<ComplexBlur::ComplexBlurComponent>().m_kernelTapsRadius * fitSettings.m_fitScale;
// Result of the fit
std::vector<double> fitResult = createFitResult(scene, object, fitSettings);
// Construct the target PSF
Aberration::Psf targetPsf = constructTargetPsf(scene, object, fitSettings, psf);
// Create the problem object
ceres::Problem problem;
CostFunctor* cost = new CostFunctor(targetPsf, numComponents, kernelTaps, kernelTaps);
ceres::CostFunction* costFn = makeCostFunction(fitSettings, cost, numComponents);
problem.AddResidualBlock(costFn, nullptr, fitResult.data());
problem.SetParameterLowerBound(fitResult.data(), 0, fitSettings.m_radiusLimits.x);
problem.SetParameterUpperBound(fitResult.data(), 0, fitSettings.m_radiusLimits.y);
for (size_t i = 0; i < numComponents; ++i)
{
problem.SetParameterLowerBound(fitResult.data(), i * 4 + 0, fitSettings.m_aLimits.x); // a
problem.SetParameterUpperBound(fitResult.data(), i * 4 + 0, fitSettings.m_aLimits.y);
problem.SetParameterLowerBound(fitResult.data(), i * 4 + 1, fitSettings.m_bLimits.x); // b
problem.SetParameterUpperBound(fitResult.data(), i * 4 + 1, fitSettings.m_bLimits.y);
problem.SetParameterLowerBound(fitResult.data(), i * 4 + 2, fitSettings.m_ALimits.x); // A
problem.SetParameterUpperBound(fitResult.data(), i * 4 + 2, fitSettings.m_ALimits.y);
problem.SetParameterLowerBound(fitResult.data(), i * 4 + 3, fitSettings.m_BLimits.x); // B
problem.SetParameterUpperBound(fitResult.data(), i * 4 + 3, fitSettings.m_BLimits.y);
}
// Create the solver options
ceres::Solver::Options options;
// Common options
options.num_threads = Threading::numThreads();
options.logging_type = fitSettings.m_logProgress ? ceres::PER_MINIMIZER_ITERATION : ceres::SILENT;
// Line-search options
//options.minimizer_type = ceres::LINE_SEARCH;
options.line_search_type = ceres::WOLFE;
options.line_search_direction_type = ceres::BFGS;
// Trust region options
options.minimizer_type = ceres::TRUST_REGION;
//options.trust_region_strategy_type = ceres::LEVENBERG_MARQUARDT;
options.trust_region_strategy_type = ceres::DOGLEG;
options.dogleg_type = ceres::TRADITIONAL_DOGLEG;
// Other optimizer options
options.linear_solver_type = ceres::DENSE_QR;
//options.linear_solver_type = ceres::DENSE_SCHUR;
//options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;
options.preconditioner_type = ceres::SCHUR_JACOBI;
options.visibility_clustering_type = ceres::SINGLE_LINKAGE;
options.use_approximate_eigenvalue_bfgs_scaling = true;
options.use_nonmonotonic_steps = true;
options.initial_trust_region_radius = 1e-1f;
// Termination options
options.max_num_iterations = fitSettings.m_maxIterations;
options.max_solver_time_in_seconds = fitSettings.maxMinutes * 60.0f;
options.function_tolerance = 1e-8f;
// Solve the problem
ceres::Solver::Summary summary;
ceres::Solve(options, &problem, &summary);
// Extract and return the results
return CostFunctor::toKernelParameters(numComponents, fitResult.data());
}
////////////////////////////////////////////////////////////////////////////////
ComplexBlurKernelParameters fitKernel(Scene::Scene& scene, Scene::Object* object)
{
// Find the necessary PSF
const Aberration::PsfIndex targetPsfIndex = Psfs::findTargetDefocusPsfIndex(scene, object,
object->component<ComplexBlur::ComplexBlurComponent>().m_fitKernelSettings.m_targetDefocus);
Aberration::PsfStackElements::PsfEntry const& targetPsf = getPsfEntry(scene, Psfs::getAberration(scene, object), targetPsfIndex);
// Fit the kernel around it
return fitKernel(scene, object, targetPsf, object->component<ComplexBlurComponent>().m_fitKernelSettings);
}
};
////////////////////////////////////////////////////////////////////////////////
void updateKernelSettings(Scene::Scene& scene, Scene::Object* object)
{
// Align the kernel to the PSF
if (object->component<ComplexBlur::ComplexBlurComponent>().m_alignKernelToPsf)
{
DateTime::ScopedTimer timer = DateTime::ScopedTimer(Debug::Debug, 1, DateTime::Seconds, "Kernel Alignment");
KernelAlign::alignKernel(scene, object);
}
// Fit the kernel to the PSF
if (object->component<ComplexBlur::ComplexBlurComponent>().m_fitKernelToPsf)
{
DateTime::ScopedTimer timer = DateTime::ScopedTimer(Debug::Debug, 1, DateTime::Seconds, "Kernel Fit");
getKernel(scene, object) = KernelFit::fitKernel(scene, object);
}
}
////////////////////////////////////////////////////////////////////////////////
std::string getFullTextureName(Scene::Scene& scene, Scene::Object* object, std::string const& textureName)
{
return object->m_name + "_" + textureName;
}
////////////////////////////////////////////////////////////////////////////////
void uploadPreviewTexture(Scene::Scene& scene, Scene::Object* object, std::string const& textureName,
const size_t columns, const size_t rows, const float* pixelData)
{
Scene::createTexture(scene, getFullTextureName(scene, object, textureName), GL_TEXTURE_2D,
columns, rows, 1,
GL_RGB16F, GL_RGB, GL_LINEAR, GL_LINEAR, GL_CLAMP_TO_BORDER,
GL_FLOAT, pixelData,
GL_TEXTURE0);
}
////////////////////////////////////////////////////////////////////////////////
void uploadPreviewTexture(Scene::Scene& scene, Scene::Object* object, std::string const& textureName, Aberration::Psf psf, const bool normalize = true)
{
// Normalize the texture
if (normalize)
{
psf = psf / psf.sum();
psf = psf / psf.maxCoeff();
}
// Construct the rgb image
using MatrixXf3rm = Eigen::Matrix<glm::vec3, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
MatrixXf3rm const& psfRgb = Eigen::Map<const Aberration::Psf>(psf.data(), psf.rows(), psf.cols()).cwiseAbs().cast<glm::vec3>();
// Upload the texture data
uploadPreviewTexture(scene, object, textureName, psfRgb.cols(), psfRgb.rows(), (float*)psfRgb.data());
}
////////////////////////////////////////////////////////////////////////////////
Aberration::Psf getKernelDisplayImage(Scene::Scene& scene, Scene::Object* object, int radiusHorizontal, int radiusVertical)
{
// Column and row sizes
int maxRadius = glm::max(radiusHorizontal, radiusVertical);
int numCols = maxRadius * 2 + 1;
int numRows = numCols;
// Generate kernel weights
std::vector<float> kernelWeights = generate2DKernel(scene, object, maxRadius, maxRadius);
// Generate the image data
std::vector<float> pixelData(numCols * numRows, 0.0f);