Example #1
0
def LoadConfigData(key=None):
    """
	Load config data from file(s) to the Registry dictionary.
	@type key: string
	@param key: a given key name.  If None (default), all available keys are
		loaded.
	@returns: None
	"""

    _check_dir()

    import os

    if not key:
        files = \
         [bsys.join(_CFG_DIR, f) for f in os.listdir(_CFG_DIR) if f.endswith(_EXT)]
    else:
        files = []
        fname = bsys.join(_CFG_DIR, "%s%s" % (key, _EXT))
        if bsys.exists(fname): files.append(fname)

    for p in files:
        try:
            f = file(p, 'r')
            lines = f.readlines()
            f.close()
            if lines:  # Lines may be blank
                mainkey = lines[0].split('=')[0].strip()
                pysrc = "\n".join(lines)
                exec(pysrc)
                exec("Registry.SetKey('%s', %s)" % (str(mainkey), mainkey))
        except Exception, e:
            raise Warning(e)  # Resend exception as warning
Example #2
0
def RemoveConfigData(key=None):
    """
	Remove this key's config file from the <(u)datadir>/config/ folder.
	@type key: string
	@param key: the name of the key to be removed.  If None (default) all
		available config files are deleted.
	"""

    _check_dir()

    if not key:
        files = \
         [bsys.join(_CFG_DIR, f) for f in os.listdir(_CFG_DIR) if f.endswith(_EXT)]
    else:
        files = []
        fname = bsys.join(_CFG_DIR, "%s%s" % (key, _EXT))
        if bsys.exists(fname): files.append(fname)

    import os

    try:
        for p in files:
            os.remove(p)  # remove the file(s)
    except Exception, e:
        raise Warning(e)  # Resend exception as warning
Example #3
0
def LoadConfigData (key = None):
	"""
	Load config data from file(s) to the Registry dictionary.
	@type key: string
	@param key: a given key name.  If None (default), all available keys are
		loaded.
	@returns: None
	"""

	_check_dir()

	import os

	if not key:
		files = \
			[bsys.join(_CFG_DIR, f) for f in os.listdir(_CFG_DIR) if f.endswith(_EXT)]
	else:
		files = []
		fname = bsys.join(_CFG_DIR, "%s%s" % (key, _EXT))
		if bsys.exists(fname): files.append(fname)

	for p in files:
		try:
			f = file(p, 'r')
			lines = f.readlines()
			f.close()
			if lines: # Lines may be blank
				mainkey = lines[0].split('=')[0].strip()
				pysrc = "\n".join(lines)
				exec(pysrc)
				exec("Registry.SetKey('%s', %s)" % (str(mainkey), mainkey))
		except Exception, e:
			raise Warning(e) # Resend exception as warning
Example #4
0
def RemoveConfigData (key = None):
	"""
	Remove this key's config file from the <(u)datadir>/config/ folder.
	@type key: string
	@param key: the name of the key to be removed.  If None (default) all
		available config files are deleted.
	"""

	_check_dir()

	if not key:
		files = \
			[bsys.join(_CFG_DIR, f) for f in os.listdir(_CFG_DIR) if f.endswith(_EXT)]
	else:
		files = []
		fname = bsys.join(_CFG_DIR, "%s%s" % (key, _EXT))
		if bsys.exists(fname): files.append(fname)

	import os

	try:
		for p in files:
			os.remove(p) # remove the file(s)
	except Exception, e:
		raise Warning(e) # Resend exception as warning
Example #5
0
def button_event(evt):  # gui button events

    global SCREEN, START_SCREEN, SCRIPT_SCREEN
    global BEVT_LINK, BEVT_EMAIL, BEVT_GMENU, BUT_GMENU, SCRIPT_INFO
    global SCROLL_DOWN, FMODE

    if evt >= 100:  # group menus
        for i in range(len(BUT_GMENU)):
            if evt == BEVT_GMENU[i]:
                group = AllGroups[i]
                index = BUT_GMENU[i].val - 1
                if index < 0: return  # user didn't pick a menu entry
                script = group.get_scripts()[BUT_GMENU[i].val - 1]
                if parse_help_info(script):
                    SCREEN = SCRIPT_SCREEN
                    BEVT_LINK = range(20, len(SCRIPT_INFO.d['__url__']) + 20)
                    BEVT_EMAIL = range(50,
                                       len(SCRIPT_INFO.d['__email__']) + 50)
                    Draw.Redraw()
                else:
                    res = Draw.PupMenu(
                        "No help available%t|View Source|Cancel")
                    if res == 1:
                        load_script_text(script)
    elif evt >= 20:
        if not WEBBROWSER:
            Draw.PupMenu(
                'Missing standard Python module%t|You need module "webbrowser" to access the web'
            )
            return

        if evt >= 50:  # script screen email buttons
            email = SCRIPT_INFO.d['__email__'][evt - 50][1]
            webbrowser.open("mailto:%s" % email)
        else:  # >= 20: script screen link buttons
            link = SCRIPT_INFO.d['__url__'][evt - 20][1]
            webbrowser.open(link)
    elif evt == BEVT_VIEWSOURCE:
        if SCREEN == SCRIPT_SCREEN: load_script_text(SCRIPT_INFO.script)
    elif evt == BEVT_EXIT:
        Draw.Exit()
        return
    elif evt == BEVT_BACK:
        if SCREEN == SCRIPT_SCREEN and not FMODE:
            SCREEN = START_SCREEN
            SCRIPT_INFO = None
            SCROLL_DOWN = 0
            Draw.Redraw()
    elif evt == BEVT_EXEC:  # Execute script
        exec_line = ''
        if SCRIPT_INFO.script.userdir:
            exec_line = bsys.join(Blender.Get('uscriptsdir'),
                                  SCRIPT_INFO.script.fname)
        else:
            exec_line = bsys.join(Blender.Get('scriptsdir'),
                                  SCRIPT_INFO.script.fname)

        Blender.Run(exec_line)
Example #6
0
def button_event(evt): # gui button events

	global SCREEN, START_SCREEN, SCRIPT_SCREEN
	global BEVT_LINK, BEVT_EMAIL, BEVT_GMENU, BUT_GMENU, SCRIPT_INFO
	global SCROLL_DOWN, FMODE

	if evt >= 100: # group menus
		for i in range(len(BUT_GMENU)):
			if evt == BEVT_GMENU[i]:
				group = AllGroups[i]
				index = BUT_GMENU[i].val - 1
				if index < 0: return # user didn't pick a menu entry
				script = group.get_scripts()[BUT_GMENU[i].val - 1]
				if parse_help_info(script):
					SCREEN = SCRIPT_SCREEN
					BEVT_LINK = range(20, len(SCRIPT_INFO.d['__url__']) + 20)
					BEVT_EMAIL = range(50, len(SCRIPT_INFO.d['__email__']) + 50)
					Draw.Redraw()
				else:
					res = Draw.PupMenu("No help available%t|View Source|Cancel")
					if res == 1:
						load_script_text(script)
	elif evt >= 20:
		if not WEBBROWSER:
			Draw.PupMenu('Missing standard Python module%t|You need module "webbrowser" to access the web')
			return

		if evt >= 50: # script screen email buttons
			email = SCRIPT_INFO.d['__email__'][evt - 50][1]
			webbrowser.open("mailto:%s" % email)
		else: # >= 20: script screen link buttons
			link = SCRIPT_INFO.d['__url__'][evt - 20][1]
			webbrowser.open(link)
	elif evt == BEVT_VIEWSOURCE:
		if SCREEN == SCRIPT_SCREEN: load_script_text(SCRIPT_INFO.script)
	elif evt == BEVT_EXIT:
		Draw.Exit()
		return
	elif evt == BEVT_BACK:
		if SCREEN == SCRIPT_SCREEN and not FMODE:
			SCREEN = START_SCREEN
			SCRIPT_INFO = None
			SCROLL_DOWN = 0
			Draw.Redraw()
	elif evt == BEVT_EXEC: # Execute script
		exec_line = ''
		if SCRIPT_INFO.script.userdir:
			exec_line = bsys.join(Blender.Get('uscriptsdir'), SCRIPT_INFO.script.fname)
		else:
			exec_line = bsys.join(Blender.Get('scriptsdir'), SCRIPT_INFO.script.fname)

		Blender.Run(exec_line)
Example #7
0
def SaveConfigData(key=None):
    """
	Save Registry key(s) as file(s) in the <(u)datadir>/config/ folder.
	@type key: string
	@param key: the name of the key to be saved.  If None (default) all
		available keys are saved.
	"""

    global _KEYS, _CFG_DIR

    _check_dir()

    if key: keys = [key]
    else: keys = _KEYS

    for mainkey in keys:
        cfgdict = Registry.GetKey(mainkey).copy()
        for k in cfgdict:  # .keys()
            if not k or k[0] == '_':
                del cfgdict[k]

        if not cfgdict: continue

        try:
            filename = bsys.join(_CFG_DIR, "%s%s" % (mainkey, _EXT))
            f = file(filename, 'w')
            output = _dict_to_str(mainkey, _sanitize(cfgdict))
            if output != 'None':
                f.write(output)
                f.close()
        except Exception, e:
            raise Warning(e)  # Resend exception as warning
Example #8
0
def fs_callback(filename):
    global cmd, extension, scriptsdir
    if not filename.endswith(extension):
        filename = '%s%s' % (filename, extension)
    if bsys.exists(filename):
        if Blender.Draw.PupMenu('OVERWRITE?%t|File exists') != 1:
            return
    if cmd:
        tmp = bsys.join(scriptsdir, "tmp.xml")
        write_obj(tmp)

        print "running glexemel"
        cmd = [cmd, tmp, filename]
        print cmd
        p = subprocess.Popen(cmd,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        out = p.stdout.read()
        err = p.stderr.read()
        res = p.wait()
        if res != 0 or err:
            s = ''
            if out:
                s += out.replace('\n', '|')
            if err:
                s += err.replace('\n', '|')
            Blender.Draw.PupMenu('glexemel error: see console%t|' + s)
        print out
        print err
        print res
    else:
        write_obj(filename)
        print "glexemel not found"
Example #9
0
def SaveConfigData (key = None):
	"""
	Save Registry key(s) as file(s) in the <(u)datadir>/config/ folder.
	@type key: string
	@param key: the name of the key to be saved.  If None (default) all
		available keys are saved.
	"""

	global _KEYS, _CFG_DIR

	_check_dir()

	if key: keys = [key]
	else: keys = _KEYS

	for mainkey in keys:
		cfgdict = Registry.GetKey(mainkey).copy()
		for k in cfgdict: # .keys()
			if not k or k[0] == '_':
				del cfgdict[k]

		if not cfgdict: continue

		try:
			filename = bsys.join(_CFG_DIR, "%s%s" % (mainkey, _EXT))
			f = file(filename, 'w')
			output = _dict_to_str(mainkey, _sanitize(cfgdict))
			if output!='None':
				f.write(output)
				f.close()
		except Exception, e:
			raise Warning(e) # Resend exception as warning
Example #10
0
def load_script_text(script):
	global PATHS, SCRIPT_INFO

	if script.userdir:
		path = PATHS['uscripts']
	else:
		path = PATHS['scripts']

	fname = bsys.join(path, script.fname)

	source = Blender.Text.Load(fname)
	if source:
		Draw.PupMenu("File loaded%%t|Please check the file \"%s\" in the Text Editor window" % source.name)
Example #11
0
def load_script_text(script):
    global PATHS, SCRIPT_INFO

    if script.userdir:
        path = PATHS['uscripts']
    else:
        path = PATHS['scripts']

    fname = bsys.join(path, script.fname)

    source = Blender.Text.Load(fname)
    if source:
        Draw.PupMenu(
            "File loaded%%t|Please check the file \"%s\" in the Text Editor window"
            % source.name)
Example #12
0
	def texture(self, faces):
		tex = ""
		for f in faces:
			if f.image:
				tex = f.image.name
				break
		if tex:
			image = Image.Get(tex)
			texfname = image.filename
			if SET_TEX_DIR:
				texfname = bsys.basename(texfname)
				if TEX_DIR:
					texfname = bsys.join(TEX_DIR, texfname)
			buf = 'texture "%s"\n' % texfname
			xrep = image.xrep
			yrep = image.yrep
			buf += 'texrep %s %s\n' % (xrep, yrep)
			self.file.write(buf)
	def texture(self, faces):
		tex = ""
		for f in faces:
			if f.image:
				tex = f.image.name
				break
		if tex:
			image = Image.Get(tex)
			texfname = image.filename
			if SET_TEX_DIR:
				texfname = bsys.basename(texfname)
				if TEX_DIR:
					texfname = bsys.join(TEX_DIR, texfname)
			buf = 'texture "%s"\n' % texfname
			xrep = image.xrep
			yrep = image.yrep
			# buf += 'texrep %s %s\n' % (xrep, yrep)
			self.file.write(buf)
Example #14
0
def fill_scripts_dict():
    global ALL_SCRIPTS, ALL_GROUPS

    group = ''
    group_len = 0
    sep = bsys.sep
    home = Blender.Get('homedir')
    if not home:
        errmsg = """
Can't find Blender's home dir and so can't find the
Bpymenus file automatically stored inside it, which
is needed by this script.  Please run the
Help -> System -> System Information script to get
information about how to fix this.
"""
        raise SystemError, errmsg
    fname = bsys.join(home, 'Bpymenus')
    if not bsys.exists(fname): return False
    f = file(fname, 'r')
    lines = f.readlines()
    f.close()
    for l in lines:
        if l.rfind('{') > 0:
            group = l.split()[0]
            ALL_GROUPS.append(group)
            group_len += 1
            continue
        elif l[0] != "'":
            continue
        fields = l.split("'")
        if len(fields) > 2:
            menuname = fields[1].replace('...', '')
            fields = fields[2].split()
            if len(fields) > 1:
                fname = fields[1].split(sep)[-1]
                i = 1
                while not fname.endswith('.py'):
                    i += 1
                    fname = "%s %s" % (fname, fields[i])
                ALL_SCRIPTS[fname] = (menuname, group_len - 1)
    return True
Example #15
0
def fill_scripts_dict():
	global ALL_SCRIPTS, ALL_GROUPS

	group = ''
	group_len = 0
	sep = bsys.sep
	home = Blender.Get('homedir')
	if not home:
		errmsg = """
Can't find Blender's home dir and so can't find the
Bpymenus file automatically stored inside it, which
is needed by this script.  Please run the
Help -> System -> System Information script to get
information about how to fix this.
"""
		raise SystemError, errmsg
	fname = bsys.join(home, 'Bpymenus')
	if not bsys.exists(fname): return False
	f = file(fname, 'r')
	lines = f.readlines()
	f.close()
	for l in lines:
		if l.rfind('{') > 0:
			group = l.split()[0]
			ALL_GROUPS.append(group)
			group_len += 1
			continue
		elif l[0] != "'": continue
		fields = l.split("'")
		if len(fields) > 2:
			menuname = fields[1].replace('...','')
			fields = fields[2].split()
			if len(fields) > 1:
				fname = fields[1].split(sep)[-1]
				i = 1
				while not fname.endswith('.py'):
					i += 1
					fname = "%s %s" % (fname, fields[i])
				ALL_SCRIPTS[fname] = (menuname, group_len - 1)
	return True
Example #16
0
def HasConfigData(key):
    """
	Check if the given key exists, either already loaded in the Registry dict or
	as a file in the script data config dir.
	@type key: string
	@param key: a given key name.
	@returns:
		- 0: key does not exist;
		- 1: key exists in the Registry dict only;
		- 2: key exists as a file only;
		- 3: key exists in the Registry dict and also as a file.
	@note: for readability it's better to check against the constant bitmasks
		BPY_KEY_MISSING = 0, BPY_KEY_IN_REGISTRY = 1 and BPY_KEY_IN_FILE = 2.
	"""

    fname = bsys.join(_CFG_DIR, "%s%s" % (key, _EXT))

    result = BPY_KEY_MISSING
    if key in Registry.Keys(): result |= BPY_KEY_IN_REGISTRY
    if bsys.exists(fname): result |= BPY_KEY_IN_FILE

    return result
Example #17
0
def HasConfigData (key):
	"""
	Check if the given key exists, either already loaded in the Registry dict or
	as a file in the script data config dir.
	@type key: string
	@param key: a given key name.
	@returns:
		- 0: key does not exist;
		- 1: key exists in the Registry dict only;
		- 2: key exists as a file only;
		- 3: key exists in the Registry dict and also as a file.
	@note: for readability it's better to check against the constant bitmasks
		BPY_KEY_MISSING = 0, BPY_KEY_IN_REGISTRY = 1 and BPY_KEY_IN_FILE = 2.
	"""

	fname = bsys.join(_CFG_DIR, "%s%s" % (key, _EXT))

	result = BPY_KEY_MISSING
	if key in Registry.Keys(): result |= BPY_KEY_IN_REGISTRY
	if bsys.exists(fname): result |= BPY_KEY_IN_FILE

	return result
Example #18
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.mirCol = (mat[6][0], mat[6][1], mat[6][2])
			m.alpha = mat[7]
			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()
Example #19
0
		test = AC3DExport(OBJS, file)
	except:
		file.close()
		raise
	else:
		file.close()
		endtime = bsys.time() - starttime
		REPORT_DATA['main'].append("Done. Saved to: %s" % filename)
		REPORT_DATA['main'].append("Data exported in %.3f seconds." % endtime)

	if VERBOSE: report_data()
	Blender.Window.WaitCursor(0)


# -- End of definitions

scn = Blender.Scene.GetCurrent()

if ONLY_SELECTED:
	OBJS = list(scn.objects.context)
else:
	OBJS = list(scn.objects)

if not OBJS:
	Blender.Draw.PupMenu('ERROR: no objects selected')
else:
	fname = bsys.makename(ext=".ac")
	if EXPORT_DIR:
		fname = bsys.join(EXPORT_DIR, bsys.basename(fname))
	FileSelector(fs_callback, "Export AC3D", fname)
Example #20
0
    def texture(self, faces, mesh):
        uvlayer0 = ""
        uvlayer1 = ""
        uvlayer2 = ""
        uvlayer3 = ""

        uvlayers = mesh.getUVLayerNames()
        numlayer = len(uvlayers)
        if numlayer > 0:
            uvlayer0 = uvlayers[0]
        if numlayer > 1:
            uvlayer1 = uvlayers[1]
        if numlayer > 2:
            uvlayer2 = uvlayers[2]
        if numlayer > 3:
            uvlayer3 = uvlayers[3]

        mmat = mesh.materials
        tex = ""
        for f in faces:
            if f.image:
                tex = f.image.name
                break
        if tex:
            image = Image.Get(tex)
            texfname = image.filename
            if SET_TEX_DIR:
                texfname = bsys.basename(texfname)
                if TEX_DIR:
                    texfname = bsys.join(TEX_DIR, texfname)
            buf = 'texture "%s" base\n' % texfname
            #TODO support multi textures
            #lookup second texture value
            fmat = mmat[f.mat]
            tex1 = ""
            tex2 = ""
            mtextures = fmat.getTextures()
            for mtex in mtextures:
                if not (mtex == None):
                    if mtex.uvlayer == uvlayer1:
                        img1 = mtex.tex.getImage()
                        tex1 = img1.getFilename()
                        tex1 = bsys.basename(tex1)
                    if mtex.uvlayer == uvlayer2:
                        img2 = mtex.tex.getImage()
                        tex2 = img2.getFilename()
                        tex2 = bsys.basename(tex2)

            if tex1 != "":
                buf += 'texture "'
                buf += tex1
                buf += '" tiled\n'
            else:
                buf += 'texture empty_texture_no_mapping skids\n'

            if tex2 != "":
                buf += 'texture "'
                buf += tex2
                buf += '" tiled\n'
            else:
                buf += 'texture empty_texture_no_mapping skids\n'

            buf += 'texture empty_texture_no_mapping shad\n'

            xrep = image.xrep
            yrep = image.yrep
            #			buf += 'texrep %s %s\n' % (xrep, yrep)
            self.file.write(buf)
		test = AC3DExport(OBJS, file)
	except:
		file.close()
		raise
	else:
		file.close()
		endtime = bsys.time() - starttime
		REPORT_DATA['main'].append("Done. Saved to: %s" % filename)
		REPORT_DATA['main'].append("Data exported in %.3f seconds." % endtime)

	if VERBOSE: report_data()
	Blender.Window.WaitCursor(0)


# -- End of definitions

scn = Blender.Scene.GetCurrent()

if ONLY_SELECTED:
	OBJS = list(scn.objects.context)
else:
	OBJS = list(scn.objects)

if not OBJS:
	Blender.Draw.PupMenu('ERROR: no objects selected')
else:
	fname = bsys.makename(ext=".ac")
	if EXPORT_DIR:
		fname = bsys.join(EXPORT_DIR, bsys.basename(fname))
	FileSelector(fs_callback, "Export AC3D", fname)
Example #22
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()
Example #23
0
def load_obj_ui(filepath, BATCH_LOAD=False):
    if BPyMessages.Error_NoFile(filepath):
        return

    global CREATE_SMOOTH_GROUPS, CREATE_FGONS, CREATE_EDGES, SPLIT_OBJECTS, SPLIT_GROUPS, SPLIT_MATERIALS, CLAMP_SIZE, IMAGE_SEARCH, POLYGROUPS, KEEP_VERT_ORDER, ROTATE_X90

    CREATE_SMOOTH_GROUPS = Draw.Create(0)
    CREATE_FGONS = Draw.Create(1)
    CREATE_EDGES = Draw.Create(1)
    SPLIT_OBJECTS = Draw.Create(0)
    SPLIT_GROUPS = Draw.Create(0)
    SPLIT_MATERIALS = Draw.Create(0)
    CLAMP_SIZE = Draw.Create(10.0)
    IMAGE_SEARCH = Draw.Create(1)
    POLYGROUPS = Draw.Create(0)
    KEEP_VERT_ORDER = Draw.Create(1)
    ROTATE_X90 = Draw.Create(1)

    # Get USER Options
    # Note, Works but not pretty, instead use a more complicated GUI
    '''
	pup_block= [\
	'Import...',\
	('Smooth Groups', CREATE_SMOOTH_GROUPS, 'Surround smooth groups by sharp edges'),\
	('Create FGons', CREATE_FGONS, 'Import faces with more then 4 verts as fgons.'),\
	('Lines', CREATE_EDGES, 'Import lines and faces with 2 verts as edges'),\
	'Separate objects from obj...',\
	('Object', SPLIT_OBJECTS, 'Import OBJ Objects into Blender Objects'),\
	('Group', SPLIT_GROUPS, 'Import OBJ Groups into Blender Objects'),\
	('Material', SPLIT_MATERIALS, 'Import each material into a seperate mesh (Avoids > 16 per mesh error)'),\
	'Options...',\
	('Keep Vert Order', KEEP_VERT_ORDER, 'Keep vert and face order, disables some other options.'),\
	('Clamp Scale:', CLAMP_SIZE, 0.0, 1000.0, 'Clamp the size to this maximum (Zero to Disable)'),\
	('Image Search', IMAGE_SEARCH, 'Search subdirs for any assosiated images (Warning, may be slow)'),\
	]
	
	if not Draw.PupBlock('Import OBJ...', pup_block):
		return
	
	if KEEP_VERT_ORDER.val:
		SPLIT_OBJECTS.val = False
		SPLIT_GROUPS.val = False
		SPLIT_MATERIALS.val = False
	'''

    # BEGIN ALTERNATIVE UI *******************
    if True:

        EVENT_NONE = 0
        EVENT_EXIT = 1
        EVENT_REDRAW = 2
        EVENT_IMPORT = 3

        GLOBALS = {}
        GLOBALS['EVENT'] = EVENT_REDRAW
        #GLOBALS['MOUSE'] = Window.GetMouseCoords()
        GLOBALS['MOUSE'] = [i / 2 for i in Window.GetScreenSize()]

        def obj_ui_set_event(e, v):
            GLOBALS['EVENT'] = e

        def do_split(e, v):
            global SPLIT_OBJECTS, SPLIT_GROUPS, SPLIT_MATERIALS, KEEP_VERT_ORDER, POLYGROUPS
            if SPLIT_OBJECTS.val or SPLIT_GROUPS.val or SPLIT_MATERIALS.val:
                KEEP_VERT_ORDER.val = 0
                POLYGROUPS.val = 0
            else:
                KEEP_VERT_ORDER.val = 1

        def do_vertorder(e, v):
            global SPLIT_OBJECTS, SPLIT_GROUPS, SPLIT_MATERIALS, KEEP_VERT_ORDER
            if KEEP_VERT_ORDER.val:
                SPLIT_OBJECTS.val = SPLIT_GROUPS.val = SPLIT_MATERIALS.val = 0
            else:
                if not (SPLIT_OBJECTS.val or SPLIT_GROUPS.val
                        or SPLIT_MATERIALS.val):
                    KEEP_VERT_ORDER.val = 1

        def do_polygroups(e, v):
            global SPLIT_OBJECTS, SPLIT_GROUPS, SPLIT_MATERIALS, KEEP_VERT_ORDER, POLYGROUPS
            if POLYGROUPS.val:
                SPLIT_OBJECTS.val = SPLIT_GROUPS.val = SPLIT_MATERIALS.val = 0

        def do_help(e, v):
            url = __url__[0]
            print 'Trying to open web browser with documentation at this address...'
            print '\t' + url

            try:
                import webbrowser
                webbrowser.open(url)
            except:
                print '...could not open a browser window.'

        def obj_ui():
            ui_x, ui_y = GLOBALS['MOUSE']

            # Center based on overall pup size
            ui_x -= 165
            ui_y -= 90

            global CREATE_SMOOTH_GROUPS, CREATE_FGONS, CREATE_EDGES, SPLIT_OBJECTS, SPLIT_GROUPS, SPLIT_MATERIALS, CLAMP_SIZE, IMAGE_SEARCH, POLYGROUPS, KEEP_VERT_ORDER, ROTATE_X90

            Draw.Label('Import...', ui_x + 9, ui_y + 159, 220, 21)
            Draw.BeginAlign()
            CREATE_SMOOTH_GROUPS = Draw.Toggle(
                'Smooth Groups', EVENT_NONE, ui_x + 9, ui_y + 139, 110, 20,
                CREATE_SMOOTH_GROUPS.val,
                'Surround smooth groups by sharp edges')
            CREATE_FGONS = Draw.Toggle(
                'NGons as FGons', EVENT_NONE, ui_x + 119, ui_y + 139, 110, 20,
                CREATE_FGONS.val,
                'Import faces with more then 4 verts as fgons')
            CREATE_EDGES = Draw.Toggle(
                'Lines as Edges', EVENT_NONE, ui_x + 229, ui_y + 139, 110, 20,
                CREATE_EDGES.val,
                'Import lines and faces with 2 verts as edges')
            Draw.EndAlign()

            Draw.Label('Separate objects by OBJ...', ui_x + 9, ui_y + 110, 220,
                       20)
            Draw.BeginAlign()
            SPLIT_OBJECTS = Draw.Toggle(
                'Object', EVENT_REDRAW, ui_x + 9, ui_y + 89, 55, 21,
                SPLIT_OBJECTS.val, 'Import OBJ Objects into Blender Objects',
                do_split)
            SPLIT_GROUPS = Draw.Toggle(
                'Group', EVENT_REDRAW, ui_x + 64, ui_y + 89, 55, 21,
                SPLIT_GROUPS.val, 'Import OBJ Groups into Blender Objects',
                do_split)
            SPLIT_MATERIALS = Draw.Toggle(
                'Material', EVENT_REDRAW, ui_x + 119, ui_y + 89, 60, 21,
                SPLIT_MATERIALS.val,
                'Import each material into a seperate mesh (Avoids > 16 per mesh error)',
                do_split)
            Draw.EndAlign()

            # Only used for user feedback
            KEEP_VERT_ORDER = Draw.Toggle(
                'Keep Vert Order', EVENT_REDRAW, ui_x + 184, ui_y + 89, 113,
                21, KEEP_VERT_ORDER.val,
                'Keep vert and face order, disables split options, enable for morph targets',
                do_vertorder)

            ROTATE_X90 = Draw.Toggle('-X90', EVENT_REDRAW, ui_x + 302,
                                     ui_y + 89, 38, 21, ROTATE_X90.val,
                                     'Rotate X 90.')

            Draw.Label('Options...', ui_x + 9, ui_y + 60, 211, 20)
            CLAMP_SIZE = Draw.Number(
                'Clamp Scale: ', EVENT_NONE, ui_x + 9, ui_y + 39, 130, 21,
                CLAMP_SIZE.val, 0.0, 1000.0,
                'Clamp the size to this maximum (Zero to Disable)')
            POLYGROUPS = Draw.Toggle('Poly Groups', EVENT_REDRAW, ui_x + 144,
                                     ui_y + 39, 90, 21, POLYGROUPS.val,
                                     'Import OBJ groups as vertex groups.',
                                     do_polygroups)
            IMAGE_SEARCH = Draw.Toggle(
                'Image Search', EVENT_NONE, ui_x + 239, ui_y + 39, 100, 21,
                IMAGE_SEARCH.val,
                'Search subdirs for any assosiated images (Warning, may be slow)'
            )
            Draw.BeginAlign()
            Draw.PushButton('Online Help', EVENT_REDRAW, ui_x + 9, ui_y + 9,
                            110, 21, 'Load the wiki page for this script',
                            do_help)
            Draw.PushButton('Cancel', EVENT_EXIT, ui_x + 119, ui_y + 9, 110,
                            21, '', obj_ui_set_event)
            Draw.PushButton('Import', EVENT_IMPORT, ui_x + 229, ui_y + 9, 110,
                            21, 'Import with these settings', obj_ui_set_event)
            Draw.EndAlign()

        # hack so the toggle buttons redraw. this is not nice at all
        while GLOBALS['EVENT'] not in (EVENT_EXIT, EVENT_IMPORT):
            Draw.UIBlock(obj_ui, 0)

        if GLOBALS['EVENT'] != EVENT_IMPORT:
            return

    # END ALTERNATIVE UI *********************

    Window.WaitCursor(1)

    if BATCH_LOAD:  # load the dir
        try:
            files = [
                f for f in os.listdir(filepath) if f.lower().endswith('.obj')
            ]
        except:
            Window.WaitCursor(0)
            Draw.PupMenu('Error%t|Could not open path ' + filepath)
            return

        if not files:
            Window.WaitCursor(0)
            Draw.PupMenu('Error%t|No files at path ' + filepath)
            return

        for f in files:
            scn = bpy.data.scenes.new(stripExt(f))
            scn.makeCurrent()

            load_obj(sys.join(filepath, f),\
              CLAMP_SIZE.val,\
              CREATE_FGONS.val,\
              CREATE_SMOOTH_GROUPS.val,\
              CREATE_EDGES.val,\
              SPLIT_OBJECTS.val,\
              SPLIT_GROUPS.val,\
              SPLIT_MATERIALS.val,\
              ROTATE_X90.val,\
              IMAGE_SEARCH.val,\
              POLYGROUPS.val
            )

    else:  # Normal load
        load_obj(filepath,\
          CLAMP_SIZE.val,\
          CREATE_FGONS.val,\
          CREATE_SMOOTH_GROUPS.val,\
          CREATE_EDGES.val,\
          SPLIT_OBJECTS.val,\
          SPLIT_GROUPS.val,\
          SPLIT_MATERIALS.val,\
          ROTATE_X90.val,\
          IMAGE_SEARCH.val,\
          POLYGROUPS.val
        )

    Window.WaitCursor(0)
Example #24
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()
Example #25
0
def parse_help_info(script):

	global PATHS, SCRIPT_INFO

	if script.userdir:
		path = PATHS['uscripts']
	else:
		path = PATHS['scripts']

	fname = bsys.join(path, script.fname)

	if not bsys.exists(fname):
		Draw.PupMenu('IO Error: couldn\'t find script %s' % fname)
		return None

	f = file(fname, 'r')
	lines = f.readlines()
	f.close()

	# fix line endings:
	if lines[0].find('\r'):
		unixlines = []
		for l in lines:
			unixlines.append(l.replace('\r',''))
		lines = unixlines

	llen = len(lines)
	has_doc = 0

	doc_data = {
		'__author__': '',
		'__version__': '',
		'__url__': '',
		'__email__': '',
		'__bpydoc__': '',
		'__doc__': ''
	}

	i = 0
	while i < llen:
		l = lines[i]
		incr = 1
		for k in doc_data.keys():
			if l.find(k, 0, 20) == 0:
				value, incr = parse_pyobj(k, lines, i)
				exec("doc_data['%s'] = %s" % (k, value))
				has_doc = 1
				break
		i += incr

	# fix these to seqs, simplifies coding elsewhere
	for w in ['__author__', '__url__', '__email__']:
		val = doc_data[w]
		if val and type(val) == str:
			doc_data[w] = [doc_data[w]]

	if not doc_data['__bpydoc__']:
		if doc_data['__doc__']:
			doc_data['__bpydoc__'] = doc_data['__doc__']

	if has_doc: # any data, maybe should confirm at least doc/bpydoc
		info = BPy_Info(script, doc_data)
		SCRIPT_INFO = info
		return True

	else:
		return False
Example #26
0
  Blender's home dir is where entries like:
    folders scripts/, plugins/ and locale/ and
    files .Blanguages and .bfont.ttf
  are located.

  It's also where Blender stores the Bpymenus file
  with information about registered scripts, so it
  only needs to scan scripts dir(s) when they are
  modified.
"""
	output.write(outmsg)

has_uconfdir = False
if has_dir['udatadir']:
	uconfigdir = bsys.join(Blender.Get('udatadir'), 'config')
	output.write("\n\n User defined config data dir:")
	if bsys.exists(uconfigdir):
		has_uconfdir = True
		output.write("  %s" % uconfigdir)
	else:
		notices += 1
		output.write("""
  <NOTICE> -- not found.
  bpydata/config/ should be inside the user defined scripts dir.
  It's used by Blender to store scripts configuration data.
  (Since it is on the user defined dir, a new Blender installation
  won't overwrite the data.)
""")

configdir = bsys.join(Blender.Get('datadir'), 'config')
Example #27
0
def load_obj_ui(filepath, BATCH_LOAD= False):
	if BPyMessages.Error_NoFile(filepath):
		return
	
	global CREATE_SMOOTH_GROUPS, CREATE_FGONS, CREATE_EDGES, SPLIT_OBJECTS, SPLIT_GROUPS, SPLIT_MATERIALS, CLAMP_SIZE, IMAGE_SEARCH, POLYGROUPS, KEEP_VERT_ORDER, ROTATE_X90
	
	CREATE_SMOOTH_GROUPS= Draw.Create(0)
	CREATE_FGONS= Draw.Create(1)
	CREATE_EDGES= Draw.Create(1)
	SPLIT_OBJECTS= Draw.Create(0)
	SPLIT_GROUPS= Draw.Create(0)
	SPLIT_MATERIALS= Draw.Create(0)
	CLAMP_SIZE= Draw.Create(10.0)
	IMAGE_SEARCH= Draw.Create(1)
	POLYGROUPS= Draw.Create(0)
	KEEP_VERT_ORDER= Draw.Create(1)
	ROTATE_X90= Draw.Create(0)
	
	
	# Get USER Options
	# Note, Works but not pretty, instead use a more complicated GUI
	'''
	pup_block= [\
	'Import...',\
	('Smooth Groups', CREATE_SMOOTH_GROUPS, 'Surround smooth groups by sharp edges'),\
	('Create FGons', CREATE_FGONS, 'Import faces with more then 4 verts as fgons.'),\
	('Lines', CREATE_EDGES, 'Import lines and faces with 2 verts as edges'),\
	'Separate objects from obj...',\
	('Object', SPLIT_OBJECTS, 'Import OBJ Objects into Blender Objects'),\
	('Group', SPLIT_GROUPS, 'Import OBJ Groups into Blender Objects'),\
	('Material', SPLIT_MATERIALS, 'Import each material into a seperate mesh (Avoids > 16 per mesh error)'),\
	'Options...',\
	('Keep Vert Order', KEEP_VERT_ORDER, 'Keep vert and face order, disables some other options.'),\
	('Clamp Scale:', CLAMP_SIZE, 0.0, 1000.0, 'Clamp the size to this maximum (Zero to Disable)'),\
	('Image Search', IMAGE_SEARCH, 'Search subdirs for any assosiated images (Warning, may be slow)'),\
	]
	
	if not Draw.PupBlock('Import OBJ...', pup_block):
		return
	
	if KEEP_VERT_ORDER.val:
		SPLIT_OBJECTS.val = False
		SPLIT_GROUPS.val = False
		SPLIT_MATERIALS.val = False
	'''
	
	
	
	# BEGIN ALTERNATIVE UI *******************
	if True: 
		
		EVENT_NONE = 0
		EVENT_EXIT = 1
		EVENT_REDRAW = 2
		EVENT_IMPORT = 3
		
		GLOBALS = {}
		GLOBALS['EVENT'] = EVENT_REDRAW
		#GLOBALS['MOUSE'] = Window.GetMouseCoords()
		GLOBALS['MOUSE'] = [i/2 for i in Window.GetScreenSize()]
		
		def obj_ui_set_event(e,v):
			GLOBALS['EVENT'] = e
		
		def do_split(e,v):
			global SPLIT_OBJECTS, SPLIT_GROUPS, SPLIT_MATERIALS, KEEP_VERT_ORDER, POLYGROUPS
			if SPLIT_OBJECTS.val or SPLIT_GROUPS.val or SPLIT_MATERIALS.val:
				KEEP_VERT_ORDER.val = 0
				POLYGROUPS.val = 0
			else:
				KEEP_VERT_ORDER.val = 1
			
		def do_vertorder(e,v):
			global SPLIT_OBJECTS, SPLIT_GROUPS, SPLIT_MATERIALS, KEEP_VERT_ORDER
			if KEEP_VERT_ORDER.val:
				SPLIT_OBJECTS.val = SPLIT_GROUPS.val = SPLIT_MATERIALS.val = 0
			else:
				if not (SPLIT_OBJECTS.val or SPLIT_GROUPS.val or SPLIT_MATERIALS.val):
					KEEP_VERT_ORDER.val = 1
			
		def do_polygroups(e,v):
			global SPLIT_OBJECTS, SPLIT_GROUPS, SPLIT_MATERIALS, KEEP_VERT_ORDER, POLYGROUPS
			if POLYGROUPS.val:
				SPLIT_OBJECTS.val = SPLIT_GROUPS.val = SPLIT_MATERIALS.val = 0
			
		def do_help(e,v):
			url = __url__[0]
			print 'Trying to open web browser with documentation at this address...'
			print '\t' + url
			
			try:
				import webbrowser
				webbrowser.open(url)
			except:
				print '...could not open a browser window.'
		
		def obj_ui():
			ui_x, ui_y = GLOBALS['MOUSE']
			
			# Center based on overall pup size
			ui_x -= 165
			ui_y -= 90
			
			global CREATE_SMOOTH_GROUPS, CREATE_FGONS, CREATE_EDGES, SPLIT_OBJECTS, SPLIT_GROUPS, SPLIT_MATERIALS, CLAMP_SIZE, IMAGE_SEARCH, POLYGROUPS, KEEP_VERT_ORDER, ROTATE_X90
			
			Draw.Label('Import...', ui_x+9, ui_y+159, 220, 21)
			Draw.BeginAlign()
			CREATE_SMOOTH_GROUPS = Draw.Toggle('Smooth Groups', EVENT_NONE, ui_x+9, ui_y+139, 110, 20, CREATE_SMOOTH_GROUPS.val, 'Surround smooth groups by sharp edges')
			CREATE_FGONS = Draw.Toggle('NGons as FGons', EVENT_NONE, ui_x+119, ui_y+139, 110, 20, CREATE_FGONS.val, 'Import faces with more then 4 verts as fgons')
			CREATE_EDGES = Draw.Toggle('Lines as Edges', EVENT_NONE, ui_x+229, ui_y+139, 110, 20, CREATE_EDGES.val, 'Import lines and faces with 2 verts as edges')
			Draw.EndAlign()
			
			Draw.Label('Separate objects by OBJ...', ui_x+9, ui_y+110, 220, 20)
			Draw.BeginAlign()
			SPLIT_OBJECTS = Draw.Toggle('Object', EVENT_REDRAW, ui_x+9, ui_y+89, 55, 21, SPLIT_OBJECTS.val, 'Import OBJ Objects into Blender Objects', do_split)
			SPLIT_GROUPS = Draw.Toggle('Group', EVENT_REDRAW, ui_x+64, ui_y+89, 55, 21, SPLIT_GROUPS.val, 'Import OBJ Groups into Blender Objects', do_split)
			SPLIT_MATERIALS = Draw.Toggle('Material', EVENT_REDRAW, ui_x+119, ui_y+89, 60, 21, SPLIT_MATERIALS.val, 'Import each material into a seperate mesh (Avoids > 16 per mesh error)', do_split)
			Draw.EndAlign()
			
			# Only used for user feedback
			KEEP_VERT_ORDER = Draw.Toggle('Keep Vert Order', EVENT_REDRAW, ui_x+184, ui_y+89, 113, 21, KEEP_VERT_ORDER.val, 'Keep vert and face order, disables split options, enable for morph targets', do_vertorder)
			
			ROTATE_X90 = Draw.Toggle('-X90', EVENT_REDRAW, ui_x+302, ui_y+89, 38, 21, ROTATE_X90.val, 'Rotate X 90.')
			
			Draw.Label('Options...', ui_x+9, ui_y+60, 211, 20)
			CLAMP_SIZE = Draw.Number('Clamp Scale: ', EVENT_NONE, ui_x+9, ui_y+39, 130, 21, CLAMP_SIZE.val, 0.0, 1000.0, 'Clamp the size to this maximum (Zero to Disable)')
			POLYGROUPS = Draw.Toggle('Poly Groups', EVENT_REDRAW, ui_x+144, ui_y+39, 90, 21, POLYGROUPS.val, 'Import OBJ groups as vertex groups.', do_polygroups)
			IMAGE_SEARCH = Draw.Toggle('Image Search', EVENT_NONE, ui_x+239, ui_y+39, 100, 21, IMAGE_SEARCH.val, 'Search subdirs for any assosiated images (Warning, may be slow)')
			Draw.BeginAlign()
			Draw.PushButton('Online Help', EVENT_REDRAW, ui_x+9, ui_y+9, 110, 21, 'Load the wiki page for this script', do_help)
			Draw.PushButton('Cancel', EVENT_EXIT, ui_x+119, ui_y+9, 110, 21, '', obj_ui_set_event)
			Draw.PushButton('Import', EVENT_IMPORT, ui_x+229, ui_y+9, 110, 21, 'Import with these settings', obj_ui_set_event)
			Draw.EndAlign()
			
		
		# hack so the toggle buttons redraw. this is not nice at all
		while GLOBALS['EVENT'] not in (EVENT_EXIT, EVENT_IMPORT):
			Draw.UIBlock(obj_ui, 0)
		
		if GLOBALS['EVENT'] != EVENT_IMPORT:
			return
		
	# END ALTERNATIVE UI *********************
	
	
	
	
	
	
	
	Window.WaitCursor(1)
	
	if BATCH_LOAD: # load the dir
		try:
			files= [ f for f in os.listdir(filepath) if f.lower().endswith('.obj') ]
		except:
			Window.WaitCursor(0)
			Draw.PupMenu('Error%t|Could not open path ' + filepath)
			return
		
		if not files:
			Window.WaitCursor(0)
			Draw.PupMenu('Error%t|No files at path ' + filepath)
			return
		
		for f in files:
			scn= bpy.data.scenes.new( stripExt(f) )
			scn.makeCurrent()
			
			load_obj(sys.join(filepath, f),\
			  CLAMP_SIZE.val,\
			  CREATE_FGONS.val,\
			  CREATE_SMOOTH_GROUPS.val,\
			  CREATE_EDGES.val,\
			  SPLIT_OBJECTS.val,\
			  SPLIT_GROUPS.val,\
			  SPLIT_MATERIALS.val,\
			  ROTATE_X90.val,\
			  IMAGE_SEARCH.val,\
			  POLYGROUPS.val
			)
	
	else: # Normal load
		load_obj(filepath,\
		  CLAMP_SIZE.val,\
		  CREATE_FGONS.val,\
		  CREATE_SMOOTH_GROUPS.val,\
		  CREATE_EDGES.val,\
		  SPLIT_OBJECTS.val,\
		  SPLIT_GROUPS.val,\
		  SPLIT_MATERIALS.val,\
		  ROTATE_X90.val,\
		  IMAGE_SEARCH.val,\
		  POLYGROUPS.val
		)
	
	Window.WaitCursor(0)
Example #28
0
            if out:
                s += out.replace('\n', '|')
            if err:
                s += err.replace('\n', '|')
            Blender.Draw.PupMenu('glexemel error: see console%t|' + s)
        print out
        print err
        print res
    else:
        write_obj(filename)
        print "glexemel not found"


scriptsdir = Blender.Get('scriptsdir')
files = os.listdir(scriptsdir)
cmd = ''
extension = ".xml"
for fname in files:
    if fname.startswith("xml2g"):
        cmd = bsys.join(scriptsdir, fname)
        extension = ".g3d"
        break

OBJS = Blender.Object.GetSelected()
if not OBJS:
    Blender.Draw.PupMenu('ERROR: no objects selected')
else:
    fname = bsys.makename(ext=extension)
    Blender.Window.FileSelector(fs_callback, "Export XML-G3D", fname)
#Blender.Window.FileSelector(write_obj, "Export")
Example #29
0
def parse_help_info(script):

    global PATHS, SCRIPT_INFO

    if script.userdir:
        path = PATHS['uscripts']
    else:
        path = PATHS['scripts']

    fname = bsys.join(path, script.fname)

    if not bsys.exists(fname):
        Draw.PupMenu('IO Error: couldn\'t find script %s' % fname)
        return None

    f = file(fname, 'r')
    lines = f.readlines()
    f.close()

    # fix line endings:
    if lines[0].find('\r'):
        unixlines = []
        for l in lines:
            unixlines.append(l.replace('\r', ''))
        lines = unixlines

    llen = len(lines)
    has_doc = 0

    doc_data = {
        '__author__': '',
        '__version__': '',
        '__url__': '',
        '__email__': '',
        '__bpydoc__': '',
        '__doc__': ''
    }

    i = 0
    while i < llen:
        l = lines[i]
        incr = 1
        for k in doc_data.keys():
            if l.find(k, 0, 20) == 0:
                value, incr = parse_pyobj(k, lines, i)
                exec("doc_data['%s'] = %s" % (k, value))
                has_doc = 1
                break
        i += incr

    # fix these to seqs, simplifies coding elsewhere
    for w in ['__author__', '__url__', '__email__']:
        val = doc_data[w]
        if val and type(val) == str:
            doc_data[w] = [doc_data[w]]

    if not doc_data['__bpydoc__']:
        if doc_data['__doc__']:
            doc_data['__bpydoc__'] = doc_data['__doc__']

    if has_doc:  # any data, maybe should confirm at least doc/bpydoc
        info = BPy_Info(script, doc_data)
        SCRIPT_INFO = info
        return True

    else:
        return False
Example #30
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()
Example #31
0
	def texture(self, faces,mesh):
		uvlayer0=""
		uvlayer1=""
		uvlayer2=""
		uvlayer3=""

		uvlayers = mesh.getUVLayerNames()
		numlayer = len(uvlayers)
		if numlayer>0:
			uvlayer0 = uvlayers[0]
		if numlayer>1:
			uvlayer1 = uvlayers[1]
		if numlayer>2:
			uvlayer2 = uvlayers[2]
		if numlayer>3:
			uvlayer3 = uvlayers[3]

		mmat = mesh.materials;
		tex = ""
		for f in faces:
			if f.image:
				tex = f.image.name
				break
		if tex:
			image = Image.Get(tex)
			texfname = image.filename
			if SET_TEX_DIR:
				texfname = bsys.basename(texfname)
				if TEX_DIR:
					texfname = bsys.join(TEX_DIR, texfname)
			buf = 'texture "%s" base\n' % texfname
#TODO support multi textures
#lookup second texture value
			fmat = mmat[f.mat]
			tex1 =""
			tex2=""
			mtextures = fmat.getTextures()
			for mtex in mtextures:
				if not ( mtex == None ):
					if mtex.uvlayer==uvlayer1:
						img1 = mtex.tex.getImage()
						tex1=img1.getFilename()
						tex1=bsys.basename(tex1)
					if mtex.uvlayer==uvlayer2:
						img2 = mtex.tex.getImage()
						tex2 = img2.getFilename()
						tex2=bsys.basename(tex2)

			
			if tex1!="":
				buf +='texture "'
				buf +=tex1
				buf+='" tiled\n'
			else:
				buf+='texture empty_texture_no_mapping skids\n'

			if tex2!="":
				buf+='texture "'
				buf+=tex2
				buf+='" tiled\n'
			else:
				buf +='texture empty_texture_no_mapping skids\n'

			buf +='texture empty_texture_no_mapping shad\n'

			xrep = image.xrep
			yrep = image.yrep
#			buf += 'texrep %s %s\n' % (xrep, yrep)
			self.file.write(buf)
Example #32
0
    'home': Blender.Get('homedir'),
    'scripts': Blender.Get('scriptsdir'),
    'uscripts': Blender.Get('uscriptsdir')
}

if not PATHS['home']:
    errmsg = """
Can't find Blender's home dir and so can't find the
Bpymenus file automatically stored inside it, which
is needed by this script.  Please run the
Help -> System -> System Information script to get
information about how to fix this.
"""
    raise SystemError, errmsg

BPYMENUS_FILE = bsys.join(PATHS['home'], 'Bpymenus')

f = file(BPYMENUS_FILE, 'r')
lines = f.readlines()
f.close()

AllGroups = []


class Script:
    def __init__(self, data):
        self.name = data[0]
        self.version = data[1]
        self.fname = data[2]
        self.userdir = data[3]
        self.tip = data[4]
Example #33
0
  Blender's home dir is where entries like:
    folders scripts/, plugins/ and locale/ and
    files .Blanguages and .bfont.ttf
  are located.

  It's also where Blender stores the Bpymenus file
  with information about registered scripts, so it
  only needs to scan scripts dir(s) when they are
  modified.
"""
	output.write(outmsg)

has_uconfdir = False
if has_dir['udatadir']:
	uconfigdir = bsys.join(Blender.Get('udatadir'), 'config')
	output.write("\n\n User defined config data dir:")
	if bsys.exists(uconfigdir):
		has_uconfdir = True
		output.write("  %s" % uconfigdir)
	else:
		notices += 1
		output.write("""
  <NOTICE> -- not found.
  bpydata/config/ should be inside the user defined scripts dir.
  It's used by Blender to store scripts configuration data.
  (Since it is on the user defined dir, a new Blender installation
  won't overwrite the data.)
""")

configdir = bsys.join(Blender.Get('datadir'), 'config')
Example #34
0
	'home': Blender.Get('homedir'),
	'scripts': Blender.Get('scriptsdir'),
	'uscripts': Blender.Get('uscriptsdir')
}

if not PATHS['home']:
	errmsg = """
Can't find Blender's home dir and so can't find the
Bpymenus file automatically stored inside it, which
is needed by this script.  Please run the
Help -> System -> System Information script to get
information about how to fix this.
"""
	raise SystemError, errmsg

BPYMENUS_FILE = bsys.join(PATHS['home'], 'Bpymenus')

f = file(BPYMENUS_FILE, 'r')
lines = f.readlines()
f.close()

AllGroups = []

class Script:

	def __init__(self, data):
		self.name = data[0]
		self.version = data[1]
		self.fname = data[2]
		self.userdir = data[3]
		self.tip = data[4]