Noah4ever / NodeRunner

Blender Add-on for importing and exporting Shader Nodes with a text
MIT License
2 stars 0 forks source link

Maybe create map for type and function in serialize_attr #23

Closed Noah4ever closed 1 month ago

Noah4ever commented 1 month ago

implemented:


def serialize_attr(node, attr):
    """ Serialize attribute of a node

    Check the type of the attribute and serialize it accordingly.
    If the attribute is a complex type, call the corresponding serialization function.
    Prints an error message if the serialization fails.

    Args:
      node: Node to serialize
      attr: Attribute to serialize
    Returns:
      Serialized attribute data
    """
    serializers = {
        mathutils.Color: serialize_color,
        mathutils.Vector: serialize_vector,
        mathutils.Euler: serialize_euler,
        bpy.types.ColorRamp: lambda d: serialize_color_ramp(node),
        bpy.types.ShaderNodeTree: lambda d: serialize_node_tree(node.node_tree),
        bpy.types.ColorMapping: lambda d: serialize_color_mapping(node),
        bpy.types.TexMapping: lambda d: serialize_texture_mapping(node),
        bpy.types.CurveMapping: lambda d: serialize_curve_mapping(node),
        bpy.types.CurveMap: lambda d: serialize_curve_map(node, d),
        bpy.types.CurveMapPoint: lambda d: serialize_curve_map_point(node, d),
        bpy.types.Image: serialize_image,
        bpy.types.ImageUser: lambda d: {},
        bpy.types.NodeSocketStandard:
            lambda d:
                serialize_attr(node, d.default_value) if hasattr(d, "default_value") else None,
        bpy.types.bpy_prop_collection:
            lambda d: [serialize_attr(node, element) for element in d.values()],
        bpy.types.bpy_prop_array: lambda d: [serialize_attr(node, element) for element in d],
    }

    for data_type, serializer in serializers.items():
        if isinstance(attr, data_type):
            return serializer(attr)
    try:
        pickle.dumps(attr)  # Try to pickle dump to get error message
    except (pickle.PicklingError, TypeError, AttributeError, EOFError):
        print(
            "[ERROR] Serializing error on:",
            node.name,
            "with data:",
            attr,
            "and type:",
            type(attr),
        )
    return attr