Ejemplo n.º 1
0
    def Source(self, value: typing.Optional[sim_info.SimInfo]) -> None:
        if not isinstance(value, sim_info.SimInfo) and value is not None:
            raise Exceptions.IncorrectTypeException(value, "Source",
                                                    (sim_info.SimInfo, None))

        self._source = value
Ejemplo n.º 2
0
	def SpermCount (self, value: int) -> None:
		if not isinstance(value, (int,)):
			raise Exceptions.IncorrectTypeException(value, "SpermCount", (int,))

		self._spermCount = value
Ejemplo n.º 3
0
		def uniqueIdentifierVerifier (value: typing.Optional[uuid.UUID]) -> None:
			if not isinstance(value, uuid.UUID) and value is not None:
				raise Exceptions.IncorrectTypeException(value, self._uniqueIdentifierSavingKey, (uuid.UUID, None))
Ejemplo n.º 4
0
 def verifyY(value: typing.Union[float, int]) -> None:
     if not isinstance(value, (float, int)):
         raise Exceptions.IncorrectTypeException(
             value, "Y", (float, int))
Ejemplo n.º 5
0
	def DecayedCallback (self, value: typing.Optional[typing.Callable]) -> None:
		if not isinstance(value, typing.Callable) and value is not None:
			raise Exceptions.IncorrectTypeException(value, "DecayedCallback", ("Callable", None))

		self._decayedCallback = value
Ejemplo n.º 6
0
	def ShowFertilityNotifications (self, value: bool) -> None:
		if not isinstance(value, bool):
			raise Exceptions.IncorrectTypeException(value, "ShowFertilityNotifications", (bool,))

		self._showFertilityNotifications = value
Ejemplo n.º 7
0
	def LastSimulatedTick (self, value: int) -> None:
		if not isinstance(value, int):
			raise Exceptions.IncorrectTypeException(value, "LastSimulatedTick", (int,))

		self._lastSimulatedTick = value
Ejemplo n.º 8
0
    def _LoadSetValue(self, saveData: dict) -> bool:
        operationInformation = "Save Identifier: %s" % (self.Identifier, )
        operationSuccess = True  # type: bool

        saveSectionsData = saveData.get("Sections")

        if not isinstance(saveSectionsData, dict):
            raise Exceptions.IncorrectTypeException(
                saveSectionsData, "Root[Sections]", (dict, ),
                "The sections value for the save file is not a dictionary.")

        self._saveData = saveData
        self._saveSectionsData = saveSectionsData

        self._loaded = True

        for sectionHandler in self.Sections:  # type: Saving.SectionBase
            try:
                sectionData = self.GetSectionData(
                    sectionHandler.Identifier)  # type: typing.Any

                if sectionData is None:
                    continue

                sectionSuccess = sectionHandler.Load(sectionData)  # type: bool

                if not sectionSuccess:
                    operationSuccess = False
            except Exception:
                Debug.Log(
                    "Failed to load data to a section helper with the identifier '"
                    + sectionHandler.Identifier + "'\n" + operationInformation,
                    self.Host.Namespace,
                    Debug.LogLevels.Warning,
                    group=self.Host.Namespace,
                    owner=__name__)
                operationSuccess = False
                continue

        saveDataGUID = self.DataGUID  # type: typing.Optional[int]
        gameSaveGUID = services.get_persistence_service(
        ).get_save_slot_proto_guid()  # type: int

        if saveDataGUID is None or saveDataGUID != gameSaveGUID:
            Debug.Log("The loaded data's GUID '" + str(saveDataGUID) +
                      "' does not match the game's saved GUID '" +
                      str(gameSaveGUID) + "'\n" + operationInformation,
                      self.Host.Namespace,
                      Debug.LogLevels.Warning,
                      group=self.Host.Namespace,
                      owner=__name__)

        saveDataGameTick = self.DataGameTick  # type: typing.Optional[int]
        gameSaveGameTick = services.get_persistence_service(
        ).get_save_slot_proto_buff().gameplay_data.world_game_time  # type: int

        if saveDataGameTick is None or saveDataGameTick != gameSaveGameTick:
            Debug.Log("The loaded data's game tick '" + str(saveDataGameTick) +
                      "' does not match the game's saved game tick '" +
                      str(gameSaveGameTick) + "'\n" + operationInformation,
                      self.Host.Namespace,
                      Debug.LogLevels.Warning,
                      group=self.Host.Namespace,
                      owner=__name__)

        return operationSuccess
