Write component that either takes Brep or Mesh as input

Dear Forum,

I am currently developing a component in C# where one of the input variables can be either a brep or a mesh. How would I go about writing this?

I figured I register the input parameter as such

pManager.AddGeometryParameter("Base Surface", "S", "", GH_ParamAccess.item);

but from there on I have no clue. I thought I would continue like this

var iBaseSrf = null;
if (!DA.GetData(1, ref iBaseSrf)) return;

But I can not assign null to a variable like this.

It would be great if someone could help me out here.


Can’t take credit for this, but this is what I would try.

"Certainly! In Grasshopper for Rhino, you can use the IGH_GeometricGoo interface when you’re uncertain about the exact type of geometry you’ll be receiving. The key is to use this interface to temporarily hold the data, and then, based on its type, cast it to the desired type (in your case, either a Brep or Mesh).

Here’s a suggested approach for handling either a Brep or Mesh input:

// First, register your input parameter.
pManager.AddGeometryParameter("Base Surface", "S", "Input either a Brep or Mesh", GH_ParamAccess.item);

// ... Other code ...

public override void SolveInstance(IGH_DataAccess DA)
    // Create a variable to temporarily hold the data.
    IGH_GeometricGoo geomInput = null;
    if (!DA.GetData(0, ref geomInput)) return; // Assuming this is the first input, so index is 0.

    // Now, check and cast the geometry.
    if (geomInput is GH_Brep) // Check if it's a Brep.
        Brep brepInput = ((GH_Brep)geomInput).Value;
        // Now you have your Brep and can process it.
    else if (geomInput is GH_Mesh) // Check if it's a Mesh.
        Mesh meshInput = ((GH_Mesh)geomInput).Value;
        // Now you have your Mesh and can process it.
        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The input must be either a Brep or Mesh.");

    // Continue with the rest of your code...

Here’s a breakdown:

  1. The input is initially fetched as IGH_GeometricGoo, which is a common interface for most geometric data in Grasshopper.
  2. After fetching, you check if the received data can be cast to either a GH_Brep or a GH_Mesh.
  3. Once you know the type, you can retrieve the actual Brep or Mesh value from the wrapper type (GH_Brep or GH_Mesh) and then continue your processing.

This approach ensures that only a Brep or Mesh will be processed. If the user connects a different type of geometry, the component will display an error."

works like a charm, thank you @TuomasLehtonen!

1 Like