Exemple #1
0
    def exportLamp(self, lampName):
        """
		Exports the lamp whose name is specified.
		This must be called after the final pass of the data collection.		
		
		lampName - the name of the Blender lamp
		"""
        print "Generating code for lamp ...", lampName
        lampCodeName = reduceNamesToCodeNames(lampName)
        lampData = bpy.data.objects[lampName]
        alt_lampData = bpy.data.lamps[lampData.getData().name]

        self.writeCode("fLamp		o" + lampCodeName + " = {")
        self.writeCode('	"' + lampCodeName + '",')
        localMat = Mathutils.Matrix(lampData.matrixLocal)
        TransMat = localMat.translationPart()
        LocX = TransMat.x
        LocY = TransMat.y
        LocZ = TransMat.z

        self.writeCode("	{" + str(LocX) + "," + str(LocY) + "," + str(LocZ) +
                       ",1.0},")
        self.writeCode("	" + str(rad2deg(lampData.RotX)) + "," +
                       str(rad2deg(lampData.RotY)) + "," +
                       str(rad2deg(lampData.RotZ)) + ",")
        self.writeCode("	" + str(lampData.SizeX) + "," + str(lampData.SizeY) +
                       "," + str(lampData.SizeZ) + ",")
        self.writeCode("	{" + str(alt_lampData.R) + "," + str(alt_lampData.G) +
                       "," + str(alt_lampData.B) + ",1.0},")
        self.writeCode("	{" + str(alt_lampData.R) + "," + str(alt_lampData.G) +
                       "," + str(alt_lampData.B) + ",1.0},")
        #self.writeCode("	{"+str(alt_lampData.energy)+","+str(alt_lampData.energy)+","+str(alt_lampData.energy)+",1.0},")
        self.writeCode("};")
        self.writeCode("	")
Exemple #2
0
def pose_camera(cam, cam_etree):
    """Pose camera based on external parameters in a CameraCalibration XML etree.
    
    The following transforms are performed:
    
    1. Perform a 180 degree rotation of the camera about the y axis.

    2. Apply the inverse of the transform defined by Model2CameraMatrix to the
    camera. Use the inverse because we are moving the camera not the model.

    3. Apply the transform defined by /Model/Pose."""
    #TODO: All of the matrix operations could be switched to Matutils to remove
    #      numpy dependency.

    y_rot = asmatrix(identity(4))
    y_rot[0, 0] = -1
    y_rot[2, 2] = -1
    
    m2c = cam_etree.find('Model2CameraMatrix').find('Matrix4x4').get('RowOrder')
    m2c = asmatrix(fromstring(m2c, sep=' ').reshape(4, 4))

    m = cam_etree.find('Model').find('Pose').find('Matrix4x4').get('RowOrder')
    m = asmatrix(fromstring(m, sep=' ').reshape(4, 4))
    
    # We have been working with row-order matrices so they need to be
    # transposed before composition.
    pose = y_rot.T * m2c.T.I * m.T
    pose = pose.tolist()
    pose = Mathutils.Matrix(*pose)
    
    cam.setMatrix(pose)
Exemple #3
0
    def exportObject3D(self, objName):
        """
		Exports the object whose name is specified.
		An object structure and an array listing the order of parents of the 
		camera is written to the C file. This must be called after the final 
		pass of the data collection.
		
		objName - name of the Blender object
		"""
        print "Generating code for Object3D ...", objName
        objCodeName = reduceNamesToCodeNames(objName)
        obj = bpy.data.objects[objName]
        objData = obj.getData()

        localMat = Mathutils.Matrix(obj.matrixLocal)
        TransMat = localMat.translationPart()
        LocX = TransMat.x
        LocY = TransMat.y
        LocZ = TransMat.z

        self.writeCode("int arrChildren_" + objCodeName + " [] = {")

        childIndices = self.dictObject3DNames[objName][2]
        for index in childIndices:
            self.writeCode("	" + str(index) + ",")

        self.writeCode("	-1,")
        self.writeCode("};")

        self.writeCode("	")

        self.writeCode("fObject3D		o" + objCodeName + " = {")
        self.writeCode('	"' + objCodeName + '",')

        if objData:
            meshName = self.dictObject3DNames[objName][0]
            meshCodeName = reduceNamesToCodeNames(meshName)
            meshData = bpy.data.meshes[meshName]
            UV_ImageName = self.getTextureName(meshData.faces[0].image)
            self.writeCode("	&oMeshTable_" + meshCodeName + ",")
            self.writeCode('	//"' + UV_ImageName + '",')
            self.writeCode("	" + str(self.imageIndices[UV_ImageName]) + ",")
        else:
            self.writeCode("	NULL,")
            self.writeCode("	0,")

        self.writeCode("	NULL,")
        self.writeCode("	" + str(LocX) + "," + str(LocY) + "," + str(LocZ) +
                       ",")
        self.writeCode("	" + str(rad2deg(obj.RotX)) + "," +
                       str(rad2deg(obj.RotY)) + "," + str(rad2deg(obj.RotZ)) +
                       ",")
        self.writeCode("	" + str(obj.SizeX) + "," + str(obj.SizeY) + "," +
                       str(obj.SizeZ) + ",")
        self.writeCode("	arrChildren_" + objCodeName + ",")
        self.writeCode("};")
        self.writeCode("	")

        self.identifyRoot(objName)
 def addBone(self, parent, bone):
     #print "adding bone %s to %s"%(bone.name, parent.getAttribute("name"))
     boneNode = self.doc.createElement("TransformGroup")
     boneNode.setAttribute("name", bone.name)
     self.lastNodeId = self.lastNodeId + 1
     #boneNode.setAttribute("nodeId", "%i" %(self.lastNodeId))
     boneNameIndex.append({0: bone.name, 1: self.lastNodeId})
     mmm = Mathutils.Matrix(bone.matrix["ARMATURESPACE"])
     pa = bone.parent
     if not pa is None:
         mmm = mmm - Mathutils.Matrix(
             pa.matrix["ARMATURESPACE"])
     self.setTranslation(boneNode, mmm.translationPart())
     boneNode.setAttribute("rotation", "0 0 0")
     parent.appendChild(boneNode)
     for b in bone.children:
         addBone(self, boneNode, b)
