Skip to content

Commit

Permalink
add context manager snippets
Browse files Browse the repository at this point in the history
  • Loading branch information
Pullusb committed Jul 16, 2023
1 parent 8802fd4 commit 60e0caf
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
26 changes: 26 additions & 0 deletions snippets/dev/context_manager_bmesh.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
## context managers for Bmesh editing
## Author: Salai Vedha Viradhan : from https://salaivv.com/2023/07/07/context-mangers-blender

import bpy
import bmesh
from contextlib import contextmanager

# Bmesh operations on a mesh object
@contextmanager
def BMeshObject(mesh_object):
# Setup process
mesh = bmesh.new()
mesh.from_mesh(mesh_object.data)

try:
# Yielding mesh to the outer context to execute
# the statements inside the 'with' block
yield mesh
finally:
# Teardown process
mesh.to_mesh(mesh_object.data)
mesh.free()

## Usage:
# with BMeshObject(mesh_object) as mesh:
# bmesh.ops.remove_doubles(mesh, verts=mesh.verts, dist=0.0001)
29 changes: 29 additions & 0 deletions snippets/dev/context_manager_edit_mode.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
## context managers for edit mode
## Author: Salai Vedha Viradhan : from https://salaivv.com/2023/07/07/context-mangers-blender

import bpy
import contextlib

# Edit mode operations on passed object
@contextlib.contextmanager
def EditMode(active_object):
# Setup process
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all(action='DESELECT')
bpy.context.view_layer.objects.active = active_object
bpy.ops.object.mode_set(mode='EDIT')

try:
# Yielding execution to the outer context to execute
# the statements inside the 'with' block
yield
finally:
# Teardown process
bpy.ops.object.mode_set(mode='OBJECT')

## usage:
# with EditMode(mesh_object):
# bpy.ops.mesh.select_all(action='SELECT')
# bpy.ops.mesh.remove_doubles()
# bpy.ops.mesh.dissolve_limited()
# bpy.ops.mesh.tris_convert_to_quads()
File renamed without changes.

0 comments on commit 60e0caf

Please sign in to comment.