Meta Grasshoppering - Cleaning up wires

Metaprogramming is when you create programs to manipulate or generate other programs. This idea may be applied to Grasshopper as well. Here I will demonstrate one example where metaprogramming (or metagrasshoppering) is useful. A common problem of visual programming is the spaghetti mess of tangled wires. This limits the comprehensibility of the overall definition. We will address this problem through a Python component that allows users to toggle the wire display of selected components. 

Example definition with default wire displays

Example definition with default wire displays

The above image shows the overall definition. The upper chunk is a representation of what a complex definition may look like, with multiple wires crossing each other especially at the main nodes. Note that this chunk doesn't actually do anything useful though. The bottom left corner is the interesting part. The Python component allows you to select components anywhere in the definition and change the wire type of their inputs (default/faint/hidden). The image below shows the result of hiding the input wires of all components in the upper chunk. We will look at the code inside the Python component in a second and as usual, the download link for the definition is at the bottom of the post. 

How the definition looks after we select the hidden view

How the definition looks after we select the hidden view

The code inside the Python component  is quite succinct and straightforward. We first get the active Grasshopper document (line 11) and then search for selected DocumentObjects (line 12). We then filter the selected DocumentObjects for GH_Component objects (line 16). Components do not draw the wires, Parameters do. Therefore we look for the Params attribute of the component and specifically the Inputs (I think only the Input parameters are responsible for displaying wires). Finally, we set the WireDisplay according to the selected choice (line 18).

from Grasshopper.Kernel import GH_ParamWireDisplay
from Grasshopper.Kernel import GH_RuntimeMessageLevel 

# A dictionary of wire types 
wire_display = {'0':GH_ParamWireDisplay.default, 
                '1':GH_ParamWireDisplay.faint,
                '2':GH_ParamWireDisplay.hidden}

# Get selected components and change the wire display
if on:
    doc = ghenv.Component.OnPingDocument()
    sel_objs = doc.SelectedObjects()
    if not len(sel_objs):
        ghenv.Component.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, 'Nothing was selected')
    for sel_obj  in sel_objs:
        if not hasattr(sel_obj, 'Params'): continue
        for p in sel_obj.Params.Input:
            p.WireDisplay = wire_display[wire_type]

Here is the link to the definition. I hope to show some more example of 'metagrashoppering' soon.

 

/