示例#1
0
    def AddKeyFrame(self, controlName, time, value, low=0.0, high=1.0):

        if self.addBookmarkCheckBox.isChecked():
            if self.animset.FindControl(controlName).HasAttribute(
                    "rightvaluechannel"):
                self.animset.FindControl(
                    controlName).rightvaluechannel.log.AddBookmark(time, 0)
                self.animset.FindControl(
                    controlName).leftvaluechannel.log.AddBookmark(time, 0)
            else:
                self.animset.FindControl(controlName).channel.log.AddBookmark(
                    time, 0)

        if self.animset.FindControl(controlName).HasAttribute(
                "rightvaluechannel"):
            self.animset.FindControl(
                controlName).rightvaluechannel.log.FindOrAddKey(
                    time, vs.DmeTime_t(1.0), numpy.clip(value, low, high))
            self.animset.FindControl(
                controlName).leftvaluechannel.log.FindOrAddKey(
                    time, vs.DmeTime_t(1.0), numpy.clip(value, low, high))
        else:
            self.animset.FindControl(controlName).channel.log.FindOrAddKey(
                time, vs.DmeTime_t(1.0), numpy.clip(value, low, high))
示例#2
0
from sfmphys.bullet_utils import *

if len(sfmClipEditor.GetSelectedShots()) == 1:
    setCurrentShot(sfmClipEditor.GetSelectedShots()[0])
else:
    raise Exception("phys_simulate.py: Please select exactly one shot.")

#get info about the shot
timeSelection = GetCurrentTimeSelection()

#check for "infinite"
if (timeSelection.IsEitherInfinite()):
    raise Exception("phys_simulate.py: Please select a finite time range.")

currenttime = timeSelection.GetValue("hold_left")
dt = vs.DmeTime_t(1.0 / GetFrameRate())

#create a physics world
world = World()

#see which animsets have phys rigs applied and grab the relevant info
rigidBodies = {}
softBodies = []
constraints = []

for animSet in GetAnimationSets():
    root_group = animSet.GetRootControlGroup()

    if root_group.HasChildGroup("Rigidbodies", False):
        phys_group = root_group.FindChildByName("Rigidbodies", False)
def replaceAnimationLog(animationLog, timePoints, originalValuePoints):

    #Next, we're going to convert our times into dmeTimePoints
    dmeTimePoints = []
    for time in timePoints:
        dmeTimePoints.append(vs.DmeTime_t(time))

    # And we want a local copy of our valuePoints array, so we don't mess it up
    #  for symmetric animation replacements that use the same input values
    valuePoints = list(originalValuePoints)

    #TODO: allow us to overwrite the 0th point, since we don't just automatically trash all the data now

    # First, let's delete any old data that our animation will overwrite
    insertionPoint = -1
    for i in range(0, len(animationLog.times)):
        # If we hit a point that's past all of our time points, let's note that that's where
        #  we should be inserting points
        if (i < len(animationLog.times)) and \
           (animationLog.times[i] >= dmeTimePoints[-1]) and \
           (insertionPoint == -1):
            insertionPoint = i

        # If our new data overlaps with old data, we need to get rid of that old data,
        #  so we'll keep deleting data at the point where we find the issue until we don't
        #  have any more points that overlap
        while (i < len(animationLog.times)) and \
              (animationLog.times[i] >= dmeTimePoints[0]) and \
              (animationLog.times[i] <= dmeTimePoints[-1]) :
            # Keep deleting elements at this point, until the conditions of the while loop are broken
            del animationLog.times[i]
            del animationLog.values[i]
            # Note where this overlapped data started - that way, we know where to put
            #  the data in next
            insertionPoint = i

    # If the insertion point was never changed, tell us to insert at the end
    if insertionPoint == -1:
        insertionPoint = len(animationLog.times)

    # If there are points before our new data, we'll insert a new frame
    #  just before our animation in order to have a crisp transition
    if insertionPoint > 0:
        if (dmeTimePoints[0] - animationLog.times[insertionPoint - 1] >
                vs.DmeTime_t(20)):
            value = animationLog.values[insertionPoint - 1]
            dmeTimePoints.insert(0, dmeTimePoints[0] - vs.DmeTime_t(1))
            valuePoints.insert(0, value)

    if insertionPoint < len(animationLog.times):
        if (animationLog.times[insertionPoint] - dmeTimePoints[-1] >
                vs.DmeTime_t(20)):
            value = animationLog.values[insertionPoint]
            dmeTimePoints.append(dmeTimePoints[-1] + vs.DmeTime_t(1))
            valuePoints.append(value)
        # And add in a keyframe to the start of our new data
        #  to provide a nice crisp transition for the data
        #  so long as there isn't already a data point too close

    # Insert the data at the correct point
    for i in range(0, len(dmeTimePoints)):
        # Add in values for the time and value
        animationLog.times.insert(insertionPoint + i, dmeTimePoints[i])
        animationLog.values.insert(insertionPoint + i, valuePoints[i])
