Пример #1
0
        private void StoreOutput()
        {
            DebugEvent("Start Store Output");
            GH_DocumentServer doc_server = Instances.DocumentServer;

            if (doc_server == null)
            {
                throw new Exception("No Document Server exist!");
            }

            GH_Document doc = doc_server.ToList().Find(x => x.Properties.ProjectFileName == ID.ToString());

            if (doc == null)
            {
                throw new Exception("Tasker 未找到GH_Document");
            }

            if (string.IsNullOrEmpty(workspace) || string.IsNullOrEmpty(ticket))
            {
                throw new Exception("工作目录和Ticket为空");
            }

            string outDir = Path.Combine(taskspace, ID.ToString(), ticket);

            var hooks = doc.ClusterOutputHooks();

            if (hooks == null)
            {
                return;
            }

            foreach (var hook in hooks)
            {
                string info = hook.CustomDescription;
                if (string.IsNullOrEmpty(info))
                {
                    continue;
                }
                var paraMap = ConvertUrlParam(info);

                if (!paraMap.TryGetValue("Index", out string index) ||
                    !paraMap.TryGetValue("Type", out string type))
                {
                    continue;
                }

                DebugEvent($"Index: {index}; Type: {type}");

                string fileName = Path.Combine(outDir, index + "@" + DateTime.Now.ToString("HH-mm-ss MM-dd"));

                var volatileData = hook.VolatileData;

                if (volatileData.IsEmpty)
                {
                    continue;
                }

                dynamic content = null;

                switch (type)
                {
                case "CSV":
                {
                    var           allData = volatileData.AllData(true);
                    List <string> sList   = new List <string>();
                    allData.ToList().ForEach(el =>
                        {
                            GH_Convert.ToString(el, out string tmp, GH_Conversion.Both);
                            sList.Add(tmp);
                        });

                    string csv = string.Join(Environment.NewLine, sList);

                    fileName += ".csv";
                    File.WriteAllText(fileName, csv, Encoding.UTF8);
                    content = fileName;
                    break;
                }

                case "3DM":
                {
                    fileName += ".3dm";

                    File3dmWriter writer = new File3dmWriter(fileName);

                    foreach (var data in volatileData.AllData(true))
                    {
                        GeometryBase obj = GH_Convert.ToGeometryBase(data);

                        if (obj == null)
                        {
                            continue;
                        }

                        string layer = obj.GetUserString("Layer");
                        if (layer == null)
                        {
                            continue;
                        }
                        ObjectAttributes att = new ObjectAttributes
                        {
                            LayerIndex = writer.GetLayer(layer, Color.Black)
                        };

                        writer.ObjectMap.Add(att, obj);
                    }

                    writer.Write();
                    content = fileName;
                    break;
                }

                case "Data":
                {
                    try
                    {
                        GH_Structure <IGH_Goo> tree = volatileData as GH_Structure <IGH_Goo>;

                        content = IO.SerializeGrasshopperData(tree, hook.CustomName, volatileData.IsEmpty);
                    }
                    catch (Exception ex)
                    {
                        ErrorEvent(this, ex.Message);
                    }

                    break;
                }

                case "EPS":
                {
                    List <GeometryBase> objs = new List <GeometryBase>();

                    foreach (var data in volatileData.AllData(true))
                    {
                        if (data == null)
                        {
                            continue;
                        }
                        GeometryBase obj = GH_Convert.ToGeometryBase(data);
                        if (obj == null)
                        {
                            continue;
                        }

                        objs.Add(obj);
                    }

                    if (!Directory.Exists(fileName))
                    {
                        Directory.CreateDirectory(fileName);
                    }

                    content = JsonConvert.SerializeObject(SaveAdobeDocument(fileName, objs, AdobeDocType.EPS));
                    break;
                }

                case "PDF":
                {
                    List <GeometryBase> objs = new List <GeometryBase>();

                    fileName += ".pdf";

                    foreach (var data in volatileData.AllData(true))
                    {
                        if (data == null)
                        {
                            continue;
                        }
                        GeometryBase obj = GH_Convert.ToGeometryBase(data);
                        if (obj == null)
                        {
                            continue;
                        }

                        objs.Add(obj);
                    }

                    var res = SaveAdobeDocument(fileName, objs, AdobeDocType.PDF);
                    if (res == null || res.Count == 0)
                    {
                        break;
                    }
                    content = res[0];
                    break;
                }

                case "RhinoPDF":
                {
                    var pdf = FilePdf.Create();

                    fileName += ".pdf";

                    DebugEvent("RhinoPDF Begin");

                    foreach (var page in volatileData.AllData(true))
                    {
                        DebugEvent("RhinoPDF got 1 page");
                        if (!page.CastTo(out RhinoPageView view))
                        {
                            DebugEvent(string.Format("{0} can not convert to RhinoPageView", page.GetType()));
                            continue;
                        }

                        DebugEvent("Data is converted to RhinoPage");

                        ViewCaptureSettings settings = new ViewCaptureSettings(view, 300)
                        {
                            OutputColor = ViewCaptureSettings.ColorMode.DisplayColor,
                            RasterMode  = true
                        };

                        pdf.AddPage(settings);
                    }

                    pdf.Write(fileName);
                    content = fileName;
                    break;
                }

                case "DXF":
                {
                    break;
                }

                default:
                    break;
                }

                StoreEvent(this, new JObject
                {
                    ["route"]   = "task-stored",
                    ["id"]      = ID.ToString(),
                    ["index"]   = index.ToString(),
                    ["type"]    = type,
                    ["content"] = content
                }.ToString());
            }
        }
Пример #2
0
        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;
            }
        }