### Install Extension Package
Source: https://docs.blender.org/api/current/bpy.ops.extensions.html
Downloads and installs an extension package. Parameters allow specifying the repository, package ID, and whether to enable the extension immediately upon installation.
```python
import bpy
bpy.ops.extensions.package_install(pkg_id="example_id", enable_on_install=True)
```
--------------------------------
### Install Documentation Requirements (Python)
Source: https://docs.blender.org/api/current/info_contributing.html
Installs the necessary Python packages for building the Blender API documentation. It primarily relies on Sphinx, but installing from the requirements file is recommended for a complete setup.
```bash
pip install -r doc/python_api/requirements.txt
```
--------------------------------
### Install Add-on and Application Template
Source: https://docs.blender.org/api/current/bpy.ops.preferences.html
These operators handle the installation of add-ons and application templates. They support options like overwriting existing files, enabling on install, and specifying file paths and filters.
```python
bpy.ops.preferences.addon_install(_*_ , _overwrite =True_, _enable_on_install =False_, _target =''_, _filepath =''_, _filter_folder =True_, _filter_python =True_, _filter_glob ='*.py;*.zip'_)
# Install an add-on
# Parameters:
# * **overwrite** (_bool_) – Overwrite, Remove existing add-ons with the same ID (optional)
# * **enable_on_install** (_bool_) – Enable on Install, Enable after installing (optional)
# * **target** (_str_) – Target Path, (optional)
# * **filepath** (_str_) – filepath, (optional, never None)
# * **filter_folder** (_bool_) – Filter folders, (optional)
# * **filter_python** (_bool_) – Filter Python, (optional)
# * **filter_glob** (_str_) – filter_glob, (optional, never None)
# Returns:
# Result of the operator call.
# Return type:
# set[Literal[Operator Return Items]]
# File:
# startup/bl_operators/userpref.py:712
```
```python
bpy.ops.preferences.app_template_install(_*_ , _overwrite =True_, _filepath =''_, _filter_folder =True_, _filter_glob ='*.zip'_)
# Install an application template
# Parameters:
# * **overwrite** (_bool_) – Overwrite, Remove existing template with the same ID (optional)
# * **filepath** (_str_) – filepath, (optional, never None)
# * **filter_folder** (_bool_) – Filter folders, (optional)
# * **filter_glob** (_str_) – filter_glob, (optional, never None)
# Returns:
# Result of the operator call.
# Return type:
# set[Literal[Operator Return Items]]
# File:
# startup/bl_operators/userpref.py:1000
```
--------------------------------
### UIListPanelExample2 - Example Usage
Source: https://docs.blender.org/api/current/bpy.types.UIList.html
An example of how to register and use a custom UIList within a Blender panel.
```APIDOC
## UIListPanelExample2 - Example Usage
### Description
This example demonstrates creating a `UIListPanelExample2` that uses the `MESH_UL_vgroups_slow` UIList to display vertex groups for an object.
### Code
```python
import bpy
class UIListPanelExample2(bpy.types.Panel):
"""Creates a Panel in the Object properties window"""
bl_label = "UIList Example 2 Panel"
bl_idname = "OBJECT_PT_ui_list_example_2"
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "object"
def draw(self, context):
layout = self.layout
obj = context.object
# `template_list` now takes two new arguments.
# The first one is the identifier of the registered UIList to use (if you want only the default list,
# with no custom draw code, use "UI_UL_list").
layout.template_list("MESH_UL_vgroups_slow", "", obj, "vertex_groups", obj.vertex_groups, "active_index")
def register():
bpy.utils.register_class(MESH_UL_vgroups_slow)
bpy.utils.register_class(UIListPanelExample2)
def unregister():
bpy.utils.unregister_class(UIListPanelExample2)
bpy.utils.unregister_class(MESH_UL_vgroups_slow)
if __name__ == "__main__":
register()
```
### Registration
- The `register()` function registers the `MESH_UL_vgroups_slow` and `UIListPanelExample2` classes.
- The `unregister()` function unregisters them.
- The `if __name__ == "__main__":` block ensures registration when the script is run directly.
```
--------------------------------
### Theme Installation
Source: https://docs.blender.org/api/current/genindex-all.html
API endpoint for installing themes.
```APIDOC
## Theme Installation
### Description
Installs a new theme into Blender.
### Method
POST
### Endpoint
`/api/preferences/theme_install`
### Parameters
#### Query Parameters
- **filepath** (string) - Required - The path to the theme file.
### Request Example
```json
{
"filepath": "/path/to/your/theme.xml"
}
```
### Response
#### Success Response (200)
- **message** (string) - Confirmation message of successful installation.
#### Response Example
```json
{
"message": "Theme installed successfully."
}
```
```
--------------------------------
### Install Extension Files
Source: https://docs.blender.org/api/current/bpy.ops.extensions.html
Installs extension packages from local files (e.g., .zip or .py) into a managed repository.
```python
import bpy
bpy.ops.extensions.package_install_files(filepath="/path/to/extension.zip", overwrite=True)
```
--------------------------------
### Install Studio Light - Blender API
Source: https://docs.blender.org/api/current/bpy.ops.preferences.html
Installs a user-defined studio light. Supports various file types like HDRIs and MatCaps. It can filter folders and specify the type of light to install.
```python
bpy.ops.preferences.studiolight_install(_*_, _files =None_, _directory =''_, _filter_folder =True_, _filter_glob ='*.png;*.jpg;*.hdr;*.exr'_, _type ='MATCAP'_)
```
--------------------------------
### asset.bundle_install Function
Source: https://docs.blender.org/api/current/genindex-all.html
Installs an asset bundle.
```APIDOC
## bundle_install()
### Description
Installs an asset bundle from a specified location.
### Module
bpy.ops.asset
```
--------------------------------
### NodeTreeInterfaceSocketBundle: Setup from Existing Socket (Python)
Source: https://docs.blender.org/api/current/bpy.types.NodeTreeInterfaceSocketBundle.html
The from_socket method sets up template parameters by copying them from an existing socket. It requires the node and the original socket to perform this setup.
```Python
def from_socket(_node_ , _socket_):
"""
Setup template parameters from an existing socket
Parameters:
* **node** (`Node`) – Node, Node of the original socket (never None)
* **socket** (`NodeSocket`) – Socket, Original socket (never None)
"""
pass
```
--------------------------------
### Example File Structure for API Documentation (Python)
Source: https://docs.blender.org/api/current/info_contributing.html
Demonstrates the required structure for an example file used in the Blender Python API documentation. It includes a reStructuredText formatted doc-string for description and metadata, followed by the Python code.
```python
"""
Example Title
+++++++++++++
A description of what this example demonstrates.
This doc-string appears above the code in the documentation.
You can use **reStructuredText** formatting here, for example:
- *Italic* text with single asterisks
- **Bold** text with double asterisks
- ``inline code`` with double backticks
- :class:`bpy.types.Operator` to link to API classes
- Links to `external resources `__
.. note::
You can use this to highlight important information.
Everything after this doc-string is included as code.
"""
import bpy
# Example code goes here
print("This is an example")
```
--------------------------------
### bpy.types.Preferences.studio_lights
Source: https://docs.blender.org/api/current/genindex-P.html
Managing preferences for studio lighting setups.
```APIDOC
## bpy.types.Preferences.studio_lights
### Description
Provides access to preferences related to studio lighting setups used for rendering and viewport previews.
### Endpoint
N/A (Internal API structure)
### Parameters
N/A
### Request Example
N/A
### Response
N/A
```
--------------------------------
### POST /wm/read_homefile
Source: https://docs.blender.org/api/current/bpy.ops.wm.html
Opens the default startup file with optional configuration for UI, templates, and empty scene states.
```APIDOC
## POST /wm/read_homefile
### Description
Opens the default .blend file. Allows for overriding the file path, UI loading, and factory reset settings.
### Method
POST
### Endpoint
bpy.ops.wm.read_homefile
### Parameters
#### Request Body
- **filepath** (str) - Optional - Path to an alternative start-up file.
- **load_ui** (bool) - Optional - Load user interface setup from the .blend file.
- **use_splash** (bool) - Optional - Show splash screen.
- **use_factory_startup** (bool) - Optional - Load the default factory startup file.
- **use_empty** (bool) - Optional - After loading, remove everything except scenes, windows, and workspaces.
### Request Example
{
"filepath": "/path/to/startup.blend",
"load_ui": true,
"use_empty": false
}
### Response
#### Success Response (200)
- **result** (set) - Result of the operator call.
```
--------------------------------
### Basic Menu Example
Source: https://docs.blender.org/api/current/bpy.types.Menu.html
Demonstrates how to create a simple menu with operators and register it.
```APIDOC
## Basic Menu Example
### Description
This example shows how to create a basic menu in Blender using the Python API. Menus are UI elements that must be referenced from a header, panel, or another menu. The `bl_idname` follows a convention like `CATEGORY_MT_name`.
### Method
N/A (Python Script)
### Endpoint
N/A (Python Script)
### Parameters
N/A
### Request Example
```python
import bpy
class BasicMenu(bpy.types.Menu):
bl_idname = "OBJECT_MT_select_test"
bl_label = "Select"
def draw(self, context):
layout = self.layout
layout.operator("object.select_all", text="Select/Deselect All").action = 'TOGGLE'
layout.operator("object.select_all", text="Inverse").action = 'INVERT'
layout.operator("object.select_random", text="Random")
bpy.utils.register_class(BasicMenu)
# Test call to display immediately.
bpy.ops.wm.call_menu(name="OBJECT_MT_select_test")
```
### Response
N/A (UI Element)
```
--------------------------------
### Get Input Socket Template (Python)
Source: https://docs.blender.org/api/current/bpy.types.GeometryNodeForeachGeometryElementOutput.html
Retrieves a template for an input socket of the GeometryNodeForeachGeometryElementOutput node. This is useful for understanding socket configurations and for dynamic node setup.
```Python
GeometryNodeForeachGeometryElementOutput._input_template(index)
```
--------------------------------
### Load User Preferences and Startup File (Python)
Source: https://docs.blender.org/api/current/info_advanced_blender_as_bpy.html
These Python commands show how to load the user's preferences and the default startup file within a `bpy` module context. `bpy.ops.wm.read_userpref()` loads the user's custom settings, while `bpy.ops.wm.read_homefile()` loads the default `.blend` file found in the user's home directory. These are used to override the default factory startup behavior.
```python
import bpy
bpy.ops.wm.read_userpref()
bpy.ops.wm.read_homefile()
```
--------------------------------
### Dependency graph: Object.to_mesh()
Source: https://docs.blender.org/api/current/bpy.types.Depsgraph.html
This example shows how to use the Object.to_mesh() function to get mesh data from any object, considering whether to include modifiers or not, and how to handle temporary mesh data.
```APIDOC
## Dependency graph: Object.to_mesh()
### Description
Function to get a mesh from any object with geometry. It is typically used by exporters, render engines and tools that need to access the evaluated mesh as displayed in the viewport. Object.to_mesh() is closely interacting with dependency graph: its behavior depends on whether it is used on original or evaluated object.
When is used on original object, the result mesh is calculated from the object without taking animation or modifiers into account:
* For meshes this is similar to duplicating the source mesh.
* For curves this disables own modifiers, and modifiers of objects used as bevel and taper.
* For meta-balls this produces an empty mesh since polygonization is done as a modifier evaluation.
When is used on evaluated object all modifiers are taken into account.
### Method
N/A (This is a Python script demonstrating API usage)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```python
import bpy
class OBJECT_OT_object_to_mesh(bpy.types.Operator):
"""Convert selected object to mesh and show number of vertices"""
bl_label = "DEG Object to Mesh"
bl_idname = "object.object_to_mesh"
def execute(self, context):
# Access input original object.
obj = context.object
if obj is None:
self.report({'INFO'}, "No active mesh object to convert to mesh")
return {'CANCELLED'}
# Avoid annoying None checks later on.
if obj.type not in {'MESH', 'CURVE', 'SURFACE', 'FONT', 'META'}:
self.report({'INFO'}, "Object cannot be converted to mesh")
return {'CANCELLED'}
depsgraph = context.evaluated_depsgraph_get()
# Invoke to_mesh() for original object.
mesh_from_orig = obj.to_mesh()
self.report({'INFO'}, f"{len(mesh_from_orig.vertices)} in new mesh without modifiers.")
# Remove temporary mesh.
obj.to_mesh_clear()
# Invoke to_mesh() for evaluated object.
object_eval = obj.evaluated_get(depsgraph)
mesh_from_eval = object_eval.to_mesh()
self.report({'INFO'}, f"{len(mesh_from_eval.vertices)} in new mesh with modifiers.")
# Remove temporary mesh.
object_eval.to_mesh_clear()
return {'FINISHED'}
def register():
bpy.utils.register_class(OBJECT_OT_object_to_mesh)
def unregister():
bpy.utils.unregister_class(OBJECT_OT_object_to_mesh)
if __name__ == "__main__":
register()
```
### Response
N/A (This is a script that reports information)
#### Success Response (200)
N/A
#### Response Example
N/A
```
--------------------------------
### POST /preferences/addon_install
Source: https://docs.blender.org/api/current/bpy.ops.preferences.html
Installs a new add-on from a file path.
```APIDOC
## POST /preferences/addon_install
### Description
Installs an add-on from a specified file path.
### Method
POST
### Endpoint
bpy.ops.preferences.addon_install
### Parameters
#### Request Body
- **filepath** (str) - Required - Path to the add-on file
- **overwrite** (bool) - Optional - Remove existing add-ons with the same ID
- **enable_on_install** (bool) - Optional - Enable after installing
### Request Example
{
"filepath": "/path/to/addon.zip",
"overwrite": true,
"enable_on_install": true
}
### Response
#### Success Response (200)
- **result** (set) - Result of the operator call.
```
--------------------------------
### Blender Python API: Get RenderLayer Subclass
Source: https://docs.blender.org/api/current/bpy.types.RenderLayer.html
Provides examples of using the class methods _bl_rna_get_subclass and _bl_rna_get_subclass_py to retrieve subclass information for Blender's RNA types, specifically for RenderLayer.
```python
_classmethod _bl_rna_get_subclass(_id_ , _default =None_, _/?):
Parameters:
* **id** (_str_) – The RNA type identifier.
* **default** (`bpy.types.Struct` | None) – The value to return when not found.
Returns:
The RNA type or default when not found.
Return type:
`bpy.types.Struct`
```
```python
_classmethod _bl_rna_get_subclass_py(_id_ , _default =None_, _/?):
Parameters:
* **id** (_str_) – The RNA type identifier.
* **default** (_type_ _|__None_) – The value to return when not found.
Returns:
The class or default when not found.
Return type:
type
```
--------------------------------
### bpy.types.StudioLight
Source: https://docs.blender.org/api/current/genindex-B.html
Represents a studio lighting setup.
```APIDOC
## StudioLight
### Description
Represents a studio lighting setup, often used for rendering previews.
### Method
Class Method
### Endpoint
N/A (bpy module class)
### Parameters
N/A
### Request Example
N/A
### Response
N/A
```
--------------------------------
### POST /bpy/preferences/theme/install
Source: https://docs.blender.org/api/current/genindex-T.html
Installs a new theme into the Blender preferences.
```APIDOC
## POST /bpy/preferences/theme/install
### Description
Installs a theme file into the current Blender user preferences.
### Method
POST
### Endpoint
/bpy/preferences/theme/install
### Parameters
#### Request Body
- **filepath** (string) - Required - The absolute path to the theme file to be installed.
### Request Example
{
"filepath": "/path/to/my_theme.xml"
}
### Response
#### Success Response (200)
- **status** (string) - Confirmation of installation success.
#### Response Example
{
"status": "success"
}
```
--------------------------------
### Implement Custom Getter and Setter Accessors
Source: https://docs.blender.org/api/current/bpy.props.html
Shows how to override default property storage using get and set callbacks. Includes examples for standard properties, read-only properties, and vector property transformations.
```python
import bpy
# Custom getter/setter for float
def get_float(self):
return self.get("testprop", 0.0)
def set_float(self, value):
self["testprop"] = value
bpy.types.Scene.test_float = bpy.props.FloatProperty(get=get_float, set=set_float)
# Read-only property example
def get_date(self):
import datetime
return str(datetime.datetime.now())
bpy.types.Scene.test_date = bpy.props.StringProperty(get=get_date)
# Vector property with transform accessors
def get_array_transform(self, curr_value, is_set):
return (True, curr_value[1])
def set_array_transform(self, new_value, curr_value, is_set):
return True, new_value[0] and new_value[1]
bpy.types.Scene.test_array_transform = bpy.props.BoolVectorProperty(
size=2, get_transform=get_array_transform, set_transform=set_array_transform)
```
--------------------------------
### Get Output Socket Template (Python)
Source: https://docs.blender.org/api/current/bpy.types.CompositorNodeTransform.html
Retrieves a template for a specific output socket of the CompositorNodeTransform. This is useful for understanding socket properties and for procedural node setup. Requires an integer index for the desired output.
```python
CompositorNodeTransform.output_template(index=0)
```
--------------------------------
### bpy.ops.wm.save_homefile()
Source: https://docs.blender.org/api/current/genindex-S.html
Saves the current Blender state as the default startup file.
```APIDOC
## save_homefile()
### Description
Saves the current Blender scene and settings as the default startup file (home file).
### Method
`bpy.ops.wm.save_homefile()`
### Endpoint
N/A (Operator)
### Parameters
None
### Request Example
```python
import bpy
bpy.ops.wm.save_homefile()
```
### Response
N/A (Operator)
```
--------------------------------
### Get Input Socket Template (Python)
Source: https://docs.blender.org/api/current/bpy.types.CompositorNodeTransform.html
Retrieves a template for a specific input socket of the CompositorNodeTransform. This is useful for understanding socket properties and for procedural node setup. Requires an integer index for the desired input.
```python
CompositorNodeTransform.input_template(index=0)
```
--------------------------------
### KDTree Initialization and Usage
Source: https://docs.blender.org/api/current/mathutils.kdtree.html
Demonstrates how to create, populate, balance, and query a KDTree using Blender's mathutils module.
```APIDOC
## KDTree Initialization and Usage
### Description
This example shows the basic workflow for using the KDTree utility in Blender's Python API. It covers creating a KDTree from mesh vertices, inserting points, balancing the tree, and performing various types of spatial searches like finding the nearest point, the N nearest points, and points within a specified radius.
### Method
```python
import mathutils
from bpy import context
# Get the active object and its mesh data
obj = context.object
mesh = obj.data
# Initialize KDTree with the size of the mesh vertices
size = len(mesh.vertices)
kd = mathutils.kdtree.KDTree(size)
# Insert vertices into the KDTree
for i, v in enumerate(mesh.vertices):
kd.insert(v.co, i)
# Balance the KDTree for efficient searching
kd.balance()
# --- Search Operations ---
# Find the closest point to the origin (0,0,0)
co_find_origin = (0.0, 0.0, 0.0)
co, index, dist = kd.find(co_find_origin)
print(f"Closest point to origin: {co}, Index: {index}, Distance: {dist}")
# Find the closest 10 points to the 3D cursor location
# Convert cursor location to object's local space
co_find_cursor = obj.matrix_world.inverted() @ context.scene.cursor.location
print("\nFinding 10 closest points to 3D cursor:")
for (co, index, dist) in kd.find_n(co_find_cursor, 10):
print(f" Position: {co}, Index: {index}, Distance: {dist}")
# Find points within a radius of 0.5 units from the 3D cursor
print("\nFinding points within 0.5 distance from 3D cursor:")
for (co, index, dist) in kd.find_range(co_find_cursor, 0.5):
print(f" Position: {co}, Index: {index}, Distance: {dist}")
```
### Parameters
N/A for this general usage example.
### Request Example
N/A
### Response
N/A
```
--------------------------------
### Basic Sound Playback
Source: https://docs.blender.org/api/current/aud.html
Demonstrates how to initialize an audio device, load a sound file, and manage playback using handles.
```APIDOC
## Basic Sound Playback
### Description
This script demonstrates the fundamental workflow for playing audio in Blender using the `aud` module, including loading files and using handles for playback control.
### Method
N/A (Python Library Usage)
### Endpoint
`aud` module
### Parameters
#### Path Parameters
- **file_path** (string) - Required - The path to the audio or video file to be loaded.
### Request Example
```python
import aud
device = aud.Device()
sound = aud.Sound('music.ogg')
handle = device.play(sound)
```
### Response
#### Success Response
- **handle** (aud.Handle) - A handle object used to control the playback (pause, stop, etc.).
#### Response Example
```python
# Returns an aud.Handle instance
```
```
--------------------------------
### Blender RNA: Get Subclass Information
Source: https://docs.blender.org/api/current/bpy.types.GreasePencilNoiseModifier.html
Provides Python examples for using the `_bl_rna_get_subclass` and `_bl_rna_get_subclass_py` class methods. These methods are used to retrieve Blender's RNA type information or Python class based on an identifier string.
```python
import bpy
# Get the RNA type for GreasePencilNoiseModifier
rna_type = bpy.types.GreasePencilNoiseModifier._bl_rna_get_subclass('GPENCIL_NOISE')
if rna_type:
print(f"RNA Type: {rna_type.name}")
# Get the Python class for GreasePencilNoiseModifier
python_class = bpy.types.GreasePencilNoiseModifier._bl_rna_get_subclass_py('GPENCIL_NOISE')
if python_class:
print(f"Python Class: {python_class.__name__}")
# Example with a default value if not found
non_existent_type = bpy.types.GreasePencilNoiseModifier._bl_rna_get_subclass('NON_EXISTENT', default='Not Found')
print(f"Non-existent type lookup: {non_existent_type}")
```
--------------------------------
### Play Audio with Audaspace
Source: https://docs.blender.org/api/current/aud.html
Demonstrates initializing an audio device, loading a sound file, and playing it. It also shows how to cache a sound for performance optimization using the handle for playback control.
```python
import aud
device = aud.Device()
# Load sound file (it can be a video file with audio).
sound = aud.Sound('music.ogg')
# Play the audio, this return a handle to control play/pause.
handle = device.play(sound)
# If the audio is not too big and will be used often you can buffer it.
sound_buffered = aud.Sound.cache(sound)
handle_buffered = device.play(sound_buffered)
```
--------------------------------
### Get Grease Pencil Depth Order Node Input Template (Python)
Source: https://docs.blender.org/api/current/bpy.types.GeometryNodeSetGreasePencilDepth.html
Retrieves the template for a specific input socket of the GeometryNodeSetGreasePencilDepth node. This allows introspection of node inputs, including their types and indices, which is helpful for procedural node setup.
```Python
bpy.types.GeometryNodeSetGreasePencilDepth._input_template(index)
```
--------------------------------
### UIList Basic Example
Source: https://docs.blender.org/api/current/bpy.types.UIList.html
Demonstrates the creation of a custom UIList subclass for displaying material slots and a panel to integrate this list.
```APIDOC
## UIList(bpy_struct)
### Description
This section provides a basic example of a UIList subclass used to display material slots in Blender. It includes detailed comments explaining the `draw_item` function and how to register the UIList and a panel that uses it.
### Method
N/A (This is a Python script example for Blender's API, not a REST API endpoint)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```python
import bpy
class MATERIAL_UL_matslots_example(bpy.types.UIList):
# The draw_item function is called for each item of the collection that is visible in the list.
# data is the RNA object containing the collection,
# item is the current drawn item of the collection,
# icon is the "computed" icon for the item (as an integer, because some objects like materials or textures
# have custom icons ID, which are not available as enum items).
# active_data is the RNA object containing the active property for the collection (i.e. integer pointing to the
# active item of the collection).
# active_propname is the name of the active property (use 'getattr(active_data, active_propname)').
# index is index of the current item in the collection.
# flt_flag is the result of the filtering process for this item.
# Note: as index and flt_flag are optional arguments, you do not have to use/declare them here if you don't
# need them.
def draw_item(self, context, layout, data, item, icon, active_data, active_propname):
ob = data
slot = item
ma = slot.material
# You should always start your row layout by a label (icon + text), or a non-embossed text field,
# this will also make the row easily selectable in the list! The later also enables ctrl-click rename.
# We use icon_value of label, as our given icon is an integer value, not an enum ID.
# Note "data" names should never be translated!
if ma:
layout.prop(ma, "name", text="", emboss=False, icon_value=icon)
else:
layout.label(text="", translate=False, icon_value=icon)
# And now we can use this list everywhere in Blender. Here is a small example panel.
class UIListPanelExample1(bpy.types.Panel):
"""Creates a Panel in the Object properties window"""
bl_label = "UIList Example 1 Panel"
bl_idname = "OBJECT_PT_ui_list_example_1"
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "object"
def draw(self, context):
layout = self.layout
obj = context.object
# `template_list` now takes two new arguments.
# The first one is the identifier of the registered UIList to use (if you want only the default list,
# with no custom draw code, use "UI_UL_list").
layout.template_list("MATERIAL_UL_matslots_example", "", obj, "material_slots", obj, "active_material_index")
# The second one can usually be left as an empty string.
# It's an additional ID used to distinguish lists in case you use the same list several times in a given area.
layout.template_list("MATERIAL_UL_matslots_example", "compact", obj, "material_slots",
obj, "active_material_index", type='COMPACT')
def register():
bpy.utils.register_class(MATERIAL_UL_matslots_example)
bpy.utils.register_class(UIListPanelExample1)
def unregister():
bpy.utils.unregister_class(UIListPanelExample1)
bpy.utils.unregister_class(MATERIAL_UL_matslots_example)
if __name__ == "__main__":
register()
```
### Response
N/A (This is a script, not an API call with a response)
#### Success Response (200)
N/A
#### Response Example
N/A
```
--------------------------------
### Get Ancestors of bpy_struct using rna_ancestors() in Blender API
Source: https://docs.blender.org/api/current/bpy.types.bpy_struct.html
The rna_ancestors() method returns a list of data structures containing the current struct, starting from the root (typically an ID) down to the immediate parent. This can be helpful for understanding the hierarchical context of an object.
```python
# Example usage
ancestors = some_struct.rna_ancestors()
```
--------------------------------
### POST /bpy/ops/wm/open_mainfile
Source: https://docs.blender.org/api/current/genindex-O.html
Opens a Blender project file (.blend).
```APIDOC
## POST /bpy/ops/wm/open_mainfile
### Description
Opens a main Blender project file from the specified path.
### Method
POST
### Endpoint
bpy.ops.wm.open_mainfile(filepath=...)
### Parameters
#### Query Parameters
- **filepath** (string) - Required - The absolute path to the .blend file.
### Request Example
{
"filepath": "/path/to/project.blend"
}
### Response
#### Success Response (200)
- **status** (string) - Confirmation of file opening.
#### Response Example
{
"status": "file opened successfully"
}
```
--------------------------------
### Get Input Socket Template (Python)
Source: https://docs.blender.org/api/current/bpy.types.TextureNodeTexBlend.html
Retrieves a template for a specific input socket of the TextureNodeTexBlend node. This method takes an index to identify the desired input socket and returns a NodeInternalSocketTemplate object. It's helpful for understanding socket configurations and for dynamic node setup.
```python
TextureNodeTexBlend._input_template(_index_)
```
--------------------------------
### POST /preferences/studiolight_install
Source: https://docs.blender.org/api/current/bpy.ops.preferences.html
Installs a user-defined studio light asset such as a MatCap, HDRI, or Studio light.
```APIDOC
## POST /preferences/studiolight_install
### Description
Installs a custom studio light asset into Blender's preference library.
### Method
POST
### Endpoint
bpy.ops.preferences.studiolight_install
### Parameters
#### Query Parameters
- **files** (bpy_prop_collection) - Optional - File path elements
- **directory** (str) - Optional - Directory path
- **filter_folder** (bool) - Optional - Filter folders
- **filter_glob** (str) - Optional - Glob pattern for file filtering
- **type** (Literal) - Optional - Type of light: 'MATCAP', 'WORLD', 'STUDIO'
### Response
#### Success Response (200)
- **result** (set) - Returns the result of the operator call.
```
--------------------------------
### Get Input Socket Template (Python)
Source: https://docs.blender.org/api/current/bpy.types.CompositorNodeBokehImage.html
Retrieves a template for an input socket of the CompositorNodeBokehImage node. This method takes an index to specify which input socket's template to obtain. The returned template provides information about the socket's properties and can be used for node setup.
```python
bpy.types.CompositorNodeBokehImage.input_template(index)
```
--------------------------------
### Get Input Socket Template for TextureNodeTexture (Python)
Source: https://docs.blender.org/api/current/bpy.types.TextureNodeTexture.html
This class method retrieves a template for a specific input socket of the TextureNodeTexture. It requires an index to identify the desired input socket. The returned template provides information about the socket's properties and type, aiding in node setup and connection.
```python
TextureNodeTexture._input_template(index)
```
--------------------------------
### Preset Menus
Source: https://docs.blender.org/api/current/bpy.types.Menu.html
Demonstrates how to create and manage preset menus for configurable options.
```APIDOC
## Preset Menus
### Description
This example shows how to implement preset menus using a menu sub-class and `AddPresetBase`. It allows users to save and load configurations for specific properties.
### Method
N/A (Python Script)
### Endpoint
N/A (Python Script)
### Parameters
N/A
### Request Example
```python
import bpy
from bpy.types import Operator, Menu
from bl_operators.presets import AddPresetBase
class OBJECT_MT_display_presets(Menu):
bl_label = "Object Display Presets"
preset_subdir = "object/display"
preset_operator = "script.execute_preset"
draw = Menu.draw_preset
class AddPresetObjectDisplay(AddPresetBase, Operator):
"""Add a Object Display Preset"""
bl_idname = "camera.object_display_preset_add"
bl_label = "Add Object Display Preset"
preset_menu = "OBJECT_MT_display_presets"
# Variable used for all preset values.
preset_defines = [
"obj = bpy.context.object"
]
# Properties to store in the preset.
preset_values = [
"obj.display_type",
"obj.show_bounds",
"obj.display_bounds_type",
"obj.show_name",
"obj.show_axis",
"obj.show_wire",
]
# Where to store the preset.
preset_subdir = "object/display"
# Display into an existing panel.
def panel_func(self, context):
layout = self.layout
row = layout.row(align=True)
row.menu(OBJECT_MT_display_presets.__name__, text=OBJECT_MT_display_presets.bl_label)
row.operator(AddPresetObjectDisplay.bl_idname, text="", icon='ZOOM_IN')
row.operator(AddPresetObjectDisplay.bl_idname, text="", icon='ZOOM_OUT').remove_active = True
classes = (
OBJECT_MT_display_presets,
AddPresetObjectDisplay,
)
def register():
for cls in classes:
bpy.utils.register_class(cls)
bpy.types.OBJECT_PT_display.prepend(panel_func)
def unregister():
for cls in classes:
bpy.utils.unregister_class(cls)
bpy.types.OBJECT_PT_display.remove(panel_func)
if __name__ == "__main__":
register()
```
### Response
N/A (UI Element with Preset Functionality)
```
--------------------------------
### Get Input Template for Grease Pencil to Curves Node (Python)
Source: https://docs.blender.org/api/current/bpy.types.GeometryNodeGreasePencilToCurves.html
Retrieves a template for a specific input socket of the Grease Pencil to Curves node. This is useful for understanding the expected data type and structure for inputs when creating or manipulating node setups programmatically. It requires an index to specify which input socket's template to retrieve.
```Python
bpy.types.GeometryNodeGreasePencilToCurves.input_template(index)
```
--------------------------------
### Blender API: Efficiently Set Vertex Z-Coordinates using foreach_set
Source: https://docs.blender.org/api/current/bpy.types.bpy_prop_collection.html
Illustrates how to use the `foreach_set` method to efficiently update vertex coordinates in Blender. This example flattens all Z-coordinates to zero by first getting all coordinates with `foreach_get`, modifying the Z-values in the flat list, and then setting them back using `foreach_set`. This is a performance optimization over individual vertex manipulation.
```python
import bpy
mesh = bpy.context.object.data
collection = mesh.vertices
# Flatten all Z coordinates to zero (X, Y, Z per vertex).
coords = [0.0] * len(collection) * 3
collection.foreach_get("co", coords)
for i in range(2, len(coords), 3):
coords[i] = 0.0
# Fast assignment.
collection.foreach_set("co", coords)
# Python equivalent (per-element iteration is much slower).
# for i, vert in enumerate(collection):
# vert.co = (coords[i * 3], coords[i * 3 + 1], coords[i * 3 + 2])
```
--------------------------------
### POST /preferences/theme_install
Source: https://docs.blender.org/api/current/bpy.ops.preferences.html
Loads and applies a custom XML theme file to the Blender interface.
```APIDOC
## POST /preferences/theme_install
### Description
Imports and applies a user-provided XML theme file.
### Method
POST
### Endpoint
bpy.ops.preferences.theme_install
### Parameters
#### Query Parameters
- **overwrite** (bool) - Optional - Whether to replace existing theme files
- **filepath** (str) - Optional - Path to the XML theme file
- **filter_folder** (bool) - Optional - Filter folders
- **filter_glob** (str) - Optional - Glob pattern for file filtering
### Response
#### Success Response (200)
- **result** (set) - Returns the result of the operator call.
```
--------------------------------
### Implementing Socket Initialization
Source: https://docs.blender.org/api/current/bpy.types.NodeTreeInterfaceSocketVectorVelocity2D.html
Example of how to override or utilize the init_socket method to set up a node socket instance within a custom node tree interface.
```python
def init_socket(self, node, socket, data_path):
# Custom initialization logic for the socket
socket.name = "Velocity"
print(f"Initializing socket for node: {node.name} at {data_path}")
```
--------------------------------
### Object Indirect Only Get Method
Source: https://docs.blender.org/api/current/genindex-I.html
Method to get indirect only status for an object.
```APIDOC
## Object Indirect Only Get Method
### Description
A method to retrieve the indirect lighting exclusion status of an object.
### Method
N/A
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
#### Success Response (200)
- **indirect_only_get()** (bpy.types.Object method) - Retrieves the indirect lighting exclusion status.
#### Response Example
N/A
```
--------------------------------
### Manage Studio Lights in Blender
Source: https://docs.blender.org/api/current/bpy.types.StudioLights.html
Demonstrates how to load, create, and remove studio lights using the bpy.types.StudioLights collection interface.
```python
import bpy
# Access the studio lights collection
studio_lights = bpy.context.preferences.studio_lights
# Load a new studio light from a file
new_light = studio_lights.load(path="/path/to/light.exr", type='STUDIO')
# Create a new studio light from default settings
custom_light = studio_lights.new(path="/path/to/save/light")
# Remove a specific studio light
studio_lights.remove(new_light)
# Refresh the collection from disk
studio_lights.refresh()
```
--------------------------------
### Setup Template from Existing Socket
Source: https://docs.blender.org/api/current/bpy.types.NodeTreeInterfaceSocketVectorPercentage2D.html
The from_socket method allows for the creation of a template configuration based on an existing socket instance. This is useful for duplicating or inheriting settings from another socket.
```python
def from_socket(self, node, socket):
# Copy settings from an existing socket
self.default_value = socket.default_value
self.min_value = getattr(socket, "min_value", 0.0)
self.max_value = getattr(socket, "max_value", 0.0)
```
--------------------------------
### bpy.ops.wm.open_mainfile
Source: https://docs.blender.org/api/current/genindex-all.html
Opens a Blender main file.
```APIDOC
## [FUNCTION] bpy.ops.wm.open_mainfile()
### Description
Opens a Blender main file.
### Method
FUNCTION
### Endpoint
bpy.ops.wm.open_mainfile()
```
--------------------------------
### Blender API: Node Socket Setup from Existing
Source: https://docs.blender.org/api/current/bpy.types.NodeTreeInterfaceSocket.html
Enables setting up template parameters for a node socket by copying from an existing socket, requiring the source node and socket objects.
```python
from_socket(_node_, _socket_)
# Setup template parameters from an existing socket
# Parameters:
# * **node** (`Node`) – Node, Node of the original socket (never None)
# * **socket** (`NodeSocket`) – Socket, Original socket (never None)
```
--------------------------------
### GET /bpy/utils/get
Source: https://docs.blender.org/api/current/genindex-G.html
Retrieves data from various collections and structures using the standard get() method pattern.
```APIDOC
## GET /bpy/utils/get
### Description
Accesses the get() method available across multiple Blender modules including bmesh, bpy.types, and idprop.
### Method
GET
### Endpoint
/bpy/utils/get
### Parameters
#### Query Parameters
- **context** (string) - Required - The module context (e.g., bmesh.types, bpy.types).
- **key** (string) - Required - The identifier for the item to retrieve.
### Response
#### Success Response (200)
- **data** (any) - The requested object or value.
#### Response Example
{
"status": "success",
"value": "data_content"
}
```
--------------------------------
### Perform Spatial Searches with KDTree
Source: https://docs.blender.org/api/current/mathutils.kdtree.html
This example demonstrates how to initialize a KDTree from mesh vertices, balance the tree, and perform various spatial queries including finding the closest point, the N nearest points, and points within a specific radius.
```python
import mathutils
from bpy import context
# Create a KD-tree from a mesh.
obj = context.object
mesh = obj.data
size = len(mesh.vertices)
kd = mathutils.kdtree.KDTree(size)
for i, v in enumerate(mesh.vertices):
kd.insert(v.co, i)
kd.balance()
# Find the closest point to the center.
co_find = (0.0, 0.0, 0.0)
co, index, dist = kd.find(co_find)
print("Close to center:", co, index, dist)
# 3D cursor relative to the object data.
co_find = obj.matrix_world.inverted() @ context.scene.cursor.location
# Find the closest 10 points to the 3D cursor.
print("Close 10 points")
for (co, index, dist) in kd.find_n(co_find, 10):
print(" ", co, index, dist)
# Find points within a radius of the 3D cursor.
print("Close points within 0.5 distance")
for (co, index, dist) in kd.find_range(co_find, 0.5):
print(" ", co, index, dist)
```
--------------------------------
### Get BoidRuleFollowLeader Subclass by ID (Python - Py)
Source: https://docs.blender.org/api/current/bpy.types.BoidRuleFollowLeader.html
Retrieves a Python class of BoidRuleFollowLeader using its RNA type identifier. This is the Python-specific version of getting a subclass.
```python
bpy.types.BoidRuleFollowLeader._bl_rna_get_subclass_py(_id_, _default=None_, _/_)
Parameters:
id (str): The RNA type identifier.
default (type | None): The value to return when not found.
Returns:
The class or default when not found.
Return type:
type
```
--------------------------------
### Initialize and Combine Quaternions
Source: https://docs.blender.org/api/current/mathutils.html
Demonstrates how to create quaternions using direct values or axis-angle pairs, and how to combine multiple rotations using the @ operator.
```python
import math
import mathutils
# Initialize using axis and angle
quat_a = mathutils.Quaternion((0.0, 1.0, 0.0), math.radians(90.0))
quat_b = mathutils.Quaternion((0.0, 0.0, 1.0), math.radians(45.0))
# Combine rotations
quat_out = quat_a @ quat_b
```
--------------------------------
### Create a Basic Menu in Blender
Source: https://docs.blender.org/api/current/bpy.types.Menu.html
Demonstrates how to define a custom menu class inheriting from bpy.types.Menu. It includes registering the class and triggering the menu display using bpy.ops.wm.call_menu.
```python
import bpy
class BasicMenu(bpy.types.Menu):
bl_idname = "OBJECT_MT_select_test"
bl_label = "Select"
def draw(self, context):
layout = self.layout
layout.operator("object.select_all", text="Select/Deselect All").action = 'TOGGLE'
layout.operator("object.select_all", text="Inverse").action = 'INVERT'
layout.operator("object.select_random", text="Random")
bpy.utils.register_class(BasicMenu)
bpy.ops.wm.call_menu(name="OBJECT_MT_select_test")
```
--------------------------------
### Set Start Frame (Python)
Source: https://docs.blender.org/api/current/bpy.ops.anim.html
Sets the current frame as the preview or scene start frame. This operator is part of the animation module and returns the result of the operator call.
```python
bpy.ops.anim.start_frame_set()
```
--------------------------------
### Implement RenderEngine Constructor
Source: https://docs.blender.org/api/current/info_overview.html
Demonstrates how to correctly initialize a custom RenderEngine by calling the parent constructor. This is essential for Blender's internal initialization process.
```python
import bpy
class AwesomeRaytracer(bpy.types.RenderEngine):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.my_var = 42
```
--------------------------------
### Get Python Subclass by ID - Blender Python API
Source: https://docs.blender.org/api/current/bpy.types.CurveSlice.html
Retrieves a Python class or its default value based on an identifier string. This is the Python-specific version of getting an RNA subclass.
```python
bpy.types.CurveSlice._bl_rna_get_subclass_py(_id_ , _default =None_, _/_)
```
--------------------------------
### Select Nth Curve Point
Source: https://docs.blender.org/api/current/bpy.ops.curve.html
Deselects every Nth point in a sequence starting from the active point. Parameters control the skip count, selection count, and starting offset.
```python
import bpy
bpy.ops.curve.select_nth(skip=1, nth=1, offset=0)
```
--------------------------------
### Setup Template from Existing Socket
Source: https://docs.blender.org/api/current/bpy.types.NodeTreeInterfaceSocketVectorDirection4D.html
The from_socket method allows setting up template parameters for a new socket based on an existing one. This is useful for duplicating or inheriting socket configurations.
```python
def from_socket(node, socket):
# Setup template parameters from an existing socket
# node: Node of the original socket
# socket: Original socket to copy parameters from
pass
```
--------------------------------
### Setup Socket Parameters from Existing Socket - Python
Source: https://docs.blender.org/api/current/bpy.types.NodeTreeInterfaceSocketVectorEuler.html
Sets up template parameters from an existing socket. This is useful for creating new sockets that inherit properties from existing ones.
```python
def from_socket(_node_, _socket_):
"""Setup template parameters from an existing socket
Parameters:
node (Node): Node of the original socket (never None)
socket (NodeSocket): Original socket (never None)
"""
pass
```
--------------------------------
### Get RNA Subclass by ID (Python - Type)
Source: https://docs.blender.org/api/current/bpy.types.TransformCacheConstraint.html
Retrieves an RNA class by its identifier. If the class is not found, it returns a specified default value. This method is specifically for getting the class type itself.
```python
bpy.types.TransformCacheConstraint._bl_rna_get_subclass_py(_id_, _default=None_, _/_)
# Parameters:
# id (str): The RNA type identifier.
# default (type | None): The value to return when not found.
# Returns:
# The class or default when not found.
# Return type:
# type
```
--------------------------------
### Blender API: Setup Socket from Existing
Source: https://docs.blender.org/api/current/bpy.types.NodeTreeInterfaceSocketFloatFrequency.html
Sets up template parameters from an existing node socket. This is useful for creating new sockets that inherit properties from pre-existing ones.
```python
def from_socket(_node_, _socket_):
"""Setup template parameters from an existing socket
Parameters:
node (Node): Node of the original socket (never None)
socket (NodeSocket): Original socket (never None)
"""
pass
```
--------------------------------
### Get NodeSocketString Subclass by ID (Python - Py)
Source: https://docs.blender.org/api/current/bpy.types.NodeSocketString.html
Retrieves a Python class of NodeSocketString based on its RNA type identifier. This is the Python-specific version of getting a subclass, returning a type object.
```python
bpy.types.NodeSocketString._bl_rna_get_subclass_py(_id_, _default=None_)
# Parameters:
# id (str): The RNA type identifier.
# default (type | None): The value to return when not found.
# Returns:
# type: The class or default when not found.
```
--------------------------------
### Setup Template from Existing Socket
Source: https://docs.blender.org/api/current/bpy.types.NodeTreeInterfaceSocketFloatTime.html
The from_socket method sets up template parameters by copying them from an existing socket. This is useful for duplicating socket configurations.
```python
def from_socket(self, node, socket):
# Setup parameters from an existing socket
self.default_value = socket.default_value
```