private double EvaluateCell(int cell_index, double cur_val, List <double> n_vals) { //Dictionary<string, double> h_dict; var t = Type.GetType("IronPython.Runtime.List,IronPython"); IList n_list = Activator.CreateInstance(t) as IList; foreach (double d in n_vals) { object cast = d; n_list.Add(cast); } Dictionary <string, double> h_dict = new Dictionary <string, double>(); h_dict.Add("a", 1.0); GH_Dict test = GH_Dict.create("a", cur_val); _py.SetVariable("n_vals", n_list); _py.SetVariable("h_val", cur_val); _py.SetVariable("h_idx", cell_index); _py.SetVariable("h_dict", h_dict); _py.SetVariable("test", test); try { _compiled_py.Execute(_py); } catch (Exception ex) { AddErrorNicely(m_py_output, ex); } //object o = _py.GetVariable("h_val"); GH_Dict out_dict = (GH_Dict)_py.GetVariable("test"); var o = out_dict.val["b"]; return(System.Convert.ToDouble(o)); }
protected override void SolveInstance(IGH_DataAccess DA) { UpdateMessage(); PythonScript script = PythonScript.Create(); string outDir = ""; try { script.ExecuteScript("import scriptcontext as sc\nV=sc.sticky['NOAH_PROJECT']\nT=sc.sticky['TASK_TICKET']\nG=sc.sticky['NOAH_GENERATOR']\nID=sc.sticky['UUID']"); NOAH_PROJECT = (string)script.GetVariable("V"); TASK_TICKET = (string)script.GetVariable("T"); NOAH_GENERATOR = (string)script.GetVariable("G"); UUID = (string)script.GetVariable("ID"); if (File.Exists(NOAH_PROJECT)) { outDir = Path.Combine(Path.GetDirectoryName(NOAH_PROJECT), ".noah", "tasks", UUID, TASK_TICKET, "out"); ProjectInfo = JObject.Parse(File.ReadAllText(NOAH_PROJECT)); JArray generators = JArray.Parse(ProjectInfo["generators"].ToString()); FindJobjectFromJArray(generators, NOAH_GENERATOR, out Generator, out GeneratorIndex); } } catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, ex.Message); } int outIndex = 0; DA.GetData(1, ref outIndex); JArray output = JArray.Parse(Generator["output"].ToString()); if (outIndex >= output.Count) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "定义时未指定此输出端口"); } switch (m_mode) { case ExportMode.None: Message = null; break; case ExportMode.Rhino: string fileName = Convert.ToString(outIndex) + ".3dm"; string filePath = Path.Combine(outDir, fileName); File3dmWriter writer = new File3dmWriter(filePath); List <int> ll = new List <int>(); List <ObjectLayerInfo> layeredObj = new List <ObjectLayerInfo>(); DA.GetDataList(0, layeredObj); layeredObj.ForEach(x => { writer.ChildLayerSolution(x.Name); ll.Add(writer.CreateLayer(x.Name, x.Color)); }); if (layeredObj.Count > 0) { writer.Write(layeredObj, ll); if (!exported) { ProjectInfo["generators"][GeneratorIndex]["output"][outIndex]["value"] = filePath; File.WriteAllText(NOAH_PROJECT, JsonConvert.SerializeObject(ProjectInfo, Formatting.Indented)); exported = true; } } break; case ExportMode.Text: if (!exported) { string outputData = ""; DA.GetData(0, ref outputData); ProjectInfo["generators"][GeneratorIndex]["output"][outIndex]["value"] = outputData; File.WriteAllText(NOAH_PROJECT, JsonConvert.SerializeObject(ProjectInfo, Formatting.Indented)); exported = true; } break; case ExportMode.Data: fileName = Convert.ToString(outIndex) + ".noahdata"; filePath = Path.Combine(outDir, fileName); if (string.IsNullOrWhiteSpace(filePath)) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "未指定文件."); return; } GH_LooseChunk val = new GH_LooseChunk("Grasshopper Data"); val.SetGuid("OriginId", base.InstanceGuid); val.SetInt32("Count", base.Params.Input.Count); IGH_Param iGH_Param = base.Params.Input[0]; IGH_Structure volatileData = iGH_Param.VolatileData; GH_IWriter val2 = val.CreateChunk("Block", 0); val2.SetString("Name", iGH_Param.NickName); val2.SetBoolean("Empty", volatileData.IsEmpty); if (!volatileData.IsEmpty) { GH_Structure <IGH_Goo> tree = null; DA.GetDataTree(0, out tree); if (!tree.Write(val2.CreateChunk("Data"))) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"There was a problem writing the {iGH_Param.NickName} data."); } } byte[] bytes = val.Serialize_Binary(); try { File.WriteAllBytes(filePath, bytes); } catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, ex.Message); } if (!exported) { ProjectInfo["generators"][GeneratorIndex]["output"][outIndex]["value"] = filePath; File.WriteAllText(NOAH_PROJECT, JsonConvert.SerializeObject(ProjectInfo, Formatting.Indented)); exported = true; } break; case ExportMode.CSV: fileName = Convert.ToString(outIndex) + ".csv"; filePath = Path.Combine(outDir, fileName); List <object> oList = new List <object>(); List <string> sList = new List <string>(); DA.GetDataList(0, oList); oList.ForEach(el => { string tmp = ""; GH_Convert.ToString(el, out tmp, GH_Conversion.Both); sList.Add(tmp); }); File.WriteAllText(filePath, string.Join(Environment.NewLine, sList)); if (!exported) { ProjectInfo["generators"][GeneratorIndex]["output"][outIndex]["value"] = filePath; File.WriteAllText(NOAH_PROJECT, JsonConvert.SerializeObject(ProjectInfo, Formatting.Indented)); exported = true; } break; } }
protected override void SafeSolveInstance(IGH_DataAccess DA) { if (_py == null) { DA.SetData(0, "No Python engine available. This component needs Rhino v5"); return; } DA.DisableGapLogic(0); m_py_output.Reset(); var rhdoc = RhinoDoc.ActiveDoc; var prevEnabled = (rhdoc != null) && rhdoc.Views.RedrawEnabled; try { // set output variables to "None" for (int i = HideCodeOutput ? 0 : 1; i < Params.Output.Count; i++) { string varname = Params.Output[i].NickName; _py.SetVariable(varname, null); } // caching variable to keep things as fast as possible bool showing_code_input = CodeInputVisible; // Set all input variables. Even null variables may be used in the // script, so do not attempt to skip these for optimization purposes. // Skip "Code" input parameter // Please pay attention to the input data structure type for (int i = showing_code_input ? 1 : 0; i < Params.Input.Count; i++) { string varname = Params.Input[i].Name; // ksteinfe: changed from Params.Input[i].Nickname object o = _marshal.GetInput(DA, i); _py.SetVariable(varname, o); //_py.SetIntellisenseVariable(varname, o); // ksteinfe: i think this set the Intellisense thingos for all the input variables. we are converting, so Intellisense would just be confusing. } // the "code" string could be embedded in the component itself if (showing_code_input || _compiled_py == null) { string script; if (!showing_code_input) { script = CodeInput; } else { script = null; DA.GetData(0, ref script); } if (string.IsNullOrWhiteSpace(script)) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "No script to execute"); return; } // ksteinfe - i think we put our hack here. //_py.ExecuteScript(DcPython.Decodes.DecodesAppendedCode.header); //script = script + DcPython.Decodes.DecodesAppendedCode.footer; script = DcPython.Decodes.DecodesAppendedCode.header + script + DcPython.Decodes.DecodesAppendedCode.footer; if (_compiled_py == null || string.Compare(script, _previousRunCode, StringComparison.InvariantCulture) != 0) { if (!(_inDocStringsMode = DocStringUtils.FindApplyDocString(script, this))) { ResetAllDescriptions(); } _compiled_py = _py.Compile(script); _previousRunCode = script; } } if (_compiled_py != null) { _compiled_py.Execute(_py); // Python script completed, attempt to set all of the // output paramerers for (int i = HideCodeOutput ? 0 : 1; i < Params.Output.Count; i++) { string varname = Params.Output[i].NickName; object o = _py.GetVariable(varname); // ksteinfe: this is a tree coming in from gh python out. can we just scan the tree and grab the attributes to store somewhere, then bake each param? _marshal.SetOutput(o, DA, i); } } else { m_py_output.Write("There was a permanent error parsing this script. Please report to [email protected]."); } } catch (Exception ex) { AddErrorNicely(m_py_output, ex); SetFormErrorOrClearIt(DA, m_py_output); throw; } finally { if (rhdoc != null && prevEnabled != rhdoc.Views.RedrawEnabled) { rhdoc.Views.RedrawEnabled = true; } } SetFormErrorOrClearIt(DA, m_py_output); }
protected override void SolveInstance(IGH_DataAccess DA) { GeometryBase G = null; string L = "预设值"; List <Curve> H = new List <Curve>(); Color C = Color.Black; DA.GetData(0, ref G); DA.GetData(1, ref L); DA.GetDataList(2, H); DA.GetData(3, ref C); int NOAH_BAKE_INFO = 0; try { PythonScript script = PythonScript.Create(); script.ExecuteScript("import scriptcontext as sc\nV=sc.sticky['NOAH_BAKE_INFO']"); NOAH_BAKE_INFO = (int)script.GetVariable("V"); } catch { NOAH_BAKE_INFO = 0; } if (NOAH_BAKE_INFO == 1) { if (G != null && H.Count == 0) { //写入物件 ObjectAttributes att = getObjAttr(L, rhinoDoc, C); switch (G.ObjectType) { case ObjectType.Brep: rhinoDoc.Objects.AddBrep(G as Brep, att); break; case ObjectType.Curve: rhinoDoc.Objects.AddCurve(G as Curve, att); break; case ObjectType.Point: rhinoDoc.Objects.AddPoint((G as Rhino.Geometry.Point).Location, att); break; case ObjectType.Surface: rhinoDoc.Objects.AddSurface(G as Surface, att); break; case ObjectType.Mesh: rhinoDoc.Objects.AddMesh(G as Mesh, att); break; case ObjectType.PointSet: rhinoDoc.Objects.AddPointCloud(G as Rhino.Geometry.PointCloud, att); //This is a speculative entry break; default: AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "不能识别的物体: " + G.GetType().FullName); break; } } else if (G == null && H.Count > 0) { ObjectAttributes att = getObjAttr(L, rhinoDoc, C); Hatch[] hatches = Hatch.Create(H, 0, 0, 1, 0); foreach (Hatch hatch in hatches) { rhinoDoc.Objects.AddHatch(hatch, att); } } else { AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "G和H只能输入一个"); } } else { AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "等待写入"); } }
protected override void SafeSolveInstance(IGH_DataAccess da) { m_env.DataAccessManager = da; if (m_py == null) { da.SetData(0, "No Python engine available. This component needs Rhino v5"); return; } if (!HiddenOutOutput) { da.DisableGapLogic(0); } m_py_output.Reset(); var rhdoc = RhinoDoc.ActiveDoc; var prevEnabled = (rhdoc != null) && rhdoc.Views.RedrawEnabled; try { // set output variables to "None" for (int i = HiddenOutOutput ? 0 : 1; i < Params.Output.Count; i++) { string varname = Params.Output[i].NickName; m_py.SetVariable(varname, null); } // caching variable to keep things as fast as possible bool showing_code_input = !HiddenCodeInput; // Set all input variables. Even null variables may be used in the // script, so do not attempt to skip these for optimization purposes. // Skip "Code" input parameter // Please pay attention to the input data structure type for (int i = showing_code_input ? 1 : 0; i < Params.Input.Count; i++) { string varname = Params.Input[i].NickName; object o = m_marshal.GetInput(da, i); m_py.SetVariable(varname, o); m_py.SetIntellisenseVariable(varname, o); } // the "code" string could be embedded in the component itself if (showing_code_input || m_compiled_py == null) { string script; if (!showing_code_input) { script = Code; } else { script = null; da.GetData(0, ref script); } if (string.IsNullOrWhiteSpace(script)) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "No script to execute"); return; } if (m_compiled_py == null || string.Compare(script, m_previousRunCode, StringComparison.InvariantCulture) != 0) { if (!(m_inDocStringsMode = DocStringUtils.FindApplyDocString(script, this))) { ResetAllDescriptions(); } m_compiled_py = m_py.Compile(script); m_previousRunCode = script; } } if (m_compiled_py != null) { string localPath; bool added = AddLocalPath(out localPath); m_compiled_py.Execute(m_py); if (added) { RemoveLocalPath(localPath); } // Python script completed, attempt to set all of the // output paramerers for (int i = HiddenOutOutput ? 0 : 1; i < Params.Output.Count; i++) { string varname = Params.Output[i].NickName; object o = m_py.GetVariable(varname); m_marshal.SetOutput(o, da, i); } } else { m_py_output.Write("There was a permanent error parsing this script. Please report to [email protected]."); } } catch (Exception ex) { AddErrorNicely(m_py_output, ex); SetFormErrorOrClearIt(da, m_py_output); throw; } finally { if (rhdoc != null && prevEnabled != rhdoc.Views.RedrawEnabled) { rhdoc.Views.RedrawEnabled = true; } } SetFormErrorOrClearIt(da, m_py_output); }