Created
June 10, 2020 16:31
-
-
Save alexschreyer/b83a9dd47936c5ee6c96969fd556a304 to your computer and use it in GitHub Desktop.
Randomize object placement on faces in SketchUp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Randomize object placement on faces | |
# Select one component and at least one ungrouped face to start | |
mod = Sketchup.active_model # Open model | |
ent = mod.entities # All entities in model | |
sel = mod.selection # Current selection | |
num = 20 # Number of items to place on each face | |
max_rot = 360 # Rotation max. degrees | |
scale_var = 0.5 # Size variation | |
# Create a new layer/tag so that we can turn the created copies on/off | |
# Also add everything to a group to keep inspector manageable | |
clayer = mod.layers.add('Random Items') | |
group = mod.entities.add_group | |
group.layer = clayer | |
# Get the first component's definition from our selection | |
comp = sel.grep( Sketchup::ComponentInstance )[0].definition | |
# Get all the faces in our selection | |
faces = sel.grep( Sketchup::Face ) | |
# Iterate through all selected, ungrouped faces | |
faces.each_with_index { |e,i| | |
# Get bounding box and normal vector for face | |
bbox = e.bounds | |
norm = e.normal | |
# Place copies on each face | |
num.times { | |
# Get a random point on the face's plane - based on bounding box | |
pt = Geom::Point3d.new | |
pt.x = bbox.min.x + rand * bbox.width | |
pt.y = bbox.min.y + rand * bbox.height | |
pt.z = bbox.min.z + rand * bbox.depth | |
plpt = pt.project_to_plane(e.plane) | |
# Some points will be off the face, ignore those. Otherwise... | |
if ( e.classify_point(plpt) == Sketchup::Face::PointInside ) | |
# Scale copies randomly | |
t_sca = Geom::Transformation.scaling plpt, ( 1 - scale_var / 2 + rand * scale_var ) | |
# Use the following if you need to align things normal to face: | |
t_loc = Geom::Transformation.new plpt, norm | |
t_rot = Geom::Transformation.rotation plpt, norm, (rand * max_rot).degrees | |
# Use the following if things need to point up: | |
# t_loc = Geom::Transformation.new plpt, [0,0,1] | |
# t_rot = Geom::Transformation.rotation plpt, [0,0,1] , (rand * max_rot).degrees | |
# Now place the copy and move it to the new layer | |
new = group.entities.add_instance comp, (t_rot * t_sca * t_loc) | |
new.layer = clayer | |
# Life is always better with some feedback while SketchUp works | |
Sketchup.status_text = "Adding objects | Done with face #{(i+1).to_s}" | |
end | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment