I made the changes in order to work on a duplicate of the original spline.
It still works, but it also still returns the same error when I undo.
Here is the script:
import c4d
from c4d import gui
# Welcome to the world of Python
# Find the length of the spline segment between points p1 and p2
def GetLength(op,p1,p2):
select=op.GetPointS()
select.DeselectAll()
select.Select(p1)
select.Select(p2)
bc=c4d.BaseContainer()
result=c4d.utils.SendModelingCommand(c4d.MCOMMAND_SPLIT, [op], mode=c4d.MODELINGCOMMANDMODE_POINTSELECTION, bc=bc, doc=doc)
leng=10000000.0
if result!=False and result!=[]:
op2=result[0]
segm=c4d.utils.SplineHelp()
segm.InitSplineWith(op2, flags=c4d.SPLINEHELPFLAGS_GLOBALSPACE|c4d.SPLINEHELPFLAGS_CONTINUECURVE)
leng=segm.GetSplineLength()
segm.FreeSpline()
return leng
# Main function
def main():
selected=doc.GetActiveObjects(c4d.GETACTIVEOBJECTFLAGS_0)
if len(selected) == 0:
c4d.gui.MessageDialog("You must select a spline and two consecutive points of that spline.")
return
op=selected[0]
if op.GetType()!=5101:
c4d.gui.MessageDialog("You must select a spline and two consecutive points of that spline.")
return
selection=op.GetPointS()
if selection.GetCount()!=2:
c4d.gui.MessageDialog("You must select two consecutive points of the spline.")
return
# check if the selected points are consecutive
p1,p2=-1,-1
num=op.GetPointCount()
for s in range(num):
if selection.IsSelected(s):
if p1==-1:
p1=s
else:
p2=s
if p2-p1!=1:
c4d.gui.MessageDialog("You must select two consecutive points of the spline.")
return
# get the size of the segment
shortest=GetLength(op,p1,p2)
# work on a copy of the original spline
op2=op.GetClone()
# start at point 0
i=0
while i<num:
# get the length of the current segment between point i and i+1
new_length=GetLength(op2,i,i+1)
# if the segment is, at least one and a half times the size of the initial segment...
if (new_length>(shortest*1.5)):
subdivs=int(new_length/shortest)+1
# select point i and i+1
selection=op2.GetPointS()
selection.DeselectAll()
selection.Select(i)
selection.Select(i+1)
# subdivide that segment
bc=c4d.BaseContainer()
bc.SetInt32(c4d.MDATA_SUBDIVIDE_SPLINESUB,subdivs)
result=c4d.utils.SendModelingCommand(c4d.MCOMMAND_SUBDIVIDE, [op2], mode=c4d.MODELINGCOMMANDMODE_POINTSELECTION, bc=bc, doc=doc)
# update the counter
i=i+subdivs-1
# update the limit
num=num+subdivs-1
# increase the counter
i=i+1
# insert the new subdivided spline after the original spline
# and delete the original spline, making sure this is undoable
doc.StartUndo()
doc.InsertObject(op2, parent=None, pred=op, checknames=False)
doc.AddUndo(c4d.UNDOTYPE_NEW, op2)
doc.AddUndo(c4d.UNDOTYPE_DELETE, op)
op.Remove()
doc.EndUndo()
# update the document
c4d.EventAdd()
# Execute main()
if __name__=='__main__':
main()