Example: Cube Counter

Example: Cube Counter

The following program creates one cube (FBModelCube) and saves the scene to "one_cube.fbx". It then creates a second cube and saves the scene to "two_cubes.fbx". The number of cubes are then counted in both files; the first file contains one cube, and the second file contains two cubes. The cubes are counted according to the instances of FBComponent whose names start with "Cube" (this name is arbitrary, and is specified by the cubeBaseName variable in the code sample).

from pyfbsdk import *
import os

# Declare a base name for our cube.
cubeBaseName = 'Cube'

###############################################################
# Helper Function(s).                                         #
###############################################################
# Save the scene.
def SaveScene(pFilename):
    ''' Save the scene to MyDocuments\MB using the specified filename. '''
    directory = os.path.expanduser('~') + '\Documents\MB'
    path = os.path.join(directory, pFilename)
    FBApplication().FileSave(path)
    return path


# Create a cube using the global variable cubeBaseName,
# followed by the specified suffix.
def CreateCube(pSuffix):
    global cubeBaseName
    cube = FBModelCube(cubeBaseName + pSuffix)
    cube.Show = True   
    return cube


# Count the cubes in the scene whose names begin with cubeBaseName.
def CountCubes():
    global cubeBaseName

    # Initialize a component list to be populated.
    cl = FBComponentList()

    # Find the objects whose names start with
    # the value of cubeBaseName.
    pattern = cubeBaseName + '*'
    FBFindObjectsByName(pattern, cl, False, True)
    return len(cl)


# Print the number of cubes in the specified file.
def PrintCubesInFile(pFilename):
    FBApplication().FileOpen(pFilename, False)
    print 'Filename: ' + FBApplication().FBXFileName + '.'
    print 'Number of cubes: ' + str(CountCubes()) + '.'
    print ''


###############################################################
# Main.                                                       #
###############################################################
# Create a new scene.
FBApplication().FileNew()

# Create a first cube 'Cube1' and save the scene.
CreateCube('1')
filename1 = SaveScene('one_cube.fbx')

# Create a second cube 'Cube2' and save the scene.
CreateCube('2')
filename2 = SaveScene('two_cubes.fbx')

# Print the number of cubes in the first file.
# There should be 1 cube in this file.
PrintCubesInFile(filename1)

# Print the number of cubes in the second file.
# There should be 2 cubes in this file.
PrintCubesInFile(filename2)