Ejemplo n.º 9
0
def GetGameSaveFilePath(slotID: int) -> str:
    if not isinstance(slotID, int):
        raise Exceptions.IncorrectTypeException(slotID, "slotID", (int, ))

    return os.path.join(Paths.SavesPath,
                        "Slot_" + GetSlotIDString(slotID) + ".save")
Ejemplo n.º 10
0
    def Load(self, saveFilePath: str) -> bool:
        """
		Load a save file. If any data is already loaded it will be unloaded first.

		:param saveFilePath: The path of the save file to be loaded. If this doesn't exist the method 'LoadDefault' will be used instead.
		:type saveFilePath: str
		:return: This method will return False if an error occurred. Otherwise this method will return True if it behaved as expected.
		:rtype: bool
		"""

        if not isinstance(saveFilePath, str):
            raise Exceptions.IncorrectTypeException(saveFilePath,
                                                    "saveFilePath", (str, ))

        operationInformation = "Save Identifier: %s" % (self.Identifier, )
        operationStartTime = time.time()  # type: float

        Debug.Log(
            "Load operation starting in a saving object.\nTarget File: %s\n" %
            Paths.StripUserDataPath(saveFilePath) + operationInformation,
            self.Host.Namespace,
            Debug.LogLevels.Info,
            group=self.Host.Namespace,
            owner=__name__)

        if not self.Enabled:
            Debug.Log(
                "Triggered load operation in a disabled saving object.\n" +
                operationInformation,
                self.Host.Namespace,
                Debug.LogLevels.Warning,
                group=self.Host.Namespace,
                owner=__name__)

        if self.Loaded:
            self.Unload()

        if not os.path.exists(saveFilePath):
            self.LoadDefault()
            loadSuccessful = True

            self._loadedFileExisted = False
            self._currentFilePath = saveFilePath
        else:
            try:
                loadSuccessful = self._LoadInternal(saveFilePath)

                self._loadedFileExisted = True
                self._currentFilePath = saveFilePath
            except Exception:
                operationTime = time.time() - operationStartTime  # type: float
                Debug.Log(
                    "Load operation in a saving object aborted, falling back to the default. (Operation took "
                    + str(operationTime) + " seconds)\n" +
                    operationInformation,
                    self.Host.Namespace,
                    Debug.LogLevels.Warning,
                    group=self.Host.Namespace,
                    owner=__name__)
                self.LoadDefault()

                self._loadedFileExisted = True
                self._currentFilePath = saveFilePath

                return False

        operationTime = time.time() - operationStartTime  # type: float

        if loadSuccessful:
            Debug.Log(
                "Load operation in a saving object finished without issue. (Operation took "
                + str(operationTime) + " seconds)\n" + operationInformation,
                self.Host.Namespace,
                Debug.LogLevels.Info,
                group=self.Host.Namespace,
                owner=__name__)
        else:
            Debug.Log(
                "Load operation in a saving object at least partially failed. (Operation took "
                + str(operationTime) + " seconds)\n" + operationInformation,
                self.Host.Namespace,
                Debug.LogLevels.Warning,
                group=self.Host.Namespace,
                owner=__name__)

        return loadSuccessful
