this is an operaor for a blender addon that scatters assets across a mesh. Expand it ith additional advanced features.
Operator for Scattering
class TF_OT_Scatter(Operator):
bl_label = "Scatter Objects"
bl_idname = "TF.scatter"
bl_description = "Scatter objects based on parameters"
code
Assistant
def execute(self, context):
try:
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):
model_path = os.path.join(veg_directory, layer.model)
imported_objects = self.import_fbx(model_path)
if not imported_objects:
print(f"Failed to import model: {layer.model}")
#return
target_object = context.active_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()
imported_object = bpy.data.objects["Plant"]
# 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 = self.enforce_min_spacing(filtered_points, layer.min_spacing)
print(f"Placing {len(final_points)} instances for layer '{layer.name}'")
# Scatter the objects
for loc in final_points:
obj = self.create_instance(imported_object, loc, 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:
bpy.ops.import_scene.fbx(filepath=filepath)
imported_objects = bpy.context.selected_objects
print(f"Imported model: {filepath}")
return imported_objects
except Exception as e:
print(f"Failed to import FBX: {e}")
return None
def create_instance(self, source_obj, location, layer):
obj_copy = source_obj.copy()
obj_copy.data = source_obj.data.copy()
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)
print(f"Created instance at {location}")
return obj_copy
def sample_points_on_mesh(self, verts, faces, normals, face_areas, num_points):
# Normalize face areas to probabilities
face_probs = face_areas / face_areas.sum()
# Randomly select faces based on area
chosen_faces = np.random.choice(len(faces), size=num_points, p=face_probs)
# Generate random barycentric coordinates
us = np.random.rand(num_points, 1)
vs = np.random.rand(num_points, 1)
ws = 1 - us - vs
mask = ws.flatten() < 0
us[mask], vs[mask] = vs[mask], us[mask]
ws = 1 - us - vs
# Get vertices of the chosen faces
v0 = verts[faces[chosen_faces, 0]]
v1 = verts[faces[chosen_faces, 1]]
v2 = verts[faces[chosen_faces, 2]]
# Calculate sampled points
sampled_points = us * v0 + vs * v1 + ws * v2
sampled_normals = normals[chosen_faces]
return sampled_points, sampled_normals
def calculate_weights(self, points, normals, layer):
# Calculate slope based on normal vectors
slopes = 1 - np.abs(normals[:, 2]) # Assuming Z-up axis
slope_influence = layer.slope_influence
# Calculate altitude
altitudes = points[:, 2]
altitude_influence = layer.altitude_influence
# Normalize altitudes
altitudes_norm = (altitudes - altitudes.min()) / (altitudes.max() - altitudes.min() + 1e-6)
# Calculate weights
weights = np.ones(len(points))
weights *= np.exp(-slope_influence * slopes)
weights *= np.exp(-altitude_influence * altitudes_norm)
return weights
def filter_points(self, weights):
# Normalize weights to probabilities
probabilities = weights / weights.max()
# Accept or reject points
random_values = np.random.rand(len(weights))
accepted_indices = np.where(random_values < probabilities)[0]
return accepted_indices
def enforce_min_spacing(self, points, min_spacing):
if len(points) == 0:
return points
tree = kdtree.KDTree(len(points))
for i, co in enumerate(points):
tree.insert(co, i)
tree.balance()
accepted = []
rejected = set()
for i, co in enumerate(points):
if i in rejected:
continue
accepted.append(co)
# Find points within min_spacing
nearby = tree.find_range(co, min_spacing)
for (co_found, index, dist) in nearby:
if index > i:
rejected.add(index)
accepted_points = np.array(accepted)
print(f"After enforcing min spacing, {len(accepted_points)} points remain.")
return accepted_points
Great! Let's expand your operator to include several advanced features:
Rotation Randomization: Allow random rotation around specified axes.
Alignment Options: Enable alignment to surface normals or global axes.
Multiple Models: Support scattering multiple different models from a collection.
Weight Painting Influence: Use vertex group weights to influence scatter density.
Use Instances: Use linked duplicates (instances) instead of full copies for better performance.
Random Seed: Allow the user to specify a seed for randomization to get repeatable results.
User Interface Enhancements: Add properties to the operator for user control.
Here's the updated code:
python
import bpy
from bpy.types import Operator
import numpy as np
import os
import random
# Operator for Scattering
class TF_OT_Scatter(Operator):
bl_label = "Scatter Objects"
bl_idname = "tf.scatter"
bl_description = "Scatter objects based on parameters"
# User interface properties
density: bpy.props.IntProperty(
name="Density",
default=1000,
min=1,
description="Number of points to scatter"
)
min_spacing: bpy.props.FloatProperty(
name="Minimum Spacing",
default=0.5,
min=0.0,
description="Minimum spacing between scattered objects"
)
models_collection: bpy.props.PointerProperty(
name="Models Collection",
type=bpy.types.Collection,
description="Collection of models to scatter"
)
align_to_normal: bpy.props.BoolProperty(
name="Align to Normal",
default=True,
description="Align scattered objects to the surface normal"
)
random_rotation: bpy.props.BoolProperty(
name="Random Rotation",
default=True,
description="Randomize rotation of scattered objects"
)
rotation_offset: bpy.props.FloatVectorProperty(
name="Rotation Offset",
size=3,
description="Offset the rotation of scattered objects"
)
scale: bpy.props.FloatProperty(
name="Scale",
default=1.0,
min=0.0,
description="Base scale of scattered objects"
)
scale_random: bpy.props.FloatProperty(
name="Scale Randomness",
default=0.5,
min=0.0,
max=1.0,
description="Randomness factor for scaling"
)
use_vertex_group: bpy.props.BoolProperty(
name="Use Vertex Group",
default=False,
description="Use vertex group weights for density influence"
)
vertex_group_name: bpy.props.StringProperty(
name="Vertex Group",
default="",
description="Name of the vertex group to use"
)
use_instances: bpy.props.BoolProperty(
name="Use Instances",
default=True,
description="Use instances (linked duplicates) for better performance"
)
random_seed: bpy.props.IntProperty(
name="Random Seed",
default=42,
description="Seed for random number generator"
)
# Operator execution
def execute(self, context):
try:
# Ensure a models collection is set
if not self.models_collection:
self.report({'WARNING'}, "No models collection set for scattering.")
return {'CANCELLED'}
# Get the target object (the mesh to scatter on)
target_object = context.active_object
if not target_object or target_object.type != 'MESH':
self.report({'WARNING'}, "Please select a mesh object to scatter on.")
return {'CANCELLED'}
# Prepare RNG
np.random.seed(self.random_seed)
random.seed(self.random_seed)
# 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])
# If using weight painting (vertex groups), get the weights
if self.use_vertex_group and self.vertex_group_name:
vg = target_object.vertex_groups.get(self.vertex_group_name)
if vg is None:
self.report({'WARNING'}, f"Vertex group '{self.vertex_group_name}' not found.")
return {'CANCELLED'}
weights = np.array([vg.weight(i) if vg.weight(i) else 0.0 for i in range(len(target_object.data.vertices))])
weights_faces = np.array([weights[face.vertices].mean() for face in target_object.data.polygons])
face_areas *= weights_faces # Modulate face areas by weights
# Remove faces with zero weight
valid_faces = face_areas > 0
faces = faces[valid_faces]
normals = normals[valid_faces]
face_areas = face_areas[valid_faces]
if len(faces) == 0:
self.report({'WARNING'}, "No faces with weights greater than zero.")
return {'CANCELLED'}
# Sample points on the mesh surface
sampled_points, sampled_normals = self.sample_points_on_mesh(verts, faces, normals, face_areas, self.density)
# Enforce minimum spacing
final_points, final_normals = self.enforce_min_spacing(sampled_points, sampled_normals, self.min_spacing)
# Scatter the objects
self.scatter_objects(context, final_points, final_normals)
# Clean up
eval_obj.to_mesh_clear()
self.report({'INFO'}, f"Scattering completed with {len(final_points)} instances.")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Error during scattering: {e}")
print(f"Error during scattering: {e}")
return {'CANCELLED'}
def scatter_objects(self, context, locations, normals):
# Get the models from the collection
model_objects = [obj for obj in self.models_collection.objects if obj.type == 'MESH']
if not model_objects:
self.report({'WARNING'}, "No valid models in the specified collection.")
return
# Create a new collection for scattered objects
scatter_coll = bpy.data.collections.new("Scattered Objects")
context.scene.collection.children.link(scatter_coll)
for loc, normal in zip(locations, normals):
# Randomly pick a model
model_obj = random.choice(model_objects)
if self.use_instances:
# Use an instance
obj = self.create_instance(model_obj)
else:
# Make a full copy
obj = self.create_copy(model_obj)
# Set location
obj.location = loc
# Set rotation
self.align_object(obj, normal)
# Apply random rotation
if self.random_rotation:
obj.rotation_euler.rotate_axis('Z', random.uniform(0, 2 * np.pi))
# Apply rotation offset
obj.rotation_euler.rotate_axis('X', self.rotation_offset[0])
obj.rotation_euler.rotate_axis('Y', self.rotation_offset[1])
obj.rotation_euler.rotate_axis('Z', self.rotation_offset[2])
# Apply scaling
scale_factor = self.scale * random.uniform(1.0 - self.scale_random, 1.0 + self.scale_random)
obj.scale *= scale_factor
# Link object to the scatter collection
scatter_coll.objects.link(obj)
def create_instance(self, source_obj):
obj = bpy.data.objects.new(name=source_obj.name, object_data=source_obj.data)
obj.instance_type = 'NONE'
obj.parent = source_obj
obj.matrix_parent_inverse = source_obj.matrix_world.inverted()
return obj
def create_copy(self, source_obj):
obj_copy = source_obj.copy()
obj_copy.data = source_obj.data.copy()
return obj_copy
def align_object(self, obj, normal):
if self.align_to_normal:
# Align object to the normal
up = Vector((0, 0, 1))
direction = normal.normalized()
rotation = up.rotation_difference(direction).to_euler()
obj.rotation_euler = rotation
else:
# Default orientation
pass
def sample_points_on_mesh(self, verts, faces, normals, face_areas, num_points):
# Normalize face areas to probabilities
face_probs = face_areas / face_areas.sum()
# Randomly select faces based on area
chosen_faces = np.random.choice(len(faces), size=num_points, p=face_probs)
# Generate random barycentric coordinates
us = np.random.rand(num_points, 1)
vs = np.random.rand(num_points, 1)
ws = 1 - us - vs
mask = ws.flatten() < 0
us[mask], vs[mask] = vs[mask], us[mask]
ws = 1 - us - vs
# Get vertices of the chosen faces
v0 = verts[faces[chosen_faces, 0]]
v1 = verts[faces[chosen_faces, 1]]
v2 = verts[faces[chosen_faces, 2]]
# Calculate sampled points
sampled_points = us * v0 + vs * v1 + ws * v2
sampled_normals = normals[chosen_faces]
return sampled_points, sampled_normals
def enforce_min_spacing(self, points, normals, min_spacing):
if len(points) == 0:
return points, normals
# Use KDTree for efficient nearest neighbor search
from mathutils.kdtree import KDTree
tree = KDTree(len(points))
for i, co in enumerate(points):
tree.insert(co, i)
tree.balance()
accepted_indices = []
rejected = set()
for i, co in enumerate(points):
if i in rejected:
continue
accepted_indices.append(i)
# Find points within min_spacing
nearby = tree.find_range(co, min_spacing)
for (co_found, index, dist) in nearby:
if index > i:
rejected.add(index)
accepted_points = points[accepted_indices]
accepted_normals = normals[accepted_indices]
print(f"After enforcing min spacing, {len(accepted_points)} points remain.")
return accepted_points, accepted_normals
Explanation of New Features
Rotation Randomization and Alignment Options
Added align_to_normal boolean property to determine if objects should align to the surface normal.
Added random_rotation boolean property to enable random rotation around the Z-axis.
Added rotation_offset property to allow users to specify a rotation offset in degrees for X, Y, Z axes.
Implemented align_object method to handle the alignment based on the normal.
Multiple Models Support
Added models_collection pointer property to specify a collection containing models to scatter.
The operator now checks for valid mesh objects within the collection.
During scattering, it randomly selects a model from the collection for each instance.
Weight Painting Influence
Added use_vertex_group and vertex_group_name properties to allow the use of a vertex group.
Modified the face area calculation to multiply by the average weight of the face vertices.
Faces with zero weight are excluded from the scattering process.
Instances for Better Performance
Added use_instances boolean property to choose between instances and full copies.
If use_instances is enabled, the operator creates instances linked to the original object data.
This is more memory-efficient and improves performance for large numbers of scattered objects.
Random Seed for Repeatability
Added random_seed property to allow users to specify the seed for the random number generator.
Both numpy.random and Python's random module seeds are set for consistent results.
User Interface Enhancements
Exposed critical scattering parameters as operator properties, allowing users to adjust them through the UI.
Properties include density, min_spacing, scale, scale_random, and others.
How to Use the Enhanced Operator
Set the Target Mesh: Select the mesh object you want to scatter objects onto.
Set the Models Collection: Create a collection containing the models you wish to scatter and specify it in the operator's properties.
Adjust Parameters: Before running the operator, adjust the scattering parameters to your liking.
Density: Number of points to scatter.
Minimum Spacing: Minimal distance between scattered objects.
Scale and Randomness: Control the size of scattered objects and how much their size can vary.
Alignment and Rotation: Choose whether to align to the surface normal and apply random rotation.
Vertex Group Influence: If desired, create a vertex group on the mesh to influence scatter density.
Run the Operator: Execute the operator to scatter the objects with the specified settings.
Notes
This operator creates a new collection named "Scattered Objects" and places all instances within it.
To improve performance when scattering a large number of objects, it's recommended to enable the use_instances option.
Make sure the models in the models_collection are properly prepared for instancing, with origins set correctly.
If you experience performance issues in the viewport after scattering, consider using proxy objects or display as bounds.
Now, your scattering operator is equipped with advanced features, giving you greater control and flexibility in your asset scattering tasks within Blender.
Disclaimer: This code is provided as an example and may require additional context or adjustments to work within your specific Blender setup or version. Always make sure to test new scripts in a safe environment.