Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created Serializer for the document #4

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 9 additions & 21 deletions GHPT/Components/GHPT.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using GHPT.Prompts;
using GHPT.Serialization;
using GHPT.Utils;
using Grasshopper.Kernel;
using Grasshopper.Kernel.Special;
Expand Down Expand Up @@ -38,8 +38,7 @@ public GHPT()
private void OnReady(object sender, EventArgs e)
{
this._spinning = false;
this.AddComponents();
this.ConnectComponents();
this.MoveComponents();
Grasshopper.Instances.RedrawCanvas();
Rhino.RhinoDoc.ActiveDoc.Views.Redraw();

Expand Down Expand Up @@ -111,23 +110,24 @@ protected async override void SolveInstance(IGH_DataAccess DA)
{
this.RunSpinner();
});

_data = await PromptUtils.AskQuestion(prompt);
var serializer = new Serializer(_doc);
serializer.Deserialize(_data);

Ready?.Invoke(this, new EventArgs());
}

public event EventHandler Ready;

public void AddComponents()
public void MoveComponents()
{

if (!string.IsNullOrEmpty(_data.Advice))
this.CreateAdvicePanel(_data.Advice);

if (_data.Additions is null)
return;



// Compute tiers
Dictionary<int, List<Addition>> buckets = new();

Expand All @@ -152,26 +152,14 @@ public void AddComponents()

foreach (Addition addition in buckets[tier])
{
GraphUtil.InstantiateComponent(_doc, addition, new System.Drawing.PointF(x, y));
// Move components
// GraphUtil.InstantiateComponent(_doc, addition, new System.Drawing.PointF(x, y));
y += yIncrement;
}
}


}

private void ConnectComponents()
{
if (_data.Connections is null)
return;

foreach (ConnectionPairing connection in _data.Connections)
{
GraphUtil.ConnectComponent(_doc, connection);
}
}


