-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfluids_app.cpp
1704 lines (1408 loc) · 54.1 KB
/
fluids_app.cpp
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 "fluids_app.h"
#include "rendering/Volumetric.h"
#include "vtk_output_window.h"
#include "vtk_error_observer.h"
#include "volume.h"
#include "volume3d.h"
#include "isosurface.h"
#include "slice.h"
#include "rendering/cube.h"
#include "loaders/loader_obj.h"
#include "rendering/mesh.h"
#include "rendering/lines.h"
#include "rendering/rectangle.h"
#include <array>
#include <map>
#include <time.h>
#include <vtkSmartPointer.h>
#include <vtkNew.h>
#include <vtkDataSetReader.h>
#include <vtkXMLImageDataReader.h>
#include <vtkImageData.h>
#include <vtkImageResize.h>
#include <vtkPointData.h>
#include <vtkDataArray.h>
#include <vtkProbeFilter.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
#define NEW_STYLUS_RENDER
#define VOLUME_METRICS 0.01f
struct Particle
{
Vector3 pos;
bool valid;
int delayMs, stallMs;
timespec lastTime;
};
struct FluidMechanics::Impl
{
Impl(const std::string& baseDir);
~Impl();
bool loadDataSet(const std::string& fileName);
bool loadVelocityDataSet(const std::string& fileName);
template <typename T>
vtkSmartPointer<vtkImageData> loadTypedDataSet(const std::string& fileName);
// (GL context)
void rebind();
// (GL context)
void renderObjects();
void setMatrices(const Matrix4& volumeMatrix, const Matrix4& stylusMatrix);
void updateSlicePlanes();
void buttonPressed();
float buttonReleased();
void releaseParticles();
Vector3 particleJitter();
void integrateParticleMotion(Particle& p);
bool computeCameraClipPlane(Vector3& point, Vector3& normal);
bool computeAxisClipPlane(Vector3& point, Vector3& normal);
bool computeStylusClipPlane(Vector3& point, Vector3& normal);
void showParticules();
void showSelection();
void pushBackSelection();
Vector3 posToDataCoords(const Vector3& pos); // "pos" is in eye coordinates
Vector3 dataCoordsToPos(const Vector3& dataCoordsToPos);
void updateSurfacePreview();
void setSeedPoint(float x, float y, float z);
void resetParticles();
FluidMechanics* app;
SettingsPtr settings;
StatePtr state;
CubePtr cube, axisCube;
vtkSmartPointer<vtkImageData> data, dataLow;
int dataDim[3];
Vector3 dataSpacing;
vtkSmartPointer<vtkImageData> velocityData;
typedef LinearMath::Vector3<int> DataCoords;
// std::array<Particle, 10> particles;
// std::array<Particle, 50> particles;
// std::array<Particle, 100> particles;
Synchronized<std::array<Particle, 200>> particles;
timespec particleStartTime;
static constexpr float particleSpeed = 0.15f;
// static constexpr int particleReleaseDuration = 500; // ms
static constexpr int particleReleaseDuration = 700; // ms
static constexpr int particleStallDuration = 1000; // ms
// static constexpr float stylusEffectorDist = 20.0f;
static constexpr float stylusEffectorDist = 24.0f;
// static constexpr float stylusEffectorDist = 30.0f;
Synchronized<VolumePtr> volume;
// Synchronized<Volume3dPtr> volume; // true volumetric rendering
Synchronized<IsoSurfacePtr> isosurface, isosurfaceLow;
Synchronized<SlicePtr> slice;
Synchronized<CubePtr> outline;
Vector3 slicePoint, sliceNormal;
float sliceDepth;
Synchronized<std::vector<Vector3>> slicePoints; // max size == 6
MeshPtr particleSphere, cylinder;
LinesPtr lines;
Vector3 seedPoint;
vtkSmartPointer<vtkProbeFilter> probeFilter;
Synchronized<Vector3> effectorIntersection;
// Vector3 effectorIntersectionNormal;
bool effectorIntersectionValid;
bool buttonIsPressed;
std::vector<std::vector<Matrix4>> selectionMatrix;
std::vector<Vector3> selectionPoint;
Vector3 postTreatmentTrans;
Quaternion postTreatmentRot;
std::vector<Vector3> dataTrans;
std::vector<Quaternion> dataRot;
Cube selectionCube;
//Tells where the volume is filled. Very useful for binary option (intersect, union, etc.)
FillVolume* fillVolume=NULL;
Matrix4_f fillVolumeMatrix;
Volumetric* volumetricRendering=NULL;
};
FluidMechanics::Impl::Impl(const std::string& baseDir)
: buttonIsPressed(false)
{
selectionCube.setColor(Vector3(220, 220, 0.0));
fillVolume=NULL;
cube.reset(new Cube);
axisCube.reset(new Cube(true));
particleSphere = LoaderOBJ::load(baseDir + "/sphere.obj");
cylinder = LoaderOBJ::load(baseDir + "/cylinder.obj");
lines.reset(new Lines);
seedPoint = Vector3(-10000.0,-10000.0,-10000.0);
for (Particle& p : particles)
p.valid = false;
pushBackSelection();
fillVolumeMatrix = Matrix4_f::identity();
}
FluidMechanics::Impl::~Impl()
{
fillVolume->lock();
{
if(fillVolume)
delete fillVolume;
}
}
void FluidMechanics::Impl::pushBackSelection()
{
/* selectionMatrix.push_back(std::vector<Matrix4>());
selectionPoint.push_back(std::vector<Vector3>());
dataTrans.push_back(Vector3());
dataRot.push_back(Quaternion());
*/
}
void FluidMechanics::Impl::rebind()
{
cube->bind();
axisCube->bind();
lines->bind();
particleSphere->bind();
cylinder->bind();
synchronized_if(volume) { volume->bind(); }
synchronized_if(isosurface) { isosurface->bind(); }
synchronized_if(isosurfaceLow) { isosurfaceLow->bind(); }
synchronized_if(slice) { slice->bind(); }
synchronized_if(outline) { outline->bind(); }
}
template <typename T>
vtkSmartPointer<vtkImageData> FluidMechanics::Impl::loadTypedDataSet(const std::string& fileName)
{
vtkNew<T> reader;
LOGI("Loading file: %s...", fileName.c_str());
reader->SetFileName(fileName.c_str());
vtkNew<VTKErrorObserver> errorObserver;
reader->AddObserver(vtkCommand::ErrorEvent, errorObserver.GetPointer());
reader->Update();
if (errorObserver->hasError()) {
// TODO? Throw a different type of error to let Java code
// display a helpful message to the user
throw std::runtime_error("Error loading data: " + errorObserver->getErrorMessage());
}
vtkSmartPointer<vtkImageData> data = vtkSmartPointer<vtkImageData>::New();
data->DeepCopy(reader->GetOutputDataObject(0));
return data;
}
void FluidMechanics::Impl::setSeedPoint(float x, float y, float z){
seedPoint.x = x;
seedPoint.y = y;
seedPoint.z = z;
}
bool FluidMechanics::Impl::loadDataSet(const std::string& fileName)
{
// // Unload mesh data
// mesh.reset();
synchronized (particles) {
// Unload velocity data
velocityData = nullptr;
// Delete particles
for (Particle& p : particles)
p.valid = false;
}
VTKOutputWindow::install();
const std::string ext = fileName.substr(fileName.find_last_of(".") + 1);
if (ext == "vtk")
data = loadTypedDataSet<vtkDataSetReader>(fileName);
else if (ext == "vti")
data = loadTypedDataSet<vtkXMLImageDataReader>(fileName);
else
throw std::runtime_error("Error loading data: unknown extension: \"" + ext + "\"");
data->GetDimensions(dataDim);
double spacing[3];
data->GetSpacing(spacing);
dataSpacing = Vector3(spacing[0], spacing[1], spacing[2]);
//Init the fill volume.
if(fillVolume)
{
fillVolume->lock();
{
delete fillVolume;
}
}
fillVolume = new FillVolume(dataDim[0]*spacing[0], dataDim[1]*spacing[1], dataDim[2]*spacing[2]);
fillVolumeMatrix = Matrix4_f::makeTransform(Vector3_f(-dataDim[0]*spacing[0]/2.0, -dataDim[1]*spacing[1]/2.0, -dataDim[2]*spacing[2]/2.0), Quaternion_f::identity(), Vector3_f(1.0, 1.0, 1.0));
fillVolumeMatrix.rescale(dataDim[0]*spacing[0], dataDim[1]*spacing[1], dataDim[2]*spacing[2]);
if(volumetricRendering)
delete volumetricRendering;
volumetricRendering = new Volumetric(fillVolume, Vector3_f(1.0, 1.0, 0.0), 0.5);
// Compute a default zoom value according to the data dimensions
// static const float nativeSize = 128.0f;
static const float nativeSize = 110.0f;
state->computedZoomFactor = nativeSize / std::max(dataSpacing.x*dataDim[0], std::max(dataSpacing.y*dataDim[1], dataSpacing.z*dataDim[2]));
// FIXME: hardcoded value: 0.25 (minimum zoom level, see the
// onTouch() handler in Java code)
state->computedZoomFactor = std::max(state->computedZoomFactor, 0.25f);
dataLow = vtkSmartPointer<vtkImageData>::New();
vtkNew<vtkImageResize> resizeFilter;
resizeFilter->SetInputData(data.GetPointer());
resizeFilter->SetOutputDimensions(std::max(dataDim[0]/3, 1), std::max(dataDim[1]/3, 1), std::max(dataDim[2]/3, 1));
resizeFilter->InterpolateOn();
resizeFilter->Update();
dataLow->DeepCopy(resizeFilter->GetOutput());
probeFilter = vtkSmartPointer<vtkProbeFilter>::New();
probeFilter->SetSourceData(data.GetPointer());
synchronized(outline) {
LOGD("creating outline...");
outline.reset(new Cube(true));
outline->setScale(Vector3(dataDim[0]/2, dataDim[1]/2, dataDim[2]/2) * dataSpacing);
}
synchronized(volume) {
LOGD("creating volume...");
volume.reset(new Volume(data));
LOGD("minValue : %f", volume->getMinValue());
LOGD("maxValue : %f", volume->getMaxValue());
// volume.reset(new Volume3d(data));
// if (fileName.find("FTLE7.vtk") != std::string::npos) { // HACK
// // volume->setOpacity(0.25f);
// volume->setOpacity(0.15f);
// }
}
if (fileName.find("FTLE7.vtk") == std::string::npos) { // HACK
synchronized(isosurface) {
LOGD("creating isosurface...");
isosurface.reset(new IsoSurface(data));
isosurface->setPercentage(settings->surfacePercentage);
}
synchronized(isosurfaceLow) {
LOGD("creating low-res isosurface...");
isosurfaceLow.reset(new IsoSurface(dataLow, true));
isosurfaceLow->setPercentage(settings->surfacePercentage);
}
} else {
isosurface.reset();
isosurfaceLow.reset();
}
synchronized(slice) {
LOGD("creating slice...");
slice.reset(new Slice(data));
}
return true;
}
bool FluidMechanics::Impl::loadVelocityDataSet(const std::string& fileName)
{
if (!data)
throw std::runtime_error("No dataset currently loaded");
VTKOutputWindow::install();
const std::string ext = fileName.substr(fileName.find_last_of(".") + 1);
if (ext == "vtk")
velocityData = loadTypedDataSet<vtkDataSetReader>(fileName);
else if (ext == "vti")
velocityData = loadTypedDataSet<vtkXMLImageDataReader>(fileName);
else
throw std::runtime_error("Error loading data: unknown extension: \"" + ext + "\"");
int velocityDataDim[3];
velocityData->GetDimensions(velocityDataDim);
if (velocityDataDim[0] != dataDim[0]
|| velocityDataDim[1] != dataDim[1]
|| velocityDataDim[2] != dataDim[2])
{
throw std::runtime_error(
"Dimensions do not match: "
"vel: " + Utility::toString(velocityDataDim[0]) + "x" + Utility::toString(velocityDataDim[1]) + "x" + Utility::toString(velocityDataDim[2])
+ ", data: " + Utility::toString(dataDim[0]) + "x" + Utility::toString(dataDim[1]) + "x" + Utility::toString(dataDim[2])
);
}
int dim = velocityData->GetDataDimension();
if (dim != 3)
throw std::runtime_error("Velocity data is not 3D (dimension = " + Utility::toString(dim) + ")");
if (!velocityData->GetPointData() || !velocityData->GetPointData()->GetVectors())
throw std::runtime_error("Invalid velocity data: no vectors found");
return true;
}
Vector3 FluidMechanics::Impl::posToDataCoords(const Vector3& pos)
{
Vector3 result;
synchronized(state->modelMatrix) {
// Transform "pos" into object space
result = state->modelMatrix.inverse() * pos;
}
// Compensate for the scale factor
result *= 1/settings->zoomFactor;
// The data origin is on the corner, not the center
result += Vector3(dataDim[0]/2, dataDim[1]/2, dataDim[2]/2) * dataSpacing;
return result;
}
Vector3 FluidMechanics::Impl::particleJitter()
{
return Vector3(
(float(std::rand()) / RAND_MAX),
(float(std::rand()) / RAND_MAX),
(float(std::rand()) / RAND_MAX)
) * 1.0f;
// ) * 0.5f;
}
void FluidMechanics::Impl::buttonPressed()
{
buttonIsPressed = true;
}
float FluidMechanics::Impl::buttonReleased()
{
buttonIsPressed = false;
settings->surfacePreview = false;
try {
updateSurfacePreview();
return settings->surfacePercentage;
} catch (const std::exception& e) {
LOGD("Exception: %s", e.what());
return 0.0f;
}
}
void FluidMechanics::Impl::resetParticles(){
for (Particle& p : particles) {
p.pos = Vector3(0, 0, 0);
p.stallMs = 0;
p.valid = false;
}
}
void FluidMechanics::Impl::releaseParticles()
{
/*if (!velocityData || !state->tangibleVisible || !state->stylusVisible ||
(interactionMode!=seedPointTangible && interactionMode!=seedPointTouch &&
interactionMode != seedPointHybrid )){
LOGD("Cannot place Seed");
seedPointPlacement = false ;
return;
}*/
//LOGD("Conditions met to place particles");
Matrix4 smm;
synchronized (state->stylusModelMatrix) {
smm = state->stylusModelMatrix;
}
//LOGD("Got stylus Model Matrix");
//const float size = 0.5f * (stylusEffectorDist + std::max(dataSpacing.x*dataDim[0], std::max(dataSpacing.y*dataDim[1], dataSpacing.z*dataDim[2])));
//Vector3 dataPos = posToDataCoords(smm * Matrix4::makeTransform(Vector3(-size, 0, 0)*settings->zoomFactor) * Vector3::zero());
Vector3 tmp = Vector3(-10000.0,-10000.0,-10000.0);
if(seedPoint == tmp){
return ;
}
Vector3 dataPos = posToDataCoords(seedPoint) ;
if (dataPos.x < 0 || dataPos.y < 0 || dataPos.z < 0
|| dataPos.x >= dataDim[0] || dataPos.y >= dataDim[1] || dataPos.z >= dataDim[2])
{
LOGD("outside bounds");
//seedPointPlacement = false ;
return;
}
LOGD("Coords correct");
DataCoords coords(dataPos.x, dataPos.y, dataPos.z);
clock_gettime(CLOCK_REALTIME, &particleStartTime);
int delay = 0;
LOGD("Starting Particle Computation");
synchronized (particles) {
for (Particle& p : particles) {
p.pos = Vector3(coords.x, coords.y, coords.z) + particleJitter();
p.lastTime = particleStartTime;
p.delayMs = delay;
delay += particleReleaseDuration/particles.size();
p.stallMs = 0;
p.valid = true;
}
}
}
/*void FluidMechanics::Impl::releaseParticles()
{
if (!velocityData || !state->tangibleVisible || !state->stylusVisible)
return;
Matrix4 smm;
synchronized (state->stylusModelMatrix) {
smm = state->stylusModelMatrix;
}
const float size = 0.5f * (stylusEffectorDist + std::max(dataSpacing.x*dataDim[0], std::max(dataSpacing.y*dataDim[1], dataSpacing.z*dataDim[2])));
Vector3 dataPos = posToDataCoords(smm * Matrix4::makeTransform(Vector3(-size, 0, 0)*settings->zoomFactor) * Vector3::zero());
if (dataPos.x < 0 || dataPos.y < 0 || dataPos.z < 0
|| dataPos.x >= dataDim[0] || dataPos.y >= dataDim[1] || dataPos.z >= dataDim[2])
{
LOGD("outside bounds");
return;
}
DataCoords coords(dataPos.x, dataPos.y, dataPos.z);
// LOGD("coords = %s", Utility::toString(coords).c_str());
// vtkDataArray* vectors = velocityData->GetPointData()->GetVectors();
// double* v = vectors->GetTuple3(coords.z*(dataDim[0]*dataDim[1]) + coords.y*dataDim[0] + coords.x);
// LOGD("v = %f, %f, %f", v[0], v[1], v[2]);
// TODO(?)
// vtkNew<vtkStreamLine> streamLine;
// streamLine->SetInputData(velocityData);
// // streamLine->SetStartPosition(coords.x, coords.y, coords.z);
// streamLine->SetStartPosition(dataPos.x, dataPos.y, dataPos.z);
// streamLine->SetMaximumPropagationTime(200);
// streamLine->SetIntegrationStepLength(.2);
// streamLine->SetStepLength(.001);
// streamLine->SetNumberOfThreads(1);
// streamLine->SetIntegrationDirectionToForward();
// streamLine->Update();
// vtkDataArray* vectors = streamLine->GetPointData()->GetVectors();
// android_assert(vectors);
// unsigned int num = vectors->GetNumberOfTuples();
// LOGD("num = %d", num);
// for (unsigned int i = 0; i < num; ++j) {
// double* v = vectors->GetTuple3(i);
// Vector3 pos(v[0], v[1], v[2]);
// LOGD("pos = %s", Utility::toString(pos).c_str());
// }
clock_gettime(CLOCK_REALTIME, &particleStartTime);
int delay = 0;
synchronized (particles) {
for (Particle& p : particles) {
p.pos = Vector3(coords.x, coords.y, coords.z) + particleJitter();
p.lastTime = particleStartTime;
p.delayMs = delay;
delay += particleReleaseDuration/particles.size();
p.stallMs = 0;
p.valid = true;
}
}
}*/
void FluidMechanics::Impl::integrateParticleMotion(Particle& p)
{
if (!p.valid)
return;
// Pause particle motion when the data is not visible
if (!state->tangibleVisible)
return;
timespec now;
clock_gettime(CLOCK_REALTIME, &now);
int elapsedMs = (now.tv_sec - p.lastTime.tv_sec) * 1000
+ (now.tv_nsec - p.lastTime.tv_nsec) / 1000000;
p.lastTime = now;
if (p.delayMs > 0) {
p.delayMs -= elapsedMs;
if (p.delayMs < 0)
elapsedMs = -p.delayMs;
else
return;
}
if (p.stallMs > 0) {
p.stallMs -= elapsedMs;
if (p.stallMs < 0)
p.valid = false;
return;
}
vtkDataArray* vectors = velocityData->GetPointData()->GetVectors();
while (elapsedMs > 0) {
--elapsedMs;
DataCoords coords = DataCoords(p.pos.x, p.pos.y, p.pos.z);
if (coords.x < 0 || coords.y < 0 || coords.z < 0
|| coords.x >= dataDim[0] || coords.y >= dataDim[1] || coords.z >= dataDim[2])
{
// LOGD("particle moved outside bounds");
p.valid = false;
return;
}
double* v = vectors->GetTuple3(coords.z*(dataDim[0]*dataDim[1]) + coords.y*dataDim[0] + coords.x);
// LOGD("v = %f, %f, %f", v[0], v[1], v[2]);
// Vector3 vel(v[0], v[1], v[2]);
Vector3 vel(v[1], v[0], v[2]); // XXX: workaround for a wrong data orientation
//if (!vel.isNull()) {
if (vel.length() > 0.001f) {
p.pos += vel * particleSpeed;
} else {
// LOGD("particle stopped");
p.stallMs = particleStallDuration;
break;
}
}
}
bool FluidMechanics::Impl::computeCameraClipPlane(Vector3& point, Vector3& normal)
{
// static const float weight = 0.3f;
// static const float weight = 0.5f;
static const float weight = 0.8f;
static bool wasVisible = false;
static Vector3 prevPos;
if (!state->tangibleVisible) {
wasVisible = false;
return false;
}
Matrix4 slicingMatrix;
// synchronized(modelMatrix) { // not needed since this thread is the only one to write to "modelMatrix"
// Compute the inverse rotation matrix to render this
// slicing plane
slicingMatrix = Matrix4((app->getProjMatrix() * state->modelMatrix).inverse().get3x3Matrix());
// }
// Compute the slicing origin location in data coordinates:
// Center of the screen (at depth "clipDist")
Vector3 screenSpacePos = Vector3(0, 0, settings->clipDist);
// Transform the position in object space
Vector3 pos = state->modelMatrix.inverse() * screenSpacePos;
// Transform the screen normal in object space
Vector3 n = (state->modelMatrix.transpose().get3x3Matrix() * Vector3::unitZ()).normalized();
// Filter "pos" using a weighted average, but only in the
// "n" direction (the screen direction)
// TODO: Kalman filter?
if (wasVisible)
pos += -n.project(pos) + n.project(pos*weight + prevPos*(1-weight));
wasVisible = true;
prevPos = pos;
// Transform the position back in screen space
screenSpacePos = state->modelMatrix * pos;
// Store the computed depth
sliceDepth = screenSpacePos.z;
// Unproject the center of the screen (at the computed depth
// "sliceDepth"), then convert the result into data coordinates
Vector3 pt = app->getProjMatrix().inverse() * Vector3(0, 0, app->getDepthValue(sliceDepth));
Vector3 dataCoords = posToDataCoords(pt);
slicingMatrix.setPosition(dataCoords);
synchronized(slice) {
slice->setSlice(slicingMatrix, sliceDepth, settings->zoomFactor);
}
point = pt;
normal = -Vector3::unitZ();
return true;
}
bool FluidMechanics::Impl::computeAxisClipPlane(Vector3& point, Vector3& normal)
{
if (state->tangibleVisible) {
Matrix3 normalMatrix = state->modelMatrix.inverse().transpose().get3x3Matrix();
float xDot = (normalMatrix*Vector3::unitX()).normalized().dot(Vector3::unitZ());
float yDot = (normalMatrix*Vector3::unitY()).normalized().dot(Vector3::unitZ());
float zDot = (normalMatrix*Vector3::unitZ()).normalized().dot(Vector3::unitZ());
// Prevent back and forth changes between two axis (unless no
// axis is defined yet)
const float margin = (state->clipAxis != CLIP_NONE ? 0.1f : 0.0f);
if (std::abs(xDot) > std::abs(yDot)+margin && std::abs(xDot) > std::abs(zDot)+margin) {
state->clipAxis = (xDot < 0 ? CLIP_AXIS_X : CLIP_NEG_AXIS_X);
} else if (std::abs(yDot) > std::abs(xDot)+margin && std::abs(yDot) > std::abs(zDot)+margin) {
state->clipAxis = (yDot < 0 ? CLIP_AXIS_Y : CLIP_NEG_AXIS_Y);
} else if (std::abs(zDot) > std::abs(xDot)+margin && std::abs(zDot) > std::abs(yDot)+margin) {
state->clipAxis = (zDot < 0 ? CLIP_AXIS_Z : CLIP_NEG_AXIS_Z);
}
if (state->lockedClipAxis != CLIP_NONE) {
Vector3 axis;
ClipAxis neg;
switch (state->lockedClipAxis) {
case CLIP_AXIS_X: axis = Vector3::unitX(); neg = CLIP_NEG_AXIS_X; break;
case CLIP_AXIS_Y: axis = Vector3::unitY(); neg = CLIP_NEG_AXIS_Y; break;
case CLIP_AXIS_Z: axis = Vector3::unitZ(); neg = CLIP_NEG_AXIS_Z; break;
case CLIP_NEG_AXIS_X: axis = -Vector3::unitX(); neg = CLIP_AXIS_X; break;
case CLIP_NEG_AXIS_Y: axis = -Vector3::unitY(); neg = CLIP_AXIS_Y; break;
case CLIP_NEG_AXIS_Z: axis = -Vector3::unitZ(); neg = CLIP_AXIS_Z; break;
default: android_assert(false);
}
float dot = (normalMatrix*axis).normalized().dot(Vector3::unitZ());
if (dot > 0)
state->lockedClipAxis = neg;
}
} else {
state->clipAxis = state->lockedClipAxis = CLIP_NONE;
}
const ClipAxis ca = (state->lockedClipAxis != CLIP_NONE ? state->lockedClipAxis : state->clipAxis);
if (ca == CLIP_NONE)
return false;
Vector3 axis;
Quaternion rot;
switch (ca) {
case CLIP_AXIS_X: axis = Vector3::unitX(); rot = Quaternion(Vector3::unitY(), -M_PI/2)*Quaternion(Vector3::unitZ(), M_PI); break;
case CLIP_AXIS_Y: axis = Vector3::unitY(); rot = Quaternion(Vector3::unitX(), M_PI/2)*Quaternion(Vector3::unitZ(), M_PI); break;
case CLIP_AXIS_Z: axis = Vector3::unitZ(); rot = Quaternion::identity(); break;
case CLIP_NEG_AXIS_X: axis = -Vector3::unitX(); rot = Quaternion(Vector3::unitY(), M_PI/2)*Quaternion(Vector3::unitZ(), M_PI); break;
case CLIP_NEG_AXIS_Y: axis = -Vector3::unitY(); rot = Quaternion(Vector3::unitX(), -M_PI/2)*Quaternion(Vector3::unitZ(), M_PI); break;
case CLIP_NEG_AXIS_Z: axis = -Vector3::unitZ(); rot = Quaternion(Vector3::unitX(), M_PI); break;
default: android_assert(false);
}
// Project "pt" on the chosen axis in object space
Vector3 pt = state->modelMatrix.inverse() * app->getProjMatrix().inverse() * Vector3(0, 0, app->getDepthValue(settings->clipDist));
Vector3 absAxis = Vector3(std::abs(axis.x), std::abs(axis.y), std::abs(axis.z));
Vector3 pt2 = absAxis * absAxis.dot(pt);
// Return to eye space
pt2 = state->modelMatrix * pt2;
Vector3 dataCoords = posToDataCoords(pt2);
// static const float size = 128.0f;
const float size = 0.5f * std::max(dataSpacing.x*dataDim[0], std::max(dataSpacing.y*dataDim[1], dataSpacing.z*dataDim[2]));
Matrix4 proj = app->getProjMatrix(); proj[0][0] = -proj[1][1] / 1.0f; // same as "projMatrix", but with aspect = 1
Matrix4 slicingMatrix = Matrix4((proj * Matrix4::makeTransform(dataCoords, rot)).inverse().get3x3Matrix());
slicingMatrix.setPosition(dataCoords);
synchronized(slice) {
slice->setSlice(slicingMatrix, -proj[1][1]*size*settings->zoomFactor, settings->zoomFactor);
}
synchronized(state->sliceModelMatrix) {
state->sliceModelMatrix = Matrix4(state->modelMatrix * Matrix4::makeTransform(state->modelMatrix.inverse() * pt2, rot, settings->zoomFactor*Vector3(size, size, 0.0f)));
}
if (!slice->isEmpty())
state->lockedClipAxis = ca;
else
state->lockedClipAxis = CLIP_NONE;
point = pt2;
normal = state->modelMatrix.inverse().transpose().get3x3Matrix() * axis;
return true;
}
bool FluidMechanics::Impl::computeStylusClipPlane(Vector3& point, Vector3& normal)
{
#if 0
// static const float posWeight = 0.7f;
// static const float rotWeight = 0.8f;
static const float posWeight = 0.8f;
static const float rotWeight = 0.8f;
static bool wasVisible = false;
static Matrix4 prevMatrix;
if (!state->stylusVisible) {
wasVisible = false;
return false;
}
#else
if (!state->stylusVisible)
return false;
#endif
// FIXME: state->stylusModelMatrix may be invalid (non-invertible) in some cases
try {
// Vector3 pt = state->stylusModelMatrix * Vector3::zero();
// LOGD("normal = %s", Utility::toString(normal).c_str());
// LOGD("pt = %s", Utility::toString(pt).c_str());
// static const float size = 128.0f;
// static const float size = 180.0f;
const float size = 0.5f * (60.0f + std::max(dataSpacing.x*dataDim[0], std::max(dataSpacing.y*dataDim[1], dataSpacing.z*dataDim[2])));
Matrix4 planeMatrix = state->stylusModelMatrix;
// Matrix4 planeMatrix = state->stylusModelMatrix;
// // planeMatrix = planeMatrix * Matrix4::makeTransform(Vector3(-size, 0, 0)*settings->zoomFactor);
// Project the stylus->data vector onto the stylus X axis
Vector3 dataPosInStylusSpace = state->stylusModelMatrix.inverse() * state->modelMatrix * Vector3::zero();
// Shift the clip plane along the stylus X axis in order to
// reach the data, even if the stylus is far away
// Vector3 offset = (-Vector3::unitX()).project(dataPosInStylusSpace);
// Shift the clip plane along the other axis in order to keep
// it centered on the data
Vector3 n = Vector3::unitZ(); // plane normal in stylus space
// Vector3 v = dataPosInStylusSpace - offset; // vector from the temporary position to the data center point
// offset += v.planeProject(n); // project "v" on the plane, and shift the clip plane according to the result
Vector3 v = dataPosInStylusSpace;
Vector3 offset = v.projectOnPlane(n); // project "v" on the plane, and shift the clip plane according to the result
// Apply the computed offset
planeMatrix = planeMatrix * Matrix4::makeTransform(offset);
// The slice will be rendered from the viewpoint of the plane
Matrix4 proj = app->getProjMatrix(); proj[0][0] = -proj[1][1] / 1.0f; // same as "projMatrix", but with aspect = 1
Matrix4 slicingMatrix = Matrix4((proj * planeMatrix.inverse() * state->modelMatrix).inverse().get3x3Matrix());
Vector3 pt2 = planeMatrix * Vector3::zero();
// Position of the stylus tip, in data coordinates
Vector3 dataCoords = posToDataCoords(pt2);
// LOGD("dataCoords = %s", Utility::toString(dataCoords).c_str());
slicingMatrix.setPosition(dataCoords);
synchronized(slice) {
slice->setSlice(slicingMatrix, -proj[1][1]*size*settings->zoomFactor, settings->zoomFactor);
}
synchronized(state->sliceModelMatrix) {
state->sliceModelMatrix = Matrix4(planeMatrix * Matrix4::makeTransform(Vector3::zero(), Quaternion::identity(), settings->zoomFactor*Vector3(size, size, 0.0f)));
}
point = pt2;
normal = state->stylusModelMatrix.inverse().transpose().get3x3Matrix() * Vector3::unitZ();
} catch (const std::exception& e) { LOGD("%s", e.what()); return false; }
return true;
}
Vector3 FluidMechanics::Impl::dataCoordsToPos(const Vector3& dataCoords)
{
Vector3 result = dataCoords;
// The data origin is on the corner, not the center
result -= Vector3(dataDim[0]/2, dataDim[1]/2, dataDim[2]/2) * dataSpacing;
// Compensate for the scale factor
result *= settings->zoomFactor;
synchronized(state->modelMatrix) {
// Transform "result" into eye space
result = state->modelMatrix * result;
}
return result;
}
template <typename T>
T lowPassFilter(const T& cur, const T& prev, float alpha)
{ return prev + alpha * (cur-prev); }
void FluidMechanics::Impl::setMatrices(const Matrix4& volumeMatrix, const Matrix4& stylusMatrix)
{
synchronized(state->modelMatrix) {
state->modelMatrix = volumeMatrix;
}
synchronized(state->stylusModelMatrix) {
state->stylusModelMatrix = stylusMatrix;
}
updateSlicePlanes();
}
void FluidMechanics::Impl::updateSlicePlanes()
{
if (state->stylusVisible) {
if (state->tangibleVisible) { // <-- because of posToDataCoords()
// Effector 2
const float size = 0.5f * (stylusEffectorDist + std::max(dataSpacing.x*dataDim[0], std::max(dataSpacing.y*dataDim[1], dataSpacing.z*dataDim[2])));
Vector3 dataPos = posToDataCoords(state->stylusModelMatrix * Matrix4::makeTransform(Vector3(-size, 0, 0)*settings->zoomFactor) * Vector3::zero());
if (dataPos.x >= 0 && dataPos.y >= 0 && dataPos.z >= 0
&& dataPos.x < dataDim[0]*dataSpacing.x && dataPos.y < dataDim[1]*dataSpacing.y && dataPos.z < dataDim[2]*dataSpacing.z)
{
// const auto rayPlaneIntersection2 = [](const Vector3& rayPoint, const Vector3& rayDir, const Vector3& planePoint, const Vector3& planeNormal, float& t) -> bool {
// float dot = rayDir.dot(planeNormal);
// if (dot != 0) {
// t = -(rayPoint.dot(planeNormal) - planeNormal.dot(planePoint)) / dot;
// LOGD("rayPlaneIntersection2 %s %s %s %s => %f", Utility::toString(rayPoint).c_str(), Utility::toString(rayDir).c_str(), Utility::toString(planePoint).c_str(), Utility::toString(planeNormal).c_str(), t);
// return true;
// } else {
// LOGD("rayPlaneIntersection2 %s %s %s %s => [dot=%f]", Utility::toString(rayPoint).c_str(), Utility::toString(rayDir).c_str(), Utility::toString(planePoint).c_str(), Utility::toString(planeNormal).c_str(), dot);
// return false;
// }
// };
const auto rayAABBIntersection = [](const Vector3& rayPoint, const Vector3& rayDir, const Vector3& aabbMin, const Vector3& aabbMax, float& tmin, float& tmax) -> bool {
// http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
float tmin_ = (aabbMin.x - rayPoint.x) / rayDir.x;
float tmax_ = (aabbMax.x - rayPoint.x) / rayDir.x;
if (tmin_ > tmax_) std::swap(tmin_, tmax_);
float tymin = (aabbMin.y - rayPoint.y) / rayDir.y;
float tymax = (aabbMax.y - rayPoint.y) / rayDir.y;
if (tymin > tymax) std::swap(tymin, tymax);
if ((tmin_ > tymax) || (tymin > tmax_))
return false;
if (tymin > tmin_)
tmin_ = tymin;
if (tymax < tmax_)
tmax_ = tymax;
float tzmin = (aabbMin.z - rayPoint.z) / rayDir.z;
float tzmax = (aabbMax.z - rayPoint.z) / rayDir.z;
if (tzmin > tzmax) std::swap(tzmin, tzmax);
if ((tmin_ > tzmax) || (tzmin > tmax_))
return false;
if (tzmin > tmin_)
tmin_ = tzmin;
if (tzmax < tmax_)
tmax_ = tzmax;
if ((tmin_ > tmax) || (tmax_ < tmin)) return false;
if (tmin < tmin_) tmin = tmin_;
if (tmax > tmax_) tmax = tmax_;
// LOGD("tmin = %f, tmax = %f", tmin, tmax);
return true;
};
// const auto getAABBNormalAt = [](Vector3 point, const Vector3& aabbMin, const Vector3& aabbMax) -> Vector3 {
// const auto sign = [](float value) {
// return (value >= 0 ? 1 : -1);
// };
// // http://www.gamedev.net/topic/551816-finding-the-aabb-surface-normal-from-an-intersection-point-on-aabb/#entry4549909
// Vector3 normal = Vector3::zero();
// float min = std::numeric_limits<float>::max();
// float distance;
// Vector3 extents = aabbMax-aabbMin;
// Vector3 center = (aabbMax+aabbMin)/2;
// point -= center;
// LOGD("point = %s, extents = %s", Utility::toString(point).c_str(), Utility::toString(extents).c_str());
// distance = std::abs(extents.x - std::abs(point.x));
// if (distance < min) {
// min = distance;
// normal = sign(point.x) * Vector3::unitX();
// }
// distance = std::abs(extents.y - std::abs(point.y));
// if (distance < min) {
// min = distance;
// normal = sign(point.y) * Vector3::unitY();
// }
// distance = std::abs(extents.z - std::abs(point.z));
// if (distance < min) {
// min = distance;
// normal = sign(point.z) * Vector3::unitZ();
// }
// return normal;
// };
// Same as posToDataCoords(), but for directions (not positions)
// (direction goes from the effector to the stylus: +X axis)
Vector3 dataDir = state->modelMatrix.transpose().get3x3Matrix() * state->stylusModelMatrix.inverse().transpose().get3x3Matrix() * Vector3::unitX();
// static const float min = 0.0f;
// const float max = settings->zoomFactor;
// float t;
float tmin = 0, tmax = 10000;
synchronized (effectorIntersection) {
// effectorIntersection = Vector3::zero();
effectorIntersectionValid = false;
// if (rayPlaneIntersection2(dataPos, dataDir, Vector3(0, 0, 0), -Vector3::unitX(), t) && t >= min && t <= max)
// effectorIntersection = dataCoordsToPos(dataPos + dataDir*t);
// if (rayPlaneIntersection2(dataPos, dataDir, Vector3(dataDim[0]*dataSpacing.x, 0, 0), Vector3::unitX(), t) && t >= min && t <= max)
// effectorIntersection = dataCoordsToPos(dataPos + dataDir*t);
// if (rayPlaneIntersection2(dataPos, dataDir, Vector3(0, 0, 0), -Vector3::unitY(), t) && t >= min && t <= max)
// effectorIntersection = dataCoordsToPos(dataPos + dataDir*t);
// if (rayPlaneIntersection2(dataPos, dataDir, Vector3(0, dataDim[1]*dataSpacing.y, 0), Vector3::unitY(), t) && t >= min && t <= max)
// effectorIntersection = dataCoordsToPos(dataPos + dataDir*t);
// if (rayPlaneIntersection2(dataPos, dataDir, Vector3(0, 0, 0), -Vector3::unitZ(), t) && t >= min && t <= max)
// effectorIntersection = dataCoordsToPos(dataPos + dataDir*t);
// if (rayPlaneIntersection2(dataPos, dataDir, Vector3(0, 0, dataDim[2]*dataSpacing.z), Vector3::unitZ(), t) && t >= min && t <= max)
// effectorIntersection = dataCoordsToPos(dataPos + dataDir*t);
if (rayAABBIntersection(dataPos, dataDir, Vector3::zero(), Vector3(dataDim[0], dataDim[1], dataDim[2])*dataSpacing, tmin, tmax) && tmax > 0) {
effectorIntersection = dataCoordsToPos(dataPos + dataDir*tmax);
// effectorIntersectionNormal = state->modelMatrix.transpose().get3x3Matrix() * getAABBNormalAt(dataPos + dataDir*tmax, Vector3::zero(), Vector3(dataDim[0], dataDim[1], dataDim[2])*dataSpacing);
// LOGD("intersection = %s", Utility::toString(posToDataCoords(effectorIntersection)).c_str());
// LOGD("intersection normal = %s", Utility::toString(getAABBNormalAt(dataPos + dataDir*tmax, Vector3::zero(), Vector3(dataDim[0], dataDim[1], dataDim[2])*dataSpacing)).c_str());
effectorIntersectionValid = true;