def ParsePythonEnum(string: str, enumType: typing.Type[enum_lib.Enum]) -> typing.Any: if not isinstance(string, str): raise Exceptions.IncorrectTypeException(string, "string", (str, )) if not isinstance(enumType, type): raise Exceptions.IncorrectTypeException(enumType, "enumType", (type, )) if not issubclass(enumType, enum_lib.Enum): raise Exceptions.DoesNotInheritException("enumType", (enum_lib.Enum, )) if "." in string: stringSplit = string.split(".") # type: typing.List[str] if len(stringSplit) == 2: if stringSplit[0] == enumType.__name__: string = stringSplit[1] else: raise ValueError("Cannot parse '" + string + "' to '" + Types.GetFullName(enumType) + "'.") else: raise ValueError("Cannot parse '" + string + "' to '" + Types.GetFullName(enumType) + "'.") try: return enumType[string] except KeyError: pass raise ValueError("'" + string + "' is not an attribute of '" + Types.GetFullName(enumType) + "'.")
def ParseS4Enum(string: str, enumType: enum.Metaclass) -> typing.Any: if not isinstance(string, str): raise Exceptions.IncorrectTypeException(string, "string", (str, )) if not isinstance(enumType, enum.Metaclass): raise Exceptions.IncorrectTypeException(enumType, "enumType", (enum.Metaclass, )) if "." in string: stringSplit = string.split(".") # type: typing.List[str] if len(stringSplit) == 2: if stringSplit[0] == enumType.__name__: string = stringSplit[1] else: raise ValueError("Cannot parse '" + string + "' to '" + Types.GetFullName(enumType) + "'.") else: raise ValueError("Cannot parse '" + string + "' to '" + Types.GetFullName(enumType) + "'.") try: return enumType[string] except KeyError: pass raise ValueError("'" + string + "' is not an attribute of '" + Types.GetFullName(enumType) + "'.")
def GenerateCycle (self, cycleTypeIdentifier: str) -> CycleBase.CycleBase: """ Create a cycle object based off and made for this reproductive system. :param cycleTypeIdentifier: The identifier of the type of cycle to be generated, this must be registered in with cycles types module. :type cycleTypeIdentifier: str """ generationSeed = self.TrackingSystem.CurrentSeed # type: int random.seed(self.CycleObjectsGenerated) generationSeed += random.randint(-1000000000, 1000000000) cycleType = CycleTypes.GetCycleType(cycleTypeIdentifier) cycle = cycleType() cycleGuide = cycle.GetCycleGuide(self.TrackingSystem) # type: CycleGuides.CycleGuide eventArgumentsType = cycle.GetGenerationArgumentsType(self.TrackingSystem) # type: typing.Type[CycleEvents.CycleGeneratingArguments] eventArguments = eventArgumentsType(generationSeed, cycle, cycleGuide) for cycleGeneratingCallback in self.CycleGeneratingEvent: try: cycleGeneratingCallback(self, eventArguments) except: Debug.Log("Failed to call cycle generating callback '" + Types.GetFullName(cycleGeneratingCallback) + "'.\n" + self.TrackingSystem.DebugInformation, This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__, lockIdentifier = __name__ + ":" + str(Python.GetLineNumber()), lockReference = cycleGeneratingCallback) cycle.Generate(eventArguments) return cycle
def _AddMissingHandlers(self) -> None: activeTypeIdentifiers = set( handler.TypeIdentifier for handler in self.ActiveHandlers) # type: typing.Set[str] allTypeIdentifiers = HandlersTypes.GetAllHandlerTypeIdentifiers( ) # type: typing.Set[str] for typeIdentifier in allTypeIdentifiers: # type: str if not typeIdentifier in activeTypeIdentifiers: addingHandlerType = HandlersTypes.GetHandlerType( typeIdentifier) try: addingHandler = addingHandlerType( self.TrackingSystem) # type: HandlersBase.HandlerBase except: Debug.Log( "Failed to create instance of the handler type '" + Types.GetFullName(addingHandlerType) + "'.\n" + self.TrackingSystem.DebugInformation, This.Mod.Namespace, Debug.LogLevels.Exception, group=This.Mod.Namespace, owner=__name__, lockIdentifier=__name__ + " | Creating_Handler", lockReference=addingHandlerType) continue self._AddHandler(addingHandler)
def NotifyPregnancyEnded(self) -> None: """ Notify this reproductive system that a pregnancy has ended. If we are not monitoring the pregnancy, or we detect the sim is still pregnant, nothing will happen. """ if self.IsPregnant: return if not self.MonitoringPregnancy: return self.MonitoringPregnancy = False eventArguments = CycleEvents.PregnancyEndedArguments() for pregnancyEndedCallback in self.PregnancyEndedEvent: try: pregnancyEndedCallback(self, eventArguments) except: Debug.Log("Failed to call pregnancy ended callback '" + Types.GetFullName(pregnancyEndedCallback) + "'.\n" + self.TrackingSystem.DebugInformation, This.Mod.Namespace, Debug.LogLevels.Exception, group=This.Mod.Namespace, owner=__name__, lockIdentifier=__name__ + ":" + str(Python.GetLineNumber()), lockReference=pregnancyEndedCallback) self.ResetPregnancyVisualsIfAppropriate()
def CurrentCycle (self, value: typing.Optional[CycleBase.CycleBase]) -> None: if not isinstance(value, CycleBase.CycleBase) and value is not None: raise Exceptions.IncorrectTypeException(value, "CurrentCycle", (CycleBase.CycleBase, None)) if hasattr(self, "_currentCycle"): previousValue = self._currentCycle if previousValue is value: return if previousValue is not None: self._UnsetCycleCallbacks(previousValue) else: previousValue = None # type: typing.Optional[CycleBase.CycleBase] self._currentCycle = value if value is not None: self._SetCycleCallbacks(value) if self.TrackingSystem.Simulating: if value is None and previousValue is None: return self.TrackingSystem.Simulation.NeedToPlan = True cycleChangedEventArguments = CycleEvents.CycleAbortTestingArguments() # type: CycleEvents.CycleAbortTestingArguments for cycleChangedCallback in self.CycleChangedEvent: try: cycleChangedCallback(self, cycleChangedEventArguments) except: Debug.Log("Failed to call cycle changed callback '" + Types.GetFullName(cycleChangedCallback) + "'.\n" + self.TrackingSystem.DebugInformation, This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__, lockIdentifier = __name__ + ":" + str(Python.GetLineNumber()), lockReference = cycleChangedCallback)
def PatchDirectly (originalCallable: typing.Callable, targetFunction: typing.Callable, patchType: PatchTypes = PatchTypes.After, permanent: bool = False) -> typing.Callable: """ Combine a function with another function or method, the patched function will be returned upon completion. :param originalCallable: The original callable object to be patched. :param targetFunction: The function object that will be combined with the original. This can only be a function or a built in function. :type targetFunction: typing.Callable :param patchType: Controls when the original callable is called. A value of PatchTypes.Custom requires that the target function take an extra argument in the first argument position. The extra argument will be a reference to the original callable. :type patchType: PatchTypes :param permanent: Whether or not the patch will be disabled if the module the patching function resides in is unloaded. :type permanent: bool :return: Returns the patched function. :rtype: typing.Callable """ if not isinstance(originalCallable, types.BuiltinFunctionType) and not isinstance(originalCallable, types.FunctionType) and not isinstance(originalCallable, types.MethodType): raise Exception(Types.GetFullName(originalCallable) + " is not a function, built-in function or a method.") if not isinstance(targetFunction, types.FunctionType) and not isinstance(targetFunction, types.BuiltinFunctionType): raise Exceptions.IncorrectTypeException(targetFunction, "targetFunction", (types.FunctionType, types.BuiltinFunctionType)) if not isinstance(patchType, PatchTypes): raise Exceptions.IncorrectTypeException(patchType, "patchType", (PatchTypes,)) if not isinstance(permanent, bool): raise Exceptions.IncorrectTypeException(permanent, "permanent", (bool,)) information = _Information(originalCallable, targetFunction, patchType, permanent) # type: _Information patchedFunction = _Wrapper(information) _storage.append(information) return patchedFunction
def RegisterObject(self, objectType: typing.Type[script_object.ScriptObject], interactionReference: typing.Type) -> bool: """ Add the specified interaction to the specified object. This will return false if the interaction could not be registered and true if it could. """ objectInteractionList = getattr(objectType, self.InteractionListAttribute, None) if isinstance(objectInteractionList, (tuple, list)): objectInteractionList += (interactionReference, ) setattr(objectType, self.InteractionListAttribute, objectInteractionList) return True else: if not self.IgnoreMissingAttribute: Debug.Log( "Failed to find valid interaction list with the attribute name '%s' in an object with a type of '%s'" % (self.InteractionListAttribute, Types.GetFullName(interactionReference)), This.Mod.Namespace, Debug.LogLevels.Error, group=This.Mod.Namespace, owner=__name__, lockIdentifier=__name__ + ":ObjectRegistration", lockReference=interactionReference) return False
def InvokeModUnloadedEvent(mod: Mods.Mod, exiting: bool) -> ModUnloadedEventArguments: """ Invokes the mod unloaded event. Should be triggered every time a mod is unloaded. :param mod: A reference the mod in question. :type mod: Mods.Mod :param exiting: Whether or not the mod is unloading because the application is closing. :type exiting: bool :rtype: None """ eventArguments = ModUnloadedEventArguments( mod, exiting) # type: ModUnloadedEventArguments for modUnloadedCallback in ModUnloadedEvent: try: modUnloadedCallback(sys.modules[__name__], eventArguments) except: Debug.Log("Failed to invoke a mod unloaded callback at '" + Types.GetFullName(modUnloadedCallback) + "'.", This.Mod.Namespace, Debug.LogLevels.Exception, group=This.Mod.Namespace, owner=__name__) return eventArguments
def _EvaluateExpressionNode ( self, expressionNode, binaryOperators: typing.Dict[typing.Any, typing.Callable[[float, float], float]], unaryOperators: typing.Dict[typing.Any, typing.Callable[[float], float]], functions: typing.Dict[typing.Any, typing.Callable], variables: typing.Dict[str, float]) -> float: if isinstance(expressionNode, ast.Num): return expressionNode.n elif isinstance(expressionNode, ast.BinOp): operationCallable = binaryOperators[type(expressionNode.op)] leftSide = self._EvaluateExpressionNode(expressionNode.left, binaryOperators, unaryOperators, functions, variables) rightSide = self._EvaluateExpressionNode(expressionNode.right, binaryOperators, unaryOperators, functions, variables) return operationCallable(leftSide, rightSide) elif isinstance(expressionNode, ast.UnaryOp): operationCallable = unaryOperators[type(expressionNode.op)] operand = self._EvaluateExpressionNode(expressionNode.operand, binaryOperators, unaryOperators, functions, variables) return operationCallable(operand) elif isinstance(expressionNode, ast.Call): if len(expressionNode.keywords) != 0: raise ValueError("Expression functions cannot have keyword arguments.") functionCallable = functions[expressionNode.func.id] functionArguments = (self._EvaluateExpressionNode(argument, binaryOperators, unaryOperators, functions, variables) for argument in expressionNode.args) return functionCallable(*functionArguments) elif isinstance(expressionNode, ast.Name): return variables[expressionNode.id] else: raise ValueError("Invalid node in found in parsed expression.\nNode Type: " + Types.GetFullName(expressionNode))
def GenerateSperm (self) -> Sperm.Sperm: """ Create an sperm object based off and made for this reproductive system. """ generationSeed = self.TrackingSystem.CurrentSeed # type: int random.seed(self.SpermObjectsGenerated) generationSeed += random.randint(-1000000000, 1000000000) sperm = Sperm.Sperm() spermGuide = sperm.GetSpermGuide(self.TrackingSystem) # type: CycleGuides.SpermGuide eventArguments = CycleEvents.SpermGeneratingArguments(generationSeed, sperm, spermGuide) for spermGeneratingCallback in self.SpermGeneratingEvent: try: spermGeneratingCallback(self, eventArguments) except: Debug.Log("Failed to call sperm generating callback '" + Types.GetFullName(spermGeneratingCallback) + "'.\n" + self.TrackingSystem.DebugInformation, This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__, lockIdentifier = __name__ + ":" + str(Python.GetLineNumber()), lockReference = spermGeneratingCallback) sperm.Generate(eventArguments) self._spermObjectsGenerated += 1 return sperm
def GetIncorrectReturnTypeExceptionText (value, callableName: str, correctTypes: typing.Tuple[typing.Union[type, str, None], ...], *additional) -> str: if not isinstance(callableName, str): raise IncorrectTypeException(callableName, "callableName", (str,)) if not isinstance(correctTypes, tuple): raise IncorrectTypeException(correctTypes, "correctTypes", (tuple,)) if len(correctTypes) == 0: raise Exception("This exception must receive at least one correct type") for correctTypeIndex in range(len(correctTypes)): # type: int if isinstance(correctTypes[correctTypeIndex], type): continue if isinstance(correctTypes[correctTypeIndex], str): continue if correctTypes[correctTypeIndex] is None: continue raise IncorrectTypeException(correctTypes[correctTypeIndex], "correctTypes[%d]" % correctTypeIndex, (type, str, None)) valueType = type(value) correctString = "'{}'" + (", '{}'" * (len(correctTypes) - 2) if len(correctTypes) > 2 else "") + (" or '{}'" if len(correctTypes) > 1 else "") formatList = list() formatList.append(callableName) for correctTypeIndex in range(0, len(correctTypes)): if isinstance(correctTypes[correctTypeIndex], type) or correctTypes[correctTypeIndex] is None: formatList.append(Types.GetFullName(correctTypes[correctTypeIndex])) elif isinstance(correctTypes[correctTypeIndex], str): formatList.append(correctTypes[correctTypeIndex]) else: formatList.append("") formatList.append(Types.GetFullName(valueType)) exceptionString = ("Expected '{}' to return a '" + correctString + "' not '{}'.").format(*formatList) for additionalObject in additional: # type: typing.Any exceptionString += "\n" + str(additionalObject) return exceptionString
def _NotifyEffectRemoved (self, removedEffect: EffectsBase.EffectBase) -> None: eventArguments = CycleEvents.EffectRemovedArguments(removedEffect) # type: CycleEvents.EffectRemovedArguments for effectRemovedCallback in self.EffectRemovedEvent: try: effectRemovedCallback(self, eventArguments) except: Debug.Log("Failed to call effect removed callback '" + Types.GetFullName(effectRemovedCallback) + "'.\n" + self.TrackingSystem.DebugInformation, This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__, lockIdentifier = __name__ + ":" + str(Python.GetLineNumber()), lockReference = effectRemovedCallback)
def _InvokeOnLoadWrapperEvent () -> Events.EventArguments: eventArguments = Events.EventArguments() # type: Events.EventArguments for updateCallback in _onUpdateWrapper: # type: typing.Callable[[types.ModuleType, Events.EventArguments], None] try: updateCallback(sys.modules[__name__], eventArguments) except: Debug.Log("Failed to run the 'OnLoadWrapper' callback '" + Types.GetFullName(updateCallback) + "'.", This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__) return eventArguments
def _InvokeOnUpdateWrapperEvent (changedSettings: typing.Set[str]) -> UpdateEventArguments: updateEventArguments = UpdateEventArguments(changedSettings) # type: UpdateEventArguments for updateCallback in _onUpdateWrapper: # type: typing.Callable[[types.ModuleType, Events.EventArguments], None] try: updateCallback(sys.modules[__name__], updateEventArguments) except: Debug.Log("Failed to run the 'OnUpdateWrapper' callback '" + Types.GetFullName(updateCallback) + "'.", This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__) return updateEventArguments
def DoBuffSelectionTesting (self) -> CycleEvents.MenstrualEffectBuffSelectionTestingArguments: eventArguments = CycleEvents.MenstrualEffectBuffSelectionTestingArguments(self.AffectingSystem.CurrentSeed, self.AffectingSystem.SimInfo) # type: CycleEvents.MenstrualEffectBuffSelectionTestingArguments for buffSelectionTestingCallback in self.BuffSelectionTestingEvent: try: buffSelectionTestingCallback(self, eventArguments) except: Debug.Log("Failed to call buff selection testing callback '" + Types.GetFullName(buffSelectionTestingCallback) + "'.\n" + self.AffectingSystem.DebugInformation, This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__, lockIdentifier = __name__ + ":" + str(Python.GetLineNumber()), lockReference = buffSelectionTestingCallback) return eventArguments
def run(self) -> None: while True: if not self.isAlive( ) or self._parentTimer is None or not self._parentTimer.isAlive(): break if self.daemon != self._parentTimer.daemon: self.daemon = self._parentTimer.daemon currentlyQueued = len(self._queuedCallbacks) # type: int if currentlyQueued == 0: time.sleep(0.05) else: callback = self._queuedCallbacks[0][0] # type: typing.Callable callbackArguments = self._queuedCallbacks[0][1] # type: tuple callbackKeywordArguments = self._queuedCallbacks[0][ 2] # type: dict try: callback(*callbackArguments, **callbackKeywordArguments) except Exception: Debug.Log("Failed to call a timer callback. Callback '" + Types.GetFullName(callback) + "'", This.Mod.Namespace, level=Debug.LogLevels.Warning, group=This.Mod.Namespace, owner=__name__) self._queuedCallbacks.pop(0) if currentlyQueued >= 10: if not self._reportedBacklog: Debug.Log( "A timer's callback thread has developed a backlog. This might mean callbacks are being added faster than they can be dealt with. Last Callback: '" + Types.GetFullName(callback) + "'", This.Mod.Namespace, level=Debug.LogLevels.Warning, group=This.Mod.Namespace, owner=__name__) self._reportedBacklog = True
def _ScanForAllSnippets() -> None: if services.snippet_manager is None: raise Exception("Cannot look for snippets, the manager is None.") if len(_scanningSnippets) == 0: return operationStartTime = time.time() # type: float snippetsByType = dict( ) # type: typing.Dict[str, typing.List[snippets.SnippetInstanceMetaclass]] for snippetID, snippet in services.snippet_manager().types.items( ): # type: typing.Any, snippets.SnippetInstanceMetaclass if isinstance(snippet, snippets.SnippetInstanceMetaclass): snippetList = snippetsByType.get( snippet.snippet_type, None) # type: typing.List[snippets.SnippetInstanceMetaclass] if snippetList is None: snippetList = list() snippetsByType[snippet.snippet_type] = snippetList snippetList.append(snippet) for snippetType, snippetCallbacks in _scanningSnippets.items( ): # type: str, typing.List[typing.Callable] snippetList = snippetsByType.get(snippetType, None) if snippetList is None: snippetList = list() for snippetCallback in snippetCallbacks: # type: typing.Callable try: snippetCallback(snippetList) except: Debug.Log("Failed to trigger snippet scan callback at '%s'." % Types.GetFullName(snippetCallback), This.Mod.Namespace, Debug.LogLevels.Exception, group=This.Mod.Namespace, owner=__name__) operationTime = time.time() - operationStartTime Debug.Log( "Finished scanning for %s types of snippet in %s seconds with %s snippets existing." % (len(_scanningSnippets), operationTime, len(services.snippet_manager().types)), This.Mod.Namespace, Debug.LogLevels.Info, group=This.Mod.Namespace, owner=__name__)
def _TriggerAnnouncement (self, announcementMethodName: str, preemptive: bool, *announcementArgs, **announcementKwargs) -> None: for announcer in Director.GetAllAnnouncers(): # type: typing.Type[Director.Announcer] readReportLockIdentifier = None # type: typing.Optional[str] readReportLockReference = None # type: typing.Any if self.LimitErrors: readReportLockIdentifier = __name__ + ":" + str(Python.GetLineNumber()) # type: str readReportLockReference = announcer try: if not announcer.Enabled: continue if not announcer.Host.IsLoaded() and not announcer.Reliable: continue if preemptive != announcer.Preemptive: continue announcementMethod = getattr(announcer, announcementMethodName) # type: typing.Callable except Exception: from NeonOcean.S4.Main import Debug Debug.Log("Failed to read the announcer at '" + Types.GetFullName(announcer) + "' when triggering the announcement '" + announcementMethodName + "'.", announcer.Host.Namespace, Debug.LogLevels.Exception, group = announcer.Host.Namespace, owner = __name__, lockIdentifier = readReportLockIdentifier, lockReference = readReportLockReference) return else: if readReportLockIdentifier is not None: from NeonOcean.S4.Main import Debug Debug.Unlock(readReportLockIdentifier, readReportLockReference) callReportLockIdentifier = None # type: typing.Optional[str] callReportLockReference = None # type: typing.Any if self.LimitErrors: callReportLockIdentifier = __name__ + ":" + str(Python.GetLineNumber()) # type: str callReportLockReference = announcer try: if self.AnnouncementCallWrapper is None: announcementMethod(*announcementArgs, **announcementKwargs) else: self.AnnouncementCallWrapper(announcementMethod, *announcementArgs, **announcementKwargs) except Exception: from NeonOcean.S4.Main import Debug Debug.Log("Failed to trigger the announcement '" + announcementMethodName + "' for '" + Types.GetFullName(announcer) + "'.", announcer.Host.Namespace, Debug.LogLevels.Exception, group = announcer.Host.Namespace, owner = __name__, lockIdentifier = callReportLockIdentifier, lockReference = callReportLockReference) return else: if callReportLockIdentifier is not None: from NeonOcean.S4.Main import Debug Debug.Unlock(callReportLockIdentifier, callReportLockReference)
def run(self) -> None: if self._repeat: lastInterval = self.Interval # type: float sleepStartTime = time.time() # type: float targetTime = sleepStartTime + lastInterval # type: float sleepTime = lastInterval # type: float while self.isAlive(): time.sleep(sleepTime) if self.isAlive(): self._CallCallback() sleepEndTime = time.time() # type: float sleepTimeOversleep = sleepEndTime - targetTime # type: float if self.Interval != lastInterval: sleepTimeOversleep = max( min(sleepTimeOversleep, self.Interval), -self.Interval) sleepTime = self.Interval - sleepTimeOversleep # type: float if sleepTime < 0: if not self._reportedMissedTick: actualSleepTime = sleepEndTime - sleepStartTime # type: float Debug.Log( "A timer slept over an interval. This will be the only warning though there may be more missed ticks. Interval: '" + str(self.Interval) + "' Actual Interval: '" + str(actualSleepTime) + "' Callback: '" + Types.GetFullName(self.Callback) + "'", This.Mod.Namespace, level=Debug.LogLevels.Warning, group=This.Mod.Namespace, owner=__name__) self._reportedMissedTick = True sleepTime = 0 lastInterval = self.Interval sleepStartTime = time.time() # type: float targetTime += lastInterval else: if self.isAlive(): time.sleep(self.Interval) if self.isAlive(): self._CallCallback()
def _InvokeOnLoadEvent(self) -> Events.EventArguments: eventArguments = Events.EventArguments() # type: Events.EventArguments for loadCallback in self.OnLoad: # type: typing.Callable[[PersistentBranched, Events.EventArguments], None] try: loadCallback(self, eventArguments) except: Debug.Log("Failed to run the 'OnLoad' callback '" + Types.GetFullName(loadCallback) + "'.", This.Mod.Namespace, Debug.LogLevels.Exception, group=This.Mod.Namespace, owner=__name__) return eventArguments
def NotifyBuffRemoved (self, removedBuff: BuffsMenstrual.MenstrualBuffBase) -> None: """ Notify the effect that a new buff was just added. """ if not isinstance(removedBuff, BuffsMenstrual.MenstrualBuffBase): raise Exceptions.IncorrectTypeException(removedBuff, "removedBuff", (BuffsMenstrual.MenstrualBuffBase,)) eventArguments = CycleEvents.MenstrualEffectBuffRemovedArguments(removedBuff) # type: CycleEvents.MenstrualEffectBuffRemovedArguments for buffRemovedCallback in self.BuffRemovedEvent: try: buffRemovedCallback(self, eventArguments) except: Debug.Log("Failed to call buff removed callback '" + Types.GetFullName(buffRemovedCallback) + "'.\n" + self.AffectingSystem.DebugInformation, This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__, lockIdentifier = __name__ + ":" + str(Python.GetLineNumber()), lockReference = buffRemovedCallback)
def InvokeUnregisteredReproductiveSystemEvent( reproductiveSystem: ReproductionShared.ReproductiveSystem) -> None: thisModule = sys.modules[__name__] registeredArguments = RegistrationChangedArguments(reproductiveSystem) for unregisteredEventCallback in UnregisteredReproductiveSystemEvent: try: unregisteredEventCallback(thisModule, registeredArguments) except: Debug.Log( "Failed to run unregistered reproductive system event callback " + Types.GetFullName(unregisteredEventCallback), This.Mod.Namespace, Debug.LogLevels.Exception, group=This.Mod.Namespace, owner=__name__)
def _TargetException (exception: BaseException) -> None: originalCallableFullName = Types.GetFullName(information.OriginalCallable) # type: str if originalCallableFullName == Types.GetFullName(log.exception): Debug.Log("Failed to call target function '" + Types.GetFullName(information.TargetFunction) + "'. Original callable: '" + originalCallableFullName + "'.", This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__, exception = exception, logToGame = False) information.OriginalCallable(This.Mod.Namespace, "Failed to call target function '" + Types.GetFullName(information.TargetFunction) + "'. Original callable: '" + originalCallableFullName + "'.", exc = exception) else: if originalCallableFullName == Types.GetFullName(log.Logger.exception): Debug.Log("Failed to call target function '" + Types.GetFullName(information.TargetFunction) + "'. Original callable: '" + originalCallableFullName + "'.", This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__, exception = exception, logToGame = False) information.OriginalCallable(log.Logger(This.Mod.Namespace), "Failed to call target function '" + Types.GetFullName(information.TargetFunction) + "'. Original callable: '" + originalCallableFullName + "'.", exc = exception) else: Debug.Log("Failed to call target function '" + Types.GetFullName(information.TargetFunction) + "'. Original callable: '" + originalCallableFullName + "'.", This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__, exception = exception)
def DoCycleAbortTesting (self) -> CycleEvents.CycleAbortTestingArguments: """ Test if the currently active cycle should abort. :return: Testing event arguments that carry information on whether or not the current cycle should abort. :rtype: EventsCycles.CycleAbortTestingArguments """ eventArguments = CycleEvents.CycleAbortTestingArguments() # type: CycleEvents.CycleAbortTestingArguments for cycleAbortTestingCallback in self.CycleAbortTestingEvent: try: cycleAbortTestingCallback(self, eventArguments) except: Debug.Log("Failed to call cycle abort testing callback '" + Types.GetFullName(cycleAbortTestingCallback) + "'.\n" + self.TrackingSystem.DebugInformation, This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__, lockIdentifier = __name__ + ":" + str(Python.GetLineNumber()), lockReference = cycleAbortTestingCallback) return eventArguments
def _AddMissingEffects (self) -> None: activeTypeIdentifiers = set(effect.TypeIdentifier for effect in self.ActiveEffects) # type: typing.Set[str] allTypeIdentifiers = EffectsTypes.GetAllEffectTypeIdentifiers() # type: typing.Set[str] for typeIdentifier in allTypeIdentifiers: # type: str if not typeIdentifier in activeTypeIdentifiers: addingEffectType = EffectsTypes.GetEffectType(typeIdentifier) try: addingEffect = addingEffectType(self.TrackingSystem) # type: EffectsBase.EffectBase except: Debug.Log("Failed to create instance of the effect type '" + Types.GetFullName(addingEffectType) + "'.\n" + self.TrackingSystem.DebugInformation, This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__, lockIdentifier = __name__ + ":CreatingEffect", lockReference = addingEffectType) continue self._AddEffect(addingEffect)
def DoCycleReleaseOvumTesting (self, ovumRelease: CycleOvumRelease.OvumRelease) -> CycleEvents.CycleReleaseOvumTestingArguments: """ Test if the a cycle should release an ovum. :param ovumRelease: The object that has indicated to the cycle that an ovum should release. :type ovumRelease: CycleOvumRelease.OvumRelease :return: Testing event arguments that carry information on whether or not a cycle should release an ovum. :rtype: EventsCycles.CycleReleaseOvumTestingArguments """ eventArguments = CycleEvents.CycleReleaseOvumTestingArguments(ovumRelease) # type: CycleEvents.CycleReleaseOvumTestingArguments for cycleReleaseOvumTestingCallback in self.CycleReleaseOvumTestingEvent: try: cycleReleaseOvumTestingCallback(self, eventArguments) except: Debug.Log("Failed to call cycle release ovum testing callback '" + Types.GetFullName(cycleReleaseOvumTestingCallback) + "'.\n" + self.TrackingSystem.DebugInformation, This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__, lockIdentifier = __name__ + ":" + str(Python.GetLineNumber()), lockReference = cycleReleaseOvumTestingCallback) return eventArguments
def _NotifyHandlerAdded(self, addedHandler: HandlersBase.HandlerBase) -> None: eventArguments = CycleEvents.HandlerAddedArguments( addedHandler) # type: CycleEvents.HandlerAddedArguments for handlerAddedCallback in self.HandlerAddedEvent: try: handlerAddedCallback(self, eventArguments) except: Debug.Log("Failed to call handler added callback '" + Types.GetFullName(handlerAddedCallback) + "'.\n" + self.TrackingSystem.DebugInformation, This.Mod.Namespace, Debug.LogLevels.Exception, group=This.Mod.Namespace, owner=__name__, lockIdentifier=__name__ + ":" + str(Python.GetLineNumber()), lockReference=handlerAddedCallback)
def _CurrentCycleCompletedCallback (self, completionReason: CycleShared.CompletionReasons) -> None: eventArguments = CycleEvents.CycleCompletedArguments(completionReason) # type: CycleEvents.CycleCompletedArguments for cycleCompletedCallback in self.CycleCompletedEvent: try: cycleCompletedCallback(self, eventArguments) except: Debug.Log("Failed to call cycle completed callback '" + Types.GetFullName(cycleCompletedCallback) + "'.\n" + self.TrackingSystem.DebugInformation, This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__, lockIdentifier = __name__ + ":" + str(Python.GetLineNumber()), lockReference = cycleCompletedCallback) self.CurrentCycle = None self.CompletedInitialCycle = True self.CompletedFirstCycle = True self.TimeSinceLastCycle = None self.LastCycleCompletionReason = completionReason if completionReason == CycleShared.CompletionReasons.Finished: self.TimeSinceLastCycle = 0 # TODO this should be set only if the sim experiences any symptoms instead.
def DoCycleStartTesting (self) -> CycleEvents.CycleStartTestingArguments: """ Test for when the next cycle is to start and of what type it will be. :return: Testing event arguments that carry information on whether or not a cycle should start. :rtype: EventsCycles.CycleStartTestingArguments """ if self.CycleStartTestingSeed is None: self.CycleStartTestingSeed = self.TrackingSystem.CurrentSeed eventArguments = CycleEvents.CycleStartTestingArguments(self.CycleStartTestingSeed, self.TimeSinceLastCycle) # type: CycleEvents.CycleStartTestingArguments self.CycleStartTestingEvent.Invoke(self, eventArguments) for cycleStartTestingCallback in self.CycleStartTestingEvent: try: cycleStartTestingCallback(self, eventArguments) except: Debug.Log("Failed to call cycle start testing callback '" + Types.GetFullName(cycleStartTestingCallback) + "'.\n" + self.TrackingSystem.DebugInformation, This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__, lockIdentifier = __name__ + ":" + str(Python.GetLineNumber()), lockReference = cycleStartTestingCallback) return eventArguments