// ------------------------------------------ // CLONING // ------------------------------------------ #region Cloning /// <summary> /// Clones this instance. /// </summary> /// <returns>Returns a clone of this instance.</returns> public override object Clone(params string[] areas) { IBdoScriptwordConfiguration config = base.Clone(areas) as BdoScriptwordConfiguration; config.ParameterDetail = ParameterDetail?.Clone <DataElementSet>(); config.SubScriptword = SubScriptword?.Clone <BdoScriptwordConfiguration>(); return(config); }
/// <summary> /// Start Strategy Optimization /// </summary> /// <param name="optimizationParameters">Contains info for the parameters to be used for optimization</param> private void StartOptimization(BruteForceParameters optimizationParameters) { try { // Save instance _optimizationParameters = optimizationParameters; if (_asyncClassLogger.IsInfoEnabled) { _asyncClassLogger.Info("Getting argument combinations", _type.FullName, "StartOptimization"); } // Change Status to indicate on UI _optimizationParameters.Status = OptimizationStatus.Working; // Clear all previous information _strategiesCollection.Clear(); _ctorArguments.Clear(); // Get Parameter values to be used in the Constructor object[] ctorArguments = optimizationParameters.GetParameterValues(); // Get Conditional Parameter values to be used for creating Iterations Tuple <int, object, double>[] conditionalParameters = optimizationParameters.GetConditionalParameters(); // Save Parameter Details _parmatersDetails = optimizationParameters.ParameterDetails; // Get all ctor arguments to be used for optimization CreateCtorCombinations(ctorArguments, conditionalParameters); // Initialize Stratgey for each set of arguments foreach (object[] ctorArgumentValues in _ctorArguments) { // Get new Key. string key = ApplicationIdGenerator.NextId(); var instanceParameterDetails = new Dictionary <string, ParameterDetail>(); for (int i = 0; i < ctorArgumentValues.Length; i++) { // Create new parameter details to be when creating Strategy Instance object ParameterDetail tempParameterDetail = new ParameterDetail(_parmatersDetails[i].ParameterType, ctorArgumentValues[i]); instanceParameterDetails.Add(_parmatersDetails[i].Description, tempParameterDetail); } // Create Strategy Instance object var instance = new StrategyInstance(key, instanceParameterDetails, optimizationParameters.StrategyType); // Save Strategy details in new Strategy Executor object var strategyExecutor = new StrategyExecutor(instance, _currentDispatcher); // Register Event strategyExecutor.StatusChanged += OnStrategyExecutorStatusChanged; // Add to local map _strategiesCollection.AddOrUpdate(key, strategyExecutor, (ky, value) => strategyExecutor); StringBuilder parametersInfo = new StringBuilder(); foreach (object ctorArgument in strategyExecutor.CtorArguments) { parametersInfo.Append(ctorArgument.ToString()); parametersInfo.Append(" | "); } // Create new object to be used with Event Aggregator var optimizationStatistics = new OptimizationStatistics(strategyExecutor.StrategyKey); optimizationStatistics.Description = parametersInfo.ToString(); optimizationStatistics.ExecutionDetails = instance.ExecutionDetails; // Raise event to Bind statistics to UI and will be updated as each instance is executed EventSystem.Publish <OptimizationStatistics>(optimizationStatistics); } // Save total number of iterations count _optimizationParameters.TotalIterations = _strategiesCollection.Count; // Start executing each instance StartStrategyExecution(); } catch (Exception exception) { _asyncClassLogger.Error(exception, _type.FullName, "StartOptimization"); } }
/// <summary> /// Returns if animator is updated and bytes of updated values. /// </summary> /// <returns></returns> private bool AnimatorUpdated(out byte[] updatedBytes, bool forceAll = false) { updatedBytes = null; List <ChangedParameter> cps = new List <ChangedParameter>(); //Bytes required to accomodate changed parameters. int requiredBytes = 0; /* Every time a parameter is updated a byte is added * for it's index, this is why requiredBytes increases * by 1 when a value updates. ChangedParameter contains * the index updated and the new value. The requiresBytes * is increased also by however many bytes are required * for the type which has changed. Some types use special parameter * detail indexes, such as layer weights; these can be found under const. */ for (byte i = 0; i < _parameterDetails.Count; i++) { ParameterDetail pd = _parameterDetails[i]; /* Bool. */ if (pd.ControllerParameter.type == AnimatorControllerParameterType.Bool) { bool next = _animator.GetBool(pd.Hash); //If changed. if (forceAll || _bools[pd.TypeIndex] != next) { cps.Add(new ChangedParameter(i, BitConverter.GetBytes(next))); _bools[pd.TypeIndex] = next; //Parameter index + data. requiredBytes += (1 + 1); } } /* Float. */ else if (pd.ControllerParameter.type == AnimatorControllerParameterType.Float) { float next = _animator.GetFloat(pd.Hash); //If changed. if (forceAll || _floats[pd.TypeIndex] != next) { byte[] data = Compression.ReturnCompressedFloat(next); cps.Add(new ChangedParameter(i, data)); _floats[pd.TypeIndex] = next; //Parameter index + data. requiredBytes += (1 + data.Length); } } /* Int. */ else if (pd.ControllerParameter.type == AnimatorControllerParameterType.Int) { int next = _animator.GetInteger(pd.Hash); //If changed. if (forceAll || _ints[pd.TypeIndex] != next) { byte[] data = Compression.ReturnCompressedInteger(next); cps.Add(new ChangedParameter(i, data)); _ints[pd.TypeIndex] = next; //Parameter index + data. requiredBytes += (1 + data.Length); } } } /* Also add any trigger updates. * Each trigger update will require * 2 bytes, for the indicator and value. * So add on two required bytes * for every trigger update count. */ /* Don't need to force trigger sends since * they're one-shots. */ requiredBytes += (_triggerUpdates.Count * 2); cps.AddRange(_triggerUpdates); _triggerUpdates.Clear(); //States. if (forceAll) { //Add all layers to layer states. for (int i = 0; i < _animator.layerCount; i++) { _unsynchronizedLayerStates.Add(i); } } //Go through each layer which needs to be synchronized. foreach (int layerIndex in _unsynchronizedLayerStates) { if (ReturnLayerState(out int stateHash, out float normalizedTime, layerIndex)) { int writeIndex = 0; //Cannot compress hash, it will always be too large. byte[] hashBytes = BitConverter.GetBytes(stateHash); byte[] time = Compression.ReturnCompressedFloat(normalizedTime); //Resize for layerindex, hash, and time. byte[] data = new byte[1 + hashBytes.Length + time.Length]; //Layer index. data[0] = (byte)layerIndex; writeIndex++; //Hash. Array.Copy(hashBytes, 0, data, writeIndex, hashBytes.Length); writeIndex += hashBytes.Length; //Time. Array.Copy(time, 0, data, writeIndex, time.Length); _animator.Play(stateHash, layerIndex, normalizedTime); //1 for parameter index and then data. requiredBytes += (1 + data.Length); //Add to cps. cps.Add(new ChangedParameter(STATE, data)); } } _unsynchronizedLayerStates.Clear(); //Layer weights are added on as raw bytes List <byte> layerBytes = null; for (int i = 0; i < _layerWeights.Length; i++) { float next = _animator.GetLayerWeight(i); if (forceAll || _layerWeights[i] != next) { if (layerBytes == null) { layerBytes = new List <byte>(); } //Layerweight indicator. layerBytes.Add(LAYER_WEIGHT); //Layer index. layerBytes.Add((byte)i); //Weight value. byte[] compressedWeight = Compression.ReturnCompressedFloat(next); layerBytes.AddRange(compressedWeight); //indicator, layer index, data. requiredBytes += (2 + compressedWeight.Length); _layerWeights[i] = next; } } /* Speed is similar to layer weights but we don't need the index, * only the indicator and value. */ byte[] speedBytes = null; float speedNext = _animator.speed; if (forceAll || _speed != speedNext) { byte[] speedCompressed = Compression.ReturnCompressedFloat(speedNext); //1 byte for speed indicator, rest for actual speed. speedBytes = new byte[1 + speedCompressed.Length]; speedBytes[0] = SPEED; Array.Copy(speedCompressed, 0, speedBytes, 1, speedCompressed.Length); //Indicator + value. requiredBytes += speedBytes.Length; _speed = speedNext; } //If no bytes are required then there is nothing to update. if (requiredBytes == 0) { return(false); } //Current write index for byte array. int updateWriteIndex = 0; updatedBytes = new byte[requiredBytes]; //If speed change exist. if (speedBytes != null) { Array.Copy(speedBytes, 0, updatedBytes, updateWriteIndex, speedBytes.Length); updateWriteIndex += speedBytes.Length; } //If there are layer weights to add. if (layerBytes != null) { byte[] layersArray = layerBytes.ToArray(); Array.Copy(layersArray, 0, updatedBytes, updateWriteIndex, layersArray.Length); updateWriteIndex += layersArray.Length; } //If there are changed parameters. if (cps.Count > 0) { //Build into byte array. foreach (ChangedParameter cp in cps) { updatedBytes[updateWriteIndex] = cp.ParameterIndex; Array.Copy(cp.Data, 0, updatedBytes, updateWriteIndex + 1, cp.Data.Length); //Increase index. updateWriteIndex += (1 + cp.Data.Length); } } return(true); }
/// <summary>InspectConstructor /// <para></para> /// </summary> public Dictionary <int, ParameterDetail> InspectMethods(Type CurrentType) { ParameterInfo[] parameters = null; ParameterDetail ObjParameterDetail = null; AnnotationDefination ObjAnnotationDefination = null; Dictionary <int, ParameterDetail> CtorParams = new Dictionary <int, ParameterDetail>(); List <string> TypeCollections = null; ParameterNameCollection ObjParameterNameCollection = null; List <string> GenericParameterTypeName = new List <string>(); try { int index = 0; TypeCollections = new List <string>(); foreach (var ctor in CurrentType.GetConstructors()) { ObjParameterDetail = new ParameterDetail(); parameters = ctor.GetParameters(); foreach (var param in parameters) { var NewType = param.ParameterType; String FullNameSpace = NewType.AssemblyQualifiedName; if (FullNameSpace != null) { if (FullNameSpace != null) { ObjParameterNameCollection = new ParameterNameCollection(); ObjParameterDetail.WrapperFullDescription = ""; if (FullNameSpace.IndexOf("`") != -1) { ObjParameterNameCollection.Name = FullNameSpace; } else { ObjParameterNameCollection.Name = FullNameSpace.Split(new char[] { ',' })[0]; } ObjParameterNameCollection.ArgumentName = param.Name; ObjParameterDetail.Parameters.Add(ObjParameterNameCollection); } else { throw new ApplicationException("Unable to resolve constructor paramter for class: " + NewType.Name); } } else if (NewType.AssemblyQualifiedName == null) { if (NewType.IsGenericType) { if (NewType.AssemblyQualifiedName == null) { if (NewType.GenericTypeArguments.Count() > 0) { ObjParameterNameCollection = BuildParameter(NewType, ref GenericParameterTypeName); } if (ObjParameterNameCollection != null) { TypeCollections.Add(ObjParameterNameCollection.Name); } } } else { ObjParameterNameCollection = BuildParameter(NewType, ref GenericParameterTypeName); if (ObjParameterNameCollection != null) { TypeCollections.Add(ObjParameterNameCollection.Name); } } ObjParameterDetail.WrapperFullDescription = ""; if (ObjParameterNameCollection == null) { ObjParameterNameCollection = new ParameterNameCollection { Name = NewType.Name } } ; ObjParameterDetail.Parameters.Add(ObjParameterNameCollection); } } IEnumerable <Attribute> CtorAttributes = ctor.GetCustomAttributes(); foreach (var attr in CtorAttributes) { ObjAnnotationDefination = new AnnotationDefination(); ObjAnnotationDefination.AnnotationName = attr.GetType().Name; ObjAnnotationDefination.AppliedOn = "ctor"; if (ObjAnnotationDefination.AnnotationName == "Enabled") { ObjAnnotationDefination.OrderNo = ((BottomhalfCore.Annotations.Enabled)attr).Order; } if (ObjAnnotationDefination.AnnotationName == "File") { ObjAnnotationDefination.Filename = ((BottomhalfCore.Annotations.File)attr).Filename; } if (ObjParameterDetail.AnnotationDetail == null) { ObjParameterDetail.AnnotationDetail = new List <AnnotationDefination>(); } ObjParameterDetail.AnnotationDetail.Add(ObjAnnotationDefination); } if ((ObjParameterDetail.AnnotationDetail != null && ObjParameterDetail.AnnotationDetail.Count > 0) || ObjParameterDetail.Parameters.Count > 0) { CtorParams.Add(++index, ObjParameterDetail); } } if (TypeCollections.Count() > 0) { ObjParameterDetail.IsGeneric = true; if (GenericParameterTypeName.Count() > 0) { ObjParameterDetail.GenericParameterTypeName = GenericParameterTypeName; } else { GenericParameterTypeName = null; } } return(CtorParams); } catch (BeanException _beanEx) { _beanEx.LocationTrack(this.GetType().FullName + "InspectConstructor()"); throw _beanEx; } catch (Exception ex) { BeanException ObjBeanException = new BeanException(); ObjBeanException.LocationTrack(this.GetType().FullName + "InspectConstructor()"); ObjBeanException.SetMessage(ex.Message); throw ObjBeanException; } }
/// <summary>ManageConstructor /// <para></para> /// </summary> public void ManageConstructor(Dictionary <string, TypeRefCollection> ClassTypeCollection) { try { string Element = null; ParameterNameCollection ParamCollectionName = null; int typeindex = 0, CtorIndex = 0, paramindex = 0; List <string> Properties = null; TypeRefCollection TypeRef = null; ParameterDetail ObjParameterDetail = null; Boolean RemoveFlag = false; Dictionary <string, List <InterfaceClassLinker> > interfaceClassLinker = container.GetInterfaceClassLinker(); INameSpaceHandler nameSpaceHandler = new NameSpaceHandler(); while (typeindex < ClassTypeCollection.Count) { TypeRef = ClassTypeCollection.ElementAt(typeindex).Value; //--------------------------------- Managing attribute --------------------------------------------------- if (TypeRef.FieldAttributesCollection != null && TypeRef.FieldAttributesCollection.Count > 0) { int fieldindex = 0; Properties = new List <string>(); while (fieldindex < TypeRef.FieldAttributesCollection.Count) { var FieldName = TypeRef.FieldAttributesCollection[fieldindex].FieldName; if (FieldName != null && FieldName.IndexOf('`') != -1) { Element = null; Element = FieldName.Substring(0, FieldName.IndexOf("[[")); var NewObj = interfaceClassLinker.Where(x => x.Key == Element).FirstOrDefault().Value; if (NewObj != null && NewObj.Count > 0) { if (TypeRef.FieldAttributesCollection[fieldindex].IsInterface) { List <string> SplittedCollection = ConvertNameSpaceToList(FieldName); /// <summary> /// Handle and manage class or types namespace /// </summary> SplittedCollection = nameSpaceHandler.ResolveNamespace(SplittedCollection); if (SplittedCollection.Count == 2) { int removeindex = 0; while (removeindex < SplittedCollection.Count) { if (SplittedCollection[removeindex].IndexOf("`") != 1) { SplittedCollection.RemoveAt(removeindex); } removeindex++; } } else { SplittedCollection[0] = NewObj.FirstOrDefault().FullName; //ParamCollectionName.Name; } if (SplittedCollection.Count == 1) { TypeRef.FieldAttributesCollection[fieldindex].FieldName = SplittedCollection[0]; TypeRef.FieldAttributesCollection[fieldindex].GenericList = null; Properties.Add(SplittedCollection[0]); } else { TypeRef.FieldAttributesCollection[fieldindex].FieldName = null; TypeRef.FieldAttributesCollection[fieldindex].GenericList = SplittedCollection; Properties.AddRange(SplittedCollection); } } } } fieldindex++; } } //-------------------------------------------- Managing controller ------------------------------------------- if (TypeRef != null && TypeRef.Constructors.Count > 0) { CtorIndex = 0; while (CtorIndex < TypeRef.Constructors.Count) { ObjParameterDetail = TypeRef.Constructors.ElementAt(CtorIndex).Value; if (ObjParameterDetail != null && ObjParameterDetail.Parameters.Count > 0) { paramindex = 0; while (paramindex < ObjParameterDetail.Parameters.Count) { RemoveFlag = false; ParamCollectionName = ObjParameterDetail.Parameters.ElementAt(paramindex); //-------------> Converting generic collection types ----------------------------- if (ParamCollectionName.Name.IndexOf("`") != -1) { if ((ParamCollectionName.Name.Split(new char[] { '`' })[0]).IndexOf("System.Collections") == -1) { if (ParamCollectionName.Name.IndexOf("[[") != -1) { Element = ParamCollectionName.Name.Split(new string[] { "[[" }, StringSplitOptions.RemoveEmptyEntries)[0]; } else { Element = ParamCollectionName.Name; } if (Element.IndexOf("`1") != -1) { if (ParamCollectionName.Name.IndexOf("[[") != -1) { Element = ParamCollectionName.Name.Split(new string[] { "[[" }, StringSplitOptions.RemoveEmptyEntries)[1]; } else { Element = ParamCollectionName.Name; } ParamCollectionName.Name = Element.Split(new[] { ',' })[0]; RemoveFlag = true; } else { var NewObj = interfaceClassLinker.Where(x => x.Key == Element).FirstOrDefault().Value; if (NewObj != null) { RemoveFlag = true; ParamCollectionName.Name = NewObj.FirstOrDefault().FullName; } } ObjParameterDetail.Parameters[paramindex++] = ParamCollectionName; } else { RemoveFlag = true; Element = GetImplementedName(ParamCollectionName.Name); ObjParameterDetail.Parameters[paramindex++] = ParamCollectionName; } } if (!RemoveFlag) { paramindex++; } } } CtorIndex++; } } typeindex++; } } catch (BeanException _beanEx) { _beanEx.LocationTrack(this.GetType().FullName + "ManageConstructor()"); throw _beanEx; } catch (Exception ex) { BeanException ObjBeanException = new BeanException(); ObjBeanException.LocationTrack(this.GetType().FullName + "ManageConstructor()"); ObjBeanException.SetMessage(ex.Message); throw ObjBeanException; } }