-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExportOpenEMSDialog.py
3496 lines (2842 loc) · 187 KB
/
ExportOpenEMSDialog.py
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
try:
from PySide import QtGui, QtCore, QtWidgets
from PySide.QtCore import Slot
except ImportError:
from PySide6 import QtGui, QtCore, QtWidgets
from PySide6.QtCore import Slot
import os, sys
import re
import random
import numpy as np
import math
#import needed local classes
import sys
import traceback
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
APP_CONTEXT = "None"
try:
import FreeCAD
import WebGui
import KiCADImporterToolDialog #import for KiCAD Import Tool
APP_CONTEXT = "FreeCAD"
except ImportError:
pass
APP_DIR = os.path.dirname(os.path.abspath(__file__))
path_to_ui = os.path.join(APP_DIR, "ui", "dialog.ui")
from utilsOpenEMS.SettingsItem.SettingsItem import SettingsItem
from utilsOpenEMS.SettingsItem.PortSettingsItem import PortSettingsItem
from utilsOpenEMS.SettingsItem.ProbeSettingsItem import ProbeSettingsItem
from utilsOpenEMS.SettingsItem.ExcitationSettingsItem import ExcitationSettingsItem
from utilsOpenEMS.SettingsItem.LumpedPartSettingsItem import LumpedPartSettingsItem
from utilsOpenEMS.SettingsItem.MaterialSettingsItem import MaterialSettingsItem
from utilsOpenEMS.SettingsItem.SimulationSettingsItem import SimulationSettingsItem
from utilsOpenEMS.SettingsItem.GridSettingsItem import GridSettingsItem
from utilsOpenEMS.SettingsItem.FreeCADSettingsItem import FreeCADSettingsItem
from utilsOpenEMS.ScriptLinesGenerator.PythonScriptLinesGenerator2 import PythonScriptLinesGenerator2 #EXPERIMENTAL JUST FOR DEBUGGING TILL MOVE TO RELEASE
from utilsOpenEMS.GuiHelpers.GuiHelpers import GuiHelpers
from utilsOpenEMS.GuiHelpers.FactoryCadInterface import FactoryCadInterface
from utilsOpenEMS.GuiHelpers.GuiSignals import GuiSignals
from utilsOpenEMS.SaveLoad.IniFile0v1 import IniFile0v1
# UI file (use Qt Designer to modify)
from utilsOpenEMS.GlobalFunctions.GlobalFunctions import _bool, _r
#
# Main GUI panel class
#
class ExportOpenEMSDialog(QtCore.QObject):
def finished(self):
"""
Finish observing CAD signals for add/remove/rename.
:return: None
"""
if self.cadInterfaceType == "FreeCAD":
self.observer.endObservation()
self.observer = None
print("FreeCAD observer terminated.")
#if KiCAD import tool is opened close it
if hasattr(self, "KiCADImportTool"):
self.KiCADImportTool.close()
del self.KiCADImportTool
print("Kicad Import Tool closed")
def eventFilter(self, object, event):
if event.type() == QtCore.QEvent.Close:
self.finished()
return super(ExportOpenEMSDialog, self).eventFilter(object, event)
def __init__(self):
QtCore.QObject.__init__(self)
self.APP_DIR = APP_DIR
#
# Directory for generated .m file for openEMS
# - by default set to None, that means simulation file should be generated into current directory
#
self.simulationOutputDir = None
#
# LOCAL OPENEMS OBJECT
#
self.cadHelpers = FactoryCadInterface.createHelper(self.APP_DIR)
#
# Check if document is available, otherwise exit early.
#
if not self.cadHelpers.documentReady():
msgBox = QtWidgets.QMessageBox()
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setText("This macro needs an active document to run. Please open or create one.")
msgBox.exec()
return
#
# Change current path to script file folder
#
os.chdir(APP_DIR)
# this will create a Qt widget from our ui file
self.form = self.cadHelpers.loadUI(path_to_ui, self)
# self.form.finished.connect(self.finished) # QDialog event
self.form.installEventFilter(self)
# add a statusBar widget (comment to revert to QMessageBox if there are any problems)
self.statusBar = QtWidgets.QStatusBar()
self.statusBar.setStyleSheet("QStatusBar{border-top: 1px outset grey;}")
self.form.dialogVertLayout.addWidget(self.statusBar)
#
# FONT SIZE whoole GUI
#
#self.form.setStyleSheet(".QLabel{font-size: 25pt;}")
#
# instantiate script generators using this dialog form
#
guiHelpers = GuiHelpers(self.form, statusBar = self.statusBar)
self.pythonScriptGenerator = PythonScriptLinesGenerator2(self.form, guiHelpers=guiHelpers)
self.scriptGenerator = self.pythonScriptGenerator
#
# GUI helpers function like display message box and so
#
self.guiHelpers = GuiHelpers(self.form, statusBar = self.statusBar, APP_DIR=APP_DIR)
self.guiSignals = GuiSignals()
#
# INI file object to used for save/load operation
#
self.simulationSettingsFile = IniFile0v1(self.form, statusBar = self.statusBar, guiSignals = self.guiSignals, APP_DIR = APP_DIR)
#
# TOP LEVEL ITEMS / Category Items (excitation, grid, materials, ...)
#
self.guiHelpers.initRightColumnTopLevelItems()
#select first item
topItem = self.form.objectAssignmentRightTreeWidget.itemAt(0,0)
self.form.objectAssignmentRightTreeWidget.setCurrentItem(topItem)
self.form.moveLeftButton.clicked.connect(self.onMoveLeft)
self.form.moveRightButton.clicked.connect(self.onMoveRight)
#########################################################################################################
# Left Column - FreeCAD objects list
#########################################################################################################
self.internalObjectNameLabelList = {}
self.initLeftColumnTopLevelItems()
self.form.objectAssignmentLeftTreeWidget.itemDoubleClicked.connect(self.objectAssignmentLeftTreeWidgetItemDoubleClicked)
self.form.objectAssignmentLeftTreeWidget.itemSelectionChanged.connect(self.objectAssignmentLeftTreeWidgetItemSelectionChanged)
#########################################################################################################
# RIGHT COLUMN - Simulation Object Assignment
#########################################################################################################
self.form.objectAssignmentRightTreeWidget.itemSelectionChanged.connect(self.objectAssignmentRightTreeWidgetItemSelectionChanged)
self.form.objectAssignmentRightTreeWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.form.objectAssignmentRightTreeWidget.customContextMenuRequested.connect(self.objectAssignmentRightTreeWidgetContextClicked)
self.form.objectAssignmentRightTreeWidget.itemDoubleClicked.connect(self.objectAssignmentRightTreeWidgetItemDoubleClicked)
#########################################################################################################
#########################################################################################################
#########################################################################################################
#
# SETTINGS FOR BUTTONS CLICK, functions assignments
#
self.form.gridSettingsAddButton.clicked.connect(self.gridSettingsAddButtonClicked)
self.form.gridSettingsRemoveButton.clicked.connect(self.gridSettingsRemoveButtonClicked)
self.form.gridSettingsUpdateButton.clicked.connect(self.gridSettingsUpdateButtonClicked)
self.form.materialSettingsAddButton.clicked.connect(self.materialSettingsAddButtonClicked)
self.form.materialSettingsRemoveButton.clicked.connect(self.materialSettingsRemoveButtonClicked)
self.form.materialSettingsUpdateButton.clicked.connect(self.materialSettingsUpdateButtonClicked)
self.guiSignals.materialsChanged.connect(self.materialsChanged)
self.form.excitationSettingsAddButton.clicked.connect(self.excitationSettingsAddButtonClicked)
self.form.excitationSettingsRemoveButton.clicked.connect(self.excitationSettingsRemoveButtonClicked)
self.form.excitationSettingsUpdateButton.clicked.connect(self.excitationSettingsUpdateButtonClicked)
self.form.portSettingsAddButton.clicked.connect(self.portSettingsAddButtonClicked)
self.form.portSettingsRemoveButton.clicked.connect(self.portSettingsRemoveButtonClicked)
self.form.portSettingsUpdateButton.clicked.connect(self.portSettingsUpdateButtonClicked)
self.guiSignals.portsChanged.connect(self.portsChanged)
self.form.lumpedPartSettingsAddButton.clicked.connect(self.lumpedPartSettingsAddButtonClicked)
self.form.lumpedPartSettingsRemoveButton.clicked.connect(self.lumpedPartSettingsRemoveButtonClicked)
self.form.lumpedPartSettingsUpdateButton.clicked.connect(self.lumpedPartSettingsUpdateButtonClicked)
self.form.probeSettingsAddButton.clicked.connect(self.probeSettingsAddButtonClicked)
self.form.probeSettingsRemoveButton.clicked.connect(self.probeSettingsRemoveButtonClicked)
self.form.probeSettingsUpdateButton.clicked.connect(self.probeSettingsUpdateButtonClicked)
self.guiSignals.probesChanged.connect(self.probesChanged)
#
# Handle function for grid radio buttons click
#
self.form.userDefinedRadioButton.clicked.connect(self.userDefinedRadioButtonClicked)
self.form.fixedCountRadioButton.clicked.connect(self.fixedCountRadioButtonClicked)
self.form.fixedDistanceRadioButton.clicked.connect(self.fixedDistanceRadioButtonClicked)
self.form.smoothMeshRadioButton.clicked.connect(self.smoothMeshRadioButtonClicked)
# Handle function for MATERIAL RADIO BUTTONS
self.form.materialUserDefinedRadioButton.toggled.connect(self.materialUserDeinedRadioButtonToggled)
self.form.materialConductingSheetRadioButton.toggled.connect(self.materialConductingSheetRadioButtonToggled)
#
# Clicked on "Generate OpenEMS Script"
#
self.form.generateOpenEMSScriptButton.clicked.connect(self.generateOpenEMSScriptButtonClicked)
#
# Clicked on BUTTONS FOR OBJECT PRIORITIES
#
self.form.moveupPriorityButton.clicked.connect(self.moveupPriorityButtonClicked)
self.form.movedownPriorityButton.clicked.connect(self.movedownPriorityButtonClicked)
#
# Clicked on BUTTONS FOR MESH PRIORITIES
#
self.form.moveupMeshPriorityButton.clicked.connect(self.moveupPriorityMeshButtonClicked)
self.form.movedownMeshPriorityButton.clicked.connect(self.movedownPriorityMeshButtonClicked)
#
# Octave/Matlab script generating buttons handlers
#
self.form.eraseAuxGridButton.clicked.connect(self.eraseAuxGridButtonClicked) # Clicked on "Erase aux Grid"
self.form.abortSimulationButton.clicked.connect(lambda: self.abortSimulationButtonClicked(self.simulationOutputDir)) # Clicked on "Write ABORT Simulation File"
self.form.drawS11Button.clicked.connect(self.drawS11ButtonClicked) # Clicked on "Write Draw S11 Script"
self.form.drawS21Button.clicked.connect(self.drawS21ButtonClicked) # Clicked on "Write Draw S21 Script"
self.form.writeNf2ffButton.clicked.connect(self.writeNf2ffButtonClicked) # Clicked on "Write NF2FF"
#
# GRID
# - button "Display gridlines...."
# - button "Create userdef..."
# - select rectangular or cylindrical grid
#
self.form.createUserdefGridLinesFromCurrentButton.clicked.connect(self.createUserdefGridLinesFromCurrentButtonClicked)
self.form.displayXYGridLinesInModelButton.clicked.connect(self.displayXYGridLinesInModelButtonClicked)
self.form.gridRectangularRadio.toggled.connect(self.gridCoordsTypeChoosed)
self.form.gridCylindricalRadio.toggled.connect(self.gridCoordsTypeChoosed)
self.form.gridXEnable.stateChanged.connect(lambda:[
element.setEnabled(True)
if self.form.gridXEnable.checkState() == QtCore.Qt.Checked else
element.setEnabled(False)
for element in [self.form.fixedCountXNumberInput, self.form.fixedDistanceXNumberInput, self.form.smoothMeshXMaxRes]
])
self.form.gridYEnable.stateChanged.connect(lambda:[
element.setEnabled(True)
if self.form.gridYEnable.checkState() == QtCore.Qt.Checked else
element.setEnabled(False)
for element in [self.form.fixedCountYNumberInput, self.form.fixedDistanceYNumberInput, self.form.smoothMeshYMaxRes]
])
self.form.gridZEnable.stateChanged.connect(lambda:[
element.setEnabled(True)
if self.form.gridZEnable.checkState() == QtCore.Qt.Checked else
element.setEnabled(False)
for element in [self.form.fixedCountZNumberInput, self.form.fixedDistanceZNumberInput, self.form.smoothMeshZMaxRes]
])
# grid offset gui form enable/disable
self.form.gridXEnable.stateChanged.connect(lambda:[
element.setEnabled(True)
if self.form.gridXEnable.checkState() == QtCore.Qt.Checked and self.form.gridGenerateLinesInsideCheckbox.checkState() == QtCore.Qt.Checked else
element.setEnabled(False)
for element in [self.form.gridOffsetX]
])
self.form.gridYEnable.stateChanged.connect(lambda:[
element.setEnabled(True)
if self.form.gridYEnable.checkState() == QtCore.Qt.Checked and self.form.gridGenerateLinesInsideCheckbox.checkState() == QtCore.Qt.Checked else
element.setEnabled(False)
for element in [self.form.gridOffsetY]
])
self.form.gridZEnable.stateChanged.connect(lambda:[
element.setEnabled(True)
if self.form.gridZEnable.checkState() == QtCore.Qt.Checked and self.form.gridGenerateLinesInsideCheckbox.checkState() == QtCore.Qt.Checked else
element.setEnabled(False)
for element in [self.form.gridOffsetZ]
])
self.form.gridGenerateLinesInsideCheckbox.stateChanged.connect(self.gridGenerateLinesInsideCheckboxToggle)
self.guiSignals.gridCoordsTypeChanged.connect(self.gridCoordsTypeChanged)
#
# Material, Grid, Excitation, ... item changed handler functions.
#
self.form.materialSettingsTreeView.currentItemChanged.connect(self.materialTreeWidgetItemChanged)
self.form.excitationSettingsTreeView.currentItemChanged.connect(self.excitationTreeWidgetItemChanged)
self.form.gridSettingsTreeView.currentItemChanged.connect(self.gridTreeWidgetItemChanged)
self.form.portSettingsTreeView.currentItemChanged.connect(self.portTreeWidgetItemChanged)
self.form.lumpedPartTreeView.currentItemChanged.connect(self.lumpedPartTreeWidgetItemChanged)
self.form.probeSettingsTreeView.currentItemChanged.connect(self.probeTreeWidgetItemChanged)
#
# PORT tab settings events handlers
#
self.form.lumpedPortRadioButton.toggled.connect(self.portSettingsTypeChoosed)
self.form.microstripPortRadioButton.toggled.connect(self.portSettingsTypeChoosed)
self.form.circularWaveguidePortRadioButton.toggled.connect(self.portSettingsTypeChoosed)
self.form.rectangularWaveguidePortRadioButton.toggled.connect(self.portSettingsTypeChoosed)
self.form.coaxialPortRadioButton.toggled.connect(self.portSettingsTypeChoosed)
self.form.coplanarPortRadioButton.toggled.connect(self.portSettingsTypeChoosed)
self.form.striplinePortRadioButton.toggled.connect(self.portSettingsTypeChoosed)
self.form.curvePortRadioButton.toggled.connect(self.portSettingsTypeChoosed)
self.form.microstripPortDirection.activated.connect(self.microstripPortDirectionOnChange)
self.form.striplinePortDirection.activated.connect(self.striplinePortDirectionOnChange)
self.form.coplanarPortDirection.activated.connect(self.coplanarPortDirectionOnChange)
self.form.lumpedPortInfinitResistance.stateChanged.connect(lambda: [
element.setEnabled(False) if self.form.lumpedPortInfinitResistance.isChecked() else element.setEnabled(True)
for element in [self.form.lumpedPortResistanceValue, self.form.lumpedPortResistanceUnits]
])
self.form.microstripPortDirection.activated.emit(0) #emit signal to fill connected combobox or whatever with right values after startup, ie. when user start GUI there is no change
# and combobox with propagation direction left with all possibilities
self.form.coplanarPortDirection.activated.emit(0) #emit signal to fill connected combobox or whatever with right values after startup, ie. when user start GUI there is no change
# and combobox with propagation direction left with all possibilities
self.form.striplinePortDirection.activated.emit(0) #emit signal to fill connected combobox or whatever with right values after startup, ie. when user start GUI there is no change
# and combobox with propagation direction left with all possibilities
################################################################################################################
# PROBE TAB -> DUMPBOX TAB UI EVENT HANDLERS
################################################################################################################
self.form.probeProbeRadioButton.toggled.connect(self.probeSettingsTypeChoosed)
self.form.dumpboxProbeRadioButton.toggled.connect(self.probeSettingsTypeChoosed)
self.form.etDumpProbeRadioButton.toggled.connect(self.probeSettingsTypeChoosed)
self.form.htDumpProbeRadioButton.toggled.connect(self.probeSettingsTypeChoosed)
self.form.nf2ffBoxProbeRadioButton.toggled.connect(self.probeSettingsTypeChoosed)
self.form.probeProbeFrequencyAddButton.clicked.connect(self.probeProbeFrequencyAddButtonClicked)
self.form.probeProbeFrequencyRemoveButton.clicked.connect(self.probeProbeFrequencyRemoveButtonClicked)
self.form.probeProbeDomain.currentIndexChanged.connect(lambda:[
element.setEnabled(True)
if self.form.probeProbeDomain.currentText() == "frequency" else
element.setEnabled(False)
for element in [self.form.probeProbeFrequencyInput, self.form.probeProbeFrequencyUnits, self.form.probeProbeFrequencyList, self.form.probeProbeFrequencyAddButton, self.form.probeProbeFrequencyRemoveButton]
])
self.form.dumpboxProbeFrequencyAddButton.clicked.connect(self.dumpboxProbeFrequencyAddButtonClicked)
self.form.dumpboxProbeFrequencyRemoveButton.clicked.connect(self.dumpboxProbeFrequencyRemoveButtonClicked)
self.form.dumpboxProbeDomain.currentIndexChanged.connect(self.dumpboxProbeDomainChanged) #enable/disable frequency settings for probe based on domain, also change filetype for domains
################################################################################################################
# SIMULATION TAB boundary condition change handlers, minimal spacing handler enable/disable spinboxes
################################################################################################################
#SIMULATION Boundary Conditions change event mapping
self.form.BCxmin.currentIndexChanged.connect(self.BCxminCurrentIndexChanged)
self.form.BCxmax.currentIndexChanged.connect(self.BCxmaxCurrentIndexChanged)
self.form.BCymin.currentIndexChanged.connect(self.BCyminCurrentIndexChanged)
self.form.BCymax.currentIndexChanged.connect(self.BCymaxCurrentIndexChanged)
self.form.BCzmin.currentIndexChanged.connect(self.BCzminCurrentIndexChanged)
self.form.BCzmax.currentIndexChanged.connect(self.BCzmaxCurrentIndexChanged)
self.form.genParamMinGridSpacingEnable.stateChanged.connect(lambda:
[element.setEnabled(True) for element in [self.form.genParamMinGridSpacingX, self.form.genParamMinGridSpacingY, self.form.genParamMinGridSpacingZ]]
if self.form.genParamMinGridSpacingEnable.isChecked() else
[element.setEnabled(False) for element in [self.form.genParamMinGridSpacingX, self.form.genParamMinGridSpacingY, self.form.genParamMinGridSpacingZ]]
)
####################################################################################################
# GUI SAVE/LOAD from file
####################################################################################################
self.form.saveToFileSettingsButton.clicked.connect(self.saveToFileSettingsButtonClicked)
self.form.loadFromFileSettingsButton.clicked.connect(self.loadFromFileSettingsButtonClicked)
#
# FILTER LEFT COLUMN ITEMS
#
self.form.objectAssignmentFilterLeft.returnPressed.connect(self.applyObjectAssignmentFilter)
# MinDecrement changed
self.form.simParamsMinDecrement.valueChanged.connect(self.simParamsMinDecrementValueChanged)
### Other Initialization
# initialize dB preview label with converted value
self.simParamsMinDecrementValueChanged(self.form.simParamsMinDecrement.value())
#
# KiCAD Importer Tool
#
self.form.KiCADImportButton.clicked.connect(self.KiCADImportButtonClicked)
self.cadInterfaceType = APP_CONTEXT
print("Creating document handlers")
if APP_CONTEXT == "FreeCAD":
try:
self.form.KiCADImportButton.setEnabled(True) #enable KiCAD Importer Tool, it's JUST FOR FreeCAD
# create observer instance
from utilsOpenEMS.GuiHelpers.FreeCADDocObserver import FreeCADDocObserver
self.observer = FreeCADDocObserver()
self.observer.objectCreated += self.freecadObjectCreated
self.observer.objectChanged += self.freecadObjectChanged
self.observer.objectDeleted += self.freecadBeforeObjectDeleted
self.observer.startObservation()
except:
self.cadHelpers.printError("Cannot create FreeCAD observer, there is no connection to CAD program signals.")
pass
# connect signal for button to display help page
try:
self.form.buttonOpenHelpPage.clicked.connect(self.openFreeCADWebGuiHelp)
except Exception as e:
self.cadHelpers.printError("Error to connect signal for button to display help.")
self.cadHelpers.printError(e)
#
# GUI font size change
#
self.form.guiFontSizeCombobox.currentIndexChanged.connect(lambda: self.form.setStyleSheet(f"font: {self.form.guiFontSizeCombobox.currentText()} \"{self.form.guiFontFamilyCombobox.currentText()}\";"))
self.form.guiFontFamilyCombobox.currentIndexChanged.connect(lambda: self.form.setStyleSheet(f"font: {self.form.guiFontSizeCombobox.currentText()} \"{self.form.guiFontFamilyCombobox.currentText()}\";"))
#
# add default PEC material
#
self.materialAddPEC()
#
# Simulation items (grid, material, excitation, port, lumped part) renamed signal connect
#
self.guiSignals.gridRenamed.connect(self.gridRenamed)
self.guiSignals.gridTypeChangedToSmoothMesh.connect(self.gridTypeChangedToSmoothMesh)
self.guiSignals.gridTypeChangedFromSmoothMesh.connect(self.gridTypeChangedFromSmoothMesh)
self.guiSignals.materialRenamed.connect(self.materialRenamed)
self.guiSignals.excitationRenamed.connect(self.excitationRenamed)
self.guiSignals.portRenamed.connect(self.portRenamed)
self.guiSignals.lumpedPartRenamed.connect(self.lumpedPartRenamed)
self.guiSignals.probeRenamed.connect(self.probeRenamed)
print(f"----> init finished")
def KiCADImportButtonClicked(self):
# if KiCAD import tool is not created create new one
if not hasattr(self, "KiCADImportTool"):
self.KiCADImportTool = KiCADImporterToolDialog.KiCADImporterToolDialog()
self.KiCADImportTool.show()
def openFreeCADWebGuiHelp(self):
"""
Open index help html webpage inside freecad window.
:return:
"""
WebGui.openBrowser(f"{os.path.dirname(__file__)}\\documentation\\help\\index.html")
def freecadObjectCreated(self, obj):
print("freecadObjectCreated :{} ('{}')".format(obj.FullName, obj.Label))
# A new object has been created. Only the list of available objects needs to be updated.
filterStr = self.form.objectAssignmentFilterLeft.text()
self.initLeftColumnTopLevelItems(filterStr)
def freecadObjectChanged(self, obj, prop, enableReInitLeftColumn=True):
print("freecadObjectChanged :{} ('{}') property changed: {}".format(obj.FullName, obj.Label, prop))
#property label was changes, object was renamed in freecad
if prop == 'Label':
# The label (displayed name) of an object has changed.
# (TODO) Update all mentions in the ObjectAssigments panel.
#
# Rename items in right column where objects are assigned to categories
#
itemsWithOriginalLabel = self.form.objectAssignmentRightTreeWidget.findItems(self.internalObjectNameLabelList[obj.Name], QtCore.Qt.MatchExactly | QtCore.Qt.MatchFlag.MatchRecursive)
print(f"RIGHT ASSIGNMENT WIDGET found {len(itemsWithOriginalLabel)}")
for itemToRename in itemsWithOriginalLabel:
reResult = re.search("([A-Za-z]*)SettingsItem'", str(type(itemToRename.data(0, QtCore.Qt.UserRole))))
if (reResult.group(1).lower() == "freecad"):
itemToRename.setText(0, obj.Label)
#
# Renames items in priority list and mesh priority list, names there are like:
# Material, some name, objectName
# so this object name from end must be replace by new name
#
itemsWithOriginalLabel = []
itemsWithOriginalLabel += self.form.objectAssignmentPriorityTreeView.findItems(self.internalObjectNameLabelList[obj.Name], QtCore.Qt.MatchEndsWith | QtCore.Qt.MatchFlag.MatchRecursive)
itemsWithOriginalLabel += self.form.meshPriorityTreeView.findItems(self.internalObjectNameLabelList[obj.Name], QtCore.Qt.MatchEndsWith | QtCore.Qt.MatchFlag.MatchRecursive)
print(f"OBJECT PRIORITIES found {len(itemsWithOriginalLabel)}")
for itemToRename in itemsWithOriginalLabel:
newLabel = itemToRename.text(0)
newLabel = newLabel[:-len(self.internalObjectNameLabelList[obj.Name])] + obj.Label
itemToRename.setText(0, newLabel)
#
# TinitLeftCOlumnToLevelItems refill internalObjectNameLabelList, so when working in bulk this reinit must be supressed till last item
#
if enableReInitLeftColumn:
filterStr = self.form.objectAssignmentFilterLeft.text()
self.initLeftColumnTopLevelItems(filterStr)
def freecadBeforeObjectDeleted(self,obj):
# event is generated before object is being removed, so observing instances have to
# (TODO) un-list the object without drawing upon the FreeCAD objects list, and
# (TODO) propagate changes to prevent corruption.
# Simple approach: delete dependent entries.
# Advanced: remember and gray out deleted objects to allow settings to be restored when
# the user brings the object back with Redo.
print("freecadObjectDeleted :{} ('{}')".format(obj.FullName, obj.Label))
#
# Rename items in right column where objects are assigned to categories
#
itemsWithOriginalLabel = self.form.objectAssignmentRightTreeWidget.findItems(obj.Label, QtCore.Qt.MatchExactly | QtCore.Qt.MatchFlag.MatchRecursive)
for itemToRename in itemsWithOriginalLabel:
reResult = re.search("([A-Za-z]*)SettingsItem'", str(type(itemToRename.data(0, QtCore.Qt.UserRole))))
if (reResult.group(1).lower() == "freecad"):
itemToRename.parent().removeChild(itemToRename)
#
# Renames items in priority list and mesh priority list, names there are like:
# Material, some name, objectName
# so this object name from end must be replace by new name
#
itemsWithOriginalLabel = self.form.objectAssignmentPriorityTreeView.findItems(obj.Label, QtCore.Qt.MatchEndsWith | QtCore.Qt.MatchFlag.MatchRecursive)
for itemToRename in itemsWithOriginalLabel:
self.form.objectAssignmentPriorityTreeView.invisibleRootItem().removeChild(itemToRename)
itemsWithOriginalLabel = self.form.meshPriorityTreeView.findItems(obj.Label, QtCore.Qt.MatchEndsWith | QtCore.Qt.MatchFlag.MatchRecursive)
for itemToRename in itemsWithOriginalLabel:
self.form.meshPriorityTreeView.invisibleRootItem().removeChild(itemToRename)
#
# Remove from left widget object because this is running before delete so if init function for left widget would be executed object will be still there
#
itemsWithOriginalLabel = self.form.objectAssignmentLeftTreeWidget.findItems(obj.Label, QtCore.Qt.MatchEndsWith | QtCore.Qt.MatchFlag.MatchRecursive)
for itemToRename in itemsWithOriginalLabel:
self.form.meshPriorityTreeView.invisibleRootItem().removeChild(itemToRename)
# remove object label from internal list
del self.internalObjectNameLabelList[obj.Name]
def simParamsMinDecrementValueChanged(self, newValue):
if newValue == 0:
s = '( -inf dB )'
else:
s = '( ' + str(np.round(10 * np.log10(newValue), decimals=2)) + ' dB )'
self.form.simParamsMinDecrementdBLabel.setText(s)
def BCxminCurrentIndexChanged(self, index):
self.form.PMLxmincells.setEnabled(self.form.BCxmin.currentText() == "PML")
def BCxmaxCurrentIndexChanged(self, index):
self.form.PMLxmaxcells.setEnabled(self.form.BCxmax.currentText() == "PML")
def BCyminCurrentIndexChanged(self, index):
self.form.PMLymincells.setEnabled(self.form.BCymin.currentText() == "PML")
def BCymaxCurrentIndexChanged(self, index):
self.form.PMLymaxcells.setEnabled(self.form.BCymax.currentText() == "PML")
def BCzminCurrentIndexChanged(self, index):
self.form.PMLzmincells.setEnabled(self.form.BCzmin.currentText() == "PML")
def BCzmaxCurrentIndexChanged(self, index):
self.form.PMLzmaxcells.setEnabled(self.form.BCzmax.currentText() == "PML")
def eraseAuxGridButtonClicked(self):
print("--> Start removing auxiliary gridlines from 3D view.")
auxGridLines = self.cadHelpers.getObjects()
for gridLine in auxGridLines:
print("--> Removing " + gridLine.Label + " from 3D view.")
if "auxGridLine" in gridLine.Label:
self.cadHelpers.removeObject(gridLine.Name)
print("--> End removing auxiliary gridlines from 3D view.")
def createUserdefGridLinesFromCurrentButtonClicked(self):
"""
print("--> Start creating user defined grid from 3D model.")
allObjects = self.cadHelpers.getObjects()
gridLineListX = []
gridLineListY = []
gridLineListZ = []
for gridLine in allObjects:
if "auxGridLine" in gridLine.Label:
gridLineDirection = abs(gridLine.End - gridLine.Start)
if (gridLineDirection[0] > 0):
gridLineListX.append(gridLine)
print("Discovered " + str(len(gridLineList)) + " gridlines in model.")
print("--> End creating user defined grid from 3D model.")
"""
self.guiHelpers.displayMessage("createUserdefGridLinesFromCurrentButtonClicked")
def displayXYGridLinesInModelButtonClicked(self):
print('displayXYGridLinesInModelButtonClicked: start draw whole XY grid for each object')
gridCategory = self.form.objectAssignmentRightTreeWidget.findItems("Grid", QtCore.Qt.MatchFixedString)[0]
for gridItemIndex in range(gridCategory.childCount()):
for objIndex in range(gridCategory.child(gridItemIndex).childCount()):
currItem = gridCategory.child(gridItemIndex).child(objIndex)
print(currItem.text(0))
self.objectDrawGrid(currItem)
def updateComboboxWithAllowedItems(self, comboboxRef, sourceCategory="", allowedTypes=[], isActive=None):
currentItemText = comboboxRef.currentText()
comboboxRef.clear()
currentIndex = 0
addedItemCounter = 0
for k in range(0, self.form.objectAssignmentRightTreeWidget.topLevelItemCount()):
if (self.form.objectAssignmentRightTreeWidget.topLevelItem(k).text(0) == sourceCategory):
for l in range(0, self.form.objectAssignmentRightTreeWidget.topLevelItem(k).childCount()):
itemSettings = self.form.objectAssignmentRightTreeWidget.topLevelItem(k).child(l).data(0, QtCore.Qt.UserRole)
#Check if item is applicable to be added into combobox
if ((len(allowedTypes) == 0 or itemSettings.type in allowedTypes) and (isActive == None or (hasattr(itemSettings, 'isActive') and itemSettings.isActive == isActive))):
if (self.form.objectAssignmentRightTreeWidget.topLevelItem(k).child(l).childCount() > 0):
#iterate through each added object into port category and generate name for it in format "[category name] - [assigned object label]"
for m in range(0, self.form.objectAssignmentRightTreeWidget.topLevelItem(k).child(l).childCount()):
subNewItemText = self.form.objectAssignmentRightTreeWidget.topLevelItem(k).child(l).text(0)
subNewItemText += " - "
subNewItemText += self.form.objectAssignmentRightTreeWidget.topLevelItem(k).child(l).child(m).text(0)
comboboxRef.addItem(subNewItemText)
if (subNewItemText == currentItemText):
currentIndex = addedItemCounter
addedItemCounter += 1
"""
else:
newItemText = self.form.objectAssignmentRightTreeWidget.topLevelItem(k).child(l).text(0)
comboboxRef.addItem(newItemText)
if (newItemText == currentItemText):
currentIndex = addedItemCounter
addedItemCounter += 1
"""
comboboxRef.setCurrentIndex(currentIndex)
def updateObjectAssignmentRightTreeWidgetItemData(self, groupName, itemName, data):
updatedItems = self.form.objectAssignmentRightTreeWidget.findItems(
itemName,
QtCore.Qt.MatchExactly | QtCore.Qt.MatchFlag.MatchRecursive
)
#there can be more items in right column which has same name, like air under MAterials and Grid, so always is needed to compare if parent
#is same as parent from update function when this was called to update new settings
for item in updatedItems:
if item.parent().text(0) == groupName:
item.setData(0, QtCore.Qt.UserRole, data)
def renameObjectAssignmentRightTreeWidgetItem(self, groupName, itemOldName, itemNewName):
updatedItems = self.form.objectAssignmentRightTreeWidget.findItems(
itemOldName,
QtCore.Qt.MatchExactly | QtCore.Qt.MatchFlag.MatchRecursive
)
#there can be more items in right column which has same name, like air under MAterials and Grid, so always is needed to compare if parent
#is same as parent from update function when this was called to update new settings
for item in updatedItems:
if item.parent().text(0) == groupName:
item.setText(0, itemNewName)
def renameObjectAssignmentPriorityTreeViewItem(self, groupName, itemOldName, itemNewName):
searchStr = groupName + ", " + itemOldName
updatedItems = self.form.objectAssignmentPriorityTreeView.findItems(
searchStr,
QtCore.Qt.MatchStartsWith
)
for item in updatedItems:
newName = groupName + ", " + itemNewName + ", " + item.text(0)[len(searchStr)+2:] #must take end of mesh priority item name, means length of searchStr + len(", ")
self.cadHelpers.printWarning(f"Updating {item.text(0)} -> {newName}")
item.setText(0, newName)
def renameMeshPriorityTreeViewItem(self, itemOldName, itemNewName):
searchStr = "Grid, " + itemOldName
updatedItems = self.form.meshPriorityTreeView.findItems(
searchStr,
QtCore.Qt.MatchStartsWith
)
for item in updatedItems:
newName = "Grid, " + itemNewName + ", " + item.text(0)[len(searchStr)+2:] #must take end of mesh priority item name, means length of searchStr + len(", ")
self.cadHelpers.printWarning(f"Updating {item.text(0)} -> {newName}")
item.setText(0, newName)
def renameTreeViewItem(self, treeViewRef, itemOldName, itemNewName):
"""
Renames item in tree view to new name. String search must match exactly.
:param treeViewRef: Reference to tree view widget
:param itemOldName: Old item name.
:param itemNewName: New item name.
:return:
"""
updatedItems = treeViewRef.findItems(
itemOldName,
QtCore.Qt.MatchExactly
)
for item in updatedItems:
item.setText(0, itemNewName)
def objectAssignmentRightTreeWidgetItemSelectionChanged(self):
currItem = self.form.objectAssignmentRightTreeWidget.currentItem()
currItemLabel = None
#check if there is some current item due this function is trigered also during deleting all items in right assignment widget and then currItem is None
if currItem:
currItemLabel = currItem.text(0)
if (currItemLabel):
self.cadHelpers.clearSelection()
self.cadHelpers.selectObjectByLabel(currItemLabel)
def objectAssignmentLeftTreeWidgetItemSelectionChanged(self):
currItem = self.form.objectAssignmentLeftTreeWidget.currentItem()
currItemLabel = None
#check if there is some current item due this function is trigered also during deleting all items in right assignment widget and then currItem is None
if currItem:
currItemLabel = currItem.text(0)
if (currItemLabel):
self.cadHelpers.clearSelection()
self.cadHelpers.selectObjectByLabel(currItemLabel)
def objectAssignmentRightTreeWidgetContextClicked(self, event):
self.objAssignCtxMenu = QtWidgets.QMenu(self.form.objectAssignmentRightTreeWidget)
action_expand = self.objAssignCtxMenu.addAction("Expand all")
actioN_collapse = self.objAssignCtxMenu.addAction("Collapse all")
menu_action = self.objAssignCtxMenu.exec_(self.form.objectAssignmentRightTreeWidget.mapToGlobal(event))
if menu_action is not None:
if menu_action == action_expand:
self.form.objectAssignmentRightTreeWidget.expandAll()
if menu_action == actioN_collapse:
self.form.objectAssignmentRightTreeWidget.collapseAll()
#
# Handler for DOUBLE CLICK on grid item in FreeCAD objects list
#
def objectAssignmentLeftTreeWidgetItemDoubleClicked(self):
self.onMoveRight()
#
# Handler for DOUBLE CLICK on grid item in object assignment list
#
def objectAssignmentRightTreeWidgetItemDoubleClicked(self):
currItem = self.form.objectAssignmentRightTreeWidget.currentItem()
self.objectDrawGrid(currItem)
#
# Draw auxiliary grid in FreeCAD 3D view
#
def objectDrawGrid(self, currItem):
#
# Drawing auxiliary object grid for meshing.
#
# example how to draw line for grid: self.cadHelpers.drawDraftLine("gridXY", [-78.0, -138.0, 0.0], [5.0, -101.0, 0.0])
currSetting = currItem.data(0, QtCore.Qt.UserRole)
genScript = ""
# must be selected FreeCAD object which is child of grid item which gridlines will be draw
gridObj = self.cadHelpers.getObjectsByLabel(currItem.text(0))
if ("FreeCADSettingItem" in currSetting.type):
if ("GridSettingsItem" in currItem.parent().data(0, QtCore.Qt.UserRole).__class__.__name__):
currSetting = currItem.parent().data(0, QtCore.Qt.UserRole)
else:
self.guiHelpers.displayMessage('Cannot draw grid for non-grid item object.')
return
else:
self.guiHelpers.displayMessage('Cannot draw grid for object group.')
return
bbCoords = gridObj[0].Shape.BoundBox
print("Start drawing aux grid for: " + currSetting.name)
print("Enabled coords: " + str(currSetting.xenabled) + " " + str(currSetting.yenabled) + " " + str(currSetting.zenabled))
#getting model boundaries to draw gridlines properly
modelMinX, modelMinY, modelMinZ, modelMaxX, modelMaxY, modelMaxZ = self.cadHelpers.getModelBoundaryBox(self.form.objectAssignmentRightTreeWidget)
#don't know why I put here this axis list code snippet probably to include case if there are some auxiliary axis but now seems useless
#THERE IS QUESTION IN WHICH PLANE GRID SHOULD BE DRAWN IF in XY, XZ or YZ
currGridAxis = self.form.auxGridAxis.currentText().lower()
print("Aux grid axis: " + currGridAxis)
refUnit = currSetting.getSettingsUnitAsNumber()
#refUnit = 1
print("Current object grid units set as number to: refUnit: " + str(refUnit))
"""
axisList = collections.deque(['x', 'y', 'z'])
while axisList[0] != currGridAxis:
axisList.rotate()
"""
if (currSetting.coordsType == 'cylindrical' and currGridAxis == "z"):
if (currSetting.getType() == 'Fixed Distance'):
#need to be done for this case
pass
elif (currSetting.getType() == 'Fixed Count'):
#collecting Z coordinates where grid will be drawn, gird will be drawn in XY plane
zAuxGridCoordList = []
if (currSetting.zenabled):
if int(currSetting.getXYZ(refUnit)['z']) != 0:
if int(currSetting.getXYZ(refUnit)['z']) == 1:
zlines = np.array([(bbCoords.ZMin + bbCoords.ZMax)/2])
else:
zlines = np.linspace(bbCoords.ZMin, bbCoords.ZMax, int(currSetting.getXYZ(refUnit)['z']))
#collecting Z coordinates where grid layers will be drawn
for zGridLine in zlines:
zAuxGridCoordList.append(zGridLine)
print("zlines")
print(zAuxGridCoordList)
if len(zAuxGridCoordList) == 0:
zAuxGridCoordList.append(bbCoords.ZMax)
for zAuxGridCoord in zAuxGridCoordList:
bbPointsVectors = [self.cadHelpers.Vector(bbCoords.YMin, bbCoords.XMin, 0), self.cadHelpers.Vector(bbCoords.YMin, bbCoords.XMax, 0), self.cadHelpers.Vector(bbCoords.YMax, bbCoords.XMin, 0), self.cadHelpers.Vector(bbCoords.YMax, bbCoords.XMax, 0)]
angle1 = math.atan2(bbCoords.YMin, bbCoords.XMin) + 2*math.pi % (2*math.pi)
angle2 = math.atan2(bbCoords.YMin, bbCoords.XMax) + 2*math.pi % (2*math.pi)
angle3 = math.atan2(bbCoords.YMax, bbCoords.XMin) + 2*math.pi % (2*math.pi)
angle4 = math.atan2(bbCoords.YMax, bbCoords.XMax) + 2*math.pi % (2*math.pi)
minAngle = min([angle1, angle2, angle3, angle4])
maxAngle = max([angle1, angle2, angle3, angle4])
radius = max([math.sqrt(modelMinX**2 + modelMinY**2), math.sqrt(modelMaxX**2 + modelMaxY**2)])
print("Calculate ylines for cylindrical coords.")
print("minAngle: " + str(minAngle))
print("maxAngle: " + str(maxAngle))
print("radius: " + str(radius))
#DRAW X LINES auxiliary grid in 3D view
if (currSetting.xenabled):
a = np.array([angle1, angle2, angle3, angle4])
indicesMin = a.argmin()
indicesMax = a.argmax()
closestLineToCenter = bbPointsVectors[indicesMin] - bbPointsVectors[indicesMax]
#minRadius = closestLineToCenter.distanceToPoint(self.cadHelpers.Vector(0,0,0))
minRadius = abs((bbPointsVectors[indicesMax].x - bbPointsVectors[indicesMin].x)*bbPointsVectors[indicesMin].y - (bbPointsVectors[indicesMax].y - bbPointsVectors[indicesMin].y)*bbPointsVectors[indicesMin].x)/closestLineToCenter.Length
maxRadius = max([math.sqrt(bbCoords.XMin**2 + bbCoords.YMin**2), math.sqrt(bbCoords.XMax**2 + bbCoords.YMax**2)])
if float(currSetting.getXYZ(refUnit)['x']) == 1:
xlines = np.array([(minRadius + maxRadius)/2])
else:
xlines = np.linspace(minRadius, maxRadius, int(currSetting.getXYZ(refUnit)['x']))
for xGridLine in xlines:
self.cadHelpers.drawDraftCircle("auxGridLine", self.cadHelpers.Vector(0,0,zAuxGridCoord), xGridLine)
#DRAW Y LINES auxiliary grid in 3D view
if (currSetting.yenabled):
if float(currSetting.getXYZ(refUnit)['y']) == 1:
ylines = np.array([(minAngle, maxAngle)/2])
else:
ylines = np.linspace(minAngle, maxAngle, int(currSetting.getXYZ(refUnit)['y']))
print(ylines)
for yGridLine in ylines:
self.cadHelpers.drawDraftLine("auxGridLine", [0, 0, zAuxGridCoord], [math.cos(yGridLine)*radius, math.sin(yGridLine)*radius, zAuxGridCoord])
elif (currSetting.coordsType == 'rectangular' and currGridAxis == "z"):
#######################################################################################################################################################################
# Z grid axis
#######################################################################################################################################################################
print("Drawing GRID in Z axis.")
if (currSetting.getType() == 'Fixed Distance'):
#here adding Z coordinates for which grid will be drawn so grid will be drawn in XY plane, so here are collected just Z coords for which it will be drawn
zAuxGridCoordList = []
if (currSetting.zenabled):
if float(currSetting.getXYZ(refUnit)['z']) != 0:
zlines = np.arange(bbCoords.ZMin, bbCoords.ZMax, currSetting.getXYZ(refUnit)['z']) #split Z interval and generate Z layers
for zGridLine in zlines:
zAuxGridCoordList.append(zGridLine)
if len(zAuxGridCoordList) == 0:
zAuxGridCoordList.append(bbCoords.ZMax)
for zAuxGridCoord in zAuxGridCoordList:
#DRAW X LINES auxiliary grid in 3D view
if (currSetting.xenabled):
if float(currSetting.getXYZ(refUnit)['x']) != 0:
xlines = np.arange(bbCoords.XMin, bbCoords.XMax, currSetting.getXYZ(refUnit)['x'])
for xGridLine in xlines:
#self.cadHelpers.drawDraftLine("auxGridLine", [xGridLine, bbCoords.YMin, zAuxGridCoord], [xGridLine, bbCoords.YMax, zAuxGridCoord])
self.cadHelpers.drawDraftLine("auxGridLine", [xGridLine, modelMinY, zAuxGridCoord], [xGridLine, modelMaxY, zAuxGridCoord])
#DRAW Y LINES auxiliary grid in 3D view
if (currSetting.yenabled):
if float(currSetting.getXYZ(refUnit)['y']) != 0:
ylines = np.arange(bbCoords.YMin, bbCoords.YMax, currSetting.getXYZ(refUnit)['y'])
for yGridLine in ylines:
#self.cadHelpers.drawDraftLine("auxGridLine", [bbCoords.XMin, yGridLine, zAuxGridCoord], [bbCoords.XMax, yGridLine, zAuxGridCoord])
self.cadHelpers.drawDraftLine("auxGridLine", [modelMinX, yGridLine, zAuxGridCoord], [modelMaxX, yGridLine, zAuxGridCoord])
elif (currSetting.getType() == 'Fixed Count'):
#collecting Z coordinates where grid will be drawn, grid will be drawn in XY plane
zAuxGridCoordList = []
if (currSetting.zenabled):
if float(currSetting.getXYZ(refUnit)['z']) != 0:
if float(currSetting.getXYZ(refUnit)['z']) == 1:
zlines = np.arange(bbCoords.ZMin, bbCoords.ZMax, int(currSetting.getXYZ(refUnit)['z']))
else:
zlines = np.array([(bbCoords.ZMin + bbCoords.ZMax)/2])
#collecting Z coordinates where grid layers will be drawn
for zGridLine in zlines:
zAuxGridCoordList.append(zGridLine)
if len(zAuxGridCoordList) == 0:
zAuxGridCoordList.append(bbCoords.ZMax)
for zAuxGridCoord in zAuxGridCoordList:
#DRAW X LINES auxiliary grid in 3D view
if (currSetting.xenabled):
if float(currSetting.getXYZ(refUnit)['x']) == 1:
xlines = np.array([(bbCoords.XMin + bbCoords.XMax)/2])
else:
xlines = np.linspace(bbCoords.XMin, bbCoords.XMax, int(currSetting.getXYZ(refUnit)['x']))
for xGridLine in xlines:
#self.cadHelpers.drawDraftLine("auxGridLine", [xGridLine, bbCoords.YMin, zAuxGridCoord], [xGridLine, bbCoords.YMax, zAuxGridCoord])
self.cadHelpers.drawDraftLine("auxGridLine", [xGridLine, modelMinY, zAuxGridCoord], [xGridLine, modelMaxY, zAuxGridCoord])
#DRAW Y LINES auxiliary grid in 3D view
if (currSetting.yenabled):
if float(currSetting.getXYZ(refUnit)['y']) == 1:
ylines = np.array([(bbCoords.YMin + bbCoords.YMax)/2])
else:
ylines = np.linspace(bbCoords.YMin, bbCoords.YMax, int(currSetting.getXYZ(refUnit)['y']))
for yGridLine in ylines:
#self.cadHelpers.drawDraftLine("auxGridLine", [bbCoords.XMin, yGridLine, zAuxGridCoord], [bbCoords.XMax, yGridLine, zAuxGridCoord])
self.cadHelpers.drawDraftLine("auxGridLine", [modelMinX, yGridLine, zAuxGridCoord], [modelMaxX, yGridLine, zAuxGridCoord])
elif (currSetting.getType() == 'User Defined'):
#UNIT FOR MESH
genScript += "meshUnit = " + currSetting.getUnitAsScriptLine() + "; % all length in mm\n"
genScript += "mesh = " + currSetting.getXYZ(refUnit) + ";\n"
elif (currSetting.coordsType == 'rectangular' and currGridAxis == "x"):
#######################################################################################################################################################################
# X grid axis - STILL EXPERIMENTAL require REPAIR
#######################################################################################################################################################################
print("Drawing GRID in X axis.")
if (currSetting.getType() == 'Fixed Distance'):
#here adding Z coordinates for which grid will be drawn so grid will be drawn in XY plane, so here are collected just Z coords for which it will be drawn
xAuxGridCoordList = []
if (currSetting.xenabled):
if float(currSetting.getXYZ(refUnit)['x']) != 0:
xlines = np.arange(bbCoords.XMin, bbCoords.XMax, currSetting.getXYZ(refUnit)['x']) #split Z interval and generate Z layers
for xGridLine in xlines:
xAuxGridCoordList.append(xGridLine)
if len(xAuxGridCoordList) == 0:
xAuxGridCoordList.append(bbCoords.XMax)
for xAuxGridCoord in xAuxGridCoordList: