Thanks TIG for the snippets - perfect.
For others, this is the code I have so far. It has lots of room for improvement, and I'm happy for others to improve, extend, and post back here.
I assigned attributes to each face with a key/value of faceid/x.
model = Sketchup.active_model
entities = model.entities
selection = model.selection
#Define array
faces = []
# choose either the selection, or the active model
if model.selection.empty?
# UI.messagebox "You have nothing selected. This will color all faces that are not grouped."
entities = model.active_entities
else
entities = model.selection
end
#go through every entity, and if it is a face then add it to the faces array
entities.each do |e|
faces.push e if e.is_a? Sketchup;;Face
end
#Debug; how many faces are going to be shaded
#UI.messagebox "No of faces in model/selection; " + faces.length.to_s
#get the materials from a csv file which has corresonding faceids
@filepath=UI.openpanel("Face Color Code Choose File...","","*.csv")
if not @filepath
puts "FACE COLOR CODE FILE - CANCELED."
@go_on = false
Sketchup.send_action("selectSelectionTool;")
return nil
else
@go_on = true
end
if @go_on
#read the file into the instance variable @alltext
@alltext=IO.readlines(@filepath)
#debug; how many lines/rows were in the file?
#UI.messagebox "Number of rows in file is " + @alltext.length.to_s
faces.each do |m|
@currentfaceid = m.get_attribute("fn","faceid",nil)
#UI.messagebox "@currentfaceid = " + @currentfaceid.to_s
#UI.messagebox @face
#now apply the material to each face
0.upto(@alltext.length-1) do |i| #beginning with 0
line = @alltext[i]
if line
line.strip! #remove whitespace
line.chomp! #remove carriage returns
# we'll assume csv file in the format 'faceid,material_name'
# e.g. "...\n6,red\n7,green\n..."
if line and @currentfaceid == line.split(",")[0] # e.g. "6"
#Apply the material
@matchedcolor = line.split(",")[1]
m.material = @matchedcolor # set material - e.g. "red"
m.back_material = @matchedcolor # set material - e.g. "red"
### you can add extra tests, make materials if not existing etc etc
break ### we leave the do loop as we have a 'hit'.
end
end
end
end
end
The contents of the CSV file, for reference:
faceid,material
1,CadetBlue
2,Aqua
3,DarkOrange
4,LawnGreen
5,Red
6,PowderBlue
7,Yellow
Things that need improvement:
make it executable script from a menu
make it work on groups and not just faces
pass the contents of the CSV into an array once rather than reading the file over and over
and plenty of more things I'm sure!