Exemple #5
0
def do_export(sel_group, filepath):
	Window.WaitCursor(1)
	t = sys.time()

	#init Drawing ---------------------
	d=Drawing()
	#add Tables -----------------
	#d.blocks.append(b)					#table blocks
	d.styles.append(Style())			#table styles
	d.views.append(View('Normal'))		#table view
	d.views.append(ViewByWindow('Window',leftBottom=(1,0),rightTop=(2,1)))  #idem

	#add Entities --------------------
	something_ready = False
	#ViewVector = Mathutils.Vector(Window.GetViewVector())
	#print 'deb: ViewVector=', ViewVector #------------------
	mw0 = Window.GetViewMatrix()
	#mw0 = Window.GetPerspMatrix() #TODO: how get it working?
	mw = mw0.copy()
	if FLATTEN:
		m0 = Mathutils.Matrix()
		m0[2][2]=0.0
		mw *= m0 #flatten ViewMatrix

	for ob in sel_group:
		entities = []
		mx = ob.matrix.copy()
		mb = mx.copy()
		#print 'deb: mb    =\n', mb     #---------
		#print 'deb: mw0    =\n', mw0     #---------
		mx_n = mx.rotationPart() * mw0.rotationPart() #trans-matrix for normal_vectors
		if SCALE_FACTOR!=1.0: mx *= SCALE_FACTOR
		if FLATTEN:	mx *= mw
			
		#mx_inv = mx.copy().invert()
		#print 'deb: mx    =\n', mx     #---------
		#print 'deb: mx_inv=\n', mx_inv #---------

		if (ob.type == 'Mesh'):
			entities = exportMesh(ob, mx, mx_n)
		elif (ob.type == 'Curve'):
			entities = exportCurve(ob, mx)

		for e in entities:
			d.append(e)
			something_ready = True

	if something_ready:
		d.saveas(filepath)
		Window.WaitCursor(0)
		#Draw.PupMenu('DXF Exporter: job finished')
		print 'exported to %s' % filepath
		print 'finished in %.2f seconds' % (sys.time()-t)
	else:
		Window.WaitCursor(0)
		print "Abort: selected objects dont mach choosen export option, nothing exported!"
		Draw.PupMenu('DXF Exporter:   nothing exported!|selected objects dont mach choosen export option!')
    def __populateData(self, prefs):
        # go through each armature object
        for armOb in Blender.Object.Get():
            if (armOb.getType() != 'Armature'): continue
            # add a dictionary entry for the armature, and store all it's static data in a list
            armDb = armOb.getData()
            armMat = bMath.Matrix(armOb.getMatrix('worldspace'))
            armRot = self.toTorqueQuat(
                armMat.rotationPart().toQuat().normalize())
            armRotInv = armRot.inverse()
            armLoc = self.toTorqueVec(armMat.translationPart())
            armSize = self.toTorqueVec(armOb.getSize('worldspace'))
            try:
                exportScale = prefs['ExportScale']
            except:
                exportScale = 1.0
            armSize[0], armSize[1], armSize[
                2] = armSize[0] * exportScale, armSize[
                    1] * exportScale, armSize[2] * exportScale
            armLoc[0], armLoc[1], armLoc[2] = armLoc[0] * exportScale, armLoc[
                1] * exportScale, armLoc[2] * exportScale
            self.armInfo[armOb.name] = [
                armOb, armDb, armRot, armRotInv, armLoc, armSize
            ]
            self.armBones[armOb.name] = {}

            # loop through the armature's bones
            for bone in armDb.bones.values():
                bName = bone.name
                # store off all static values for each bone
                # leaks memory in blender 2.41
                bMat = bone.matrix['ARMATURESPACE']
                if bone.hasParent():
                    parentName = bone.parent.name
                else:
                    parentName = None
                self.armBones[armOb.name][bName] = [
                    bone, bMat, None, None, parentName, None, None
                ]
                self.armBones[
                    armOb.name][bName][BONERESTPOSWS] = self.getBoneRestPosWS(
                        armOb.name, bName)
                self.armBones[
                    armOb.name][bName][BONERESTROTWS] = self.getBoneRestRotWS(
                        armOb.name, bName)

            # second pass for calculated static bone data
            for bone in armDb.bones.values():
                bName = bone.name
                if bone.hasParent():
                    self.armBones[armOb.name][bName][
                        BONEDEFPOSPS] = self.getBoneDefPosPS(
                            armOb.name, bName)
                    self.armBones[armOb.name][bName][
                        BONEDEFROTPS] = self.getBoneDefRotPS(
                            armOb.name, bName)
Exemple #7
0
def exportFrame(_armature, i, bone, out):
    print "===Frame :"+ str(i)+"========"
    Blender.Set("curframe",i)
    pose = _armature.getPose()

    tail = pose.bones[bone.name].tail
    head = pose.bones[bone.name].head
    print "tail:"
    print tail
    print "head:"
    print head

    initial = bone.matrix['ARMATURESPACE']
    initial.invert()
    
    flipMatrix = Mathutils.Matrix([1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1])

    finalmatrix = Mathutils.Matrix(bone.matrix['ARMATURESPACE']) * pose.bones[bone.name].poseMatrix  #* flipMatrix#initial * matrix 
    
    
    print "Euler:"
    print matrixToEuler(finalmatrix)
    print "Pos:"
    print vector_by_matrix(finalmatrix, Mathutils.Vector( [ 0, 0, 0 ] ))

    

    floats = array('f')
    #print finalmatrix
    for a in range(4):
        for b in range(4):
            floats.append(finalmatrix[a][b])

    #floats = array('f')
    floats.append(tail[0])
    floats.append(tail[1])
    floats.append(tail[2])

    floats.append(head[0])
    floats.append(head[1])
    floats.append(head[2])

    floats.tofile(out)