protected override void AfterSolveInstance()
{
base.AfterSolveInstance();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System.Collections.Generic;
using System.Linq;

namespace GHPT.Prompts
namespace GHPT.Serialization
{

public struct PromptData
Expand All @@ -12,7 +12,7 @@ public struct PromptData

public void ComputeTiers()
{
List<Addition> additions = this.Additions.ToList();
List<Addition> additions = Additions.ToList();
if (additions == null)
return;

Expand All @@ -24,7 +24,7 @@ public void ComputeTiers()

additions[i] = addition;
}
this.Additions = additions;
Additions = additions;
}

public int FindParentsRecursive(Addition child, int depth = 0)
Expand Down
223 changes: 178 additions & 45 deletions GHPT/Utils/GraphUtil.cs → GHPT/Serialization/Serializer.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using FuzzySharp;
using FuzzySharp.Extractor;
using GHPT.Prompts;
using Grasshopper;
using Grasshopper.Kernel;
using Grasshopper.Kernel.Parameters;
Expand All @@ -9,21 +8,148 @@
using System.Collections.Generic;
using System.Linq;

namespace GHPT.Utils
namespace GHPT.Serialization
{
public static class GraphUtil
public sealed class Serializer
{

private static readonly Dictionary<string, string> fuzzyPairs = new()
private readonly Dictionary<int, IGH_DocumentObject> createdComponents;
private Dictionary<IGH_DocumentObject, int> documentObjects;
private readonly GH_Document doc;

public Serializer(GH_Document ghDocument)
{
{ "Extrusion", "Extrude" },
{ "Text Panel", "Panel" }
createdComponents = new();
documentObjects = new();
doc = ghDocument;
}

// Serialization

public PromptData Serialize()
{
var actives = doc.ActiveObjects();
var docObjs = doc.Objects.Where(o => !o.Obsolete && o.Name != "GHPT").ToArray();

documentObjects = GetSerializableComponents(docObjs);

PromptData data = new()
{
Additions = documentObjects.Select(kvp => DocumentObjectToAddition(kvp.Key, kvp.Value)),
Connections = DocumentObjectToConnection(),
Advice = GetAdvice()
};

return data;
}

private string GetAdvice()
{
GH_Panel panel = doc.Objects.OfType<GH_Panel>().FirstOrDefault(p => p.UserText == "Advice");
return panel.UserText;
}

private IEnumerable<ConnectionPairing> DocumentObjectToConnection()
{
List<ConnectionPairing> pairings = new();

foreach (var docObj in documentObjects.Keys)
{
if (docObj is IGH_Param param)
{
pairings.AddRange(GetConnections(param));
}
else if (docObj is IGH_Component component)
{
foreach (IGH_Param compParam in component.Params)
{
pairings.AddRange(GetConnections(compParam));
}
}
}

return pairings;
}

private IEnumerable<ConnectionPairing> GetConnections(IGH_Param param)
{
foreach (var source in param.Sources)
{
yield return GetConnection(param, source);
}
}

private ConnectionPairing GetConnection(IGH_Param from, IGH_Param to) => new()
{
From = new() { Id = GetId(from), ParameterName = from.Name },
To = new() { Id = GetId(to), ParameterName = to.Name }
};

private int GetId(IGH_DocumentObject docObj)
=> documentObjects.FirstOrDefault(_do => _do.Key == docObj).Value;

private static bool ToSerialize(IGH_DocumentObject docObj)
{
var ass = docObj.GetType().Assembly;

if (docObj is IGH_Param param)
{
bool noSources = param.SourceCount == 0;
return noSources;
}
else if (docObj is IGH_Component component)
{
if (component.Name == "GHPT")
return false;

foreach (IGH_Param cParam in component.Params)
{
if (cParam.SourceCount > 0)
{
return true;
}
}
}

return false;
}

private static Dictionary<IGH_DocumentObject, int> GetSerializableComponents(IEnumerable<IGH_DocumentObject> docObjs)
{
Dictionary<IGH_DocumentObject, int> _objects = new(docObjs.Count());
int i = 0;
foreach (var docObj in docObjs)
{
if (!ToSerialize(docObj))
continue;
i++;
_objects.Add(docObj, i);
}

return _objects;
}

private static Addition DocumentObjectToAddition(IGH_DocumentObject docObj, int i) => new()
{
Id = i,
Name = docObj.Name
};

private static readonly Dictionary<int, IGH_DocumentObject> CreatedComponents = new();
// DeSerialization
public void Deserialize(PromptData data)
{
foreach (Addition addition in data.Additions)
{
CreateComponent(addition);
}

foreach (ConnectionPairing pairing in data.Connections)
{
ConnectComponent(pairing);
}
}

public static void InstantiateComponent(GH_Document doc, Addition addition, System.Drawing.PointF pivot)
private void CreateComponent(Addition addition)
{
try
{
Expand All @@ -34,27 +160,61 @@ public static void InstantiateComponent(GH_Document doc, Addition addition, Syst

Guid myId = myProxy.Guid;

if (CreatedComponents.ContainsKey(addition.Id))
if (createdComponents.ContainsKey(addition.Id))
{
CreatedComponents.Remove(addition.Id);
createdComponents.Remove(addition.Id);
}

var emit = Instances.ComponentServer.EmitObject(myId);
CreatedComponents.Add(addition.Id, emit);
createdComponents.Add(addition.Id, emit);

doc.AddObject(emit, false);
emit.Attributes.Pivot = pivot;
SetValue(addition, emit);
}
catch
{
}
}

public static void ConnectComponent(GH_Document doc, ConnectionPairing pairing)
private static readonly Dictionary<string, string> fuzzyPairs = new()
{
{ "Extrusion", "Extrude" },
{ "Text Panel", "Panel" }
};

private static IGH_ObjectProxy GetObject(string name)
{
IGH_ObjectProxy[] results = Array.Empty<IGH_ObjectProxy>();
double[] resultWeights = new double[] { 0 };
Instances.ComponentServer.FindObjects(new string[] { name }, 10, ref results, ref resultWeights);

var myProxies = results.Where(ghpo => ghpo.Kind == GH_ObjectType.CompiledObject);

var _components = myProxies.OfType<IGH_Component>();
var _params = myProxies.OfType<IGH_Param>();

// Prefer Components to Params
var myProxy = myProxies.First();
if (_components is not null)
myProxy = _components.FirstOrDefault() as IGH_ObjectProxy;
else if (myProxy is not null)
myProxy = _params.FirstOrDefault() as IGH_ObjectProxy;

// Sort weird names
if (fuzzyPairs.ContainsKey(name))
{
name = fuzzyPairs[name];
}

myProxy = Instances.ComponentServer.FindObjectByName(name, true, true);

return myProxy;
}

public void ConnectComponent(ConnectionPairing pairing)
{
CreatedComponents.TryGetValue(pairing.From.Id, out IGH_DocumentObject componentFrom);
CreatedComponents.TryGetValue(pairing.To.Id, out IGH_DocumentObject componentTo);
createdComponents.TryGetValue(pairing.From.Id, out IGH_DocumentObject componentFrom);
createdComponents.TryGetValue(pairing.To.Id, out IGH_DocumentObject componentTo);

IGH_Param fromParam = GetParam(componentFrom, pairing.From, false);
IGH_Param toParam = GetParam(componentTo, pairing.To, true);
Expand All @@ -69,7 +229,7 @@ public static void ConnectComponent(GH_Document doc, ConnectionPairing pairing)
toParam.ComputeData();
}

private static IGH_Param GetParam(IGH_DocumentObject docObj, Connection connection, bool isInput)
private IGH_Param GetParam(IGH_DocumentObject docObj, Connection connection, bool isInput)
{
var resultParam = docObj switch
{
Expand Down Expand Up @@ -110,35 +270,6 @@ private static IGH_Param GetComponentParam(IGH_Component component, Connection c
return null;
}

private static IGH_ObjectProxy GetObject(string name)
{
IGH_ObjectProxy[] results = Array.Empty<IGH_ObjectProxy>();
double[] resultWeights = new double[] { 0 };
Instances.ComponentServer.FindObjects(new string[] { name }, 10, ref results, ref resultWeights);

var myProxies = results.Where(ghpo => ghpo.Kind == GH_ObjectType.CompiledObject);

var _components = myProxies.OfType<IGH_Component>();
var _params = myProxies.OfType<IGH_Param>();

// Prefer Components to Params
var myProxy = myProxies.First();
if (_components is not null)
myProxy = _components.FirstOrDefault() as IGH_ObjectProxy;
else if (myProxy is not null)
myProxy = _params.FirstOrDefault() as IGH_ObjectProxy;

// Sort weird names
if (fuzzyPairs.ContainsKey(name))
{
name = fuzzyPairs[name];
}

myProxy = Instances.ComponentServer.FindObjectByName(name, true, true);

return myProxy;
}

private static void SetValue(Addition addition, IGH_DocumentObject ghProxy)
{
string lowerCaseName = addition.Name.ToLowerInvariant();
Expand Down Expand Up @@ -194,4 +325,6 @@ private static bool SetNumberSliderData(Addition addition, GH_NumberSlider slide
}

}


}
1 change: 1 addition & 0 deletions GHPT/Utils/PromptUtils.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using GHPT.Prompts;
using GHPT.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
Expand Down
2 changes: 1 addition & 1 deletion tests/QuestionTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using GHPT.Prompts;
using GHPT.Serialization;
using GHPT.Utils;
using NUnit.Framework;
using System.Collections;
Expand Down
Loading