Ejemplo n.º 11
0
    def Save(self, saveFilePath: str) -> bool:
        """
		Write the loaded data to the active save file.

		This saving object must have save data loaded or this method will raise an exception.

		:param saveFilePath: The path to save the data to.
		:type saveFilePath: str
		:return: This method will return False if an error in saving any section occurred. Otherwise this method will return True if it behaved as expected.
		:rtype: bool
		"""

        if not isinstance(saveFilePath, str):
            raise Exceptions.IncorrectTypeException(saveFilePath,
                                                    "saveFilePath", (str, ))

        operationInformation = "Save Identifier: %s" % (self.Identifier, )
        operationStartTime = time.time()  # type: float

        Debug.Log(
            "Save operation starting in a saving object.\nTarget File: %s\n" %
            Paths.StripUserDataPath(saveFilePath) + operationInformation,
            self.Host.Namespace,
            Debug.LogLevels.Info,
            group=self.Host.Namespace,
            owner=__name__)

        if not self.Enabled:
            Debug.Log(
                "Triggered save operation in a disabled saving object.\n" +
                operationInformation,
                self.Host.Namespace,
                Debug.LogLevels.Warning,
                group=self.Host.Namespace,
                owner=__name__)

        try:
            saveSuccessful = self._SaveInternal(saveFilePath)
            self._currentFilePath = saveFilePath
        except:
            self._currentFilePath = saveFilePath
            operationTime = time.time() - operationStartTime  # type: float
            Debug.Log(
                "Save operation in a saving object aborted. (Operation took " +
                str(operationTime) + " seconds)\n" + operationInformation,
                self.Host.Namespace,
                Debug.LogLevels.Warning,
                group=self.Host.Namespace,
                owner=__name__)
            return False

        operationTime = time.time() - operationStartTime  # type: float

        if saveSuccessful:
            Debug.Log(
                "Save operation in a saving object finished without issue. (Operation took "
                + str(operationTime) + " seconds)\n" + operationInformation,
                self.Host.Namespace,
                Debug.LogLevels.Info,
                group=self.Host.Namespace,
                owner=__name__)
        else:
            Debug.Log(
                "Save operation in a saving object at least partially failed. (Operation took "
                + str(operationTime) + " seconds)\n" + operationInformation,
                self.Host.Namespace,
                Debug.LogLevels.Warning,
                group=self.Host.Namespace,
                owner=__name__)

        return saveSuccessful
Ejemplo n.º 12
0
    def Log(self,
            message,
            level: Debug.LogLevels,
            group: str = None,
            owner: str = None,
            logStack: bool = False,
            exception: BaseException = None,
            frame: types.FrameType = None) -> None:

        if not isinstance(level, int):
            raise Exceptions.IncorrectTypeException(level, "level", (int, ))

        if not isinstance(group, str) and group is not None:
            raise Exceptions.IncorrectTypeException(group, "group", (str, ))

        if not isinstance(owner, str) and owner is not None:
            raise Exceptions.IncorrectTypeException(owner, "owner", (str, ))

        if not isinstance(exception, BaseException) and exception is not None:
            raise Exceptions.IncorrectTypeException(exception, "exception",
                                                    (BaseException, ))

        if not isinstance(logStack, bool):
            raise Exceptions.IncorrectTypeException(logStack, "logStack",
                                                    (bool, ))

        if isinstance(frame, singletons.DefaultType):
            frame = None

        if not isinstance(frame, types.FrameType) and frame is not None:
            raise Exceptions.IncorrectTypeException(frame, "frame",
                                                    (types.FrameType, ))

        if self._writeFailureCount >= self._writeFailureLimit:
            return

        if not _loggingEnabled and _loggingEnabled is not None:
            return

        if frame is log.DEFAULT:
            frame = None

        if exception is None:
            exception = sys.exc_info()[1]

        logCount = self.LogCount  # type: int
        self.LogCount += 1

        if _logLevel is not None:
            if level > _logLevel:
                return

        report = DebugShared.Report(
            None,
            logCount + 1,
            datetime.datetime.now().isoformat(),
            str(message),
            level=level,
            group=str(group),
            owner=owner,
            exception=exception,
            logStack=logStack,
            stacktrace=str.join(
                "",
                traceback.format_stack(f=frame)))  # type: DebugShared.Report

        self._reportStorage.append(report)

        if _logInterval == 0:
            self.Flush()
Ejemplo n.º 13
0
    def LowerBound(self, value: typing.Optional[int]) -> None:
        if not isinstance(value, int) and value is not None:
            raise Exceptions.IncorrectTypeException(value, "LowerBound",
                                                    (int, None))

        self._lowerBound = value
Ejemplo n.º 14
0
	def SpermGeneratingEvent (self, value: Events.EventHandler) -> None:
		if not isinstance(value, Events.EventHandler):
			raise Exceptions.IncorrectTypeException(value, "SpermGeneratingEvent", (Events.EventHandler,))

		self._spermGeneratingEvent = value
Ejemplo n.º 15
0
	def Enabled (self, value: bool) -> None:
		if not isinstance(value, bool):
			raise Exceptions.IncorrectTypeException(value, "Enabled", (bool,))

		self._enabled = value
Ejemplo n.º 16
0
	def EffectRemovedEvent (self, value: Events.EventHandler) -> None:
		if not isinstance(value, Events.EventHandler):
			raise Exceptions.IncorrectTypeException(value, "EffectRemovedEvent", (Events.EventHandler,))

		self._effectRemovedEvent = value
Ejemplo n.º 17
0
	def TrackingMode (self, value: TrackingMode) -> None:
		if not isinstance(value, TrackingMode):
			raise Exceptions.IncorrectTypeException(value, "TrackingMode", (TrackingMode,))

		self._trackingMode = value
Ejemplo n.º 18
0
	def WeightOffset (self, value: float) -> None:
		if not isinstance(value, (float, int)):
			raise Exceptions.IncorrectTypeException(value, "WeightOffset", (float, int))

		self._weightOffset = value
Ejemplo n.º 19
0
	def TimeSinceCycleStart (self, value: typing.Optional[float]) -> None:
		if not isinstance(value, (float, int)) and value is not None:
			raise Exceptions.IncorrectTypeException(value, "TimeSinceCycleStart", (float, int, None))

		self._timeSinceCycleStart = value
Ejemplo n.º 20
0
	def Adjustment (self, value: float) -> None:
		if not isinstance(value, (float, int, OptionAdjustmentExpression)):
			raise Exceptions.IncorrectTypeException(value, "Adjustment", (float, int, OptionAdjustmentExpression))

		self._adjustment = value
Ejemplo n.º 21
0
    def RemovePoint(self, point: CurvePoint) -> None:
        if not isinstance(point, CurvePoint):
            raise Exceptions.IncorrectTypeException(point, "point",
                                                    (CurvePoint, ))

        self._points.remove(point)
Ejemplo n.º 22
0
	def OffsetMinimum (self, value: typing.Optional[float]) -> None:
		if not isinstance(value, (float, int)) and value is not None:
			raise Exceptions.IncorrectTypeException(value, "OffsetMinimum", (float, int, None))

		self._offsetMinimum = value
Ejemplo n.º 23
0
	def Guides (self, value: list):
		if not isinstance(value, list):
			raise Exceptions.IncorrectTypeException(value, "value", (list,))

		self._guides = value
Ejemplo n.º 24
0
	def __init__ (self, expression: str):
		if not isinstance(expression, str):
			raise Exceptions.IncorrectTypeException(expression, "expression", (str,))

		self._expression = expression  # type: str
		self._additionalVariables = dict()  # type: typing.Dict[str, float]
Ejemplo n.º 25
0
	def SourcePointer (self, value: SimPointer.SimPointer) -> None:
		if not isinstance(value, SimPointer.SimPointer):
			raise Exceptions.IncorrectTypeException(value, "SourcePointer", (SimPointer.SimPointer,))

		self._sourcePointer = value
Ejemplo n.º 26
0
	def AddVariables (self, **additionalVariables) -> None:
		for variableIdentifier, variable in additionalVariables.items():  # type: str, float
			if not isinstance(variable, (float, int)):
				raise Exceptions.IncorrectTypeException(variable, "additionalVariables[%s]" % variableIdentifier, (float, int))

		self._additionalVariables.update(additionalVariables)
Ejemplo n.º 27
0
	def LifetimeDistribution (self, value: Distribution.NormalDistribution) -> None:
		if not isinstance(value, Distribution.NormalDistribution):
			raise Exceptions.IncorrectTypeException(value, "LifetimeDistribution", (Distribution.NormalDistribution,))

		self._lifetimeDistribution = value
Ejemplo n.º 28
0
    def __contains__(self, item: typing.Callable) -> bool:
        if not callable(item):
            raise Exceptions.IncorrectTypeException(item, "item",
                                                    ("Callable", ))

        return item in self.Callbacks
Ejemplo n.º 29
0
		def uniqueSeedVerifier (value: typing.Optional[int]) -> None:
			if not isinstance(value, int) and value is not None:
				raise Exceptions.IncorrectTypeException(value, self._uniqueSeedSavingKey, (int, None))
