forked from KeckCAVES/SARndbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sandbox.cpp
1481 lines (1325 loc) · 53.9 KB
/
Sandbox.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
/***********************************************************************
Sandbox - Vrui application to drive an augmented reality sandbox.
Copyright (c) 2012-2016 Oliver Kreylos
This file is part of the Augmented Reality Sandbox (SARndbox).
The Augmented Reality Sandbox is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
The Augmented Reality Sandbox is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License along
with the Augmented Reality Sandbox; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***********************************************************************/
#include "Sandbox.h"
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string>
#include <vector>
#include <stdexcept>
#include <iostream>
#include <Misc/SizedTypes.h>
#include <Misc/SelfDestructPointer.h>
#include <Misc/FixedArray.h>
#include <Misc/FunctionCalls.h>
#include <Misc/FileNameExtensions.h>
#include <Misc/StandardValueCoders.h>
#include <Misc/ArrayValueCoders.h>
#include <Misc/ConfigurationFile.h>
#include <IO/File.h>
#include <IO/ValueSource.h>
#include <Math/Math.h>
#include <Math/Constants.h>
#include <Math/Interval.h>
#include <Math/MathValueCoders.h>
#include <Geometry/Point.h>
#include <Geometry/AffineCombiner.h>
#include <Geometry/HVector.h>
#include <Geometry/Plane.h>
#include <Geometry/LinearUnit.h>
#include <Geometry/GeometryValueCoders.h>
#include <Geometry/OutputOperators.h>
#include <GL/gl.h>
#include <GL/GLMaterialTemplates.h>
#include <GL/GLColorMap.h>
#include <GL/GLLightTracker.h>
#include <GL/Extensions/GLEXTFramebufferObject.h>
#include <GL/Extensions/GLARBTextureRectangle.h>
#include <GL/Extensions/GLARBTextureFloat.h>
#include <GL/Extensions/GLARBTextureRg.h>
#include <GL/Extensions/GLARBDepthTexture.h>
#include <GL/Extensions/GLARBShaderObjects.h>
#include <GL/Extensions/GLARBVertexShader.h>
#include <GL/Extensions/GLARBFragmentShader.h>
#include <GL/Extensions/GLARBMultitexture.h>
#include <GL/GLContextData.h>
#include <GL/GLGeometryWrappers.h>
#include <GL/GLTransformationWrappers.h>
#include <GLMotif/StyleSheet.h>
#include <GLMotif/WidgetManager.h>
#include <GLMotif/PopupMenu.h>
#include <GLMotif/Menu.h>
#include <GLMotif/PopupWindow.h>
#include <GLMotif/Margin.h>
#include <GLMotif/Label.h>
#include <GLMotif/TextField.h>
#include <Vrui/Vrui.h>
#include <Vrui/CoordinateManager.h>
#include <Vrui/Lightsource.h>
#include <Vrui/LightsourceManager.h>
#include <Vrui/Viewer.h>
#include <Vrui/ToolManager.h>
#include <Vrui/DisplayState.h>
#include <Vrui/OpenFile.h>
#include <Kinect/FileFrameSource.h>
#include <Kinect/DirectFrameSource.h>
#include <Kinect/OpenDirectFrameSource.h>
#define SAVEDEPTH 0
#if SAVEDEPTH
#include <Images/RGBImage.h>
#include <Images/WriteImageFile.h>
#endif
#include "FrameFilter.h"
#include "DepthImageRenderer.h"
#include "ElevationColorMap.h"
#include "DEM.h"
#include "SurfaceRenderer.h"
#include "WaterTable2.h"
#include "HandExtractor.h"
#include "WaterRenderer.h"
#include "GlobalWaterTool.h"
#include "LocalWaterTool.h"
#include "DEMTool.h"
#include "BathymetrySaverTool.h"
#include "Config.h"
/**********************************
Methods of class Sandbox::DataItem:
**********************************/
Sandbox::DataItem::DataItem(void)
:waterTableTime(0.0),
shadowFramebufferObject(0),shadowDepthTextureObject(0)
{
/* Check if all required extensions are supported: */
bool supported=GLEXTFramebufferObject::isSupported();
supported=supported&&GLARBTextureRectangle::isSupported();
supported=supported&&GLARBTextureFloat::isSupported();
supported=supported&&GLARBTextureRg::isSupported();
supported=supported&&GLARBDepthTexture::isSupported();
supported=supported&&GLARBShaderObjects::isSupported();
supported=supported&&GLARBVertexShader::isSupported();
supported=supported&&GLARBFragmentShader::isSupported();
supported=supported&&GLARBMultitexture::isSupported();
if(!supported)
Misc::throwStdErr("Sandbox: Not all required extensions are supported by local OpenGL");
/* Initialize all required extensions: */
GLEXTFramebufferObject::initExtension();
GLARBTextureRectangle::initExtension();
GLARBTextureFloat::initExtension();
GLARBTextureRg::initExtension();
GLARBDepthTexture::initExtension();
GLARBShaderObjects::initExtension();
GLARBVertexShader::initExtension();
GLARBFragmentShader::initExtension();
GLARBMultitexture::initExtension();
}
Sandbox::DataItem::~DataItem(void)
{
/* Delete all shaders, buffers, and texture objects: */
glDeleteFramebuffersEXT(1,&shadowFramebufferObject);
glDeleteTextures(1,&shadowDepthTextureObject);
}
/****************************************
Methods of class Sandbox::RenderSettings:
****************************************/
Sandbox::RenderSettings::RenderSettings(void)
:fixProjectorView(false),projectorTransform(PTransform::identity),projectorTransformValid(false),
hillshade(false),surfaceMaterial(GLMaterial::Color(1.0f,1.0f,1.0f)),
useShadows(false),
elevationColorMap(0),
useContourLines(true),contourLineSpacing(0.75f),
renderWaterSurface(false),waterOpacity(2.0f),
surfaceRenderer(0),waterRenderer(0)
{
/* Load the default projector transformation: */
loadProjectorTransform(CONFIG_DEFAULTPROJECTIONMATRIXFILENAME);
}
Sandbox::RenderSettings::RenderSettings(const Sandbox::RenderSettings& source)
:fixProjectorView(source.fixProjectorView),projectorTransform(source.projectorTransform),projectorTransformValid(source.projectorTransformValid),
hillshade(source.hillshade),surfaceMaterial(source.surfaceMaterial),
useShadows(source.useShadows),
elevationColorMap(source.elevationColorMap!=0?new ElevationColorMap(*source.elevationColorMap):0),
useContourLines(source.useContourLines),contourLineSpacing(source.contourLineSpacing),
renderWaterSurface(source.renderWaterSurface),waterOpacity(source.waterOpacity),
surfaceRenderer(0),waterRenderer(0)
{
}
Sandbox::RenderSettings::~RenderSettings(void)
{
delete surfaceRenderer;
delete waterRenderer;
delete elevationColorMap;
}
void Sandbox::RenderSettings::loadProjectorTransform(const char* projectorTransformName)
{
std::string fullProjectorTransformName;
try
{
/* Open the projector transformation file: */
if(projectorTransformName[0]=='/')
{
/* Use the absolute file name directly: */
fullProjectorTransformName=projectorTransformName;
}
else
{
/* Assemble a file name relative to the configuration file directory: */
fullProjectorTransformName=CONFIG_CONFIGDIR;
fullProjectorTransformName.push_back('/');
fullProjectorTransformName.append(projectorTransformName);
}
IO::FilePtr projectorTransformFile=Vrui::openFile(fullProjectorTransformName.c_str(),IO::File::ReadOnly);
projectorTransformFile->setEndianness(Misc::LittleEndian);
/* Read the projector transformation matrix from the binary file: */
Misc::Float64 pt[16];
projectorTransformFile->read(pt,16);
projectorTransform=PTransform::fromRowMajor(pt);
projectorTransformValid=true;
}
catch(std::runtime_error err)
{
/* Print an error message and disable calibrated projections: */
std::cerr<<"Unable to load projector transformation from file "<<fullProjectorTransformName<<" due to exception "<<err.what()<<std::endl;
projectorTransformValid=false;
}
}
void Sandbox::RenderSettings::loadHeightMap(const char* heightMapName)
{
try
{
/* Load the elevation color map of the given name: */
ElevationColorMap* newElevationColorMap=new ElevationColorMap(heightMapName);
/* Delete the previous elevation color map and assign the new one: */
delete elevationColorMap;
elevationColorMap=newElevationColorMap;
}
catch(std::runtime_error err)
{
std::cerr<<"Ignoring height map due to exception "<<err.what()<<std::endl;
}
}
/************************
Methods of class Sandbox:
************************/
void Sandbox::rawDepthFrameDispatcher(const Kinect::FrameBuffer& frameBuffer)
{
/* Pass the received frame to the frame filter and the hand extractor: */
if(frameFilter!=0&&!pauseUpdates)
frameFilter->receiveRawFrame(frameBuffer);
if(handExtractor!=0)
handExtractor->receiveRawFrame(frameBuffer);
}
void Sandbox::receiveFilteredFrame(const Kinect::FrameBuffer& frameBuffer)
{
/* Put the new frame into the frame input buffer: */
filteredFrames.postNewValue(frameBuffer);
/* Wake up the foreground thread: */
Vrui::requestUpdate();
}
void Sandbox::toggleDEM(DEM* dem)
{
/* Check if this is the active DEM: */
if(activeDem==dem)
{
/* Deactivate the currently active DEM: */
activeDem=0;
}
else
{
/* Activate this DEM: */
activeDem=dem;
}
/* Enable DEM matching in all surface renderers that use a fixed projector matrix, i.e., in all physical sandboxes: */
for(std::vector<RenderSettings>::iterator rsIt=renderSettings.begin();rsIt!=renderSettings.end();++rsIt)
if(rsIt->fixProjectorView)
rsIt->surfaceRenderer->setDem(activeDem);
}
void Sandbox::addWater(GLContextData& contextData) const
{
/* Check if the most recent rain object list is not empty: */
if(handExtractor!=0&&!handExtractor->getLockedExtractedHands().empty())
{
/* Render all rain objects into the water table: */
glPushAttrib(GL_ENABLE_BIT);
glDisable(GL_CULL_FACE);
/* Create a local coordinate frame to render rain disks: */
Vector z=waterTable->getBaseTransform().inverseTransform(Vector(0,0,1));
Vector x=Geometry::normal(z);
Vector y=Geometry::cross(z,x);
x.normalize();
y.normalize();
glVertexAttrib1fARB(1,rainStrength/waterSpeed);
for(HandExtractor::HandList::const_iterator hIt=handExtractor->getLockedExtractedHands().begin();hIt!=handExtractor->getLockedExtractedHands().end();++hIt)
{
/* Render a rain disk approximating the hand: */
glBegin(GL_POLYGON);
for(int i=0;i<32;++i)
{
Scalar angle=Scalar(2)*Math::Constants<Scalar>::pi*Scalar(i)/Scalar(32);
glVertex(hIt->center+x*(Math::cos(angle)*hIt->radius*0.75)+y*(Math::sin(angle)*hIt->radius*0.75));
}
glEnd();
}
glPopAttrib();
}
}
void Sandbox::pauseUpdatesCallback(GLMotif::ToggleButton::ValueChangedCallbackData* cbData)
{
pauseUpdates=cbData->set;
}
void Sandbox::showWaterControlDialogCallback(Misc::CallbackData* cbData)
{
Vrui::popupPrimaryWidget(waterControlDialog);
}
void Sandbox::waterSpeedSliderCallback(GLMotif::TextFieldSlider::ValueChangedCallbackData* cbData)
{
waterSpeed=cbData->value;
}
void Sandbox::waterMaxStepsSliderCallback(GLMotif::TextFieldSlider::ValueChangedCallbackData* cbData)
{
waterMaxSteps=int(Math::floor(cbData->value+0.5));
}
void Sandbox::waterAttenuationSliderCallback(GLMotif::TextFieldSlider::ValueChangedCallbackData* cbData)
{
waterTable->setAttenuation(GLfloat(1.0-cbData->value));
}
GLMotif::PopupMenu* Sandbox::createMainMenu(void)
{
/* Create a popup shell to hold the main menu: */
GLMotif::PopupMenu* mainMenuPopup=new GLMotif::PopupMenu("MainMenuPopup",Vrui::getWidgetManager());
mainMenuPopup->setTitle("AR Sandbox");
/* Create the main menu itself: */
GLMotif::Menu* mainMenu=new GLMotif::Menu("MainMenu",mainMenuPopup,false);
/* Create a button to pause topography updates: */
pauseUpdatesToggle=new GLMotif::ToggleButton("PauseUpdatesToggle",mainMenu,"Pause Topography");
pauseUpdatesToggle->setToggle(false);
pauseUpdatesToggle->getValueChangedCallbacks().add(this,&Sandbox::pauseUpdatesCallback);
if(waterTable!=0)
{
/* Create a button to show the water control dialog: */
GLMotif::Button* showWaterControlDialogButton=new GLMotif::Button("ShowWaterControlDialogButton",mainMenu,"Show Water Simulation Control");
showWaterControlDialogButton->getSelectCallbacks().add(this,&Sandbox::showWaterControlDialogCallback);
}
/* Finish building the main menu: */
mainMenu->manageChild();
return mainMenuPopup;
}
GLMotif::PopupWindow* Sandbox::createWaterControlDialog(void)
{
const GLMotif::StyleSheet& ss=*Vrui::getWidgetManager()->getStyleSheet();
/* Create a popup window shell: */
GLMotif::PopupWindow* waterControlDialogPopup=new GLMotif::PopupWindow("WaterControlDialogPopup",Vrui::getWidgetManager(),"Water Simulation Control");
waterControlDialogPopup->setCloseButton(true);
waterControlDialogPopup->setResizableFlags(true,false);
waterControlDialogPopup->popDownOnClose();
GLMotif::RowColumn* waterControlDialog=new GLMotif::RowColumn("WaterControlDialog",waterControlDialogPopup,false);
waterControlDialog->setOrientation(GLMotif::RowColumn::VERTICAL);
waterControlDialog->setPacking(GLMotif::RowColumn::PACK_TIGHT);
waterControlDialog->setNumMinorWidgets(2);
new GLMotif::Label("WaterSpeedLabel",waterControlDialog,"Speed");
waterSpeedSlider=new GLMotif::TextFieldSlider("WaterSpeedSlider",waterControlDialog,8,ss.fontHeight*10.0f);
waterSpeedSlider->getTextField()->setFieldWidth(7);
waterSpeedSlider->getTextField()->setPrecision(4);
waterSpeedSlider->getTextField()->setFloatFormat(GLMotif::TextField::SMART);
waterSpeedSlider->setSliderMapping(GLMotif::TextFieldSlider::EXP10);
waterSpeedSlider->setValueRange(0.001,10.0,0.05);
waterSpeedSlider->getSlider()->addNotch(0.0f);
waterSpeedSlider->setValue(waterSpeed);
waterSpeedSlider->getValueChangedCallbacks().add(this,&Sandbox::waterSpeedSliderCallback);
new GLMotif::Label("WaterMaxStepsLabel",waterControlDialog,"Max Steps");
waterMaxStepsSlider=new GLMotif::TextFieldSlider("WaterMaxStepsSlider",waterControlDialog,8,ss.fontHeight*10.0f);
waterMaxStepsSlider->getTextField()->setFieldWidth(7);
waterMaxStepsSlider->getTextField()->setPrecision(0);
waterMaxStepsSlider->getTextField()->setFloatFormat(GLMotif::TextField::FIXED);
waterMaxStepsSlider->setSliderMapping(GLMotif::TextFieldSlider::LINEAR);
waterMaxStepsSlider->setValueType(GLMotif::TextFieldSlider::UINT);
waterMaxStepsSlider->setValueRange(0,200,1);
waterMaxStepsSlider->setValue(waterMaxSteps);
waterMaxStepsSlider->getValueChangedCallbacks().add(this,&Sandbox::waterMaxStepsSliderCallback);
new GLMotif::Label("FrameRateLabel",waterControlDialog,"Frame Rate");
GLMotif::Margin* frameRateMargin=new GLMotif::Margin("FrameRateMargin",waterControlDialog,false);
frameRateMargin->setAlignment(GLMotif::Alignment::LEFT);
frameRateTextField=new GLMotif::TextField("FrameRateTextField",frameRateMargin,8);
frameRateTextField->setFieldWidth(7);
frameRateTextField->setPrecision(2);
frameRateTextField->setFloatFormat(GLMotif::TextField::FIXED);
frameRateTextField->setValue(0.0);
frameRateMargin->manageChild();
new GLMotif::Label("WaterAttenuationLabel",waterControlDialog,"Attenuation");
waterAttenuationSlider=new GLMotif::TextFieldSlider("WaterAttenuationSlider",waterControlDialog,8,ss.fontHeight*10.0f);
waterAttenuationSlider->getTextField()->setFieldWidth(7);
waterAttenuationSlider->getTextField()->setPrecision(5);
waterAttenuationSlider->getTextField()->setFloatFormat(GLMotif::TextField::SMART);
waterAttenuationSlider->setSliderMapping(GLMotif::TextFieldSlider::EXP10);
waterAttenuationSlider->setValueRange(0.001,1.0,0.01);
waterAttenuationSlider->getSlider()->addNotch(Math::log10(1.0-double(waterTable->getAttenuation())));
waterAttenuationSlider->setValue(1.0-double(waterTable->getAttenuation()));
waterAttenuationSlider->getValueChangedCallbacks().add(this,&Sandbox::waterAttenuationSliderCallback);
waterControlDialog->manageChild();
return waterControlDialogPopup;
}
namespace {
/****************
Helper functions:
****************/
void printUsage(void)
{
std::cout<<"Usage: SARndbox [option 1] ... [option n]"<<std::endl;
std::cout<<" Options:"<<std::endl;
std::cout<<" -h"<<std::endl;
std::cout<<" Prints this help message"<<std::endl;
std::cout<<" -c <camera index>"<<std::endl;
std::cout<<" Selects the local 3D camera of the given index (0: first camera"<<std::endl;
std::cout<<" on USB bus)"<<std::endl;
std::cout<<" Default: 0"<<std::endl;
std::cout<<" -f <frame file name prefix>"<<std::endl;
std::cout<<" Reads a pre-recorded 3D video stream from a pair of color/depth"<<std::endl;
std::cout<<" files of the given file name prefix"<<std::endl;
std::cout<<" -s <scale factor>"<<std::endl;
std::cout<<" Scale factor from real sandbox to simulated terrain"<<std::endl;
std::cout<<" Default: 100.0 (1:100 scale, 1cm in sandbox is 1m in terrain"<<std::endl;
std::cout<<" -slf <sandbox layout file name>"<<std::endl;
std::cout<<" Loads the sandbox layout file of the given name"<<std::endl;
std::cout<<" Default: "<<CONFIG_CONFIGDIR<<'/'<<CONFIG_DEFAULTBOXLAYOUTFILENAME<<std::endl;
std::cout<<" -er <min elevation> <max elevation>"<<std::endl;
std::cout<<" Sets the range of valid sand surface elevations relative to the"<<std::endl;
std::cout<<" ground plane in cm"<<std::endl;
std::cout<<" Default: Range of elevation color map"<<std::endl;
std::cout<<" -hmp <x> <y> <z> <offset>"<<std::endl;
std::cout<<" Sets an explicit base plane equation to use for height color mapping"<<std::endl;
std::cout<<" -nas <num averaging slots>"<<std::endl;
std::cout<<" Sets the number of averaging slots in the frame filter; latency is"<<std::endl;
std::cout<<" <num averaging slots> * 1/30 s"<<std::endl;
std::cout<<" Default: 30"<<std::endl;
std::cout<<" -sp <min num samples> <max variance>"<<std::endl;
std::cout<<" Sets the frame filter parameters minimum number of valid samples"<<std::endl;
std::cout<<" and maximum sample variance before convergence"<<std::endl;
std::cout<<" Default: 10 2"<<std::endl;
std::cout<<" -he <hysteresis envelope>"<<std::endl;
std::cout<<" Sets the size of the hysteresis envelope used for jitter removal"<<std::endl;
std::cout<<" Default: 0.1"<<std::endl;
std::cout<<" -wts <water grid width> <water grid height>"<<std::endl;
std::cout<<" Sets the width and height of the water flow simulation grid"<<std::endl;
std::cout<<" Default: 640 480"<<std::endl;
std::cout<<" -ws <water speed> <water max steps>"<<std::endl;
std::cout<<" Sets the relative speed of the water simulation and the maximum"<<std::endl;
std::cout<<" number of simulation steps per frame"<<std::endl;
std::cout<<" Default: 1.0 30"<<std::endl;
std::cout<<" -rer <min rain elevation> <max rain elevation>"<<std::endl;
std::cout<<" Sets the elevation range of the rain cloud level relative to the"<<std::endl;
std::cout<<" ground plane in cm"<<std::endl;
std::cout<<" Default: Above range of elevation color map"<<std::endl;
std::cout<<" -rs <rain strength>"<<std::endl;
std::cout<<" Sets the strength of global or local rainfall in cm/s"<<std::endl;
std::cout<<" Default: 0.25"<<std::endl;
std::cout<<" -evr <evaporation rate>"<<std::endl;
std::cout<<" Water evaporation rate in cm/s"<<std::endl;
std::cout<<" Default: 0.0"<<std::endl;
std::cout<<" -dds <DEM distance scale>"<<std::endl;
std::cout<<" DEM matching distance scale factor in cm"<<std::endl;
std::cout<<" Default: 1.0"<<std::endl;
std::cout<<" -wi <window index>"<<std::endl;
std::cout<<" Sets the zero-based index of the display window to which the"<<std::endl;
std::cout<<" following rendering settings are applied"<<std::endl;
std::cout<<" Default: 0"<<std::endl;
std::cout<<" -fpv [projector transform file name]"<<std::endl;
std::cout<<" Fixes the navigation transformation so that Kinect camera and"<<std::endl;
std::cout<<" projector are aligned, as defined by the projector transform file"<<std::endl;
std::cout<<" of the given name"<<std::endl;
std::cout<<" Default projector transform file name: "<<CONFIG_CONFIGDIR<<'/'<<CONFIG_DEFAULTPROJECTIONMATRIXFILENAME<<std::endl;
std::cout<<" -nhs"<<std::endl;
std::cout<<" Disables hill shading"<<std::endl;
std::cout<<" -uhs"<<std::endl;
std::cout<<" Enables hill shading"<<std::endl;
std::cout<<" -ns"<<std::endl;
std::cout<<" Disables shadows"<<std::endl;
std::cout<<" -us"<<std::endl;
std::cout<<" Enables shadows"<<std::endl;
std::cout<<" -nhm"<<std::endl;
std::cout<<" Disables elevation color mapping"<<std::endl;
std::cout<<" -uhm [elevation color map file name]"<<std::endl;
std::cout<<" Enables elevation color mapping and loads the elevation color map from"<<std::endl;
std::cout<<" the file of the given name"<<std::endl;
std::cout<<" Default elevation color map file name: "<<CONFIG_CONFIGDIR<<'/'<<CONFIG_DEFAULTHEIGHTCOLORMAPFILENAME<<std::endl;
std::cout<<" -ncl"<<std::endl;
std::cout<<" Disables topographic contour lines"<<std::endl;
std::cout<<" -ucl [contour line spacing]"<<std::endl;
std::cout<<" Enables topographic contour lines and sets the elevation distance between"<<std::endl;
std::cout<<" adjacent contour lines to the given value in cm"<<std::endl;
std::cout<<" Default contour line spacing: 0.75"<<std::endl;
std::cout<<" -rws"<<std::endl;
std::cout<<" Renders water surface as geometric surface"<<std::endl;
std::cout<<" -rwt"<<std::endl;
std::cout<<" Renders water surface as texture"<<std::endl;
std::cout<<" -wo <water opacity>"<<std::endl;
std::cout<<" Sets the water depth at which water appears opaque in cm"<<std::endl;
std::cout<<" Default: 2.0"<<std::endl;
std::cout<<" -cp <control pipe name>"<<std::endl;
std::cout<<" Sets the name of a named POSIX pipe from which to read control commands"<<std::endl;
}
}
Sandbox::Sandbox(int& argc,char**& argv)
:Vrui::Application(argc,argv),
camera(0),pixelDepthCorrection(0),
frameFilter(0),pauseUpdates(false),
depthImageRenderer(0),
waterTable(0),
handExtractor(0),addWaterFunction(0),addWaterFunctionRegistered(false),
sun(0),
activeDem(0),
mainMenu(0),pauseUpdatesToggle(0),waterControlDialog(0),
waterSpeedSlider(0),waterMaxStepsSlider(0),frameRateTextField(0),waterAttenuationSlider(0),
controlPipeFd(-1)
{
/* Read the sandbox's default configuration parameters: */
std::string sandboxConfigFileName=CONFIG_CONFIGDIR;
sandboxConfigFileName.push_back('/');
sandboxConfigFileName.append(CONFIG_DEFAULTCONFIGFILENAME);
Misc::ConfigurationFile sandboxConfigFile(sandboxConfigFileName.c_str());
Misc::ConfigurationFileSection cfg=sandboxConfigFile.getSection("/SARndbox");
unsigned int cameraIndex=cfg.retrieveValue<int>("./cameraIndex",0);
std::string cameraConfiguration=cfg.retrieveString("./cameraConfiguration","Camera");
double scale=cfg.retrieveValue<double>("./scaleFactor",100.0);
std::string sandboxLayoutFileName=CONFIG_CONFIGDIR;
sandboxLayoutFileName.push_back('/');
sandboxLayoutFileName.append(CONFIG_DEFAULTBOXLAYOUTFILENAME);
sandboxLayoutFileName=cfg.retrieveString("./sandboxLayoutFileName",sandboxLayoutFileName);
Math::Interval<double> elevationRange=cfg.retrieveValue<Math::Interval<double> >("./elevationRange",Math::Interval<double>(-1000.0,1000.0));
bool haveHeightMapPlane=cfg.hasTag("./heightMapPlane");
Plane heightMapPlane;
if(haveHeightMapPlane)
heightMapPlane=cfg.retrieveValue<Plane>("./heightMapPlane");
unsigned int numAveragingSlots=cfg.retrieveValue<unsigned int>("./numAveragingSlots",30);
unsigned int minNumSamples=cfg.retrieveValue<unsigned int>("./minNumSamples",10);
unsigned int maxVariance=cfg.retrieveValue<unsigned int>("./maxVariance",2);
float hysteresis=cfg.retrieveValue<float>("./hysteresis",0.1f);
Misc::FixedArray<unsigned int,2> wtSize;
wtSize[0]=640;
wtSize[1]=480;
wtSize=cfg.retrieveValue<Misc::FixedArray<unsigned int,2> >("./waterTableSize",wtSize);
waterSpeed=cfg.retrieveValue<double>("./waterSpeed",1.0);
waterMaxSteps=cfg.retrieveValue<unsigned int>("./waterMaxSteps",30U);
Math::Interval<double> rainElevationRange=cfg.retrieveValue<Math::Interval<double> >("./rainElevationRange",Math::Interval<double>(-1000.0,1000.0));
rainStrength=cfg.retrieveValue<GLfloat>("./rainStrength",0.25f);
double evaporationRate=cfg.retrieveValue<double>("./evaporationRate",0.0);
float demDistScale=cfg.retrieveValue<float>("./demDistScale",1.0f);
std::string controlPipeName=cfg.retrieveString("./controlPipeName","");
/* Process command line parameters: */
bool printHelp=false;
const char* frameFilePrefix=0;
int windowIndex=0;
renderSettings.push_back(RenderSettings());
for(int i=1;i<argc;++i)
{
if(argv[i][0]=='-')
{
if(strcasecmp(argv[i]+1,"h")==0)
printHelp=true;
else if(strcasecmp(argv[i]+1,"c")==0)
{
++i;
cameraIndex=atoi(argv[i]);
}
else if(strcasecmp(argv[i]+1,"f")==0)
{
++i;
frameFilePrefix=argv[i];
}
else if(strcasecmp(argv[i]+1,"s")==0)
{
++i;
scale=atof(argv[i]);
}
else if(strcasecmp(argv[i]+1,"slf")==0)
{
++i;
sandboxLayoutFileName=argv[i];
}
else if(strcasecmp(argv[i]+1,"er")==0)
{
++i;
double elevationMin=atof(argv[i]);
++i;
double elevationMax=atof(argv[i]);
elevationRange=Math::Interval<double>(elevationMin,elevationMax);
}
else if(strcasecmp(argv[i]+1,"hmp")==0)
{
/* Read height mapping plane coefficients: */
haveHeightMapPlane=true;
double hmp[4];
for(int j=0;j<4;++j)
{
++i;
hmp[j]=atof(argv[i]);
}
heightMapPlane=Plane(Plane::Vector(hmp),hmp[3]);
heightMapPlane.normalize();
}
else if(strcasecmp(argv[i]+1,"nas")==0)
{
++i;
numAveragingSlots=atoi(argv[i]);
}
else if(strcasecmp(argv[i]+1,"sp")==0)
{
++i;
minNumSamples=atoi(argv[i]);
++i;
maxVariance=atoi(argv[i]);
}
else if(strcasecmp(argv[i]+1,"he")==0)
{
++i;
hysteresis=float(atof(argv[i]));
}
else if(strcasecmp(argv[i]+1,"wts")==0)
{
for(int j=0;j<2;++j)
{
++i;
wtSize[j]=(unsigned int)(atoi(argv[i]));
}
}
else if(strcasecmp(argv[i]+1,"ws")==0)
{
++i;
waterSpeed=atof(argv[i]);
++i;
waterMaxSteps=atoi(argv[i]);
}
else if(strcasecmp(argv[i]+1,"rer")==0)
{
++i;
double rainElevationMin=atof(argv[i]);
++i;
double rainElevationMax=atof(argv[i]);
rainElevationRange=Math::Interval<double>(rainElevationMin,rainElevationMax);
}
else if(strcasecmp(argv[i]+1,"rs")==0)
{
++i;
rainStrength=GLfloat(atof(argv[i]));
}
else if(strcasecmp(argv[i]+1,"evr")==0)
{
++i;
evaporationRate=atof(argv[i]);
}
else if(strcasecmp(argv[i]+1,"dds")==0)
{
++i;
demDistScale=float(atof(argv[i]));
}
else if(strcasecmp(argv[i]+1,"wi")==0)
{
++i;
windowIndex=atoi(argv[i]);
/* Extend the list of render settings if an index beyond the end is selected: */
while(int(renderSettings.size())<=windowIndex)
renderSettings.push_back(renderSettings.back());
/* Disable fixed projector view on the new render settings: */
renderSettings.back().fixProjectorView=false;
}
else if(strcasecmp(argv[i]+1,"fpv")==0)
{
renderSettings.back().fixProjectorView=true;
if(i+1<argc&&argv[i+1][0]!='-')
{
/* Load the projector transformation file specified in the next argument: */
++i;
renderSettings.back().loadProjectorTransform(argv[i]);
}
}
else if(strcasecmp(argv[i]+1,"nhs")==0)
renderSettings.back().hillshade=false;
else if(strcasecmp(argv[i]+1,"uhs")==0)
renderSettings.back().hillshade=true;
else if(strcasecmp(argv[i]+1,"ns")==0)
renderSettings.back().useShadows=false;
else if(strcasecmp(argv[i]+1,"us")==0)
renderSettings.back().useShadows=true;
else if(strcasecmp(argv[i]+1,"nhm")==0)
{
delete renderSettings.back().elevationColorMap;
renderSettings.back().elevationColorMap=0;
}
else if(strcasecmp(argv[i]+1,"uhm")==0)
{
if(i+1<argc&&argv[i+1][0]!='-')
{
/* Load the height color map file specified in the next argument: */
++i;
renderSettings.back().loadHeightMap(argv[i]);
}
else
{
/* Load the default height color map: */
renderSettings.back().loadHeightMap(CONFIG_DEFAULTHEIGHTCOLORMAPFILENAME);
}
}
else if(strcasecmp(argv[i]+1,"ncl")==0)
renderSettings.back().useContourLines=false;
else if(strcasecmp(argv[i]+1,"ucl")==0)
{
renderSettings.back().useContourLines=true;
if(i+1<argc&&argv[i+1][0]!='-')
{
/* Read the contour line spacing: */
++i;
renderSettings.back().contourLineSpacing=GLfloat(atof(argv[i]));
}
}
else if(strcasecmp(argv[i]+1,"rws")==0)
renderSettings.back().renderWaterSurface=true;
else if(strcasecmp(argv[i]+1,"rwt")==0)
renderSettings.back().renderWaterSurface=false;
else if(strcasecmp(argv[i]+1,"wo")==0)
{
++i;
renderSettings.back().waterOpacity=GLfloat(atof(argv[i]));
}
else if(strcasecmp(argv[i]+1,"cp")==0)
{
++i;
controlPipeName=argv[i];
}
else
std::cerr<<"Ignoring unrecognized command line switch "<<argv[i]<<std::endl;
}
}
/* Print usage help if requested: */
if(printHelp)
printUsage();
if(frameFilePrefix!=0)
{
/* Open the selected pre-recorded 3D video files: */
std::string colorFileName=frameFilePrefix;
colorFileName.append(".color");
std::string depthFileName=frameFilePrefix;
depthFileName.append(".depth");
camera=new Kinect::FileFrameSource(Vrui::openFile(colorFileName.c_str()),Vrui::openFile(depthFileName.c_str()));
}
else
{
/* Open the 3D camera device of the selected index: */
Kinect::DirectFrameSource* realCamera=Kinect::openDirectFrameSource(cameraIndex);
Misc::ConfigurationFileSection cameraConfigurationSection=cfg.getSection(cameraConfiguration.c_str());
realCamera->configure(cameraConfigurationSection);
camera=realCamera;
}
for(int i=0;i<2;++i)
frameSize[i]=camera->getActualFrameSize(Kinect::FrameSource::DEPTH)[i];
/* Get the camera's per-pixel depth correction parameters and evaluate it on the depth frame's pixel grid: */
Kinect::FrameSource::DepthCorrection* depthCorrection=camera->getDepthCorrectionParameters();
if(depthCorrection!=0)
{
pixelDepthCorrection=depthCorrection->getPixelCorrection(frameSize);
delete depthCorrection;
}
else
{
/* Create dummy per-pixel depth correction parameters: */
pixelDepthCorrection=new PixelDepthCorrection[frameSize[1]*frameSize[0]];
PixelDepthCorrection* pdcPtr=pixelDepthCorrection;
for(unsigned int y=0;y<frameSize[1];++y)
for(unsigned int x=0;x<frameSize[0];++x,++pdcPtr)
{
pdcPtr->scale=1.0f;
pdcPtr->offset=0.0f;
}
}
/* Get the camera's intrinsic parameters: */
cameraIps=camera->getIntrinsicParameters();
/* Read the sandbox layout file: */
Geometry::Plane<double,3> basePlane;
Geometry::Point<double,3> basePlaneCorners[4];
{
IO::ValueSource layoutSource(Vrui::openFile(sandboxLayoutFileName.c_str()));
layoutSource.skipWs();
std::string s=layoutSource.readLine();
basePlane=Misc::ValueCoder<Geometry::Plane<double,3> >::decode(s.c_str(),s.c_str()+s.length());
basePlane.normalize();
for(int i=0;i<4;++i)
{
layoutSource.skipWs();
s=layoutSource.readLine();
basePlaneCorners[i]=Misc::ValueCoder<Geometry::Point<double,3> >::decode(s.c_str(),s.c_str()+s.length());
}
}
/* Limit the valid elevation range to the intersection of the extents of all height color maps: */
for(std::vector<RenderSettings>::iterator rsIt=renderSettings.begin();rsIt!=renderSettings.end();++rsIt)
if(rsIt->elevationColorMap!=0)
{
Math::Interval<double> mapRange(rsIt->elevationColorMap->getScalarRangeMin(),rsIt->elevationColorMap->getScalarRangeMax());
elevationRange.intersectInterval(mapRange);
}
/* Scale all sizes by the given scale factor: */
double sf=scale/100.0; // Scale factor from cm to final units
for(int i=0;i<3;++i)
for(int j=0;j<4;++j)
cameraIps.depthProjection.getMatrix()(i,j)*=sf;
basePlane=Geometry::Plane<double,3>(basePlane.getNormal(),basePlane.getOffset()*sf);
for(int i=0;i<4;++i)
for(int j=0;j<3;++j)
basePlaneCorners[i][j]*=sf;
if(elevationRange!=Math::Interval<double>::full)
elevationRange*=sf;
if(rainElevationRange!=Math::Interval<double>::full)
rainElevationRange*=sf;
for(std::vector<RenderSettings>::iterator rsIt=renderSettings.begin();rsIt!=renderSettings.end();++rsIt)
{
if(rsIt->elevationColorMap!=0)
rsIt->elevationColorMap->setScalarRange(rsIt->elevationColorMap->getScalarRangeMin()*sf,rsIt->elevationColorMap->getScalarRangeMax()*sf);
rsIt->contourLineSpacing*=sf;
rsIt->waterOpacity/=sf;
for(int i=0;i<4;++i)
rsIt->projectorTransform.getMatrix()(i,3)*=sf;
}
rainStrength*=sf;
evaporationRate*=sf;
demDistScale*=sf;
/* Create the frame filter object: */
frameFilter=new FrameFilter(frameSize,numAveragingSlots,pixelDepthCorrection,cameraIps.depthProjection,basePlane);
frameFilter->setValidElevationInterval(cameraIps.depthProjection,basePlane,elevationRange.getMin(),elevationRange.getMax());
frameFilter->setStableParameters(minNumSamples,maxVariance);
frameFilter->setHysteresis(hysteresis);
frameFilter->setSpatialFilter(true);
frameFilter->setOutputFrameFunction(Misc::createFunctionCall(this,&Sandbox::receiveFilteredFrame));
if(waterSpeed>0.0)
{
/* Create the hand extractor object: */
handExtractor=new HandExtractor(frameSize,pixelDepthCorrection,cameraIps.depthProjection);
}
/* Start streaming depth frames: */
camera->startStreaming(0,Misc::createFunctionCall(this,&Sandbox::rawDepthFrameDispatcher));
/* Create the depth image renderer: */
depthImageRenderer=new DepthImageRenderer(frameSize);
depthImageRenderer->setDepthProjection(cameraIps.depthProjection);
depthImageRenderer->setBasePlane(basePlane);
/* Calculate the transformation from camera space to sandbox space: */
{
ONTransform::Vector z=basePlane.getNormal();
ONTransform::Vector x=(basePlaneCorners[1]-basePlaneCorners[0])+(basePlaneCorners[3]-basePlaneCorners[2]);
ONTransform::Vector y=z^x;
boxTransform=ONTransform::rotate(Geometry::invert(ONTransform::Rotation::fromBaseVectors(x,y)));
ONTransform::Point center=Geometry::mid(Geometry::mid(basePlaneCorners[0],basePlaneCorners[1]),Geometry::mid(basePlaneCorners[2],basePlaneCorners[3]));
boxTransform*=ONTransform::translateToOriginFrom(basePlane.project(center));
}
/* Calculate a bounding box around all potential surfaces: */
bbox=Box::empty;
for(int i=0;i<4;++i)
{
bbox.addPoint(basePlane.project(basePlaneCorners[i])+basePlane.getNormal()*elevationRange.getMin());
bbox.addPoint(basePlane.project(basePlaneCorners[i])+basePlane.getNormal()*elevationRange.getMax());
}
if(waterSpeed>0.0)
{
/* Initialize the water flow simulator: */
waterTable=new WaterTable2(wtSize[0],wtSize[1],depthImageRenderer,basePlaneCorners);
waterTable->setElevationRange(elevationRange.getMin(),rainElevationRange.getMax());
waterTable->setWaterDeposit(evaporationRate);
/* Register a render function with the water table: */
addWaterFunction=Misc::createFunctionCall(this,&Sandbox::addWater);
waterTable->addRenderFunction(addWaterFunction);
addWaterFunctionRegistered=true;
}
/* Initialize all surface renderers: */
for(std::vector<RenderSettings>::iterator rsIt=renderSettings.begin();rsIt!=renderSettings.end();++rsIt)
{
/* Calculate the texture mapping plane for this renderer's height map: */
if(rsIt->elevationColorMap!=0)
{
if(haveHeightMapPlane)
rsIt->elevationColorMap->calcTexturePlane(heightMapPlane);
else
rsIt->elevationColorMap->calcTexturePlane(depthImageRenderer);
}
/* Initialize the surface renderer: */
rsIt->surfaceRenderer=new SurfaceRenderer(depthImageRenderer);
rsIt->surfaceRenderer->setDrawContourLines(rsIt->useContourLines);
rsIt->surfaceRenderer->setContourLineDistance(rsIt->contourLineSpacing);
rsIt->surfaceRenderer->setElevationColorMap(rsIt->elevationColorMap);
rsIt->surfaceRenderer->setIlluminate(rsIt->hillshade);
if(waterTable!=0)
{
if(rsIt->renderWaterSurface)
{
/* Create a water renderer: */
rsIt->waterRenderer=new WaterRenderer(waterTable);
}
else
{
rsIt->surfaceRenderer->setWaterTable(waterTable);
rsIt->surfaceRenderer->setAdvectWaterTexture(true);
rsIt->surfaceRenderer->setWaterOpacity(rsIt->waterOpacity);
}
}
rsIt->surfaceRenderer->setDemDistScale(demDistScale);
}
#if 0
/* Create a fixed-position light source: */
sun=Vrui::getLightsourceManager()->createLightsource(true);
for(int i=0;i<Vrui::getNumViewers();++i)
Vrui::getViewer(i)->setHeadlightState(false);
sun->enable();
sun->getLight().position=GLLight::Position(1,0,1,0);
#endif
/* Create the GUI: */
mainMenu=createMainMenu();
Vrui::setMainMenu(mainMenu);
if(waterTable!=0)
waterControlDialog=createWaterControlDialog();
/* Initialize the custom tool classes: */
GlobalWaterTool::initClass(*Vrui::getToolManager());
LocalWaterTool::initClass(*Vrui::getToolManager());
DEMTool::initClass(*Vrui::getToolManager());
if(waterTable!=0)
BathymetrySaverTool::initClass(waterTable,*Vrui::getToolManager());
addEventTool("Pause Topography",0,0);
if(!controlPipeName.empty())
{
/* Open the control pipe in non-blocking mode: */
controlPipeFd=open(controlPipeName.c_str(),O_RDONLY|O_NONBLOCK);
if(controlPipeFd<0)
std::cerr<<"Unable to open control pipe "<<controlPipeName<<"; ignoring"<<std::endl;
}
/* Inhibit the screen saver: */
Vrui::inhibitScreenSaver();
/* Set the linear unit to support proper scaling: */
Vrui::getCoordinateManager()->setUnit(Geometry::LinearUnit(Geometry::LinearUnit::METER,scale/100.0));
/* Initialize the navigation transformation: */
Vrui::Point::AffineCombiner cc;