To optimize your Blender operator for scattering vegetation, you can make two significant changes:
-
Use Shared Mesh Data: Instead of copying the mesh data for each instance, you can reference the same mesh data. This reduces memory usage because all instances share the same underlying mesh.
-
Set Display Type to 'BOUNDS': By setting the display type of each instance to 'BOUNDS', you improve viewport performance because Blender only needs to draw bounding boxes instead of detailed geometry.
Here's how you can modify your code:
1. Modify create_instance to Use Shared Mesh Data and Set Display Type
def create_instance(self, source_obj, location, normal, layer):
obj_copy = source_obj.copy()
# Use shared mesh data to save memory
obj_copy.data = source_obj.data
# Set instance location and transform
obj_copy.location = location
scale_rand = ((np.random.rand() * layer.scale_rand) + (1 - (np.random.rand() * layer.scale_rand)))
obj_copy.scale *= (layer.scale * scale_rand)
rotation_rand = ((2 * np.pi) - ((layer.rot_rand * np.random.rand()) * 2 * np.pi)) + (layer.rot * 2 * np.pi)
obj_copy.rotation_euler.rotate_axis('Z', rotation_rand)
self.align_object(obj_copy, normal, layer)
# Set display type to 'BOUNDS' for better viewport performance
obj_copy.display_type = 'BOUNDS'
print(f"Created instance at {location}")
return obj_copy
2. Ensure You Are Referencing the Correct Source Object
In your import_fbx function, you are returning imported_objects, which is a list of objects. You need to make sure you're passing the correct object to create_instance. You can modify import_fbx to return the first imported object:
def import_fbx(self, filepath):
try:
# Deselect all objects before import
bpy.ops.object.select_all(action='DESELECT')
bpy.ops.import_scene.fbx(filepath=filepath)
imported_objects = bpy.context.selected_objects
print(f"Imported model: {filepath}")
# Return the first object
if imported_objects:
return imported_objects[0]
else:
return None
except Exception as e:
print(f"Failed to import FBX: {e}")
return None
3. Update scatter_layer to Handle the Updated import_fbx Return Value
Since import_fbx now returns a single object, ensure that scatter_layer works accordingly:
def scatter_layer(self, context, layer):
veg_directory = context.scene.TF_vegetation_path
model_path = os.path.join(veg_directory, layer.model)
imported_object = self.import_fbx(model_path)
if not imported_object:
print(f"Failed to import model: {layer.model}")
return
# Hide the imported object to prevent duplicate rendering
imported_object.hide_render = True
imported_object.hide_viewport = True
target_object = get_terrain_object()
if not target_object or target_object.type != 'MESH':
print("No valid target object selected for scattering.")
return
# [Rest of your code...]
4. Optionally, Use Linked Instances Instead of Duplicates
If you want to further optimize memory usage, you can link the object data instead of copying it:
def create_instance(self, source_obj, location, normal, layer):
obj_copy = bpy.data.objects.new(name=source_obj.name, object_data=source_obj.data)
# [Rest of your code...]
5. Hide the Original Imported Object
To prevent the original imported object from appearing in the scene, you can hide it:
# After importing the object
imported_object.hide_render = True
imported_object.hide_viewport = True
Full Modified Code Snippet:
# Operator for Scattering
def execute(self, context):
try:
obj = get_terrain_object()
if not obj:
print("Cannot find valid terrain object")
return {'CANCELLED'}
scene_props = obj.TF_scatter_data
if not scene_props.layers:
self.report({'WARNING'}, "No layers to scatter.")
return {'CANCELLED'}
for layer in scene_props.layers:
print(f"Scattering Layer: {layer.name}")
self.scatter_layer(context, layer)
self.report({'INFO'}, "Scattering completed.")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Error during scattering: {e}")
print(f"Error during scattering: {e}")
return {'CANCELLED'}
def scatter_layer(self, context, layer):
veg_directory = context.scene.TF_vegetation_path
model_path = os.path.join(veg_directory, layer.model)
imported_object = self.import_fbx(model_path)
if not imported_object:
print(f"Failed to import model: {layer.model}")
return
# Hide the imported object
imported_object.hide_render = True
imported_object.hide_viewport = True
target_object = get_terrain_object()
if not target_object or target_object.type != 'MESH':
print("No valid target object selected for scattering.")
return
# Ensure we have up-to-date mesh data
depsgraph = context.evaluated_depsgraph_get()
eval_obj = target_object.evaluated_get(depsgraph)
mesh = eval_obj.to_mesh()
# Get face and vertex data
faces = np.array([face.vertices for face in mesh.polygons])
verts = np.array([vert.co for vert in mesh.vertices])
normals = np.array([face.normal for face in mesh.polygons])
face_areas = np.array([face.area for face in mesh.polygons])
num_points = layer.density
# Sample points on the mesh surface
sampled_points, sampled_normals = self.sample_points_on_mesh(verts, faces, normals, face_areas, num_points)
# Adjust points based on terrain characteristics
weights = self.calculate_weights(sampled_points, sampled_normals, layer)
accepted_indices = self.filter_points(weights)
filtered_points = sampled_points[accepted_indices]
# Enforce minimum spacing (resource competition)
final_points, final_normals = self.enforce_min_spacing(filtered_points, sampled_normals, layer.min_spacing)
print(f"Placing {len(final_points)} instances for layer '{layer.name}'")
# Scatter the objects
for loc, normal in zip(final_points, final_normals):
obj = self.create_instance(imported_object, loc, normal, layer)
obj.TF_SID = layer.TF_SID
context.collection.objects.link(obj)
# Clean up
eval_obj.to_mesh_clear()
def import_fbx(self, filepath):
try:
# Deselect all objects before import
bpy.ops.object.select_all(action='DESELECT')
bpy.ops.import_scene.fbx(filepath=filepath)
imported_objects = bpy.context.selected_objects
print(f"Imported model: {filepath}")
# Return the first object
if imported_objects:
return imported_objects[0]
else:
return None
except Exception as e:
print(f"Failed to import FBX: {e}")
return None
def create_instance(self, source_obj, location, normal, layer):
obj_copy = source_obj.copy()
# Use shared mesh data
obj_copy.data = source_obj.data
obj_copy.location = location
scale_rand = ((np.random.rand() * layer.scale_rand) + (1 - (np.random.rand() * layer.scale_rand)))
obj_copy.scale *= (layer.scale * scale_rand)
rotation_rand = ((2 * np.pi) - ((layer.rot_rand * np.random.rand()) * 2 * np.pi)) + (layer.rot * 2 * np.pi)
obj_copy.rotation_euler.rotate_axis('Z', rotation_rand)
self.align_object(obj_copy, normal, layer)
# Set display type to 'BOUNDS'
obj_copy.display_type = 'BOUNDS'
print(f"Created instance at {location}")
return obj_copy
def align_object(self, obj, normal, layer):
if layer.align_to_normal:
# Align object to the normal
up = Vector((0, 0, 1))
direction = Vector(normal).normalized()
rotation = up.rotation_difference(direction).to_euler()
obj.rotation_euler = rotation
else:
# Default orientation
pass
# [Rest of your code...]
Explanation:
-
Shared Mesh Data: By setting obj_copy.data = source_obj.data, all instances share the same mesh data. This reduces memory usage significantly, especially when scattering a large number of instances.
-
Display as Bounds: Setting obj_copy.display_type = 'BOUNDS' instructs Blender to display the object as a bounding box in the viewport. This reduces the computational load for rendering in the viewport, making interactions smoother.
Additional Tips:
-
Use Collection Instances: For even better performance, consider using Collection Instances. You can add all your instances to a collection and then create instances of that collection. This further reduces memory usage and can improve performance.
-
Use Geometry Nodes: For complex scattering tasks, Blender's Geometry Nodes system is highly efficient and designed for this purpose. It might be worth exploring for future projects.
-
Avoid Using Operators in Scripts: Directly manipulating data blocks (like creating objects or modifying their attributes) is generally faster and more reliable in scripts than using bpy.ops operators.
By implementing these changes, your scattering operator should perform more efficiently, both in terms of memory usage and viewport performance.