0
$\begingroup$

Help please. I want to add geometry nodes using Python.

I assume/guess the steps are

  1. Create a primitive

    bpy.ops.mesh.primitive_plane_add()
    
  2. Add a new geometry node

    bpy.ops.node.new_geometry_nodes_modifier()
    
  3. Add the node I want

    from_node = bpy.ops.node.add_node(use_transform=True, type="GeometryNodeCurveArc")
    
  4. Connect the new node to the output

    to_node = nodes["Group Output"]
    
    
    links.new(from_node.outputs["Curve"], to_node.inputs["Geometry"])
    
  5. Start using the node

Needless to say, this does not work. What, please, is the correct code?

RuntimeError: Operator bpy.ops.node.add_node.poll() failed, context is incorrect
$\endgroup$
2
  • $\begingroup$ Do it without context operations (bpy.ops. [...]). See this q. $\endgroup$
    – Leander
    Commented Apr 22 at 11:54
  • $\begingroup$ @Leander Please will you tell me what I should use instead of: bpy.ops.node.new_geometry_nodes_modifier() I just don't get it. I have tried. $\endgroup$ Commented Apr 22 at 13:20

1 Answer 1

1
$\begingroup$

Use the bmesh module to create a plane primitive. Output the bmesh into a new mesh data block, then create a new object with that mesh.

import bpy
import bmesh

me = bpy.data.meshes.new("mesh name")
ob = bpy.data.objects.new("object name", me)
bpy.context.scene.collection.objects.link(ob)

bm = bmesh.new()
bmesh.ops.create_grid(bm, x_segments=1, y_segments=1, size=1)
bm.to_mesh(me)

Add a new modifier and create the nodes in the node group. Check out this answer about group interface.

mod = ob.modifiers.new("Geo Node Modifier", type='NODES')
node_group = bpy.data.node_groups.new("group name", type='GeometryNodeTree')
node_group.interface.new_socket(name="Geo In", in_out ="INPUT", socket_type="NodeSocketGeometry")
node_group.interface.new_socket(name="Geo Out", in_out ="OUTPUT", socket_type="NodeSocketGeometry")

node_in        = node_group.nodes.new("NodeGroupInput")
node_transform = node_group.nodes.new("GeometryNodeTransform")
node_out       = node_group.nodes.new("NodeGroupOutput")

node_group.links.new(node_in.outputs[0], node_transform.inputs[0])
node_group.links.new(node_transform.outputs[0], node_out.inputs[0])

node_transform.inputs["Translation"].default_value[2] = 1

mod.node_group = node_group
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .