Mesh callbacks

Mesh plot objects (e.g. mesh, surface, marching_cubes, texture) can be configured to run backend callback on following events:

  • plt_obj.hover_callback

  • plt_obj.click_callback

[1]:
import numpy as np
import k3d

plot = k3d.plot()
# note: plot must be displayed before mode is set to callback
plot.display()


Nx, Ny = 50, 60
xmin, xmax, ymin, ymax = -3, 3, 0, 3
x = np.linspace(xmin, xmax, Nx, dtype=np.float32)
y = np.linspace(ymin, ymax, Ny, dtype=np.float32)
x, y = np.meshgrid(x, y)
f = np.sin(x**2 + y**2)
plt_surface = k3d.surface(f, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax)
plot += plt_surface
# surface uses model_matrix for xy ranges
M = plt_surface.model_matrix[:3,:3]

def update_label(p):
    global plt_label
    global plt_normal
    global M
    plt_label.text = '\\vec{p} = \\begin{bmatrix} ' + "\\\\".join([str(np.round(v,2)) for v in p['position']]) +' \\end{bmatrix}'
    plt_label.position = p['position']
    plt_normal.origins = p['position']
    plt_normal.vectors = np.linalg.inv(M).dot(p['normal'])*10

plt_surface.hover_callback = update_label

plt_label = k3d.label('', mode='local', color=0x0)
plot += plt_label

plt_normal = k3d.vectors([0,0,0],[0,1,0],color = 0xff0000,head_color = 0xff0000,line_width = 0.01)
plot += plt_normal

plot.mode = 'callback'
[2]:
from matplotlib.tri import Triangulation

# this code is a part of matplotlib trisurf3d_demo
n_radii = 38
n_angles = 46

radii = np.linspace(0.1, 3.0, n_radii, dtype=np.float32)
angles = np.linspace(np.pi, 2*np.pi, n_angles, endpoint=False, dtype=np.float32)[..., np.newaxis]

x = np.append(np.float32(0), (radii*np.cos(angles)).flatten())
y = np.append(np.float32(0), (radii*np.sin(angles)).flatten())
z = np.sin(x**2+y**2) + 0.00001
indices = Triangulation(x,y).triangles.astype(np.uint32)

plt_mesh = k3d.mesh(np.vstack([x,y,z]).T, indices,
                   color_map = k3d.colormaps.basic_color_maps.Jet,
                   attribute=z,
                   color_range = [-1.,1.0],
                   side='double'
                   )
plot += plt_mesh



def update_label2(p):
    global plt_label
    global plt_normal
    global M
    plt_label.text = '\\vec{p} = \\begin{bmatrix} ' + "\\\\".join([str(np.round(v,2)) for v in p['position']]) +' \\end{bmatrix}'
    plt_label.position = p['position']
    plt_normal.origins = p['position']
    plt_normal.vectors = p['normal']

plt_mesh.hover_callback = update_label2
[ ]: