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

# node flags
node_flags = {'textures': 1, 'brushes': 1, 'meshes': 1, 'bones': 1, 'animations': 1, 'timeline': 0}

#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)

def write_chunk(name,value):
    return name + write_int(len(value)) + value
Beispiel #2
0
def vectors_on_same_side(v1, v2):
    # checks if the vec are on the same side of a ball. expects that v1
    # and v2 have been normalized already
    return math.acos(Mathutils.DotVecs(v1, v2)) < math.pi
Beispiel #3
0
def calcArc(center, radius, start, end, arc_res, triples):
    """calculate Points (or BezierTriples) for ARC/CIRCLEs representation.
	
	Given parameters of the ARC/CIRCLE,
	returns points/segments (or BezierTriples) and centerPoint
	"""
    # center is currently set by object
    # if start > end: start = start - 360
    if end > 360: end = end % 360.0

    startmatrix = Mathutils.RotationMatrix(-start, 3, "Z")
    startpoint = startmatrix * Mathutils.Vector(radius, 0, 0)
    endmatrix = Mathutils.RotationMatrix(-end, 3, "Z")
    endpoint = endmatrix * Mathutils.Vector(radius, 0, 0)

    if end < start: end += 360.0
    angle = end - start
    #length = radians(angle) * radius

    if not triples:  #IF mesh-representation -----------
        print 'mesh-representation\n'
        if arc_res > 1024: arc_res = 1024
        elif arc_res < 4: arc_res = 4
        pieces = int(abs(angle) /
                     (360.0 / arc_res))  # set a fixed step of ARC_RESOLUTION
        if pieces < 3: pieces = 3
        step = angle / pieces  # set step so pieces * step = degrees in arc
        stepmatrix = Mathutils.RotationMatrix(-step, 3, "Z")

        points = [startpoint]
        point = startpoint
        for i in xrange(int(pieces) - 1):
            point = stepmatrix * point
            points.append(point)
        points.append(endpoint)

        if center:
            centerVec = Mathutils.Vector(center)
            #points = [point + centerVec for point in points()]
            points = [point + centerVec for point in points]
        # vector to point convertion:
        points = [list(point) for point in points]
        return points

    else:  #IF curve-representation ---------------
        if arc_res > 32: arc_res = 32
        elif arc_res < 3: arc_res = 3
        pieces = int(abs(angle) /
                     (360.0 / arc_res))  # set a fixed step of ARC_RESOLUTION
        if pieces < 2: pieces = 2
        step = angle / pieces  # set step so pieces * step = degrees in arc
        stepmatrix = Mathutils.RotationMatrix(-step, 3, "Z")

        # correct Bezier curves representation for free segmented circles/arcs
        step2 = radians(step * 0.5)
        bulg = radius * (1 - cos(step2))
        deltaY = 4.0 * bulg / (3.0 * sin(step2))
        print 'deb:calcArcCurve: bulg, deltaY:\n', bulg, deltaY  #---------
        print 'deb:calcArcCurve: step:\n', step  #---------
        handler0 = Mathutils.Vector(0.0, -deltaY, 0.0)

        points = [startpoint]
        handler = startmatrix * handler0
        endhandler = endmatrix * handler0
        handlers1 = [startpoint + handler]
        handlers2 = [startpoint - handler]
        point = Mathutils.Vector(startpoint)
        for i in xrange(int(pieces) - 1):
            point = stepmatrix * point
            handler = stepmatrix * handler
            handler1 = point + handler
            handler2 = point - handler
            points.append(point)
            handlers1.append(handler1)
            handlers2.append(handler2)
        points.append(endpoint)
        handlers1.append(endpoint + endhandler)
        handlers2.append(endpoint - endhandler)
        VectorTriples = [
            list(h1) + list(p) + list(h2)
            for h1, p, h2 in zip(handlers1, points, handlers2)
        ]
        print 'deb:calcArcCurve: handlers1:\n', handlers1  #---------
        print 'deb:calcArcCurve: points:\n', points  #---------
        print 'deb:calcArcCurve: handlers2:\n', handlers2  #---------
        print 'deb:calcArcCurve: VectorTriples:\n', VectorTriples  #---------
        return VectorTriples
Beispiel #4
0
    def animatedensity(self, filenamelist, renderingpath, isovalue):
        context = self.scene.getRenderingContext()
        context.extensions = True
        context.renderPath = renderingpath
        #context.imageType=Render.JPEG
        context.sFrame = 1
        context.eFrame = 1
        context.sizeX = width
        context.sizeY = height

        cubeobject = cube(filenamelist[0])
        cubeobject.readCube()
        atoms = []
        ipokeytypeloc = Object.IpoKeyTypes.LOC
        ipokeytyperot = Object.IpoKeyTypes.ROT
        for i in range(len(cubeobject.atomtypes)):
            me = Mesh.Primitives.Icosphere(
                spheresubdivisions,
                atomicradii.get(cubeobject.atomtypes[i], 2.0))
            me.materials = [
                materials.get(cubeobject.atomtypes[i], materials["default"])
            ]
            for face in me.faces:
                face.smooth = True
            obj = self.scene.objects.new(me, 'Atom')
            obj.setLocation(cubeobject.coord[i][0], cubeobject.coord[i][1],
                            cubeobject.coord[i][2])
            atoms.append(obj)

        bonds = []
        for i in range(len(cubeobject.atomtypes)):
            for j in range(i + 1, len(cubeobject.atomtypes)):
                vec1 = Mathutils.Vector(cubeobject.coord[i])
                vec2 = Mathutils.Vector(cubeobject.coord[j])
                vec = vec2 - vec1
                distcovalent = covalentradii.get(
                    cubeobject.atomtypes[i], 2.0) + covalentradii.get(
                        cubeobject.atomtypes[j], 2.0)
                if (vec.length - distcovalent) <= 0.10 * distcovalent:
                    me = Mesh.Primitives.Tube(32, stickradius, vec.length)
                    for face in me.faces:
                        face.smooth = True
                    obj = self.scene.objects.new(me, 'Cylinder')
                    axis = Mathutils.CrossVecs(Vector([0, 0, 1]), vec)
                    angle = Mathutils.AngleBetweenVecs(Vector([0, 0, 1]), vec)
                    rotmat = Mathutils.RotationMatrix(angle, 4, "R", axis)
                    obj.setMatrix(obj.matrix * rotmat)
                    obj.setLocation((vec1 + vec2) * 0.5)
                    bonds.append([i, j, vec, obj, vec.length])
        self.isosurface(cubeobject, isovalue)
        context.render()
        filename = "RENDER/image_0000.jpg"
        context.saveRenderedImage(filename)

        for j in range(1, len(filenamelist)):
            print "Rendering:", j
            filename = "RENDER/image_%04d.jpg" % (j)
            for ob in self.scene.objects:
                if "Lobe" in ob.name:
                    self.scene.unlink(ob)
            cubeobject = cube(filenamelist[j])
            cubeobject.readCube()
            for i in range(len(atoms)):
                atoms[i].setLocation(cubeobject.coord[i][0],
                                     cubeobject.coord[i][1],
                                     cubeobject.coord[i][2])
                atoms[i].insertIpoKey(ipokeytypeloc)
            for i in range(len(bonds)):
                vec1 = Mathutils.Vector(cubeobject.coord[bonds[i][0]])
                vec2 = Mathutils.Vector(cubeobject.coord[bonds[i][1]])
                vec = vec2 - vec1
                dist = vec.length
                axis = Mathutils.CrossVecs(bonds[i][2], vec)
                angle = Mathutils.AngleBetweenVecs(bonds[i][2], vec)
                rotmat = Mathutils.RotationMatrix(angle, 4, "R", axis)
                bonds[i][3].setMatrix(bonds[i][3].matrix * rotmat)
                bonds[i][3].setLocation((vec1 + vec2) * 0.5)
                bonds[i][3].setSize(1.0, 1.0, dist / bonds[i][4])
                bonds[i][3].insertIpoKey(ipokeytypeloc)
                bonds[i][3].insertIpoKey(ipokeytyperot)
                bonds[i][2] = vec
                bonds[i][4] = dist
            self.isosurface(cubeobject, isovalue)
            context.render()
            context.saveRenderedImage(filename)