Exemple #8
0
    def exportCamera(self, cameraName):
        """
		Exports the camera whose name is specified.
		A camera structure and an array listing the order of parents of the 
		camera is written to the C file. This must be called after the final 
		pass of the data collection.
		
		cameraName - name of the Blender camera object
		"""
        print "Generating code for camera ...", cameraName
        cameraCodeName = reduceNamesToCodeNames(cameraName)
        cameraData = bpy.data.objects[cameraName]
        alt_cameraData = bpy.data.cameras[cameraData.getData().name]

        self.writeCode("int arrParent_" + cameraCodeName + " [] = {")

        cameraParent = cameraData.getParent()
        if cameraParent:
            arrParentList = []
            while cameraParent:
                objName = cameraParent.name
                index = self.dictObject3DNames[objName][1]
                arrParentList.append(index)
                cameraParent = bpy.data.objects[objName].getParent()

            for index in arrParentList:
                self.writeCode("	" + str(index) + ",")

        self.writeCode("	-1,")
        self.writeCode("};")

        self.writeCode("fCamera		o" + cameraCodeName + " = {")
        self.writeCode('	"' + cameraCodeName + '",')
        localMat = Mathutils.Matrix(cameraData.matrixLocal)
        TransMat = localMat.translationPart()
        LocX = TransMat.x
        LocY = TransMat.y
        LocZ = TransMat.z

        self.writeCode("	" + str(LocX) + "," + str(LocY) + "," + str(LocZ) +
                       ",")
        self.writeCode("	" + str(rad2deg(cameraData.RotX)) + "," +
                       str(rad2deg(cameraData.RotY)) + "," +
                       str(rad2deg(cameraData.RotZ)) + ",")
        self.writeCode("	" + str(cameraData.SizeX) + "," +
                       str(cameraData.SizeY) + "," + str(cameraData.SizeZ) +
                       ",")
        self.writeCode("	" + str(alt_cameraData.getClipStart()) + "," +
                       str(alt_cameraData.getClipEnd()) + ",")
        self.writeCode("	" + str(alt_cameraData.getLens()) + ",")
        self.writeCode("	arrParent_" + cameraCodeName + ",")
        self.writeCode("};")
        self.writeCode("	")
Exemple #9
0
def cleanMeshes():
    objs = Object.Get()
    for o in objs:
        if o.getType(
        ) == 'Mesh':  #Applies all scales and rotations (imitates CTRL+A behaviour)
            me = o.getData()
            mat = Mathutils.Matrix(o.matrix[0][:], o.matrix[1][:],
                                   o.matrix[2][:], [.0, .0, .0, 1.0])
            me.transform(mat)
            me.update()
            o.setEuler(0.0, 0.0, 0.0)
            o.setSize(1.0, 1.0, 1.0)
Exemple #10
0
def exportFrame(_armature, i, bone, out, swap):
    #if (i == 30):
    #    print "===Frame :"+ str(i)+"========"
    Blender.Set("curframe",i)
    pose = _armature.getPose()
    armpos = _armature.mat

    identity = Mathutils.Matrix([1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1])
    rotation = Mathutils.RotationMatrix(-90, 4, 'x')
    swapyz = rotation * identity


    if (swap == True):
        initial = Mathutils.Matrix(bone.matrix['ARMATURESPACE']) * armpos * swapyz
        initial.invert()
        posematrix = Mathutils.Matrix(pose.bones[bone.name].poseMatrix) * armpos * swapyz
    else:
        initial = Mathutils.Matrix(bone.matrix['ARMATURESPACE']) * armpos
        initial.invert()
        posematrix = Mathutils.Matrix(pose.bones[bone.name].poseMatrix) * armpos

    
    finalmatrix = initial * posematrix

    #if (i==30):
    #    print _armature.mat
    
    floats = array('f')
    #if (i == 30):
    #    print finalmatrix
    for a in range(4):
        for b in range(4):
            floats.append(finalmatrix[a][b])

    floats.tofile(out)
    
    #export only pose matrix
    """poser = array('f')
    def setRotation(self, node, rot, rotX90):
        rot[0], rot[1], rot[2] = math.degrees(rot[0]), math.degrees(
            rot[2]), math.degrees(-rot[1])

        RotationMatrix = Mathutils.RotationMatrix
        MATRIX_IDENTITY_3x3 = Mathutils.Matrix([1.0, 0.0, 0.0],
                                               [0.0, 1.0, 0.0],
                                               [0.0, 0.0, 1.0])
        x, y, z = rot[0] % 360, rot[1] % 360, rot[
            2] % 360  # Clamp all values between 0 and 360, values outside this raise an error.
        xmat = RotationMatrix(x, 3, 'x')
        ymat = RotationMatrix(y, 3, 'y')
        zmat = RotationMatrix(z, 3, 'z')
        eRot = (xmat * (zmat * (ymat * MATRIX_IDENTITY_3x3))).toEuler()

        if rotX90:
            node.setAttribute("rotation",
                              "%f %f %f" % (eRot.x - 90, eRot.y, eRot.z))
        else:
            node.setAttribute("rotation",
                              "%f %f %f" % (eRot.x, eRot.y, eRot.z))
Exemple #12
0
 def fix_transform(self, transform, frame):
     """ Return adjusted transform, compensating for a) mannequin size,
         b) model size, and c) model orientation at given frame."""
     ## print " fix_transform: transform = '%s'" % str(transform)
     ## print " fix_transform: frame = '%s'" % str(frame)
     model_scale = self.model.size[0]       # assuming same scaling in x,y,z
     armature_scale = self.armature.size[0] # ditto
     offset = transform.translationPart()
     #
     # scaled_offset = offset * model_scale * armature_scale
     ## Hmmm. The scaling seems to be going in twice, so I'll try it this way.
     scaled_offset = offset * armature_scale
     #
     if frame > 0:
         blender_frame(frame)
         model_orientation = self.model.getMatrix().rotationPart()
     else:
         model_orientation = Mathutils.Matrix([1,0,0],[0,1,0],[0,0,1])
     rotated_scaled_offset = scaled_offset * model_orientation
     new_transform = offset_and_rotation_to_matrix(rotated_scaled_offset,
                                                   transform.rotationPart())
     return new_transform
Exemple #13
0
 def add_motion(self, motion, frame_duration='default', frame_start=None):
     """ Add a movement action, and adjust object location accordingly. """
     strip = self.add_action(motion)
     foot = Step.foot(strip.name)
     if foot:
         self.foot = foot
     actionStrips = self.model.actionStrips
     if frame_duration == 'default':
         frame_duration = strip.actionEnd - strip.actionStart
     index = len(actionStrips) - 1
     while True:           # move action strip up past any non-step motions
         if index == 1:
             previous_strip = None
             previous_step = None
             break
         previous_strip = actionStrips[index-1]
         previous_step = Step(previous_strip)
         if previous_step.is_motion():
             break
         else:
             actionStrips.moveUp(strip)
             index = index - 1
     if frame_start:
         strip.stripSart = frame_start
     elif previous_strip:
         strip.stripStart = previous_strip.stripEnd
     else:
         strip.stripStart = start_frame
     strip.stripEnd = strip.stripStart + frame_duration
     if previous_step:
         # Key model ipo location and rotation at start of new strip
         # so that motion continues from end of previous strip.
         previous_motion = previous_step.bone_transform()
     else:
         previous_motion = Mathutils.Matrix().identity().resize4x4()
     self.place_actionstrip(previous_motion, strip)
Exemple #14
0
    def writeObject(self, ob):

        obname = self.cleanStr(ob.name)

        try:
            obtype = ob.getType()
        except AttributeError:
            print "Error: Unable to get type info for %s" % obname
            return

        if self.verbose >= 1:
            print "++ Writing %s object %s (Blender name: %s)\n" % \
               (obtype, obname, ob.name)

        # Note: I am leaving empties out for now -- the original
        # script does some really weird stuff with empties
        if ( (obtype != "Camera") and \
          (obtype != "Mesh") and \
          (obtype != "Lamp") ):
            print "Info: Ignoring [%s], object type [%s] " \
               "not handle yet" % (obname, obtype)
            return

        ob_matrix = Mathutils.Matrix(ob.getMatrix('worldspace'))
        if export_rotate_z_to_y.val:
            matrix = M_blen2vrml * ob_matrix * M_vrml2blen
        else:
            matrix = ob_matrix
        e = matrix.rotationPart().toEuler()

        v = matrix.translationPart()
        (axis, angle) = self.eulToVecRot(self.deg2rad(e.x), \
                 self.deg2rad(e.y), \
                 self.deg2rad(e.z))

        mrot = e.toMatrix().resize4x4()
        try:
            mrot.invert()
        except:
            print "Warning: %s has degenerate transformation!" % (obname)
            return

        diag = matrix * mrot
        sizeX = diag[0][0]
        sizeY = diag[1][1]
        sizeZ = diag[2][2]

        if self.verbose >= 1:
            print "  Transformation:\n" \
               "    loc:  %f %f %f\n" \
               "    size: %f %f %f\n" \
               "    Rot:  (%f %f %f), %f\n" % \
               (v.x, v.y, v.z, \
                sizeX, sizeY, sizeZ, \
                axis[0], axis[1], axis[2], angle)

        self.writeIndented("DEF OB_%s Transform {\n" % (obname), 1)
        self.writeIndented("translation %f %f %f\n" % \
               (v.x, v.y, v.z) )

        self.writeIndented("rotation %f %f %f %f\n" % \
               (axis[0],axis[1],axis[2],angle) )

        self.writeIndented("scale %f %f %f\n" % \
               (sizeX, sizeY, sizeZ) )

        self.writeIndented("children [\n", 1)

        self.writeObData(ob)

        self.writeIndented("]\n", -1)  # end object
        self.writeIndented("}\n", -1)  # end object
Exemple #15
0
scene = Blender.Scene.getCurrent()
world = Blender.World.GetCurrent()
worldmat = Blender.Texture.Get()
filename = Blender.Get('filename')
_safeOverwrite = True
extension = ''

# Matrices below are used only when export_rotate_z_to_y.val:
#
# Blender is Z up, VRML is Y up, both are right hand coordinate
# systems, so to go from Blender coords to VRML coords we rotate
# by 90 degrees around the X axis. In matrix notation, we have a
# matrix, and it's inverse, as:
M_blen2vrml = Mathutils.Matrix([1,0,0,0], \
          [0,0,1,0], \
          [0,-1,0,0], \
          [0,0,0,1])
M_vrml2blen = Mathutils.Matrix([1,0,0,0], \
          [0,0,-1,0], \
          [0,1,0,0], \
          [0,0,0,1])


class DrawTypes:
    """Object DrawTypes enum values
    BOUNDS - draw only the bounding box of the object
    WIRE - draw object as a wire frame
    SOLID - draw object with flat shading
    SHADED - draw object with OpenGL shading
