implementing undo/redo with simple command


#1

yo,

i have this code that i need to create a curve with the api:

import maya.OpenMaya as om 

positions=[(1,2,3),(0,2,3),(2,3,4),(5,2,4)] 

curveFn = om.MFnNurbsCurve() 
arr = om.MPointArray() 

for pos in positions: 
    arr.append(*pos) 

obj = curveFn.createWithEditPoints( 
                                  arr, 
                                  3, 
                                  om.MFnNurbsCurve.kOpen, 
                                  False, 
                                  False, 
                                  True 
                          ) 

but i want to implement undo functionality. I have an example piece of template code that is setup for undo/redo but i just dont know how and where to add my curve creation code to this to make it undoable. the Dag and dg node stuff is mind blowing

here is the template code for undo/redo:

import sys
import maya.OpenMayaMPx as OpenMayaMPx

kPluginCmdName = 'myUndoableCommandName'

class MyUndoableCommand( OpenMayaMPx.MPxCommand ):
    
    def __init__(self):
        OpenMayaMPx.MPxCommand.__init__(self)
    
    
    def doIt(self, args):
        self.redoIt()
        
        
    def redoIt(self):
        pass
    
    
    def undoIt(self):
        pass
    
    
    def isUndoable(self):
        return True

if anyone could help me out id really appreciate it thanks!!,
Sam


#2

you need to make it is a plug-in,and load it in Plug-in Manager.
if you only want write a script ,this command cann’t undo


#3

hey,

yeah i am trying to write it as a plugin. Imagine all the other stuff is there for the plugin to work. im mainly concerned with where to place the code for undo/redo with this particular example.


#4

The way it’s usually done is you have the execution of your stuff inside the redoit method. Doit simply calls redoit (for the sake of simplicity).

In redoit you also add to the instance of the command whatever you need to keep track of to be able to undo what you did (e.g. if your script changes a few parameters you would save the original values to restore them to).
In undoit you look up whatever data is needed and basically change things back to how they were before.

Undo/Redo in Maya isn’t a time machine/diff system unless you limits yourself to commands (whcih are journalled and therefore easily reversible internally), you literally have to keep track of what you did and then execute the opposite operation (which often makes it a pain in the ass, and means for complex things to “redo” like deletion you often have to use commands because they will be buffered up for you).