Skip to content

Instantly share code, notes, and snippets.

@camnewnham
Last active February 6, 2020 23:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save camnewnham/e3779b279e9d59e5510d69a30637dde4 to your computer and use it in GitHub Desktop.
Save camnewnham/e3779b279e9d59e5510d69a30637dde4 to your computer and use it in GitHub Desktop.
using Grasshopper.Kernel;
using System;
namespace MyTestComponent
{
public class TestComponent : GH_Component
{
public override Guid ComponentGuid => new Guid("{86A4E46A-520B-4C6B-8AD2-9939097778E5}");
public TestComponent() : base(
"Test ScheduleSolution",
"ScheduleSolution",
"Schedules document solutions at a given interval",
"Test",
"Test"
)
{ }
public override void AddedToDocument(GH_Document document)
{
timer = new System.Threading.Timer(OnTimerTick, null, timerTickDelay, timerTickDelay);
base.AddedToDocument(document);
}
System.Threading.Timer timer;
void OnTimerTick(object state)
{
timer.Change(timerTickDelay, timerTickDelay);
Recompute();
}
public override void RemovedFromDocument(GH_Document document)
{
timer.Dispose();
timer = null;
base.RemovedFromDocument(document);
}
protected override void RegisterInputParams(GH_InputParamManager pManager)
{
pManager.AddIntegerParameter("TimerTick", "T", "The time between timer ticks", GH_ParamAccess.item);
pManager.AddIntegerParameter("Delay", "D", "The delay between a timer tick and executing the scheduled solution", GH_ParamAccess.item);
}
protected override void RegisterOutputParams(GH_OutputParamManager pManager)
{
pManager.AddTextParameter("Updated", "U", "Attach a counter to see how often this component updates", GH_ParamAccess.item);
}
protected override void SolveInstance(IGH_DataAccess DA)
{
DA.GetData("TimerTick", ref timerTickDelay);
DA.GetData("Delay", ref callbackDelay);
UpdateMessage();
DA.SetData(0, "Updated");
}
int timerTickDelay = 100;
int callbackDelay = 20;
int delegateInvokedCount = 0;
int callbackRequestedCount = 0;
void UpdateMessage()
{
Message = $"{delegateInvokedCount}/{callbackRequestedCount}";
Grasshopper.Instances.ActiveCanvas.Invalidate();
}
/// <summary>
/// Requests the component to recompute and output a new solution.
/// If the component is locked or the document is not the current canvas document the component will be expired, but not immediately recomputed
/// </summary>
protected void Recompute()
{
if (!Locked)
{
if (this.Phase == GH_SolutionPhase.Blank) return;
if (OnPingDocument() is GH_Document doc && doc == Grasshopper.Instances.ActiveCanvas?.Document)
{
callbackRequestedCount++;
UpdateMessage();
Grasshopper.Instances.DocumentEditor.BeginInvoke((Action)(() =>
{
doc.ScheduleSolution(callbackDelay, (callback) =>
{
delegateInvokedCount++;
if (this.Phase != GH_SolutionPhase.Blank)
{
ExpireSolution(false);
}
UpdateMessage();
});
}));
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment