Esempio n. 1
0
	def endDocument(self):
		"""
			Invoked when mesh processing is done. Used for realizing
			the mesh from collected vertex/faces and texturizing info.
		"""
		# report
		print("Finished loading file, constructing mesh...")
		Blender.Window.DrawProgressBar(0.9, "Building mesh...")
		# build object
		meshtools.create_mesh(self.verts, self.faces, self.objName, self.faceuvs, self.uvs)
		print("Done, object built")
		# load corresponding images and set texture
		Blender.Window.DrawProgressBar(0.95, "Loading/Applying Texture...")
		colorTex, specTex = None, None
		# convert images into textures
		if self.colorTexture:
			colTexFName		= FindTexture(self.path, self.colorTexture)
			if colTexFName != None:
				colorImg		= Image.Load(colTexFName)
				colorTex		= Texture.New(self.objName + ".col.tx")
				colorTex.type	= Texture.Types.IMAGE
				colorTex.image	= colorImg
		if self.specTexture:
			specTexFName	= FindTexture(self.path, self.specTexture)
			if specTexFName != None:
				specImg			= Image.Load(specTexFName)
				specTex			= Texture.New(self.objName + ".spe.tx")
				specTex.type	= Texture.Types.IMAGE
				specTex.image	= specImg
		# make material with them and all other previously collected data
		mat = Material.New(self.objName + ".mat")
		mat.mode		|= Material.Modes.TEXFACE | Material.Modes.SHADOW | Material.Modes.TRACEABLE | Material.Modes.ZTRANSP
		mat.specTransp	= 1.0
		if self.alpha	: mat.alpha		= self.alpha
		if self.rgbCol	: mat.rgbCol	= self.rgbCol
		if self.amb		: mat.amb		= self.amb
		if self.emit	: mat.emit		= self.emit
		if self.spec	: mat.spec		= self.spec
		if self.specCol	: mat.specCol	= self.specCol
		if colorTex:
			mat.setTexture(0, colorTex, Texture.TexCo.UV, Texture.MapTo.COL)
		if specTex:
			mat.setTexture(1, specTex, Texture.TexCo.UV, Texture.MapTo.SPEC)
		# apply to mesh
		obj = Object.Get(self.objName)
		mesh = obj.data
		# mesh.mode = NMesh.Modes.NOVNORMALSFLIP
		# uncomment the following if you want models automatically sub-surfaced
		"""for currFace in mesh.faces:
			currFace.smooth = 1
		mesh.setSubDivLevels([1,2])
		mesh.setMode("SubSurf", "TwoSided")"""
		mesh.setMode("TwoSided")
		mesh.addMaterial(mat)
		mesh.update(1)
		# Done, notify user
		Blender.Window.DrawProgressBar(1.0, "Done.")
Esempio n. 2
0
def dodialog(newname):
    global newimage, newsize, offsets, rows, cols

    try:
        newimage = Image.Load(newname)
        newsize = newimage.getSize()
    except:
        Draw.PupMenu("Can't read image %s" % newname)
        return

    if newsize[0] == oldsize[0] and newsize[1] == oldsize[1]:
        # same size, just replace
        doapply(0, 0)
        return
    elif newsize[0] < oldsize[0] or newsize[1] < oldsize[1]:
        Draw.PupMenu("The new image must be larger than the old image")
        return
    else:
        if newsize[0] % oldsize[0] == 0:
            xoffs = range(0, newsize[0], oldsize[0])
        else:
            xoffs = [0, newsize[0] - oldsize[0]]
        if newsize[1] % oldsize[1] == 0:
            yoffs = range(newsize[1] - oldsize[1], -oldsize[1], -oldsize[1])
        else:
            yoffs = [newsize[1] - oldsize[1], 0]
        for i in yoffs:
            for j in xoffs:
                offsets.append((j, i))
        cols = len(xoffs)
        rows = len(yoffs)
        Draw.Register(gui, event, bevent)
Esempio n. 3
0
def draw():
    global as_package_name
    global fileButton, expFileName
    global engine_menu, engine_name
    global EVENT_NOEVENT, EVENT_DRAW, EVENT_EXIT, EVENT_EXPORT
    global export_all
    expFileName = ""
    ########## Titles
    glClear(GL_COLOR_BUFFER_BIT)
    glRasterPos2i(40, 240)

    logoImage = Image.Load(Get('scriptsdir') + sys.sep + 'AS3Export.png')
    Draw.Image(logoImage, 40, 155)

    as_package_name = Draw.String("Package name: ", EVENT_NOEVENT, 40, 130,
                                  250, 20, as_package_name.val, 300)
    engine_name = "Away3D%x1|Away3D 2.1.0%x5|Away3D 2.2.0%x6|Papervision3D%x2|Papervision3D 2.0%x3|Sandy 3.0%x4"
    engine_menu = Draw.Menu(engine_name, EVENT_NOEVENT, 40, 100, 200, 20,
                            engine_menu.val, "Choose your engine")

    fileButton = Draw.String('File location: ', EVENT_NOEVENT, 40, 70, 250, 20,
                             fileButton.val, 255)
    Draw.PushButton('...', EVENT_BROWSEFILE, 300, 70, 30, 20, 'browse file')
    export_all = Draw.Toggle('Export ALL scene objects', EVENT_NOEVENT, 40, 45,
                             200, 20, 0)
    ######### Draw and Exit Buttons
    Draw.Button("Export", EVENT_EXPORT, 40, 20, 80, 18)
    Draw.Button("Exit", EVENT_EXIT, 140, 20, 80, 18)
Esempio n. 4
0
def createImage(fn):
    try:
        img = Image.Load(fn)
    except:
        return (None)

    return (img)
Esempio n. 5
0
def load_image(root_dir, file_name):
    file_path = find_file_path(root_dir, file_name)
    
    if file_path:
        return Image.Load(file_path)
    
    try:
        return Image.Get(file_name)
    except:
        pass
Esempio n. 6
0
    def _pil_im_to_blender_disk(self, im):
        im, ext = get_image_extension(im)

        temporary_image = TempFile(ext)
        self.temporary_images.append(temporary_image)

        im.save(temporary_image.path)

        ret_im = Image.Load(temporary_image.path)

        return ret_im
Esempio n. 7
0
 def make_image(self, root):
     fullpath = root + '/' + self.tex
     if not os.path.exists(fullpath):
         fullpath = fullpath[:-3] + 'dds'
     if not os.path.exists(fullpath):
         fullpath = fullpath[:-3] + 'png'
     print "Will load image %s" % fullpath
     img = Image.Load(fullpath)
     mat = Material.New(self.name)
     tex = Texture.New(self.name)
     tex.setImage(img)
     mat.setTexture(0, tex)
     self.material = mat
Esempio n. 8
0
  def bitmap(file, words, data):
    global filename
    imagefname=os.path.dirname(filename) + '\\' + words[1]+'.tga'
    try:
      image=Image.Get(imagefname)
    except NameError:
      try:
	image=Image.Load(imagefname)
      except IOError:
        print '**************ERROR********************'
        print 'file : ' + filename
        print 'texture : ' + words[1]+'.tga unknown in directory : '
        print os.path.dirname(filename)
        print 'check if the bitmap exists with an other extension => translate in tga format'
        print 'or move it in the directory of the .mdl model'
        print 'null.tga could be used instead of the current one'
        print '**************ERROR********************'
        imagefname=os.path.dirname(filename) + '\\null.tga'
        image=Image.Load(imagefname)
        pass
    data['nwnprops'].write('%s.texture=%s\n'%(data['object'].name, words[1]))
    data['texture']=image
Esempio n. 9
0
def findTex(basefile, texture, subdirs):
    texdir = basefile
    for l in range(PanelRegionHandler.REGIONCOUNT + 1):
        q = texdir[:-1].rfind(Blender.sys.dirsep)
        if q == -1:
            return
        texdir = texdir[:q + 1]

        for subdir in subdirs:
            # Handle empty subdir
            if subdir:
                sd = subdir + Blender.sys.dirsep
            for extension in ['.dds', '.DDS', '.png', '.PNG', '.bmp', '.BMP']:
                try:
                    return Image.Load(texdir + sd + texture + extension)
                except IOError:
                    pass
    return None
Esempio n. 10
0
    def execute(self, input_image_path, blender_object):
        im = Image.Load(input_image_path)

        im_width, im_height = im.getSize()
        im_size_ratio = im_width / im_height

        tex_width = blender_object.texface.width
        tex_height = blender_object.texface.height
        tex_size_ratio = tex_width / tex_height

        ob = Object.Get(blender_object.name).getParent()
        if tex_size_ratio > im_size_ratio:
            # scale width
            scaling_ratio = im_size_ratio / tex_size_ratio
            ob.SizeY *= scaling_ratio
        else:
            # scale height
            scaling_ratio = tex_size_ratio / im_size_ratio
            ob.SizeZ *= scaling_ratio

        return im
Esempio n. 11
0
def loadTGARAW(fileName):
    """
	Loads a RAW TGA image from a file.  On success, the method
	returns: (image, imagebuffer).  On failure, the method
	returns None.
	
	@param filename: Name of the RAW TGA file to load.
	
	@return: (image, imagebuffer) 2-tuple on success, or None
	         on failure.
	"""

    # create the image and allocate the image buffer using
    #  Blender's own methods
    image = Image.Load(fileName)
    #ibuf = BGL.Buffer(BGL.GL_BYTE, (image.size[1], image.size[0], 4))

    ## read in the file
    #infile = open(fileName, 'rb')
    #array = map(ord, infile.read())
    #infile.close()

    ## check the validity of the file and offset the data
    ##  array to the start of the image data
    #if array[2] is not 2:
    #	menuError('Can only load RAW TGA images.')
    #	return None
    #array = array[(18+array[0]):]

    # read the array into the image buffer
    #index = 0
    #for y in range(0, image.size[1]):
    #	for x in range(0, image.size[0]):
    #		ibuf[y][x][2] = array[index]
    #		ibuf[y][x][1] = array[index+1]
    #		ibuf[y][x][0] = array[index+2]
    #		index += 3

    # return the (image, imagebuffer) tuple
    return (image, )
Esempio n. 12
0
def setTex(ob):
    scn = Scene.GetCurrent()  # link object to current scene
    #ob = scn.objects.get('myObj')
    mat = Material.New('myMat')
    mat.rgbCol = [0.9, 0.9, 0.9]

    footex = Texture.New('footex')
    footex.setType('Image')
    img = Image.Load('/tmp/t-XXXXXXXX.tga')
    footex.image = img
    #mat.tex.type = Texture.Types.IMAGE

    mat.setTexture(0, footex)
    for potential_ob in scn.objects:
        if potential_ob.name == 'myObj':
            ob = potential_ob
            break
    ob.setMaterials([mat])
    ob.colbits = 1
    print 'I did what you asked me to!'
    for ob in scn.objects:
        print ob.name
Esempio n. 13
0
def gettexture(name, dirname, filename):
    (filename,ext)=splitext(basename(filename).lower())
    img=None
    for d in [dirname, normpath(join(dirname, pardir, 'texture'))]:
        for e in ['.png', '.psd', '.jpg', '.jpeg', '.tga', '.bmp', '.dds',ext]:
            try:
                img=Image.Load(join(d,filename+e))
                img.getSize()	# force attempt to load image
                break
            except:
                pass
        else:
            continue

    # Re-use existing
    for tex in Texture.Get():
        if tex.name.startswith(name) and tex.type==Texture.Types.IMAGE and tex.image==img:
            return tex

    tex=Texture.New(name)
    tex.type=Texture.Types.IMAGE
    if img: tex.image=img

    return tex
Esempio n. 14
0
		def load_image(name):
			try:
				return Image.Load(Blender.sys.join(my_path,name))
			except:
				return None
Esempio n. 15
0
 def execute(self, input_image_path, blender_object):
     return Image.Load(input_image_path)
Esempio n. 16
0
    def testAC3DImport(self):

        FACE_TWOSIDE = Mesh.FaceModes['TWOSIDE']
        FACE_TEX = Mesh.FaceModes['TILES']
        #FACE_TEX = Mesh.FaceModes['TEX']
        MESH_AUTOSMOOTH = Mesh.Modes['AUTOSMOOTH']

        MAT_MODE_ZTRANSP = Material.Modes['ZTRANSP']
        MAT_MODE_TRANSPSHADOW = Material.Modes['TRANSPSHADOW']

        scene = self.scene

        bl_images = {}  # loaded texture images
        missing_textures = []  # textures we couldn't find
        bl_textures = {}  # loaded textures

        objlist = self.objlist[1:]  # skip 'world'

        #bmat = []
        bmat = {}
        m = None
        has_transp_mats = False
        for mat in self.mlist:
            name = mat[0]
            #			if name=='':
            name = 'BaseMaterial'
            if m == None:
                m = Material.New(name)

            m.rgbCol = (mat[1][0], mat[1][1], mat[1][2])
            m.amb = mat[2]
            m.emit = mat[3]
            m.specCol = (mat[4][0], mat[4][1], mat[4][2])
            m.spec = mat[5]
            m.alpha = mat[6]
            #force it to zero because that is how Speed Dreams / Torcs work
            m.alpha = 0.0
            if m.alpha < 1.0:
                m.mode |= MAT_MODE_ZTRANSP
                has_transp_mats = True
#			bmat[name]=m

#		if has_transp_mats:
#			for mat in bmat:
#				mat.mode |= MAT_MODE_TRANSPSHADOW

        obj_idx = 0  # index of current obj in loop
        for obj in objlist:
            if obj.type == AC_GROUP:
                continue
            elif obj.type == AC_LIGHT:
                light = Lamp.New('Lamp')
                object = scene.objects.new(light, obj.name)
                #object.select(True)
                obj.bl_obj = object
                if obj.data:
                    light.name = obj.data
                continue

            # type AC_POLY:

            # old .ac files used empty meshes as groups, convert to a real ac group
            if not obj.vlist and obj.kids:
                obj.type = AC_GROUP
                continue

            mesh = Mesh.New()
            object = scene.objects.new(mesh, obj.name)
            #object.select(True)
            obj.bl_obj = object
            if obj.data: mesh.name = obj.data
            mesh.degr = obj.crease  # will auto clamp to [1, 80]

            if not obj.vlist:  # no vertices? nothing more to do
                continue

            #Setup UV Layers
            mesh.addUVLayer("ImageUV")
            mesh.addUVLayer("ShadowUV")
            mesh.activeUVLayer = "ImageUV"

            mesh.verts.extend(obj.vlist)

            objmat_indices = []

            for e in obj.elist:
                mesh.edges.extend(e)

            if obj.flist_v:
                mesh.faces.extend(obj.flist_v)

                facesnum = len(mesh.faces)

                if facesnum == 0:  # shouldn't happen, of course
                    continue

                mesh.faceUV = True

                # checking if the .ac file had duplicate faces (Blender ignores them)
                if facesnum != len(obj.flist_v):
                    # it has, ugh. Let's clean the uv list:
                    lenfl = len(obj.flist_v)
                    flist = obj.flist_v
                    uvlist = obj.flist_uv
                    uvlist2 = obj.flist_uv2
                    cfglist = obj.flist_cfg
                    for f in flist:
                        f.sort()
                    fi = lenfl
                    while fi > 0:  # remove data related to duplicates
                        fi -= 1
                        if flist[fi] in flist[:fi]:
                            uvlist.pop(fi)
                            cfglist.pop(fi)
                            if len(uvlist2) > 0:
                                uvlist2.pop(fi)

                img = None
                img2 = None

                if obj.tex != '':
                    if obj.tex in bl_images.keys():
                        img = bl_images[obj.tex]
                    elif obj.tex not in missing_textures:
                        texfname = None
                        objtex = obj.tex
                        baseimgname = bsys.basename(objtex)
                        if bsys.exists(objtex) == 1:
                            texfname = objtex
                        else:
                            if baseimgname.find('\\') > 0:
                                baseimgname = bsys.basename(
                                    objtex.replace('\\', '/'))
                            objtex = bsys.join(self.importdir, baseimgname)
                            if bsys.exists(objtex) == 1:
                                texfname = objtex
                            else:
                                objtex = bsys.join(TEXTURES_DIR2, baseimgname)
                                if bsys.exists(objtex):
                                    texfname = objtex
                                else:
                                    inform(
                                        "Couldn't find texture in alt path %s"
                                        % TEXTURES_DIR2)
                        if texfname:
                            try:
                                img = Image.Load(texfname)
                                # Commented because it's unnecessary:
                                #img.xrep = int(obj.texrep[0])
                                #img.yrep = int(obj.texrep[1])
                                if img:
                                    bl_images[obj.tex] = img
                            except:
                                inform("THROW:  Couldn't load texture: %s" %
                                       baseimgname)
                        else:
                            missing_textures.append(obj.tex)
                            inform("Couldn't find texture: %s" % baseimgname)

                if obj.tex2 != '':
                    if obj.tex2 in bl_images.keys():
                        img2 = bl_images[obj.tex2]
                    elif obj.tex2 not in missing_textures:
                        texfname = None
                        objtex2 = obj.tex2
                        baseimgname = bsys.basename(objtex2)
                        if bsys.exists(objtex2) == 1:
                            texfname = objtex2
                        else:
                            if baseimgname.find('\\') > 0:
                                baseimgname = bsys.basename(
                                    objtex2.replace('\\', '/'))
                            objtex2 = bsys.join(self.importdir, baseimgname)
                            if bsys.exists(objtex) == 1:
                                texfname = objtex2
                            else:
                                objtex2 = bsys.join(TEXTURES_DIR2, baseimgname)
                                if bsys.exists(objtex2):
                                    texfname = objtex2
                                else:
                                    inform(
                                        "Couldn't find texture in alt path %s"
                                        % objtex2)

                        if texfname:
                            try:
                                img2 = Image.Load(texfname)
                                # Commented because it's unnecessary:
                                #img.xrep = int(obj.texrep[0])
                                #img.yrep = int(obj.texrep[1])
                                if img2:
                                    bl_images[obj.tex2] = img2
                            except:
                                inform("THROW:  Couldn't load texture: %s" %
                                       baseimgname)
                        else:
                            missing_textures.append(obj.tex2)
                            inform("Couldn't find texture: %s" % baseimgname)

                if obj.tex not in bmat.keys():
                    if img:
                        #Create a new material with a texture attached to it
                        m1 = Material.New(obj.tex)
                        m1.rgbCol = m.rgbCol
                        m1.amb = m.amb
                        m1.emit = m.emit
                        m1.specCol = m.specCol
                        m1.spec = m.spec
                        m1.alpha = m.alpha
                        texname = 'Tex%s' % obj.tex
                        texname2 = 'Tex2%s' % obj.tex

                        if img:
                            iname = img.getName()
                            if iname not in bl_textures.keys():
                                basetex = Texture.New(iname)
                                basetex.setType('Image')
                                map1 = Texture.MapTo.COL | Texture.MapTo.ALPHA
                                basetex.image = img
                                bl_textures[iname] = basetex

                            basetex = bl_textures[iname]
                            m1.setTexture(0, basetex, Texture.TexCo.UV, map1)

                        if img2:
                            iname2 = img2.getName()
                            if iname2 not in bl_textures.keys():
                                basetex2 = Texture.New(iname2)
                                basetex2.setType('Image')
                                map2 = Texture.MapTo.COL
                                basetex2.image = img2
                                bl_textures[iname2] = basetex2
                            else:
                                map2 = Texture.MapTo.COL

                            basetex2 = bl_textures[iname2]
                            m1.setTexture(1, basetex2, Texture.TexCo.UV, map2)

                        if m1.alpha < 1.0:
                            m1.mode |= MAT_MODE_ZTRANSP
                            has_transp_mats = True

                        mtextures = m1.getTextures()
                        tunit = 0
                        for mtex in mtextures:
                            if not (mtex == None):
                                if tunit == 1:
                                    mtex.uvlayer = "ShadowUV"
                                    mtex.colfac = 0.3
                                    tunit = tunit + 1
                                if tunit == 0:
                                    mtex.uvlayer = "ImageUV"

                                    tunit = tunit + 1

                        bmat[obj.tex] = m1

                if obj.tex != '':
                    if obj.tex in bl_images.keys():
                        img = bl_images[obj.tex]

                #TODO attach correct materials to objects
                if obj.tex in bmat.keys():
                    mat1 = bmat[obj.tex]
                    if len(mesh.materials) == 0:
                        mesh.materials += [mat1]
                else:
                    inform('Material %s not found\n' % obj.tex)

                for i in range(facesnum):
                    f = obj.flist_cfg[i]
                    fmat = f[0]
                    is_smooth = f[1]
                    twoside = f[2]
                    bface = mesh.faces[i]
                    bface.smooth = is_smooth
                    if twoside: bface.mode |= FACE_TWOSIDE
                    if img:
                        bface.mode |= FACE_TEX
                        bface.image = img
                    #TODO handle material properly
                    #bface.mat = objmat_indices.index(fmat)
                    bface.mat = 0
                    fuv = obj.flist_uv[i]
                    if len(obj.flist_uv2) > 0:
                        fuv2 = obj.flist_uv2[i]

                    if obj.texoff:
                        uoff = obj.texoff[0]
                        voff = obj.texoff[1]
                        urep = obj.texrep[0]
                        vrep = obj.texrep[1]
                        for uv in fuv:
                            uv[0] *= urep
                            uv[1] *= vrep
                            uv[0] += uoff
                            uv[1] += voff

                        if len(fuv2) > 0:
                            for uv2 in fuv2:
                                uv2[0] *= urep
                                uv2[1] *= vrep
                                uv2[0] += uoff
                                uv2[1] += voff

                    mesh.activeUVLayer = "ImageUV"
                    mesh.faces[i].uv = fuv

                    if len(fuv2) > 0:
                        mesh.activeUVLayer = "ShadowUV"
                        mesh.faces[i].uv = fuv2
#						for uv2 in fuv2:
#							inform('UV2 coords %.5f %.5f\n' % (uv2[0],uv2[1]))

                    mesh.activeUVLayer = "ImageUV"

                # finally, delete the 1st vertex we added to prevent vindices == 0
                mesh.verts.delete(0)

                mesh.calcNormals()

                mesh.mode = MESH_AUTOSMOOTH

            obj_idx += 1

        self.build_hierarchy()
        scene.update()
Esempio n. 17
0
	def testAC3DImport(self):

		FACE_TWOSIDE = Mesh.FaceModes['TWOSIDE']
		FACE_TEX = Mesh.FaceModes['TEX']
		MESH_AUTOSMOOTH = Mesh.Modes['AUTOSMOOTH']

		MAT_MODE_ZTRANSP = Material.Modes['ZTRANSP']
		MAT_MODE_TRANSPSHADOW = Material.Modes['TRANSPSHADOW']

		scene = self.scene

		bl_images = {} # loaded texture images
		missing_textures = [] # textures we couldn't find

		objlist = self.objlist[1:] # skip 'world'

		bmat = []
		has_transp_mats = False
		for mat in self.mlist:
			name = mat[0]
			m = Material.New(name)
			m.rgbCol = (mat[1][0], mat[1][1], mat[1][2])
			m.amb = mat[2]
			m.emit = mat[3]
			m.specCol = (mat[4][0], mat[4][1], mat[4][2])
			m.spec = mat[5]
			m.alpha = mat[6]
			if m.alpha < 1.0:
				m.mode |= MAT_MODE_ZTRANSP
				has_transp_mats = True
			bmat.append(m)

		if has_transp_mats:
			for mat in bmat:
				mat.mode |= MAT_MODE_TRANSPSHADOW

		obj_idx = 0 # index of current obj in loop
		for obj in objlist:
			if obj.type == AC_GROUP:
				continue
			elif obj.type == AC_LIGHT:
				light = Lamp.New('Lamp')
				object = scene.objects.new(light, obj.name)
				#object.select(True)
				obj.bl_obj = object
				if obj.data:
					light.name = obj.data
				continue

			# type AC_POLY:

			# old .ac files used empty meshes as groups, convert to a real ac group
			if not obj.vlist and obj.kids:
				obj.type = AC_GROUP
				continue

			mesh = Mesh.New()
			object = scene.objects.new(mesh, obj.name)
			#object.select(True)
			obj.bl_obj = object
			if obj.data: mesh.name = obj.data
			mesh.degr = obj.crease # will auto clamp to [1, 80]

			if not obj.vlist: # no vertices? nothing more to do
				continue

			mesh.verts.extend(obj.vlist)

			objmat_indices = []
			for mat in bmat:
				if bmat.index(mat) in obj.matlist:
					objmat_indices.append(bmat.index(mat))
					mesh.materials += [mat]
					if DISPLAY_TRANSP and mat.alpha < 1.0:
						object.transp = True

			for e in obj.elist:
				mesh.edges.extend(e)

			if obj.flist_v:
				mesh.faces.extend(obj.flist_v)

				facesnum = len(mesh.faces)

				if facesnum == 0: # shouldn't happen, of course
					continue

				mesh.faceUV = True

				# checking if the .ac file had duplicate faces (Blender ignores them)
				if facesnum != len(obj.flist_v):
					# it has, ugh. Let's clean the uv list:
					lenfl = len(obj.flist_v)
					flist = obj.flist_v
					uvlist = obj.flist_uv
					cfglist = obj.flist_cfg
					for f in flist:
						f.sort()
					fi = lenfl
					while fi > 0: # remove data related to duplicates
						fi -= 1
						if flist[fi] in flist[:fi]:
							uvlist.pop(fi)
							cfglist.pop(fi)

				img = None
				if obj.tex != '':
					if obj.tex in bl_images.keys():
						img = bl_images[obj.tex]
					elif obj.tex not in missing_textures:
						texfname = None
						objtex = obj.tex
						baseimgname = bsys.basename(objtex)
						if bsys.exists(objtex) == 1:
							texfname = objtex
						elif bsys.exists(bsys.join(self.importdir, objtex)):
							texfname = bsys.join(self.importdir, objtex)
						else:
							if baseimgname.find('\\') > 0:
								baseimgname = bsys.basename(objtex.replace('\\','/'))
							objtex = bsys.join(self.importdir, baseimgname)
							if bsys.exists(objtex) == 1:
								texfname = objtex
							else:
								objtex = bsys.join(TEXTURES_DIR, baseimgname)
								if bsys.exists(objtex):
									texfname = objtex
						if texfname:
							try:
								img = Image.Load(texfname)
								# Commented because it's unnecessary:
								#img.xrep = int(obj.texrep[0])
								#img.yrep = int(obj.texrep[1])
								if img:
									bl_images[obj.tex] = img
							except:
								inform("Couldn't load texture: %s" % baseimgname)
						else:
							missing_textures.append(obj.tex)
							inform("Couldn't find texture: %s" % baseimgname)

				for i in range(facesnum):
					f = obj.flist_cfg[i]
					fmat = f[0]
					is_smooth = f[1]
					twoside = f[2]
					bface = mesh.faces[i]
					bface.smooth = is_smooth
					if twoside: bface.mode |= FACE_TWOSIDE
					if img:
						bface.mode |= FACE_TEX
						bface.image = img
					bface.mat = objmat_indices.index(fmat)
					fuv = obj.flist_uv[i]
					if obj.texoff:
						uoff = obj.texoff[0]
						voff = obj.texoff[1]
						urep = obj.texrep[0]
						vrep = obj.texrep[1]
						for uv in fuv:
							uv[0] *= urep
							uv[1] *= vrep
							uv[0] += uoff
							uv[1] += voff

					mesh.faces[i].uv = fuv

				# finally, delete the 1st vertex we added to prevent vindices == 0
				mesh.verts.delete(0)

				mesh.calcNormals()

				mesh.mode = MESH_AUTOSMOOTH

				# subdiv: create SUBSURF modifier in Blender
				if SUBDIV and obj.subdiv > 0:
					subdiv = obj.subdiv
					subdiv_render = subdiv
					# just to be safe:
					if subdiv_render > 6: subdiv_render = 6
					if subdiv > 3: subdiv = 3
					modif = object.modifiers.append(Modifier.Types.SUBSURF)
					modif[Modifier.Settings.LEVELS] = subdiv
					modif[Modifier.Settings.RENDLEVELS] = subdiv_render

			obj_idx += 1

		self.build_hierarchy()
		scene.update()
Esempio n. 18
0
def readDSF(path):
    baddsf=(0, "Invalid DSF file", path)

    h=file(path, 'rb')
    h.seek(0, 2)
    hlen=h.tell()
    h.seek(0, 0)
    if h.read(8)!='XPLNEDSF' or unpack('<I',h.read(4))!=(1,) or h.read(4)!='DAEH':
        raise IOError, baddsf
    (l,)=unpack('<I', h.read(4))
    headend=h.tell()+l-8
    if h.read(4)!='PORP':
        raise IOError, baddsf
    (l,)=unpack('<I', h.read(4))
    properties=[]
    c=h.read(l-9).split('\0')
    h.read(1)
    overlay=0
    for i in range(0, len(c)-1, 2):
        if c[i]=='sim/overlay': overlay=int(c[i+1])
        elif c[i]=='sim/south': lat=int(c[i+1])
        elif c[i]=='sim/west': lon=int(c[i+1])
        properties.append((c[i],c[i+1]))
    h.seek(headend)
    if overlay:
        # Overlay DSF - bail early
        h.close()
        raise IOError, (0, "This is an overlay DSF", path)

    # Definitions Atom
    if h.read(4)!='NFED':
        raise IOError, baddsf
    (l,)=unpack('<I', h.read(4))
    defnend=h.tell()+l-8
    terrain=objects=polygons=network=[]
    while h.tell()<defnend:
        c=h.read(4)
        (l,)=unpack('<I', h.read(4))
        if l==8:
            pass	# empty
        elif c=='TRET':
            terrain=h.read(l-9).replace('\\','/').replace(':','/').split('\0')
            h.read(1)
        elif c=='TJBO':
            objects=h.read(l-9).replace('\\','/').replace(':','/').split('\0')
            h.read(1)
        elif c=='YLOP':
            polygons=h.read(l-9).replace('\\','/').replace(':','/').split('\0')
            h.read(1)
        elif c=='WTEN':
            networks=h.read(l-9).replace('\\','/').replace(':','/').split('\0')
            h.read(1)
        else:
            h.seek(l-8, 1)

    # Geodata Atom
    if h.read(4)!='DOEG':
        raise IOError, baddsf
    (l,)=unpack('<I', h.read(4))
    geodend=h.tell()+l-8
    pool=[]
    scal=[]
    while h.tell()<geodend:
        c=h.read(4)
        (l,)=unpack('<I', h.read(4))
        if c=='LOOP':
            thispool=[]
            (n,)=unpack('<I', h.read(4))
            (p,)=unpack('<B', h.read(1))
            for i in range(p):
                thisplane=[]
                (e,)=unpack('<B', h.read(1))
                if e==0 or e==1:
                    last=0
                    for j in range(n):
                        (d,)=unpack('<H', h.read(2))
                        if e==1: d=(last+d)&65535
                        thisplane.append(d)
                        last=d
                elif e==2 or e==3:
                    last=0
                    while(len(thisplane))<n:
                        (r,)=unpack('<B', h.read(1))
                        if (r&128):
                            (d,)=unpack('<H', h.read(2))
                            for j in range(r&127):
                                if e==3:
                                    thisplane.append((last+d)&65535)
                                    last=(last+d)&65535
                                else:
                                    thisplane.append(d)
                        else:
                            for j in range(r):
                                (d,)=unpack('<H', h.read(2))
                                if e==3: d=(last+d)&65535
                                thisplane.append(d)
                                last=d
                else:
                    raise IOError, baddsf
                thispool.append(thisplane)
            pool.append(thispool)
        elif c=='LACS':
            thisscal=[]
            for i in range(0, l-8, 8):
                d=unpack('<2f', h.read(8))
                thisscal.append(d)
            scal.append(thisscal)
        else:
            h.seek(l-8, 1)

    # Rescale pool and transform to one list per entry
    if len(scal)!=len(pool): raise(IOError)
    newpool=[]
    for i in range(len(pool)):
        curpool=pool[i]
        n=len(curpool[0])
        newpool=[[] for j in range(n)]
        for plane in range(len(curpool)):
            (scale,offset)=scal[i][plane]
            scale=scale/65535
            for j in range(n):
                newpool[j].append(curpool[plane][j]*scale+offset)
        pool[i]=newpool

    # Commands Atom
    if h.read(4)!='SDMC':
        raise IOError, baddsf
    (l,)=unpack('<I', h.read(4))
    cmdsend=h.tell()+l-8
    curpool=0
    idx=0
    near=0
    far=-1
    flags=0	# 0=physical, 1=overlay
    f=[[[],[]] for i in range(len(terrain))]
    v=[[[],[]] for i in range(len(terrain))]
    t=[[[],[]] for i in range(len(terrain))]
    pscale=99.0/(hlen-geodend)
    progress=0
    while h.tell()<cmdsend:
        now=int((h.tell()-geodend)*pscale)
        if progress!=now:
            progress=now
            Window.DrawProgressBar(progress/100.0, "Importing %2d%%"%progress)

        (c,)=unpack('<B', h.read(1))
        if c==1:	# Coordinate Pool Select
            (curpool,)=unpack('<H', h.read(2))

        elif c==2:	# Junction Offset Select
            h.read(4)	# not implemented

        elif c==3:	# Set Definition
            (idx,)=unpack('<B', h.read(1))

        elif c==4:	# Set Definition
            (idx,)=unpack('<H', h.read(2))

        elif c==5:	# Set Definition
            (idx,)=unpack('<I', h.read(4))

        elif c==6:	# Set Road Subtype
            h.read(1)	# not implemented

        elif c==7:	# Object
            h.read(2)	# not implemented

        elif c==8:	# Object Range
            h.read(4)	# not implemented

        elif c==9:	# Network Chain
            (l,)=unpack('<B', h.read(1))
            h.read(l*2)	# not implemented

        elif c==10:	# Network Chain Range
            h.read(4)	# not implemented

        elif c==11:	# Network Chain
            (l,)=unpack('<B', h.read(1))
            h.read(l*4)	# not implemented

        elif c==12:	# Polygon
            (param,l)=unpack('<HB', h.read(3))
            h.read(l*2)	# not implemented

        elif c==13:	# Polygon Range (DSF2Text uses this one)
            (param,first,last)=unpack('<HHH', h.read(6))	# not implemented

        elif c==14:	# Nested Polygon
            (param,n)=unpack('<HB', h.read(3))
            for i in range(n):
                (l,)=unpack('<B', h.read(1))
                h.read(l*2)	# not implemented

        elif c==15:	# Nested Polygon Range (DSF2Text uses this one too)
            (param,n)=unpack('<HB', h.read(3))
            h.read((n+1)*2)	# not implemented

        elif c==16:	# Terrain Patch
            pass

        elif c==17:	# Terrain Patch w/ flags
            (flags,)=unpack('<B', h.read(1))
            flags-=1

        elif c==18:	# Terrain Patch w/ flags & LOD
            (flags,near,far)=unpack('<Bff', h.read(9))
            flags-=1

        elif c==23:	# Patch Triangle
            (l,)=unpack('<B', h.read(1))
            n=len(v[idx][flags])
            for i in range(n,n+l,3):
                f[idx][flags].append([i+2,i+1,i])
            for i in range(l):
                (d,)=unpack('<H', h.read(2))
                p=pool[curpool][d]
                v[idx][flags].append([(p[0]-lon)*hscale,
                                      (p[1]-lat)*hscale, p[2]*vscale])
                if len(p)>=7:
                    t[idx][flags].append([p[5],p[6]])


        elif c==24:	# Patch Triangle - cross-pool
            (l,)=unpack('<B', h.read(1))
            n=len(v[idx][flags])
            for i in range(n,n+l,3):
                f[idx][flags].append([i+2,i+1,i])
            for i in range(l):
                (c,d)=unpack('<HH', h.read(4))
                p=pool[c][d]
                v[idx][flags].append([(p[0]-lon)*hscale,
                                      (p[1]-lat)*hscale, p[2]*vscale])
                if len(p)>=7:
                    t[idx][flags].append([p[5],p[6]])

        elif c==25:	# Patch Triangle Range
            (first,last)=unpack('<HH', h.read(4))
            n=len(v[idx][flags])
            for i in range(n,n+last-first,3):
                f[idx][flags].append([i+2,i+1,i])
            for d in range(first,last):
                p=pool[curpool][d]
                v[idx][flags].append([(p[0]-lon)*hscale,
                                      (p[1]-lat)*hscale, p[2]*vscale])
                if len(p)>=7:
                    t[idx][flags].append([p[5],p[6]])

        #elif c==26:	# Patch Triangle Strip (not used by DSF2Text)
        #elif c==27:
        #elif c==28:

        elif c==29:	# Patch Triangle Fan
            (l,)=unpack('<B', h.read(1))
            n=len(v[idx][flags])
            for i in range(1,l-1):
                f[idx][flags].append([n+i+1,n+i,n])
            for i in range(l):
                (d,)=unpack('<H', h.read(2))
                p=pool[curpool][d]
                v[idx][flags].append([(p[0]-lon)*hscale,
                                      (p[1]-lat)*hscale, p[2]*vscale])
                if len(p)>=7:
                    t[idx][flags].append([p[5],p[6]])

        elif c==30:	# Patch Triangle Fan - cross-pool
            (l,)=unpack('<B', h.read(1))
            n=len(v[idx][flags])
            for i in range(1,l-1):
                f[idx][flags].append([n+i+1,n+i,n])
            for i in range(l):
                (c,d)=unpack('<HH', h.read(4))
                p=pool[c][d]
                v[idx][flags].append([(p[0]-lon)*hscale,
                                      (p[1]-lat)*hscale, p[2]*vscale])
                if len(p)>=7:
                    t[idx][flags].append([p[5],p[6]])

        elif c==31:	# Patch Triangle Fan Range
            (first,last)=unpack('<HH', h.read(4))
            n=len(v[idx][flags])
            for i in range(1,last-first-1):
                f[idx][flags].append([n+i+1,n+i,n])
            for d in range(first, last):
                p=pool[curpool][d]
                v[idx][flags].append([(p[0]-lon)*hscale,
                                      (p[1]-lat)*hscale, p[2]*vscale])
                if len(p)>=7:
                    t[idx][flags].append([p[5],p[6]])

        elif c==32:	# Comment
            (l,)=unpack('<B', h.read(1))
            h.read(l)

        elif c==33:	# Comment
            (l,)=unpack('<H', h.read(2))
            h.read(l)

        elif c==34:	# Comment
            (l,)=unpack('<I', h.read(4))
            h.read(l)

        else:
            raise IOError, (c, "Unrecognised command (%d)" % c, c)

    h.close()

    Window.DrawProgressBar(0.99, "Realising")

    scene=Scene.GetCurrent()
    scene.layers=[1,2]

    for flags in [0]:# was [1,0]:	# overlay first so overlays
        for idx in range(len(terrain)):
            if not f[idx][flags]: continue
            if idx:
                name=basename(terrain[idx])[:-4]
                if flags: name=name+'.2'
                if terrain[idx] in libterrain:
                    (texture, angle, xscale, zscale)=readTER(libterrain[terrain[idx]])
                elif exists(join(dirname(path), pardir, pardir, terrain[idx])):
                    (texture, angle, xscale, zscale)=readTER(abspath(join(dirname(path), pardir, pardir, terrain[idx])))
                else:
                    raise IOError(0, 'Terrain %s not found' % terrain[idx], terrain[idx])
                try:
                    mat=Material.Get(name)
                except:
                    mat=Material.New(name)
                    mat.rgbCol=[1.0, 1.0, 1.0]
                    mat.spec=0
                    try:
                        img=Image.Get(basename(texture))
                    except:
                        img=Image.Load(texture)
                    tex=Texture.New(name)
                    tex.setType('Image')
                    tex.image=img
                    mat.setTexture(0, tex)
                    if flags:
                        mat.zOffset=1
                        mat.mode |= Material.Modes.ZTRANSP
                    mtex=mat.getTextures()[0]
                    mtex.size=(xscale*250, zscale*250, 0)
                    mtex.zproj=Texture.Proj.NONE
                    if t[idx][flags]:
                        mtex.texco=Texture.TexCo.UV
                    else:
                        mtex.texco=Texture.TexCo.GLOB
            else:
                name=terrain[idx]
                mat=Material.New(terrain[idx])
                mat.rgbCol=[0.1, 0.1, 0.2]
                mat.spec=0

            mesh=Mesh.New(name)
            mesh.mode &= ~(Mesh.Modes.TWOSIDED|Mesh.Modes.AUTOSMOOTH)
            mesh.mode |= Mesh.Modes.NOVNORMALSFLIP
            mesh.materials += [mat]
            mesh.verts.extend(v[idx][flags])
            mesh.faces.extend(f[idx][flags])
            if t[idx][flags]:
                faceno=0
                for face in mesh.faces:
                    face.uv=[Vector(t[idx][flags][i][0], t[idx][flags][i][1]) for i in f[idx][flags][faceno]]
                    face.image=img
                    faceno+=1
            mesh.update()

            ob = Object.New("Mesh", name)
            ob.link(mesh)
            scene.objects.link(ob)
            ob.Layer=flags+1
            ob.addProperty('terrain', terrain[idx])

            mesh.sel=True
            mesh.remDoubles(0.001)	# must be after linked to object
            mesh.sel=False

        if 0:	# Unreliable
            for face in mesh.faces:
                for v in face.verts:
                    if v.co[2]!=0.0:
                        break
                else:
                    face.mat=1	# water

    lamp=Lamp.New("Lamp", "Sun")
    ob = Object.New("Lamp", "Sun")
    ob.link(lamp)
    scene.objects.link(ob)
    lamp.type=1
    ob.Layer=3
    ob.setLocation(500, 500, 1000)
	def ParseMesh( self, szMeshName ):
		print "\tfound Mesh", szMeshName
		self.FindNextCharacter( '{' )
		nHierarchyLevel = 1

		aLineTokens = self.TokeniseLine()
		aVertices = self.ParseVec3Array( int( aLineTokens[ 0 ]))
		aLineTokens = self.TokeniseLine()
		aFaces = self.ParseFaceArray( int( aLineTokens[ 0 ]))
		aMaterialList = []

		while self.m_uLineIndex < self.m_uLineCount:
			uBaseLine = self.m_uLineIndex
			aLineTokens = self.TokeniseLine()
			strToken = aLineTokens[ 0 ].lower()

			if "material" == strToken:
				aMaterialList.append( self.ParseMaterial() )

			elif "meshmateriallist" == strToken:
				nHierarchyLevel += 1
				self.FindNextCharacter( '{' )
				aLineTokens = self.TokeniseLine()
				uMaterialCount = int( aLineTokens[ 0 ])
				aLineTokens = self.TokeniseLine()
				aMaterialFaces = self.ParseIntArray( int( aLineTokens[ 0 ]))

				print "\tMaterial Count =", uMaterialCount, "Material Faces =", len( aMaterialFaces )

			elif "meshnormals" == strToken:
				self.FindBracePair()

#				nHierarchyLevel += 1
#				self.FindNextCharacter( '{' )
#				aLineTokens = self.TokeniseLine()
#				aNormals = self.ParseVec3Array( int( aLineTokens[ 0 ]))
#				aLineTokens = self.TokeniseLine()
#				aNormalFaces = self.ParseFaceArray( int( aLineTokens[ 0 ]))
#				print "\tNormal count =", len( aNormals ), "Normal Faces =", len( aNormalFaces )

			elif "meshtexturecoords" == strToken:
				nHierarchyLevel += 1
				self.FindNextCharacter( '{' )
				aLineTokens = self.TokeniseLine()
				aTexCoords = self.ParseVec2Array( int( aLineTokens[ 0 ]))

			elif "skinweights" == strToken:
				self.ParseSkinWeights()

			elif "xskinmeshheader" == strToken:
				self.ParseXSkinMeshHeader()

			elif -1 != string.find( self.m_aLines[ uBaseLine ], '}' ):
				nHierarchyLevel -= 1

				if 0 == nHierarchyLevel:
					print "End Mesh"
					break
			else:
				print "Unexpected Mesh Token '", strToken, "' on line", self.m_uLineIndex
				break

		print "Vertex count =", len( aVertices ), "Face Count =", len( aFaces ), "Tex Coord count =", len( aTexCoords )
		meshCurrent = NMesh.GetRaw()

		for vertex in aVertices:
			v3Vertex = Blender.Mathutils.Vector( vertex ) * self.matrix
			meshCurrent.verts.append( NMesh.Vert( v3Vertex[ 0 ], v3Vertex[ 2 ], v3Vertex[ 1 ]))