示例#4
0
    def analyze(self, dataValue, freqvalue, function, startframe, endframe):

        self.progressbarWindow.setWindowTitle('Calculating...')
        self.progressbar.setMinimum(0)
        self.progressbar.setValue(0)

        duration = endframe - startframe
        swidth = self.wf.getsampwidth()
        RATE = self.wf.getframerate()

        index = 0
        datachunk = self.DatawaveArray[index]
        #datachunkNormalized=self.DatawaveArrayInterp[index]
        #loops though entire wav file
        while len(datachunk) == self.chunk:

            self.progressbar.setValue(self.progressbar.value() + 1)

            #peak value in chunk , not sure which one is better
            dataValue.append(function(datachunk))

            #  dataValue.append(float(numpy.max((datachunk)))/2.0**15)

            #dataValue.append(float(numpy.average(numpy.abs(datachunk)))/2.0**15)

            #https://stackoverflow.com/questions/2648151/python-frequency-detection
            # Take the fft and square each value
            fftData = numpy.abs(numpy.fft.rfft(datachunk))**2.0

            # find the maximum
            which = fftData[1:].argmax() + 1

            # use quadratic interpolation around the max
            if which != len(fftData) - 1:
                y0, y1, y2 = numpy.log(fftData[which - 1:which + 2:])
                x1 = (y2 - y0) * .5 / (2 * y1 - y2 - y0)
                #find the frequency and output it
                freqvalue.append((which + x1) * RATE / self.chunk)

#print "The freq is %f Hz." %(freqvalue[-1])
            else:
                freqvalue.append(which * RATE / self.chunk)

            if self.printInfo:
                framenum = (vs.DmeTime_t(
                    (startframe * (1.0 / sfmApp.GetFramesPerSecond()))) +
                            self.getBufferFrameTime(numofchunks=index + 1)
                            ).ToFractionalFrame(
                                vs.DmeFramerate_t(
                                    sfmApp.GetFramesPerSecond())) - (
                                        sfmApp.GetFramesPerSecond() * 5.0)

                print "Chunk: %d | Frame: %d | Freq: %.02fHz." % (
                    index, numpy.round(framenum), freqvalue[-1])

            #checks if we hit the endframe
            if index >= (float(RATE / sfmApp.GetFramesPerSecond()) *
                         duration) // self.chunk:
                break

            index += 1
            datachunk = self.DatawaveArray[index]

        self.wf.close()
示例#5
0
    def getBufferFrameTime(self, numofchunks=1):

        return vs.DmeTime_t(5.00000 + (1.0 / self.wf.getframerate()) *
                            (self.chunk * numofchunks))
示例#6
0
    def startAnalyze(self):

        if not self.audiofilepath:
            self.ErrorBox("No Wave file picked!")
            return

        #get start and end time of wav clip
        endFramevalue = self.sfmCDmeSoundClip.GetEndTime().ToFractionalFrame(
            vs.DmeFramerate_t(sfmApp.GetFramesPerSecond()))

        startFramevalue = self.sfmCDmeSoundClip.GetStartTime(
        ).ToFractionalFrame(vs.DmeFramerate_t(sfmApp.GetFramesPerSecond()))

        ###loops though all the pages and adds them to the dict if they are enabled
        ##key=control name: value=[min value,max value,min freq,max freq]
        controldict = {}

        for index in range(self.control_toolBox.count()):

            if self.control_toolBox.widget(index).IsEnabled():

                minvalue, maxvalue = self.control_toolBox.widget(
                    index).GetValueRange()

                if self.control_toolBox.widget(index).IsFreqEnable():
                    minfreqvalue, maxfreqvalue = self.control_toolBox.widget(
                        index).GetFreqRange()
                    controldict[self.control_toolBox.itemText(index)] = [
                        minvalue, maxvalue, minfreqvalue, maxfreqvalue
                    ]
                else:
                    controldict[self.control_toolBox.itemText(index)] = [
                        minvalue, maxvalue
                    ]

        ####

        if not controldict:
            self.ErrorBox("No Controls were Enabled!")
            return

