Ejemplo n.º 1
0
	def addOption(self, option):
		"""Adds an Option to the dictionary if its ID doesn't clash."""
		if option.id in self.options:
			BugUtil.error("BugOptions - duplicate option %s", option.id)
		else:
			self.options[option.id] = option
			BugUtil.debug("BugOptions - added option %s", str(option))
Ejemplo n.º 2
0
	def addFile(self, file):
		"""Adds the given IniFile to the dictionary."""
		if file.id in self.files:
			BugUtil.error("BugOptions - duplicate INI file: %s", file.id)
		else:
			self.files[file.id] = file
			self.createFileGetter(file)
Ejemplo n.º 3
0
def initRootFolder():
    """
    Finds the directory that contains the CivilizationIV.ini file and the user's documents directory.
    """
    global _rootFolderInitDone
    if _rootFolderInitDone:
        return
    BugUtil.debug("BugPath - initializing system folders")
    global _rootDir, _userDir

    # override root dir from CvAltRoot
    try:
        import CvAltRoot
        altRootDir = CvAltRoot.rootDir
        if not setRootDir(altRootDir):
            BugUtil.error(
                "Directory from CvAltRoot.py is not valid or does not contain CivilizationIV.ini"
            )
    except ImportError:
        BugUtil.debug("BugPath - CvAltRoot module not present")
    except AttributeError:
        BugUtil.error("CvAltRoot.py module has no rootDir setting")
    except OSError, (errno, strerror):
        BugUtil.trace("Error accessing directory from CvAltRoot.py: [%d] %s",
                      errno, strerror)
Ejemplo n.º 4
0
def initAfterReload():
	"""
	Initialize BUG and fires PythonReloaded event after reloading Python modules while game is still running.
	
	The first time this module is loaded after the game launches, the global context is not yet ready,
	and thus BUG cannot be initialized. When the Python modules are reloaded after being changed, however,
	this will reinitialize BUG and the main interface.
	"""

	import BugInit
	if BugInit.init():
		try:
			import CvScreensInterface
			CvScreensInterface.reinitMainInterface()
		except:
			import BugUtil
			BugUtil.error("BugInit - failure rebuilding main interface after reloading Python modules")
		getEventManager().fireEvent("PythonReloaded")

	import CvMainInterface #added Sephi		
	mainInterface = CvMainInterface.CvMainInterface()		
	mainInterface.initState()
		
# initialize BUG after Python modules have been reloaded
	initAfterReload()
Ejemplo n.º 5
0
	def addFile(self, file):
		"""Adds the given IniFile to the dictionary."""
		if file.id in self.files:
			BugUtil.error("BugOptions - duplicate INI file: %s", file.id)
		else:
			self.files[file.id] = file
			self.createFileGetter(file)
Ejemplo n.º 6
0
	def addOption(self, option):
		"""Adds an Option to the dictionary if its ID doesn't clash."""
		if option.id in self.options:
			BugUtil.error("BugOptions - duplicate option %s", option.id)
		else:
			self.options[option.id] = option
			BugUtil.debug("BugOptions - added option %s", str(option))
Ejemplo n.º 7
0
 def __call__(self, argsList=None):
     for handler in self.handlers:
         if self.log:
             BugUtil.debug("BugGameUtils - %s - dispatching to %s handler",
                           self.name, handler.__module__)
         result = self.callHandler(handler, argsList)
         if result is not None and result != self.default:
             break
     else:
         if self.default is not None:
             if self.log:
                 BugUtil.debug("BugGameUtils - %s - using default %s",
                               self.name, self.default)
             result = self.default
         else:
             if self.log:
                 BugUtil.debug(
                     "BugGameUtils - %s - dispatching to base handler",
                     self.name)
             result = self.callHandler(self.baseHandler, argsList)
     if result is not None:
         for listener in self.listeners:
             if self.log:
                 BugUtil.debug("BugGameUtils - %s - calling %s listener",
                               self.name, listener.__module__)
             self.callListener(listener, argsList, result)
     else:
         BugUtil.error("BugGameUtils - %s - no handler returned a value",
                       self.name)
     return result
def configure(logging=None, noLogEvents=None):
	"""Sets the global event manager's logging options."""
	if g_eventManager:
		g_eventManager.setLogging(logging)
		g_eventManager.setNoLogEvents(noLogEvents)
	else:
		BugUtil.error("BugEventManager - BugEventManager not setup before configure()")
