Question

https://developers.google.com/sketchup/docs/ourdoc/entities

I want to add an array of entities to an entities collection, but the entities collection (as you can see in the reference) requires i add them by type, ie. entities.add_edge(). What's the best way to do this for an array of mixed types?

Here's a snippet - the second last line isnt valid (a generic .add doesnt exist)

layers.each do |layer|
    layerEnts = []
    entities.each { |e| layerEnts << e if layer == (e.layer) }
    layerGroup = entities.add_group
    layerGroup.name = layer.name
    layerGroup.entities.add(layerEnts)
end
Was it helpful?

Solution

You can call methods in a dynamic way using send

Assuming that you can get the type doing layer.type this should solve your problem.

layerEnts.each do |l|
  type = l.typename.downcase
  layerGroup.entities.send("add_#{type}".to_sym, l)
end

UPDATE: Just reading the documentation seems that there is actually a method to get the type, it's typename and seems it's camel cased so we need to downcase it.

https://developers.google.com/sketchup/docs/ourdoc/entity#typename


Also it seems there are types with more than one word so you need some underscores in there. Here is a solution

layerEnts.each do |l|
  type = l.typename.gsub(/(.)([A-Z])/,'\1_\2').downcase
  layerGroup.entities.send("add_#{type}".to_sym, l)
end

OTHER TIPS

When you add a group you can specify a set of existing entities to be added to that group.

layers.each do |layer|
  layerEnts = []
  entities.each { |e| layerEnts << e if layer == (e.layer) }
  layerGroup = entities.add_group(layerEnts)
  layerGroup.name = layer.name
end

But note! Moving entities around between contexts like this is prone to crash if done incorrectly - and doing it incorrectly is easy to do - SU doesn't do much safeguarding here.

Only ever use entities.add_group(ents) when entities is the model.active_entities and ents are entities within the model.active_entities.

And, I'm not 100% sure here, there might be issues if you try to group a face without also also adding it's edges. (This would need testing.)

If your plugin created the geometry you want to group then you would be better of adding them directly to the target group - instead of adding them into one context and then grouping then later on. It avoids so many potential issues, crashes - and is much faster.

If you described the more abstract purpose of your plugin or feature it might be that the answer is something completely different.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top