Delete empty geometry layers
This script delete geometry layers that contains no surfaces.
1from p3dsdk import *
2
3
4def delete_layer_if_empty(layer: GeometryLayer):
5 sub_layers = layer.list_child_layers(recursive=False)
6 for s in sub_layers:
7 delete_layer_if_empty(s)
8
9 have_surfaces = len(layer.list_surfaces()) > 0
10 have_sub_layers = len(layer.list_child_layers(recursive=False)) > 0
11
12 # Delete the layer if it contains no surfaces and no sub_layers
13 # (they are already deleted if they were empty)
14 if not have_surfaces and not have_sub_layers:
15 layer.remove(True)
16
17
18with CurrentP3DSession(fallback_port=33900) as p3d:
19 model = p3d.data.list_models()[0] # Get the first model
20 layers = model.list_geometry_layers(recursive=False)
21 for layer in layers[1:]:
22 delete_layer_if_empty(layer)
23
24 layers_count = len(model.list_geometry_layers(recursive=False))
25 # if there is at least one layer not empty, check if the first layer is empty and deletable
26 if layers_count > 1:
27 delete_layer_if_empty(layers[0])
28 else: # delete only the empty sublayers of the remaining layer
29 sub_layers = layers[0].list_child_layers(recursive=False)
30 for s in sub_layers:
31 delete_layer_if_empty(s)
32
delete_layer_if_empty()
is a post-order recursive function.
It does the following:
Recurse into direct sub layers of the layer.
Delete the layer if it contains no surfaces and no sub layers (i.e. it is empty). The empty child layers are already removed by the recursive step.