Ejemplo n.º 9
0
def processSetupFile():
    """
	Reads and processes the GameSetUpCheck.txt file.
	"""
    filename = BugPath.findDataFile("GameSetUpCheck.txt", "GameSetUpCheck")
    if not filename:
        BugUtil.error("Cannot find GameSetUpCheck.txt")
    else:
        try:
            BugUtil.debug("GameSetUpCheck - processing GameSetUpCheck.txt")
            fp = open(filename, 'r')
            for line in fp:
                BugUtil.debug("GameSetUpCheck - %s", line)
                (type, key, value) = line.split(",")
                if (type == 'minHOFOpponents'):
                    minHOFOpponents.append(int(value.strip()))
                elif (type == 'maxHOFOpponents'):
                    maxHOFOpponents.append(int(value.strip()))
                elif (type == 'reqHOFGameOptions'):
                    hofGameOptionRequirements.append(int(value.strip()))
                elif (type == 'hofAllowedMapScripts'):
                    hofAllowedMapScripts[key.strip()] = int(value.strip())
                elif (type == 'hofAllowedCylindrical'):
                    hofAllowedCylindrical[key.strip()] = int(value.strip())
                elif (type == 'hofAllowedToroidal'):
                    hofAllowedToroidal[key.strip()] = int(value.strip())
                elif (type == 'balancedOptionIndex'):
                    balancedOptionIndex[key.strip()] = int(value.strip())
                elif (type == 'worldWrapOptionIndex'):
                    worldWrapOptionIndex[key.strip()] = int(value.strip())
                elif (type == 'allowedWorldWrapValue'):
                    allowedWorldWrapValue[key.strip()] = int(value.strip())
                elif (type == 'modCRC'):
                    global modCRC
                    modCRC = key
                elif (type == 'dllCRC'):
                    global dllCRC
                    dllCRC = key
                elif (type == 'shaderCRC'):
                    global shaderCRC
                    shaderCRC = key
                elif (type == 'pythonCRC'):
                    global pythonCRC
                    pythonCRC = key
                elif (type == 'xmlCRC'):
                    global xmlCRC
                    xmlCRC = key
                else:
                    BugUtil.warn("Unknown type '%s' in GameSetUpCheck.txt",
                                 type)
            fp.close()
            return True
        except:
            BugUtil.trace("Error processing GameSetUpCheck.txt")
            try:
                fp.close()
            except:
                pass
    return False
Ejemplo n.º 10
0
def initDataFolder():
	"""
	Finds the first directory that contains a folder named SETTINGS_FOLDER.
	"""
	global _dataFolderInitDone
	if _dataFolderInitDone:
		return
	BugUtil.debug("BugPath - initializing data folder")

	# K-Mod. If it doesn't already exist, create the folder in the user directory.
	dir = join(getRootDir(), getModName(), SETTINGS_FOLDER)
	if dir != None:
		if not isdir(dir):
			# copy the default settings from the K-Mod folder.
			default_dir = join(getModDir(), SETTINGS_FOLDER)
			if isdir(default_dir):
				try:
					safeInfoPath("BugPath - copying settings to '%s'", dir)
					# copytree is suppose to create the missing parent directores, but apparently it doesn't work. So I need to do this:
					try:
						os.makedirs(join(getRootDir(), getModName()))
					except OSError:
						pass
					# sucks.
					shutil.copytree(default_dir, dir)
				except:
					BugUtil.trace("Failed to copy settings")
		if not isdir(dir):
			# Second attempt: create the directory manually
			try:
				safeInfoPath("BugPath - creating '%s'", dir)
				os.makedirs(dir)
			except OSError:
				BugUtil.trace("Failed to create directory '%s'", dir)
	# K-Mod end
	
	dataDirs = (
		join(getRootDir(), getModName()),	# My Games\BTS\BUG Mod
		join(getUserDir(), getModName()),	# My Games\BUG Mod
		join(getAppDir(), getModName()),	 # Civ4\BTS\BUG Mod
		join(getModDir(), DATA_FOLDER),	  # Civ4\BTS\Mods\BUG Mod 3.6\Data
		join(getModDir()),				   # Civ4\BTS\Mods\BUG Mod 3.6
	)
	for dir in dataDirs:
		if setDataDir(dir):
			break
	else:
		BugUtil.error("No valid data directory containing %s found", SETTINGS_FOLDER)
	_dataFolderInitDone = True
	# <advc.009> setDataDir tries to locate INFO_FOLDER in the same place
	# as SETTINGS_FOLDER, but settings need to be in \My Games\, whereas
	# info is in the program folder. I don't see how this can work in standalone
	# BUG (same code there) either - perhaps it doesn't; haven't tried it.
	global _infoDir
	for dir in dataDirs:
		_infoDir = join(dir, INFO_FOLDER)
		if isdir(_infoDir): # Show the troublesome path in the System tab too
			BugConfigTracker.add("Info_Directory", _infoDir)
			break
Ejemplo n.º 11
0
Archivo: BugCore.py Proyecto: AP-ML/DTM
	def _getMod(self, id):
		if id in self._mods:
			return self._mods[id]
		elif not self._inited:
			BugUtil.info("BugCore - creating uninitialized mod %s", id)
			return self._newMod(id)
		else:
			BugUtil.error("BugCore - invalid mod %s", id)
Ejemplo n.º 12
0
 def _getMod(self, id):
     if id in self._mods:
         return self._mods[id]
     elif not self._inited:
         BugUtil.info("BugCore - creating uninitialized mod %s", id)
         return self._newMod(id)
     else:
         BugUtil.error("BugCore - invalid mod %s", id)
Ejemplo n.º 13
0
def configure(logging=None, noLogEvents=None):
    """Sets the global event manager's logging options."""
    if g_eventManager:
        g_eventManager.setLogging(logging)
        g_eventManager.setNoLogEvents(noLogEvents)
    else:
        BugUtil.error(
            "BugEventManager - BugEventManager not setup before configure()")
