How to get all visible entities?

Here is my code to get all visible entities:

def get_all_visible_entities() 
	begin 
		@visited = {}
		@visible_entities = {}
		all_entities = Sketchup.active_model.entities

		def get_visible_entities(all_entities)
			all_entities.each do |entity|
				if entity.is_a?(Sketchup::Group) || entity.is_a?(Sketchup::ComponentInstance) 
					next if @visited[entity.definition]
					@visited[entity.definition] = true
					entities_inside = entity.definition.entities
					get_visible_entities(entities_inside)	

				elsif entity.visible? && entity.layer.visible?
					@visible_entities[entity] = true 
				end
			end  
		end

		get_visible_entities(all_entities)
		return @visible_entities.keys
	rescue => e
		puts e.inspect 
		puts e.backtrace 
	end
end
	
get_all_visible_entities()

In many cases, I call my function and it can’t get any entities although the entities is visible. That is because entity.layer.visible? return False while that entity is displaying. This confuses me, so how can I check the visibility of entity?

Here is the test scene: visibility.skp (10.9 MB)

FYI … you do not need a beginend within a method definition. The def acts as the block opener:

def my_method(arg1, argd2)
  #
  # method code
  #
rescue => error
  # error handling
else
  # when no errors happen
ensure
  # always do this
end # of my_method

I find nested methods within methods to be poor coding practice.

Your methods should be within a module or a class anyway and such methods can call other methods in the same scope.

entity.layer.visible? is a entity property. If the rendering options for the model (or the current scene) is set to show hidden entities then you will see them with a hatch pattern and dashed edges.

See:

I would need to double check, but with the addition of layer/tag folders, I think I created a hash with layer objects as the key, and ‘walked up’ the folder structure to determine if a layer was visible, and the ‘actual’ layer visibility was the value in the hash. I think I walked ‘up’ because a folder may not contain any layers, not sure.

You may need to add code similar to that…

Thank you very much for your guidance!

There’s a misunderstood here but Greg already gave me the solution. Thank you for your suggestion about writing code!