def render(self, _interactive=True): """ """ mv = Plotter( N=2, axes=4 if brainrender.SHOW_AXES else 0, size="full" if brainrender.WHOLE_SCREEN else "auto", pos=brainrender.WINDOW_POS, bg=brainrender.BACKGROUND_COLOR, sharecam=True, ) actors = [] for scene in self.scenes: scene.apply_render_style() actors.append(scene.actors) mv.add(scene.actors) mv.show( actors[0], at=0, zoom=1.15, axes=4 if brainrender.SHOW_AXES else 0, roll=180, interactive=False, ) mv.show(actors[1], at=1, interactive=False) if _interactive: interactive()
class MainWindow(Qt.QMainWindow): def __init__(self, parent=None): Qt.QMainWindow.__init__(self, parent) self.frame = Qt.QFrame() self.vl = Qt.QVBoxLayout() self.vtkWidget = QVTKRenderWindowInteractor(self.frame) self.vl.addWidget(self.vtkWidget) # create renderer and add the actors self.vp = Plotter(qtWidget=self.vtkWidget) self.vp += Cone().rotateX(20) self.vp.show(interactorStyle=0) # set-up the rest of the Qt window button = Qt.QPushButton("My Button makes the cone red") button.setToolTip('This is an example button') button.clicked.connect(self.onClick) self.vl.addWidget(button) self.frame.setLayout(self.vl) self.setCentralWidget(self.frame) self.show() # <--- show the Qt Window def onClose(self): #Disable the interactor before closing to prevent it #from trying to act on already deleted items self.vtkWidget.close() @Qt.pyqtSlot() def onClick(self): self.vp.actors[0].color('red').rotateZ(40) self.vp.interactor.Render()
class Visualization: """ Visualization of a 3D N-Body simulation. """ def __init__(self, simulation: Simulation, max_fps: float, title: str = 'Simulation', size_multiplier: float = 0.02, trail_length: float = 2.0, show_trails: bool = True): self._simulation = simulation self._min_step_time = 1.0 / max_fps # display setup self._plotter = Plotter(interactive=False, title=title, axes=4) # bodies setup sizes = simulation.masses * size_multiplier self._bodies = [ Sphere(pos, r=r, c='black') for pos, r in zip(simulation.positions, sizes) ] self._plotter += self._bodies # trails if show_trails: for body in self._bodies: body.addTrail(alpha=0.3, lw=1, maxlength=trail_length, n=100) self._plotter.show(resetcam=True) def run(self): """ Runs the visualization of the simulation. """ last_timestamp = time.time() for positions, velocities, accelerations in self._simulation.simulate( ): # throttle the simulation delta_time = time.time() - last_timestamp if delta_time < self._min_step_time: time.sleep(self._min_step_time - delta_time) last_timestamp = time.time() # update bodies for body, pos in zip(self._bodies, positions): body.pos(pos) # update display self._plotter.show(resetcam=False)
def export_for_web(self, filepath="brexport.html"): """ This function is used to export a brainrender scene for hosting it online. It saves an html file that can be opened in a web browser to show an interactive brainrender scene """ if not filepath.endswith(".html"): raise ValueError("Filepath should point to a .html file") # prepare settings vedosettings.notebookBackend = "k3d" # Create new plotter and save to file plt = Plotter() plt.add(self.actors) plt = plt.show(interactive=False) plt.camera[-2] = -1 if self.verbose: print( "Ready for exporting. Exporting scenes with many actors might require a few minutes" ) with open(filepath, "w") as fp: fp.write(plt.get_snapshot()) if self.verbose: print( f"The brainrender scene has been exported for web. The results are saved at {filepath}" ) # Reset settings vedosettings.notebookBackend = None self.jupyter = False
def __init__(self, parent=None): Qt.QMainWindow.__init__(self, parent) self.frame = Qt.QFrame() self.vl = Qt.QVBoxLayout() self.vtkWidget = QVTKRenderWindowInteractor(self.frame) self.vl.addWidget(self.vtkWidget) vp = Plotter(qtWidget=self.vtkWidget, axes=2, N=2) cn = Cone() cc = Cube().pos(1, 1, 1).color("pink") ss = Torus() vp.show(cn, cc, at=0) vp.show(ss, at=1, viewup="z", interactorStyle=0) self.start(vp)
def render(self, _interactive=True, **kwargs): """ :param _interactive: (Default value = True) :param **kwargs: """ camera = kwargs.pop("camera", None) for scene in self.scenes: scene.apply_render_style() if camera is None: if scene.atlas.default_camera is None: scene_camera = brainrender.CAMERA else: scene_camera = scene.atlas.default_camera else: if camera: scene_camera = camera else: scene_camera = None if scene_camera is not None: set_camera(scene, scene_camera) mv = Plotter( N=self.N, axes=4 if brainrender.SHOW_AXES else 0, size="full" if brainrender.WHOLE_SCREEN else "auto", sharecam=True, bg=brainrender.BACKGROUND_COLOR, ) actors = [] for i, scene in enumerate(self.scenes): scene.apply_render_style() actors.append(scene.actors) mv.add(scene.actors) for i, scene.actors in enumerate(actors): mv.show(scene.actors, at=i, interactive=False) print("Rendering complete") if _interactive: interactive()
def __init__(self, parent=None): Qt.QMainWindow.__init__(self, parent) self.frame = Qt.QFrame() self.vl = Qt.QVBoxLayout() self.vtkWidget = QVTKRenderWindowInteractor(self.frame) self.vl.addWidget(self.vtkWidget) vp = Plotter(qtWidget=self.vtkWidget) vp += Cone() vp.show(interactorStyle=0) # create renderer and add the actors # set-up the rest of the Qt window self.frame.setLayout(self.vl) self.setCentralWidget(self.frame) self.show() # <--- show the Qt Window
class MainWindow(Qt.QMainWindow): def __init__(self, parent=None): Qt.QMainWindow.__init__(self, parent) self.frame = Qt.QFrame() self.layout = Qt.QVBoxLayout() self.vtkWidget = QVTKRenderWindowInteractor(self.frame) # Create renderer and add the vedo objects and callbacks self.vp = Plotter(qtWidget=self.vtkWidget) self.id1 = self.vp.addCallback("mouse click", self.onMouseClick) self.id2 = self.vp.addCallback("key press", self.onKeypress) self.vp += Cone().rotateX(20) self.vp.show() # <--- show the vedo rendering # Set-up the rest of the Qt window button = Qt.QPushButton("My Button makes the cone red") button.setToolTip('This is an example button') button.clicked.connect(self.onClick) self.layout.addWidget(self.vtkWidget) self.layout.addWidget(button) self.frame.setLayout(self.layout) self.setCentralWidget(self.frame) self.show() # <--- show the Qt Window def onMouseClick(self, evt): printc("You have clicked your mouse button. Event info:\n", evt, c='y') def onKeypress(self, evt): printc("You have pressed key:", evt.keyPressed, c='b') @Qt.pyqtSlot() def onClick(self): printc("..calling onClick") self.vp.actors[0].color('red').rotateZ(40) self.vp.interactor.Render() def onClose(self): #Disable the interactor before closing to prevent it #from trying to act on already deleted items printc("..calling onClose") self.vtkWidget.close()
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self, parent=None): QtWidgets.QMainWindow.__init__(self, parent) self.setupUi(self) self.vtkWidget = QVTKRenderWindowInteractor(self) self.vtkLayout.addWidget(self.vtkWidget) self.plt = Plotter(qtWidget=self.vtkWidget, axes=1) self.plt += load(datadir + 'shark.ply').c('cyan') self.plt.show(interactorStyle=0) def onClose(self): print( "Disable the interactor before closing to prevent it from trying to act on a already deleted items" ) self.vtkWidget.close()
class MainWindow(Qt.QMainWindow): def __init__(self, parent=None): Qt.QMainWindow.__init__(self, parent) self.frame = Qt.QFrame() self.layout = Qt.QVBoxLayout() self.vtkWidget = QVTKRenderWindowInteractor(self.frame) # Create vedo renderer and add objects and callbacks self.vp = Plotter(qtWidget=self.vtkWidget) self.cbid = self.vp.addCallback("key press", self.onKeypress) self.imgActor = Picture( "https://icatcare.org/app/uploads/2018/07/Helping-your-new-cat-or-kitten-settle-in-1.png" ) self.text2d = Text2D("Use slider to change contrast") self.slider = Qt.QSlider(1) self.slider.valueChanged.connect(self.onSlider) self.layout.addWidget(self.vtkWidget) self.layout.addWidget(self.slider) self.frame.setLayout(self.layout) self.setCentralWidget(self.frame) self.vp.show(self.imgActor, self.text2d, mode='image') # build the vedo rendering self.show() # show the Qt Window def onSlider(self, value): self.imgActor.window(value * 10) # change image contrast self.text2d.text(f"window level is now: {value*10}") self.vp.render() def onKeypress(self, evt): printc("You have pressed key:", evt.keyPressed, c='b') if evt.keyPressed == 'q': self.vp.close() self.vtkWidget.close() exit() def onClose(self): self.vtkWidget.close()
def draw(m, backend=False, **kwargs): """Visualize meshes.""" import vedo vedo.embedWindow(backend) from vedo import Plotter, UGrid vp = Plotter() grid = None with tempfile.NamedTemporaryFile() as tmp: m.save(tmp.name + '.vtk', encode_cell_data=False, encode_point_data=True, **kwargs) grid = UGrid(tmp.name + '.vtk') # save these for further use grid.show = lambda: vp.show([grid.tomesh()]).close() grid.plotter = vp return grid
def export(self, savepath): """ Exports the scene to a .html file for online renderings. :param savepath: str, Path to a .html file to save the export """ logger.debug(f"Exporting scene to {savepath}") _backend = self.backend if not self.is_rendered: self.render(interactive=False) path = Path(savepath) if path.suffix != ".html": raise ValueError("Savepath should point to a .html file") # prepare settings vsettings.notebookBackend = "k3d" # Create new plotter and save to file plt = Plotter() plt.add(self.renderables) plt = plt.show(interactive=False) plt.camera[-2] = -1 with open(path, "w") as fp: fp.write(plt.get_snapshot()) print( f"The brainrender scene has been exported for web. The results are saved at {path}" ) # Reset settings vsettings.notebookBackend = None self.backend = _backend return str(path)
def demo3d_hanoi(**kwargs): nr_disks = kwargs.get("nr_disks", 5) interactive = kwargs.get("interactive", 1) hanoi = Hanoi(nr_disks) tower_states = list([hanoi.towers]) for _ in hanoi.moves(): tower_states.append(hanoi.towers) vp = Plotter(axes=0, interactive=0, bg="w", size=(800, 600)) vp.camera.SetPosition([18.5, -20.7, 7.93]) vp.camera.SetFocalPoint([3.0, 0.0, 2.5]) vp.camera.SetViewUp([-0.1, +0.17, 0.977]) cols = makePalette("red", "blue", hanoi.nr_disks + 1, hsv=True) disks = { hanoi.nr_disks - i: Cylinder(pos=[0, 0, 0], r=0.2 * (hanoi.nr_disks - i + 1), c=cols[i]) for i in range(hanoi.nr_disks) } for k in disks: vp += disks[k] vp += Box(pos=(3.0, 0, -.5), length=12.0, width=4.0, height=0.1) vp.show(zoom=1.2) printc("\n Press q to continue, Esc to exit. ", c="y", invert=1) pb = ProgressBar(0, len(tower_states), 1, c="b", ETA=False) for t in pb.range(): pb.print() state = tower_states[t] for tower_nr in range(3): for i, disk in enumerate(state[tower_nr]): disks[disk].pos([3 * tower_nr, 0, i + 0.5]) vp.show(resetcam=0, interactive=interactive, rate=10) vp.show(resetcam=0, interactive=1)
"""Mesh smoothing with two different methods""" from vedo import Plotter, dataurl plt = Plotter(N=2) # Load a mesh and show it vol = plt.load(dataurl + "embryo.tif") m0 = vol.isosurface().normalize().lw(0.1).c("violet") plt.show(m0, __doc__ + "\nOriginal Mesh:", at=0) plt.background([0.8, 1, 1], at=0) # set first renderer color # Smooth the mesh m1 = m0.clone().smooth(niter=20).color("lg") plt.show(m1, "Polygons are smoothed:", at=1, viewup='z', zoom=1.5, interactive=True).close()
# An example simulation of N particles scattering on a charged target. # See e.g. https://en.wikipedia.org/wiki/Rutherford_scattering vp = Plotter(title="Particle Simulator", bg="black", axes=0, interactive=False) vp += Cube(c="white").wireframe(1) # a wireframe cube sim = ParticleSim(dt=5e-6, iterations=200) sim.add_particle((-0.4, 0, 0), color="w", charge=3e-6, radius=0.01, fixed=True) # the target positions = np.random.randn(500, 3) / 60 # generate a beam of 500 particles for p in positions: p[0] = -0.5 # Fix x position. Their charge are small/negligible compared to target: sim.add_particle(p, charge=0.01e-6, mass=0.1e-6, vel=(1000, 0, 0), negligible=True) sim.simulate() vp.show(interactive=True, resetcam=False)
"""Mouse click and other type of events will trigger a call to a custom function""" from vedo import printc, Plotter, Mesh, datadir printc("Click object to trigger a function call", invert=1) # callback functions def onLeftClick(event): if not event.actor: return printc("Left button pressed on", [event.actor], c=event.actor.color()) # printc('full dump of event:', event) def onEvent(event): printc(event.name, 'happened at mouse position', event.picked2d) ###################### tea = Mesh(datadir + "teapot.vtk").c("gold") mug = Mesh(datadir + "mug.ply").rotateX(90).scale(8).pos(2, 0, -.7).c("silver") plt = Plotter(axes=11) plt.addCallback('LeftButtonPress', onLeftClick) plt.addCallback('Interaction', onEvent) # mouse dragging triggers this plt.show(tea, mug, __doc__)
"""Setting illumination properties: ambient, diffuse, specular, specularPower, specularColor. """ from vedo import Plotter, Mesh, dataurl plt = Plotter(axes=1) ambient, diffuse, specular = 0.1, 0., 0. specularPower, specularColor = 20, 'white' apple = Mesh(dataurl + 'apple.ply').normalize().c('gold') for i in range(8): s = apple.clone().pos((i % 4) * 2.2, int(i < 4) * 3, 0) #s.phong() s.flat() # modify the default with specific values s.lighting('default', ambient, diffuse, specular, specularPower, specularColor) #ambient += 0.125 diffuse += 0.125 specular += 0.125 plt += s plt += __doc__ plt.show().close()
class VirtualKeyboard: def __init__(self, songname=''): self.KB = dict() self.vp = None self.rightHand = None self.leftHand = None self.vpRH = None self.vpLH = None self.playsounds = True self.verbose = True self.songname = songname self.t0 = 0 # keep track of how many seconds to play self.dt = 0.1 self.speedfactor = 1 self.engagedfingersR = [False] * 6 # element 0 is dummy self.engagedfingersL = [False] * 6 self.engagedkeysR = [] self.engagedkeysL = [] self.build_keyboard() ################################################################################ def makeHandActor(self, f=1): a1, a2, a3, c = (10 * f, 0, 0), (0, 7 * f, 0), (0, 0, 3 * f), (.7, 0.3, 0.3) palm = Ellipsoid(pos=(0, -3, 0), axis1=a1, axis2=a2, axis3=a3, alpha=0.6, c=c) wrist = Box(pos=(0, -9, 0), length=6 * f, width=5, height=2, alpha=0.4, c=c) arm = Assembly([palm, wrist]) f1 = Cylinder((-2, 1.5, 0), axis=(0, 1, 0), height=5, r=.8 * f, c=c) f2 = Cylinder((-1, 3, 0), axis=(0, 1, 0), height=6, r=.7 * f, c=c) f3 = Cylinder((0, 4, 0), axis=(0, 1, 0), height=6.2, r=.75 * f, c=c) f4 = Cylinder((1, 3.5, 0), axis=(0, 1, 0), height=6.1, r=.7 * f, c=c) f5 = Cylinder((2, 2, 0), axis=(0, 1, 0), height=5, r=.6 * f, c=c) self.vp += [arm, f1, f2, f3, f4, f5] # add actors to internal list return [arm, f1, f2, f3, f4, f5] def build_RH(self, hand): #########################Build Right Hand self.rightHand = hand f = utils.handSizeFactor(hand.size) self.vpRH = self.makeHandActor(f) for limb in self.vpRH: # initial x positions are superseded later limb.x(limb.x() * 2.5) limb.addPos([16.5 * 5 + 1, -7.5, 3]) def build_LH(self, hand): ########################Build Left Hand self.leftHand = hand f = utils.handSizeFactor(hand.size) self.vpLH = self.makeHandActor(f) for limb in self.vpLH: limb.x(limb.x() * 2.5) limb.addPos([16.5 * 3 + 1, -7.5, 3]) #######################################################Build Keyboard def build_keyboard(self): nts = ("C", "D", "E", "F", "G", "A", "B") tol = 0.12 keybsize = 16.5 # in cm, span of one octave wb = keybsize / 7 nr_octaves = 7 span = nr_octaves * wb * 7 self.vp = Plotter(title='PianoPlayer ' + __version__, axes=0, size=(1400, 700), bg='cornsilk', bg2='lb') #wooden top and base self.vp += Box(pos=(span / 2 + keybsize, 6, 1), length=span + 1, height=3, width=5).texture('wood1') self.vp += Box(pos=(span / 2 + keybsize, 0, -1), length=span + 1, height=1, width=17).texture('wood1') self.vp += Text('PianoPlayer ^' + __version__ + " ", pos=(18, 5., 2.3), depth=.5, c='silver', italic=0.8) leggio = Box(pos=(span / 1.55, 8, 10), length=span / 2, height=span / 8, width=0.08, c=(1, 1, 0.9)).rotateX(-20) self.vp += leggio.texture('paper1') self.vp += Text('Playing:\n' + self.songname[-30:].replace('_', "\\_"), font="Theemim", vspacing=3, depth=0.04, s=1.35, c='k', italic=0.5).rotateX(70).pos([55, 10, 6]) for ioct in range(nr_octaves): for ik in range(7): #white keys x = ik * wb + (ioct + 1) * keybsize + wb / 2 tb = Box(pos=(x, -2, 0), length=wb - tol, height=1, width=12, c='white') self.KB.update({nts[ik] + str(ioct + 1): tb}) self.vp += tb if not nts[ik] in ("E", "B"): #black keys tn = Box(pos=(x + wb / 2, 0, 1), length=wb * .6, height=1, width=8, c='black') self.KB.update({nts[ik] + "#" + str(ioct + 1): tn}) self.vp += tn cam = dict(pos=(110, -51.1, 89.1), focalPoint=(81.5, 0.531, 2.82), viewup=(-0.163, 0.822, 0.546), distance=105, clippingRange=(41.4, 179)) self.vp.show(interactive=0, camera=cam, resetcam=0) ##################################################################### def play(self): printc('Press space to proceed by one note', c=1) printc('Press Esc to exit.', c=1) if self.rightHand: self.engagedkeysR = [False] * len(self.rightHand.noteseq) self.engagedfingersR = [False] * 6 # element 0 is dummy if self.leftHand: self.engagedkeysL = [False] * len(self.leftHand.noteseq) self.engagedfingersL = [False] * 6 t = 0.0 while True: if self.rightHand: self._moveHand(1, t) if self.leftHand: self._moveHand(-1, t) if t > 1000: break t += self.dt # absolute time flows if self.verbose: printc('End of note sequence reached.') self.vp.keyPressFunction = None # disable observer ################################################################### def _moveHand(self, side, t): ############# runs inside play() loop if side == 1: c1, c2 = 'tomato', 'orange' engagedkeys = self.engagedkeysR engagedfingers = self.engagedfingersR H = self.rightHand vpH = self.vpRH else: c1, c2 = 'purple', 'mediumpurple' engagedkeys = self.engagedkeysL engagedfingers = self.engagedfingersL H = self.leftHand vpH = self.vpLH for i, n in enumerate(H.noteseq): ##################### start, stop, f = n.time, n.time + n.duration, n.fingering if isinstance(f, str): continue if f and stop <= t <= stop + self.dt and engagedkeys[ i]: #release key engagedkeys[i] = False engagedfingers[f] = False name = nameof(n) krelease(self.KB[name]) frelease(vpH[f]) if hasattr(self.vp, 'interactor'): self.vp.render() for i, n in enumerate(H.noteseq): ##################### start, stop, f = n.time, n.time + n.duration, n.fingering if isinstance(f, str): print('Warning: cannot understand lyrics:', f, 'skip note', i) continue if f and start <= t < stop and not engagedkeys[ i] and not engagedfingers[f]: # press key if i >= len(H.fingerseq): return engagedkeys[i] = True engagedfingers[f] = True name = nameof(n) if t > self.t0 + self.vp.clock: self.t0 = t self.vp.show(interactive=False, resetcam=False) for g in [1, 2, 3, 4, 5]: vpH[g].x(side * H.fingerseq[i][g]) vpH[0].x(vpH[3].x() ) # index 0 is arm, put it where middle finger is fpress(vpH[f], c1) kpress(self.KB[name], c2) if self.verbose: msg = 'meas.' + str(n.measure) + ' t=' + str(round(t, 2)) if side == 1: printc(msg, '\t\t\t\tRH.finger', f, 'hit', name, c='b') else: printc(msg, '\tLH.finger', f, 'hit', name, c='m') if self.playsounds: self.vp.show(interactive=False, resetcam=False) playSound(n, self.speedfactor, wait=True) if hasattr(self.vp, 'interactor'): self.vp.interactor.Start() else: self.vp.show(interactive=1, resetcam=0)
"""delaunay2D() and cellCenters() functions""" from vedo import Plotter, delaunay2D, Points, datadir vp = Plotter(shape=(1, 2), interactive=0) d0 = vp.load(datadir + "250.vtk").rotateY(-90).legend("original mesh") coords = d0.points() # get the coordinates of the mesh vertices # Build a mesh starting from points in space # (points must be projectable on the XY plane) d1 = delaunay2D(coords, mode='fit') d1.color("r").wireframe(True).legend("delaunay mesh") cents = d1.cellCenters() ap = Points(cents).legend("cell centers") vp.show(d0, d1, __doc__, at=0) # NB: d0 and d1 are slightly different vp.show(d1, ap, at=1, interactive=1)
from vedo import Plotter, Plane, datadir vp = Plotter() cow = vp.load(datadir + "cow.vtk", c="grey").scale(4).rotateX(-90) vp += Plane(pos=[0, -3.6, 0], normal=[0, 1, 0], sx=20).texture("grass") vp.show(viewup='y', interactive=0) # vp.light() returns a vtkLight object with focal Point, fp, to mesh cow # fp can also be explicitly set as fp=[x,y,z] l = vp.addLight(pos=[-6, 6, 6], focalPoint=cow, deg=12, showsource=1) # can be switched on/off this way #l.SwitchOff() vp.show(interactive=1)
"""Record and playback camera movements and other events \rightarrow Move the cube around, press 1, and finally press q""" from vedo import Cube, Plotter plt1 = Plotter(axes=1, interactive=0, title="recording window") evts = plt1.show(Cube(), __doc__).record() # print("Events:", evts) # a simple string (also saved as .vedo_recorded_events.log) plt2 = Plotter(axes=1, interactive=0, title="playback window", pos=(1100,0)) plt2.show(Cube(), "...now playing!").play(evts).interactive().close()
txt = Text2D('..' + data.filename[-30:], font='MonospaceTypewriter') plt.show(vol, msh, sb, box, txt, at=index, interactorStyle=6) def func(widget, event): i = int(widget.GetRepresentation().GetValue()) plt.renderer = widget.GetCurrentRenderer() plt.resetcam = False msh = vol.zSlice(i).lighting('off') msh.pointColors(cmap=cmaps[index], vmin=vmin, vmax=vmax) plt.remove(visibles[0], render=False) if 0 < i < dims[2]: zlev = zb[1] / (zb[1] - zb[0]) * i + zb[0] plt.add([msh, sb.z(zlev)]) visibles[0] = msh return func ###################################################################### plt = Plotter(shape=(1, 3), sharecam=False, bg2='lightcyan') for index, data in enumerate(volumes): plt.addSlider2D(slicerfunc(index, data), 0, data.dimensions()[2], value=0, pos=(sliderstart, sliderstop)) printc("Right click to rotate, use slider to slice along z.", box='-') plt.show(interactive=True)
# Check to see if the spheres are colliding for ij in hitlist: s1, s2 = divmod(ij, Nsp) # decode the spheres pair (s1,s2) colliding hitlist.remove(s2 * Nsp + s1) # remove symmetric (s2,s1) pair from list R12 = Pos[s2] - Pos[s1] nR12 = np.linalg.norm(R12) d12 = Radius[s1] + Radius[s2] - nR12 tau = R12 / nR12 DR0 = d12 * tau x1 = Mass[s1] / (Mass[s1] + Mass[s2]) x2 = 1 - x1 # x2 = Mass[s2]/(Mass[s1]+Mass[s2]) Pos[s1] -= x2 * DR0 Pos[s2] += x1 * DR0 DV0 = 2 * dot(Vel[s2] - Vel[s1], tau) * tau Vel[s1] += x2 * DV0 Vel[s2] -= x1 * DV0 # Update the location of the spheres for s in range(Nsp): Spheres[s].pos([Pos[s][0], Pos[s][1], 0]) if not int(i) % 10: # every ten steps: rsp = [Pos[0][0], Pos[0][1], 0] rsv = [Vel[0][0], Vel[0][1], 0] vp += Point(rsp, c="r", r=5, alpha=0.1) # leave a point trace vp.show() # render scene pb.print() vp.show(interactive=1)
vmax=MAXLAT).addScalarBar() coloredMesh = Mesh([vertices, faces]) coloredMesh.interpolateDataFrom(estPoints, N=1).cmap('rainbow_r', vmin=MINLAT, vmax=MAXLAT).addScalarBar() # dEPoints = Points(np.array(dE), r=5).c('black') vplt0 = Plotter(N=1, bg='black', resetcam=True, sharecam=False, offscreen=True) vplt0.show(coloredMesh, verPoints, title='Patient{}, Front View'.format(patient), camera=cam0) video0.addFrame() vplt1 = Plotter(N=1, bg='black', resetcam=True, sharecam=False, offscreen=True) vplt1.show(coloredMesh, verPoints, title='Patient{}, Back View'.format(patient), camera=cam1) video1.addFrame() vplt2 = Plotter(offscreen=True)
"""Mesh smoothing with two different methods""" from vedo import Plotter, dataurl plt = Plotter(N=3) # Load a mesh and show it vol = plt.load(dataurl+"embryo.tif") m0 = vol.isosurface().normalize().lw(0.1).c("violet") plt.show(m0, __doc__+"\nOriginal Mesh:", at=0) # Adjust mesh using Laplacian smoothing m1 = m0.clone().smoothLaplacian(niter=20, relaxfact=0.1, edgeAngle=15, featureAngle=60) m1.color("pink") plt.show(m1, "Laplacian smoothing", at=1, viewup='z') # Adjust mesh using a windowed sinc function interpolation kernel m2 = m0.clone().smoothWSinc(niter=20, passBand=0.1, edgeAngle=15, featureAngle=60) m2.color("lg") plt.show(m2, "WindowSinc smoothing", at=2) plt.backgroundColor([0.8, 1, 1], at=0) # set first renderer color plt.show(zoom=1.4, interactive=True)
hanoi = Hanoi(nr_disks) tower_states = list([hanoi.towers]) for _ in hanoi.moves(): tower_states.append(hanoi.towers) disks = { hanoi.nr_disks - i: Cylinder(r=0.2 * (hanoi.nr_disks - i + 1), c=i) for i in range(hanoi.nr_disks) } plt = Plotter(interactive=False, size=(800, 600), bg='wheat', bg2='lb') plt += disks.values() plt += Box(pos=(3, 0, -0.5), size=(12, 4, 0.1)) cam = dict( pos=(14.60, -20.56, 7.680), focalPoint=(3.067, 0.5583, 1.910), viewup=(-0.1043, 0.2088, 0.9724), ) plt.show(camera=cam) pb = ProgressBar(0, len(tower_states), 1, c="y") for t in pb.range(): pb.print() state = tower_states[t] for tower_nr in range(3): for i, disk in enumerate(state[tower_nr]): disks[disk].pos([3 * tower_nr, 0, i + 0.5]) plt.render() plt.interactive().close()
for k in range(1, N): factor = fctr(dij_m[k + 1]) x_dot[k] -= Dt * Ks * (bob_x_m[k] - bob_x_m[k + 1]) * factor y_dot[k] -= Dt * Ks * (bob_y_m[k] - bob_y_m[k + 1]) * factor # Check to see if they are colliding for i in range(1, N): for j in range(i + 1, N + 1): dist2 = (bob_x[i] - bob_x[j])**2 + (bob_y[i] - bob_y[j])**2 if dist2 < DiaSq: # are colliding Ddist = np.sqrt(dist2) - 2 * R tau = versor([bob_x[j] - bob_x[i], bob_y[j] - bob_y[i], 0]) DR = Ddist / 2 * tau bob_x[i] += DR[0] # DR.x bob_y[i] += DR[1] # DR.y bob_x[j] -= DR[0] # DR.x bob_y[j] -= DR[1] # DR.y Vji = vector(x_dot[j] - x_dot[i], y_dot[j] - y_dot[i]) DV = np.dot(Vji, tau) * tau x_dot[i] += DV[0] # DV.x y_dot[i] += DV[1] # DV.y x_dot[j] -= DV[0] # DV.x y_dot[j] -= DV[1] # DV.y # Update the loations of the bobs and the stretching of the springs for k in range(1, N + 1): bob[k].pos([bob_x[k], bob_y[k], 0]) link[k - 1].stretch(bob[k - 1].pos(), bob[k].pos()) vp.show()
rrel = versor(pos[j] - pos[i]) pcmi = pcmi - 2 * np.dot(pcmi, rrel) * rrel # bounce in cm frame pcmj = pcmj - 2 * np.dot(pcmj, rrel) * rrel p[i] = pcmi + ptot * mi / mtot # transform momenta back to lab frame p[j] = pcmj + ptot * mj / mtot pos[i] = pos[i] + (p[i] / mi) * deltat # move forward deltat in time pos[j] = pos[j] + (p[j] / mj) * deltat # Bounce off the boundary of the torus for j in range(Natoms): poscircle[j] = versor(pos[j]) * RingRadius * [1, 1, 0] outside = np.greater_equal(mag(poscircle - pos), RingThickness - 2 * Ratom) for k in range(len(outside)): if outside[k] == 1 and np.dot(p[k], pos[k] - poscircle[k]) > 0: p[k] = reflection(p[k], pos[k] - poscircle[k]) # then update positions of display objects for i in range(Natoms): Atoms[i].pos(pos[i]) ### <-- outside = np.greater_equal(mag(pos), RingRadius + RingThickness) plt.show() ### <-- if plt.escaped: break # if ESC is hit during the loop plt.camera.Azimuth(0.5) plt.camera.Elevation(0.1) pb.print() plt.show(interactive=1).close()
y_dot[k] -= Dt * Ks * (bob_y_m[k] - bob_y_m[k + 1]) * factor # Check to see if they are colliding for i in range(1, N): for j in range(i + 1, N + 1): dist2 = (bob_x[i] - bob_x[j])**2 + (bob_y[i] - bob_y[j])**2 if dist2 < DiaSq: # are colliding Ddist = np.sqrt(dist2) - 2 * R tau = versor([bob_x[j] - bob_x[i], bob_y[j] - bob_y[i], 0]) DR = Ddist / 2 * tau bob_x[i] += DR[0] # DR.x bob_y[i] += DR[1] # DR.y bob_x[j] -= DR[0] # DR.x bob_y[j] -= DR[1] # DR.y Vji = vector(x_dot[j] - x_dot[i], y_dot[j] - y_dot[i]) DV = np.dot(Vji, tau) * tau x_dot[i] += DV[0] # DV.x y_dot[i] += DV[1] # DV.y x_dot[j] -= DV[0] # DV.x y_dot[j] -= DV[1] # DV.y # Update the loations of the bobs and the stretching of the springs for k in range(1, N + 1): bob[k].pos([bob_x[k], bob_y[k], 0]) link[k - 1].stretch(bob[k - 1].pos(), bob[k].pos()) plt.show() if plt.escaped: break # if ESC is hit during the loop plt.close()
input( '\nControl returned to terminal shell:\nwindow is now unresponsive (press Enter)' ) vp1.closeWindow() # window should now close, the Plotter instance becomes unusable # but mesh objects still exist in it: print("First Plotter actors:", vp1.actors) vp1.show() # THIS HAS NO EFFECT: window does not exist anymore. Cannot reopen. ################################################################## # Can now create a brand new Plotter and show the old object in it vp2 = Plotter(title='Second Plotter instance', pos=(500, 0)) vp2.show(vp1.actors[0].color('red')) ################################################################## # Create a third new Plotter and then close the second vp3 = Plotter(title='Third Plotter instance') vp2.closeWindow() print('vp2.closeWindow() called') vp3.show(Hyperboloid()) from vedo import closeWindow closeWindow() # automatically find and close the current window print('done.')