def processSetupFile():
	"""
	Reads and processes the GameSetUpCheck.txt file.
	"""
	filename = BugPath.findDataFile("GameSetUpCheck.txt", "GameSetUpCheck")
	if not filename:
		BugUtil.error("Cannot find GameSetUpCheck.txt")
	else:
		try:
			BugUtil.debug("GameSetUpCheck - processing GameSetUpCheck.txt")
			fp = open(filename, 'r')
			for line in fp:
				BugUtil.debug("GameSetUpCheck - %s", line)
				(type, key, value) = line.split(",")
				if (type == 'minHOFOpponents'):
					minHOFOpponents.append(int(value.strip()))
				elif (type == 'maxHOFOpponents'):
					maxHOFOpponents.append(int(value.strip()))
				elif (type == 'reqHOFGameOptions'):
					hofGameOptionRequirements.append(int(value.strip()))
				elif (type == 'hofAllowedMapScripts'):
					hofAllowedMapScripts[key.strip()] = int(value.strip())
				elif (type == 'hofAllowedCylindrical'):
					hofAllowedCylindrical[key.strip()] = int(value.strip())
				elif (type == 'hofAllowedToroidal'):
					hofAllowedToroidal[key.strip()] = int(value.strip())
				elif (type == 'balancedOptionIndex'):
					balancedOptionIndex[key.strip()] = int(value.strip())
				elif (type == 'worldWrapOptionIndex'):
					worldWrapOptionIndex[key.strip()] = int(value.strip())
				elif (type == 'allowedWorldWrapValue'):
					allowedWorldWrapValue[key.strip()] = int(value.strip())
				elif (type == 'modCRC'):
					global modCRC
					modCRC = key
				elif (type == 'dllCRC'):
					global dllCRC
					dllCRC = key
				elif (type == 'shaderCRC'):
					global shaderCRC
					shaderCRC = key
				elif (type == 'pythonCRC'):
					global pythonCRC
					pythonCRC = key
				elif (type == 'xmlCRC'):
					global xmlCRC
					xmlCRC = key
				else:
					BugUtil.warn("Unknown type '%s' in GameSetUpCheck.txt", type)
			fp.close()
			return True
		except:
			BugUtil.trace("Error processing GameSetUpCheck.txt")
			try:
				fp.close()
			except:
				pass
	return False
Ejemplo n.º 15
0
def getViewAndType(iView):
	"""Returns the view boolean and YieldTypes enum given the give number 0-3."""
	if iView == 0:
		return (False, YieldTypes.YIELD_FOOD)
	elif iView in (1, 2, 3):
		return (True, YIELDS[iView - 1])
	else:
		BugUtil.error("RawYields - invalid view number %d", iView)
		return (False, YieldTypes.YIELD_FOOD)
Ejemplo n.º 16
0
def getBuildingType(index):
    """
	Returns the <index>th BuildingType.
	"""
    try:
        return BUILDINGS[index]
    except IndexError:
        BugUtil.error("ReligionUtil - invalid building type %i", index)
        return None
Ejemplo n.º 17
0
def getUnitType(index):
    """
	Returns the <index>th UnitType.
	"""
    try:
        return UNITS[index]
    except IndexError:
        BugUtil.error("ReligionUtil - invalid unit type %i", index)
        return None
Ejemplo n.º 18
0
def getBuildings(iReligion):
	"""
	Returns the list of building info types for <iReligion>.
	"""
	try:
		return BUILDINGS_BY_RELIGION[iReligion]
	except IndexError:
		BugUtil.error("ReligionUtil - invalid religion %i", iReligion)
		return [-1] * NUM_BUILDING_TYPES
Ejemplo n.º 19
0
def getUnits(iReligion):
    """
	Returns the list of unit info types for <iReligion>.
	"""
    try:
        return UNITS_BY_RELIGION[iReligion]
    except IndexError:
        BugUtil.error("ReligionUtil - invalid religion %i", iReligion)
        return [-1] * NUM_UNIT_TYPES
Ejemplo n.º 20
0
def getBuildingType(index):
	"""
	Returns the <index>th BuildingType.
	"""
	try:
		return BUILDINGS[index]
	except IndexError:
		BugUtil.error("ReligionUtil - invalid building type %i", index)
		return None
Ejemplo n.º 21
0
def getUnitType(index):
	"""
	Returns the <index>th UnitType.
	"""
	try:
		return UNITS[index]
	except IndexError:
		BugUtil.error("ReligionUtil - invalid unit type %i", index)
		return None
Ejemplo n.º 22
0
def getBuilding(iReligion, index):
	"""
	Returns the single <index>th building info type for <iReligion>.
	"""
	try:
		return BUILDINGS_BY_RELIGION[iReligion][index]
	except IndexError:
		BugUtil.error("ReligionUtil - invalid religion %i or building type %i", iReligion, index)
		return -1
Ejemplo n.º 23
0
def getUnits(iReligion):
	"""
	Returns the list of unit info types for <iReligion>.
	"""
	try:
		return UNITS_BY_RELIGION[iReligion]
	except IndexError:
		BugUtil.error("ReligionUtil - invalid religion %i", iReligion)
		return [-1] * NUM_UNIT_TYPES
Ejemplo n.º 24
0
def getUnit(iReligion, index):
	"""
	Returns the single <index>th unit info type for <iReligion>.
	"""
	try:
		return UNITS_BY_RELIGION[iReligion][index]
	except IndexError:
		BugUtil.error("ReligionUtil - invalid religion %i or unit type %i", iReligion, index)
		return -1
Ejemplo n.º 25
0
def getViewAndType(iView):
	"""Returns the view boolean and YieldTypes enum given the give number 0-3."""
	if iView == 0:
		return (False, YieldTypes.YIELD_FOOD)
	elif iView in (1, 2, 3):
		return (True, YIELDS[iView - 1])
	else:
		BugUtil.error("RawYields - invalid view number %d", iView)
		return (False, YieldTypes.YIELD_FOOD)
Ejemplo n.º 26
0
def getBuildings(iReligion):
    """
	Returns the list of building info types for <iReligion>.
	"""
    try:
        return BUILDINGS_BY_RELIGION[iReligion]
    except IndexError:
        BugUtil.error("ReligionUtil - invalid religion %i", iReligion)
        return [-1] * NUM_BUILDING_TYPES
Ejemplo n.º 27
0
def getBuilding(iReligion, index):
    """
	Returns the single <index>th building info type for <iReligion>.
	"""
    try:
        return BUILDINGS_BY_RELIGION[iReligion][index]
    except IndexError:
        BugUtil.error("ReligionUtil - invalid religion %i or building type %i",
                      iReligion, index)
        return -1
Ejemplo n.º 28
0
def getUnit(iReligion, index):
    """
	Returns the single <index>th unit info type for <iReligion>.
	"""
    try:
        return UNITS_BY_RELIGION[iReligion][index]
    except IndexError:
        BugUtil.error("ReligionUtil - invalid religion %i or unit type %i",
                      iReligion, index)
        return -1
Ejemplo n.º 29
0
	def handle(self, element, id, to, getter, setter):
		mod = element.getState("mod")
		id = qualify(mod._id, id)
		to = qualify(mod._id, to)
		option = g_options.getOption(to)
		if option is not None:
			link = option.createLinkedOption(mod, id)
			self.addOption(mod, link, getter, setter)
		else:
			BugUtil.error("Option ID %s in element <%s> %s not found", to, element.tag, id)
Ejemplo n.º 30
0
	def handle(self, element, id, to, getter, setter):
		mod = element.getState("mod")
		id = qualify(mod._id, id)
		to = qualify(mod._id, to)
		option = g_options.getOption(to)
		if option is not None:
			link = option.createLinkedOption(mod, id)
			self.addOption(mod, link, getter, setter)
		else:
			BugUtil.error("Option ID %s in element <%s> %s not found", to, element.tag, id)
Ejemplo n.º 31
0
 def __eventReminderStoreApply(self, playerID, userData, popupReturn):
     if (popupReturn.getButtonClicked() != 1):
         turns = popupReturn.getSpinnerWidgetValue(0)
         if turns < 0:
             BugUtil.error("Invalid number of turns (%d) for reminder",
                           turns)
         else:
             reminderTurn = turns + gc.getGame().getGameTurn()
             reminderText = popupReturn.getEditBoxString(1)
             self.addReminder(playerID, Reminder(reminderTurn,
                                                 reminderText))
	def __eventReminderStoreApply(self, playerID, userData, popupReturn):
		if (popupReturn.getButtonClicked() != 1):
			turns = popupReturn.getSpinnerWidgetValue(0)
			if turns < 0:
				BugUtil.error("Invalid number of turns (%d) for reminder", turns)
			else:
				reminderTurn = turns + gc.getGame().getGameTurn()
				reminderText = popupReturn.getEditBoxString(1)
				self.addReminder(playerID, Reminder(reminderTurn, reminderText))
				if (g_autolog.isLogging() and ReminderOpt.isAutolog()):
					g_autolog.writeLog("Reminder: On Turn %d, %s" % (reminderTurn, reminderText))
Ejemplo n.º 33
0
	def createLinkedOption(self, id, linkId, getter=None, setter=None, attrs=None):
		id = makeOptionId(self.mod._id, id)
		linkId = makeOptionId(self.mod._id, linkId)
		option = self.options.getOption(linkId)
		if option is not None:
			link = option.createLinkedOption(self.mod, id)
			self.addOption(link, getter, setter, attrs)
			return link
		else:
			BugUtil.error("BugConfig - link option %s not found", linkId)
			return None
	def __initRWCoordinatesList(self):
		iNumPlayers = game.countCivPlayersEverAlive()
		for iPlayer in range(iNumPlayers):
			pPlayer = gc.getPlayer(iPlayer)
			eCivilization = pPlayer.getCivilizationType()
			if eCivilization in CoordinatesDictionary:
				pCoordinate = CoordinatesDictionary[eCivilization]
			else:
				BugUtil.error(" Culturally Linked Starts ERROR: civilization %s (%d) not defined:", gc.getCivilizationInfo(eCivilization).getDescription(), eCivilization)
				pCoordinate = CoordinatesDictionary[eCivilization]
			CultureLink.pRWCoordinatesList.append(pCoordinate)
Ejemplo n.º 35
0
	def read(self):
		try:
			self.path = BugPath.findIniFile(self.name)
			if not self.path:
				self.create()
			else:
				self.config = ConfigObj(self.path, encoding='utf_8')
#			BugConfigTracker.add("BUG_Mod_Config", self.path)
		except IOError:
			self.path = None
			self.config = None
			BugUtil.error("BugOptions - error reading file '%s'", name)
Ejemplo n.º 36
0
Archivo: BugCore.py Proyecto: AP-ML/DTM
	def _addMod(self, mod):
		id = mod._getID()
		if self._inited:
			BugUtil.warn("BugCore - cannot add mod %s post-init", id)
		elif id in self._emptyMods:
			if not mod._inited:
				BugUtil.error("BugCore - mod %s not initialized", id)
			del self._emptyMods[id]
		elif id in self._mods:
			BugUtil.error("BugCore - mod %s already exists", id)
		else:
			self._mods[id] = mod
Ejemplo n.º 37
0
 def _addMod(self, mod):
     id = mod._getID()
     if self._inited:
         BugUtil.warn("BugCore - cannot add mod %s post-init", id)
     elif id in self._emptyMods:
         if not mod._inited:
             BugUtil.error("BugCore - mod %s not initialized", id)
         del self._emptyMods[id]
     elif id in self._mods:
         BugUtil.error("BugCore - mod %s already exists", id)
     else:
         self._mods[id] = mod
Ejemplo n.º 38
0
def loadMod(name):
	"""Load the given mod from its XML file using a custom parser."""
	path = BugPath.findAssetFile(name + ".xml", "Config")
	if path:
		BugUtil.debug("BugInit - loading mod %s...", name)
		parser = BugConfig.XmlParser()
		timer = BugUtil.Timer("load mod")
		try:
			parser.parse(path)
		finally:
			timer.log(name)
	else:
		BugUtil.error("BugInit - cannot find XML file for mod %s", name)
Ejemplo n.º 39
0
def loadMod(name):
    """Load the given mod from its XML file using a custom parser."""
    path = BugPath.findAssetFile(name + ".xml", "Config")
    if path:
        BugUtil.debug("BugInit - loading mod %s...", name)
        parser = BugConfig.ConfigParser()
        timer = BugUtil.Timer("load mod")
        try:
            parser.parse(path)
        finally:
            timer.log(name)
    else:
        BugUtil.error("BugInit - cannot find XML file for mod %s", name)
Ejemplo n.º 40
0
def initDataFolder():
    """
	Finds the first directory that contains a folder named SETTINGS_FOLDER.
	"""
    global _dataFolderInitDone
    if _dataFolderInitDone:
        return
    BugUtil.debug("BugPath - initializing data folder")

    # K-Mod. If it doesn't already exist, create the folder in the user directory.
    dir = join(getRootDir(), getModName(), SETTINGS_FOLDER)
    if dir != None:
        if not isdir(dir):
            # copy the default settings from the K-Mod folder.
            default_dir = join(getModDir(), SETTINGS_FOLDER)
            if isdir(default_dir):
                try:
                    safeInfoPath("BugPath - copying settings to '%s'", dir)
                    # copytree is suppose to create the missing parent directores, but apparently it doesn't work. So I need to do this:
                    try:
                        os.makedirs(join(getRootDir(), getModName()))
                    except OSError:
                        pass
                    # sucks.
                    shutil.copytree(default_dir, dir)
                except:
                    BugUtil.trace("Failed to copy settings")
        if not isdir(dir):
            # Second attempt: create the directory manually
            try:
                safeInfoPath("BugPath - creating '%s'", dir)
                os.makedirs(dir)
            except OSError:
                BugUtil.trace("Failed to create directory '%s'", dir)
    # K-Mod end

    dataDirs = (
        join(getRootDir(), getModName()),  # My Games\BTS\BUG Mod
        join(getUserDir(), getModName()),  # My Games\BUG Mod
        join(getAppDir(), getModName()),  # Civ4\BTS\BUG Mod
        join(getModDir(), DATA_FOLDER),  # Civ4\BTS\Mods\BUG Mod 3.6\Data
        join(getModDir()),  # Civ4\BTS\Mods\BUG Mod 3.6
    )
    for dir in dataDirs:
        if setDataDir(dir):
            break
    else:
        BugUtil.error("No valid data directory containing %s found",
                      SETTINGS_FOLDER)
    _dataFolderInitDone = True
Ejemplo n.º 41
0
def initDataFolder():
	"""
	Finds the first directory that contains a folder named SETTINGS_FOLDER.
	"""
	global _dataFolderInitDone
	if _dataFolderInitDone:
		return
	BugUtil.debug("BugPath - initializing data folder")

	# K-Mod. If it doesn't already exist, create the folder in the user directory.
	dir = join(getRootDir(), getModName(), SETTINGS_FOLDER)
	if dir != None:
		if not isdir(dir):
			# copy the default settings from the K-Mod folder.
			default_dir = join(getModDir(), SETTINGS_FOLDER)
			if isdir(default_dir):
				try:
					safeInfoPath("BugPath - copying settings to '%s'", dir)
					# copytree is suppose to create the missing parent directores, but apparently it doesn't work. So I need to do this:
					try:
						os.makedirs(join(getRootDir(), getModName()))
					except OSError:
						pass
					# sucks.
					shutil.copytree(default_dir, dir)
				except:
					BugUtil.trace("Failed to copy settings")
		if not isdir(dir):
			# Second attempt: create the directory manually
			try:
				safeInfoPath("BugPath - creating '%s'", dir)
				os.makedirs(dir)
			except OSError:
				BugUtil.trace("Failed to create directory '%s'", dir)
	# K-Mod end
	
	dataDirs = (
		join(getRootDir(), getModName()),	# My Games\BTS\BUG Mod
		join(getUserDir(), getModName()),	# My Games\BUG Mod
		join(getAppDir(), getModName()),	 # Civ4\BTS\BUG Mod
		join(getModDir(), DATA_FOLDER),	  # Civ4\BTS\Mods\BUG Mod 3.6\Data
		join(getModDir()),				   # Civ4\BTS\Mods\BUG Mod 3.6
	)
	for dir in dataDirs:
		if setDataDir(dir):
			break
	else:
		BugUtil.error("No valid data directory containing %s found", SETTINGS_FOLDER)
	_dataFolderInitDone = True
Ejemplo n.º 42
0
def loadMod(name):
    """Load the given mod from its XML file using a custom parser."""
    path = BugPath.findAssetFile(name + ".xml", "Config")
    if path:
        BugUtil.debug("BugInit - loading module %s...", name)
        parser = BugConfig.ConfigParser()
        timer = BugUtil.Timer("load mod")
        try:
            parser.parse(path)
        # <advc.009b> Say which module failed
        except Exception, e:
            BugUtil.error("BugInit - failed to parse module %s", name)
            timer.log(name)
            raise e  # </advc.009b>
        timer.log(name)
Ejemplo n.º 43
0
def initModName():
	"""
	Pulls the modName attribute from the CvModName module.
	"""
	global _modNameInitDone
	if _modNameInitDone:
		return
	global _modName
	try:
		import CvModName
		_modName = CvModName.modName
		safeInfoPath("BugPath - mod name is '%s'", _modName)
	except ImportError:
		BugUtil.error("CvModName.py module not present")
	except AttributeError:
		BugUtil.error("CvModName.py module has no modName setting")
	_modNameInitDone = True
Ejemplo n.º 44
0
def initModName():
    """
	Pulls the modName attribute from the CvModName module.
	"""
    global _modNameInitDone
    if _modNameInitDone:
        return
    global _modName
    try:
        import CvModName
        _modName = CvModName.modName
        safeInfoPath("BugPath - mod name is '%s'", _modName)
    except ImportError:
        BugUtil.error("CvModName.py module not present")
    except AttributeError:
        BugUtil.error("CvModName.py module has no modName setting")
    _modNameInitDone = True
Ejemplo n.º 45
0
def saveGameStart():
    """
	Saves the single-player game when the map is generated as long as MapFinder isn't active.
	
	Checks the CRCs and map settings if BUFFY is active.
	
	NOTE: The save is created and deleted in some cases because it is needed to check the CRCs.
	      Do not try to optimize this unless you are sure you know what's up!
	"""
    if not CyGame().isGameMultiPlayer() and not MapFinder.isActive():
        fileName = AutoSave.saveGame()
        if isNeedToCheckCRCs():
            checkCRCs(fileName)
            if not settingsOK():
                BugUtil.error(getWarningMessage())
        if not AutoSaveOpt.isCreateStartSave():
            os.remove(fileName)
Ejemplo n.º 46
0
	def addShortcutHandler(self, keys, handler):
		"""Adds the given handler to be called when any of the keyboard shortcut(s) is hit.

		The keys argument may be a single Keystroke, a collection of one or more Keystrokes, or
		a string which will be converted to such.
		If any keystrokes have existing handlers, new ones are ignored and a warning is displayed.
		"""
		if isinstance(keys, InputUtil.Keystroke):
			keys = (keys,)
		elif isinstance(keys, basestring):
			keys = InputUtil.stringToKeystrokes(keys)
		for key in keys:
			if key in self.shortcuts:
				BugUtil.error("shortcut %s already assigned", key)
			else:
				BugUtil.debug("BugEventManager - setting shortcut handler for %s", key)
				self.shortcuts[key] = handler
def saveGameStart():
	"""
	Saves the single-player game when the map is generated as long as MapFinder isn't active.
	
	Checks the CRCs and map settings if BUFFY is active.
	
	NOTE: The save is created and deleted in some cases because it is needed to check the CRCs.
	      Do not try to optimize this unless you are sure you know what's up!
	"""
	if not CyGame().isGameMultiPlayer() and not MapFinder.isActive():
		fileName = AutoSave.saveGame()
		if isNeedToCheckCRCs():
			checkCRCs(fileName)
			if not settingsOK():
				BugUtil.error(getWarningMessage())
		if not AutoSaveOpt.isCreateStartSave():
			os.remove(fileName)
	def addShortcutHandler(self, keys, handler):
		"""Adds the given handler to be called when any of the keyboard shortcut(s) is hit.
		
		The keys argument may be a single Keystroke, a collection of one or more Keystrokes, or
		a string which will be converted to such.
		If any keystrokes have existing handlers, new ones are ignored and a warning is displayed.
		
		"""
		if isinstance(keys, InputUtil.Keystroke):
			keys = (keys,)
		elif isinstance(keys, types.StringTypes):
			keys = InputUtil.stringToKeystrokes(keys)
		for key in keys:
			if key in self.shortcuts:
				BugUtil.error("shortcut %s already assigned", key)
			else:
				BugUtil.debug("BugEventManager - setting shortcut handler for %s", key)
				self.shortcuts[key] = handler
Ejemplo n.º 49
0
def initAfterReload():
	"""
	Initialize BUG and fires PythonReloaded event after reloading Python modules while game is still running.
	
	The first time this module is loaded after the game launches, the global context is not yet ready,
	and thus BUG cannot be initialized. When the Python modules are reloaded after being changed, however,
	this will reinitialize BUG and the main interface.
	"""
	import BugInit
	import BugPath
	if not BugPath.isMac() and BugInit.init():
		try:
			import CvScreensInterface
			CvScreensInterface.reinitMainInterface()
		except:
			import BugUtil
			BugUtil.error("BugInit - failure rebuilding main interface after reloading Python modules")
		getEventManager().fireEvent("PythonReloaded")
Ejemplo n.º 50
0
    def _getMod(self, mod_id):
        'get mod by id'
        if mod_id in self._mods:
            return self._mods[mod_id]
        if not self._inited:
            BugUtil.info("BugCore - creating uninitialized mod %s", mod_id)
            return self._newMod(mod_id)

        raise BugUtil.error("BugCore - invalid mod %s", mod_id)
Ejemplo n.º 51
0
def configure(logging=None, noLogEvents=None):
    # """Sets the global event manager's logging options."""
    # if g_eventManager:
    # g_eventManager.setLogging(logging)
    # g_eventManager.setNoLogEvents(noLogEvents)
    # else:
    # BugUtil.error("BugEventManager - BugEventManager not setup before configure()")
    # K-Mod. I've expanded the purpose of this function.
    """Sets the global event manager's logging options. And registers some BUG events handlers."""

    if not g_eventManager:
        BugUtil.error(
            "BugEventManager - BugEventManager not setup before configure()")
        return

    g_eventManager.setLogging(logging)
    g_eventManager.setNoLogEvents(noLogEvents)

    # K-Mod. Don't use register BUG events for PitBoss host.
    # (Note: actually, if this is a PitBoss host, this function won't even be called
    #  because the BUG core will not initialize any mod components in PitBoss mode.)
    if CyGame().isPitbossHost():
        BugUtil.debug(
            "BugEventManager - skipping event registration for PitBoss host")
        return
    # K-Mod end

    # --------- Better BTS AI (2/2) (moved by K-Mod) -------------
    # K-Mod, only enable these features if the cheat mode is enabled.
    #if getChtLvl():
    # advc.127: Replacing the above. ChtLvl is always 0 in multiplayer.
    if getChtLvl() or (CyGame().isGameMultiPlayer()
                       and gc.getDefineINT("ENABLE_AUTOPLAY_MULTIPLAYER") > 0):
        AIAutoPlay.AIAutoPlay(g_eventManager)
        ChangePlayer.ChangePlayer(g_eventManager)
        Tester.Tester(g_eventManager)

    # advc.106c: Changed OnLoad handler
    g_eventManager.addEventHandler("kbdEvent", g_eventManager.onKbdEvent)
    g_eventManager.addEventHandler("OnLoad",
                                   g_eventManager.resetActiveTurnAfterLoad)
    g_eventManager.addEventHandler("GameStart", g_eventManager.resetActiveTurn)
    g_eventManager.addEventHandler("gameUpdate", g_eventManager.onGameUpdate)
Ejemplo n.º 52
0
def saveGame(type=SINGLE, variant=None):
    """
	Saves the current game to the folder designated by the type and optional variant
	and returns the full path to it.
	
	All in the types except WORLDBUILDER allow the AUTO variant while only SINGLE allows QUICK.
	"""
    if _saveDir:
        if variant:
            BugUtil.debug("AutoSave - saving %s %s game", type, variant)
        else:
            BugUtil.debug("AutoSave - saving %s game", type)
        (fileName, _) = getSaveFileName(getSaveDir(type, variant))
        if fileName:
            fileName += ".CivBeyondSwordSave"
            gc.getGame().saveGame(fileName)
            return fileName
        else:
            BugUtil.error("Could not build saved game file name")
    return None
Ejemplo n.º 53
0
def saveGame(type=SINGLE, variant=None):
	"""
	Saves the current game to the folder designated by the type and optional variant
	and returns the full path to it.
	
	All in the types except WORLDBUILDER allow the AUTO variant while only SINGLE allows QUICK.
	"""
	if _saveDir:
		if variant:
			BugUtil.debug("AutoSave - saving %s %s game", type, variant)
		else:
			BugUtil.debug("AutoSave - saving %s game", type)
		(fileName, _) = getSaveFileName(getSaveDir(type, variant))
		if fileName:
			fileName += ".CivBeyondSwordSave"
			gc.getGame().saveGame(fileName)
			return fileName
		else:
			BugUtil.error("Could not build saved game file name")
	return None
Ejemplo n.º 54
0
	def __call__(self, argsList=None):
		for handler in self.handlers:
			if self.log: BugUtil.debug("BugGameUtils - %s - dispatching to %s handler", self.name, handler.__module__)
			result = self.callHandler(handler, argsList)
			if result is not None and result != self.default:
				break
		else:
			if self.default is not None:
				if self.log: BugUtil.debug("BugGameUtils - %s - using default %s", self.name, self.default)
				result = self.default
			else:
				if self.log: BugUtil.debug("BugGameUtils - %s - dispatching to base handler", self.name)
				result = self.callHandler(self.baseHandler, argsList)
		if result is not None:
			for listener in self.listeners:
				if self.log: BugUtil.debug("BugGameUtils - %s - calling %s listener", self.name, listener.__module__)
				self.callListener(listener, argsList, result)
		else:
			BugUtil.error("BugGameUtils - %s - no handler returned a value", self.name)
		return result
Ejemplo n.º 55
0
def initSearchPaths():
    """
	Adds the CustomAssets, mod Assets and BTS Assets directories to a list of search paths.
	"""
    global _searchPathsInitDone
    if _searchPathsInitDone:
        return
    BugUtil.debug("BugPath - initializing asset search paths")

    assetDirs = [join(getModDir(), ASSETS_FOLDER), join(getAppDir(), ASSETS_FOLDER)]
    # EF: Mod's no longer access CustomAssets folder; too many issues
    if not isNoCustomAssets() and not isMod():
        assetDirs.insert(0, join(getRootDir(), CUSTOM_ASSETS_FOLDER))
    for dir in assetDirs:
        addAssetFileSearchPath(dir)

    if _assetFileSearchPaths:
        BugConfigTracker.add("Asset_Search_Paths", _assetFileSearchPaths)
    else:
        BugUtil.error("No asset directories found")
    _searchPathsInitDone = True
Ejemplo n.º 56
0
	def write(self):
		if self.fileExists():
			if self.isDirty():
				BugUtil.debug("BugOptions - writing INI file '%s'", self.name)
				try:
					self.config.write()
					self.dirty = False
				except IOError:
					BugUtil.error("BugOptions - failed writing INI file '%s'", self.path)
		elif self.isLoaded():
			self.path = BugPath.createIniFile(self.name)
			BugUtil.debug("BugOptions - writing new INI file '%s'", self.name)
			try:
				file = open(self.path, "w")
				self.config.write(file)
				file.close()
				self.dirty = False
			except IOError:
				BugUtil.error("BugOptions - failed creating INI file '%s'", self.path)
		else:
			BugUtil.warn("BugOptions - INI file '%s' was never read", self.name)
Ejemplo n.º 57
0
def initRootFolder():
	"""
	Finds the directory that contains the CivilizationIV.ini file and the user's documents directory.
	"""
	global _rootFolderInitDone
	if _rootFolderInitDone:
		return
	BugUtil.debug("BugPath - initializing system folders")
	global _rootDir, _userDir
	
	# override root dir from CvAltRoot
	try:
		import CvAltRoot
		altRootDir = CvAltRoot.rootDir
		if not setRootDir(altRootDir):
			BugUtil.error("Directory from CvAltRoot.py is not valid or does not contain CivilizationIV.ini")
	except ImportError:
		BugUtil.debug("BugPath - CvAltRoot module not present")
	except AttributeError:
		BugUtil.error("CvAltRoot.py module has no rootDir setting")
	except IOError, (errno, strerror):
		BugUtil.trace("Error accessing directory from CvAltRoot.py: [%d] %s", errno, strerror)
def initDataFolder():
	"""
	Finds the first directory that contains a folder named SETTINGS_FOLDER.
	"""
	global _dataFolderInitDone
	if _dataFolderInitDone:
		return
	BugUtil.debug("BugPath - initializing data folder")
	
	dataDirs = (
		join(getUserDir(), getModName()),	# My Games\BUG Mod
		join(getRootDir(), getModName()),	# My Games\BTS\BUG Mod
		join(getAppDir(), getModName()),	 # Civ4\BTS\BUG Mod
		join(getModDir(), DATA_FOLDER),	  # Civ4\BTS\Mods\BUG Mod 3.6\Data
		join(getModDir()),				   # Civ4\BTS\Mods\BUG Mod 3.6
	)
	for dir in dataDirs:
		if setDataDir(dir):
			break
	else:
		BugUtil.error("No valid data directory containing %s found", SETTINGS_FOLDER)
	_dataFolderInitDone = True
Ejemplo n.º 59
0
def initDataFolder():
    """
	Finds the first directory that contains a folder named SETTINGS_FOLDER.
	"""
    global _dataFolderInitDone
    if _dataFolderInitDone:
        return
    BugUtil.debug("BugPath - initializing data folder")

    dataDirs = (
        join(getUserDir(), getModName()),  # My Games\BUG Mod
        join(getRootDir(), getModName()),  # My Games\BTS\BUG Mod
        join(getAppDir(), getModName()),  # Civ4\BTS\BUG Mod
        join(getModDir(), DATA_FOLDER),  # Civ4\BTS\Mods\BUG Mod 3.6\Data
        join(getModDir()),  # Civ4\BTS\Mods\BUG Mod 3.6
    )
    for dir in dataDirs:
        if setDataDir(dir):
            break
    else:
        BugUtil.error("No valid data directory containing %s found", SETTINGS_FOLDER)
    _dataFolderInitDone = True
Ejemplo n.º 60
0
def configure(logging=None, noLogEvents=None):
	# """Sets the global event manager's logging options."""
	# if g_eventManager:
		# g_eventManager.setLogging(logging)
		# g_eventManager.setNoLogEvents(noLogEvents)
	# else:
		# BugUtil.error("BugEventManager - BugEventManager not setup before configure()")
	# K-Mod. I've expanded the purpose of this function.
	"""Sets the global event manager's logging options. And registers some BUG events handlers."""

	if not g_eventManager:
		BugUtil.error("BugEventManager - BugEventManager not setup before configure()")
		return

	g_eventManager.setLogging(logging)
	g_eventManager.setNoLogEvents(noLogEvents)

	# K-Mod. Don't use register BUG events for PitBoss host.
	# (Note: actually, if this is a PitBoss host, this function won't even be called
	#  because the BUG core will not initialize any mod components in PitBoss mode.)
	if CyGame().isPitbossHost():
		BugUtil.debug("BugEventManager - skipping event registration for PitBoss host")
		return
	# K-Mod end

	# --------- Better BTS AI (2/2) (moved by K-Mod) -------------
	# K-Mod, only enable these feature if the cheat mode is enabled.
	if getChtLvl():
		AIAutoPlay.AIAutoPlay(g_eventManager)
		ChangePlayer.ChangePlayer(g_eventManager)
		Tester.Tester(g_eventManager)

	g_eventManager.addEventHandler("kbdEvent", g_eventManager.onKbdEvent)
	g_eventManager.addEventHandler("OnLoad", g_eventManager.resetActiveTurn)
	g_eventManager.addEventHandler("GameStart", g_eventManager.resetActiveTurn)
	g_eventManager.addEventHandler("gameUpdate", g_eventManager.onGameUpdate)