/// <summary> /// Create a XmlElement that contains all data required to save in file /// </summary> /// <returns></returns> public XmlElement ToXmlElement() { XmlElement behavior = new XmlElement("Behavior"); behavior.SetAttributeValue("BehaviorType", BehaviorType.ToString()); behavior.SetAttributeValue("Name", Name); behavior.SetAttributeValue("Id", Id); behavior.SetAttributeValue("Weight", Weight); behavior.SetAttributeValue("Concurrency", Concurrency.ToString()); //if (_Parameters != null && _Parameters.Count > 0) //{ // XmlElement childParameters = new XmlElement("ChildParameters"); // foreach (var p in _Parameters) // childParameters.AppendChild(p.ToXmlElement()); // behavior.AppendChild(childParameters); //} if (!string.IsNullOrEmpty(Comment)) { XmlElement comment = new XmlElement("Comment"); comment.Value = Comment; behavior.AppendChild(comment); } WriteAttributes(behavior); // allow subclass to add additional data return(behavior); }
internal static IBehaviorHandler CreateBehaviorHandler(BehaviorType behaviorType, IActor actor, WeakReference <MixedRealityExtensionApp> appRef) { if (s_behaviorHandlerTypeLookup.ContainsKey(behaviorType)) { var methodInfo = s_behaviorHandlerTypeLookup[behaviorType].GetMethod("Create", BindingFlags.Static | BindingFlags.NonPublic); if (methodInfo != null) { try { return((IBehaviorHandler)methodInfo.Invoke(null, new object[] { actor, appRef })); } catch (Exception e) { Debug.LogException(e); return(null); } } else { throw new NotImplementedException($"A handler for the behavior type {behaviorType.ToString()} exists but does not have a static create method implemented on it."); } } MixedRealityExtensionApp app; if (appRef.TryGetTarget(out app)) { app.Logger.LogError($"Trying to create a behavior of type {behaviorType.ToString()}, but no handler is registered for the given type."); } return(null); }
public void WorldUpdating() { #region Visuals _core.Transform = this.PhysicsBody.Transform; #endregion #region Behavior switch (_behavior) { case BehaviorType.StraightToTarget: Brain_StraightToTarget(); break; case BehaviorType.StraightToTarget_VelocityAware1: Brain_StraightToTarget_VelocityAware1(); break; //case BehaviorType.StraightToTarget_VelocityAware2: //Brain_StraightToTarget_VelocityAware2(); // currently there is no difference //break; case BehaviorType.TowardCenterOfFlock: Brain_TowardCenterOfFlock(); break; case BehaviorType.CenterFlock_AvoidNeighbors: Brain_CenterFlock_AvoidNeighbors(); break; case BehaviorType.CenterFlock_AvoidNeighbors_FlockVelocity: Brain_CenterFlock_AvoidNeighbors_FlockVelocity(); break; case BehaviorType.Flocking_ChasePoint: Brain_Flocking_ChasePoint(); break; default: throw new ApplicationException("Unknown BehaviorType: " + _behavior.ToString()); } #endregion #region Thrust Line if (_shouldDrawThrustLine) { _thruster.DrawVisual(_thrustPercent, this.PhysicsBody.Transform, _thrustTransform); } #endregion }
internal static BehaviorContextBase CreateContext(BehaviorType behaviorType, IActor actor, WeakReference <MixedRealityExtensionApp> appRef) { if (s_factoryMethods.TryGetValue(behaviorType, out FactoryFunc factoryMethod)) { return(factoryMethod.Invoke(actor, appRef)); } if (appRef.TryGetTarget(out MixedRealityExtensionApp app)) { app.Logger.LogError($"Trying to create a behavior of type {behaviorType.ToString()}, but no handler is registered for the given type."); } return(null); }
private static string GetBehaviorsResult(SortedList CustomBehaviorsList) { StringBuilder resultsSB = new StringBuilder(""); for (int i = 0; i < CustomBehaviorsList.Count; i++) { BehaviorType key = (BehaviorType)CustomBehaviorsList.GetKey(i); Collection <CustomBehaviorAttribute> CustomBehaviorsColln = CustomBehaviorsList.GetByIndex(i) as Collection <CustomBehaviorAttribute>; foreach (CustomBehaviorAttribute cba in CustomBehaviorsColln) { bool behaviorInvoked = false; switch (key) { case BehaviorType.IServiceBehavior: behaviorInvoked = cba.IsServiceBehaviorOnlyInvoked(); break; case BehaviorType.IEndpointBehavior: behaviorInvoked = cba.IsServiceEndpointBehaviorOnlyInvoked(); break; case BehaviorType.IContractBehavior: behaviorInvoked = cba.IsDispatcherContractBehaviorOnlyInvoked(); break; case BehaviorType.IOperationBehavior: behaviorInvoked = cba.IsDispatcherOperationBehaviorOnlyInvoked(); break; default: break; } resultsSB.Append(key.ToString() + ":"); resultsSB.Append(cba.ToString()); if (!behaviorInvoked) { resultsSB.Append("[NotInvoked]"); } resultsSB.Append(";"); } } return(resultsSB.ToString()); }
public override void WorldUpdating() { // Figure out which behavior to use //NOTE: These set this.ThrustTransform and this.ThrustPercent switch (_behavior) { case BehaviorType.StraightToTarget: Brain_StraightToTarget(); break; case BehaviorType.StraightToTarget_VelocityAware1: Brain_StraightToTarget_VelocityAware1(); break; case BehaviorType.StraightToTarget_VelocityAware2: Brain_StraightToTarget_VelocityAware2(); break; case BehaviorType.TowardCenterOfFlock: Brain_TowardCenterOfFlock(); break; case BehaviorType.CenterFlock_AvoidNeighbors: Brain_CenterFlock_AvoidNeighbors(); break; case BehaviorType.CenterFlock_AvoidNeighbors_FlockVelocity: Brain_CenterFlock_AvoidNeighbors_FlockVelocity(); break; case BehaviorType.Flocking_ChasePoint: Brain_Flocking_ChasePoint(); break; case BehaviorType.Flocking_ChasePoint_AvoidKnownObstacles: Brain_Flocking_ChasePoint_AvoidKnownObstacles(); break; default: throw new ApplicationException("Unknown BehaviorType: " + _behavior.ToString()); } // Call the base class base.WorldUpdating(); }
public string GetShortName(AIModel model, BehaviorType type, int index) { string shortName = ""; if (name != null) { shortName = name; //string comportNamePattern = @"^(?<family>[^\\]+?)\\(?<model>[^\\]+?)\\(?<model2>[^\\]+?)\.(?<type>...?)\^CreateIntelligence\^CreateComport:(?<name>.*?)$"; if (shortName.Contains("^CreateComport:")) { shortName = shortName.Substring(shortName.LastIndexOf("^CreateComport:") + 15); } shortName = "[\"" + shortName + "\"]"; } shortName = model.name + "." + type.ToString() + "[" + index + "]" + shortName; return(shortName); }
/// <summary> /// Returns the ToString representation to be used for the Fish asset /// </summary> /// <returns /> public override string ToString() { if (Id == -4) { return(""); } string timeString = ""; if (ExcludedTimes.MinValue < 600 || ExcludedTimes.MaxValue < 600) { timeString = $"{Times.MinValue} {Times.MaxValue}"; } else { timeString = $"{Times.MinValue} {ExcludedTimes.MinValue} {ExcludedTimes.MaxValue} {Times.MaxValue}"; } string seasonsString = ""; foreach (Seasons season in AvailableSeasons) { seasonsString += $"{season.ToString().ToLower()} "; } seasonsString = seasonsString.Trim(); string weatherString = ""; if (Weathers.Count >= 2) { weatherString = "both"; } else { weatherString = Weathers[0].ToString().ToLower(); } string spawnMultiplierString = (SpawnMultiplier == 0) ? "0" : SpawnMultiplier.ToString().TrimStart(new char[] { '0' }); string depthMultiplierString = (DepthMultiplier == 0) ? "0" : DepthMultiplier.ToString().TrimStart(new char[] { '0' }); return($"{Name}/{DartChance}/{BehaviorType.ToString().ToLower()}/{MinSize}/{MaxSize}/{timeString}/{seasonsString}/{weatherString}/{UnusedData}/{MinWaterDepth}/{spawnMultiplierString}/{depthMultiplierString}/{MinFishingLevel}"); }
internal static BehaviorContextBase CreateContext(BehaviorType behaviorType, IActor actor, WeakReference <MixedRealityExtensionApp> appRef) { MixedRealityExtensionApp app; appRef.TryGetTarget(out app); if (MREAPI.AppsAPI.BehaviorFactory == null) { app?.Logger.LogWarning("Host app does not provide a behavior factory. Behavior system not available"); return(null); } if (s_factoryMethods.TryGetValue(behaviorType, out FactoryFunc factoryMethod)) { return(factoryMethod.Invoke(actor, appRef)); } app?.Logger.LogError($"Trying to create a behavior of type {behaviorType.ToString()}, but no handler is registered for the given type."); return(null); }
internal static string HookName(BehaviorType typ) { return "Singular." + typ.ToString(); }
internal static string HookName(BehaviorType typ) { return("Sadistic." + typ.ToString()); }
public static void InvokeInitializers(WoWClass wowClass, WoWSpec spec, WoWContext context, bool silent = false) { BehaviorType behavior = BehaviorType.Initialize; if (context == WoWContext.None) { return; } SilentBehaviorCreation = silent; // only load methods once if (_methods.Count <= 0) { // Logger.WriteDebug("Singular Behaviors: building method list"); foreach (var type in Assembly.GetExecutingAssembly().GetTypes()) { // All behavior methods should not be generic, and should have zero parameters, with their return types being of type Composite. _methods.AddRange( type.GetMethods(BindingFlags.Static | BindingFlags.Public).Where( mi => !mi.IsGenericMethod && mi.GetCustomAttributes(typeof(BehaviorAttribute)).Any()).Where( mi => typeof(Composite).IsAssignableFrom(mi.ReturnType) || mi.ReturnType == typeof(Task <bool>))); } Logger.WriteFile("Singular Behaviors: Added " + _methods.Count + " behaviors"); } // find all initialization methods for this class/spec/context var matchedMethods = new Dictionary <BehaviorAttribute, MethodInfo>(); foreach (MethodInfo mi in _methods) { // If the behavior is set as ignore. Don't use it? Duh? if (mi.GetCustomAttributes(typeof(IgnoreBehaviorCountAttribute), false).Any()) { continue; } // If there's no behavior attrib, then move along. foreach (var a in mi.GetCustomAttributes(typeof(BehaviorAttribute), false)) { var attribute = a as BehaviorAttribute; if (attribute == null) { continue; } // Check if our Initialization behavior matches. If not, don't add it! if (IsMatchingMethod(attribute, wowClass, spec, behavior, context)) { if (matchedMethods.ContainsKey(attribute)) { Logger.Write(LogColor.Hilite, "PROGRAM ERROR: duplicate behaviors. Notify Singular Devs!!!"); Logger.WriteDiagnostic("PROGRAM ERROR: duplicate behaviors. Notify Singular Devs!!!"); Logger.WriteDiagnostic("Error for Attribute: class={0} spec={1} type={2} context={3} priority={4} ", attribute.SpecificClass, attribute.SpecificSpec, attribute.Type, attribute.SpecificContext, attribute.PriorityLevel ); Logger.WriteDiagnostic(" exists {0}:{1}", matchedMethods[attribute].DeclaringType, matchedMethods[attribute].Name ); Logger.WriteDiagnostic(" adding {0}:{1}", mi.DeclaringType, mi.Name ); } matchedMethods.Add(attribute, mi); } } } // invoke each initialization behavior in priority order foreach (var kvp in matchedMethods.OrderByDescending(mm => mm.Key.PriorityLevel)) { CurrentBehaviorType = behavior; CurrentBehaviorPriority = kvp.Key.PriorityLevel; CurrentBehaviorName = kvp.Value.Name; string invokeInfo = string.Format("{0} {1} {2}", kvp.Key.PriorityLevel.ToString().AlignRight(5), behavior.ToString().AlignLeft(15), kvp.Value.Name); if (!silent) { Logger.WriteFile(invokeInfo); } kvp.Value.Invoke(null, null); CurrentBehaviorType = 0; CurrentBehaviorPriority = 0; CurrentBehaviorName = string.Empty; } return; }
public static Composite GetComposite(WoWClass wowClass, WoWSpec spec, BehaviorType behavior, WoWContext context, out int behaviourCount, bool silent = false) { if (context == WoWContext.None) { // None is an invalid context, but rather than stopping bot wait it out with donothing logic Logger.Write(LogColor.Hilite, "No Active Context -{0}{1} for{2} set to DoNothingBehavior temporarily", wowClass.ToString().CamelToSpaced(), behavior.ToString().CamelToSpaced(), spec.ToString().CamelToSpaced()); behaviourCount = 1; return(NoContextAvailable.CreateDoNothingBehavior()); } SilentBehaviorCreation = silent; behaviourCount = 0; var matchedMethods = new Dictionary <BehaviorAttribute, Composite>(); foreach (MethodInfo mi in _methods) { // If the behavior is set as ignore. Don't use it? Duh? if (mi.GetCustomAttributes(typeof(IgnoreBehaviorCountAttribute), false).Any()) { continue; } // If there's no behavior attrib, then move along. foreach (var a in mi.GetCustomAttributes(typeof(BehaviorAttribute), false)) { var attribute = a as BehaviorAttribute; if (attribute == null) { continue; } // Check if our behavior matches with what we want. If not, don't add it! if (IsMatchingMethod(attribute, wowClass, spec, behavior, context)) { if (!silent) { Logger.WriteFile("{0} {1} {2}", attribute.PriorityLevel.ToString().AlignRight(4), behavior.ToString().AlignLeft(15), mi.Name); } CurrentBehaviorType = behavior; CurrentBehaviorPriority = attribute.PriorityLevel; CurrentBehaviorName = mi.Name; // if it blows up here, you defined a method with the exact same attribute and priority as one already found Composite comp; if (typeof(Composite).IsAssignableFrom(mi.ReturnType)) { comp = mi.Invoke(null, null) as Composite; } else { Beta.Assert(mi.ReturnType == typeof(Task <bool>)); comp = new ActionRunCoroutine(o => mi.Invoke(null, null) as Task <bool>); } string name = behavior + "." + mi.Name + "." + attribute.PriorityLevel; if (SingularSettings.Trace) { comp = new CallTrace(name, comp); } if (matchedMethods.ContainsKey(attribute)) { Logger.Write(LogColor.Hilite, "Internal Error: method '{0}' has attribute that already exists", name); Logger.WriteDiagnostic(" "); Logger.WriteDiagnostic("Dump Methods"); Logger.WriteDiagnostic("==========================="); foreach (var v in matchedMethods) { Logger.WriteDiagnostic("{0} {1} {2} {3}", v.Key.SpecificClass, v.Key.SpecificSpec, v.Key.SpecificContext, v.Key.PriorityLevel); } Logger.WriteDiagnostic("==========================="); Logger.WriteDiagnostic("{0} {1} {2} {3} == add attempt for {4}", attribute.SpecificClass, attribute.SpecificSpec, attribute.SpecificContext, attribute.PriorityLevel, name); Logger.WriteDiagnostic(" "); } matchedMethods.Add(attribute, comp); CurrentBehaviorType = 0; CurrentBehaviorPriority = 0; CurrentBehaviorName = string.Empty; } } } // If we found no methods, rofls! if (matchedMethods.Count <= 0) { return(null); } var result = new PrioritySelector(); foreach (var kvp in matchedMethods.OrderByDescending(mm => mm.Key.PriorityLevel)) { result.AddChild(kvp.Value); behaviourCount++; } return(result); }
public static Composite GetComposite(WoWClass wowClass, WoWSpec spec, BehaviorType behavior, WoWContext context, out int behaviourCount, bool silent = false) { if (context == WoWContext.None) { // None is an invalid context, but rather than stopping bot wait it out with donothing logic Logger.Write( LogColor.Hilite, "No Active Context -{0}{1} for{2} set to DoNothingBehavior temporarily", wowClass.ToString().CamelToSpaced(), behavior.ToString().CamelToSpaced(), spec.ToString().CamelToSpaced()); behaviourCount = 1; return NoContextAvailable.CreateDoNothingBehavior(); } SilentBehaviorCreation = silent; behaviourCount = 0; var matchedMethods = new Dictionary<BehaviorAttribute, Composite>(); foreach (MethodInfo mi in _methods) { // If the behavior is set as ignore. Don't use it? Duh? if (mi.GetCustomAttributes(typeof(IgnoreBehaviorCountAttribute), false).Any()) continue; // If there's no behavior attrib, then move along. foreach (var a in mi.GetCustomAttributes(typeof(BehaviorAttribute), false)) { var attribute = a as BehaviorAttribute; if (attribute == null) continue; // Check if our behavior matches with what we want. If not, don't add it! if (IsMatchingMethod(attribute, wowClass, spec, behavior, context)) { if (!silent) Logger.WriteFile("{0} {1} {2}", attribute.PriorityLevel.ToString().AlignRight(4), behavior.ToString().AlignLeft(15), mi.Name); CurrentBehaviorType = behavior; CurrentBehaviorPriority = attribute.PriorityLevel; CurrentBehaviorName = mi.Name; // if it blows up here, you defined a method with the exact same attribute and priority as one already found // wrap in trace class Composite comp = mi.Invoke(null, null) as Composite; string name = behavior.ToString() + "." + mi.Name + "." + attribute.PriorityLevel.ToString(); if (SingularSettings.Trace) comp = new CallTrace( name, comp); if (matchedMethods.ContainsKey(attribute)) { Logger.Write(LogColor.Hilite, "Internal Error: method '{0}' has attribute that already exists", name); Logger.WriteDiagnostic(" "); Logger.WriteDiagnostic("Dump Methods"); Logger.WriteDiagnostic("==========================="); foreach (var v in matchedMethods) { Logger.WriteDiagnostic("{0} {1} {2} {3}", v.Key.SpecificClass, v.Key.SpecificSpec, v.Key.SpecificContext, v.Key.PriorityLevel); } Logger.WriteDiagnostic("==========================="); Logger.WriteDiagnostic("{0} {1} {2} {3} == add attempt for {4}", attribute.SpecificClass, attribute.SpecificSpec, attribute.SpecificContext, attribute.PriorityLevel, name); Logger.WriteDiagnostic(" "); } matchedMethods.Add(attribute, comp); CurrentBehaviorType = 0; CurrentBehaviorPriority = 0; CurrentBehaviorName = string.Empty; } } } // If we found no methods, rofls! if (matchedMethods.Count <= 0) { return null; } var result = new PrioritySelector(); foreach (var kvp in matchedMethods.OrderByDescending(mm => mm.Key.PriorityLevel)) { result.AddChild(kvp.Value); behaviourCount++; } return result; }
public static Composite GetComposite(WoWClass wowClass, WoWSpec spec, BehaviorType behavior, WoWContext context, out int behaviourCount, bool silent = false) { if (context == WoWContext.None) { // None is an invalid context, but rather than stopping bot wait it out with donothing logic Logger.Write(Color.White, "No Active Context -{0}{1} for{2} set to DoNothingBehavior temporarily", wowClass.ToString().CamelToSpaced(), behavior.ToString().CamelToSpaced(), spec.ToString().CamelToSpaced()); behaviourCount = 1; return NoContextAvailable.CreateDoNothingBehavior(); } SilentBehaviorCreation = silent; behaviourCount = 0; if (_methods.Count <= 0) { // Logger.WriteDebug("Singular Behaviors: building method list"); foreach (var type in Assembly.GetExecutingAssembly().GetTypes()) { // All behavior methods should not be generic, and should have zero parameters, with their return types being of type Composite. _methods.AddRange( type.GetMethods(BindingFlags.Static | BindingFlags.Public).Where( mi => !mi.IsGenericMethod && mi.GetParameters().Length == 0).Where( mi => mi.ReturnType.IsAssignableFrom(typeof (Composite)))); } Logger.WriteFile("Singular Behaviors: Added " + _methods.Count + " behaviors"); } var matchedMethods = new Dictionary<BehaviorAttribute, Composite>(); foreach (MethodInfo mi in _methods) { // If the behavior is set as ignore. Don't use it? Duh? if (mi.GetCustomAttributes(typeof(IgnoreBehaviorCountAttribute), false).Any()) continue; // If there's no behavior attrib, then move along. foreach (var a in mi.GetCustomAttributes(typeof(BehaviorAttribute), false)) { var attribute = a as BehaviorAttribute; if (attribute == null) continue; // Check if our behavior matches with what we want. If not, don't add it! if (IsMatchingMethod(attribute, wowClass, spec, behavior, context)) { if (!silent) Logger.WriteFile("{0} {1} {2}", attribute.PriorityLevel.ToString().AlignRight(4), behavior.ToString().AlignLeft(15), mi.Name); CurrentBehaviorType = behavior; // if it blows up here, you defined a method with the exact same attribute and priority as one already found // wrap in trace class Composite comp = mi.Invoke(null, null) as Composite; string name = behavior.ToString() + "." + mi.Name + "." + attribute.PriorityLevel.ToString(); if (SingularSettings.Trace) comp = new CallTrace( name, comp); matchedMethods.Add(attribute, comp); CurrentBehaviorType = 0; } } } // If we found no methods, rofls! if (matchedMethods.Count <= 0) { return null; } var result = new PrioritySelector(); foreach (var kvp in matchedMethods.OrderByDescending(mm => mm.Key.PriorityLevel)) { result.AddChild(kvp.Value); behaviourCount++; } return result; }