-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
1834 lines (1573 loc) · 61 KB
/
Copy pathmainwindow.cpp
File metadata and controls
1834 lines (1573 loc) · 61 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 "mainwindow.h"
#include "ui_simUVWidget.h"
#include <QDateTimeEdit>
#include <QFileDialog>
#include <QtGui>
#include <QList>
#include <QListWidgetItem>
#include <QListWidget>
#include <QSharedPointer>
#include <meshlab/mainwindow.h>
#include <wrap/gl/trimesh.h>
#include <meshlab/stdpardialog.h>
#include "OldAPISupport.h"
#include "SpreadSheet.h"
#include "Helpers.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
ui = new Ui::MainWindow;
ui->setupUi(this);
this->setCentralWidget(ui->main_frame);
spreadsheet = new SpreadSheet();
MeshDocument *mydoc;
meshDoc = mydoc;
zones = 0;
poi = 0;
minDate = 0;
maxDate = 0;
anatZonesChanged = false;
protectionsLibChanged = false;
protectionsChanged = false;
currentAnatFilename = "";
currentProtectionsLibFilename = "";
currentProtectionsFilename = "";
numPositions = 0;
sources = 0;
// Directories
// updateExportPaths();
// connect(ui->checkBoxSubdirectory, SIGNAL(toggled(bool)), this, SLOT(updateExportPaths()));
// connect(ui->lineEditSubdirectory, SIGNAL(textChanged(QString)), this, SLOT(updateExportPaths()));
// ui->diffuseMapLineEdit->setText(meshDoc->mm()->pathName()+"/%position%-diffuseMap.txt");
// ui->reflectedMapLineEdit->setText(meshDoc->mm()->pathName()+"/%position%-reflectedMap");
// connect(ui->loadWeatherDataButton, SIGNAL(clicked()),this,SLOT(loadWeatherDataFile()));
}
MainWindow::~MainWindow()
{
Helpers::deleteZones(&zones);
if(poi){
delete poi;
}
if(maxDate){
delete maxDate;
}
if(minDate){
delete minDate;
}
delete spreadsheet;
delete ui;
}
void MainWindow::closeEvent(QCloseEvent *event)
{
emit closing();
}
bool MainWindow::eventFilter(QObject *object, QEvent *event)
{
bool raiseRequired = false;
if(event->type() == QEvent::WindowStateChange)
{
auto window = dynamic_cast<QMainWindow *>(object);
if(window && window->windowState() != Qt::WindowMinimized)
raiseRequired = true;
}
else if(event->type() == QEvent::ActivationChange)
{
auto window = dynamic_cast<QMainWindow *>(object);
if(window)
raiseRequired = true;
}
if(raiseRequired)
raise();
return false;
}
//General
void MainWindow::loadWeatherDataFile(){
//Get file to open
QString dir;
if (lastDirectory == ""){
dir=".";
}else{
dir = lastDirectory;
}
QString filename = QFileDialog::getOpenFileName(this,tr("Select Weather Data File"),dir, spreadsheet->extensions().join(";;"));
if(!filename.isNull()){
//Open the Excel data file
if (spreadsheet->init(filename.toStdString().c_str())!=0 || spreadsheet->open(filename.toStdString().c_str())!=0){
QMessageBox::information(0, "Failed to open Excel File.", "Error");
return;
}
//Check Excel Data File Format
if(!spreadsheet->getFirstDate() || !spreadsheet->getLastDate() || spreadsheet->getTimeStep()<1){
QMessageBox::information(0, "Excel file does not seem to be in the right format. Please check accepted format.", "Error");
return;
}
//Store the dates
minDate = new QDateTime(QDate(spreadsheet->getFirstDate()->getYear(),spreadsheet->getFirstDate()->getMonth(),spreadsheet->getFirstDate()->getDay()),QTime(spreadsheet->getFirstDate()->getHour(),spreadsheet->getFirstDate()->getMinute()));
maxDate = new QDateTime(QDate(spreadsheet->getLastDate()->getYear(),spreadsheet->getLastDate()->getMonth(),spreadsheet->getLastDate()->getDay()),QTime(spreadsheet->getLastDate()->getHour(),spreadsheet->getLastDate()->getMinute()));
//Setup GUI based on Excel file information
weatherDataLoaded = true;
QFileInfo finfo(filename);
lastDirectory = finfo.absolutePath();
ui->weatherDataFileLineEdit->setText(filename);
//Refresh positions tab
reloadPositionsTab();
}
}
//Result file names handling
void MainWindow::exportVertCSVFile(){
exportDirBrowse("Select Directory to Export Vertex Intensities", ui->exportVertCSVLineEdit);
}
void MainWindow::exportControlCSVFile(){
exportDirBrowse("Select Directory to Export Control Surface Intensities", ui->exportFlatCSVLineEdit);
}
void MainWindow::exportZonesCSVFile(){
exportDirBrowse("Select Directory to Export Zones Intensities", ui->exportAnatZonesLineEdit);
}
void MainWindow::exportPOICSVFile(){
exportDirBrowse("Select Directory to Export POI Intensities", ui->exportPOILineEdit);
}
void MainWindow::exportProtectionsFile(){
exportDirBrowse("Select Directory to Export Protections File", ui->exportProtectionsLineEdit);
}
void MainWindow::exportDiffuseMapFile(){
exportDirBrowse("Select Directory to Export Diffuse Map", ui->diffuseMapLineEdit);
}
void MainWindow::exportReflectedMapFile(){
exportDirBrowse("Select Directory to Export Reflected Map", ui->reflectedMapLineEdit);
}
void MainWindow::filePositionLineEditChanged(){
QFileInfo finfo(((QLineEdit*)QObject::sender())->text());
//Check that the dir exists
if(!finfo.dir().exists()){
QMessageBox::warning(this,"Directory not found","The current directory does not exist. Please select an existing directory.");
}
//Check that the filename is appropriate
//search for the %position% string
if(finfo.fileName().lastIndexOf("%position%") < 0){
QMessageBox::warning(this,"Not a generic name", "The current filename will only work for a single position simulation. Valid filenames for multiple positions simulation should include the pattern '%position%' which will be replaced by individual position names.");
}
}
void MainWindow::fileIntensitiesLineEditChanged(){
QFileInfo finfo(((QLineEdit*)QObject::sender())->text());
//Check that the dir exists
if(!finfo.dir().exists()){
QMessageBox::warning(this,"Directory not found","The current directory does not exist. Please select an existing directory.");
}
//Check that the filename is appropriate
//search for the %position% string
if(finfo.fileName().lastIndexOf("%intensities%") < 0){
QMessageBox::warning(this,"Not a generic name", "The current filename will only work for a single protections file. Valid filenames for multiple protections files (ex: vertex intensities+anatomical zones or multiple positions) should include the pattern '%intensities%' which will be replaced by individual intensities files name.");
}
}
//SIMULATION
void MainWindow::runSimulation(){
//Cache position table, find used date range
const Date &firstDate = *spreadsheet->getFirstDate();
const Date &lastDate = *spreadsheet->getLastDate();
Date firstUsedDate = lastDate;
Date lastUsedDate = firstDate;
QVector<Position> positionsTable;
positionsTable.resize(ui->positionsTableWidget->rowCount());
for(int i=0; i<ui->positionsTableWidget->rowCount(); ++i){
Position &position = positionsTable[i];
position.checked = ((QCheckBox*)ui->positionsTableWidget->cellWidget(i,PositionsTableColumns::ACTIVE))->isChecked();
QDateTime qStartDate = ((QDateTimeEdit*)ui->positionsTableWidget->cellWidget(i, PositionsTableColumns::STARTTIME))->dateTime();
QDateTime qEndDate = ((QDateTimeEdit*)ui->positionsTableWidget->cellWidget(i, PositionsTableColumns::ENDTIME))->dateTime();
position.qStartDate = qStartDate;
position.qEndDate = qEndDate;
position.startDate = Date(qStartDate.date().year(), qStartDate.date().month(), qStartDate.date().day(), qStartDate.time().hour(), qStartDate.time().minute());
position.endDate = Date(qEndDate.date().year(), qEndDate.date().month(), qEndDate.date().day(), qEndDate.time().hour(), qEndDate.time().minute());
position.timeStep = ((QTimeEdit*)ui->positionsTableWidget->cellWidget(i, PositionsTableColumns::TIMESTEP))->time();
position.meshIndex = ((QComboBox*)ui->positionsTableWidget->cellWidget(i, PositionsTableColumns::POSITION))->currentIndex();
position.orientation = ((QComboBox*)ui->positionsTableWidget->cellWidget(i,PositionsTableColumns::ORIENTATION))->currentIndex();
position.startAngle = ((QDoubleSpinBox*)ui->positionsTableWidget->cellWidget(i,PositionsTableColumns::STARTANGLE))->value();
position.endAngle = ((QDoubleSpinBox*)ui->positionsTableWidget->cellWidget(i,PositionsTableColumns::ENDANGLE))->value();
position.angleStep = ((QDoubleSpinBox*)ui->positionsTableWidget->cellWidget(i,PositionsTableColumns::ANGULARSTEP))->value();
if(position.checked)
{
if(position.startDate < firstUsedDate && position.startDate >= firstDate)
firstUsedDate = position.startDate;
if(position.endDate > lastUsedDate && position.endDate <= lastDate)
lastUsedDate = position.endDate;
}
}
//Check output directories
const QString exportPath = this->exportPath();
if(!QDir(exportPath).exists())
QDir().mkdir(exportPath);
//Keeps track of the results
typedef QSharedPointer<UVModel> UVModelPtr;
vector<UVModelPtr> models;
try{
//Set the sources to be simulated
sources = 0;
if(ui->useDirectSourceCheckBox->isChecked()){
sources += IntensitySources::DIRECT;
}
if(ui->useDiffuseSourceCheckBox->isChecked()){
sources += IntensitySources::DIFFUSED;
}
if(ui->useReflectedSourceCheckBox->isChecked()){
sources += IntensitySources::REFLECTED;
}
//Loop over each of the positions selected for simulation
//And load the models in memory
//int totalSteps = 1;
for(int i=0; i<positionsTable.size(); ++i){
//Check that the position has been selected for simulation
const Position &position = positionsTable[i];
if(position.checked){
//Get the start and end datetimes
QDateTime startDate = position.qStartDate;
QDateTime endDate = position.qEndDate;
//Check that the endDate is after tne startDate
if(startDate.secsTo(endDate) < 1){
QMessageBox(QMessageBox::Warning,"Dates are not valid", "The start date should always be before the end date for each of the positions. Please check the dates in the positions table on line " + QString::number(i+1) + " and relaunch the simulation.", QMessageBox::Ok, this).exec();
return;
}
//Get the current Mesh
MeshModel *currentMesh = meshDoc->getMesh(position.meshIndex);
//Get the filename
std::string filename = currentMesh->fullName().toStdString();
//Create and initiate the UVModel
UVModelPtr uvModel(new UVModel(meshDoc, filename.c_str(), spreadsheet));
QString positionName = currentMesh->fullName();
positionName = positionName.left(positionName.lastIndexOf('.'));
positionName = positionName.mid(positionName.lastIndexOf('/') + 1);
//Initialize the Model. If the user cancels the operation or a problem occurs, abort the simulation)
if(!initUVModel(uvModel.data(), positionName))
return;
//store the model
models.push_back(uvModel);
//Add the number of necessary simulation steps to the total
int numPositionVertices = uvModel->getUVMesh()->getModelVertices()->size();
if(position.orientation == PositionsOrientations::AVERAGE){
//!!The calculation of numSteps should be reused since it is used in UVModel too!!
float startAngle = position.startAngle;
float endAngle = position.endAngle;
float angleStep = position.angleStep;
//Make sure all angles are minimal
startAngle = fmod(startAngle, 360.0f);
endAngle = fmod(endAngle,360.0f);
angleStep = fmod(angleStep,360.0f);
//Make sure the step is between 1 deg and 359 deg
//In case the step is a full turn, the average will not need extra computation
//since it will be like a fixed position
if(angleStep){
//If the endAngle == startAngle,
//user probably wants 1 full turn
if(endAngle == startAngle){
endAngle -= angleStep;
}
//Get the total rotation angle
float totalAngle;
if(angleStep > 0){
totalAngle = endAngle-startAngle;
}
else{
totalAngle = startAngle-endAngle;
}
if(totalAngle < 0){
totalAngle = 360 + totalAngle;
}
//UVs need to be evaluated for each of the steps
numPositionVertices*=1+(totalAngle / abs(angleStep));
}
}
}
}
//Create a progress dialog
const int firstRow = spreadsheet->searchDateRow(firstUsedDate);
const int lastRow = spreadsheet->searchDateRow(lastUsedDate);
int totalSteps = lastRow - firstRow + 1;
QProgressDialog progress("Simulation...","Cancel",0,totalSteps,this);
progress.setWindowModality(Qt::WindowModal);
progress.setValue(0);
progress.show();
progress.raise(); // bring to front
IOZones::OutputStreamMap outputStreams;
Date date = firstUsedDate;
int timeStep = spreadsheet->getTimeStep();
for(int row = firstRow; row <= lastRow; row++, date += timeStep)
{
progress.setValue(row - firstRow);
if(progress.wasCanceled()){
QMessageBox cancelCheck(QMessageBox::Warning, "Cancel Simulation?", "Are you sure you want to cancel the current simulation?",
QMessageBox::Yes | QMessageBox::No, &progress);
if(cancelCheck.exec() == QMessageBox::Yes)
//throw std::exception("Simulation canceled by user."); MODIFY
//If the user does not cancel in the end, reset the progressDialog to reset the cancel flag.
progress.reset();
}
//Run the simulations
int j = 0;
QVector<int> skippedModels;
for(int i=0; i<positionsTable.size(); ++i){
const Position &position = positionsTable[i];
//Check that the position has been selected for simulation
if(position.checked){
//run the simulation
if(date >= position.startDate && date <= position.endDate)
simulatePosition(models.at(j).data(), date, date, position);
else
skippedModels.push_back(j);
//increment the results counter
++j;
}
}
//Aggregate results if necessary
bool isAggregate = false;
std::vector<UVModelPtr> resultModels;
// TODO(vova.y): find better way
resultModels = models;
// TODO(vova.y): do we need aggregation?
/*
if(ui->multiplePositionsSeparateRadioButton->isChecked()){
resultModels = models;
}
else{
isAggregate = true;
int modelsCount = models.size();
//Get the target result
int targetIndex = ui->targetPositionComboBox->currentIndex();
if(modelsCount-1 < targetIndex){
return;
}
UVModelPtr target = models.at(targetIndex);
target->evaluateZones();
//Aggregate results (Keep only the target result)
for(int i=modelsCount-1; i >= 0; --i){
UVModelPtr currentResult = resultModels.at(i);
if(!(currentResult == target)){
currentResult->evaluateZones();
target->mergeResults(currentResult.data());
currentResult.reset();
}
}
resultModels.push_back(target);
//Divide by the number of results in case it's an average
if(ui->multiplePositionsAvgRadioButton->isChecked()){
target->getUVMesh()->multiplyZonesIntensities(1.0f/modelsCount);
target->getPlaneSurface()->multiplyIntensities(1.0f/modelsCount);
}
}
*/
//Apply protections and export the results
bool exportTotals = row == lastRow;
j = 0;
for(auto resIter = resultModels.begin(); resIter != resultModels.end(); resIter++, ++j){
if(!skippedModels.isEmpty() && skippedModels.first() == j)
{
skippedModels.pop_front();
continue;
}
QString positionName = QString::fromLatin1((*resIter)->getUVMesh()->getModelName());
positionName = positionName.left(positionName.lastIndexOf('.'));
if(ui->useProtectionsCheckBox->isChecked()){
if(ui->exportProtectionsCheckBox->isChecked()){
exportSimulationResults(resIter->data(),positionName,false,isAggregate,outputStreams,exportTotals);
(*resIter)->setProtections();
exportSimulationResults(resIter->data(),positionName,true,isAggregate,outputStreams,exportTotals);
}
else{
(*resIter)->setProtections();
exportSimulationResults(resIter->data(),positionName,false,isAggregate,outputStreams,exportTotals);
}
}
else{
exportSimulationResults(resIter->data(),positionName,false,isAggregate,outputStreams,exportTotals);
}
}
}
progress.setValue(progress.maximum());
QMessageBox(QMessageBox::Information, "Simulation done!", "The simulation has ended successfuly!",QMessageBox::Ok,this).exec();
}
catch(exception e){
//Display error for the user
QMessageBox(QMessageBox::Warning, "Error: Simulation stopped", QString::fromLatin1(e.what()), QMessageBox::Ok, this).exec();
}
Helpers::deleteZones(&zones);
}
void MainWindow::simulatePosition(UVModel *uvModel, const Date &startDate, const Date &endDate, const MainWindow::Position &position)
{
uvModel->clearEvaluatedIntensities();
//Set the POIs if selected
if(!uvModel->hasPOIs() && ui->usePOICheckBox->isChecked())
{
QFileInfo POIFile(ui->usePOILineEdit->text());
if(POIFile.exists())
uvModel->setPOIs(POIFile.absoluteFilePath().toStdString().c_str());
}
//Set the Anatomical zones
if(!uvModel->hasZones() && ui->useAnatZonesCheckBox->isChecked())
{
QFileInfo anatZonesFile(ui->useAnatZonesLineEdit->text());
if(anatZonesFile.exists())
uvModel->setZones(anatZonesFile.absoluteFilePath().toStdString().c_str());
}
//Launch the simulation
float startAngle = position.startAngle;
float angleStep, endAngle;
int timeStep;
switch(position.orientation){
case PositionsOrientations::FIXED:
uvModel->evaluateUVBetweenFixed(startDate, endDate, startAngle, sources);
break;
case PositionsOrientations::AVERAGE:
endAngle = position.endAngle;
angleStep = position.angleStep;
uvModel->evaluateUVBetweenAvg(startDate, endDate, startAngle, endAngle, angleStep, sources);
break;
case PositionsOrientations::SEQUENCE:
angleStep = position.angleStep;
timeStep = QTime(0,0,0).secsTo(position.timeStep);
uvModel->evaluateUVBetweenSeq(startDate, endDate, startAngle, angleStep, timeStep, sources);
break;
}
}
void MainWindow::exportSimulationResults(UVModel *uvModel, QString positionName, bool exportProtectionsSeparately, bool isAggregate,
IOZones::OutputStreamMap &outputStreams, bool exportTotals){
//Get the control surface
Intensity flatSurfaceIntensity = uvModel->getPlaneSurface()->getTotalIntensity(false);
/* RAW INTENSITIES */
if(exportTotals && !isAggregate && ui->exportVertCheckBox->isChecked()){
QString vertFilename;
if(exportProtectionsSeparately){
vertFilename = ui->exportProtectionsLineEdit->text();
QFileInfo finfo(ui->exportVertCSVLineEdit->text());
vertFilename.replace("%intensities%",finfo.baseName());
}
else{
vertFilename = ui->exportVertCSVLineEdit->text();
}
vertFilename.replace("%position%",positionName);
uvModel->getUVMesh()->exportIntensitiesCSV(&flatSurfaceIntensity,vertFilename.toStdString());
}
/* ZONES */
if(ui->useAnatZonesCheckBox->isChecked()){
//Aggregate must evaluate their zones earlier
//to aggregate their results
if(!isAggregate){
uvModel->evaluateZones();
}
if(ui->exportAnatZonesCheckBox->isChecked()){
QString anatZonesFilename;
if(exportProtectionsSeparately){
anatZonesFilename = ui->exportProtectionsLineEdit->text();
QFileInfo finfo(ui->exportAnatZonesLineEdit->text());
anatZonesFilename.replace("%intensities%",finfo.baseName());
}
else{
anatZonesFilename = ui->exportAnatZonesLineEdit->text();
}
anatZonesFilename.replace("%position%",positionName);
uvModel->getUVMesh()->exportZonesIntensitiesCSV(&flatSurfaceIntensity,anatZonesFilename.toStdString(),outputStreams);
}
}
/* CONTROL PLANE SURFACE */
if(ui->exportFlatCSVCheckBox->isChecked() && !exportProtectionsSeparately){
uvModel->getPlaneSurface()->exportIntensitiesCSV(ui->exportFlatCSVLineEdit->text().replace("%position%",positionName).toStdString(), outputStreams);
}
/* POI */
// TODO(vova.y): restore
/*
if(!isAggregate && ui->exportPOICheckBox->isChecked()){
uvModel->evaluatePOI(ui->POIRadiusSpinBox->value());
QString POIFilename;
if(exportProtectionsSeparately){
POIFilename = ui->exportProtectionsLineEdit->text();
QFileInfo finfo(ui->exportPOILineEdit->text());
POIFilename.replace("%intensities%",finfo.baseName());
}
else{
POIFilename = ui->exportPOILineEdit->text();
}
POIFilename.replace("%position%",positionName);
uvModel->getUVMesh()->exportPOIIntensitiesCSV(&flatSurfaceIntensity,POIFilename.toStdString());
}
*/
/* MESH */
if(exportTotals)
{
uvModel->getPlaneSurface()->evaluateTotalEvaluatedIntensity(true);
uvModel->getUVMesh()->evaluateTotalEvaluatedIntensity(true);
Intensity flatSurfaceIntensity = uvModel->getPlaneSurface()->getTotalIntensity(true);
//Generate the name
QString meshName;
QFileInfo positionFinfo(positionName);
if(exportProtectionsSeparately){
QFileInfo finfo(ui->exportProtectionsLineEdit->text());
meshName = finfo.baseName();
meshName.replace("%intensities%",positionFinfo.baseName());
}
else{
meshName = positionFinfo.baseName();
}
meshName.append("-SimUV");
//Set the colors
//Set the color boundaries as selected by the user
float fromBlue, fromGreen, fromRed, toRed;
if(ui->renderAmbiantRadioBtn->isChecked()){
float ambiantIntensity = 0;
if(ui->renderAmbiantDirectCheckBox->isChecked()){
ambiantIntensity += flatSurfaceIntensity.direct;
}
if(ui->renderAmbiantDiffusedCheckBox->isChecked()){
ambiantIntensity += flatSurfaceIntensity.diffused;
}
if(ui->renderAmbiantReflectedCheckBox->isChecked()){
ambiantIntensity += flatSurfaceIntensity.reflected;
}
fromBlue = ambiantIntensity*ui->renderBlueFromSpinBox->value()/100.0f;
fromGreen = ambiantIntensity*ui->renderGreenFromSpinBox->value()/100.0f;
fromRed = ambiantIntensity*ui->renderRedFromSpinBox->value()/100.0f;
toRed = ambiantIntensity*ui->renderRedToSpinBox->value()/100.0f;
}
else{
fromBlue = ui->renderBlueFromSpinBox->value();
fromGreen = ui->renderGreenFromSpinBox->value();
fromRed = ui->renderRedFromSpinBox->value();
toRed = ui->renderRedToSpinBox->value();
}
//Set the sources to be rendered
int sources = 0;
if(ui->renderDirectCheckBox->isEnabled() && ui->renderDirectCheckBox->isChecked()){
sources += IntensitySources::DIRECT;
}
if(ui->renderDiffusedCheckBox->isEnabled() && ui->renderDiffusedCheckBox->isChecked()){
sources += IntensitySources::DIFFUSED;
}
if(ui->renderReflectedCheckBox->isEnabled() && ui->renderReflectedCheckBox->isChecked()){
sources += IntensitySources::REFLECTED;
}
if(isAggregate){
//UVMesh::setColors(destMesh,uvModel->getUVMesh()->getZones(),flatSurfaceIntensity.diffused + flatSurfaceIntensity.direct + flatSurfaceIntensity.reflected);
uvModel->getUVMesh()->setColorsFromZones(fromBlue, fromGreen, fromRed, toRed,sources);
}
else{
//UVMesh::setColors(destMesh,uvModel->getUVMesh()->getEvaluatedIntensityList(),flatSurfaceIntensity.diffused + flatSurfaceIntensity.direct + flatSurfaceIntensity.reflected);
uvModel->getUVMesh()->setColors(fromBlue, fromGreen, fromRed, toRed,sources);
}
// creating the new layer
MeshModel *currentMesh = uvModel->getUVMesh()->getModel();
MeshModel *destMesh= OldApi::AddMeshModel(meshDoc, meshName.toStdString().c_str());
vcg::tri::Append<CMeshO,CMeshO>::Mesh(destMesh->cm, currentMesh->cm, false, true); // the last true means "copy all vertices"
// init new layer
vcg::tri::UpdateBounding<CMeshO>::Box(destMesh->cm); // updates bounding box
CMeshO::FaceIterator fi;
for(fi=destMesh->cm.face.begin();fi!=destMesh->cm.face.end();++fi) // face normals
OldApi::ComputeNormalizedNormal(*fi);
vcg::tri::UpdateNormal<CMeshO>::PerVertex(destMesh->cm); // vertex normals
destMesh->cm.Tr = currentMesh->cm.Tr; // copy transformation
destMesh->updateDataMask(MeshModel::MM_VERTCOLOR);
}
}
bool MainWindow::initUVModel(UVModel *uvModel, QString positionName){
//General options
uvModel->setRayPlaneTolerance(ui->rayPlaneSpinBox->value());
//Bounding Boxes
uvModel->setNumBoxes(ui->xBBSpinBox->value(),ui->yBBSpinBox->value(), ui->zBBSpinBox->value());
uvModel->setDirectUseBoxes(ui->bbDirectCheckBox->isChecked());
uvModel->setDiffuseUseBoxes(ui->bbDiffuseCheckBox->isChecked());
uvModel->setReflectedUseBoxes(ui->bbReflectedCheckBox->isChecked());
//Direct Source setup
uvModel->setUseDirectSource(ui->useDirectSourceCheckBox->isChecked());
//Diffuse Source setup
uvModel->setUseDiffuseSource(ui->useDiffuseSourceCheckBox->isChecked());
uvModel->setDiffuseLvlNb(ui->diffuseNumLevelSpinBox->value());
uvModel->setDiffusePtNb(ui->diffuseNumPtsSpinBox->value());
uvModel->setDiffuseRadiusFactor(ui->diffuseRadiusSpinBox->value());
uvModel->setDiffuseAttenuationAngle(ui->attenuationAngleSpinBox->value());
if(sources & IntensitySources::DIFFUSED && ui->diffuseMapCheckBox->isChecked()){
if(!uvModel->setDiffuseMapPath(ui->diffuseMapLineEdit->text().replace("%position%",positionName).toStdString())){
QMessageBox warningMessage(QMessageBox::Warning, "Diffused Map not found", "The diffused map for position " + positionName + " was not found or did not correspond to the position (different number of vertices). The calculation for this position might therefore be very long. Continue?",QMessageBox::Yes | QMessageBox::No, this);
if(warningMessage.exec() == QMessageBox::No){
return false;
}
}
}
//Reflected Source setup
uvModel->setUseReflectedSource(ui->useReflectedSourceCheckBox->isChecked());
uvModel->setReflectedLvlNb(ui->reflectedNumLevelSpinBox->value());
uvModel->setReflectedPtNb(ui->reflectedNumPtsSpinBox->value());
uvModel->setReflectedRadiusFactor(ui->reflectedRadiusSpinBox->value());
if(sources & IntensitySources::REFLECTED && ui->reflectedMapCheckBox->isChecked()){
if(!uvModel->setReflectedMapPath(ui->reflectedMapLineEdit->text().replace("%position%",positionName).toStdString())){
QMessageBox warningMessage(QMessageBox::Warning, "Reflected Map not found", "The reflected map for position " + positionName + " was not found or did not correspond to the position (different number of vertices). The calculation for this position might therefore be very long. Continue?",QMessageBox::Yes | QMessageBox::No, this);
if(warningMessage.exec() == QMessageBox::No){
return false;
}
}
}
//Initiate the Model with the paramters set above
uvModel->initModel();
return true;
}
//ANATOMICAL ZONES
void MainWindow::loadAnatZones(){
QString dir;
if (lastDirectory == ""){
dir=".";
}else{
dir = lastDirectory;
}
currentAnatFilename = QFileDialog::getOpenFileName(this,tr("Select Anatomical Zones Data File"),dir, "*.xml");
if(!currentAnatFilename.isNull()){
//Parse the zone file
zones = IOZones::parseXMLFile(currentAnatFilename.toStdString().c_str());
if(!zones){
QMessageBox::information(0, "Failed to parse anatomical zones file.", "Error");
return;
}
anatZonesChanged = false;
//(Re-)Load the zones in the QTreeWidget
reloadAnatZones();
//Setup GUI based on Excel file information
QFileInfo finfo(currentAnatFilename);
lastDirectory = finfo.absolutePath();
ui->useAnatZonesLineEdit->setText(currentAnatFilename);
checkProtectionsAgainstLibrary();
}
}
QList<QTreeWidgetItem*> MainWindow::loadZonesInTree(vector<Zone*>* zones){
vector<Zone*>::iterator zoneIter;
QList<QTreeWidgetItem*> zoneList;
for(zoneIter = zones->begin(); zoneIter != zones->end(); zoneIter++){
QStringList zoneAttr(QString::fromStdString((*zoneIter)->getName()));
vcg::Color4b *color = (*zoneIter)->getColor();
if(color){
zoneAttr << "" << QString::number((*color)[0]) << QString::number((*color)[1]) << QString::number((*color)[2]);
}
else{
zoneAttr << "" << "" << "" << "";
}
QTreeWidgetItem *zoneItem = new QTreeWidgetItem(zoneAttr);
//Set whether the zone is active
if((*zoneIter)->isZoneActive()){
zoneItem->setCheckState(AnatZonesTreeColumns::ZONE,Qt::Checked);
}
else{
zoneItem->setCheckState(AnatZonesTreeColumns::ZONE,Qt::Unchecked);
}
//Set the zone to be editable
zoneItem->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsUserCheckable ) ;
//Set the color if any
if(color){
zoneItem->setBackgroundColor(AnatZonesTreeColumns::COLOR,QColor((*color)[0], (*color)[1], (*color)[2]));
}
if((*zoneIter)->getSubZones()){
zoneItem->addChildren(loadZonesInTree((*zoneIter)->getSubZones()));
}
zoneList << zoneItem;
}
return zoneList;
}
void MainWindow::anatTreeItemChanged(QTreeWidgetItem *item, int column){
//Set the anatzones changes
anatZonesChanged = true;
reloadAnatZonesChanged();
//Changing zone name is fine in any case
if(column == AnatZonesTreeColumns::ZONE){
return;
}
//Check whether the item has children or not
//If it has, signal to user that the modification is void
if(item->childCount() > 0){
QMessageBox::information(0, "Only anatomical zones without children can have a color.","Notice");
item->setText(column,"");
return;
}
//If the user attempts to change the color directly inform that this is no possible
if(column == AnatZonesTreeColumns::COLOR){
item->setText(column,"");
return;
}
//Finally, if the color was changed, make sure it's within boundaries and change the color column
bool ok;
int newColor = item->text(column).toInt(&ok);
if(!ok || newColor<0){
QMessageBox::information(0, "RGB values can only be integer numbers between 0 and 255.","Notice");
item->setText(column, "0");
}
else if(newColor > 255){
QMessageBox::information(0, "RGB values can only be integer numbers between 0 and 255.","Notice");
item->setText(column, "255");
}
item->setBackgroundColor(AnatZonesTreeColumns::COLOR,QColor(item->text(AnatZonesTreeColumns::RED).toInt(), item->text(AnatZonesTreeColumns::GREEN).toInt(), item->text(AnatZonesTreeColumns::BLUE).toInt()));
}
void MainWindow::addAnatZone(bool topLevel){
//Create new Item
QStringList zoneAttr(QString("New Zone"));
zoneAttr << "" << "" << "" << "";
QTreeWidgetItem *newItem = new QTreeWidgetItem(zoneAttr);
newItem->setCheckState(AnatZonesTreeColumns::ZONE,Qt::Checked);
newItem->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable ) ;
if(topLevel){
ui->anatZonesTreeWidget->addTopLevelItem(newItem);
}
else{
QList<QTreeWidgetItem*> selectedItem = ui->anatZonesTreeWidget->selectedItems();
if(selectedItem.count() == 1){
selectedItem.at(0)->addChild(newItem);
}
}
//Set the anatzones changes
anatZonesChanged = true;
reloadAnatZonesChanged();
}
void MainWindow::addTopLevelAnatZone(){
addAnatZone(true);
}
void MainWindow::deleteAnatZone(){
QList<QTreeWidgetItem*> selectedItem = ui->anatZonesTreeWidget->selectedItems();
if(selectedItem.count() == 1){
delete selectedItem.at(0);
//Set the anatzones changes
anatZonesChanged = true;
reloadAnatZonesChanged();
}
}
void MainWindow::reloadAnatZones(){
//Delete the tree
while( int nb = ui->anatZonesTreeWidget->topLevelItemCount () )
{
delete ui->anatZonesTreeWidget->takeTopLevelItem( nb - 1 );
}
//Reload the zones in the QTreeWidget
if(zones){
ui->anatZonesTreeWidget->addTopLevelItems(loadZonesInTree(zones));
ui->anatZonesTreeWidget->expandAll();
}
//Reload the changed indicator
reloadAnatZonesChanged();
}
void MainWindow::saveAnatZonesAs(){
QString dir;
if (lastDirectory == ""){
dir=".";
}else{
dir = lastDirectory;
}
QString filename = QFileDialog::getSaveFileName(this,"Select File to Save Zones",dir, "*.xml");
if(!filename.isNull()){
currentAnatFilename = filename;
QFileInfo finfo(currentAnatFilename);
lastDirectory = finfo.absolutePath();
saveAnatZones();
}
}
void MainWindow::saveAnatZones(){
if(currentAnatFilename.isEmpty()){
saveAnatZonesAs();
}
else{
IOZones::saveZonesFile(ui->anatZonesTreeWidget,currentAnatFilename.toStdString());
ui->useAnatZonesLineEdit->setText(currentAnatFilename);
Helpers::deleteZones(&zones);
zones = IOZones::parseXMLFile(currentAnatFilename.toStdString().c_str());
anatZonesChanged = false;
reloadAnatZones();
checkProtectionsAgainstLibrary();
}
}
/*void MainWindow::setAnatZonesExportName(){
if(ui->exportAnatZonesLineEdit->text().isEmpty()){
ui->exportAnatZonesLineEdit->setText(meshDoc->mm()->pathName()+"/"+anatZonesFilename);
}
}*/
void MainWindow::reloadAnatZonesChanged(){
if(anatZonesChanged){
ui->advancedTabWidget->setTabText(AdvancedTabs::ANATZONES,"Anatomical Zones*");
ui->anatomicalZonesGroupBox->setTitle("Anatomical Zones*");
}
else{
ui->advancedTabWidget->setTabText(AdvancedTabs::ANATZONES,"Anatomical Zones");
ui->anatomicalZonesGroupBox->setTitle("Anatomical Zones");
}
}
//POI
void MainWindow::loadPOI(){
QString dir;
if (lastDirectory == ""){
dir=".";
}else{
dir = lastDirectory;
}
QString filename = QFileDialog::getOpenFileName(this,tr("Select POI Data File"),dir, "*.pp");
if(!filename.isNull()){
//Parse the POI file
poi = IOPoints::parseXMLFile(filename.toStdString().c_str());
//(Re-)load the POIs
reloadPOI();
//Setup GUI based on Excel file information
QFileInfo finfo(filename);
lastDirectory = finfo.absolutePath();
ui->usePOILineEdit->setText(filename);
}
}
void MainWindow::reloadPOI(){
while( int nb = ui->POITreeWidget->topLevelItemCount () )
{
delete ui->POITreeWidget->takeTopLevelItem( nb - 1 );
}
//Display the points
if(poi){
vector<POI>::iterator poiIter;
for(poiIter = poi->begin(); poiIter != poi->end(); poiIter++){
ui->POITreeWidget->addTopLevelItem(new QTreeWidgetItem(QStringList(QString::fromStdString(poiIter->getPointName()))));
}
}
}
/*void MainWindow::setPOIexportName(){
if(ui->exportPOILineEdit->text().count() < 1){
//ui->exportPOILineEdit->setText(baseName + "-POI_intensities.csv");
ui->exportPOILineEdit->setText(meshDoc->mm()->pathName()+"/"+POIFilename);
}
}*/
//PROTECTIONS
void MainWindow::loadProtectionsLib(){
QString dir;
if (lastDirectory == ""){
dir=".";
}else{
dir = lastDirectory;
}
currentProtectionsLibFilename = QFileDialog::getOpenFileName(this,tr("Select Protections Library File"),dir, "*.xml");
if(!currentProtectionsLibFilename.isNull()){
//Parse the Protections lib file
Protections::loadProtectionsLib(currentProtectionsLibFilename.toStdString().c_str());
//(Re)load the library
reloadProtectionsLib();
}
}
void MainWindow::reloadProtectionsLib(){
//Empty the protections lib
while( int nb = ui->protectionsLibClothesTreeWidget->topLevelItemCount () )
{
delete ui->protectionsLibClothesTreeWidget->takeTopLevelItem( nb - 1 );
}