#		aMaterialList = []
#		material = Material.New( "Material_Test" )
#		material.rgbCol = [ float(words[0]), float(words[1]), float(words[2]) ]
#		material.setAlpha( float(words[3]) )
#		aMaterialList.append( material )
#		meshCurrent.setMaterials( aMaterialList )
#		meshCurrent.update()

		aImageList = []
		uFaceIndex = 0

		for material in aMaterialList:
			szFileName = self.szDirectoryName + '\\' + material[ 0 ]
			print "Loading Image " + szFileName
			aImageList.append( Image.Load( szFileName ))

		for face in aFaces:
			faceNew = NMesh.Face()
			faceNew.v.append( meshCurrent.verts[ face[ 0 ]])
			faceNew.uv.append( (aTexCoords[ face[ 0 ]][ 0 ], -aTexCoords[ face[ 0 ]][ 1 ]) )
			faceNew.v.append( meshCurrent.verts[ face[ 2 ]])
			faceNew.uv.append( (aTexCoords[ face[ 2 ]][ 0 ], -aTexCoords[ face[ 2 ]][ 1 ]) )
			faceNew.v.append( meshCurrent.verts[ face[ 1 ]])
			faceNew.uv.append( (aTexCoords[ face[ 1 ]][ 0 ], -aTexCoords[ face[ 1 ]][ 1 ]) )
			faceNew.image = aImageList[ aMaterialFaces[ uFaceIndex ]]
#			faceNew.materialIndex = uMaterialIndex
#			faceNew.smooth = 1
			meshCurrent.faces.append( faceNew )
			uFaceIndex += 1

		NMesh.PutRaw( meshCurrent, self.szModelName + "_" + str( self.uMeshIndex ), 1 )
		self.uMeshIndex += 1
		meshCurrent.update()
def ImportFromC(file_name):
	print ("\n" * 2)
	print ("_" * 20)
	print ("\n" * 2)
	print "Beginning import from c script..."
	print ("\n" * 2)

	#get header filename from filename
	print file_name
	stringParts = file_name.split(".")
	
	headerFile_name = ""
	for i in range(0, len(stringParts)-1):
		headerFile_name += stringParts[i]
		headerFile_name += "."

	headerFile_name += "h"

	#open and read header file
	file = open(headerFile_name, "r")

	code = [l_split for l in file.readlines() for l_split in (' '.join(l.split()),) if l_split]
	fileLinePos = 0
	fileColPos = 0

	cDefineNames = []
	cDefineValues = []
	cDefineCount = 0

	print "Finding c defines"
	while True:
		# find the listed c defines
		fileLineCount = len(code)
		doesExist = False
		for i in range(0, fileLineCount-fileLinePos): #for (i=0; i < sizeof(code); i++)
			if code[fileLinePos+i][0:len("#define")] == "#define":
				fileLinePos += i
				cDefineCount += 1
				doesExist = True
				break

		# break the while loop if c defines are not found
		if doesExist == False:
			break

		# find the first underscore
		fileColCount = len(code[fileLinePos])
		for i in range(0, fileColCount): #for (i=0; i < sizeof(code[fileLinePos]); i++)
			if code[fileLinePos][i] == "_":
				fileColPos = i+1
				break
	
		# read c define name after the first underscore
		cDefName = ''
		for i in range(0, fileColCount-fileColPos):
			if code[fileLinePos][fileColPos+i] == " ":
				fileColPos += i+1
				break
			cDefName += code[fileLinePos][fileColPos+i]
		cDefineNames.append(cDefName)

		# read c define value
		cDefVal = ''
		for i in range(0, fileColCount-fileColPos):
			cDefVal += code[fileLinePos][fileColPos+i]
		cDefineValues.append(int(cDefVal))

		fileLinePos += 1

	objectNames = []
	imageNamesUnderscore = []
	imageNames = []

	# seperate the c defines into object and image names

	# find where the image Names are located within c defines
	imagesLoc = cDefineCount
	for i in range(1, cDefineCount):
		if cDefineValues[i] == 0:
			imagesLoc = i
			break

	# get the object names
	for i in range(0, imagesLoc):
		objectNames.append(cDefineNames[i])
	
	# get the image names
	for i in range(imagesLoc, cDefineCount):
		imgNameUnder = []
		for j in range(0, len(cDefineNames[i])):
			imgNameUnder.append(cDefineNames[i][j])
		imageNamesUnderscore.extend([imgNameUnder])

	# find the last underscore in each of the image names
	# and change it to a period
	for i in range(0, len(imageNamesUnderscore)):
		for j in range(0, len(imageNamesUnderscore[i])):
			if imageNamesUnderscore[i][len(imageNamesUnderscore[i])-j-1] == "_":
				imageNamesUnderscore[i][len(imageNamesUnderscore[i])-j-1] = "."
				break

	for i in range(0, len(imageNamesUnderscore)):
		imgName = ''
		for j in range(0, len(imageNamesUnderscore[i])):
			imgName += imageNamesUnderscore[i][j]
		imageNames.append(imgName)
	
	#close header file
	file.close()

	#open and read c file
	file = open(file_name, "r")

	scene = bpy.data.scenes.active
	meshes = []
	for ob in scene.objects:
		obtype = ob.type
		if obtype == "Mesh":
			meshes.append(ob)

	fileLines = [l_split for l in file.readlines() for l_split in (' '.join(l.split()),) if l_split]

	print "Erasing all comments"
	# erase all of the comments (/* */)
	i = 0
	insideComment = 0
	while i < len(fileLines):
		stopErase = 0
		
		commentStart = fileLines[i].find("/*")
		if insideComment == 1:
			commentStart = 0
			
		if fileLines[i].find("//") != -1:
			if fileLines[i].find("//") < commentStart:
				stopErase = 1
		if stopErase != 1:
			if commentStart != -1:
				insideComment = 1
	
		lineEnd = len(fileLines[i])
		commentEnd = fileLines[i].find("*/")
		
		if commentEnd != -1:
			if insideComment == 1:
				commentEnd = fileLines[i].find("*/")+2
				insideComment = 0
		else:
			if insideComment == 1:
				commentEnd = lineEnd
		
		if commentStart != -1:
			if fileLines[i].find("//") != -1:
				if fileLines[i].find("//") < commentStart:
					stopErase = 1
				if fileLines[i].find("//")+2 < commentEnd:
					stopErase = 1
			if stopErase != 1:
				fileLines[i] = fileLines[i].replace(fileLines[i][commentStart:commentEnd], "")
		
		commentStart = fileLines[i].find("/*")
		if commentStart == -1:
			i = i + 1
		if stopErase == 1:
			i = i + 1

	# erase all of the comments (//)
	i = 0
	while i < len(fileLines):
		commentStart = fileLines[i].find("//")
		commentEnd = len(fileLines[i])
		if commentStart != -1:
			fileLines[i] = fileLines[i].replace(fileLines[i][commentStart:commentEnd], "")
		i = i + 1
	
	print "Erasing all spaces"
	# erase all spaces
	i = 0
	while i < len(fileLines):
		fileLines[i] = fileLines[i].replace(" ", "")
		i = i + 1
	
	print "Moving code to buffer"
	# move the data from "fileLines" buffer to "code" buffer ignoring returns
	i = 0
	code = []
	while i < len(fileLines):
		lineEnd = len(fileLines[i])
		j = 0
		while j < lineEnd:
			code[len(code):] = fileLines[i][j]
			j = j + 1
		i = i + 1
	
##################################################################################################

	codePos = 0

	print "Finding vertex array size"
	# find the first listed vertex array size
	i = 0
	while i < len(code):
		if code[0+i:12+i] == ["_", "P", "O", "I", "N", "T", "D", "A", "T", "S", "Z", "["]:
			codePos = i + 12
			i = len(code)
		i = i + 1
	
	i = codePos
	while i < len(code):
		if code[0+i:3+i] == ["]", "=", "{"]:
			codePos = i + 3
			i = len(code)
		i = i + 1

	print "Reading vertex array sizes"
	# read the vertex array sizes from the code
	endOfNum = 0
	numCnt = 0
	pointDatSz = []
	while endOfNum != 2:
		i = 0
		num = ""
		endOfNum = 0
		while endOfNum == 0:
			if code[codePos+i] == "," or code[codePos+i] == "}":
				endOfNum = 1
			else:
				num = num + code[codePos+i]
			if code[codePos+i] == "}":
				endOfNum = 2
			i = i + 1
		
		if endOfNum != 2:
			codePos = codePos+i

		if num != "":
			pointDatSz[len(pointDatSz):] = [int(num)]
	print pointDatSz
	#number of meshes
	meshCnt = len(pointDatSz)-1
	
	print "Finding quad array size"
	# find the first listed quad array size
	i = 0
	while i < len(code):
		if code[0+i:11+i] == ["_", "Q", "U", "A", "D", "D", "A", "T", "S", "Z", "["]:
			codePos = i + 11
			i = len(code)
		i = i + 1
	
	i = codePos
	while i < len(code):
		if code[0+i:3+i] == ["]", "=", "{"]:
			codePos = i + 3
			i = len(code)
		i = i + 1

	print "Reading quad array sizes"
	# read the quad array sizes from the code
	endOfNum = 0
	numCnt = 0
	quadDatSz = []
	while endOfNum != 2:
		i = 0
		num = ""
		endOfNum = 0
		while endOfNum == 0:
			if code[codePos+i] == "," or code[codePos+i] == "}":
				endOfNum = 1
			else:
				num = num + code[codePos+i]
			if code[codePos+i] == "}":
				endOfNum = 2
			i = i + 1
		
		if endOfNum != 2:
			codePos = codePos+i
		
		if num != "":
			quadDatSz[len(quadDatSz):] = [int(num)]
	

	print "Finding tri array size"
	# find the first listed tri array size
	i = 0
	while i < len(code):
		if code[0+i:10+i] == ["_", "T", "R", "I", "D", "A", "T", "S", "Z", "["]:
			codePos = i + 10
			i = len(code)
		i = i + 1
	
	i = codePos
	while i < len(code):
		if code[0+i:3+i] == ["]", "=", "{"]:
			codePos = i + 3
			i = len(code)
		i = i + 1

	print "Reading tri array sizes"
	# read the tri array sizes from the code
	endOfNum = 0
	numCnt = 0
	triDatSz = []
	while endOfNum != 2:
		i = 0
		num = ""
		endOfNum = 0
		while endOfNum == 0:
			if code[codePos+i] == "," or code[codePos+i] == "}":
				endOfNum = 1
			else:
				num = num + code[codePos+i]
			if code[codePos+i] == "}":
				endOfNum = 2
			i = i + 1
		
		if endOfNum != 2:
			codePos = codePos+i

		if num != "":
			triDatSz[len(triDatSz):] = [int(num)]
	
	
##################################################################################################

	print "Finding fist listed vertex"
	# find the first listed vertex
	i = 0
	while i < len(code):
		if code[0+i:7+i] == ["_", "P", "O", "I", "N", "T", "["]:
			codePos = i + 7
			i = len(code)
		i = i + 1
	
	i = codePos
	while i < len(code):
		if code[0+i:3+i] == ["]", "=", "{"]:
			codePos = i + 3
			i = len(code)
		i = i + 1
	
	print "Reading verticies"
	# read the verticies from the code
	endOfNum = 0
	vert = []
	while endOfNum != 2:
		i = 0
		num = ""
		endOfNum = 0
		while endOfNum == 0:
			if code[codePos+i] == "," or code[codePos+i] == "}":
				endOfNum = 1
			else:
				num = num + code[codePos+i]
			if code[codePos+i] == "}":
				endOfNum = 2
			i = i + 1
		
		if endOfNum != 2:
			codePos = codePos+i
		
		if num != "":
			vert[len(vert):] = [float(num)]
	

	print "Finding first listed quad"
	# find the first listed quad data number
	i = 0
	while i < len(code):
		if code[0+i:6+i] == ["_", "Q", "U", "A", "D", "["]:
			codePos = i + 6
			i = len(code)
		i = i + 1
	
	i = codePos
	while i < len(code):
		if code[0+i:3+i] == ["]", "=", "{"]:
			codePos = i + 3
			i = len(code)
		i = i + 1
	
	print "Reading quads"
	# read the quad data from the code
	endOfNum = 0
	quad = []
	while endOfNum != 2:
		i = 0
		num = ""
		endOfNum = 0
		while endOfNum == 0:
			if code[codePos+i] == "," or code[codePos+i] == "}":
				endOfNum = 1
			else:
				num = num + code[codePos+i]
			if code[codePos+i] == "}":
				endOfNum = 2
			i = i + 1
		
		if endOfNum != 2:
			codePos = codePos+i
		
		if num != "":
			quad[len(quad):] = [int(num)]



	print "Finding first listed tri"
	# find the first listed tri data number
	i = 0
	while i < len(code):
		if code[0+i:5+i] == ["_", "T", "R", "I", "["]:
			codePos = i + 5
			i = len(code)
		i = i + 1
	
	i = codePos
	while i < len(code):
		if code[0+i:3+i] == ["]", "=", "{"]:
			codePos = i + 3
			i = len(code)
		i = i + 1
	
	print "Reading tris"
	# read the tri data from the code
	endOfNum = 0
	tri = []
	while endOfNum != 2:
		i = 0
		num = ""
		endOfNum = 0
		while endOfNum == 0:
			if code[codePos+i] == "," or code[codePos+i] == "}":
				endOfNum = 1
			else:
				num = num + code[codePos+i]
			if code[codePos+i] == "}":
				endOfNum = 2
			i = i + 1
		
		if endOfNum != 2:
			codePos = codePos+i
		
		if num != "":
			tri[len(tri):] = [int(num)]


	print "Finding first listed vertex color"
	# find the first listed vertex color data number
	i = 0
	while i < len(code):
		if code[0+i:8+i] == ["_", "V", "C", "O", "L", "O", "R", "["]:
			codePos = i + 8
			i = len(code)
		i = i + 1
	
	i = codePos
	while i < len(code):
		if code[0+i:3+i] == ["]", "=", "{"]:
			codePos = i + 3
			i = len(code)
		i = i + 1
	
	print "Reading vertex color"
	# read the vertex color data from the code
	endOfNum = 0
	vColor = []
	while endOfNum != 2:
		i = 0
		num = ""
		endOfNum = 0
		while endOfNum == 0:
			if code[codePos+i] == "," or code[codePos+i] == "}":
				endOfNum = 1
			else:
				num = num + code[codePos+i]
			if code[codePos+i] == "}":
				endOfNum = 2
			i = i + 1
		
		if endOfNum != 2:
			codePos = codePos+i
		
		if num != "":
			vColor[len(vColor):] = [int(num)]


	print "Finding first listed texture coordinate"
	# find the first listed texture coordinate data number
	i = 0
	while i < len(code):
		if code[0+i:8+i] == ["_", "T", "E", "X", "C", "O", "O", "R", "D", "["]:
			codePos = i + 8
			i = len(code)
		i = i + 1
	
	i = codePos
	while i < len(code):
		if code[0+i:3+i] == ["]", "=", "{"]:
			codePos = i + 3
			i = len(code)
		i = i + 1
	
	print "Reading texture coordinates"
	# read the texture coordinate data from the code
	endOfNum = 0
	texCoord = []
	while endOfNum != 2:
		i = 0
		num = ""
		endOfNum = 0
		while endOfNum == 0:
			if code[codePos+i] == "," or code[codePos+i] == "}":
				endOfNum = 1
			else:
				num = num + code[codePos+i]
			if code[codePos+i] == "}":
				endOfNum = 2
			i = i + 1
		
		if endOfNum != 2:
			codePos = codePos+i
		
		if num != "":
			texCoord[len(texCoord):] = [float(num)]


	print "Finding first listed texture link data"
	# find the first listed texture link data number
	i = 0
	while i < len(code):
		if code[0+i:8+i] == ["_", "T", "E", "X", "L", "I", "N", "K", "D", "A", "T", "["]:
			codePos = i + 8
			i = len(code)
		i = i + 1
	
	i = codePos
	while i < len(code):
		if code[0+i:3+i] == ["]", "=", "{"]:
			codePos = i + 3
			i = len(code)
		i = i + 1
	
	print "Reading texture link data"
	# read the texture link data from the code
	endOfNum = 0
	texLinkDat = []
	while endOfNum != 2:
		i = 0
		num = ""
		endOfNum = 0
		while endOfNum == 0:
			if code[codePos+i] == "," or code[codePos+i] == "}":
				endOfNum = 1
			else:
				num = num + code[codePos+i]
			if code[codePos+i] == "}":
				endOfNum = 2
			i = i + 1
		
		if endOfNum != 2:
			codePos = codePos+i
		if num != "":
			texLinkDat[len(texLinkDat):] = [int(num)]

##################################################################################################

	vColorInc = 0
	texCoordInc = 0
	for meshInc in range(0, meshCnt):
		print ("meshInc %i" % (meshInc))
		mesh = Mesh.New()
		
		print "Importing verticies"
		# import verticies to blender
		i = pointDatSz[meshInc]
		while i < pointDatSz[meshInc+1]:
			mesh.verts.extend(vert[i],vert[i+1],vert[i+2])
			i = i + 3

		print "Importing quads"
		# import quads to blender
		i = quadDatSz[meshInc]
		polyBgn = pointDatSz[meshInc] / 3
		while i < quadDatSz[meshInc+1]:
			mesh.faces.extend(quad[i]-polyBgn, quad[i+1]-polyBgn, quad[i+2]-polyBgn, quad[i+3]-polyBgn)
			i = i + 4
		
		print "Importing tris"
		# import tris to blender
		i = triDatSz[meshInc]
		polyBgn = pointDatSz[meshInc] / 3
		while i < triDatSz[meshInc+1]:
			mesh.faces.extend(tri[i]-polyBgn, tri[i+1]-polyBgn, tri[i+2]-polyBgn)
			i = i + 3
		

		# enable vertex colors
		mesh.vertexColors = 1

		print "Importing vertex colors"
		# import vertex colors for quads to blender

		faceCnt = 0

		i = quadDatSz[meshInc]
		while i < quadDatSz[meshInc+1]:

			mesh.faces[faceCnt].col[0].r = vColor[vColorInc]
			vColorInc += 1
			mesh.faces[faceCnt].col[0].g = vColor[vColorInc]
			vColorInc += 1
			mesh.faces[faceCnt].col[0].b = vColor[vColorInc]
			vColorInc += 2

			mesh.faces[faceCnt].col[1].r = vColor[vColorInc]
			vColorInc += 1
			mesh.faces[faceCnt].col[1].g = vColor[vColorInc]
			vColorInc += 1
			mesh.faces[faceCnt].col[1].b = vColor[vColorInc]
			vColorInc += 2

			mesh.faces[faceCnt].col[2].r = vColor[vColorInc]
			vColorInc += 1
			mesh.faces[faceCnt].col[2].g = vColor[vColorInc]
			vColorInc += 1
			mesh.faces[faceCnt].col[2].b = vColor[vColorInc]
			vColorInc += 2

			mesh.faces[faceCnt].col[3].r = vColor[vColorInc]
			vColorInc += 1
			mesh.faces[faceCnt].col[3].g = vColor[vColorInc]
			vColorInc += 1
			mesh.faces[faceCnt].col[3].b = vColor[vColorInc]
			vColorInc += 2

			faceCnt += 1
			i += 4

		# import vertex colors for tris to blender
		i = triDatSz[meshInc]
		while i < triDatSz[meshInc+1]:

			mesh.faces[faceCnt].col[0].r = vColor[vColorInc]
			vColorInc += 1
			mesh.faces[faceCnt].col[0].g = vColor[vColorInc]
			vColorInc += 1
			mesh.faces[faceCnt].col[0].b = vColor[vColorInc]
			vColorInc += 2

			mesh.faces[faceCnt].col[1].r = vColor[vColorInc]
			vColorInc += 1
			mesh.faces[faceCnt].col[1].g = vColor[vColorInc]
			vColorInc += 1
			mesh.faces[faceCnt].col[1].b = vColor[vColorInc]
			vColorInc += 2

			mesh.faces[faceCnt].col[2].r = vColor[vColorInc]
			vColorInc += 1
			mesh.faces[faceCnt].col[2].g = vColor[vColorInc]
			vColorInc += 1
			mesh.faces[faceCnt].col[2].b = vColor[vColorInc]
			vColorInc += 2

			faceCnt += 1
			i += 3


		# if object has texture than make "faceUV" true
		if texLinkDat[meshInc] != -1:
			mesh.faceUV = True
		else:
			mesh.faceUV = False

		print "Importing texture coordinates"
		# import texture coordinate for quads to blender

		uvFaceCnt = 0

		i = quadDatSz[meshInc]
		if texLinkDat[meshInc] != -1:
			while i < quadDatSz[meshInc+1]:

				mesh.faces[uvFaceCnt].uv[0].x = texCoord[texCoordInc]
				texCoordInc += 1
				mesh.faces[uvFaceCnt].uv[0].y = texCoord[texCoordInc]
				texCoordInc += 1

				mesh.faces[uvFaceCnt].uv[1].x = texCoord[texCoordInc]
				texCoordInc += 1
				mesh.faces[uvFaceCnt].uv[1].y = texCoord[texCoordInc]
				texCoordInc += 1

				mesh.faces[uvFaceCnt].uv[2].x = texCoord[texCoordInc]
				texCoordInc += 1
				mesh.faces[uvFaceCnt].uv[2].y = texCoord[texCoordInc]
				texCoordInc += 1

				mesh.faces[uvFaceCnt].uv[3].x = texCoord[texCoordInc]
				texCoordInc += 1
				mesh.faces[uvFaceCnt].uv[3].y = texCoord[texCoordInc]
				texCoordInc += 1

				uvFaceCnt += 1
				i += 4
		else:
			texCoordInc += (quadDatSz[meshInc+1]-i)/4*8
			uvFaceCnt += (quadDatSz[meshInc+1]-i)/4

		# import texture coordinate for tris to blender
		i = triDatSz[meshInc]
		if texLinkDat[meshInc] != -1:
			while i < triDatSz[meshInc+1]:

				mesh.faces[uvFaceCnt].uv[0].x = texCoord[texCoordInc]
				texCoordInc += 1
				mesh.faces[uvFaceCnt].uv[0].y = texCoord[texCoordInc]
				texCoordInc += 1

				mesh.faces[uvFaceCnt].uv[1].x = texCoord[texCoordInc]
				texCoordInc += 1
				mesh.faces[uvFaceCnt].uv[1].y = texCoord[texCoordInc]
				texCoordInc += 1

				mesh.faces[uvFaceCnt].uv[2].x = texCoord[texCoordInc]
				texCoordInc += 1
				mesh.faces[uvFaceCnt].uv[2].y = texCoord[texCoordInc]
				texCoordInc += 1

				uvFaceCnt += 1
				i += 3
		else:
			texCoordInc += (triDatSz[meshInc+1]-i)/3*6
			uvFaceCnt += (triDatSz[meshInc+1]-i)/3

		# import image files to blender
		print "Importing texture data"
		tex_dir = Blender.sys.dirname(file_name) + "/texture/"
		
		for i in range(0, len(imageNames)):
			try:
				imgData = Image.Load(Blender.sys.join(tex_dir, imageNames[i]))
			except IOError:
				continue
			else:
				if texLinkDat[meshInc] == i:
					for f in mesh.faces:
						f.image = imgData
		
		scene.objects.new(mesh)
	