# Change the operation mode to passthrough so changes chan be made temporarily
        sfm.SetOperationMode("Pass")
        sfmApp.SetTimelineMode(2)

        self.Dialog.hide()

        #inits audio class
        self.audioAnalyze = AudioFileAnalyze(
            self.audiofilepath,
            self.spinBox_buffer.value()
            if self.checkBox_overrideBuffer.isChecked() else None,
            self.checkBox_printfreq.isChecked())

        #used to calulate the number of chunks ,for progressbar

        numframes = (numpy.ceil(
            float(
                (self.audioAnalyze.wf.getframerate() /
                 sfmApp.GetFramesPerSecond()) *
                (endFramevalue - startFramevalue)) / self.audioAnalyze.chunk))

        #set max for progressbar
        self.audioAnalyze.progressbar.setMaximum(numframes * 2 *
                                                 len(controldict.keys()))

        if self.radioMax.isChecked():
            function = numpy.max

        elif self.radioAvg.isChecked():
            function = numpy.mean

        elif self.radioMin.isChecked():
            function = numpy.min

        #fill up array with the data
        dataValue = []
        freqvalues = []
        self.audioAnalyze.analyze(
            dataValue, freqvalues, function, startFramevalue,
            endFramevalue)  #fill up the array with data points

        dataValue = numpy.interp(dataValue,
                                 (numpy.min(dataValue), numpy.max(dataValue)),
                                 (0.0, 1.0))

        #loop though the dict
        for control in controldict.keys():

            #add a blank key 1 frame before we start
            beforetime = vs.DmeTime_t(5.0 +
                                      ((startFramevalue - 1) *
                                       (1.0 / sfmApp.GetFramesPerSecond())))
            val = self.GetKeyFrameValue(str(control), beforetime)
            self.AddKeyFrame(str(control), beforetime, val)

            #loop though data array
            for index in range(len(dataValue)):

                if len(controldict[control]) == 2:  #only peak

                    self.AddKeyFrame(
                        str(control),
                        vs.DmeTime_t((startFramevalue *
                                      (1.0 / sfmApp.GetFramesPerSecond()))) +
                        self.audioAnalyze.getBufferFrameTime(
                            numofchunks=index + 1), dataValue[index],
                        controldict[control][0], controldict[control][1])

                if len(controldict[control]
                       ) > 2 and controldict[control][2] <= freqvalues[
                           index] <= controldict[control][3]:  #only on freq

                    self.AddKeyFrame(
                        str(control),
                        vs.DmeTime_t((startFramevalue *
                                      (1.0 / sfmApp.GetFramesPerSecond()))) +
                        self.audioAnalyze.getBufferFrameTime(
                            numofchunks=index + 1), dataValue[index],
                        controldict[control][0], controldict[control][1])

                else:  #give min value when not in freq range
                    self.AddKeyFrame(
                        str(control),
                        vs.DmeTime_t((startFramevalue *
                                      (1.0 / sfmApp.GetFramesPerSecond()))) +
                        self.audioAnalyze.getBufferFrameTime(
                            numofchunks=index + 1), controldict[control][0])

                self.audioAnalyze.progressbar.setValue(
                    self.audioAnalyze.progressbar.value() + 1)

            #set last key to value before the clip
            self.AddKeyFrame(
                str(control),
                vs.DmeTime_t(5.0 + ((endFramevalue + 1) *
                                    (1.0 / sfmApp.GetFramesPerSecond()))), val)

        #cleanup
        del self.audioAnalyze
        self.Dialog.accept()