"""
    BOUNDBOX = 1
Exemple #16
0
def export(filename):

    out = file(filename,'wb+')
    scene = bpy.data.scenes.active
    Objects = scene.objects

    magic = array('c')
    magic.fromstring('RM2')
    magic.tofile(out)

    
    ints = array('i')
    
    ints.append(ObjectCount(Objects, 'Mesh'))
    ints.tofile(out)
    ints.pop

    swapyz = True
    
    for ob in Objects:
        if (ob.getType()== 'Mesh'):
            mesh = ob.getData()

            m = Mathutils.Matrix(ob.getMatrix())

            ExportGeometry(mesh, m, out, swapyz)

            if (ob.parent != None):
                parent = ob.parent

                if (parent.getType() == 'Armature'):
                    ArmatureData = parent.getData()
                    Bones = ArmatureData.bones
                    BoneData = Bones.values()

                    bonec = array('i')
                    bonec.append(len(BoneData))
                    bonec.tofile(out)

                    BoneList = []
                    for bone in BoneData:
                        BoneList.append(bone.name)

                    WriteInfluences(BoneList, mesh, out)

                    totalFrames = Blender.Get("endframe") -\
                                  Blender.Get("staframe") + 1

                    framec = array('i')
                    framec.append(totalFrames)
                    framec.tofile(out)
                    framec.pop

                    for bone in BoneData:
                        for i in range(Blender.Get("staframe"),Blender.Get("endframe")+1):
                            exportFrame(parent, i, bone, out, swapyz)
                        #for each frame

                #if armature
            else:
                bonec = array('i')
                bonec.append(0)
                bonec.append(0)
                bonec.tofile(out)

    out.close()
Exemple #17
0
EVENT_CAM = 5
EVENT_LIG = 6
EVENT_EXP = 7
EVENT_QUI = 8

#Global Stacks
flag_stack = []
sets_stack = []
texs_stack = []
brus_stack = []
mesh_stack = []
bone_stack = []
keys_stack = []

#Transformation Matrix
TRANS_MATRIX = Mathutils.Matrix([-1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0],
                                [0, 0, 0, 1])


#Support Functions
def write_int(value):
    return struct.pack("<i", value)


def write_float(value):
    return struct.pack("<f", round(value, 4))


def write_string(value):
    binary_format = "<%ds" % (len(value) + 1)
    return struct.pack(binary_format, value)
Exemple #18
0
  def mainloop(self):
        import sys,os
        import numpy
        from numpy import oldnumeric as Numeric
        import PyARTK
        from PyARTK import video,arparamlib,arlib,utils,glutils
        import Image
        import Tkinter
        import ImageTk
        from Blender import Mathutils
    #try:
     
        self.videoApp.lock.acquire()        # detect the markers in the video frame
        if sys.platform == 'darwin':
          im_array = utils.convert_ARGB_RGBA(self.videoApp.cam.im_array)
        else:
          im_array = self.videoApp.cam.im_array

        marker_info  = arlib.arDetectMarker(im_array,self.thresh)
        marker_num = len(marker_info)
        
        # check for object visibility
        k = -1;
        for j in range(marker_num):
            if( self.patt_id == marker_info[j].id ):
                if( k == -1 ):k = j
                elif( marker_info[k].cf < marker_info[j].cf ): k = j
        
        
        if( k > -1 ):
            conf = marker_info[k].cf
	    sys.stdout.write("-- Detected Marker --")
	    sys.stderr.write("-- Detected Marker --")
            print "-- Detected Marker --"
            print " Marker id = %d conf= %d\n "%(marker_info[k].id,int(conf*100.0))
	    sys.stderr.write(" Marker id = %d conf= %d\n "%(marker_info[k].id,int(conf*100.0)))
            # get the transformation between the marker and the real camera */
            if(self.mode == 0):
                arlib.arGetTransMat(marker_info[k], self.patt_center,
                                    self.patt_width, self.patt_trans)
            else:
                arlib.arGetTransMatCont(marker_info[k], self.patt_prev,
                                        self.patt_center, self.patt_width,
                                        self.patt_trans)
                # save as for averaging
                self.patt_prev = Numeric.array(self.patt_trans,copy=1)
      
        m_modelview = Numeric.zeros(16,'d')
        scale = 1.0
        glutils.arglCameraView(self.patt_trans,m_modelview,scale)
        print "-- Model View Matrix arglCameraView --"
        for i in range(4):
            i = i *4
            print "%.2f %.2f %.2f %.2f"%(m_modelview[i],
                                         m_modelview[i+1],
                                         m_modelview[i+2],
                                         m_modelview[i+3])
        print ''
        print "-- Model View Matrix arglCameraViewRH --"     
        m_modelview_rh = Numeric.zeros(16,'d')
        glutils.arglCameraViewRH(self.patt_trans,m_modelview_rh,scale)
        for i in range(4):
            i = i *4
            print "%.2f %.2f %.2f %.2f"%(m_modelview_rh[i],
                                         m_modelview_rh[i+1],
                                         m_modelview_rh[i+2],
                                         m_modelview_rh[i+3])
	    sys.stderr.write("%.2f %.2f %.2f %.2f"%(m_modelview_rh[i],
                                         m_modelview_rh[i+1],
                                         m_modelview_rh[i+2],
                                         m_modelview_rh[i+3]))
	    sys.stdout.write("%.2f %.2f %.2f %.2f"%(m_modelview_rh[i],
                                         m_modelview_rh[i+1],
                                         m_modelview_rh[i+2],
                                         m_modelview_rh[i+3]))
	self.matrix=m_modelview
        if self.tk != None : 
            im = Image.fromstring(self.pixel_format,(self.width,self.height),im_array.tostring())
            self.videoApp.lock.release()
            #update Tk label
            self.photo.paste(im)
            self.tk.update()
	else :
	    im = Image.fromstring(self.pixel_format,(self.width,self.height),im_array.tostring())
	    self.videoApp.lock.release()
	    im.save(self.data_path+'/tmp.png')
	    #data=im.getdata()
	    #for y in range(self.height-1):
	    #    ind=(self.height-1)+y
	    #    for x in range(self.width-1):
	    #        r,g,b=data[x+ind]
	    #        self.photo.setPixelI(x, y, (int(r), int(g), int(b), 255)) 
	    self.photo.reload()

	if self.trackedObj != None :
		#self.matrix[14]=self.matrix[14]/10.0
		mat=self.matrix.reshape(4,4)
		self.trackedObj.setMatrix(Mathutils.Matrix(mat[0],mat[1],mat[2],mat[3]))

	sys.stderr.write('i am in the loop\n')
	sys.stderr.flush()
	sys.stdout.flush()
Exemple #19
0
# check General scripts config key for default behaviors
rd = Registry.GetKey('General', True)
if rd:
	try:
		VERBOSE = rd['verbose']
		CONFIRM_OVERWRITE = rd['confirm_overwrite']
	except: pass


# The default material to be used when necessary (see ADD_DEFAULT_MAT)
DEFAULT_MAT = \
'MATERIAL "DefaultWhite" rgb 1 1 1  amb 1 1 1  emis 0 0 0  \
spec 0.5 0.5 0.5  shi 64  trans 0'

# This transformation aligns Blender and AC3D coordinate systems:
BLEND_TO_AC3D_MATRIX = Mathutils.Matrix([1,0,0,0], [0,0,-1,0], [0,1,0,0], [0,0,0,1])

def Round_s(f):
	"Round to default precision and turn value to a string"
	r = round(f,6) # precision set to 10e-06
	if r == int(r):
		return str(int(r))
	else:
		return str(r)
 
def transform_verts(verts, m):
	vecs = []
	for v in verts:
		x, y, z = v.co
		vec = Mathutils.Vector([x, y, z, 1])
		vecs.append(vec*m)
Exemple #20
0
def export_lights(lmp):
    # only lamp type 0 supported at the moment
    # lamp types are: 0 - Lamp, 1 - Sun, 2 - Spot, 3 - Hemi, 4 - Area
    lamp = lmp.getData()
    if lamp.type == 0:
        print "o exporting lamp " + lmp.name + "..."
        # get the rgb component for the lamp
        red = lamp.col[0]
        green = lamp.col[1]
        blue = lamp.col[2]
        power = lamp.energy

        # get the location of the lamp
        objmatrix = lmp.matrix
        lampV = Mathutils.Vector([0, 0, 0, 1])
        lampV = lampV * objmatrix

        FILE.write("\n\nlight {\n")
        FILE.write("\ttype point\n")
        FILE.write("\tcolor { \"sRGB nonlinear\" %s %s %s }\n" %
                   (red, green, blue))
        FILE.write("\tpower %s\n" % (power))
        FILE.write("\tp %s %s %s\n" % (lampV[0], lampV[1], lampV[2]))
        FILE.write("}")
    elif lamp.type == 1:
        print "o exporting sun-light " + lmp.name + "..."
        invmatrix = Mathutils.Matrix(lmp.getInverseMatrix())
        FILE.write("\nlight {\n")
        FILE.write("\ttype sunsky\n")
        FILE.write("\tup 0 0 1\n")
        FILE.write("\teast 0 1 0\n")
        FILE.write("\tsundir %f %f %f\n" %
                   (invmatrix[0][2], invmatrix[1][2], invmatrix[2][2]))
        FILE.write("\tturbidity 6\n")
        FILE.write("\tsamples %s\n" % DSAMPLES.val)
        FILE.write("}")
    elif lamp.type == 4:
        print "o exporting area-light " + lmp.name + "..."
        objmatrix = lmp.matrix
        size = lamp.areaSizeX * 0.5
        lampV0 = Mathutils.Vector([-size, size, 0, 1])
        lampV1 = Mathutils.Vector([size, size, 0, 1])
        lampV2 = Mathutils.Vector([size, -size, 0, 1])
        lampV3 = Mathutils.Vector([-size, -size, 0, 1])

        lampV0 = lampV0 * objmatrix
        lampV1 = lampV1 * objmatrix
        lampV2 = lampV2 * objmatrix
        lampV3 = lampV3 * objmatrix

        red = lamp.col[0]
        green = lamp.col[1]
        blue = lamp.col[2]
        radiance = lamp.energy * MESHLIGHTPOWER.val

        FILE.write("\n\nlight {\n")
        FILE.write("\ttype meshlight\n")
        FILE.write("\tname \"%s\"\n" % (lmp.name))
        FILE.write("\temit { \"sRGB nonlinear\" %s %s %s }\n" %
                   (red, green, blue))
        FILE.write("\tradiance %s\n" % (radiance))
        FILE.write("\tsamples %s\n" % DSAMPLES.val)
        FILE.write("\tpoints 4\n")
        FILE.write("\t\t%s %s %s\n" % (lampV0[0], lampV0[1], lampV0[2]))
        FILE.write("\t\t%s %s %s\n" % (lampV1[0], lampV1[1], lampV1[2]))
        FILE.write("\t\t%s %s %s\n" % (lampV2[0], lampV2[1], lampV2[2]))
        FILE.write("\t\t%s %s %s\n" % (lampV3[0], lampV3[1], lampV3[2]))
        FILE.write("\ttriangles 2\n")
        FILE.write("\t\t0 1 2\n")
        FILE.write("\t\t0 2 3\n")
        FILE.write("}")
    def addObject(self, obj):  #adds a scene node.
        #print("add object %s" %(obj.getName()))
        node = None
        parentNode = self.scene
        if not obj.getParent() is None:
            #searching parent asuming it is already in i3d (must export ordered by hyrarchie)
            for sceneNode in self.scene.getElementsByTagName("Shape"):
                if sceneNode.getAttribute("name") == obj.getParent().getName():
                    parentNode = sceneNode
                    break
            if parentNode == self.scene:
                for sceneNode in self.scene.getElementsByTagName(
                        "TransformGroup"):
                    if sceneNode.getAttribute(
                            "name") == obj.getParent().getName():
                        parentNode = sceneNode
                        break
            if parentNode == self.scene:
                print("  parent not found!")
        rotX90 = 0

        if obj.type == "Mesh":
            #need armature parent data
            #parentArmBones holds the names of the bones and the i3d nodeId

            node = self.doc.createElement("Shape")
            shapeId, materialIds = self.addMesh(obj.getData(mesh=1),
                                                self.parentArmBones)
            #node.setAttribute("shapeId", "%i" %(shapeId))
            node.setAttribute("ref", "%s" % (obj.getData(mesh=1).name))

            if not self.parentArmBones is None:
                skinBindNodeIds = ""
                for pab in self.parentArmBones:
                    if skinBindNodeIds == "":
                        skinBindNodeIds = "%i" % (pab[1])
                    else:
                        skinBindNodeIds = "%s %i" % (skinBindNodeIds, pab[1])
                node.setAttribute("skinBindNodeIds", skinBindNodeIds)
                self.parentArmBones = None

            #shading propertys stored per object in giants: getting them from first blender material
            if len(obj.getData(mesh=1).materials) > 0:
                if obj.getData(mesh=1).materials[0]:
                    mat = obj.getData(mesh=1).materials[0]
                    if mat.getMode() & Material.Modes['SHADOWBUF']:
                        node.setAttribute("castsShadows", "true")
                    else:
                        node.setAttribute("castsShadows", "false")
                    if mat.getMode() & Material.Modes['SHADOW']:
                        node.setAttribute("receiveShadows", "true")
                    else:
                        node.setAttribute("receiveShadows", "false")
            else:
                node.setAttribute("castsShadows", "false")
                node.setAttribute("receiveShadows", "false")
        elif obj.type == "Empty":
            node = self.doc.createElement("TransformGroup")
        elif obj.type == "Armature":
            node = self.doc.createElement("TransformGroup")
            #self.parentArmBones = self.addArmature(node, obj.getData())
            #self.parentArmBones = self.addArmature(parentNode, obj.getData(), obj)
            self.parentArmBones = self.addArmature(node, obj.getData(), obj)
            #self.armaturesMap.append({0:obj.name, 1:self.parentArmBones})
        elif obj.type == "Camera":
            rotX90 = 1
            node = self.doc.createElement("Camera")
            node.setAttribute("fov", "%f" % (obj.getData().lens))
            node.setAttribute("nearClip", "%f" % (obj.getData().clipStart))
            node.setAttribute("farClip", "%f" % (obj.getData().clipEnd))
        elif obj.type == "Lamp":
            rotX90 = 1
            node = self.doc.createElement("Light")
            lamp = obj.getData()
            lampType = ["point", "directional", "spot", "ambient"]
            if lamp.getType() > 3:
                node.setAttribute("type", lampType[0])
                print("WARNING: lamp type not supported")
            else:
                node.setAttribute("type", lampType[lamp.getType()])
            node.setAttribute(
                "diffuseColor",
                "%f %f %f" % (lamp.R * lamp.energy, lamp.G * lamp.energy,
                              lamp.B * lamp.energy))
            node.setAttribute("emitDiffuse", "true")
            node.setAttribute(
                "specularColor",
                "%f %f %f" % (lamp.R * lamp.energy, lamp.G * lamp.energy,
                              lamp.B * lamp.energy))
            node.setAttribute("emitSpecular", "true")
            node.setAttribute("decayRate", "%f" % (5000 - lamp.getDist()))
            node.setAttribute("range", "500")
            if lamp.getMode() & lamp.Modes['Shadows']:
                node.setAttribute("castShadowMap", "true")
            else:
                node.setAttribute("castShadowMap", "false")
            node.setAttribute("depthMapBias", "%f" % (lamp.bias / 1000))
            node.setAttribute("depthMapResolution", "%i" % lamp.bufferSize)
            node.setAttribute("coneAngle", "%f" % (lamp.getSpotSize()))
            node.setAttribute("dropOff", "%f" %
                              (lamp.getSpotBlend() *
                               5))  #dropOff seems to be between 0 and 5 right?

        if not node is None:
            node.setAttribute("name", obj.getName())
            #self.lastNodeId = self.lastNodeId + 1
            #node.setAttribute("nodeId", "%i" %(self.lastNodeId))

            # getLocation("localspace") seems to be buggy!
            # http://blenderartists.org/forum/showthread.php?t=117421
            localMat = Mathutils.Matrix(obj.matrixLocal)
            #self.setTranslation(node, obj.getLocation("localspace"))
            self.setTranslation(node, localMat.translationPart())
            #self.setRotation(node, localMat.rotationPart().toEuler(), rotX90)
            self.setRotation(node, obj.getEuler("localspace"), rotX90)
            parentNode.appendChild(node)

            #Todo....
            #Export the animations, assuming obj is an armature, hopefully it will also work with objects
            #only the active action (=clip) is exported
            """
			action = obj.getAction()
			if not action is None:
				print("exporting animation: "+action.getName())
				animSet = self.doc.createElement("AnimationSet")
				animSet.setAttribute("name", obj.getName())#AnimationSets are equivalent to blenders NLA, only one per object
				
				clip = self.doc.createElement("Clip")
				clip.setAttribute("name", action.getName())
				print self.parentArmBones
				print action.getFrameNumbers()#the keyframes (would be nice to have them per channel)
				for channel in action.getChannelNames():
					print " "+channel
					key_NodeId = self.lastNodeId
					if not self.parentArmBones is None:
						for nameId in self.parentArmBones:
							if nameId[0] == channel:
								key_NodeId = nameId[1]
					keyframes = self.doc.createElement("Keyframes")
					keyframes.setAttribute("nodeId", "%i"%key_NodeId)
					
					ipo = action.getChannelIpo(channel)
					for curve in ipo:
						print "  "+curve.name
						for bezTri in curve.bezierPoints:
							time, value = bezTri.pt
						#ohoh, now the rotation would have to be calculated from Quats...
						
						#another aproach would be to set the time of the global timeline to the keyframe times
						#and then get the data from the object.getPose() which returns the current pose. (probably eazyer, but might result in redundant data)
						
					clip.appendChild(keyframes)
				#clip.setAttribute("duration", 
				animSet.appendChild(clip)
				#print("chanels: ")
				#print(action.getChannelNames())
				
				self.animationSets.appendChild(animSet)
			"""

            #parse ScriptLink file and merge xml into i3d
            for sl in obj.getScriptLinks("FrameChanged") + obj.getScriptLinks(
                    "Render"
            ) + obj.getScriptLinks("Redraw") + obj.getScriptLinks(
                    "ObjectUpdate") + obj.getScriptLinks("ObDataUpdate"):
                if sl.endswith(".i3d"):
                    xmlText = ""
                    #print Text.Get(sl).asLines()
                    for l in Text.Get(sl).asLines():
                        #print l.replace("i3dNodeId", "%i" %self.lastNodeId)
                        xmlText = xmlText + l.replace("i3dNodeId",
                                                      "%i" % self.lastNodeId)
                    #print "xml: ",xmlText
                    #slDom = parseString(xmlText)
                    slDom = None
                    try:
                        slDom = parseString(xmlText)
                    except:
                        print "WARNING: cant parse %s" % sl
                    if not slDom is None:
                        for ua in slDom.getElementsByTagName("UserAttribute"):
                            self.userAttributes.appendChild(ua)

                        for st in slDom.getElementsByTagName("SceneType"):
                            i = 0
                            while i < st.attributes.length:
                                attr = st.attributes.item(i)
                                node.setAttribute(attr.nodeName,
                                                  attr.nodeValue)
                                i = i + 1
        else:
            print "WARNING: cant export ", obj.type, ": ", obj.getName()
Exemple #22
0
def export(filename):


    out = file(filename,'wb+')
    scene = bpy.data.scenes.active
    Objects = scene.objects    
    
    ints = array('i')
    
    ints.append(ObjectCount(Objects, 'Mesh'))
    ints.tofile(out)
    ints.pop
    
    for ob in Objects:
        if (ob.getType()== 'Mesh'):
            mesh = ob.getData()

            ExportGeometry(mesh, out)

            if (ob.parent != None):
                parent = ob.parent

                if (parent.getType() == 'Armature'):
                    ArmatureData = parent.getData()

                    RootBone = getRootBone(ArmatureData)
                    print 'root bone name is:' + RootBone.name
                    PrintBones(RootBone)
                    WriteBoneTree(RootBone, mesh, out)

                    Bones = ArmatureData.bones
                    BoneData = Bones.values()
                    

                    totalFrames = Blender.Get("endframe") -\
                                  Blender.Get("staframe") + 1

                    framec = array('i')
                    framec.append(totalFrames)
                    framec.tofile(out)
                    framec.pop


                    for bone in BoneData:
                        bnameLen = array('i')
                        bnameLen.append(len(bone.name))
                        bnameLen.tofile(out)
                        bname = array('c')
                        bname.fromstring(bone.name)
                        print '-----------------------------'
                        print bname
                        bname.tofile(out)

                        floats = array('f')
                        floats.append(bone.head['ARMATURESPACE'].x)
                        floats.append(bone.head['ARMATURESPACE'].y)
                        floats.append(bone.head['ARMATURESPACE'].z)

                        floats.append(bone.tail['ARMATURESPACE'].x)
                        floats.append(bone.tail['ARMATURESPACE'].y)
                        floats.append(bone.tail['ARMATURESPACE'].z)
                        floats.tofile(out)

                        print "--------------------------"
                        m = Mathutils.Matrix(bone.matrix['ARMATURESPACE'])
                        m = m.invert()
                        fm = array('f')
                        for a in range(4):
                                for b in range(4):
                                    fm.append(m[a][b])
                        fm.tofile(out)
                        print "Euler values:"
                        print matrixToEuler(m)
                        print "translation:"
                        print vector_by_matrix(m, Mathutils.Vector( [ 0, 0, 0 ] ))
                        print "----------------------------"


                        for i in range(Blender.Get("staframe"),Blender.Get("endframe")+1):
                            exportFrame(parent, i, bone, out)
                          
                        #for each frame

                #if armature
    out.close()
Exemple #23
0
def writeLamp(o, obj):
    lamp = obj.getData()

    objmatrix = obj.matrix
    lampV = Mathutils.Vector([0, 0, 0, 1])
    lampV = lampV * objmatrix

    p = lamp.energy
    red = lamp.r * p
    green = lamp.b * p
    blue = lamp.b * p
    rgb = (red, green, blue)

    if lamp.getType() == Lamp.Types.Lamp:
        o.write("# point lamp %s\n" % str(lamp))
        o.write("light {\n")
        o.write("   point\n")
        o.write("   intensity rgb %f %f %f\n" % rgb)
        o.write("   position %f %f %f\n" % (lampV[0], lampV[1], lampV[2]))
        o.write("}\n")

    elif lamp.getType() == Lamp.Types.Area:
        o.write("# area lamp " + str(dir(lamp)) + "\n")

        # first emission spectrum

        o.write("emission { rgb %f %f %f }\n" % rgb)

        # then geometry
        xsize = lamp.areaSizeX * 0.5

        if lamp.areaSizeY:
            ysize = lamp.areaSizeY * 0.5
        else:
            ysize = xsize

        lampV0 = Mathutils.Vector([-xsize, ysize, 0, 1])
        lampV1 = Mathutils.Vector([xsize, ysize, 0, 1])
        lampV2 = Mathutils.Vector([xsize, -ysize, 0, 1])
        lampV3 = Mathutils.Vector([-xsize, -ysize, 0, 1])

        lampV0 = lampV0 * objmatrix
        lampV1 = lampV1 * objmatrix
        lampV2 = lampV2 * objmatrix
        lampV3 = lampV3 * objmatrix

        o.write("shape {\n")
        o.write("   mesh\n")
        o.write("   vertexCount 4\n")
        o.write("   faceCount 1\n")
        o.write("   v %f %f %f\n" % (lampV0[0], lampV0[1], lampV0[2]))
        o.write("   v %f %f %f\n" % (lampV1[0], lampV1[1], lampV1[2]))
        o.write("   v %f %f %f\n" % (lampV2[0], lampV2[1], lampV2[2]))
        o.write("   v %f %f %f\n" % (lampV3[0], lampV3[1], lampV3[2]))
        o.write("   f 3 2 1 0\n")
        o.write("}\n")

        # and turn off emission for remaining gemoetry

        o.write("emission { none }\n")

    elif lamp.getType() == Lamp.Types.Sun:
        o.write("# Sun Lamp %s\n" % str(lamp))
        o.write("light {\n")
        o.write("   directional\n")
        o.write("   intensity rgb %f %f %f\n" % rgb)
        im = Mathutils.Matrix(obj.getInverseMatrix())
        o.write("   normal %f %f %f\n" % (im[0][2], im[1][2], im[2][2]))
        o.write("}\n")

    else:
        o.write("# unsupported lamp type " + str(lamp.getType()) + "\n")