##################################################################################################

	scene = Blender.Scene.GetCurrent()
	meshes = []
	i = len(objectNames)-1
	for ob in scene.objects:
		obtype = ob.type
		if obtype == "Mesh":
			meshes.append(ob)

		# rename objects
		if i >= 0:
			ob.name = objectNames[i]
			i -= 1


	print "Importing trasformation data for each mesh object"

	# find the first listed transformation data value
	i = 0
	while i < len(code):
		if code[0+i:7+i] == ["_", "T", "R", "A", "N", "S", "["]:
			codePos = i + 7
			i = len(code)
		i = i + 1
	
	i = codePos
	while i < len(code):
		if code[0+i:3+i] == ["]", "=", "{"]:
			codePos = i + 3
			i = len(code)
		i = i + 1

	# read the transformation data from the code
	endOfNum = 0
	numCnt = 0
	trans = []
	while endOfNum != 2:
		i = 0
		num = ""
		endOfNum = 0
		while endOfNum == 0:
			if code[codePos+i] == "," or code[codePos+i] == "}":
				endOfNum = 1
			else:
				num = num + code[codePos+i]
			if code[codePos+i] == "}":
				endOfNum = 2
			i = i + 1
		
		if endOfNum != 2:
			codePos = codePos+i
		
		if num != "":
			trans[len(trans):] = [float(num)]
	
	#Read the transformation data from file
	i = 0
	matrix = ob.getMatrix()
	while i < meshCnt:
		meshes[meshCnt-1-i].rot = [trans[i*16+0]*math.pi/180.0, trans[i*16+1]*math.pi/180.0, trans[i*16+2]*math.pi/180.0]
		meshes[meshCnt-1-i].loc = [trans[i*16+3], trans[i*16+4], trans[i*16+5]]
		meshes[meshCnt-1-i].size = [trans[i*16+6], trans[i*16+7], trans[i*16+8]]
		i = i + 1
	
	#close c file
	file.close()
Esempio n. 21
0
import Blender
from Blender import Image
from Blender import Draw, BGL

fn = "C:\\lux\\luxgui\\luxblend\\new_icons\\filter.png"

img = Image.Load(fn)
ofn = Blender.sys.makename(fn, '.txt')


def base64char(value):
    if value < 26: return chr(65 + value)
    if value < 52: return chr(97 - 26 + value)
    if value < 62: return chr(48 - 52 + value)
    if value == 62: return '+'
    return '/'


def base64value(char):
    if ord(char) in range(65, 91): return ord(char) - 65
    if ord(char) in range(97, 123): return ord(char) - 97 + 26
    if ord(char) in range(48, 58): return ord(char) - 48 + 52
    if char == '+': return 62
    return 63


s = ""
for y in range(16):
    for x in range(16):
        print x
        print y
Esempio n. 22
0
def makeTree():
    #INIZIO PROGRAMMA
    print "-------------------"
    global leafTexture, stemTexture
    global tronco, foglie
    n = baseResolutionButton.val
    #Creo Mesh del tronco
    tronco = NMesh.GetRaw("stemMesh")
    if (tronco == None): tronco = NMesh.GetRaw()
    tronco.verts = []
    tronco.faces = []

    #Creo Mesh delle foglie
    foglie = NMesh.GetRaw("leafMesh")
    if (foglie == None): foglie = NMesh.GetRaw()
    foglie.verts = []
    foglie.faces = []

    #Creo la base del tronco
    for i in range(0, n):
        x = baseFactorButton.val * cos(2 * pi * i / (n - 1))
        y = baseFactorButton.val * sin(2 * pi * i / (n - 1))
        z = 0
        v = NMesh.Vert(x, y, z)
        tronco.verts.append(v)
    #

    direction = Vector([0, 0, treeGrowSpeedButton.val, 1])
    traslTotal = TranslationMatrix(direction)
    rotTotal = RotationMatrix(0, 4, 'z')

    nTasselli = creaTronco(
        treeLengthButton.val, 0, initialMinBranchHeightButton.val,
        initialBranchFrequencyButton.val, direction, rotTotal, traslTotal,
        closureGrowFactorButton.val, 0,
        treeGrowSpeedButton.val * closureTreeGrowSpeedButton.val)

    progressMAX = nTasselli * 1.0
    #Drawing Faces TRONCO
    for j in range(0, nTasselli):
        #Al posto di 1000 mettere nTasselli/numeroRedraw (???Non so come trasformare in intero)
        if ((j % 1000) == 0):
            DrawProgressBar(j / progressMAX, "Drawing Trunc...")
        for i in range(0, n - 1):
            #print "faccia:"
            #print i
            #Evito di disegnare i punti collassati in [0,0,0] inseriti per accorgermi della giunzione
            if ((tronco.verts[(j + 1) * n + i + 1].co[0] == 0)
                    and (tronco.verts[(j + 1) * n + i + 1].co[1] == 0)
                    and (tronco.verts[(j + 1) * n + i + 1].co[2] == 0)):
                continue
            if ((tronco.verts[(j) * n + i + 1].co[0] == 0)
                    and (tronco.verts[(j) * n + i + 1].co[1] == 0)
                    and (tronco.verts[(j) * n + i + 1].co[2] == 0)):
                continue
            f = NMesh.Face()
            f.v.append(tronco.verts[j * n + i])
            f.v.append(tronco.verts[j * n + i + 1])
            f.v.append(tronco.verts[(j + 1) * n + i + 1])
            f.v.append(tronco.verts[(j + 1) * n + i])
            tronco.faces.append(f)
        #

    #Drawing Faces LEAF
    cont = 0
    numVert = 0
    numFace = 0
    f = NMesh.Face()
    nFoglie = len(foglie.verts) * 1.0
    actual_nFoglie = 0.0
    for vert in foglie.verts:
        #modificare anche qui come sopra
        if ((actual_nFoglie % 10000) == 0):
            DrawProgressBar(actual_nFoglie / nFoglie, "Drawing Leaf...")
        actual_nFoglie += 1
        numVert += 1
        #print "Aggiungo vertice"
        f.v.append(vert)
        cont += 1
        if (cont == 4):
            f.uv.append((0, 0))
            f.uv.append((1, 0))
            f.uv.append((1, 1))
            f.uv.append((0, 1))
            foglie.faces.append(f)
            f = NMesh.Face()
            #print "Stampo Faccia"
            #print numFace
            numFace += 1
            cont = 0
    #

    #Materiali, Texture, e update
    if ((not tronco.materials) and (not foglie.materials)):
        #Primo avvio: inserire materiali etcc..

        #Materiale e texture Foglia
        leafMat = Material.New("leafMaterial")
        leafMat.setAlpha(0)
        leafMat.setRGBCol([0, 0.3, 0])
        leafMat.setSpecCol([0, 0, 0])
        leafMat.mode |= Material.Modes.ZTRANSP

        leafTex = Texture.New("leafTexture")
        leafTex.setType("Image")
        image = Image.Load(defaultDirButton.val)
        leafTex.image = image
        leafTex.setImageFlags("MipMap", "UseAlpha")

        leafMat.setTexture(0, leafTex)

        leafMTexList = leafMat.getTextures()
        leafMTex = leafMTexList[0]
        leafMTex.texco = Texture.TexCo.UV
        leafMTex.mapto |= Texture.MapTo.ALPHA

        #Associo materiale
        foglie.materials.append(leafMat)

        #Materiale Tronco
        stemMat = Material.New("stemMaterial")
        stemMat.setSpecCol([0, 0, 0])

        stemTex = Texture.New("stemTexture")
        stemTex.setType("Image")

        image = Image.Load(defaultDirButtonStem.val)
        stemTex.image = image
        stemTex.setImageFlags("MipMap")

        stemMat.setTexture(0, stemTex)

        stemMTexList = stemMat.getTextures()
        stemMTex = stemMTexList[0]
        stemMTex.texco = Texture.TexCo.UV

        #Associo materiale
        tronco.materials.append(stemMat)

        NMesh.PutRaw(tronco, "stemMesh", 1)
        NMesh.PutRaw(foglie, "leafMesh", 1)

    else:
        #Neccessito solo di cambiare le immagini texture
        leafMat = foglie.materials[0]
        leafMTexList = leafMat.getTextures()
        leafMTex = leafMTexList[0]
        image = Image.Load(defaultDirButton.val)
        leafTex = leafMTex.tex
        leafTex.image = image

        stemMat = tronco.materials[0]
        stemMTexList = stemMat.getTextures()
        stemMTex = stemMTexList[0]
        image = Image.Load(defaultDirButtonStem.val)
        stemTex = stemMTex.tex
        stemTex.image = image

        tronco.update()
        foglie.update()

    DrawProgressBar(1.0, "Finished")
Esempio n. 23
0
def LoadImage(filename):
    image = Image.Load(filename)
    print "Image from", image.getFilename(),
    print "loaded to obj", image.getName()
    MakeMesh(image)
