protected override void SolveInstance(IGH_DataAccess DA) { bool S = false; DA.GetData(0, ref S); PythonScript script = PythonScript.Create(); script.SetVariable("bakeornot", S ? 1 : 0); script.ExecuteScript("import scriptcontext as sc\nsc.sticky['NOAH_BAKE_INFO'] = bakeornot"); foreach (IGH_DocumentObject obj in ghDoc.Objects) { if (obj is GH_Cluster) { GH_Cluster objCluster = (GH_Cluster)obj; GH_Document clusterDoc = objCluster.Document(""); foreach (IGH_DocumentObject clusterObj in clusterDoc.Objects) { if (clusterObj.ComponentGuid == new Guid("79EF4718-2B5A-4BFF-AB97-76A036598DB9")) { clusterObj.ExpireSolution(true); } } obj.ExpireSolution(true); } else { if (obj.ComponentGuid == new Guid("79EF4718-2B5A-4BFF-AB97-76A036598DB9")) { obj.ExpireSolution(true); } } } }
protected override void Initialize() { base.Initialize(); if (Doc != null) { Doc.SolutionEnd += OnDocSolutionEnd; } m_py = PythonScript.Create(); if (m_py != null) { SetScriptTransientGlobals(); m_py.Output = m_py_output.Write; m_py.SetVariable("__name__", "__main__"); m_env = new PythonEnvironment(this, m_py); m_py.SetVariable(PARENT_ENVIRONMENT_NAME, m_env); m_py.SetIntellisenseVariable(PARENT_ENVIRONMENT_NAME, m_env); m_py.ContextId = 2; // 2 is Grasshopper m_env.LoadAssembly(typeof(GH_Component).Assembly); //add Grasshopper.dll reference m_env.LoadAssembly(typeof(ZuiPythonComponent).Assembly); //add GHPython.dll reference UnpackScriptResources(); m_env.AddGhPythonPackage(); } }
protected override void SolveInstance(IGH_DataAccess DA) { string str = ""; object obj = null; DA.GetData <string>(0, ref str); DA.GetData <object>(1, ref obj); PythonScript val = PythonScript.Create(); val.SetVariable("V", obj); val.ExecuteScript("import scriptcontext as sc\nsc.sticky['" + str + "'] = V"); }
protected override void Initialize() { base.Initialize(); if (Doc != null) { Doc.SolutionEnd += OnDocSolutionEnd; } // ksteinfe _py = PythonScript.Create(); if (_py != null) { SetScriptTransientGlobals(); _py.Output = m_py_output.Write; _py.SetVariable("__name__", "__main__"); _env = new PythonEnvironment(this, _py); _py.SetVariable(PARENT_ENVIRONMENT_NAME, _env); _py.SetIntellisenseVariable(PARENT_ENVIRONMENT_NAME, _env); _py.ContextId = 2; // 2 is Grasshopper } }
protected override void CollectVolatileData_Custom() { m_data.Clear(); string k = NickName; var script = PythonScript.Create(); script.ExecuteScript("import scriptcontext as sc\nif sc.sticky.has_key('" + k + "'):\t\t\t\tV = sc.sticky['" + k + "']\nelse : V = 0"); object value = script.GetVariable("V"); GH_Number castNumber = null; GH_String castString = null; if (GH_Convert.ToGHNumber(value, GH_Conversion.Both, ref castNumber)) { m_data.Append(new GH_ObjectWrapper(castNumber)); } else if (GH_Convert.ToGHString(value, GH_Conversion.Both, ref castString)) { m_data.Append(new GH_ObjectWrapper(castString)); } else { m_data.Append((IGH_Goo)value); } }
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; } }
// the main listener function protected void TcpServerWorkerListening(object sender, DoWorkEventArgs e) { //---listen at the specified IP and port no.--- const int portNo = 614; IPAddress serverIp = IPAddress.Parse("127.0.0.1"); if (_server == null) { _server = new TcpListener(serverIp, portNo); } try { _server.Start(); RhinoApp.WriteLine("VS Code Listener Started..."); } catch (Exception err) { RhinoApp.WriteLine(err.ToString()); } while (true) { // incoming client connected TcpClient client; try { client = _server.AcceptTcpClient(); } catch (Exception serverException) { return; } // get the incoming data through a network stream NetworkStream nwStream = client.GetStream(); byte[] buffer = new byte[client.ReceiveBufferSize]; // read incoming stream int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize); // convert the data received into a string StringBuilder msg = new StringBuilder(); // parse the buffer into msg foreach (var b in buffer) { if (b.Equals(00)) { break; } msg.Append(Convert.ToChar(b).ToString()); } // parse the received message into C# Object string msgString = msg.ToString(); msgString = Regex.Split(msgString, "}")[0] + "}"; MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(msgString)); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(msgObject)); msgObject msgObj; try { msgObj = ser.ReadObject(ms) as msgObject; } catch (Exception ex) { RhinoApp.WriteLine("Received invalid data, please try again."); return; } ms.Close(); // invoke the main task in the main thread Application.Current.Dispatcher.Invoke(() => { // create python script runner PythonScript myScript = PythonScript.Create(); // redirect output to _output field myScript.Output = PrintToVSCode; FeedbackSender feedbackSender = new FeedbackSender(nwStream); GotCodeFeekBack += feedbackSender.OnGotCodeFeedBack; // if flagged reset, then reset the script engine. if (msgObj.reset) { ResetScriptEngine.ResetEngine(); } // if it is not a temp folder, add the folder to python library path if (!msgObj.temp) { string pythonFilePath = Path.GetDirectoryName(msgObj.filename); string code = string.Format("import sys\nimport os\nif \"{0}\" not in sys.path: sys.path.append(\"{0}\")", pythonFilePath); try { myScript.ExecuteScript(code); } catch (Exception exception) { PrintToVSCode(exception.Message); } } // determines if run actual script if (msgObj.run) { uint sn = _idoc.BeginUndoRecord("VS Code execution"); var sn_start = RhinoObject.NextRuntimeSerialNumber; try { if (msgObj.minimize) { Utils.MinimizeVSCodeWindow(); } myScript.ExecuteFile(msgObj.filename); } catch (Exception ex) { // get the exception message var error = myScript.GetStackTraceFromException(ex); string message = ex.Message + "\n" + error; // send exception msg back to VS Code PrintToVSCode(message); } finally { CloseConnection(nwStream); _idoc.EndUndoRecord(sn); if (msgObj.minimize) { Utils.RestoreVSCodeWindow(); } // fix the rs.Prompt bug RhinoApp.SetCommandPrompt("Command"); // select created objects var sn_end = RhinoObject.NextRuntimeSerialNumber; if (sn_end > sn_start) { for (var i = sn_start; i < sn_end; i++) { var obj = _idoc.Objects.Find(i); if (null != obj) { obj.Select(true); } } } // enable the view _idoc.Views.RedrawEnabled = true; } } else { CloseConnection(nwStream); } }); } }
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, "等待写入"); } }
private PythonEnvironment CreateEnvironment() { var externalPy = PythonScript.Create(); return(new PythonEnvironment(null, externalPy)); }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object can be used to retrieve data from input parameters and /// to store data in output parameters.</param> protected override void SolveInstance(IGH_DataAccess DA) { bool test_bool = false; List <GH_ObjectWrapper> vals = new List <GH_ObjectWrapper>(); List <GH_ObjectWrapper> output = new List <GH_ObjectWrapper>(); GH_ObjectWrapper f = new GH_ObjectWrapper(); StringList m_py_output = new StringList(); // python output stream is piped to m_py_output Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_String> consoleOut = new Grasshopper.Kernel.Data.GH_Structure <Grasshopper.Kernel.Types.GH_String>(); GH_ObjectWrapper key_str = new GH_ObjectWrapper(); //if (!DA.GetData(0, ref key_str)) return; if (!DA.GetDataList(0, vals)) { return; } if (!DA.GetData(1, ref f)) { return; } var ret = key_str; Type t = ret.GetType(); ScriptEngine pyEngine = Python.CreateEngine(); //var outputStream = m_py_output.Write; var outputStream = new System.IO.MemoryStream(); var outputStreamWriter = new System.IO.StreamReader(outputStream); //pyEngine.Runtime.IO.SetOutput(outputStream, outputStreamWriter); //pyEngine.Runtime.IO.SetOutput(m_py_output.Write); //pyEngine. = m_py_output.Write; PythonScript _py = PythonScript.Create(); //_py.Output = m_py_output.Write; Rhino.RhinoApp.WriteLine("Testing, testong"); //var textWriter = new System.IO.TextWriter; //pyEngine.Runtime.IO.RedirectToConsole(); //Console.SetOut(TextWriter.Synchronized(textWriter)); //System.IO.Stream out_string = pyEngine.Runtime.IO.OutputStream; //pyEngine.Runtime.IO.RedirectToConsole(); //pyEngine.Runtime.IO.SetOutput //System.IO.TextWriter test = Console.Out; //Console.SetOut(test); //pyEngine. = this.m_py_output.Write; //_py = PythonScript.Create(); //pyEngine.Operations.Output = this.m_py_output.Write; for (int i = 0; i < vals.Count; i++) { //ret = vals[i]; Type the_type = vals[i].Value.GetType(); dynamic result = pyEngine.Operations.Invoke(f.Value, vals[i].Value); object return_object = (object)result; GH_ObjectWrapper temp = new GH_ObjectWrapper(return_object); var temp2 = temp.Value; output.Add(new GH_ObjectWrapper(return_object)); } //string out_str = return_object.GetType().ToString(); SpatialGraph gph = new SpatialGraph(); DA.SetData(0, test_bool); DA.SetDataList(1, output); //DA.SetData(2, return_object); //DA.SetData(3, out_str); }