private int wordCharIndex; // Character index for the current word being parsed. #endregion Fields #region Constructors //----------------------------------------------------------------------------- // Constructor //----------------------------------------------------------------------------- public ScriptReader() { parameter = null; parameterRoot = null; commands = new List<ScriptCommand>(); lines = new List<string>(); }
private void _InvokeRegister(string name, CommandParam param) { var registerMethod = GetRegister(param.Types, param.ReturnType); if(param.ReturnType != null) { var returnValue = registerMethod.Invoke( _Command, new[] { name, param.Callback, param.Return }); } else { var returnValue = registerMethod.Invoke( _Command, new[] { name, param.Callback }); } }
// Parse and interpret the given text stream as a script, line by line. public void ReadScript(StreamReader reader, string path) { this.fileName = path; this.streamReader = reader; BeginReading(); // Setup the parsing variables. parameterParent = new CommandParam(""); parameterParent.Type = CommandParamType.Array; parameterRoot = parameterParent; parameter = null; // Read all lines. lineIndex = -1; lines.Clear(); while (!reader.EndOfStream) { NextLine(); ParseLine(line); } EndReading(); }
DesignDataAgent.CommandExecuteResult ResetPropertyValue(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //none param IEnumerable <string> path = designDataAgent.GetPathWithCommandAndParam(param, "target"); SerializedProperty p = designDataAgent.GetNodeByPath(path).GetProperty(); foreach (var el in GetVisibleChildren(p)) { if (el.isArray) { el.ClearArray(); } else { SetDefaultValue(el); } } p.serializedObject.ApplyModifiedProperties(); return(new DesignDataAgent.CommandExecuteResult { resultDescription = $"Reset : {Utilities.GetPathString(path)}" }); void SetDefaultValue(SerializedProperty spForSetDefault) { switch (spForSetDefault.propertyType) { case SerializedPropertyType.Integer: spForSetDefault.intValue = default; break; case SerializedPropertyType.Float: spForSetDefault.floatValue = default; break; case SerializedPropertyType.String: spForSetDefault.stringValue = default; break; case SerializedPropertyType.Boolean: spForSetDefault.boolValue = default; break; case SerializedPropertyType.Enum: spForSetDefault.intValue = default; break; case SerializedPropertyType.Vector2: spForSetDefault.vector2Value = default; break; case SerializedPropertyType.ObjectReference: spForSetDefault.objectReferenceValue = default; break; case SerializedPropertyType.ArraySize: //Do nothing break; default: Debug.LogError($"{designDataAgent.GetCellId(designDataAgent.currentExecutingCommand.Value)} 執行設定預設值時,沒有對應的型別可執行:{spForSetDefault.displayName} ({spForSetDefault.propertyType})。"); //throw new Exception($"{GetCommandId(currentExecutingCommand.Value)} 執行設定預設值時,沒有對應的型別可執行:{spForSetDefault.displayName} ({spForSetDefault.propertyType})。"); break; } } IEnumerable <SerializedProperty> GetVisibleChildren(SerializedProperty serializedProperty) { SerializedProperty currentProperty = serializedProperty.Copy(); SerializedProperty nextSiblingProperty = serializedProperty.Copy(); { nextSiblingProperty.NextVisible(false); } if (currentProperty.NextVisible(true)) { do { if (SerializedProperty.EqualContents(currentProperty, nextSiblingProperty)) { break; } yield return(currentProperty); }while (currentProperty.NextVisible(false)); } } }
DesignDataAgent.CommandExecuteResult SetObject(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //value: [格值][賦予值] //target: [目標路徑] AssetDatabase.SaveAssets(); UnityEngine.Object target = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(param["value"]); return(SetValue(cellInfo, param, target, ValueType.Object)); }
DesignDataAgent.CommandExecuteResult SetEnum <T>(DesignDataAgent.CellInfo cellInfo, CommandParam param) where T : Enum { return(SetValue(cellInfo, param, Enum.Parse(typeof(T), cellInfo.value), ValueType.Enum)); }
// Complete the current statement being parsed, looking for a command. protected void CompleteStatement() { if (parameterRoot.Children != null) { // Take the command name from the parameters. string commandName = parameterRoot.Children.StringValue; parameterRoot.LineIndex = parameterRoot.Children.LineIndex; parameterRoot.CharIndex = parameterRoot.Children.CharIndex; parameterRoot.Children = parameterRoot.Children.NextParam; parameterRoot.ChildCount--; // Attempt to perform the command. PerformCommand(commandName, parameterRoot); } // Reset the parameter list. parameterParent = new CommandParam(""); parameterParent.Type = CommandParamType.Array; parameterRoot = parameterParent; parameter = null; }
DesignDataAgent.CommandExecuteResult IsTrue(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //value: [格值][判斷值] param = SetDefaultValueParam(cellInfo, param); string v = param["value"]; return(new DesignDataAgent.CommandExecuteResult { conditionResult = bool.Parse(v), hideInLog = true, }); }
DesignDataAgent.CommandExecuteResult IsEmptyString(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //value [格值][判斷值] param = SetDefaultValueParam(cellInfo, param); string value = param["value"].Trim(); string[] compare = new[] { "''", "\"\"", emptyString, "" }; bool result = compare.Any(c => c == value); return(new DesignDataAgent.CommandExecuteResult { conditionResult = result, hideInLog = true, }); }
DesignDataAgent.CommandExecuteResult ForMethod(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //methodName: [MethodName] //rangeString: [範圍] 1.單範圍指定:「1」2.範圍指定:「1-10」 3.集合指定:「[1,3,5,7]」 //[indexName]: [index名稱](預設index) //[rootPath]: [RootPath] //提供{param.rootPath}可使用rootPath //提供{param.index}、{param.index:00}、{param.index:000}可使用index param = SetDefaultValueParam(cellInfo, param); param = SetDefaultParam(param, "indexName", "index"); param = SetDefaultParam(param, "rootPath", ""); string indexKeyName = param["indexName"]; IEnumerable <int> elements = GetIndexSet(param["rangeString"]); Debug.Log($"{designDataAgent.GetCellId(cellInfo)}\tFor {indexKeyName} = {param["rangeString"]}"); designDataAgent.logDepth++; // foreach (int index in GetIndexSet(param["rangeString"])) { SetIndexParam(indexKeyName, index); //執行 Method(cellInfo, new CommandParam { ["methodName"] = designDataAgent.FillParam(cellInfo, param["methodName"]), //此時填入Param ["rootPath"] = param["rootPath"], }); } // designDataAgent.logDepth--; Debug.Log($"{designDataAgent.GetCellId(cellInfo)}\tEnd {indexKeyName}"); ClearIndexParam(indexKeyName); return(new DesignDataAgent.CommandExecuteResult { hideInLog = true, }); IEnumerable <int> GetIndexSet(string rangeString) { if (Utilities.IsStartWith(rangeString, "[") && Utilities.IsEndWith(rangeString, "]")) { foreach (var el in rangeString .Substring(1, rangeString.Length - 2) .Split(',') .Select(_ => int.Parse(_.Trim()))) { yield return(el); } } else if (rangeString.Contains('-')) { IEnumerable <int> range = rangeString.Split('-').Select(_ => int.Parse(_.Trim())); int startIndex = range.ElementAt(0); int endIndex = range.ElementAt(1); int indexStep = (endIndex - startIndex > 0) ? 1 : -1; int currentIndex = startIndex; while ((indexStep > 0) ? currentIndex <= endIndex : currentIndex >= endIndex) { yield return(currentIndex); currentIndex += indexStep; } } else { yield return(int.Parse(rangeString)); } } void SetIndexParam(string _indexKeyName, int i) { designDataAgent.SetParam(_indexKeyName, $"{i}"); designDataAgent.SetParam($"{_indexKeyName}:00", $"{i:00}"); designDataAgent.SetParam($"{_indexKeyName}:000", $"{i:000}"); } void ClearIndexParam(string _indexKeyName) { designDataAgent.ClearParam(_indexKeyName); designDataAgent.ClearParam($"{_indexKeyName}:00"); designDataAgent.ClearParam($"{_indexKeyName}:000"); } }
// Add a new command parameter child to the current parent parameter. private CommandParam AddParam() { CommandParam newParam = new CommandParam(word); newParam.CharIndex = wordCharIndex; newParam.LineIndex = lineIndex; if (parameter == null) parameterParent.Children = newParam; else parameter.NextParam = newParam; parameterParent.ChildCount++; newParam.Parent = parameterParent; parameter = newParam; return newParam; }
// Throw a parse error exception for a specific argument. protected void ThrowParseError(string message, CommandParam param) { throw new ScriptReaderException(message, fileName, lines[param.LineIndex], param.LineIndex + 1, param.CharIndex + 1, true); }
//----------------------------------------------------------------------------- // Misc //----------------------------------------------------------------------------- protected void PrintParementers(CommandParam param) { CommandParam p = param.Children; while (p != null) { if (p.Type == CommandParamType.Array) { Console.Write("("); PrintParementers(p); Console.Write(")"); } else Console.Write(p.StringValue); p = p.NextParam; if (p != null) Console.Write(", "); } }
// Reads a line in the script as a command. protected virtual bool PerformCommand(string commandName, CommandParam parameters) { List<string> matchingFormats = new List<string>(); CommandParam newParams = null; // Search for the correct command. for (int i = 0; i < commands.Count; i++) { ScriptCommand command = commands[i]; if (command.HasName(commandName)) { if (command.HasParameters(parameters, out newParams)) { // Run the command. command.Action(newParams); return true; } else { // Preemptively append the possible overloads to the error message. for (int j = 0; j < command.ParameterOverloads.Count; j++) matchingFormats.Add(command.Name + " " + CommandParamParser.ToString(command.ParameterOverloads[j])); } } } // Throw an error because the command was not found. if (matchingFormats.Count > 0) { Console.WriteLine(CommandParamParser.ToString(parameters)); string msg = "No matching overload found for the command " + commandName + "\n"; msg += "Possible overloads include:\n"; for (int i = 0; i < matchingFormats.Count; i++) { msg += " * " + matchingFormats[i]; if (i + 1 < matchingFormats.Count) msg += "\n"; } ThrowCommandParseError(msg); } else { ThrowCommandParseError(commandName + " is not a valid command"); } return false; }
// Parse a single line in the script. protected void ParseLine(string line) { bool quotes = false; word = ""; charIndex = 0; // Parse line character by character. for (int i = 0; i < line.Length; i++) { char c = line[i]; charIndex = i; // Parse quotes. if (quotes) { // Closing quotes. if (c == '"') { quotes = false; CompleteWord(true); } else word += c; } // Whitespace and commas (parameter delimiters). else if (c == ' ' || c == '\t' || c == ',') CompleteWord(); // Semicolons. else if (c == ';') { CompleteWord(); int prevLineIndex = lineIndex; CompleteStatement(); if (lineIndex > prevLineIndex) // Commands are allowed to read the next lines in the file. return; } // Single-line comment. else if (c == '#') break; // Ignore the rest of the line. // Opening quotes. else if (word.Length == 0 && c == '\"') quotes = true; // Opening parenthesis: begin an array parameter. else if (word.Length == 0 && c == '(') { parameterParent = AddParam(); parameterParent.Type = CommandParamType.Array; parameter = null; } // Closing parenthesis. else if (c == ')') { CompleteWord(); if (parameterParent == parameterRoot) { ThrowParseError("Unexpected symbol ')'"); } else { parameter = parameterParent; parameterParent = parameterParent.Parent; } } // Valid keyword character. else if (IsValidKeywordCharacter(c)) { if (word.Length == 0) wordCharIndex = charIndex; word += c; } // Error: Unexpected character. else ThrowParseError("Unexpected symbol '" + c + "'"); } charIndex++; // Make sure quotes are closed at the end of the line. if (quotes) ThrowParseError("Expected \""); CompleteWord(); }
DesignDataAgent.CommandExecuteResult PrintText(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //value: [格值][印出值] param = SetDefaultValueParam(cellInfo, param); Debug.Log(param["value"]); return(new DesignDataAgent.CommandExecuteResult { hideInLog = true }); }
DesignDataAgent.CommandExecuteResult SaveAssets(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //none param AssetDatabase.SaveAssets(); return(new DesignDataAgent.CommandExecuteResult { hideInLog = true, }); }
public void Free2(CommandParam param) { ControlCommandPackage package = new ControlCommandPackage(); package.CommandType = CommandType.Free2; package.CommandParam = param; WriteData(CreateCommandBuffer(package)); }
DesignDataAgent.CommandExecuteResult SetRoot(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //asset: [asset目錄] if (designDataAgent.targetTable.tableVersion >= 1) { } else if (designDataAgent.targetTable.tableVersion >= 0) { throw new Exception("SetRoot 的參數 assetPath已過時,請改為asset"); } param = SetDefaultValueParam(cellInfo, param); string assetPath = param["asset"]; designDataAgent.SetRoot(assetPath); return(new DesignDataAgent.CommandExecuteResult { resultDescription = $"SetRoot = {assetPath}" }); }
public static object returnValue(ISGWorld61 sgWorld,CommandParam ICommandID) { return sgWorld.Command.GetValue((int)ICommandID); }
DesignDataAgent.CommandExecuteResult IsExist(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //assetPath: [asset目錄] //assetName: [asset名稱](不含.asset) bool result; string path = $"{Path.Combine(param["assetPath"], param["assetName"])}.asset"; var o = AssetDatabase.LoadAssetAtPath(path, typeof(UnityEngine.Object)); result = o != null; return(new DesignDataAgent.CommandExecuteResult { conditionResult = result, resultDescription = $"{path} isExist = {result}", hideInLog = true, }); }
public static void RunMenuCommand(ISGWorld61 sgWorld, CommandParam ICommandID, CommandParam pCommandID) { sgWorld.Command.Execute((int)ICommandID, (int)pCommandID); }
DesignDataAgent.CommandExecuteResult IsEqual(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //value: [格值][判斷值] //compareValue: [比對值] //[splitChar]: [分割字元](預設|) param = SetDefaultParam(param, "splitChar", "|"); char splitChar = param["splitChar"][0]; IEnumerable <string> compareValue = param["compareValue"] .Split(splitChar) .Select(item => designDataAgent.FillParam(cellInfo, item)); param = SetDefaultValueParam(cellInfo, param); string v = param["value"]; bool result = compareValue.Any(s => s == v); return(new DesignDataAgent.CommandExecuteResult { conditionResult = result, hideInLog = true, }); }
public IEnumerable<CommandParam> GetParameters() { CommandParam a1 = new CommandParam { Name = "command" }; CommandParam a2 = new CommandParam { Name = "arguments", Null = true}; return new[] { a1, a2 }; }
DesignDataAgent.CommandExecuteResult SetVector2(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //value: [格值][賦予值] //target: [目標路徑] //[splitChar]: [分割字元](預設,) char spChar = ','; param = SetDefaultValueParam(cellInfo, param); param = SetDefaultParam(param, "splitChar", spChar.ToString()); spChar = param["splitChar"][0]; string[] v = param["value"].Split(spChar).Select(item => item.Trim()).ToArray(); float x = float.Parse(v.First()); float y = float.Parse(v.Last()); //取最後一個,若只填A而非A,B時,xy都會是A Vector2 v2 = new Vector2(x, y); return(SetValue(cellInfo, param, v2, ValueType.Vector2)); }
public List <AppReturn> post([FromBody] JObject values) { //_g.CONFIG_FILE = "ngarbi.settings.json"; DateTime startProcess = DateTime.Now; if (values[_g.KEY_QPARAM_JSON] != null) { // get request with complex parameters initiated return(RequestData(values)); } //dGhpcyBpcyBhIHRlc3Q= byte[] bytes = Convert.FromBase64String("dGhpcyBpcyBhIHRlc3Q="); string text = System.Text.Encoding.Default.GetString(bytes); byte[] bytes2 = System.Text.Encoding.Default.GetBytes(text); string textB64 = Convert.ToBase64String(bytes2); JObject args = AppArgs; // initialize return object AppReturn ret = new AppReturn(); if (values.ContainsKey(_g.KEY_REQUEST_HEADER_CODE)) { try { string header = (String)values[_g.KEY_REQUEST_HEADER_CODE]; // extract header Base64 byte[] jsonBytes = Convert.FromBase64String(header); // convert to byte array string jsonText = System.Text.Encoding.Default.GetString(jsonBytes); // convert to JSON string JObject json = JObject.Parse(jsonText); // convert to JSON object // loop through header information and add token to AppArgs if not yet existing foreach (JProperty jph in (JToken)json) { if (!args.ContainsKey(jph.Name)) { args.Add(jph.Name, jph.Value); } } ret.headerProcessResult.Add("result", "Success"); } catch (Exception e) { ret.headerProcessResult.Add("ErrorDetails", e.ToString()); ret.headerProcessResult.Add("result", "Error"); } } List <AppReturn> retVal = new List <AppReturn> { }; List <CommandParam> cmds = new List <CommandParam>(); JObject postConfig = null; bool useCommonNewKey = false; bool firstTable = true; List <Int64> tblCommonId = new List <Int64>(); // generate collection of commands to execute foreach (JProperty jp in (JToken)values) { // iterate through all tables to generate CommandParams collection if (jp.Name == _g.KEY_PROCESS_HEADER_CODE) { DALData.DAL.LogGlobalMessage("proces header code is supplied!", "invoke_process"); // this section is where application-specific process will be invoked ret.invokeResult = RunModels.Invoke(jp); } else if (jp.Name == _g.KEY_REQUEST_HEADER_CODE) { ; } else if (jp.Name == _g.KEY_PROCESS_CONFIG_CODE) // config code value contains instruction/parameters which // will determine specific process when posting // eg. on creation of new record with sub table, use common id // for both { postConfig = (JObject)jp.Value; if (postConfig["useCommonNewKey"] != null) { useCommonNewKey = (bool)postConfig["useCommonNewKey"]; } } else { // PROCESS TABLE CREATE, UPDATE, DELETE // get table object from the collection DALTable tbl = AppDataset.AppTables[jp.Name]; // if(!firstTable && tblCommonId) // Int64 newRecordKeyId = -1; // get collection of CommandParams per table List <CommandParam> cmdsTemp = tbl.GetCommandParamsForPosting((JArray)jp.Value, args); CommandParam cmd1 = cmdsTemp[0]; if (firstTable) { // record first table record ids. // iterate through the records' parameters if (cmd1.newKey != -1) { // new record. populate tblCommonId with key id's of all commands cmdsTemp.ForEach(cmd => tblCommonId.Add(cmd.paramKeyValue)); } firstTable = false; // set first table flag to false after processing it } else { // if use common id, if (useCommonNewKey && cmd1.newKey != -1 && tblCommonId.Count != 0) { int ctr = 0; cmdsTemp.ForEach(cmd => { cmd.cmdParams[DALData.PARAM_PREFIX + "p" + (int)cmd.paramKeyValuePosition] = tblCommonId[ctr]; ctr++; }); } } if (DALData.DAL.globalError.Length != 0) { // error has occured, therefore empty list is returned. handle error here break; } // append commands to the general collection for execution in bulk foreach (CommandParam cmd in cmdsTemp) { cmds.Add(cmd); } } // execute commands } List <ReturnObject> cmdResults = new List <ReturnObject>(); // execute all commands in the collection (if any) - debug bypass by alv 2020/12/04 5:40am cmdResults = DALData.DAL.Excute(cmds, true); DateTime endProcess = DateTime.Now; long dur = ((endProcess.Millisecond + endProcess.Second * 1000 + endProcess.Minute * 60 * 1000 + endProcess.Hour * 60 * 60 * 1000) - (startProcess.Millisecond + startProcess.Second * 1000 + startProcess.Minute * 60 * 1000 + startProcess.Hour * 60 * 60 * 1000)); //ret.returnStrings.Add("Process Duration in milliseconds: " + dur.ToString() + "(ms)"); //if (errMessage.Length!=0) ret.returnStrings.Add("Error:" + errMessage); //ret.stamps = new DALStamps(cmds[0].table.columns, "@alv"); ret.stamps = null; ret.errorMessage = DALData.DAL.globalError; if (DALData.DAL.globalMessages.Count() != 0) { ret.globalMesages = DALData.DAL.globalMessages; } retVal.Add(ret); // ***** Generate result summary for client-side processing ****** foreach (ReturnObject rObj in cmdResults) { string retCode = rObj.returnCode; if (retCode == "chgTrack" || retCode == "") { continue; } ret = new AppReturn(); ret.returnCode = rObj.returnCode; ret.errorMessage = rObj.result.exceptionMessage; ret.returnDataParams = rObj.result.returnDataParams; ret.result = rObj.result.result; retVal.Add(ret); } return(retVal); //return new List<AppReturn>(); //return new List<AppReturn> { new AppReturn() }; } /** End of POST method **/
DesignDataAgent.CommandExecuteResult SetEnumByName(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //value: [格值][賦予值] //target: [目標路徑] //enumName: [Enum名稱] param = SetDefaultValueParam(cellInfo, param); return(SetValue(cellInfo, param, Enum.Parse(Type.GetType(param["enumName"]), param["value"]), ValueType.Enum)); }
private void outputWithParamExecute(CommandParam param) { Output = string.Format("\'{0}\' was \'{1}\'. parameter: {2}", ItemX, ItemY, param); }
DesignDataAgent.CommandExecuteResult SetSprite(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //asset: [圖片目錄路徑] //target: [目標路徑] AssetDatabase.SaveAssets(); if (designDataAgent.targetTable.tableVersion >= 1) { } else if (designDataAgent.targetTable.tableVersion >= 0) { throw new Exception("Sprite 的參數 assetPath已過時,請改為asset"); } UnityEngine.Object[] targets = AssetDatabase.LoadAllAssetsAtPath(param["asset"]); Sprite target = targets.Single(item => item is Sprite) as Sprite; IEnumerable <string> path = designDataAgent.GetPathWithCommandAndParam(param, "target"); SerializedProperty p = designDataAgent.GetNodeByPath(path).GetProperty(); try { if (target is UnityEngine.Object) { p.objectReferenceValue = target; } else { throw new Exception($"{designDataAgent.GetCellId(designDataAgent.currentExecutingCommand.Value)} 執行設定值時,沒有對應的型別可執行:{p} - {target.ToString()}。"); } //紀錄 p.serializedObject.ApplyModifiedProperties(); } catch (Exception e) { throw new Exception($"{designDataAgent.GetCellId(designDataAgent.currentExecutingCommand.Value)} 執行設定值時發生錯誤:{e.Message}。"); } return(new DesignDataAgent.CommandExecuteResult { resultDescription = $"{Utilities.GetPathString(path)} = {target.name}" }); }
private MethodInfo _GetReturn(CommandParam param) { var methods = typeof(CommandParam).GetMethods(); var baseMethod = (from m in methods let parameters = m.GetParameters() where m.Name == "Return" select m).SingleOrDefault(); return baseMethod.MakeGenericMethod(param.ReturnType); }
DesignDataAgent.CommandExecuteResult ClearArray(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //none param IEnumerable <string> path = designDataAgent.GetPathWithCommandAndParam(param, "target"); SerializedProperty p = designDataAgent.GetNodeByPath(path).GetProperty(); bool isArray = p.isArray; if (isArray == true) { p.ClearArray(); p.arraySize = 0; p.serializedObject.ApplyModifiedProperties(); } return(new DesignDataAgent.CommandExecuteResult { resultDescription = $"ClearArray : {Utilities.GetPathString(path)}" }); }
public static void Register(this Command command, string name, CommandParam param) { new CommandAdapter(command).Register(name, param); }
DesignDataAgent.CommandExecuteResult CreateAsset(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //assetPath: [asset目錄] //assetName: [asset名稱](不含.asset) //assetType: [assetType] string assetName = param["assetName"]; string assetPath = param["assetPath"]; string assetType = param["assetType"]; var instance = ScriptableObject.CreateInstance(assetType); if (instance != null) { string targetPath = $"{Path.Combine(assetPath, assetName)}.asset"; AssetDatabase.CreateAsset(instance, targetPath); AssetDatabase.SaveAssets(); return(new DesignDataAgent.CommandExecuteResult { resultDescription = $"Create Asset : {targetPath}" }); } return(new DesignDataAgent.CommandExecuteResult { resultDescription = $"Create Asset Fail : AssetName={assetName}, AssetPath={assetPath}, AssetType={assetType}" }); }
public void Register(string name, CommandParam param) { _InvokeRegister(name, param); }
DesignDataAgent.CommandExecuteResult Method(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //methodName: [MethodName] //[rootPath]: [RootPath] //提供{param.rootPath}可使用rootPath const string rootPathKeyName = "rootPath"; param = SetDefaultValueParam(cellInfo, param); param = SetDefaultParam(param, rootPathKeyName, ""); designDataAgent.SetParam(rootPathKeyName, param["rootPath"]); string templateDefineName = param["methodName"]; designDataAgent.ExecuteCellInfo(new DesignDataAgent.CellInfo { id = cellInfo.id, tableLocation = cellInfo.tableLocation, methods = cellInfo.colDefines[templateDefineName], //選擇其他指定名稱的define做為執行的method value = param["value"], }); designDataAgent.ClearParam(rootPathKeyName); return(new DesignDataAgent.CommandExecuteResult { hideInLog = true, }); }
public ThemesViewModel() { SetThemeCommand = new CommandParam <string>(SetTheme); }
DesignDataAgent.CommandExecuteResult InvokeFunction(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //target: [目標路徑] //functionName: [函式名稱] //param01: [參數01] //param..: [參數..] string functionName = param["functionName"]; IEnumerable <string> path = designDataAgent.GetPathWithCommandAndParam(param, "target"); UnityEngine.Object p = designDataAgent.GetNodeByPath(path).GetObject(); MethodInfo methodInfo = p.GetType().GetMethod(functionName); ParameterInfo[] parameters = methodInfo.GetParameters(); //把param["param01"]-param["param??"]當作參數丟進去,目前參數型別只支援string[] object[] paramsArray = parameters.Select((item, i) => param[$"param{(i + 1):00}"]).ToArray(); methodInfo.Invoke(p, paramsArray); return(new DesignDataAgent.CommandExecuteResult { resultDescription = $"{Utilities.GetPathString(path)} Invoke Function : {functionName}({string.Join(",", paramsArray)})" }); }
public static CommandParam SetDefaultValueParam(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //若參數有帶值,就不會用格內值覆寫 if (param.TryGetValue("value", out string v) == true) { return(param); } return(SetDefaultParam(param, "value", cellInfo.value)); }
DesignDataAgent.CommandExecuteResult NotEmpty(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //value [格值][判斷值] param = SetDefaultValueParam(cellInfo, param); bool result = string.IsNullOrEmpty(param["value"]) == false; return(new DesignDataAgent.CommandExecuteResult { conditionResult = result, hideInLog = true, }); }
DesignDataAgent.CommandExecuteResult SetValue(DesignDataAgent.CellInfo cellInfo, CommandParam param, object value, ValueType valueType) { IEnumerable <string> path = designDataAgent.GetPathWithCommandAndParam(param, "target"); SerializedProperty p = designDataAgent.GetNodeByPath(path).GetProperty(); if (p == null) { throw new Exception($"{designDataAgent.GetCellId(cellInfo)}找到的Path目標為null。Path={param["target"]}"); } string resultDescription = null; try { switch (valueType) { case ValueType.Int: p.intValue = (int)value; resultDescription = $"{Utilities.GetPathString(path)} = {value}"; break; case ValueType.Float: p.floatValue = (float)value; resultDescription = $"{Utilities.GetPathString(path)} = {value}F"; break; case ValueType.String: p.stringValue = value as string; resultDescription = $"{Utilities.GetPathString(path)} = \"{value}\""; break; case ValueType.Boolean: bool resultBool = (bool)value; p.boolValue = resultBool; resultDescription = $"{Utilities.GetPathString(path)} = {resultBool.ToString().ToLower()}"; break; case ValueType.Vector2: Vector2 resultVector2 = (Vector2)value; p.vector2Value = resultVector2; resultDescription = $"{Utilities.GetPathString(path)} = Vector2({resultVector2.x},{resultVector2.y})"; break; case ValueType.Enum: p.intValue = (int)value; resultDescription = $"{Utilities.GetPathString(path)} = {param["enumName"].Replace('+', '.')}.{value}"; break; case ValueType.Object: UnityEngine.Object resultObject = value as UnityEngine.Object; p.objectReferenceValue = resultObject; resultDescription = $"{Utilities.GetPathString(path)} = {resultObject.name}"; break; default: throw new Exception($"{designDataAgent.GetCellId(designDataAgent.currentExecutingCommand.Value)} 執行設定值時,沒有對應的型別可執行:{p} - {value.ToString()}({value.GetType().Name})。"); } //紀錄 p.serializedObject.ApplyModifiedProperties(); } catch (Exception e) { throw new Exception($"{designDataAgent.GetCellId(designDataAgent.currentExecutingCommand.Value)} 執行設定值時發生錯誤:{e.Message}。"); } return(new DesignDataAgent.CommandExecuteResult { resultDescription = resultDescription }); }
DesignDataAgent.CommandExecuteResult IsLast(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //colName01: [欄位名稱01] //colName..: ...[複數] int r = cellInfo.tableLocation.row - designDataAgent.targetTable.dataBeginRowIndex; string targetValue = GetCompareKey(param, r); for (int i = r + 1; i < designDataAgent.targetTable.rows.Count; i++) { string cellValue = GetCompareKey(param, i); if (targetValue == cellValue) { return(new DesignDataAgent.CommandExecuteResult { conditionResult = false, resultDescription = $"{targetValue} 並非最後一個出現的元素,不符合條件", hideInLog = true, }); } } return(new DesignDataAgent.CommandExecuteResult { conditionResult = true, resultDescription = $"{targetValue} 為最後一個出現的元素,符合條件並執行", hideInLog = true, }); string GetCompareKey(CommandParam colNames, int row) { List <string> s = new List <string>(); for (int i = 0; i < 10; i++) { if (colNames.TryGetValue($"colName{i:00}", out string v) == true) { s.Add(v); } } return(string.Join(";", s.Select(colName => designDataAgent.targetTable.rows[row][colName]))); } }
DesignDataAgent.CommandExecuteResult SetInt(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //value: [格值][賦予值] //target: [目標路徑] //parseMode: [Ceiling | Floor | Round | ""] param = SetDefaultValueParam(cellInfo, param); param = SetDefaultParam(param, "parseMode", ""); return(SetValue(cellInfo, param, GetIntValue(), ValueType.Int)); int GetIntValue() { string value = param["value"]; switch (param["parseMode"]) { case "Ceiling": return(Mathf.CeilToInt(float.Parse(value))); case "Floor": return(Mathf.FloorToInt(float.Parse(value))); case "Round": return(Mathf.RoundToInt(float.Parse(value))); default: return(int.Parse(value)); } } }
DesignDataAgent.CommandExecuteResult IsNotExist(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //assetPath: [asset目錄] //assetName: [asset名稱](不含.asset) var result = IsExist(cellInfo, param); string path = $"{Path.Combine(param["assetPath"], param["assetName"])}.asset"; return(new DesignDataAgent.CommandExecuteResult { conditionResult = (result.conditionResult == false), resultDescription = $"{path} isNotExist = {(result.conditionResult == false)}", hideInLog = true, }); }
DesignDataAgent.CommandExecuteResult SetFloat(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //value: [格值][賦予值] //target: [目標路徑] param = SetDefaultValueParam(cellInfo, param); return(SetValue(cellInfo, param, float.Parse(param["value"]), ValueType.Float)); }
DesignDataAgent.CommandExecuteResult IsFalse(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //value: [格值][判斷值] var result = IsTrue(cellInfo, param); return(new DesignDataAgent.CommandExecuteResult { conditionResult = result.conditionResult == false, hideInLog = true, }); }
DesignDataAgent.CommandExecuteResult SetString(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //value: [格值][賦予值] //target: [目標路徑] param = SetDefaultValueParam(cellInfo, param); string s = param["value"].Trim(); if (Utilities.IsPinchWith(s, new[] { '"' }) || Utilities.IsPinchWith(s, new[] { '\'' })) { s = Utilities.CutString(s, 1, 1); } else if (s == emptyString) { s = string.Empty; } return(SetValue(cellInfo, param, s, ValueType.String)); }
DesignDataAgent.CommandExecuteResult IsNotEqual(DesignDataAgent.CellInfo cellInfo, CommandParam param) { //value: [格值][判斷值] //compareValue: [比對值] //[splitChar]: [分割字元](預設|) var result = IsEqual(cellInfo, param); return(new DesignDataAgent.CommandExecuteResult { conditionResult = (result.conditionResult == false), hideInLog = true, }); }
public IEnumerable<CommandParam> GetParameters() { CommandParam a1 = new CommandParam { Name = "file" }; return new[] { a1 }; }