|
| 1 | +# This example shows how to create and update a custom mechanism built from an array of objects using one API call |
| 2 | +# You can quickly update an array of objects in one shot without penalizing simulation performance |
| 3 | +import time |
| 4 | +import math |
| 5 | +from robodk import * # RoboDK API |
| 6 | +from robolink import * # Robot toolbox |
| 7 | + |
| 8 | +# Start the RoboDK API |
| 9 | +RDK = Robolink() |
| 10 | + |
| 11 | +# Number of elements |
| 12 | +x_count = 20 |
| 13 | +y_count = 20 |
| 14 | + |
| 15 | +# Spacing between elements |
| 16 | +x_spacing = 40 |
| 17 | +y_spacing = 40 |
| 18 | + |
| 19 | +# Length along X axis |
| 20 | +x_lenth = x_count * x_spacing |
| 21 | + |
| 22 | +# Retrieve the reference box (100x100x100 mm, centered) |
| 23 | +box_ref = RDK.Item("Reference Box", ITEM_TYPE_OBJECT) |
| 24 | + |
| 25 | +# Delete the previous array |
| 26 | +frame_old = RDK.Item("Mechanism Array", ITEM_TYPE_FRAME) |
| 27 | +if frame_old.Valid(): |
| 28 | + frame_old.Delete() |
| 29 | + |
| 30 | +# Frame to place the mechanism |
| 31 | +frame_ref = RDK.AddFrame("Mechanism Array") |
| 32 | + |
| 33 | +# Show as collapsed (less cluttered tree, faster rendering) |
| 34 | +frame_ref.setParam("Tree", "Collapse") |
| 35 | + |
| 36 | +# Create the array of objects based on the model object |
| 37 | +RDK.Render(False) |
| 38 | +box_ref.Copy() |
| 39 | +# Create the objects and scale them |
| 40 | +obj_array = RDK.Paste(frame_ref, x_count * y_count) |
| 41 | +idx = 0 |
| 42 | +for i in range(x_count): |
| 43 | + for j in range(y_count): |
| 44 | + obj_array[idx].Scale([0.05, 0.05, 2]) |
| 45 | + obj_array[idx].setName("piston " + str(idx)) |
| 46 | + obj_array[idx].setVisible(True) |
| 47 | + idx = idx + 1 |
| 48 | + |
| 49 | +RDK.Render(True) |
| 50 | + |
| 51 | +# Random function to calculate a Z position based on X,Y and time |
| 52 | +def z_func(x,y, t): |
| 53 | + """x and y are the coordinates on X and Y of the parent frame, in mm. t is time in seconds.""" |
| 54 | + z = 100 * math.sin(2 * math.pi * math.sqrt(x*x + y*y) * (1/x_lenth) + t/6 ) |
| 55 | + return z |
| 56 | + |
| 57 | +def update_mechanism(t): |
| 58 | + """Update the mechanism for the time t in seconds""" |
| 59 | + obj_poses = [] |
| 60 | + for i in range(x_count): |
| 61 | + x = i*x_spacing |
| 62 | + for j in range(y_count): |
| 63 | + y = j*y_spacing |
| 64 | + z = z_func(x, y, t) |
| 65 | + pose = robomath.transl(x,y,z) |
| 66 | + obj_poses.append(pose) |
| 67 | + |
| 68 | + RDK.setPoses(obj_array, obj_poses) |
| 69 | + |
| 70 | +# Infinite loop to update the mechanism |
| 71 | +while True: |
| 72 | + # Retrieve RoboDK simulation time: |
| 73 | + t = RDK.SimulationTime() |
| 74 | + |
| 75 | + # Update the mechanism |
| 76 | + print("Updating mechanism at time frame: " + str(t)) |
| 77 | + update_mechanism(t) |
| 78 | + |
| 79 | + # Wait a bit before running the next frame |
| 80 | + time.sleep(0.05) |
| 81 | + |
0 commit comments