### Complete Blender Addon Setup Workflow Source: https://github.com/blender/blender-addons/blob/main/_autodocs/configuration.md This comprehensive example demonstrates the full setup for a Blender addon, including defining and registering custom properties, setting up addon preferences, and implementing registration and unregistration functions. ```python import bpy from bpy.types import AddonPreferences, PropertyGroup, Scene from bpy.props import BoolProperty, IntProperty, StringProperty # 1. Define properties class MyProperties(PropertyGroup): enabled: BoolProperty(name="Enabled", default=True) value: IntProperty(name="Value", default=0, min=0, max=100) # 2. Register properties Scene.my_properties = bpy.props.PointerProperty(type=MyProperties) # 3. Define preferences class MyPreferences(AddonPreferences): bl_idname = __name__ debug_mode: BoolProperty(name="Debug Mode", default=False) def draw(self, context): layout = self.layout layout.prop(self, "debug_mode") # 4. Register/unregister def register(): bpy.utils.register_class(MyProperties) bpy.utils.register_class(MyPreferences) Scene.my_properties = bpy.props.PointerProperty(type=MyProperties) def unregister(): bpy.utils.unregister_class(MyPreferences) bpy.utils.unregister_class(MyProperties) del Scene.my_properties # 5. Access in code scene = bpy.context.scene prefs = bpy.context.preferences.addons[__name__].preferences enabled = scene.my_properties.enabled debug = prefs.debug_mode ``` -------------------------------- ### Preset Menu Population Example Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/sapling-tree-gen.md Illustrates how the PresetMenu is automatically populated with .py preset files from specified directories. ```python # Menu automatically populated with all .py preset files found in: # - add_curve_sapling/presets/ # - {user_config}/presets/operator/add_curve_sapling/ ``` -------------------------------- ### AnimAll Workflow Example Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/animall.md Demonstrates a typical workflow for using AnimAll to animate vertex locations and bevel weights in Blender. This example configures AnimAll properties, sets keyframes at different frames, and shows how interpolation works. ```python import bpy # Configure AnimAll for vertex location animation scene = bpy.context.scene props = scene.animall_properties # Animate vertex locations and bevel weights props.key_point_location = True props.key_vertex_bevel = True props.key_selected = False # Animate all vertices # Select object and set current frame obj = bpy.context.active_objectpy.context.scene.frame_set(1) # Insert keyframes bpy.ops.animall.key_insert_button() # Move to frame 100 and modify geometrypy.context.scene.frame_set(100) # ... edit vertex positions or bevel weights in Edit mode ... # Insert another keyframe bpy.ops.animall.key_insert_button() # Now the object will interpolate between the two keyframe states ``` -------------------------------- ### Example Usage of Miscellaneous Operations Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/amaranth-toolset.md Demonstrates how to use the toggle_wire and color_management utilities from the amaranth.misc module. ```python from amaranth.misc import toggle_wire, color_management # Toggle wireframe display toggle_wire() # Access color management color_management() ``` -------------------------------- ### Documentation Navigation Flow Source: https://github.com/blender/blender-addons/blob/main/_autodocs/INDEX.md Follow this sequence to understand the add-ons documentation, starting from the main README and progressing to specific API references. ```markdown README.md (Start here!) ↓ REFERENCE-GUIDE.md (Overview & patterns) ├→ types.md (Type definitions) ├→ configuration.md (Setup patterns) ├→ errors.md (Error handling) └→ api-reference/*.md (Specific add-ons) ├→ amaranth-toolset.md ├→ sapling-tree-gen.md ├→ curve-tools.md ├→ add-mesh-extra-objects.md ├→ animall.md └→ gltf2-exporter.md ``` -------------------------------- ### Define Addon Preferences with Properties Source: https://github.com/blender/blender-addons/blob/main/_autodocs/REFERENCE-GUIDE.md Example of creating addon preferences by inheriting from 'AddonPreferences' and defining properties like 'BoolProperty'. ```python class MyAddonPrefs(AddonPreferences): bl_idname = __name__ debug_mode: BoolProperty(default=False) def draw(self, context): layout = self.layout layout.prop(self, "debug_mode") ``` -------------------------------- ### Curve Editing Workflow with Curve Tools Source: https://github.com/blender/blender-addons/blob/main/_autodocs/REFERENCE-GUIDE.md Example of selecting curve objects, configuring scene properties for Curve Tools, and running an operation to get curve length. ```python # 1. Select curve objects # 2. Configure in scene.curvetools properties scene.curvetools.SplineJoinDistance = 0.005 scene.curvetools.IntersectCurvesMode = 'Split' # 3. Run operation bpy.ops.curvetools.operatorcurveinfo() length = scene.curvetools.CurveLength ``` -------------------------------- ### Animall Property Path Examples Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/animall.md Examples of Animall's property path syntax for accessing and animating various object properties like vertex coordinates, bevel weights, edge creases, material indices, and custom attributes. ```plaintext # Vertex location vertices[0].co[0] # X component of vertex 0 vertices[0].co # Full XYZ vector of vertex 0 # Vertex bevel weight vertices[0].bevel_weight # Edge crease edges[0].crease # Face material index polygons[0].material_index # Attribute data attributes["my_attr"].data[0].value attributes["color"].data[0].color ``` -------------------------------- ### Example Addon Using Blender ID Authentication Source: https://github.com/blender/blender-addons/blob/main/blender_id/README.md A simple Blender addon demonstrating how to access the active Blender ID profile and display the logged-in username in its preferences panel. Ensure the Blender ID addon is installed and enabled. ```python # Extend this with your info bl_info = { 'name': 'Demo addon using Blender ID', 'location': 'Add-on preferences', 'category': 'System', 'support': 'TESTING', } import bpy class DemoPreferences(bpy.types.AddonPreferences): bl_idname = __name__ def draw(self, context): import blender_id profile = blender_id.get_active_profile() if profile: self.layout.label('You are logged in as %s' % profile.username) else: self.layout.label('You are not logged in on Blender ID') def register(): bpy.utils.register_module(__name__) def unregister(): bpy.utils.unregister_module(__name__) if __name__ == '__main__': register() ``` -------------------------------- ### Panel Organization in Blender Addons Source: https://github.com/blender/blender-addons/blob/main/_autodocs/REFERENCE-GUIDE.md Illustrates how to organize panels by function using class inheritance. This is a conceptual example. ```python # Panels grouped by function class AntLandscapeAddPanel(Panel): ... # Create class AntLandscapeToolsPanel(Panel): ... # Tools class AntMainSettingsPanel(Panel): ... # Settings class AntNoiseSettingsPanel(Panel): ... # Noise options ``` -------------------------------- ### Import Tree Preset Example Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/sapling-tree-gen.md Demonstrates importing a tree preset file using the ImportData operator. The filename property specifies which preset to load. ```python # Import a presetpy.ops.sapling.importdata(filename='big_oak.py') ``` -------------------------------- ### Get Preset Paths Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/sapling-tree-gen.md Retrieves both the built-in and user-defined preset paths. It creates the user preset directory if it does not already exist. ```python def getPresetpaths() -> tuple: ... ``` -------------------------------- ### ExportTree Preset Example Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/sapling-tree-gen.md Shows how to export the current tree configuration as a preset file using the ExportData operator. The data string includes the preset dictionary, filename, and overwrite flag. ```python # Export current tree configuration as preset data_str = "(preset_dict, 'my_tree', False)"py.ops.sapling.exportdata(data=data_str) ``` -------------------------------- ### Blender UI Layout Construction Source: https://github.com/blender/blender-addons/blob/main/_autodocs/types.md Example of using the Blender UI layout system to create columns, rows, and add properties, operators, and separators. ```python layout = panel.layout col = layout.column(align=True) row = col.row(align=True) row.prop(obj, "property_name") row.operator("operator.idname") row.separator() ``` -------------------------------- ### Workflow Example: Generating and Exporting a Tree Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/sapling-tree-gen.md Demonstrates the Python API workflow for importing a tree preset, generating a tree with specific settings, and preparing for export. This sequence can be adapted for procedural tree creation within Blender. ```python import bpy from add_curve_sapling import AddTree, ImportData, ExportData # Step 1: Import a built-in presetpy.ops.sapling.importdata(filename='small_tree.py') # Step 2: Create tree with imported settingspy.ops.curve.tree_add( showLeaves=True, bevel=True, useArm=False ) # Step 3: Customize via properties panel then export # Export settings for later use # (In practice, this happens through the UI operator) ``` -------------------------------- ### Get User Preset Directory Path Source: https://github.com/blender/blender-addons/blob/main/_autodocs/configuration.md Constructs the path to the user-specific preset directory for an addon within Blender's script path. Ensures the directory exists, creating it if necessary. ```python import os import bpy def get_addon_preset_path(): """Get user preset directory for addon""" user_presets = os.path.join( bpy.utils.script_path_user(), 'presets', 'operator', 'addon_name' ) os.makedirs(user_presets, exist_ok=True) return user_presets ``` -------------------------------- ### Configure Curve Tools Settings Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/curve-tools.md Example of how to access and configure settings for curve intersection and spline joining operations within the Curve Tools addon. ```python import bpy # Get the scene and curve tools settings scene = bpy.context.scene tools = scene.curvetools # Configure for curve intersection operations tools.IntersectCurvesAlgorithm = '3D' tools.IntersectCurvesMode = 'Split' tools.IntersectCurvesAffect = 'Both' # Set spline joining parameters tools.SplineJoinDistance = 0.002 tools.SplineJoinMode = 'Insert_segment' # Select curves and run operator # bpy.ops.curvetools.operatorcurveinfo() # Get curve length # length = tools.CurveLength ``` -------------------------------- ### Define Property Update Callback Source: https://github.com/blender/blender-addons/blob/main/_autodocs/configuration.md Implement a function to be called when a property changes. This example shows how to refresh the UI and log the change. ```python from bpy.props import BoolProperty def on_property_changed(self, context): """Called whenever property changes""" # Refresh UI for area in context.screen.areas: area.tag_redraw() # Log change print(f"Property changed to: {self.my_prop}") class MySettings(PropertyGroup): my_prop: BoolProperty( name="Setting", update=on_property_changed ) ``` -------------------------------- ### Define Dynamic Enum Items Source: https://github.com/blender/blender-addons/blob/main/_autodocs/configuration.md Populate an EnumProperty dynamically by providing a function that returns the items. This example lists all objects in the scene. ```python def get_items(scene, context): items = [] for obj in bpy.data.objects: items.append((obj.name, obj.name, "")) return items if items else [('NONE', 'No Objects', '')] prop = EnumProperty(items=get_items) ``` -------------------------------- ### Blender Addon Documentation Features Source: https://github.com/blender/blender-addons/blob/main/_autodocs/INDEX.md Highlights the key features of the documentation, such as direct source code extraction, complete API coverage, and real code examples. ```markdown ✓ **Extracted directly from source code** - All signatures, parameters, and types verified ✓ **Complete API surface** - Exported functions, classes, and operators ✓ **Real code examples** - Usage patterns from actual implementations ✓ **Type system reference** - Full property type documentation ✓ **Error handling patterns** - 30+ common failure modes with solutions ✓ **Configuration guide** - Registration, preferences, presets, paths ✓ **Workflow examples** - Real-world usage scenarios ✓ **Cross-referenced** - Links between related concepts ``` -------------------------------- ### Get Built-in Preset Path Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/sapling-tree-gen.md Retrieves the path to the directory containing the addon's built-in presets. This function is part of the preset system. ```python def getPresetpath() -> str: ... ``` -------------------------------- ### Get Built-in Preset Directory Path Source: https://github.com/blender/blender-addons/blob/main/_autodocs/configuration.md Determines the path to the built-in presets located within the addon's directory. This is useful for loading presets distributed with the addon itself. ```python import os import bpy def get_builtin_preset_path(): """Get built-in presets in addon directory""" addon_dir = os.path.dirname(__file__) return os.path.join(addon_dir, 'presets') ``` -------------------------------- ### Check Draco Compression Availability Source: https://github.com/blender/blender-addons/blob/main/_autodocs/errors.md Checks if the Draco compression library is available. Used for graceful fallback when the library is not installed. ```python def is_draco_available(): """Check if Draco compression is available""" try: from .io.com import gltf2_io_draco_compression_extension return gltf2_io_draco_compression_extension.dll_exists() except ImportError: return False ``` -------------------------------- ### Using os.path.join for Cross-Platform File Paths Source: https://github.com/blender/blender-addons/blob/main/_autodocs/REFERENCE-GUIDE.md Illustrates the correct method for constructing file paths in a cross-platform compatible way using os.path.join and bpy.utils.script_path_user. ```python import os path = os.path.join( bpy.utils.script_path_user(), 'presets', 'operator' ) ``` -------------------------------- ### Create a Minimal Test Case for Addons Source: https://github.com/blender/blender-addons/blob/main/_autodocs/REFERENCE-GUIDE.md Write a script to set up a minimal test scene, execute your addon's operator, and assert the expected results and side effects. This is crucial for verifying addon functionality. ```python import bpy # Create test scene scene = bpy.context.scene # Test addon function result = bpy.ops.addon.test_operator() # Verify result assert result == {'FINISHED'}, f"Failed: {result}" # Check side effects assert len(bpy.data.objects) > 0, "No objects created" ``` -------------------------------- ### Mesh Animation Workflow with AnimAll Source: https://github.com/blender/blender-addons/blob/main/_autodocs/REFERENCE-GUIDE.md Demonstrates selecting a mesh, configuring keyframe options, setting a frame, and inserting keyframes using the AnimAll addon. ```python # 1. Select mesh object # 2. Configure keyframe options scene.animall_properties.key_point_location = True scene.animall_properties.key_vertex_bevel = True # 3. Set frame and insert keyframes context.scene.frame_set(1) bpy.ops.animall.key_insert_button() # 4. Move, modify geometry, insert more keyframes context.scene.frame_set(100) # ... modify mesh ... bpy.ops.animall.key_insert_button() ``` -------------------------------- ### Get glTF Exporter Version String Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/gltf2-exporter.md Retrieves the current version string of the glTF exporter. The format is 'major.minor.patch'. ```python def get_version_string() -> str: ``` -------------------------------- ### Create a Preset File Source: https://github.com/blender/blender-addons/blob/main/_autodocs/configuration.md Create a Python file within the preset directory to define specific values for operator properties. This allows users to save and load configurations. ```python # preset_name.py import bpy op = bpy.context.window_manager.operators[-1] op.my_int = 10 op.my_string = "value" ``` -------------------------------- ### Tree Generation Workflow with Sapling Tree Gen Source: https://github.com/blender/blender-addons/blob/main/_autodocs/REFERENCE-GUIDE.md Shows how to load a preset, add a tree with specific settings, and export preset data using the Sapling Tree Gen addon. ```python # 1. Load preset bpy.ops.sapling.importdata(filename='big_tree.py') # 2. Add tree with loaded settings bpy.ops.curve.tree_add( showLeaves=True, useArm=True, bevel=True ) # 3. Export preset # (Via UI operator with serialized data) ``` -------------------------------- ### Add Tree with Default and Custom Settings Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/sapling-tree-gen.md Demonstrates how to add a tree using the AddTree operator, first with default settings and then with a range of customized parameters. ```python import bpy # Add a tree with default settingspy.ops.curve.tree_add() # Add a customized treepy.ops.curve.tree_add( bevel=True, prune=True, showLeaves=True, useArm=True, seed=42 ) ``` -------------------------------- ### All Documented Addons Quick Reference Source: https://github.com/blender/blender-addons/blob/main/_autodocs/INDEX.md Provides a quick reference table for all documented addons, including their version, minimum Blender version, category, and documentation status. ```markdown | Addon | Version | Min Blender | Category | Documented | |-------|---------|------------|----------|-----------| | Amaranth Toolset | 1.0.20 | 3.2.0 | Interface | ✓ | | Sapling Tree Gen | 0.3.5 | 2.80 | Add Curve | ✓ | | Curve Tools | 0.4.6 | 2.80 | Add Curve | ✓ | | Add Mesh Extra Objects | 0.3.11 | 2.80 | Add Mesh | ✓ | | AnimAll | 0.10.1 | 4.0.0 | Animation | ✓ | | glTF 2.0 Exporter | 4.2.23 | 4.2.0 | Import-Export | ✓ | ``` -------------------------------- ### Render Module Operations Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/amaranth-toolset.md Shows how to visualize camera borders and configure render sample settings using the Amaranth Render module. ```python from amaranth.render import border_camera, samples_scene # Visualize camera borders border_camera() # Configure sample settings samples_scene() ``` -------------------------------- ### Create a Custom Panel Source: https://github.com/blender/blender-addons/blob/main/_autodocs/README.md Demonstrates how to define a UI panel in Blender, specifying its space type, region type, and draw method for UI elements. ```python class MyPanel(Panel): bl_space_type = 'VIEW_3D' bl_region_type = 'UI' def draw(self, context): layout = self.layout # UI elements here ``` -------------------------------- ### Define Property Group for Settings Source: https://github.com/blender/blender-addons/blob/main/_autodocs/README.md Shows how to create a custom PropertyGroup to hold addon settings and attach it to the scene. ```python class MySettings(PropertyGroup): my_prop: IntProperty(default=0) Scene.my_settings = PointerProperty(type=MySettings) ``` -------------------------------- ### Get or Create Custom Attribute Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/animall.md Retrieves an existing custom attribute on geometry data or creates a new one if it doesn't exist. Supports various data types and domains. ```python def get_attribute(data, name: str, type: str = None, domain: str = None): pass ``` -------------------------------- ### Get glTF Export Format Items Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/gltf2-exporter.md This function returns the available format options for glTF export. It is used to determine which export formats (GLB, GLTF_SEPARATE, GLTF_EMBEDDED) are selectable by the user. ```python def get_format_items(scene, context) -> tuple: ``` -------------------------------- ### getPresetpaths() Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/sapling-tree-gen.md Retrieves the file paths for both built-in and user-created presets. It also ensures the user preset directory exists. ```APIDOC ## getPresetpaths() ### Description Retrieves the file paths for both built-in and user-created presets. The user preset directory is created if it does not exist. ### Method Python Function ### Endpoint N/A ### Parameters None ### Returns - **tuple**: A tuple containing two strings: (local_preset_path, user_preset_path). - `local_preset_path`: Path to built-in presets. - `user_preset_path`: Path to user-created presets. ``` -------------------------------- ### Using Blender API and OS Functions for Cross-Platform Paths Source: https://github.com/blender/blender-addons/blob/main/_autodocs/errors.md Avoid hardcoded paths by using `os.path.join` for constructing paths and `bpy.utils.script_path_user` or `os.path.expanduser` for cross-platform compatibility. This ensures your add-on works correctly on different operating systems. ```python import os # WRONG - Hardcoded paths preset_dir = '/home/user/.config/blender/3.0/presets' # CORRECT - Use Blender API preset_dir = os.path.join( bpy.utils.script_path_user(), 'presets', 'operator', 'addon_name' ) # CORRECT - Handle home directory preset_dir = os.path.expanduser('~/.config/blender/3.0/presets') ``` -------------------------------- ### Basic bl_info Structure for Addon Registration Source: https://github.com/blender/blender-addons/blob/main/_autodocs/configuration.md Defines the metadata for a Blender add-on, including its name, author, version, and compatibility with Blender versions. This structure is required for registering any add-on. ```python bl_info = { "name": "Addon Display Name", "author": "Author Name", "version": (1, 0, 0), "blender": (3, 0, 0), "location": "View3D > Add > Mesh", "description": "Short description", "warning": "Optional warning message", "doc_url": "{BLENDER_MANUAL_URL}/addons/category/addon_name.html", "tracker_url": "https://projects.blender.org/tracker/", "category": "Category Name", "support": "OFFICIAL" # or COMMUNITY, TESTING } ``` -------------------------------- ### Correct Operator Return Values Source: https://github.com/blender/blender-addons/blob/main/_autodocs/REFERENCE-GUIDE.md Demonstrates the proper way to handle operator execution, including returning {'FINISHED'} on success and {'CANCELLED'} with error reporting on failure. ```python def execute(self, context): try: do_something() return {'FINISHED'} except Exception as e: self.report({'ERROR'}, str(e)) return {'CANCELLED'} ``` -------------------------------- ### Import Translation Utilities with bpy.app.translations Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/animall.md Shows how to import `pgettext_iface` and `pgettext_data` from `bpy.app.translations` for supporting multiple languages in the addon's UI and data strings. ```python from bpy.app.translations import ( pgettext_iface as iface_, pgettext_data as data_ ) ``` -------------------------------- ### getPresetpath() Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/sapling-tree-gen.md Retrieves the file path to the directory containing the addon's built-in presets. ```APIDOC ## getPresetpath() ### Description Retrieves the file path to the directory containing the addon's built-in presets. ### Method Python Function ### Endpoint N/A ### Parameters None ### Returns - **str**: The absolute path to the built-in presets directory. ``` -------------------------------- ### PresetMenu Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/sapling-tree-gen.md Dynamically generates a preset menu by scanning preset directories. This menu allows users to select from various pre-defined tree presets. ```APIDOC ## Class PresetMenu ### Description Dynamically generates preset menu by scanning preset directories. Builds menu with all available presets from built-in and user directories. Each menu item calls `ImportData` operator. ### Methods #### `draw(context)` Builds menu with all available presets from built-in and user directories. Each menu item calls `ImportData` operator. ### Example ```python # Menu automatically populated with all .py preset files found in: # - add_curve_sapling/presets/ # - {user_config}/presets/operator/add_curve_sapling/ ``` ``` -------------------------------- ### Define an EnumProperty Source: https://github.com/blender/blender-addons/blob/main/_autodocs/types.md Use EnumProperty to create a selection list for users. Define the available items with their values, labels, and descriptions. A callback function can be specified to execute when the selection changes. ```python from bpy.props import EnumProperty items = ( ('VALUE1', 'Label 1', 'Description 1'), ('VALUE2', 'Label 2', 'Description 2'), ('VALUE3', 'Label 3', 'Description 3'), ) prop = EnumProperty( name="Selection", description="Tooltip", items=items, default='VALUE1', update=callback_function ) ``` -------------------------------- ### Global Dictionary for Tree Generation Settings Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/sapling-tree-gen.md A global dictionary that stores all parameters for tree generation. This dictionary is populated either from default values or by importing preset files. ```python settings = { # ... (parameters will be loaded here) } ``` -------------------------------- ### Initialize Amaranth Package Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/amaranth-toolset.md Imports the main amaranth package, which automatically registers all submodules when Blender loads the addon. ```python import amaranth # All submodules are registered automatically when Blender loads the addon ``` -------------------------------- ### Correct Blender Layout Hierarchy Source: https://github.com/blender/blender-addons/blob/main/_autodocs/errors.md Demonstrates the correct way to build UI layouts in Blender, ensuring proper hierarchy for elements like columns, rows, operators, and labels. ```python def draw(self, context): layout = self.layout # WRONG - Creating layout outside column row = layout.row() col = row.column() col.operator("op.name") row.label(text="Label") # Wrong context # CORRECT - Proper hierarchy col = layout.column(align=True) row = col.row() row.operator("op.name") row.label(text="Label") ``` -------------------------------- ### Define Addon Preferences Source: https://github.com/blender/blender-addons/blob/main/_autodocs/configuration.md Create a class inheriting from bpy.types.AddonPreferences to define custom settings for your addon. Use bpy.props to declare properties like booleans and strings with names, descriptions, and default values. The bl_idname must match the addon's module name. The draw method is used to lay out these properties in the addon's preferences panel. ```python from bpy.types import AddonPreferences from bpy.props import BoolProperty, StringProperty class MyAddonPreferences(AddonPreferences): bl_idname = __name__ # Must match addon module name allow_embedded_format: BoolProperty( name="Allow Embedded Format", description="Enable glTF embedded format export", default=False ) preset_directory: StringProperty( name="Preset Directory", description="Path to preset files", subtype='DIR_PATH' ) def draw(self, context): layout = self.layout layout.prop(self, "allow_embedded_format") layout.prop(self, "preset_directory") # Register preferences def register(): bpy.utils.register_class(MyAddonPreferences) def unregister(): bpy.utils.unregister_class(MyAddonPreferences) ``` -------------------------------- ### Blender Add-on File Structure Source: https://github.com/blender/blender-addons/blob/main/_autodocs/README.md This snippet outlines the typical directory structure for a Blender add-on project. It helps in understanding the organization of documentation, source code, and API references. ```text output/ ├── README.md # This file ├── REFERENCE-GUIDE.md # Navigation and overview ├── types.md # Type definitions ├── configuration.md # Config and setup ├── errors.md # Error handling └── api-reference/ ├── amaranth-toolset.md ├── sapling-tree-gen.md ├── curve-tools.md ├── add-mesh-extra-objects.md ├── animall.md └── gltf2-exporter.md ``` -------------------------------- ### Access Addon Preferences Source: https://github.com/blender/blender-addons/blob/main/_autodocs/configuration.md Retrieve addon preferences from bpy.context.preferences.addons. Access specific properties using dot notation. ```python prefs = bpy.context.preferences.addons[addon_name].preferences value = prefs.allow_embedded_format ``` -------------------------------- ### Import Symmetry Tools Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/amaranth-toolset.md Imports the symmetry_tools module for symmetry-aware modeling operations. ```python from amaranth.modeling import symmetry_tools ``` -------------------------------- ### register() Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/amaranth-toolset.md Automatically registers all exported submodules by calling their register() functions via the _call_globals() helper. ```APIDOC ## register() ### Description Automatically registers all exported submodules by calling their `register()` functions via the `_call_globals()` helper. ### Signature ```python def register(): """Register all Amaranth submodules""" ``` ``` -------------------------------- ### Import Preferences Module Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/amaranth-toolset.md Imports the prefs module for accessing and managing Amaranth user preferences and settings. ```python from amaranth import prefs ``` -------------------------------- ### glTF Export Workflow Source: https://github.com/blender/blender-addons/blob/main/_autodocs/REFERENCE-GUIDE.md Configures glTF export options for a specified filepath, including format, compression, materials, and texture coordinates. ```python # 1. Configure export options bpy.ops.export_scene.gltf( filepath='/path/export.glb', export_format='GLB', export_draco_mesh_compression_enable=True, export_materials='EXPORT', export_texcoords=True ) # 2. File written with compression and embedded data ``` -------------------------------- ### Blender Addon Compatibility Table Source: https://github.com/blender/blender-addons/blob/main/_autodocs/INDEX.md Lists various Blender addons and their compatibility with different Blender versions. ```markdown | Documentation | Blender Version | Notes | |---------------|-----------------| | types.md | 2.80+ | Core API stable | | configuration.md | 2.80+ | Backward compatible | | errors.md | 2.80+ | Common across versions | | Amaranth | 3.2.0+ | Latest features | | Sapling | 2.80+ | Long-standing | | Curve Tools | 2.80+ | Mature addon | | Add Mesh Extra | 2.80+ | Comprehensive | | AnimAll | 4.0.0+ | Requires newer Blender | | glTF Exporter | 4.2.0+ | Official, actively updated | ``` -------------------------------- ### Export Scene to GLB with Draco Compression Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/gltf2-exporter.md Exports the current scene to a GLB file with Draco mesh compression enabled. Configure compression level, materials, texture coordinates, and normals. ```python import bpy # Access exporter properties scene = bpy.context.scene # Export as GLB with Draco compression bpy.ops.export_scene.gltf( filepath='/path/to/export.glb', export_format='GLB', export_draco_mesh_compression_enable=True, export_draco_mesh_compression_level=6, export_materials='EXPORT', export_texcoords=True, export_normals=True, export_copyright='© 2024 My Company' ) ``` -------------------------------- ### Define Static Enum Items Source: https://github.com/blender/blender-addons/blob/main/_autodocs/configuration.md Create a static list of items for an EnumProperty. Each item is a tuple containing the identifier, display name, and description. ```python items = ( ('ITEM1', 'Label 1', 'Description 1'), ('ITEM2', 'Label 2', 'Description 2'), ) prop = EnumProperty(items=items) ``` -------------------------------- ### Blender Property Types Overview Source: https://github.com/blender/blender-addons/blob/main/_autodocs/INDEX.md A quick reference for common Blender property types and their basic function. ```plaintext BoolProperty → True/False toggle IntProperty → Integer values (0, 1, 2, ...) FloatProperty → Decimal values (0.0, 1.5, ...) StringProperty → Text strings EnumProperty → Dropdown selection FloatVectorProperty → Vectors, colors, positions CollectionProperty → Lists of items PointerProperty → References to objects ``` -------------------------------- ### is_draco_available() Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/gltf2-exporter.md Checks and returns a boolean indicating whether the Draco compression library is available on the current system. ```APIDOC ## is_draco_available() ### Description Determines if the Draco compression library (DLL) is available on the system. ### Returns - `bool`: `True` if Draco compression is available, `False` otherwise. ### Behavior - Initializes on first use (lazy loading). - Checks for the availability of the Draco compression extension. - Caches the result for subsequent calls. ### Usage Example ```python if is_draco_available(): enable_draco_compression() else: print("Draco compression not available on this system") ``` ``` -------------------------------- ### Node Editor Operations Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/amaranth-toolset.md Demonstrates accessing node information and simplifying node trees using the Amaranth Node Editor module. ```python from amaranth.node_editor import id_panel, simplify_nodes # Access node information panel id_panel() # Simplify complex node trees simplify_nodes() ``` -------------------------------- ### File I/O Handling with Error Catching Source: https://github.com/blender/blender-addons/blob/main/_autodocs/REFERENCE-GUIDE.md Safely loads file content, returning None if the file is not found or an IOError occurs. Prints error messages for IOErrors. ```python def load_file(filepath): try: with open(filepath, 'r') as f: return f.read() except FileNotFoundError: return None except IOError as e: print(f"Error: {e}") return None ``` -------------------------------- ### Registering Extension Panel Cleanup Functions Source: https://github.com/blender/blender-addons/blob/main/_autodocs/configuration.md This snippet shows how to manage cleanup functions for exporter and importer extension panels. It defines a list to store unregistration functions and a function to execute them. ```python # For glTF exporter extensions exporter_extension_panel_unregister_functors = [] importer_extension_panel_unregister_functors = [] # Extensions register cleanup functions def unregister_extension_panels(): for unreg in exporter_extension_panel_unregister_functors: unreg() ``` -------------------------------- ### mesh.make_triangle Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/add-mesh-extra-objects.md Creates triangle-based mesh topologies and performs triangle strip operations. ```APIDOC ## mesh.make_triangle ### Description Creates triangle-based mesh topologies and triangle strip operations. ``` -------------------------------- ### Handling File Not Found Errors in Python Source: https://github.com/blender/blender-addons/blob/main/_autodocs/errors.md Implement try-except blocks to gracefully handle FileNotFoundError when opening files. This pattern is useful for operations like loading presets where a file might be missing. ```python def load_preset(filepath): try: with open(filepath, 'r') as f: data = f.read() except FileNotFoundError: return None except IOError as e: print(f"Error reading file: {e}") return None return data ``` -------------------------------- ### Export Scene to Separate glTF Files with WebP Textures Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/gltf2-exporter.md Exports the current scene to separate glTF files with textures in WebP format. Enables WebP fallback and specifies a texture directory. ```python bpy.ops.export_scene.gltf( filepath='/path/to/export.gltf', export_format='GLTF_SEPARATE', export_image_format='WEBP', export_image_add_webp=True, export_image_webp_fallback=True, export_texture_dir='textures/' ) ``` -------------------------------- ### PresetMenu Class Definition Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/sapling-tree-gen.md Defines the PresetMenu class for dynamically generating preset menus. It inherits from the Menu class. ```python class PresetMenu(Menu): bl_idname: str = "SAPLING_MT_preset" bl_label: str = "Presets" ``` -------------------------------- ### Register Persistent Handlers with bpy.app.handlers Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/animall.md Demonstrates how to import the `persistent` decorator from `bpy.app.handlers` to ensure handlers persist across frame changes and scene updates in Blender. ```python from bpy.app.handlers import persistent ``` -------------------------------- ### Create Triangle Mesh Topologies Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/add-mesh-extra-objects.md Use this operator to create triangle-based mesh topologies and perform triangle strip operations. ```python bpy.ops.mesh.make_triangle() ``` -------------------------------- ### Scene Management Operations in Amaranth Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/amaranth-toolset.md Import and use scene management utilities from the Amaranth addon. Use 'refresh()' to update the scene and 'stats()' to retrieve scene statistics. ```python # Import scene utilities from amaranth.scene import refresh, stats # Refresh the scene refresh() # Get scene statistics scene_stats = stats() ``` -------------------------------- ### Correcting Attribute vs. Property Path Errors Source: https://github.com/blender/blender-addons/blob/main/_autodocs/errors.md Demonstrates the correct syntax for keyframe insertion involving array indices and custom attributes. Incorrect syntax can lead to 'ValueError: path not found'. Ensure attributes exist before animating them. ```python # WRONG - Invalid path syntax data.keyframe_insert("vertices.0.co") # Wrong separator # CORRECT - Array index syntax data.keyframe_insert("vertices[0].co[0]") # WRONG - Animate non-existent attribute mesh.keyframe_insert("attributes['missing'].data[0].value") # CORRECT - Create attribute first if 'my_attr' not in mesh.attributes: mesh.attributes.new('my_attr', 'FLOAT', 'POINT') mesh.keyframe_insert("attributes['my_attr'].data[0].value") ``` -------------------------------- ### AnimallProperties Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/animall.md Scene-level configuration for AnimAll, controlling which mesh/curve properties to keyframe and how to handle selection. ```APIDOC ## Class AnimallProperties ### Description Scene-level configuration for which mesh/curve properties to keyframe and how to handle selection. ### Source `animation_animall/__init__.py:28-90` ### Properties #### key_selected (BoolProperty) - **Default:** False - **Description:** Insert keyframes only on selected elements (vertices/edges/faces/loops). When True, only selected geometry receives keyframes. When False, all geometry receives keyframes. Respects current selection mode (vertex, edge, face, etc.). - **Source:** `animation_animall/__init__.py:29-32` ``` -------------------------------- ### Handle Conditional Imports for Version Compatibility Source: https://github.com/blender/blender-addons/blob/main/_autodocs/REFERENCE-GUIDE.md Use try-except blocks to handle imports that may only be available in certain Blender versions. Provide fallback mechanisms or alternative implementations for compatibility. ```python try: from bpy.app.handlers import persistent except ImportError: # Fallback for older versions persistent = lambda f: f ``` -------------------------------- ### Animation Module Operations Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/amaranth-toolset.md Illustrates displaying motion paths and jumping to specific frames using the Amaranth Animation module. ```python from amaranth.animation import motion_paths, jump_frames # Display motion paths for selected objects motion_paths() # Jump to specific frames jump_frames() ``` -------------------------------- ### Define File Path Properties Source: https://github.com/blender/blender-addons/blob/main/_autodocs/configuration.md Use StringProperty with specific subtypes like 'FILE_PATH', 'DIR_PATH', or 'FILE_NAME' to enable Blender's file browser integration for user input. ```python from bpy.props import StringProperty path = StringProperty( name="File Path", subtype='FILE_PATH', default="" ) dir_path = StringProperty( name="Directory", subtype='DIR_PATH', default="" ) file_name = StringProperty( name="File Name", subtype='FILE_NAME', default="" ) ``` -------------------------------- ### Item Tuple Format for EnumProperty Source: https://github.com/blender/blender-addons/blob/main/_autodocs/types.md The items for an EnumProperty can include optional icon and number identifiers in addition to the value, name, and description. ```python (identifier, name, description, icon, number) # icon: 'NONE', 'MESH_DATA', 'CURVE_DATA', etc. # number: unique integer identifier ``` -------------------------------- ### Callback Context Information Source: https://github.com/blender/blender-addons/blob/main/_autodocs/configuration.md Understand the context object available within property update callbacks. It provides access to the scene, active object, screen areas, and preferences. ```python def on_change(self, context): # self = property owner (PropertyGroup) # context.scene - Current scene # context.object - Active object # context.screen.areas - All editor areas # context.preferences - Blender preferences ``` -------------------------------- ### Correcting IntProperty Type Mismatch Source: https://github.com/blender/blender-addons/blob/main/_autodocs/REFERENCE-GUIDE.md Illustrates the correct way to define an integer property, ensuring the default value is an integer, not a string. ```python IntProperty(default=5) ``` -------------------------------- ### Add Various Primitive Mesh Objects Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/add-mesh-extra-objects.md Demonstrates how to add different types of primitive mesh objects using Blender's Python API, such as gears, diamonds, and procedural shapes. ```python import bpy # Add a spur gearpy.ops.mesh.primitive_gear(change=False) # Add a brilliant-cut diamondpy.ops.mesh.primitive_brilliant_add(change=False) # Create a Z-function surfacepy.ops.mesh.primitive_z_function_surface() # Generate a Platonic solidpy.ops.mesh.primitive_solid_add() # Add a procedural rockpy.ops.mesh.primitive_rock_add() ``` -------------------------------- ### ExportData Operator Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/sapling-tree-gen.md Handles writing tree configuration presets to disk, allowing users to save and share their tree designs. ```APIDOC ## ExportData ### Description Handles writing tree configuration presets to disk. ### Method `bpy.ops.sapling.exportdata()` ### Properties - **data** (StringProperty) - Serialized preset data, filename, and overwrite flag ### Methods #### `execute(context)` Writes preset to the user or built-in preset directory. **Returns:** `{'FINISHED'}` on success, `{'CANCELLED'}` on failure **Conditions that trigger cancellation:** - Preset filename matches an existing built-in preset - Preset already exists and overwrite is False - Preset data is empty ### Example ```python # Export current tree configuration as preset data_str = "(preset_dict, 'my_tree', False)"py.ops.sapling.exportdata(data=data_str) ``` ``` -------------------------------- ### Enable Operator Presets Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/gltf2-exporter.md Enables the operator preset system for the glTF exporter. This allows saving and loading export configurations. ```python bl_options = {'PRESET'} ``` -------------------------------- ### Define a Custom Menu Source: https://github.com/blender/blender-addons/blob/main/_autodocs/types.md Create a custom menu by inheriting from bpy.types.Menu. Define bl_idname and bl_label. Implement the draw method to add operators, separators, or other menus to the menu. ```python from bpy.types import Menu class MyMenu(Menu): bl_idname: str = "VIEW3D_MT_my_menu" bl_label: str = "My Menu" def draw(self, context): layout = self.layout layout.operator("operator.idname") layout.separator() layout.menu("OTHER_MT_menu") ``` -------------------------------- ### Generate a Standard Diamond Cut Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/add-mesh-extra-objects.md Use this operator to create a standard diamond cut with characteristic proportions. Set 'change' to True to edit an existing gem. ```python bpy.ops.mesh.primitive_diamond_add() ``` -------------------------------- ### Create a Custom Operator Source: https://github.com/blender/blender-addons/blob/main/_autodocs/README.md Illustrates the basic structure of a Blender operator, including its ID, label, poll method, and execute method. ```python class MyOperator(Operator): bl_idname = "addon.op" bl_label = "Operation" @classmethod def poll(cls, context): return True def execute(self, context): return {'FINISHED'} ``` -------------------------------- ### Render Module Operations Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/amaranth-toolset.md Offers utilities for rendering visualization and settings within the Amaranth Render module. Users can access functions for camera border visualization, mesh light management, passepartout previews, final resolution display, and scene sample configuration. ```APIDOC ## Render Module ### Available Operations - **border_camera** - Camera border visualization - **meshlight_add** - Add mesh lights - **meshlight_select** - Select mesh lights - **passepartout** - Passepartout preview - **final_resolution** - Display final render resolution - **samples_scene** - Scene sample settings ### Example Usage ```python from amaranth.render import border_camera, samples_scene # Visualize camera borders border_camera() # Configure sample settings samples_scene() ``` ``` -------------------------------- ### Access and Configure Curve Tools Settings Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/curve-tools.md Demonstrates how to access the scene-level `curvetoolsSettings` property group in Blender Python and modify various settings for spline operations, curve intersection, and visualization. ```python import bpy # Access curve tools settings from scene scene = bpy.context.scene settings = scene.curvetools # Configure spline operations settings.SplineJoinDistance = 0.005 settings.SplineJoinMode = 'Insert_segment' # Set intersection detection settings.IntersectCurvesAlgorithm = '3D' settings.IntersectCurvesMode = 'Split' # Customize visualization settings.curve_vertcolor = (1.0, 0.5, 0.2, 1.0) # Orange settings.path_thickness = 15 ``` -------------------------------- ### ImportData Operator Source: https://github.com/blender/blender-addons/blob/main/_autodocs/api-reference/sapling-tree-gen.md Imports preset tree configurations from disk into the active operator panel, enabling quick application of saved tree designs. ```APIDOC ## ImportData ### Description Imports preset tree configurations from disk into the active operator panel. ### Method `bpy.ops.sapling.importdata()` ### Properties - **filename** (StringProperty) - Name of the preset file to load (with .py extension) ### Methods #### `execute(context)` Loads preset file and populates global settings dictionary. **Returns:** `{'FINISHED'}` on success, `{'CANCELLED'}` on failure **Behavior:** - Searches built-in presets first, then user presets - Parses Python literal expression from preset file - Handles backward compatibility for older preset versions - Updates global `useSet` flag to apply imported settings ### Preset Compatibility: - Converts old `attractUp` float to list format - Normalizes leaf rotation properties - Sets default bend value for legacy presets ### Example ```python # Import a presetpy.ops.sapling.importdata(filename='big_oak.py') ``` ``` -------------------------------- ### Dynamic Property Display Based on Object Type Source: https://github.com/blender/blender-addons/blob/main/_autodocs/REFERENCE-GUIDE.md Shows how to display different object properties in the UI based on the active object's type (MESH or CURVE). ```python def draw(self, context): obj = context.active_object layout = self.layout # Show different properties based on selection if obj.type == 'MESH': layout.prop(obj, "vertex_property") elif obj.type == 'CURVE': layout.prop(obj, "spline_property") ```