diff --git a/.github/workflows/github_pages.yml b/.github/workflows/github_pages.yml index f883519..b60cf98 100644 --- a/.github/workflows/github_pages.yml +++ b/.github/workflows/github_pages.yml @@ -6,6 +6,8 @@ on: - main pull_request: +concurrency: preview-${{ github.ref }} + jobs: deploy: runs-on: ubuntu-20.04 @@ -28,3 +30,9 @@ jobs: with: github_token: ${{ secrets.GITHUB_TOKEN }} publish_dir: ./book/book + + - name: Deploy preview + uses: rossjrw/pr-preview-action@v1 + if: ${{ github.ref != 'refs/heads/main' }} + with: + source-dir: ./book/book \ No newline at end of file diff --git a/README.md b/README.md index 786e8c6..c548a26 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ def repeat_grid(geometry: Geometry, width: Int, height: Int): g = grid( size_x=width, size_y=height, vertices_x=width, vertices_y=height - ).mesh_to_points() + ).mesh.mesh_to_points() return g.instance_on_points(instance=geometry) ``` diff --git a/api/arrange.py b/api/arrange.py index da0a421..a71d336 100644 --- a/api/arrange.py +++ b/api/arrange.py @@ -1,34 +1,42 @@ import bpy import typing +from collections import deque, Counter def _arrange(node_tree, padding: typing.Tuple[float, float] = (50, 25)): # Organize the nodes into columns based on their links. columns: typing.List[typing.List[typing.Any]] = [] - def contains_link(node, column): - return any( - any( - any(link.from_node == node for link in input.links) - for input in n.inputs - ) - for n in column - ) - for node in reversed(node_tree.nodes): - if (x := next( - filter( - lambda x: contains_link(node, x[1]), - enumerate(columns) - ), - None - )) is not None: - if x[0] > 0: - columns[x[0] - 1].append(node) - else: - columns.insert(x[0], [node]) + + def topo_sort(graph): + in_degree = {u: 0 for u in graph} + for u in graph: + for v in graph[u]: + in_degree[v] += 1 + queue = deque([u for u in in_degree if in_degree[u] == 0]) + topo_order = [] + while queue: + u = queue.popleft() + topo_order.append(u) + for v in graph[u]: + in_degree[v] -= 1 + if in_degree[v] == 0: + queue.append(v) + return topo_order + + graph = { node:set() for node in node_tree.nodes } + node_input_link_count = Counter() + for link in node_tree.links: + graph[link.from_node].add(link.to_node) + node_input_link_count[link.to_socket] += 1 + sorted_nodes = topo_sort(graph) + + column_index = {} + for node in reversed(sorted_nodes): + column_index[node] = max([ column_index[adj_node] for adj_node in graph[node] ], default=-1) + 1 + if column_index[node] == len(columns): + columns.append([node]) else: - if len(columns) == 0: - columns.append([node]) - else: - columns[len(columns) - 1].append(node) + columns[column_index[node]].append(node) + columns = reversed(columns) # Arrange the columns, computing the size of the node manually so arrangement can be done without UI being visible. UI_SCALE = bpy.context.preferences.view.ui_scale @@ -46,7 +54,7 @@ def _arrange(node_tree, padding: typing.Tuple[float, float] = (50, 25)): output_count = len(list(filter(lambda i: i.enabled, node.outputs))) parent_props = [prop.identifier for base in type(node).__bases__ for prop in base.bl_rna.properties] properties_count = len([prop for prop in node.bl_rna.properties if prop.identifier not in parent_props]) - unset_vector_count = len(list(filter(lambda i: i.enabled and i.type == 'VECTOR' and len(i.links) == 0, node.inputs))) + unset_vector_count = len(list(filter(lambda i: i.enabled and i.type == 'VECTOR' and node_input_link_count[i] == 0, node.inputs))) node_height = ( NODE_HEADER_HEIGHT \ + (output_count * NODE_LINK_HEIGHT) \ diff --git a/api/node_mapper.py b/api/node_mapper.py index 876540b..0fd4dbd 100644 --- a/api/node_mapper.py +++ b/api/node_mapper.py @@ -1,11 +1,12 @@ import bpy -import bl_ui import itertools import enum import re +import os from .state import State from .types import * from .static.input_group import InputGroup +from .static.curve import Curve from ..absolute_path import absolute_path class OutputsList(dict): @@ -13,6 +14,21 @@ class OutputsList(dict): __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ +def set_or_create_link(x, node_input): + if issubclass(type(x), Type): + State.current_node_tree.links.new(x._socket, node_input) + else: + def link_constant(): + constant = Type(value=x) + State.current_node_tree.links.new(constant._socket, node_input) + if node_input.hide_value: + link_constant() + else: + try: + node_input.default_value = x + except: + link_constant() + def build_node(node_type): def build(_primary_arg=None, **kwargs): for k, v in kwargs.copy().items(): @@ -28,6 +44,13 @@ def build_node(node_type): argname = prop.identifier.lower().replace(' ', '_') if argname in kwargs: value = kwargs[argname] + if isinstance(value, list) and len(value) > 0 and isinstance(value[0], Curve): + for i, curve in enumerate(value): + curve.apply(getattr(node, prop.identifier).curves[i]) + continue + if isinstance(value, Curve): + value.apply(getattr(node, prop.identifier).curves[0]) + continue if isinstance(value, enum.Enum): value = value.value setattr(node, prop.identifier, value) @@ -40,20 +63,6 @@ def build_node(node_type): if node_input2.name.lower().replace(' ', '_') == argname and node_input2.type == node_input.type: all_with_name.append(node_input2) if argname in kwargs: - def set_or_create_link(x, node_input): - if issubclass(type(x), Type): - State.current_node_tree.links.new(x._socket, node_input) - else: - def link_constant(): - constant = Type(value=x) - State.current_node_tree.links.new(constant._socket, node_input) - if node_input.hide_value: - link_constant() - else: - try: - node_input.default_value = x - except: - link_constant() value = kwargs[argname] if isinstance(value, enum.Enum): value = value.value @@ -105,35 +114,18 @@ def register_node(node_type, category_path=None): enum_type = enum.Enum(enum_type_name, { map_case_name(i): i.identifier for i in prop.enum_items }) setattr(globals()[node_namespace_name], enum_type_name, enum_type) registered_nodes.add(node_type) -for category_name in list(filter(lambda x: x.startswith('NODE_MT_category_GEO_'), dir(bpy.types))): - category = getattr(bpy.types, category_name) - if not hasattr(category, 'category'): - category_path = category.bl_label.lower().replace(' ', '_') - add_node_type = bl_ui.node_add_menu.add_node_type - draw_node_group_add_menu = bl_ui.node_add_menu.draw_node_group_add_menu - draw_assets_for_catalog = bl_ui.node_add_menu.draw_assets_for_catalog - bl_ui.node_add_menu.add_node_type = lambda _layout, node_type_name: register_node(getattr(bpy.types, node_type_name), category_path) - bl_ui.node_add_menu.draw_node_group_add_menu = lambda _context, _layout: None - bl_ui.node_add_menu.draw_assets_for_catalog = lambda _context, _layout: None - class CategoryStub: - bl_label = "" - def __init__(self): - self.layout = Layout() - class Layout: - def separator(self): pass - category.draw(CategoryStub(), None) - bl_ui.node_add_menu.add_node_type = add_node_type - bl_ui.node_add_menu.draw_node_group_add_menu = draw_node_group_add_menu - bl_ui.node_add_menu.draw_assets_for_catalog = draw_assets_for_catalog - else: - category_path = category.category.name.lower().replace(' ', '_') - for node in category.category.items(None): - node_type = getattr(bpy.types, node.nodetype) - register_node(node_type, category_path) -for node_type_name in list(filter(lambda x: 'GeometryNode' in x, dir(bpy.types))): + +denylist = {'filter'} # some nodes should be excluded. +class_denylist = {'CompositorNodeMath', 'TextureNodeMath'} +node_types_to_register = [] +for node_type_name in dir(bpy.types): node_type = getattr(bpy.types, node_type_name) - if issubclass(node_type, bpy.types.GeometryNode): - register_node(node_type) + if isinstance(node_type, type) and issubclass(node_type, bpy.types.Node): + if node_type.is_registered_node_type() and node_type.bl_rna.name.lower() not in denylist and node_type.__name__ not in class_denylist: + node_types_to_register.append(node_type) +node_types_to_register.sort(key=lambda node_type: node_type.__name__.startswith("GeometryNode")) +for node_type in node_types_to_register: + register_node(node_type) def create_documentation(): temp_node_group = bpy.data.node_groups.new('temp_node_group', 'GeometryNodeTree') @@ -155,6 +147,7 @@ def create_documentation(): docstrings = [] symbols = [] enums = {} + skipped_nodes = [] for func in sorted(documentation.keys()): try: method = documentation[func] @@ -261,12 +254,8 @@ def create_documentation(): {output_symbol_separator.join(output_symbols)}""") return_type_hint = list(symbol_outputs.values())[0] if len(output_symbols) == 1 else f"{node_namespace_name}.Result" symbols.append(f"""def {func}({', '.join(symbol_args)}) -> {return_type_hint}: \"\"\"![]({image}.webp)\"\"\"""") - except Exception as e: - import os, sys - print(e) - exc_type, exc_obj, exc_tb = sys.exc_info() - fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] - print(exc_type, fname, exc_tb.tb_lineno) + except: + skipped_nodes.append(documentation[func].bl_node_type.__name__) continue bpy.data.node_groups.remove(temp_node_group) html = f""" @@ -362,6 +351,9 @@ class Type: fpyi.write(contents) fpy.write(contents) + if len(skipped_nodes) > 0: + pass # This could be reported later. + def create_docs(): create_documentation() -bpy.app.timers.register(create_docs) \ No newline at end of file +bpy.app.timers.register(create_docs) diff --git a/api/static/attribute.py b/api/static/attribute.py index 8038a5e..ad8bd5d 100644 --- a/api/static/attribute.py +++ b/api/static/attribute.py @@ -44,12 +44,19 @@ class Attribute: """ Creates a "Named Attribute" node with the correct arguments passed, and returns the "Attribute" socket. """ - from geometry_script import named_attribute - return named_attribute(data_type=self.data_type, name=self.name, *args, **kwargs).attribute + from geometry_script import named_attribute, Type + result = named_attribute(data_type=self.data_type, name=self.name, *args, **kwargs) + # Handle Blender 3.5+, which includes an `exists` result. + if isinstance(result, Type): + return result + else: + return result.attribute def exists(self, *args, **kwargs): """ Creates a "Named Attribute" node with the correct arguments passed, and returns the "Exists" socket. + + > Only available in Blender 3.5+ """ from geometry_script import named_attribute return named_attribute(data_type=self.data_type, name=self.name, *args, **kwargs).exists @@ -59,9 +66,10 @@ class Attribute: Creates a "Store Named Attribute" node with the correct arguments passed, and returns the modified `Geometry`. """ from geometry_script import store_named_attribute + if 'domain' not in kwargs: + kwargs['domain'] = self.domain return store_named_attribute( data_type=self.data_type, - domain=self.domain, geometry=geometry, name=self.name, value=value, diff --git a/api/static/curve.py b/api/static/curve.py new file mode 100644 index 0000000..e53a282 --- /dev/null +++ b/api/static/curve.py @@ -0,0 +1,54 @@ +from typing import List +import enum + +class HandleType(enum.Enum): + AUTO = 'AUTO' + VECTOR = 'VECTOR' + AUTO_CLAMPED = 'AUTO_CLAMPED' + +class Point: + """ + A single point on a curve + """ + + x: float + y: float + handle_type: HandleType + + def __init__(self, x: float, y: float, handle_type: HandleType = HandleType.AUTO): + self.x = x + self.y = y + self.handle_type = handle_type + +class Curve: + """ + A class that represents a curve. + + Create a curve from a set of `Point`s. + ```python + my_curve = Curve( + Point(0, 0, Handle.AUTO_CLAMPED), + Point(0.2, 0.3, Handle.AUTO), + Point(1, 1, Handle.VECTOR) + ) + ``` + """ + + points: List[Point] + + def __init__(self, *points: Point): + if len(points) == 1 and isinstance(points[0], list): + self.points = points[0] + else: + self.points = list(points) + + def apply(self, curve): + """ + Apply the points to a curve object. + """ + for i, point in enumerate(self.points): + if len(curve.points) > i: + curve.points[i].location = (point.x, point.y) + curve.points[i].handle_type = point.handle_type.value + else: + curve.points.new(point.x, point.y).handle_type = point.handle_type.value \ No newline at end of file diff --git a/api/static/repeat.py b/api/static/repeat.py new file mode 100644 index 0000000..df8f2bb --- /dev/null +++ b/api/static/repeat.py @@ -0,0 +1,51 @@ +import bpy +import inspect +import typing + +def repeat_zone(block: typing.Callable): + """ + Create a repeat input/output block. + + > Only available in Blender 4.0+. + """ + def wrapped(*args, **kwargs): + from geometry_script.api.node_mapper import OutputsList, set_or_create_link + from geometry_script.api.state import State + from geometry_script.api.types import Type, socket_class_to_data_type + + signature = inspect.signature(block) + + # setup zone + repeat_in = State.current_node_tree.nodes.new(bpy.types.GeometryNodeRepeatInput.__name__) + repeat_out = State.current_node_tree.nodes.new(bpy.types.GeometryNodeRepeatOutput.__name__) + repeat_in.pair_with_output(repeat_out) + + # clear state items + for item in repeat_out.repeat_items: + repeat_out.repeat_items.remove(item) + + # link the iteration count + set_or_create_link(args[0], repeat_in.inputs[0]) + + # create state items from block signature + repeat_items = {} + for param in signature.parameters.values(): + repeat_items[param.name] = (param.annotation, param.default, None, None) + for i, arg in enumerate(repeat_items.items()): + repeat_out.repeat_items.new(socket_class_to_data_type(arg[1][0].socket_type), arg[0].replace('_', ' ').title()) + # skip the first index, which is reserved for the iteration count + i = i + 1 + set_or_create_link(kwargs[arg[0]] if arg[0] in kwargs else args[i], repeat_in.inputs[i]) + + step = block(*[Type(o) for o in repeat_in.outputs[:-1]]) + + if isinstance(step, Type): + step = (step,) + for i, result in enumerate(step): + set_or_create_link(result, repeat_out.inputs[i]) + + if len(repeat_out.outputs[:-1]) == 1: + return Type(repeat_out.outputs[0]) + else: + return OutputsList({o.name.lower().replace(' ', '_'): Type(o) for o in repeat_out.outputs[:-1]}) + return wrapped \ No newline at end of file diff --git a/api/static/simulation.py b/api/static/simulation.py index 9805449..39926b6 100644 --- a/api/static/simulation.py +++ b/api/static/simulation.py @@ -1,25 +1,48 @@ +import bpy import inspect import typing -class SimulationInput: - class DeltaTime: pass - class ElapsedTime: pass - -def simulation(block: typing.Callable[typing.Any, 'Geometry']): +def simulation_zone(block: typing.Callable): """ Create a simulation input/output block. - > Only available in the `geometry-node-simulation` branch of Blender 3.5. + In Blender 4.0+, you must return a boolean value for the "Skip" argument as the first element in the return tuple. + + > Only available in Blender 3.6+. """ - def wrapped(geometry: 'Geometry', *args, **kwargs): - from geometry_script import simulation_input, simulation_output - simulation_in = simulation_input(geometry=geometry) + def wrapped(*args, **kwargs): + from geometry_script.api.node_mapper import OutputsList, set_or_create_link + from geometry_script.api.state import State + from geometry_script.api.types import Type, socket_class_to_data_type + signature = inspect.signature(block) - for key, value in signature.parameters.items(): - match value.annotation: - case SimulationInput.DeltaTime: - kwargs[key] = simulation_in.delta_time - case SimulationInput.ElapsedTime: - kwargs[key] = simulation_in.elapsed_time - return simulation_output(geometry=block(simulation_in.geometry, *args, **kwargs)).geometry + + # setup zone + simulation_in = State.current_node_tree.nodes.new(bpy.types.GeometryNodeSimulationInput.__name__) + simulation_out = State.current_node_tree.nodes.new(bpy.types.GeometryNodeSimulationOutput.__name__) + simulation_in.pair_with_output(simulation_out) + + # clear state items + for item in simulation_out.state_items: + simulation_out.state_items.remove(item) + + # create state items from block signature + state_items = {} + for param in [*signature.parameters.values()][1:]: + state_items[param.name] = (param.annotation, param.default, None, None) + for i, arg in enumerate(state_items.items()): + simulation_out.state_items.new(socket_class_to_data_type(arg[1][0].socket_type), arg[0].replace('_', ' ').title()) + set_or_create_link(kwargs[arg[0]] if arg[0] in kwargs else args[i], simulation_in.inputs[i]) + + step = block(*[Type(o) for o in simulation_in.outputs[:-1]]) + + if isinstance(step, Type): + step = (step,) + for i, result in enumerate(step): + set_or_create_link(result, simulation_out.inputs[i]) + + if len(simulation_out.outputs[:-1]) == 1: + return Type(simulation_out.outputs[0]) + else: + return OutputsList({o.name.lower().replace(' ', '_'): Type(o) for o in simulation_out.outputs[:-1]}) return wrapped \ No newline at end of file diff --git a/api/tree.py b/api/tree.py index a85e80d..d34dc81 100644 --- a/api/tree.py +++ b/api/tree.py @@ -8,12 +8,16 @@ from .state import State from .types import * from .node_mapper import * from .static.attribute import * +from .static.curve import * from .static.expression import * from .static.input_group import * +from .static.repeat import * from .static.sample_mode import * from .static.simulation import * from .arrange import _arrange +IS_BLENDER_4 = bpy.app.version[0] >= 4 + def _as_iterable(x): if isinstance(x, Type): return [x,] @@ -22,6 +26,17 @@ def _as_iterable(x): except TypeError: return [x,] +def get_node_inputs(x): + if IS_BLENDER_4: + return [i for i in x.interface.items_tree if i.item_type == 'SOCKET' and i.in_out == 'INPUT'] + else: + return x.inputs +def get_node_outputs(x): + if IS_BLENDER_4: + return [i for i in x.interface.items_tree if i.item_type == 'SOCKET' and i.in_out == 'OUTPUT'] + else: + return x.outputs + def tree(name): tree_name = name def build_tree(builder): @@ -33,13 +48,27 @@ def tree(name): node_group = bpy.data.node_groups[tree_name] else: node_group = bpy.data.node_groups.new(tree_name, 'GeometryNodeTree') + + if IS_BLENDER_4: + node_group.is_modifier = True + # Clear the node group before building for node in node_group.nodes: node_group.nodes.remove(node) - while len(node_group.inputs) > sum(map(lambda p: len(p.annotation.__annotations__) if issubclass(p.annotation, InputGroup) else 1, list(signature.parameters.values()))): - node_group.inputs.remove(node_group.inputs[-1]) - for group_output in node_group.outputs: - node_group.outputs.remove(group_output) + + node_inputs = get_node_inputs(node_group) + input_count = sum(map(lambda p: len(p.annotation.__annotations__) if issubclass(p.annotation, InputGroup) else 1, list(signature.parameters.values()))) + for node_input in node_inputs[input_count:]: + if IS_BLENDER_4: + node_group.interface.remove(node_input) + else: + node_group.inputs.remove(node_input) + + for group_output in get_node_outputs(node_group): + if IS_BLENDER_4: + node_group.interface.remove(group_output) + else: + node_group.outputs.remove(group_output) # Setup the group inputs group_input_node = node_group.nodes.new('NodeGroupInput') @@ -64,19 +93,28 @@ def tree(name): inputs[param.name] = (param.annotation, param.default, None, None) # Create the input sockets and collect input values. - for i, node_input in enumerate(node_group.inputs): + node_inputs = get_node_inputs(node_group) + for i, node_input in enumerate(node_inputs): if node_input.bl_socket_idname != list(inputs.values())[i][0].socket_type: - for ni in node_group.inputs: - node_group.inputs.remove(ni) + for ni in node_inputs: + if IS_BLENDER_4: + node_group.interface.remove(ni) + else: + node_group.inputs.remove(ni) break builder_inputs = {} + + node_inputs = get_node_inputs(node_group) for i, arg in enumerate(inputs.items()): input_name = arg[0].replace('_', ' ').title() - if len(node_group.inputs) > i: - node_group.inputs[i].name = input_name - node_input = node_group.inputs[i] + if len(node_inputs) > i: + node_inputs[i].name = input_name + node_input = node_inputs[i] else: - node_input = node_group.inputs.new(arg[1][0].socket_type, input_name) + if IS_BLENDER_4: + node_input = node_group.interface.new_socket(socket_type=arg[1][0].socket_type, name=input_name, in_out='INPUT') + else: + node_input = node_group.inputs.new(arg[1][0].socket_type, input_name) if arg[1][1] != inspect.Parameter.empty: node_input.default_value = arg[1][1] if arg[1][2] is not None: @@ -98,19 +136,36 @@ def tree(name): outputs = builder(**builder_inputs) # Create the output sockets - for i, result in enumerate(_as_iterable(outputs)): - if not issubclass(type(result), Type): - result = Type(value=result) - # raise Exception(f"Return value '{result}' is not a valid 'Type' subclass.") - node_group.outputs.new(result.socket_type, 'Result') - link = node_group.links.new(result._socket, group_output_node.inputs[i]) + if isinstance(outputs, dict): + # Use a dict to name each return value + for i, (k, v) in enumerate(outputs.items()): + if not issubclass(type(v), Type): + v = Type(value=v) + if IS_BLENDER_4: + node_group.interface.new_socket(socket_type=v.socket_type, name=k, in_out='OUTPUT') + else: + node_group.outputs.new(v.socket_type, k) + node_group.links.new(v._socket, group_output_node.inputs[i]) + else: + for i, result in enumerate(_as_iterable(outputs)): + if not issubclass(type(result), Type): + result = Type(value=result) + # raise Exception(f"Return value '{result}' is not a valid 'Type' subclass.") + if IS_BLENDER_4: + node_group.interface.new_socket(socket_type=result.socket_type, name='Result', in_out='OUTPUT') + else: + node_group.outputs.new(result.socket_type, 'Result') + node_group.links.new(result._socket, group_output_node.inputs[i]) _arrange(node_group) # Return a function that creates a NodeGroup node in the tree. # This lets @trees be used in other @trees via simple function calls. def group_reference(*args, **kwargs): - result = group(node_tree=node_group, *args, **kwargs) + if IS_BLENDER_4: + result = geometrynodegroup(node_tree=node_group, *args, **kwargs) + else: + result = group(node_tree=node_group, *args, **kwargs) group_outputs = [] for group_output in result._socket.node.outputs: group_outputs.append(Type(group_output)) diff --git a/api/types.py b/api/types.py index e1e9611..2b89168 100644 --- a/api/types.py +++ b/api/types.py @@ -20,6 +20,15 @@ def socket_type_to_data_type(socket_type): case _: return socket_type +def socket_class_to_data_type(socket_class_name): + match socket_class_name: + case 'NodeSocketGeometry': + return 'GEOMETRY' + case 'NodeSocketFloat': + return 'FLOAT' + case _: + return socket_class_name + # The base class all exposed socket types conform to. class _TypeMeta(type): def __getitem__(self, args): @@ -57,10 +66,15 @@ class Type(metaclass=_TypeMeta): self.socket_type = type(socket).__name__ def _math(self, other, operation, reverse=False): - if self._socket.type == 'VECTOR': - return geometry_script.vector_math(operation=operation, vector=(other, self) if reverse else (self, other)) + if other is None: + vector_or_value = self else: - return geometry_script.math(operation=operation, value=(other, self) if reverse else (self, other)) + vector_or_value = (other, self) if reverse else (self, other) + + if self._socket.type == 'VECTOR': + return geometry_script.vector_math(operation=operation, vector=vector_or_value) + else: + return geometry_script.math(operation=operation, value=vector_or_value) def __add__(self, other): return self._math(other, 'ADD') @@ -92,6 +106,36 @@ class Type(metaclass=_TypeMeta): def __rmod__(self, other): return self._math(other, 'MODULO', True) + def __floordiv__(self, other): + return self._math(other, 'DIVIDE')._math(None,'FLOOR') + + def __rfloordiv__(self, other): + return self._math(other, 'DIVIDE',True)._math(None,'FLOOR') + + def __pow__(self, other): + return self._math(other, 'POWER') + + def __rpow__(self, other): + return self._math(other, 'POWER', True) + + def __matmul__(self, other): + return self._math(other, 'DOT_PRODUCT') + + def __rmatmul__(self, other): + return self._math(other, 'DOT_PRODUCT', True) + + def __abs__(self): + return self._math(None,'ABSOLUTE') + + def __neg__(self): + return self._math(-1, 'MULTIPLY') + + def __pos__(self): + return self + + def __round__(self): + return self._math(None,'ROUND') + def _compare(self, other, operation): return geometry_script.compare(operation=operation, a=self, b=other) @@ -175,13 +219,15 @@ class Type(metaclass=_TypeMeta): def capture(self, value, **kwargs): data_type = socket_type_to_data_type(value._socket.type) - geometry, attribute = self.capture_attribute(data_type=data_type, value=value, **kwargs) - return geometry, attribute + res = self.capture_attribute(data_type=data_type, value=value, **kwargs) + return res.geometry, res.attribute def transfer(self, attribute, **kwargs): data_type = socket_type_to_data_type(attribute._socket.type) return self.transfer_attribute(data_type=data_type, attribute=attribute, **kwargs) def __getitem__(self, subscript): + if self._socket.type == 'VECTOR' and isinstance(subscript, int): + return self._get_xyz_component(subscript) if isinstance(subscript, tuple): accessor = subscript[0] args = subscript[1:] diff --git a/book/src/SUMMARY.md b/book/src/SUMMARY.md index 64be5ea..a01665e 100644 --- a/book/src/SUMMARY.md +++ b/book/src/SUMMARY.md @@ -21,8 +21,10 @@ - [Input Groups](./api/advanced-scripting/input-groups.md) - [Attributes](./api/advanced-scripting/attributes.md) - [Boolean Math](./api/advanced-scripting/boolean-math.md) + - [Curves](./api/advanced-scripting/curves.md) - [Drivers](./api/advanced-scripting/drivers.md) - - [Simulation](./api/advanced-scripting/simulation.md) + - [Simulation Zones](./api/advanced-scripting/simulation-zones.md) + - [Repeat Zones](./api/advanced-scripting/repeat-zones.md) # Tutorials diff --git a/book/src/api/advanced-scripting/curves.md b/book/src/api/advanced-scripting/curves.md new file mode 100644 index 0000000..3a007c3 --- /dev/null +++ b/book/src/api/advanced-scripting/curves.md @@ -0,0 +1,32 @@ +# Curves + +Some nodes, such as *Float Curve* take a curve as a property. You can create a curve with the `Curve` class. + +```python +float_curve( + mapping=Curve( + Point(0, 0), + Point(0.5, 0.25), + Point(1, 1, HandleType.VECTOR), # Optionally specify a handle type, such as `AUTO`, `VECTOR`, or `AUTO_CLAMPED`. + ) +) +``` + +![](./float_curve.png) + +You can also pass the points as a list to `Curve`. + +```python +points = [Point(0, 0), Point(1, 1)] +float_curve( + mapping=Curve(points) +) +``` + +If a node has multiple curve properties, such as the *Vector Curves* node, pass a list of curves to the node. + +```python +vector_curves( + mapping=[x_curve, y_curve, z_curve] +) +``` \ No newline at end of file diff --git a/book/src/api/advanced-scripting/float_curve.png b/book/src/api/advanced-scripting/float_curve.png new file mode 100644 index 0000000..53bb1c9 Binary files /dev/null and b/book/src/api/advanced-scripting/float_curve.png differ diff --git a/book/src/api/advanced-scripting/repeat-zones.md b/book/src/api/advanced-scripting/repeat-zones.md new file mode 100644 index 0000000..b52c5d1 --- /dev/null +++ b/book/src/api/advanced-scripting/repeat-zones.md @@ -0,0 +1,42 @@ +# Repeat Zones + +Blender 4.0 introduced repeat zones. + +Using a *Repeat Input* and *Repeat Output* node, you can loop a block of nodes for a specific number of iterations. + +You must use the `@repeat_zone` decorator to create these special linked nodes. + +```python +from geometry_script import * + +@tree +def test_loop(geometry: Geometry): + @repeat_zone + def doubler(value: Float): + return value * 2 + return points(count=doubler(5, 1)) # double the input value 5 times. +``` + +The function should modify the input values and return them in the same order. + +When calling the repeat zone, pass the *Iterations* argument first, then any other arguments the function accepts. + +For example: + +```python +def doubler(value: Float) -> Float +``` + +would be called as: + +```python +doubler(iteration_count, value) +``` + +When a repeat zone has multiple arguments, return a tuple from the zone. + +```python +@repeat_zone +def multi_doubler(value1: Float, value2: Float): + return (value1 * 2, value2 * 2) +``` \ No newline at end of file diff --git a/book/src/api/advanced-scripting/simulation-zones.md b/book/src/api/advanced-scripting/simulation-zones.md new file mode 100644 index 0000000..cd5a945 --- /dev/null +++ b/book/src/api/advanced-scripting/simulation-zones.md @@ -0,0 +1,38 @@ +# Simulation Zones + +Blender 3.6 includes simulation nodes. + +Using a *Simulation Input* and *Simulation Output* node, you can create effects that change over time. + +As a convenience, the `@simulation_zone` decorator is provided to make simulation node blocks easier to create. + +```python +from geometry_script import * + +@tree +def test_sim(geometry: Geometry): + @simulation_zone + def my_sim(delta_time, geometry: Geometry, value: Float): + return (geometry, value) + return my_sim(geometry, 0.26).value +``` + +The first argument should always be `delta_time`. Any other arguments must also be returned as a tuple with their modified values. +Each frame, the result from the previous frame is passed into the zone's inputs. +The initial call to `my_sim` in `test_sim` provides the initial values for the simulation. + +## Blender 4.0+ + +A "Skip" argument was added to the *Simulation Output* node in Blender 4.0. + +Return a boolean value first from any simulation zone to determine whether the step should be skipped. + +The simplest way to migrate existing node trees is by adding `False` to the return tuple. + +```python +@simulation_zone +def my_sim(delta_time, geometry: Geometry, value: Float): + return (False, geometry, value) +``` + +You can pass any boolean value as the skip output. \ No newline at end of file diff --git a/book/src/api/advanced-scripting/simulation.md b/book/src/api/advanced-scripting/simulation.md deleted file mode 100644 index d471439..0000000 --- a/book/src/api/advanced-scripting/simulation.md +++ /dev/null @@ -1,26 +0,0 @@ -# Simulation - -> This API is subject to change as future builds of Blender with simulation nodes are released. - -The `geometry-nodes-simulation` branch of Blender 3.5 includes support for "simulation nodes". - -Using a *Simulation Input* and *Simulation Output* node, you can create effects that change over time. - -As a convenience, the `@simulation` decorator is provided to make simulation node blocks easier to create. - -```python -@simulation -def move_over_time( - geometry: Geometry, # the first input must be `Geometry` - speed: Float, - dt: SimulationInput.DeltaTime, # Automatically passes the delta time on any argument annotated with `SimulationInput.DeltaTime`. - elapsed: SimulationInput.ElapsedTime, # Automatically passes the elapsed time -) -> Geometry: - return geometry.set_position( - offset=combine_xyz(x=speed) - ) -``` - -Every frame the argument `geometry` will be set to the geometry from the previous frame. This allows the offset to accumulate over time. - -The `SimulationInput.DeltaTime`/`SimulationInput.ElapsedTime` types mark arguments that should be given the outputs from the *Simulation Input* node. \ No newline at end of file diff --git a/book/src/api/basics/cube_tree_named_outputs.png b/book/src/api/basics/cube_tree_named_outputs.png new file mode 100644 index 0000000..a029c08 Binary files /dev/null and b/book/src/api/basics/cube_tree_named_outputs.png differ diff --git a/book/src/api/basics/tree-functions.md b/book/src/api/basics/tree-functions.md index c77ba00..888bcec 100644 --- a/book/src/api/basics/tree-functions.md +++ b/book/src/api/basics/tree-functions.md @@ -41,6 +41,19 @@ def cube_tree(): ![](./cube_tree_int.png) +By default, each output is named 'Result'. To customize the name, return a dictionary. + +```python +@tree("Cube Tree") +def cube_tree(): + return { + "My Cube": cube(), + "Scale Constant": 5 + } +``` + +![](./cube_tree_named_outputs.png) + ## Group Input All arguments in a tree function must be annotated with a valid socket type. These types are provided by Geometry Script, and are not equivalent to Python's built-in types. Let's add a size argument to our Cube Tree. diff --git a/examples/Repeat Grid.py b/examples/Repeat Grid.py index 1dd5e39..3d993f7 100644 --- a/examples/Repeat Grid.py +++ b/examples/Repeat Grid.py @@ -1,9 +1,26 @@ from geometry_script import * @tree("Repeat Grid") -def repeat_grid(geometry: Geometry, width: Int, height: Int): +def repeat_grid( + geometry: Geometry, + columns: Int, + rows: Int, + spacing_x: Float = 0.0, + spacing_y: Float = 0.0 +): + # measure your geometry’s bounds + bbox = geometry.bounding_box() + span_x = bbox.max.x - bbox.min.x + span_y = bbox.max.y - bbox.min.y + + # total grid size = N * object size + total_x = columns * span_x + (columns - 1) * spacing_x + total_y = rows * span_y + (rows - 1) * spacing_y + + # one extra vertex gives N cells g = grid( - size_x=width, size_y=height, - vertices_x=width, vertices_y=height - ).mesh_to_points() + size_x=total_x, size_y=total_y, + vertices_x=columns + 1, vertices_y=rows + 1 + ).mesh.mesh_to_points() + return g.instance_on_points(instance=geometry) \ No newline at end of file diff --git a/preferences.py b/preferences.py index 3773433..3c2219b 100644 --- a/preferences.py +++ b/preferences.py @@ -25,4 +25,4 @@ class GeometryScriptPreferences(bpy.types.AddonPreferences): vscode.label(text=f"2. Search for 'Preferences: Open Settings (UI)'") vscode.label(text=f"3. Search for 'Python > Analysis: Extra Paths") vscode.label(text=f"4. Click 'Add Item'") - vscode.label(text=f"5. Pase the typeshed path from above") \ No newline at end of file + vscode.label(text=f"5. Paste the typeshed path from above")