def write_mesh(file, scn, exp_list, matTable, total):
    print "Write Geometric"

    for current_container in exp_list:

        TransTable = {'SizeX': 1, 'SizeY': 1, 'SizeZ': 1}
        nameMe = {'objName': 'obj', 'meName': 'me'}
        sGroups = {}
        hasTable = {
            'hasMat': 0,
            'hasSG': 0,
            'hasUV': 0,
            'hasVC': 0,
            'matRef': 0
        }
        count = {'face': 0, 'vert': 0, 'UVs': 0, 'cVert': 0}

        obj = current_container[0]
        #mat_ref = current_container[1]
        data = obj.getData(0, 1)
        nameMe['objName'] = obj.name
        nameMe['meName'] = data.name

        mats_me = [
            mat for mat in data.materials if mat
        ]  #fix for 2.44, get rid of NoneType Objects in me.materials
        mats_ob = obj.getMaterials(0)
        materials = False

        if mats_me:
            materials = mats_me
        elif mats_ob:
            materials = mats_ob

        if guiTable['MTL'] and materials:
            hasTable['hasMat'] = 1
            hasTable['matRef'] = current_container[1]

        if obj.getParent():
            nameMe['parent'] = obj.getParent().name

        me = Mesh.New()  # Create a new mesh

        if guiTable['MOD']:  # Use modified mesh
            me.getFromObject(
                obj.name, 0)  # Get the object's mesh data, cage 0 = apply mod
        else:
            me.getFromObject(obj.name, 1)

        me.transform(obj.matrix)  # ASE stores transformed mesh data
        if guiTable['RECENTER']:  # Recentre Objects to 0,0,0 feature
            rec_matrix = Mathutils.TranslationMatrix(
                obj.matrix.translationPart().negate())
            me.transform(rec_matrix)

        tempObj = Blender.Object.New('Mesh', 'ASE_export_temp_obj')
        tempObj.setMatrix(obj.matrix)
        tempObj.link(me)

        if guiTable['VG2SG']:
            VGNames = data.getVertGroupNames()
            for vg in VGNames:
                me.addVertGroup(vg)
                gverts = data.getVertsFromGroup(vg, 1)
                gverts_copy = []
                for gv in gverts:
                    gverts_copy.append(gv[0])
                me.assignVertsToGroup(vg, gverts_copy, 1, 1)

        obj = tempObj
        faces = me.faces
        verts = me.verts

        count['vert'] = len(verts)
        total['Verts'] += count['vert']

        if count['vert'] == 0:
            print 'Error: ' + nameMe['meName'] + 'has 0 Verts'
            continue

        vGroups = me.getVertGroupNames()
        if guiTable['VG2SG'] and len(vGroups) > 0:
            for current_VG in vGroups:
                if current_VG.lower().count("smooth."):
                    hasTable['hasSG'] = 1
                    smooth_num = int(current_VG.lower().replace("smooth.", ""))
                    gverts = me.getVertsFromGroup(current_VG)
                    for vi in gverts:
                        if not sGroups.has_key(vi):
                            sGroups[vi] = [smooth_num]
                        else:
                            sGroups[vi].append(smooth_num)

        if guiTable['UV']:
            if me.faceUV == True or me.faceUV == 1:
                hasTable['hasUV'] = 1

        if guiTable['VC']:
            if me.vertexColors:
                hasTable['hasVC'] = 1
            elif hasTable['hasMat']:  # Blender material
                for current_mat in materials:
                    if current_mat.getMode() & Material.Modes['VCOL_PAINT']:
                        hasTable['hasVC'] = 1
                        break

        for current_face in faces:
            if len(current_face.verts) is 3:
                count['face'] += 1
                total['Tris'] += 1
                total['Faces'] += 1
            elif len(current_face.verts) is 4:
                count['face'] += 2
                total['Tris'] += 2
                total['Faces'] += 1

        #Open Geomobject
        file.write("*GEOMOBJECT {\n")
        file.write("%s*NODE_NAME \"%s\"\n" % (Tab, nameMe['objName']))

        if nameMe.has_key('parent'):
            file.write("%s*NODE_PARENT \"%s\"\n" % (Tab, nameMe['parent']))

        idnt = 1
        mesh_matrix(file, idnt, obj, nameMe, TransTable)

        #Open Mesh
        file.write("%s*MESH {\n" % (Tab))

        idnt = 2
        file.write("%s*TIMEVALUE 0\n" % (Tab * idnt))
        file.write("%s*MESH_NUMVERTEX %i\n" % ((Tab * idnt), count['vert']))
        file.write("%s*MESH_NUMFACES %i\n" % ((Tab * idnt), count['face']))

        idnt = 2
        mesh_vertexList(file, idnt, verts, count)
        idnt = 2
        mesh_faceList(file, idnt, me, materials, sGroups, faces, matTable,
                      hasTable, count)

        if hasTable['hasUV'] == 1:
            UVTable = {}

            active_map_channel = me.activeUVLayer
            map_channels = me.getUVLayerNames()

            idnt = 2
            mesh_tVertList(file, idnt, faces, UVTable, count)
            #idnt = 2
            mesh_tFaceList(file, idnt, faces, UVTable, count)
            UVTable = {}

            if len(map_channels) > 1:
                chan_index = 2
                for map_chan in map_channels:
                    if map_chan != active_map_channel:
                        me.activeUVLayer = map_chan

                        idnt = 2
                        file.write("%s*MESH_MAPPINGCHANNEL %i {\n" %
                                   ((Tab * idnt), chan_index))
                        idnt = 3
                        mesh_tVertList(file, idnt, faces, UVTable, count)
                        mesh_tFaceList(file, idnt, faces, UVTable, count)
                        UVTable = {}
                        chan_index += 1
                        idnt = 2
                        file.write("%s}\n" % (Tab * idnt))

            me.activeUVLayer = active_map_channel

        else:
            # dirty fix
            file.write("%s*MESH_NUMTVERTEX %i\n" %
                       ((Tab * idnt), count['UVs']))

        if hasTable['hasVC'] == 1:
            cVertTable = {}

            idnt = 2
            mesh_cVertList(file, idnt, faces, cVertTable, count)
            #idnt = 2
            mesh_cFaceList(file, idnt, faces, cVertTable, count)
        else:
            # dirty fix
            file.write("%s*MESH_NUMCVERTEX %i\n" %
                       ((Tab * idnt), count['cVert']))

        idnt = 2
        mesh_normals(file, idnt, faces, verts, count)

        # Close *MESH
        idnt = 1
        file.write("%s}\n" % (Tab * idnt))

        idnt = 1
        mesh_footer(file, idnt, hasTable)

        # Close *GEOMOBJECT
        file.write("}\n")

        #free some memory
        me.materials = [None]
        me.faces.delete(1, [(f.index) for f in me.faces])
        me.verts.delete(me.verts)
        obj.fakeUser = False
        me.fakeUser = False
        scn.objects.unlink(obj)