-
Notifications
You must be signed in to change notification settings - Fork 76
/
AnimationLib.py
870 lines (711 loc) · 31.7 KB
/
AnimationLib.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
#!/usr/bin/env python3
# coding: utf-8
#
# LGPL
# Copyright HUBERT Zoltán
#
# AnimationLib.py
import os, numpy
from PySide import QtGui, QtCore
from enum import Enum
import FreeCADGui as Gui
import FreeCAD as App
import Asm4_libs as Asm4
# from AnimationProvider import animationProvider
"""
+-----------------------------------------------+
| animationProvider class |
+-----------------------------------------------+
"""
class animationProvider:
#
# Setup the scene for the next frame of the animation.
# Set resetAnimation True for the first frame
# Signals that the last frame has been reached by returning True
#
def nextFrame(self, resetAnimation) -> bool:
raise NotImplementedError("animationProvider.nextFrame not implemented.")
#
# Optionally flag that pendulum (forth and back animation) is wanted.
# Prevents the need to capture identical frames on the "returning path"
# of the animation.
#
def pendulumWanted(self) -> bool:
return False
class Error(Exception):
"""
Base class for exceptions thrown when issues with
animating the scene from an animationProvider occur.
"""
def __init__(self, shortMsg: str, detailMsg: str):
self.shortMsg = shortMsg
self.detailMsg = detailMsg
"""
+-----------------------------------------------+
| main class |
+-----------------------------------------------+
"""
class animateVariable(animationProvider):
"""
+-----------------------------------------------+
| State and Transition Enums |
+-----------------------------------------------+
"""
class AnimationState(Enum):
STOPPED = 0
RUNNING = 1
class AnimationRequest(Enum):
NONE = 0
START = 1
STOP = 2
"""
+-----------------------------------------------+
| Exception Definitions |
+-----------------------------------------------+
"""
class variableInvalidError(animationProvider.Error):
"""
Exception to be raised when animation fails because
the selected variable is not valid/does not exist.
"""
def __init__(self, varName):
shortMsg = 'Variable name invalid'
detailMsg = 'The selected variable name "' + varName + '" is not valid. ' + \
'Please select an existing variable.'
super().__init__(shortMsg, detailMsg)
self.varName = varName
"""
+-----------------------------------------------+
| Initialization and Registration |
+-----------------------------------------------+
"""
def __init__(self):
super(animateVariable,self).__init__()
self.UI = QtGui.QDialog()
self.drawUI()
self.MDIArea = Gui.getMainWindow().findChild(QtGui.QMdiArea)
# Initialize States and timing logic.
self.RunState = self.AnimationState.STOPPED
self.reverseAnimation = False # True flags when the animation is "in reverse" for the pendulum mode.
self.ForceGUIUpdate = False # True Forces GUI to update on every step of the animation.
self.timer = QtCore.QTimer()
self.timer.setInterval(0)
self.timer.timeout.connect(self.onTimerTick)
self.ActiveDocument = None
self.AnimatedDocument = None
self.Variables = None
self.knownDocumentList = []
self.knownVariableList = []
self.plotter = None
self.exporter = None
def GetResources(self):
return {"MenuText": "Animate Assembly",
"ToolTip": "Animate Assembly",
"Pixmap" : os.path.join( Asm4.iconPath , 'Asm4_GearsAnimate.svg')
}
def IsActive(self):
# is there an active document ?
if App.ActiveDocument :
variables = App.ActiveDocument.getObject('Variables')
if variables and variables.Type == "App::PropertyContainer":
return True
return False
"""
+-----------------------------------------------+
| the real stuff |
+-----------------------------------------------+
"""
def Activated(self):
# if the previously animated documents has been closed
self.ActiveDocument = App.ActiveDocument
if self.AnimatedDocument not in App.listDocuments().values():
self.AnimatedDocument = self.ActiveDocument
self.updateDocList()
# grab the Variables container (just do it always, this prevents problems with newly opened docs)
#self.Variables = self.AnimatedDocument.getObject('Variables') if self.AnimatedDocument in App.listDocuments().values() else None
self.Variables = self.AnimatedDocument.getObject('Variables')
# the root assembly in the current document is wherever the Variables container is
# self.rootAssembly = Asm4.getAssembly()
self.rootAssembly = self.Variables.getParentGeoFeatureGroup()
self.updateVarList()
# in case the dialog is newly opened, register for changes of the selected document
if not self.UI.isVisible():
self.MDIArea.subWindowActivated.connect(self.onDocChanged)
self.UI.show()
"""
+------------------------------------------------+
| fill default values when selecting a document |
+------------------------------------------------+
"""
def updateDocList(self):
docDocs = ['- Select Document -']
# Collect all documents currently available
for doc in App.listDocuments():
docDocs.append(doc)
# only update the gui-element if documents actually changed
if self.knownDocumentList != docDocs:
self.docList.clear()
self.docList.addItems(docDocs)
self.knownDocumentList = docDocs
# set current active documents per default
#if self.AnimatedDocument is None:
activeDoc = App.ActiveDocument
if activeDoc in App.listDocuments().values():
docIndex = list(App.listDocuments().values()).index(activeDoc)
self.docList.setCurrentIndex(docIndex + 1)
def onSelectDoc(self):
self.update(self.AnimationRequest.STOP)
# the currently selected document
selectedDoc = self.docList.currentText()
# if it's indeed a document (one never knows)
documents = App.listDocuments()
if len(selectedDoc) > 0 and selectedDoc in documents:
# update vars
self.AnimatedDocument = documents[selectedDoc]
self.Variables = self.AnimatedDocument.getObject('Variables')
self.updateVarList()
else:
self.AnimatedDocument = None
self.Variables = None
self.updateVarList()
"""
+------------------------------------------------+
| fill default values when selecting a variable |
+------------------------------------------------+
"""
def updateVarList(self):
docVars = ['- Select Variable (only float) -']
# Collect all variables currently available in the doc
if self.Variables:
for prop in self.Variables.PropertiesList:
if self.Variables.getGroupOfProperty(prop) == 'Variables':
if self.Variables.getTypeIdOfProperty(prop) == 'App::PropertyFloat':
docVars.append(prop)
# only update the gui-element if variables actually changed
if self.knownVariableList != docVars:
self.varList.clear()
self.varList.addItems(docVars)
self.knownVariableList = docVars
animationHints.cleanUp(self.Variables)
# prevent active gui controls when no valid variable is selected
self.onSelectVar()
def onSelectVar(self):
self.update(self.AnimationRequest.STOP)
# the currently selected variable
selectedVar = self.varList.currentText()
# if it's indeed a property in the Variables object (one never knows)
if self.isKnownVariable(selectedVar):
# grab animationsHints related to the variable and init accordingly
aniHints = animationHints.get(self.Variables, selectedVar)
self.beginValue.setValue(aniHints[animationHints.Key.RangeBegin])
self.endValue.setValue(aniHints[animationHints.Key.RangeEnd])
self.stepValue.setValue(aniHints[animationHints.Key.StepSize])
self.sleepValue.setValue(aniHints[animationHints.Key.SleepTime])
self.Loop.setChecked(aniHints[animationHints.Key.Loop])
self.Pendulum.setChecked(aniHints[animationHints.Key.Pendulum])
self.enableDependentGuiElements(True)
else:
self.enableDependentGuiElements(False)
def isKnownVariable(self, varName):
"""
Returns True if a variable with name varName exists
"""
return len(varName) > 0 and self.Variables and varName in self.Variables.PropertiesList
"""
+-----------------------------------------------+
| Animation Tick Functions |
+-----------------------------------------------+
"""
def initAnimation(self):
# Set GUI-state, initial value and start the timer
varName = self.varList.currentText()
if not self.isKnownVariable(varName):
self.updateVarList()
raise animateVariable.variableInvalidError(varName)
self.RunButton.setEnabled(False)
self.StopButton.setEnabled(True)
self.setVarValue(self.varList.currentText(), self.beginValue.value())
self.reverseAnimation = False
def nextStep(self, reverse):
# Calculate the next variable increment/decrement
begin = self.beginValue.value()
end = self.endValue.value()
step = abs(self.stepValue.value())
varName = self.varList.currentText()
if not self.isKnownVariable(varName):
raise animateVariable.variableInvalidError(varName)
varValue = self.Variables.getPropertyByName(varName)
if reverse:
begin, end = end, begin
if begin < end:
varValue += step
elif begin > end:
varValue -= step
# Assert varValue is in currently set range (range can now update with the animation running)
varValue = min(varValue, max(begin, end))
varValue = max(varValue, min(begin, end))
# Update document variable and slider
self.setVarValue(varName, varValue)
self.slider.setValue(varValue)
# Flag when the end of one sweep is reached
return (varValue == begin) or (varValue == end)
def update(self, req):
# Flag out for end of cycle
endOfCycle = False
# STOPPED STATE; NO ANIMATION RUNNING
if self.RunState == self.AnimationState.STOPPED:
if req == self.AnimationRequest.START:
self.initAnimation()
self.RunState = self.AnimationState.RUNNING
# RUNNING STATE
elif self.RunState == self.AnimationState.RUNNING:
stop = (req == self.AnimationRequest.STOP)
if not stop:
endOfCycle = self.nextStep(self.reverseAnimation)
stop |= endOfCycle and not (self.Pendulum.isChecked() or self.Loop.isChecked())
if stop:
self.RunButton.setEnabled(True)
self.StopButton.setEnabled(False)
self.RunState = self.AnimationState.STOPPED
elif endOfCycle:
if self.Loop.isChecked():
self.initAnimation()
elif self.Pendulum.isChecked():
self.reverseAnimation = not self.reverseAnimation
# SANITY CHECK
else:
print("Unknown State/Transition")
return endOfCycle
def onTimerTick(self):
try:
self.update(self.AnimationRequest.NONE)
except animationProvider.Error as e:
self.timer.stop()
self.RunState == self.AnimationState.STOPPED
QtGui.QMessageBox.warning(self.UI, e.shortMsg, e.detailMsg)
else:
if self.ForceGUIUpdate:
Gui.updateGui()
if self.RunState == self.AnimationState.STOPPED:
self.timer.stop()
def setVarValue(self,name,value):
setattr( self.Variables, name, value )
if App.ActiveDocument == self.AnimatedDocument:
self.rootAssembly.recompute(True)
else:
App.ActiveDocument.recompute(None, True, True)
self.variableValue.setText('{:.2f}'.format(value))
"""
+-----------------------------------------------+
| Loop or Pendulum Selector |
+-----------------------------------------------+
"""
def onLoop(self):
aniHints = animationHints.get(self.Variables, self.varList.currentText())
aniHints[animationHints.Key.Loop] = self.Loop.isChecked()
if self.Pendulum.isChecked() and self.Loop.isChecked():
self.Pendulum.setChecked(False)
def onPendulum(self):
aniHints = animationHints.get(self.Variables, self.varList.currentText())
aniHints[animationHints.Key.Pendulum] = self.Pendulum.isChecked()
if self.Loop.isChecked() and self.Pendulum.isChecked():
self.Loop.setChecked(False)
return
def onForceRender(self):
self.ForceGUIUpdate = self.ForceRender.isChecked()
"""
+-----------------------------------------------+
| Slider |
+-----------------------------------------------+
"""
def sliderMoved(self):
varName = self.varList.currentText()
varValue = self.slider.value()
self.setVarValue(varName, varValue)
return
def updateSlider(self):
# Get range-values from spinboxes
beginVal = self.beginValue.value()
endVal = self.endValue.value()
# Update the slider's ranges
# The slider will automatically settle to the nearest value possible based on the new begin/end/stepsize.
self.slider.setRange(beginVal, endVal, self.stepValue.value())
# Update the labels with the actual range of the slider
self.sliderLeftValue.setText(str(self.slider.leftValue()))
self.sliderRightValue.setText(str(self.slider.rightValue()))
# Check the current variable state vs. the slider. Update if needed
varName = self.varList.currentText()
curVal = self.Variables.getPropertyByName(varName)
sliderVal = self.slider.value()
if curVal != sliderVal:
self.setVarValue(varName, sliderVal)
# Check whether the end of the range can actually be reached with the current stepping.
# Flag label if needed.
rangeShort = (self.slider.rightValue() < endVal) if (beginVal < endVal) else (self.slider.rightValue() > endVal)
if rangeShort:
self.sliderRightValue.setStyleSheet("background-color: tomato")
else:
self.sliderRightValue.setStyleSheet("background-color: none")
def onBeginValChanged(self):
varName = self.varList.currentText()
val = self.beginValue.value()
animationHints.get(self.Variables, varName)['rangeBegin'] = val
self.updateSlider()
def onEndValChanged(self):
varName = self.varList.currentText()
val = self.endValue.value()
animationHints.get(self.Variables, varName)['rangeEnd'] = val
self.updateSlider()
def onStepValChanged(self):
varName = self.varList.currentText()
val = self.stepValue.value()
animationHints.get(self.Variables, varName)['stepSize'] = val
self.updateSlider()
def onSleepValChanged(self):
varName = self.varList.currentText()
val = self.sleepValue.value()
animationHints.get(self.Variables, varName)['sleepValue'] = val
self.timer.setInterval(val * 1000)
"""
+-----------------------------------------------+
| Star/Stop/Close/Export |
+-----------------------------------------------+
"""
def onRun(self):
try:
self.update(self.AnimationRequest.START)
except animationProvider.Error as e:
QtGui.QMessageBox.warning(self.UI, e.shortMsg, e.detailMsg)
else:
self.timer.start()
def onStop(self):
self.update(self.AnimationRequest.STOP)
self.timer.stop()
def onClose(self):
self.onStop()
animationHints.cleanUp(self.Variables)
self.MDIArea.subWindowActivated[QtGui.QMdiSubWindow].disconnect(self.onDocChanged)
self.UI.close()
def onPlot(self):
self.onStop()
# check whether a plotter window has been created before
if not self.plotter:
# Only import the export-lib if requested. Helps to keep WB loading times in check.
import AnimationPlotLib
self.plotter = AnimationPlotLib.animationPlotter(self)
self.plotter.openUI()
def onSave(self):
self.onStop()
# check for OpenCV module installed (cv2)
try:
import cv2
except:
Asm4.warningBox('The Python module \"OpenCV\" (cv2) is not installed')
return
if not self.exporter:
# Only import the export-lib if requested. Helps to keep WB loading times in check.
import AnimationExportLib
self.exporter = AnimationExportLib.animationExporter(self)
self.exporter.openUI()
def onDocChanged(self):
if App.ActiveDocument != self.ActiveDocument:
# Check if AnimatedDocument still exists
if not self.AnimatedDocument in App.listDocuments().values():
self.AnimatedDocument = None
self.onStop()
#self.Activated()
#
# animationProvider Interface
#
def nextFrame(self, resetAnimation) -> bool:
req = animateVariable.AnimationRequest.START if resetAnimation else animateVariable.AnimationRequest.NONE
endOfCycle = self.update(req)
if endOfCycle:
self.update(animateVariable.AnimationRequest.STOP)
animationEnded = self.RunState == animateVariable.AnimationState.STOPPED
return animationEnded
def pendulumWanted(self) -> bool:
return self.Pendulum.isChecked()
"""
+-----------------------------------------------+
| defines the UI, only static elements |
+-----------------------------------------------+
"""
def drawUI(self):
# Our main window will be a QDialog
# make this dialog stay above the others, always visible
self.UI.setWindowFlags( QtCore.Qt.WindowStaysOnTopHint )
self.UI.setWindowTitle('Animate Assembly')
self.UI.setWindowIcon( QtGui.QIcon( os.path.join( Asm4.iconPath , 'FreeCad.svg' ) ) )
self.UI.setMinimumWidth(470)
self.UI.setModal(False)
# set main window widgets
self.mainLayout = QtGui.QVBoxLayout(self.UI)
# Define the fields for the form ( label + widget )
self.formLayout = QtGui.QFormLayout()
# select Document
self.docList = updatingComboBox()
self.formLayout.addRow(QtGui.QLabel('Document'), self.docList)
# select Variable
self.varList = updatingComboBox()
self.formLayout.addRow(QtGui.QLabel('Variable'),self.varList)
# Range Minimum
self.beginValue = QtGui.QDoubleSpinBox()
self.beginValue.setRange(numpy.finfo(float).min, numpy.finfo(float).max)
self.beginValue.setKeyboardTracking(False)
self.formLayout.addRow(QtGui.QLabel('Range Begin'), self.beginValue)
# Maximum
self.endValue = QtGui.QDoubleSpinBox()
self.endValue.setRange(numpy.finfo(float).min, numpy.finfo(float).max)
self.endValue.setKeyboardTracking(False)
self.formLayout.addRow(QtGui.QLabel('Range End'), self.endValue)
# Step
self.stepValue = QtGui.QDoubleSpinBox()
self.stepValue.setRange( 0.01, numpy.finfo(float).max )
self.stepValue.setValue( 1.0 )
self.stepValue.setKeyboardTracking(False)
self.formLayout.addRow(QtGui.QLabel('Step Size'), self.stepValue)
# Sleep
self.sleepValue = QtGui.QDoubleSpinBox()
self.sleepValue.setRange( 0.0, 10.0 )
self.sleepValue.setValue( 0.0 )
self.sleepValue.setSingleStep(0.01)
self.sleepValue.setKeyboardTracking(False)
self.formLayout.addRow(QtGui.QLabel('Sleep (s)'),self.sleepValue)
# apply the layout
self.mainLayout.addLayout(self.formLayout)
self.mainLayout.addWidget(QtGui.QLabel())
# Current Variable Value
self.curVarLayout = QtGui.QHBoxLayout()
self.variableValue = QtGui.QLabel('Variable')
self.curVarLayout.addWidget(QtGui.QLabel('Current Value:'))
self.curVarLayout.addStretch()
self.curVarLayout.addWidget(self.variableValue)
self.mainLayout.addLayout(self.curVarLayout)
# slider
self.sliderLayout = QtGui.QHBoxLayout()
self.slider = animationSlider()
self.slider.setOrientation(QtCore.Qt.Orientation.Horizontal)
self.slider.setRange(0, 10)
self.slider.setTickInterval(0)
self.sliderLeftValue = QtGui.QLabel('Begin')
self.sliderRightValue = QtGui.QLabel('End')
tt = "The last reachable variable value with the given stepping. "
tt += "Flagged red in case this is not equal to the intended value. "
tt += "The last step of the animation will be reduced to stay inside the configured limits."
self.sliderRightValue.setToolTip(tt)
self.sliderLayout.addWidget(self.sliderLeftValue)
self.sliderLayout.addWidget(self.slider)
self.sliderLayout.addWidget(self.sliderRightValue)
self.mainLayout.addLayout(self.sliderLayout)
# Options
self.optionsGroup = QtGui.QGroupBox()
self.optionsGroup.setToolTip("Options Box")
self.optionsGroup.setTitle("Options")
self.optionsGroup.setObjectName("optionsGroup")
self.optionsLayout = QtGui.QVBoxLayout(self.optionsGroup)
# ForceUpdate, loop and pendulum tick-boxes
self.ForceRender = QtGui.QCheckBox()
self.ForceRender.setLayoutDirection(QtCore.Qt.LeftToRight)
self.ForceRender.setToolTip("Force GUI to update on every step.")
self.ForceRender.setText("Force-render every step")
self.ForceRender.setChecked(False)
self.optionsLayout.addWidget(self.ForceRender)
self.Loop = QtGui.QCheckBox()
self.Loop.setLayoutDirection(QtCore.Qt.LeftToRight)
self.Loop.setToolTip("Infinite Loop")
self.Loop.setText("Loop")
self.Loop.setChecked(False)
self.optionsLayout.addWidget(self.Loop)
self.Pendulum = QtGui.QCheckBox()
self.Pendulum.setLayoutDirection(QtCore.Qt.LeftToRight)
self.Pendulum.setToolTip("Back-and-forth pendulum")
self.Pendulum.setText("Pendulum")
self.Pendulum.setChecked(False)
self.optionsLayout.addWidget(self.Pendulum)
self.mainLayout.addWidget(self.optionsGroup)
#self.mainLayout.addWidget(self.Loop)
#self.cbLayout = QtGui.QFormLayout()
#self.cbLayout.addRow(self.ForceRender, self.Pendulum)
#self.mainLayout.addLayout(self.cbLayout)
#self.mainLayout.addWidget(QtGui.QLabel())
#self.mainLayout.addStretch()
# the button row definition
self.buttonLayout = QtGui.QHBoxLayout()
# Close button
self.CloseButton = QtGui.QPushButton('Close')
self.CloseButton.setToolTip("Exit")
self.buttonLayout.addWidget(self.CloseButton)
self.buttonLayout.addStretch()
# Plot button
self.PlotButton = QtGui.QPushButton('Plot')
self.PlotButton.setToolTip("Plot trajectories in this sequence")
self.buttonLayout.addWidget(self.PlotButton)
self.buttonLayout.addStretch()
# Export button
self.SaveButton = QtGui.QPushButton('Save')
self.SaveButton.setToolTip("Save this sequence as video")
self.buttonLayout.addWidget(self.SaveButton)
self.buttonLayout.addStretch()
# Stop button
self.StopButton = QtGui.QPushButton('Stop')
self.buttonLayout.addWidget(self.StopButton)
self.buttonLayout.addStretch()
self.StopButton.setEnabled(False)
# Run button
self.RunButton = QtGui.QPushButton('Run')
tt = "Run this sequence in the 3D window"
tt+= "\n\nIf the model is large and complex,"
tt+= "\nit is advisable to try with 10 frames"
self.RunButton.setToolTip(tt)
self.buttonLayout.addWidget(self.RunButton)
# Add an invisibly dummy button to circumvent QDialogs default-button behavior.
# We need the enter key to trigger spinbox-commits only, without also triggering button actions.
self.DummyButton = QtGui.QPushButton('Dummy')
self.DummyButton.setDefault(True)
self.DummyButton.setVisible(False)
self.buttonLayout.addWidget(self.DummyButton)
# add buttons to layout
self.mainLayout.addLayout(self.buttonLayout)
# finally, apply the layout to the main window
self.UI.setLayout(self.mainLayout)
# Actions
self.docList.currentIndexChanged.connect( self.onSelectDoc)
self.docList.popupList.connect( self.updateDocList)
self.varList.currentIndexChanged.connect( self.onSelectVar )
self.varList.popupList.connect( self.updateVarList)
self.slider.sliderMoved.connect( self.sliderMoved)
self.slider.valueChanged.connect( self.sliderMoved)
self.beginValue.valueChanged.connect( self.onBeginValChanged)
self.endValue.valueChanged.connect( self.onEndValChanged)
self.stepValue.valueChanged.connect( self.onStepValChanged)
self.sleepValue.valueChanged.connect( self.onSleepValChanged)
self.Loop.toggled.connect( self.onLoop )
self.Pendulum.toggled.connect( self.onPendulum )
self.ForceRender.toggled.connect( self.onForceRender)
self.CloseButton.clicked.connect( self.onClose )
self.PlotButton.clicked.connect( self.onPlot)
self.SaveButton.clicked.connect( self.onSave)
self.StopButton.clicked.connect( self.onStop)
self.RunButton.clicked.connect( self.onRun )
def enableDependentGuiElements(self, state):
self.beginValue.setEnabled(state)
self.endValue.setEnabled(state)
self.stepValue.setEnabled(state)
self.sleepValue.setEnabled(state)
self.slider.setEnabled(state)
self.RunButton.setEnabled(state)
self.Loop.setEnabled(state)
self.Pendulum.setEnabled(state)
self.SaveButton.setEnabled(state)
self.PlotButton.setEnabled(state)
"""
+-----------------------------------------------+
| Custom Slider handling inverse ranges |
| and steps != 1. |
+-----------------------------------------------+
"""
class animationSlider(QtGui.QSlider):
def __init__(self, parent=None):
self.leftVal = 0.0
self.rightVal = 1.0
self.stepSize = 1.0
super().__init__(parent)
# All ranges will be mapped to positive whole numbers.
# By definition, the "left hand side value" (begin range) will be reachable.
# The last reachable "right hand side value" depends on the step-size
# The functions below translate accordingly
def setRange(self, leftVal, rightVal, stepSize=1.0):
val = self.value()
self.leftVal = leftVal
self.rightVal = rightVal
self.stepSize = abs(stepSize)
if leftVal > rightVal:
self.stepSize *= -1.0
super().setRange(0, (rightVal - leftVal) / self.stepSize)
# ensure that the exposed slider value stays stable and gets capped if needed
sig = self.stepSize/abs(self.stepSize)
val = max(val, leftVal * sig)
val = min(val, rightVal * sig)
self.setValue(val)
def __calculateInternalValue__(self, value):
return value * self.stepSize + self.leftVal
def value(self):
return self.__calculateInternalValue__(super().value())
def leftValue(self):
return self.__calculateInternalValue__(super().minimum())
def rightValue(self):
return self.__calculateInternalValue__(super().maximum())
def setValue(self, value):
super().setValue((value - self.leftVal) / self.stepSize)
"""
+-----------------------------------------------+
| Custom Combobox that emits a Signal when |
| the user clicks for the popup menu. |
| Needed to update the list of variables |
| on the fly. |
+-----------------------------------------------+
"""
class updatingComboBox(QtGui.QComboBox):
popupList = QtCore.Signal()
def __init__(self, parent=None):
super().__init__(parent)
def showPopup(self):
self.popupList.emit()
super().showPopup()
"""
+-----------------------------------------------+
| Animation Hint Record Helper |
+-----------------------------------------------+
"""
class animationHints():
class Key:
RangeBegin = 'rangeBegin'
RangeEnd = 'rangeEnd'
StepSize = 'stepSize'
SleepTime = 'sleepTime'
Loop = 'loop'
Pendulum = 'pendulum'
@staticmethod
def get(variables, varName):
# Get the hints for the given variable.
# Ensure that hints with sensible values are created in case there is no entry yet
varValue = variables.getPropertyByName(varName)
defaultHints = {animationHints.Key.RangeBegin: varValue,
animationHints.Key.RangeEnd: varValue,
animationHints.Key.StepSize: 1.0,
animationHints.Key.SleepTime: 0.0,
animationHints.Key.Loop: False,
animationHints.Key.Pendulum: False}
hintList = animationHints.__getHintList__(variables)
return hintList.setdefault(varName, defaultHints)
@staticmethod
def __getHintList__(variables):
# Ensure that a hint-dictionary is available and return it
if "AnimationHintList" not in variables.PropertiesList:
variables.addProperty("App::PropertyPythonObject", "AnimationHintList", "AnimationHints", "The hintfield for the animation dialog").AnimationHintList = {}
variables.setPropertyStatus("AnimationHintList", "Hidden")
# see https://forum.freecad.org/viewtopic.php?p=745163#p700080
if variables.getPropertyByName("AnimationHintList") == None:
variables.AnimationHintList = {}
return variables.getPropertyByName("AnimationHintList")
@staticmethod
def cleanUp(variables):
if not variables:
return
# Walk through all variable-entries and collect the relevant hints for them
newHints = {}
hintList = animationHints.__getHintList__(variables)
for entry in variables.PropertiesList:
if variables.getGroupOfProperty(entry) == 'Variables':
hint = hintList.get(entry, None)
if hint:
newHints[entry] = hint
# Throw old list away and use the new (possibly reduced) one
setattr(variables, "AnimationHintList", newHints)
"""
+-----------------------------------------------+
| add the command to the workbench |
+-----------------------------------------------+
"""
Gui.addCommand( 'Asm4_Animate', animateVariable() )