Esempio n. 24
0
def imageFromObjectsOrtho(objects,
                          path,
                          width,
                          height,
                          smooth,
                          alpha=True,
                          camera_matrix=None,
                          format=Render.PNG):
    '''
	Takes any number of objects and renders them on the z axis, between x:y-0 and x:y-1
	Usefull for making images from a mesh without per pixel operations
	- objects must be alredy placed
	- smooth, anti alias True/False
	- path renders to a PNG image
	- alpha weather to render background as alpha
	
	returns the blender image
	'''
    ext = '.' + extFromFormat(format)
    print ext
    # remove an extension if its alredy there
    if path.lower().endswith(ext):
        path = path[:-4]

    path_expand = sys.expandpath(path) + ext

    print path_expand, 'path'

    # Touch the path
    try:
        f = open(path_expand, 'w')
        f.close()
    except:
        raise 'Error, could not write to path:' + path_expand

    # RENDER THE FACES.
    scn = Scene.GetCurrent()
    render_scn = Scene.New()
    render_scn.makeCurrent()
    render_scn.Layers |= (1 << 20) - 1  # all layers enabled

    # Add objects into the current scene
    for ob in objects:
        render_scn.link(ob)

    render_context = render_scn.getRenderingContext()
    render_context.setRenderPath(
        '')  # so we can ignore any existing path and save to the abs path.

    render_context.imageSizeX(width)
    render_context.imageSizeY(height)

    if smooth:
        render_context.enableOversampling(True)
        render_context.setOversamplingLevel(16)
    else:
        render_context.enableOversampling(False)

    render_context.setRenderWinSize(100)
    render_context.setImageType(format)
    render_context.enableExtensions(True)
    #render_context.enableSky() # No alpha needed.
    if alpha:
        render_context.alphaMode = 1
        render_context.enableRGBAColor()
    else:
        render_context.alphaMode = 0
        render_context.enableRGBColor()

    render_context.displayMode = 0  # fullscreen

    # New camera and object
    render_cam_data = Camera.New('ortho')
    render_cam_ob = Object.New('Camera')
    render_cam_ob.link(render_cam_data)
    render_scn.link(render_cam_ob)
    render_scn.objects.camera = render_cam_ob

    render_cam_data.type = 'ortho'

    # Position the camera
    if camera_matrix:
        render_cam_ob.setMatrix(camera_matrix)
        # We need to take into account the matrix scaling when setting the size
        # so we get the image bounds defined by the matrix
        # first get the x and y factors from the matrix.
        # To render the correct dimensions we must use the aspy and aspy to force the matrix scale to
        # override the aspect enforced by the width and weight.
        cent = Vector() * camera_matrix
        xvec = Vector(1, 0, 0) * camera_matrix
        yvec = Vector(0, 1, 0) * camera_matrix
        # zvec= Vector(0,0,1) * camera_matrix
        xlen = (cent - xvec).length  # half height of the image
        ylen = (cent - yvec).length  # half width of the image
        # zlen = (cent-zvec).length # dist to place the camera? - just use the loc for now.

        # less then 1.0 portrate, 1.0 or more is portrate
        asp_cam_mat = xlen / ylen  # divide by zero? - possible but scripters fault.
        asp_image_res = float(width) / height
        #print 'asp quad', asp_cam_mat, 'asp_image', asp_image_res
        #print 'xylen', xlen, ylen, 'w/h', width, height
        # Setup the aspect

        if asp_cam_mat > asp_image_res:
            # camera is wider then image res.
            # to make the image wider, reduce the aspy
            asp_diff = asp_image_res / asp_cam_mat
            min_asp = asp_diff * 200
            #print 'X', min_asp

        elif asp_cam_mat < asp_image_res:  # asp_cam_mat < asp_image_res
            # camera is narrower then image res
            # to make the image narrower, reduce the aspx
            asp_diff = asp_cam_mat / asp_image_res
            min_asp = asp_diff * 200
            #print 'Y', min_asp
        else:
            min_asp = 200

        # set the camera size
        if xlen > ylen:
            if asp_cam_mat > asp_image_res:
                render_context.aspectX = 200  # get the greatest range possible
                render_context.aspectY = min_asp  # get the greatest range possible
            else:
                render_context.aspectY = 200  # get the greatest range possible
                render_context.aspectX = min_asp  # get the greatest range possible
            #print "xlen bigger"
            render_cam_data.scale = xlen * 2
        elif xlen < ylen:  # ylen is bigger
            if asp_cam_mat > asp_image_res:
                render_context.aspectX = 200  # get the greatest range possible
                render_context.aspectY = min_asp  # get the greatest range possible
            else:
                render_context.aspectY = 200  # get the greatest range possible
                render_context.aspectX = min_asp  # get the greatest range possible
            #print "ylen bigger"
            render_cam_data.scale = ylen * 2
        else:
            # asppect 1:1
            #print 'NOLEN Bigger'
            render_cam_data.scale = xlen * 2

        #print xlen, ylen, 'xlen, ylen'

    else:
        if width > height:
            min_asp = int((float(height) / width) * 200)
            render_context.aspectX = min_asp
            render_context.aspectY = 200
        else:
            min_asp = int((float(width) / height) * 200)
            render_context.aspectX = 200
            render_context.aspectY = min_asp

        render_cam_data.scale = 1.0
        render_cam_ob.LocZ = 1.0
        render_cam_ob.LocX = 0.5
        render_cam_ob.LocY = 0.5

    Blender.Window.RedrawAll()

    render_context.render()
    render_context.saveRenderedImage(path)
    Render.CloseRenderWindow()
    #if not B.sys.exists(PREF_IMAGE_PATH_EXPAND):
    #	raise 'Error!!!'

    scn.makeCurrent()
    Scene.Unlink(render_scn)

    # NOW APPLY THE SAVED IMAGE TO THE FACES!
    #print PREF_IMAGE_PATH_EXPAND
    try:
        target_image = Image.Load(path_expand)
        return target_image
    except:
        raise 'Error: Could not render or load the image at path "%s"' % path_expand
        return
Esempio n. 25
0
def imgImport(imgPath):
	global CUROFFS, PARAMS
	######################################
	# Load the image
	######################################
	try:
		img = Image.Load(imgPath)
		imgDimensions = img.getSize() # do this to ensure the data is available
	except:
		Blender.Draw.PupMenu('Error%t|Unsupported image format for "'+ imgPath.split('\\')[-1].split('/')[-1] +'"')
		return		
	
	if PARAMS['PackImage']:
		img.pack()
	name = Blender.sys.makename(imgPath, strip = 1)
	
	######################################
	# Construct the mesh
	######################################
	
	me = Mesh.New(name)
	
	# Calculate Dimensions from Image Size
	dim = [float(i)/PARAMS['PPU'] for i in imgDimensions]
	v = [[dim[0], dim[1], 0], [-dim[0], dim[1], 0], [-dim[0], -dim[1], 0], [dim[0], -dim[1], 0]]
	me.verts.extend(v)
	me.faces.extend([0, 1, 2, 3])
	
	me.faces[0].image = img
	me.faces[0].uv = [Vector(1.0, 1.0), Vector(0.0, 1.0), Vector(0.0, 0.0), Vector(1.0, 0.0)]
	
	if PARAMS['MakeTransp']:
		me.faces[0].transp = Mesh.FaceTranspModes.ALPHA
	
	######################################
	# Modify the Material
	######################################
	
	mat = None
	if not PARAMS['NewMat']:
		mat = PARAMS['Materials'][PARAMS['MaterialId']].__copy__()
		mat.setName(name)
	else:
		mat = Material.New(name)
		properties = PARAMS['MatProps']
		mat.setRGBCol(properties['Col'])
		mat.setRef(properties['Ref'])
		mat.setSpec(properties['Spec'])
		mat.setHardness(properties['Hard'])
		mat.setAlpha(properties['Alpha'])
		
		if properties['Shadeless']:
			mat.mode |= Material.Modes.SHADELESS
		if properties['ZTransp']:
			mat.mode |= Material.Modes.ZTRANSP
	
	properties = PARAMS['TexProps']
		
	tex = Texture.New(name)
	tex.setType('Image')
	tex.setImage(img)
	if properties['UseAlpha']:
		tex.useAlpha = Texture.ImageFlags.USEALPHA
			
	if properties['CalcAlpha']:
		tex.calcAlpha = Texture.ImageFlags.CALCALPHA
		
	if properties['ExtendMode']:
		tex.setExtend('Extend')
		
	if PARAMS['ImageProp'] == Image.Sources.SEQUENCE:
		properties = PARAMS['SeqProps']
		
		img.source = PARAMS['ImageProp'] # Needs to be done here, otherwise an error with earlier getSize()
		
		tex.animStart = properties['StartFr']
		tex.animOffset = properties['Offs']
		tex.animFrames = properties['Frames']
		tex.autoRefresh = properties['AutoRefresh']
		tex.cyclic = properties['Cyclic']
			
	texMapSetters = Texture.TexCo.UV
	
	# PARAMS['TexMapTo']['Col'] (and alpha) will either be 0 or 1 because its from a toggle, otherwise this line doesn't work
	texChanSetters = Texture.MapTo.COL * PARAMS['TexMapTo']['Col'] | Texture.MapTo.ALPHA * PARAMS['TexMapTo']['Alpha']
	
	mat.setTexture(PARAMS['TexChannel'], tex, texMapSetters, texChanSetters)
	me.materials += [mat]
	
	######################################
	# Object Construction
	######################################
	
	ob = scn.objects.new(me, name)
	p = Vector(ob.getLocation()) # Should be the origin, but just to be safe, get it
	ob.setLocation((CUROFFS * PARAMS['ObOffset']) + p)
		
	return
Esempio n. 26
0
stop = 0
showHelp = 0
guiPopup = 0

# initial button values
exportPath = Draw.Create(
    Get("filename")[0:Get("filename").rfind(".")] +
    ".i3d")  #creates a text box thing

#mouse x/y (just for fun)
#mouseX = 0
#mouseY = 0

logo = false
try:
    logo = Image.Load(Get("scriptsdir") + "/morc.png")
except:
    logo = false


def gui():
    global evtExport, evtPathChanged, evtBrows
    global exportPath
    global guiExport, guiBrows, guiExportSelection, guiExportNormals, guiExportTriangulated, guiAddObjExtension, guiAddMatExtension, guiLogo

    guiAddObjExtension = Draw.PushButton(
        "add obj script link", evtAddObjExtension, 10, 155, 150, 25,
        "add a text file for more i3d object properties and link it to the active object via script links"
    )
    guiAddMatExtension = Draw.PushButton(
        "add mat script link", evtAddMatExtension, 175, 155, 155, 25,
Esempio n. 27
0
#
# 2007-10-16 v2.45
#  - Fix for Blender 2.45
#
# 2008-04-08 v3.09
#  - Fix for break in version 3.03
#

import Blender
from Blender import Draw, Image, Scene, NMesh, Window
from os.path import splitext

(newfile, ext) = splitext(Blender.Get('filename'))
for ext in ['.dds', '.DDS', '.png', '.PNG', '.bmp', '.BMP']:
    try:
        tex = Image.Load(newfile + ext)
        dim = tex.getSize()

        for ob in Scene.GetCurrent().objects:
            if ob.getType() == "Mesh" and ob.getData().hasFaceUV():
                mesh = ob.getData()
                for face in mesh.faces:
                    if face.mode & NMesh.FaceModes.TEX and face.image:
                        oldfile = face.image.filename.lower()
                        if '_paint.' in oldfile:
                            for i in range(len(face.uv)):
                                (s, t) = face.uv[i]
                                face.uv[i] = (s / 2, t)
                                face.image = tex
                        elif '_paint2.' in oldfile:
                            for i in range(len(face.uv)):