Ejemplo n.º 30
0
def Save (saveSlotID: int, commitSave: bool = False) -> None:
	"""
	Save every registered and enabled saving object's data to their active save files.
	:param saveSlotID: The save slot id this is suppose to saved to. This must be greater than or equal to 0.
	:type saveSlotID: int
	:param commitSave: If this function should commit the save file, to actually save the game not just write it to a temporary file. Save file
	commits should typically occur when the game does the same.
	:type commitSave: bool
	"""

	global _activeSlotID

	if saveSlotID is None:
		saveSlotID = services.get_persistence_service().get_save_slot_proto_buff().slot_id  # type: int

	if not isinstance(saveSlotID, int):
		raise Exceptions.IncorrectTypeException(saveSlotID, "saveSlotID", (int,))

	if saveSlotID < 0:
		raise Exception("saveSlotID values must be greater than or equal to 0.")

	if not isinstance(commitSave, bool):
		raise Exceptions.IncorrectTypeException(commitSave, "commitSave", (bool,))

	if commitSave:
		Debug.Log("Saving and committing %s saving object(s) to save slot %s." % (len(_registeredSavingObjects), saveSlotID), This.Mod.Namespace, Debug.LogLevels.Info, group = This.Mod.Namespace, owner = __name__)
	else:
		Debug.Log("Saving %s saving object(s) to save slot %s" % (len(_registeredSavingObjects), saveSlotID), This.Mod.Namespace, Debug.LogLevels.Info, group = This.Mod.Namespace, owner = __name__)

	savingFailure = False  # type: bool
	failedSavingIdentifiers = list()  # type: typing.List[str]

	try:
		if _activeSlotID != saveSlotID:
			DeactivateActiveSlot()
	except:
		Debug.Log("Failed to deactivate the active save directory.", This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__)
		savingFailure = True

	_activeSlotID = saveSlotID

	savingDirectoryPath = GetModSaveActiveDirectoryPath(saveSlotID)  # type: str

	modSaveMetaDataFileName = GetModSaveMetaDataFileName()  # type: str

	for savingObject in _registeredSavingObjects:  # type: Saving.SaveBase
		try:
			if not savingObject.Enabled:
				continue

			if not savingObject.Loaded:
				Debug.Log("Went to save a saving object with the identifier '" + savingObject.Identifier + "' but it wasn't loaded.", This.Mod.Namespace, Debug.LogLevels.Warning, group = This.Mod.Namespace, owner = __name__)
				continue

			savingObjectFileName = savingObject.GetSaveFileName()  # type: str

			if savingObjectFileName == modSaveMetaDataFileName:
				Debug.Log("Had to skip a saving object with the identifier '" + savingObject.Identifier + "' because its file name was '" + modSaveMetaDataFileName + "' which conflicts with an important file.", This.Mod.Namespace, Debug.LogLevels.Error, group = This.Mod.Namespace, owner = __name__)
				continue

			savingFilePath = os.path.abspath(os.path.join(savingDirectoryPath, savingObject.GetSaveFileName()))  # type: str

			modSaveSuccessful = savingObject.Save(savingFilePath)  # type: bool
		except Exception:
			Debug.Log("Encountered an unhandled exception upon saving a saving object with the identifier '" + savingObject.Identifier + "'.", This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__)
			modSaveSuccessful = False  # type: bool

		if not modSaveSuccessful:
			failedSavingIdentifiers.append(savingObject.Identifier)

	try:
		_CreateSaveMetaDataFile(savingDirectoryPath)
	except:
		Debug.Log("Failed to write a save meta file into the slot %s" % saveSlotID, This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__)

	if commitSave:
		Commit(savingDirectoryPath, saveSlotID)

	if savingFailure:
		_ShowSaveFailureDialog()

	if len(failedSavingIdentifiers) != 0:
		_ShowModSaveFailureDialog(failedSavingIdentifiers)

	Debug.Log("Finished saving %s saving object(s) with %s failing." % (len(_registeredSavingObjects), str(len(failedSavingIdentifiers))), This.Mod.Namespace, Debug.LogLevels.Info, group = This.Mod.Namespace, owner = __name__)