Hello cyrilp,
Please check this script. It splits the active (default) mesh model in the active chunk by NxN grid (N will be asked on script start) in XY plane (as if you are looking from Top on the mesh).
import Metashape
def split_mesh():
doc = Metashape.app.document
chunk = doc.chunk
if not chunk:
print("Empty project, script aborted")
return 0
if not chunk.model:
print("No active mesh model in chunk, script aborted")
return 0
step = Metashape.app.getInt("Please input number of tiles per side:", 5)
if step <= 0:
print("Wrong number! Value should be positive. Script aborted.")
return 0
print("Script started...")
T = chunk.transform.matrix
crs = chunk.crs
if not chunk.shapes:
chunk.shapes = Metashape.Shapes()
chunk.shapes.crs = crs
tiles = chunk.shapes.addGroup()
tiles.label = "Mesh split grid ({:d}x{:d})".format(step, step)
###creating grid
region = chunk.region
corners = list()
for i in range(8): #finding bounding box corners
pos = Metashape.Vector([region.size.x * ((i & 1) - 0.5), 0.5 * region.size.y * ((i & 2) - 1), 0.25 * region.size.z * ((i & 4) - 2)])
pos = region.center + region.rot * pos #coordinates in the internal coordinates
point = crs.project(T.mulp(pos))
corners.append(point)
x_min = min([point.x for point in corners])
x_max = max([point.x for point in corners])
y_min = min([point.y for point in corners])
y_max = max([point.y for point in corners])
x = x_min
y = y_min
x_step = (x_max - x_min) / step
y_step = (y_max - y_min) / step
shape_grid = list()
i = 1
j = 1
while x < x_max:
y = y_min
j = 1
while y < y_max:
shape = chunk.shapes.addShape()
shape.geometry.type = Metashape.Geometry.Type.PolygonType
shape.geometry = Metashape.Geometry.Polygon([Metashape.Vector([x, y]), Metashape.Vector([x+x_step, y]), Metashape.Vector([x+x_step, y+y_step]), Metashape.Vector([x, y+y_step])])
shape.label = str(i) + "/" + str(j)
shape.group = tiles
shape_grid.append(shape)
y += y_step
j += 1
x += x_step
i += 1
###splitting mesh
for shape in chunk.shapes:
shape.boundary_type = Metashape.Shape.BoundaryType.NoBoundary
model = chunk.model
for shape in shape_grid:
shape.boundary_type = Metashape.Shape.BoundaryType.OuterBoundary
task = Metashape.Tasks.DuplicateAsset()
task.clip_to_boundary = True
task.asset_type = Metashape.DataSource.ModelData
task.asset_key = model.key
task.apply(chunk)
chunk.model.label = "Tile " + shape.label
shape.boundary_type = Metashape.Shape.BoundaryType.NoBoundary
chunk.model = model
print("Script finished")
return 1
Metashape.app.addMenuItem("Custom menu/Split mesh in blocks", split_mesh)