コード例 #1
0
ファイル: test_ui.py プロジェクト: GuillaumeFavelier/fury
def test_text_block_2d():
    text_block = ui.TextBlock2D()

    def _check_property(obj, attr, values):
        for value in values:
            setattr(obj, attr, value)
            npt.assert_equal(getattr(obj, attr), value)

    _check_property(text_block, "bold", [True, False])
    _check_property(text_block, "italic", [True, False])
    _check_property(text_block, "shadow", [True, False])
    _check_property(text_block, "font_size", range(100))
    _check_property(text_block, "message", ["", "Hello World", "Line\nBreak"])
    _check_property(text_block, "justification", ["left", "center", "right"])
    _check_property(text_block, "position", [(350, 350), (0.5, 0.5)])
    _check_property(text_block, "color", [(0., 0.5, 1.)])
    _check_property(text_block, "background_color", [(0., 0.5, 1.), None])
    _check_property(text_block, "vertical_justification",
                    ["top", "middle", "bottom"])
    _check_property(text_block, "font_family", ["Arial", "Courier"])

    with npt.assert_raises(ValueError):
        text_block.font_family = "Verdana"

    with npt.assert_raises(ValueError):
        text_block.justification = "bottom"

    with npt.assert_raises(ValueError):
        text_block.vertical_justification = "left"
コード例 #2
0
ファイル: test_helpers.py プロジェクト: m-agour/fury
def test_wrap_overflow():
    text = ui.TextBlock2D(text="", position=(50, 50), color=(1, 0, 0))
    rectangle = ui.Rectangle2D(position=(50, 50), size=(100, 50))

    sm = window.ShowManager()
    sm.scene.add(rectangle, text)

    text.message = "Hello"
    wrap_overflow(text, rectangle.size[0])
    npt.assert_equal("Hello", text.message)

    text.message = "Hello wassup"
    wrap_overflow(text, rectangle.size[0])
    npt.assert_equal("Hello wassu\np", text.message)

    text.message = "A very very long message to clip text overflow"
    wrap_overflow(text, rectangle.size[0])
    npt.assert_equal("A very very\n long mess\nage to clip \ntext overflo\nw",
                     text.message)

    text.message = "A very very long message to clip text overflow"
    wrap_overflow(text, 0)
    npt.assert_equal(text.message, "")

    wrap_overflow(text, -2 * text.size[0])
    npt.assert_equal(text.message, "")
コード例 #3
0
def test_timer():
    """ Testing add a timer and exit window and app from inside timer.
    """

    xyzr = np.array([[0, 0, 0, 10], [100, 0, 0, 50], [300, 0, 0, 100]])
    xyzr2 = np.array([[0, 200, 0, 30], [100, 200, 0, 50], [300, 200, 0, 100]])
    colors = np.array([[1, 0, 0, 0.3], [0, 1, 0, 0.4], [0, 0, 1., 0.45]])

    renderer = window.Renderer()
    global sphere_actor, tb, cnt
    sphere_actor = actor.sphere(centers=xyzr[:, :3],
                                colors=colors[:],
                                radii=xyzr[:, 3])

    sphere = get_sphere('repulsion724')

    sphere_actor2 = actor.sphere(centers=xyzr2[:, :3],
                                 colors=colors[:],
                                 radii=xyzr2[:, 3],
                                 vertices=sphere.vertices,
                                 faces=sphere.faces.astype('i8'))

    renderer.add(sphere_actor)
    renderer.add(sphere_actor2)

    tb = ui.TextBlock2D()

    cnt = 0
    global showm
    showm = window.ShowManager(renderer,
                               size=(1024, 768),
                               reset_camera=False,
                               order_transparent=True)

    showm.initialize()

    def timer_callback(obj, event):
        global cnt, sphere_actor, showm, tb

        cnt += 1
        tb.message = "Let's count to 10 and exit :" + str(cnt)
        showm.render()
        if cnt > 9:
            showm.exit()

    renderer.add(tb)

    # Run every 200 milliseconds
    showm.add_timer_callback(True, 200, timer_callback)
    showm.start()

    arr = window.snapshot(renderer)

    npt.assert_(np.sum(arr) > 0)
コード例 #4
0
ファイル: viz_advanced.py プロジェクト: furious-atoms/fury
def build_label(text):
    label = ui.TextBlock2D()
    label.message = text
    label.font_size = 18
    label.font_family = 'Arial'
    label.justification = 'left'
    label.bold = False
    label.italic = False
    label.shadow = False
    label.background = (0, 0, 0)
    label.color = (1, 1, 1)

    return label
コード例 #5
0
def build_label(text, font_size=14, bold=False):
    label = ui.TextBlock2D()
    label.message = text
    label.font_size = font_size
    label.font_family = 'Arial'
    label.justification = 'left'
    label.bold = bold
    label.italic = False
    label.shadow = False
    label.actor.GetTextProperty().SetBackgroundColor(0, 0, 0)
    label.actor.GetTextProperty().SetBackgroundOpacity(0.0)
    label.color = (1, 1, 1)
    return label
コード例 #6
0
ファイル: test_helpers.py プロジェクト: guaje/fury
def test_check_overflow():
    text = ui.TextBlock2D(text="", position=(50, 50), color=(1, 0, 0))
    rectangle = ui.Rectangle2D(position=(50, 50), size=(100, 50))

    sm = window.ShowManager()
    sm.scene.add(rectangle, text)

    text.message = "A very very long message to clip text overflow"

    overflow_idx = check_overflow(text, rectangle.size[0], '~')

    npt.assert_equal(10, overflow_idx)
    npt.assert_equal('A very ver~', text.message)
コード例 #7
0
ファイル: test_ui.py プロジェクト: Saransh0905/fury
def test_timer():
    """Testing add a timer and exit window and app from inside timer."""
    xyzr = np.array([[0, 0, 0, 10], [100, 0, 0, 50], [300, 0, 0, 100]])
    xyzr2 = np.array([[0, 200, 0, 30], [100, 200, 0, 50], [300, 200, 0, 100]])
    colors = np.array([[1, 0, 0, 0.3], [0, 1, 0, 0.4], [0, 0, 1., 0.45]])

    scene = window.Scene()

    sphere_actor = actor.sphere(centers=xyzr[:, :3],
                                colors=colors[:],
                                radii=xyzr[:, 3])

    vertices, faces = prim_sphere('repulsion724')

    sphere_actor2 = actor.sphere(centers=xyzr2[:, :3],
                                 colors=colors[:],
                                 radii=xyzr2[:, 3],
                                 vertices=vertices,
                                 faces=faces.astype('i8'))

    scene.add(sphere_actor)
    scene.add(sphere_actor2)

    tb = ui.TextBlock2D()
    counter = itertools.count()
    showm = window.ShowManager(scene,
                               size=(1024, 768),
                               reset_camera=False,
                               order_transparent=True)

    showm.initialize()
    scene.add(tb)

    def timer_callback(_obj, _event):
        cnt = next(counter)
        tb.message = "Let's count to 10 and exit :" + str(cnt)
        showm.render()
        if cnt > 9:
            showm.exit()

    # Run every 200 milliseconds
    showm.add_timer_callback(True, 200, timer_callback)
    showm.start()

    arr = window.snapshot(scene, offscreen=True)
    npt.assert_(np.sum(arr) > 0)
コード例 #8
0
ファイル: test_helpers.py プロジェクト: guaje/fury
def test_clip_overflow():
    text = ui.TextBlock2D(text="", position=(50, 50), color=(1, 0, 0))
    rectangle = ui.Rectangle2D(position=(50, 50), size=(100, 50))

    sm = window.ShowManager()
    sm.scene.add(rectangle, text)

    text.message = "Hello"
    clip_overflow(text, rectangle.size[0])
    npt.assert_equal("Hello", text.message)

    text.message = "Hello wassup"
    clip_overflow(text, rectangle.size[0])
    npt.assert_equal("Hello was...", text.message)

    text.message = "A very very long message to clip text overflow"
    clip_overflow(text, rectangle.size[0])
    npt.assert_equal("A very ve...", text.message)

    text.message = "Hello"
    clip_overflow(text, rectangle.size[0], 'left')
    npt.assert_equal("Hello", text.message)

    text.message = "Hello wassup"
    clip_overflow(text, rectangle.size[0], 'left')
    npt.assert_equal("...lo wassup", text.message)

    text.message = "A very very long message to clip text overflow"
    clip_overflow(text, rectangle.size[0], 'left')
    npt.assert_equal("... overflow", text.message)

    text.message = "A very very long message to clip text overflow"
    clip_overflow(text, rectangle.size[0], 'LeFT')
    npt.assert_equal("... overflow", text.message)

    text.message = "A very very long message to clip text overflow"
    clip_overflow(text, rectangle.size[0], 'RigHT')
    npt.assert_equal("A very ve...", text.message)

    npt.assert_raises(ValueError, clip_overflow,
                      text, rectangle.size[0], 'middle')
コード例 #9
0
ファイル: viz_timers.py プロジェクト: zoq/fury
radii = np.random.rand(100) + 0.5

scene = window.Scene()

sphere_actor = actor.sphere(centers=xyz, colors=colors, radii=radii)

scene.add(sphere_actor)

showm = window.ShowManager(scene,
                           size=(900, 768),
                           reset_camera=False,
                           order_transparent=True)

showm.initialize()

tb = ui.TextBlock2D(bold=True)

# use itertools to avoid global variables
counter = itertools.count()


def timer_callback(_obj, _event):
    cnt = next(counter)
    tb.message = "Let's count up to 100 and exit :" + str(cnt)
    showm.scene.azimuth(0.05 * cnt)
    sphere_actor.GetProperty().SetOpacity(cnt / 100.)
    showm.render()
    if cnt == 100:
        showm.exit()

コード例 #10
0
ファイル: viz_combobox.py プロジェクト: pietroastolfi/fury
ComboBox
========

This example shows how to use the Combobox UI. We will demonstrate how to
create ComboBoxes for selecting colors for a label.

First, some imports.
"""
from fury import ui, window

#########################################################################
# First, we create a label.

label = ui.TextBlock2D(position=(200, 300),
                       font_size=40,
                       color=(1, 0.5, 0),
                       justification="center",
                       vertical_justification="top",
                       text="FURY rocks!!!")

########################################################################
# Now we create a dictionary to store colors as its key and their
# RGB values as its value.

colors = {
    "Violet": (0.6, 0, 0.8),
    "Indigo": (0.3, 0, 0.5),
    "Blue": (0, 0, 1),
    "Green": (0, 1, 0),
    "Yellow": (1, 1, 0),
    "Orange": (1, 0.5, 0),
    "Red": (1, 0, 0)
コード例 #11
0
color_particle = window.colors.red  # color of particle can be manipulated
pts = np.array([[x, y, z]])
charge_actor = actor.point(pts, color_particle, point_radius=radius_particle)
scene.add(charge_actor)

vertices = utils.vertices_from_actor(charge_actor)
vcolors = utils.colors_from_actor(charge_actor, 'colors')
no_vertices_per_point = len(vertices)
initial_vertices = vertices.copy() - \
    np.repeat(pts, no_vertices_per_point, axis=0)


###############################################################################
# Initializing text box to display the name of the animation

tb = ui.TextBlock2D(bold=True, position=(100, 90))
m1 = "Motion of a charged particle in a "
m2 = "combined electric and magnetic field"
tb.message = m1 + m2
scene.add(tb)

###############################################################################
# Initializing counter

counter = itertools.count()

###############################################################################
# end is used to decide when to end the animation

end = 200
コード例 #12
0
ファイル: viz_buttons.py プロジェクト: tantheta01/fury
# First we need to fetch some icons that are included in FURY.

fetch_viz_icons()

###############################################################################
# Let's create some buttons and text and put them in a panel.
# First we'll make the panel.

panel = ui.Panel2D(size=(300, 150), color=(1, 1, 1), align="right")
panel.center = (500, 400)

###############################################################################
# Then we'll make two text labels and place them on the panel.
# Note that we specifiy the position with integer numbers of pixels.

text = ui.TextBlock2D(text="Click me")
text2 = ui.TextBlock2D(text="Me too")
panel.add_element(text, (50, 100))
panel.add_element(text2, (180, 100))

###############################################################################
# Then we'll create two buttons and add them to the panel.
#
# Note that here we specify the positions with floats. In this case, these are
# percentages of the panel size.

button_example = ui.Button2D(icon_fnames=[("square",
                                           read_viz_icons(fname="stop2.png"))])

icon_files = []
icon_files.append(("down", read_viz_icons(fname="circle-down.png")))
コード例 #13
0
ファイル: viz_pbr_interactive.py プロジェクト: m-agour/fury
show_m.initialize()

###############################################################################
# We will create one single panel with all of our labels and sliders.

control_panel = ui.Panel2D((400, 500),
                           position=(5, 5),
                           color=(.25, .25, .25),
                           opacity=.75,
                           align='right')

###############################################################################
# By using our previously defined function, we can easily create all the labels
# we need for this demo. And then add them to the panel.

slider_label_metallic = ui.TextBlock2D(text='Metallic', font_size=16)
slider_label_roughness = ui.TextBlock2D(text='Roughness', font_size=16)
slider_label_anisotropy = ui.TextBlock2D(text='Anisotropy', font_size=16)
slider_label_anisotropy_rotation = ui.TextBlock2D(text='Anisotropy Rotation',
                                                  font_size=16)
slider_label_anisotropy_direction_x = ui.TextBlock2D(
    text='Anisotropy Direction X', font_size=16)
slider_label_anisotropy_direction_y = ui.TextBlock2D(
    text='Anisotropy Direction Y', font_size=16)
slider_label_anisotropy_direction_z = ui.TextBlock2D(
    text='Anisotropy Direction Z', font_size=16)
slider_label_coat_strength = ui.TextBlock2D(text='Coat Strength', font_size=16)
slider_label_coat_roughness = ui.TextBlock2D(text='Coat Roughness',
                                             font_size=16)
slider_label_base_ior = ui.TextBlock2D(text='Base IoR', font_size=16)
slider_label_coat_ior = ui.TextBlock2D(text='Coat IoR', font_size=16)
コード例 #14
0
ファイル: viz_slice.py プロジェクト: zoq/fury
###############################################################################
# Now we would like to add the ability to click on a voxel and show its value
# on a panel in the window. The panel is a UI element which requires access to
# different areas of the visualization pipeline and therefore we don't
# recommend using it with ``window.show``. The more appropriate way is to use
# the ``ShowManager`` object, which allows accessing the pipeline in different
# areas.

show_m = window.ShowManager(scene, size=(1200, 900))
show_m.initialize()

###############################################################################
# We'll start by creating the panel and adding it to the ``ShowManager``

label_position = ui.TextBlock2D(text='Position:')
label_value = ui.TextBlock2D(text='Value:')

result_position = ui.TextBlock2D(text='')
result_value = ui.TextBlock2D(text='')

panel_picking = ui.Panel2D(size=(250, 125),
                           position=(20, 20),
                           color=(0, 0, 0),
                           opacity=0.75,
                           align="left")

panel_picking.add_element(label_position, (0.1, 0.55))
panel_picking.add_element(label_value, (0.1, 0.25))

panel_picking.add_element(result_position, (0.45, 0.55))
コード例 #15
0
ファイル: test_ui.py プロジェクト: kakashihatakae/fury
def test_frame_rate_and_anti_aliasing():
    """Testing frame rate with/out anti-aliasing"""

    length_ = 200
    multi_samples = 32
    max_peels = 8

    st_x = np.arange(length_)
    st_y = np.sin(np.arange(length_))
    st_z = np.zeros(st_x.shape)
    st = np.zeros((length_, 3))
    st[:, 0] = st_x
    st[:, 1] = st_y
    st[:, 2] = st_z

    all_st = []
    all_st.append(st)
    for i in range(1000):
        all_st.append(st + i * np.array([0., .5, 0]))

    # st_actor = actor.line(all_st, linewidth=1)
    # TODO: textblock disappears when lod=True
    st_actor = actor.streamtube(all_st, linewidth=0.1, lod=False)

    scene = window.Scene()
    scene.background((1, 1., 1))

    # quick game style antialiasing
    scene.fxaa_on()
    scene.fxaa_off()

    # the good staff is later with multi-sampling

    tb = ui.TextBlock2D(font_size=40, color=(1, 0.5, 0))

    panel = ui.Panel2D(position=(400, 400), size=(400, 400))
    panel.add_element(tb, (0.2, 0.5))

    counter = itertools.count()
    showm = window.ShowManager(scene,
                               size=(1980, 1080), reset_camera=False,
                               order_transparent=True,
                               multi_samples=multi_samples,
                               max_peels=max_peels,
                               occlusion_ratio=0.0)

    showm.initialize()
    scene.add(panel)
    scene.add(st_actor)
    scene.reset_camera_tight()
    scene.zoom(5)

    class FrameRateHolder(object):
        fpss = []

    frh = FrameRateHolder()

    def timer_callback(_obj, _event):
        cnt = next(counter)
        if cnt % 1 == 0:
            fps = np.round(scene.frame_rate, 0)
            frh.fpss.append(fps)
            msg = "FPS " + str(fps) + ' ' + str(cnt)
            tb.message = msg
            showm.render()
        if cnt > 10:
            showm.exit()

    # Run every 200 milliseconds
    showm.add_timer_callback(True, 200, timer_callback)
    showm.start()

    arr = window.snapshot(scene, size=(1980, 1080),
                          offscreen=True,
                          order_transparent=True,
                          multi_samples=multi_samples,
                          max_peels=max_peels,
                          occlusion_ratio=0.0)
    assert_greater(np.sum(arr), 0)
    # TODO: check why in osx we have issues in Azure
    if not skip_osx:
        assert_greater(np.median(frh.fpss), 0)

    frh.fpss = []
    counter = itertools.count()
    multi_samples = 0
    showm = window.ShowManager(scene,
                               size=(1980, 1080), reset_camera=False,
                               order_transparent=True,
                               multi_samples=multi_samples,
                               max_peels=max_peels,
                               occlusion_ratio=0.0)

    showm.initialize()
    showm.add_timer_callback(True, 200, timer_callback)
    showm.start()

    arr2 = window.snapshot(scene, size=(1980, 1080),
                           offscreen=True,
                           order_transparent=True,
                           multi_samples=multi_samples,
                           max_peels=max_peels,
                           occlusion_ratio=0.0)
    assert_greater(np.sum(arr2), 0)
    if not skip_osx:
        assert_greater(np.median(frh.fpss), 0)
コード例 #16
0
def test_double_click_events(recording=False):
    filename = "test_double_click_events.log.gz"
    recording_filename = pjoin(DATA_DIR, filename)

    label = ui.TextBlock2D(position=(400, 780),
                           font_size=40,
                           color=(1, 0.5, 0),
                           justification="center",
                           vertical_justification="top",
                           text="FURY rocks!!!")

    cube = actor.cube(np.array([(0, 0, 0)]),
                      np.array([(0.16526678, 0.0186237, 0.01906076)]),
                      (1, 1, 1),
                      scales=3)

    states = defaultdict(lambda: 0)

    def left_single_click(iren, obj):
        states["LeftButtonPressEvent"] += 1
        iren.force_render()

    def left_double_click(iren, obj):
        states["LeftButtonDoubleClickEvent"] += 1
        label.color = (1, 0, 0)
        iren.force_render()

    def right_single_click(iren, obj):
        states["RightButtonPressEvent"] += 1
        iren.force_render()

    def right_double_click(iren, obj):
        states["RightButtonDoubleClickEvent"] += 1
        label.color = (0, 1, 0)
        iren.force_render()

    def middle_single_click(iren, obj):
        states["MiddleButtonPressEvent"] += 1
        iren.force_render()

    def middle_double_click(iren, obj):
        states["MiddleButtonDoubleClickEvent"] += 1
        label.color = (0, 0, 1)
        iren.force_render()

    test_events = {
        "LeftButtonPressEvent": left_single_click,
        "LeftButtonDoubleClickEvent": left_double_click,
        "RightButtonPressEvent": right_single_click,
        "RightButtonDoubleClickEvent": right_double_click,
        "MiddleButtonPressEvent": middle_single_click,
        "MiddleButtonDoubleClickEvent": middle_double_click
    }

    current_size = (800, 800)
    showm = window.ShowManager(size=current_size, title="Double Click Test")
    showm.scene.add(cube)
    showm.scene.add(label)

    for test_event, callback in test_events.items():
        showm.style.add_callback(cube, test_event, callback)

    if recording:
        showm.record_events_to_file(recording_filename)
        print(list(states.items()))
    else:
        showm.play_events_from_file(recording_filename)
        msg = ("Wrong count for '{}'.")
        expected = [('LeftButtonPressEvent', 3),
                    ('LeftButtonDoubleClickEvent', 1),
                    ('MiddleButtonPressEvent', 3),
                    ('MiddleButtonDoubleClickEvent', 1),
                    ('RightButtonPressEvent', 2),
                    ('RightButtonDoubleClickEvent', 1)]

        # Useful loop for debugging.
        for event, count in expected:
            if states[event] != count:
                print("{}: {} vs. {} (expected)".format(
                    event, states[event], count))

        for event, count in expected:
            npt.assert_equal(states[event], count, err_msg=msg.format(event))
コード例 #17
0
@window.vtk.calldata_type(window.vtk.VTK_OBJECT)
def vtk_shader_callback(caller, event, calldata=None):
    program = calldata
    global timer
    if program is not None:
        try:
            program.SetUniformf("time", timer)
        except ValueError:
            pass


###############################################################################
# Let's add a textblock to the scene with a custom message

tb = ui.TextBlock2D()
tb.message = "Hello Shaders"

###############################################################################
# Change the property of the actor

utah.GetProperty().SetOpacity(0.5)

###############################################################################
# Invoke callbacks to any VTK object

mapper.AddObserver(window.vtk.vtkCommand.UpdateShaderEvent,
                   vtk_shader_callback)

###############################################################################
# Show Manager
コード例 #18
0
First, a bunch of imports.
"""
from fury import ui, window
from fury.data import fetch_viz_icons

##############################################################################
# First we need to fetch some icons that are included in FURY.

fetch_viz_icons()

###############################################################################
# Create some text blocks that will be shown when
# list elements will be selected

welcome_text = ui.TextBlock2D(text="Welcome",
                              font_size=30,
                              position=(500, 400))
bye_text = ui.TextBlock2D(text="Bye", font_size=30, position=(500, 400))
fury_text = ui.TextBlock2D(text="Fury", font_size=30, position=(500, 400))

example = [welcome_text, bye_text, fury_text]

###############################################################################
# Hide these text blocks for now


def hide_all_examples():
    for element in example:
        element.set_visibility(False)

コード例 #19
0
# Get the position and orientation of base and set it.
base_pos, base_orn = p.getBasePositionAndOrientation(base)
base_actor.SetPosition(*base_pos)


# Function for syncing actors with multibodies.
def sync_actor(actor, multibody):
    pos, orn = p.getBasePositionAndOrientation(multibody)
    actor.SetPosition(*pos)
    orn_deg = np.degrees(p.getEulerFromQuaternion(orn))
    actor.SetOrientation(*orn_deg)


fpss = np.array([])
tb = ui.TextBlock2D(text="",
                    position=(0, 680),
                    font_size=30,
                    color=(1, 0.5, 0))
scene.add(tb)
scene.set_camera(position=(10.46, -8.13, 6.18),
                 focal_point=(0.0, 0.0, 0.79),
                 view_up=(-0.27, 0.26, 0.90))


# Create timer callback which will execute at each step of simulation.
def timer_callback(_obj, _event):
    global apply_force, fpss
    cnt = next(counter)
    showm.render()

    if cnt % 1 == 0:
        fps = showm.frame_rate
コード例 #20
0
ファイル: viz_wrecking_ball.py プロジェクト: jhlegarreta/fury
        chain_vertices[joint * sec: joint * sec + sec] = \
            (chain_vertices[joint * sec: joint * sec + sec] -
             linkPositions[joint]) @ rot_mat + pos

        linkPositions[joint] = pos
        linkOrientations[joint] = orn


###############################################################################
# Some helper tools to keep track of avg. FPS and simulation steps.

counter = itertools.count()
fpss = np.array([])
tb = ui.TextBlock2D(position=(0, 680),
                    font_size=30,
                    color=(1, 0.5, 0),
                    text="Avg. FPS: \nSim Steps: ")
scene.add(tb)

###############################################################################
# Timer callback to sync objects, simulate steps and apply force.

apply_force = True


# Create timer callback which will execute at each step of simulation.
def timer_callback(_obj, _event):
    global apply_force, fpss
    cnt = next(counter)
    showm.render()
コード例 #21
0
import numpy as np
from fury import actor, window, ui, utils, pick

centers = 0.5 * np.array([[0, 0, 0], [100, 0, 0], [200, 0, 0.]])
colors = np.array([[0.8, 0, 0], [0, 0.8, 0], [0, 0, 0.8]])
radii = 0.1 * np.array([50, 100, 150.])

selected = np.zeros(3, dtype=bool)

###############################################################################
# Let's create a panel to show what is picked

panel = ui.Panel2D(size=(400, 200), color=(1, .5, .0), align="right")
panel.center = (150, 200)

text_block = ui.TextBlock2D(text="Left click on object \n")
panel.add_element(text_block, (0.3, 0.3))

###############################################################################
# Build scene and add an actor with many objects.

scene = window.Scene()

label_actor = actor.label(text='Test')

###############################################################################
# This actor is made with 3 cubes of different orientation

directions = np.array([[np.sqrt(2) / 2, 0, np.sqrt(2) / 2],
                       [np.sqrt(2) / 2, np.sqrt(2) / 2, 0],
                       [0, np.sqrt(2) / 2, np.sqrt(2) / 2]])
コード例 #22
0
ファイル: test_ui.py プロジェクト: kakashihatakae/fury
def test_text_block_2d_justification():
    window_size = (700, 700)
    show_manager = window.ShowManager(size=window_size)

    # To help visualize the text positions.
    grid_size = (500, 500)
    bottom, middle, top = 50, 300, 550
    left, center, right = 50, 300, 550
    line_color = (1, 0, 0)

    grid_top = (center, top), (grid_size[0], 1)
    grid_bottom = (center, bottom), (grid_size[0], 1)
    grid_left = (left, middle), (1, grid_size[1])
    grid_right = (right, middle), (1, grid_size[1])
    grid_middle = (center, middle), (grid_size[0], 1)
    grid_center = (center, middle), (1, grid_size[1])
    grid_specs = [grid_top, grid_bottom, grid_left, grid_right,
                  grid_middle, grid_center]
    for spec in grid_specs:
        line = ui.Rectangle2D(size=spec[1], color=line_color)
        line.center = spec[0]
        show_manager.scene.add(line)

    font_size = 60
    bg_color = (1, 1, 1)
    texts = []
    texts += [ui.TextBlock2D("HH", position=(left, top),
                             font_size=font_size,
                             color=(1, 0, 0), bg_color=bg_color,
                             justification="left",
                             vertical_justification="top")]
    texts += [ui.TextBlock2D("HH", position=(center, top),
                             font_size=font_size,
                             color=(0, 1, 0), bg_color=bg_color,
                             justification="center",
                             vertical_justification="top")]
    texts += [ui.TextBlock2D("HH", position=(right, top),
                             font_size=font_size,
                             color=(0, 0, 1), bg_color=bg_color,
                             justification="right",
                             vertical_justification="top")]

    texts += [ui.TextBlock2D("HH", position=(left, middle),
                             font_size=font_size,
                             color=(1, 1, 0), bg_color=bg_color,
                             justification="left",
                             vertical_justification="middle")]
    texts += [ui.TextBlock2D("HH", position=(center, middle),
                             font_size=font_size,
                             color=(0, 1, 1), bg_color=bg_color,
                             justification="center",
                             vertical_justification="middle")]
    texts += [ui.TextBlock2D("HH", position=(right, middle),
                             font_size=font_size,
                             color=(1, 0, 1), bg_color=bg_color,
                             justification="right",
                             vertical_justification="middle")]

    texts += [ui.TextBlock2D("HH", position=(left, bottom),
                             font_size=font_size,
                             color=(0.5, 0, 1), bg_color=bg_color,
                             justification="left",
                             vertical_justification="bottom")]
    texts += [ui.TextBlock2D("HH", position=(center, bottom),
                             font_size=font_size,
                             color=(1, 0.5, 0), bg_color=bg_color,
                             justification="center",
                             vertical_justification="bottom")]
    texts += [ui.TextBlock2D("HH", position=(right, bottom),
                             font_size=font_size,
                             color=(0, 1, 0.5), bg_color=bg_color,
                             justification="right",
                             vertical_justification="bottom")]

    show_manager.scene.add(*texts)

    # Uncomment this to start the visualisation
    # show_manager.start()

    window.snapshot(show_manager.scene, size=window_size, offscreen=True)
コード例 #23
0
###############################################################################
# Panel with buttons and text
# ===========================
#
# Let's create some buttons and text and put them in a panel. First we'll
# make the panel.

panel = ui.Panel2D(size=(300, 150), color=(1, 1, 1), align="right")
panel.center = (500, 400)

###############################################################################
# Then we'll make two text labels and place them on the panel.
# Note that we specifiy the position with integer numbers of pixels.

text = ui.TextBlock2D(text='Click me')
text2 = ui.TextBlock2D(text='Me too')
panel.add_element(text, (50, 100))
panel.add_element(text2, (180, 100))

###############################################################################
# Then we'll create two buttons and add them to the panel.
#
# Note that here we specify the positions with floats. In this case, these are
# percentages of the panel size.


button_example = ui.Button2D(
    icon_fnames=[('square', read_viz_icons(fname='stop2.png'))])

icon_files = []
コード例 #24
0
]

scene.add(*l_particle)

###############################################################################
# Creating a container (cube actor) inside which the particle(s) move around

container_actor = actor.box(centers=np.array([[0, 0, 0]]),
                            colors=(0.5, 0.9, 0.7, 0.4),
                            scales=6)
scene.add(container_actor)

###############################################################################
# Initializing text box to display the name of the animation

tb = ui.TextBlock2D(bold=True, position=(235, 40), color=(0, 0, 0))
tb.message = "Brownian Motion"
scene.add(tb)

###############################################################################
# The path of the particles exhibiting Brownian motion is plotted here


def timer_callback(_obj, _event):
    global counter_step, list_particle
    counter_step += 1
    for p in l_particle:
        update_path(p, counter_step=counter_step)
    showm.render()
    scene.azimuth(2)
    if counter_step == num_total_steps:
コード例 #25
0
ファイル: test_ui.py プロジェクト: kakashihatakae/fury
def test_ui_button_panel(recording=False):
    filename = "test_ui_button_panel"
    recording_filename = pjoin(DATA_DIR, filename + ".log.gz")
    expected_events_counts_filename = pjoin(DATA_DIR, filename + ".json")

    # Rectangle
    rectangle_test = ui.Rectangle2D(size=(10, 10))
    another_rectangle_test = ui.Rectangle2D(size=(1, 1))

    # Button
    fetch_viz_icons()

    icon_files = []
    icon_files.append(('stop', read_viz_icons(fname='stop2.png')))
    icon_files.append(('play', read_viz_icons(fname='play3.png')))

    button_test = ui.Button2D(icon_fnames=icon_files)
    button_test.center = (20, 20)

    def make_invisible(i_ren, _obj, button):
        # i_ren: CustomInteractorStyle
        # obj: vtkActor picked
        # button: Button2D
        button.set_visibility(False)
        i_ren.force_render()
        i_ren.event.abort()

    def modify_button_callback(i_ren, _obj, button):
        # i_ren: CustomInteractorStyle
        # obj: vtkActor picked
        # button: Button2D
        button.next_icon()
        i_ren.force_render()

    button_test.on_right_mouse_button_pressed = make_invisible
    button_test.on_left_mouse_button_pressed = modify_button_callback

    button_test.scale((2, 2))
    button_color = button_test.color
    button_test.color = button_color

    # TextBlock
    text_block_test = ui.TextBlock2D()
    text_block_test.message = 'TextBlock'
    text_block_test.color = (0, 0, 0)

    # Panel
    panel = ui.Panel2D(size=(300, 150),
                       position=(290, 15),
                       color=(1, 1, 1), align="right")
    panel.add_element(rectangle_test, (290, 135))
    panel.add_element(button_test, (0.1, 0.1))
    panel.add_element(text_block_test, (0.7, 0.7))
    npt.assert_raises(ValueError, panel.add_element, another_rectangle_test,
                      (10., 0.5))
    npt.assert_raises(ValueError, panel.add_element, another_rectangle_test,
                      (-0.5, 0.5))

    # Assign the counter callback to every possible event.
    event_counter = EventCounter()
    event_counter.monitor(button_test)
    event_counter.monitor(panel.background)

    current_size = (600, 600)
    show_manager = window.ShowManager(size=current_size, title="FURY Button")

    show_manager.scene.add(panel)

    if recording:
        show_manager.record_events_to_file(recording_filename)
        print(list(event_counter.events_counts.items()))
        event_counter.save(expected_events_counts_filename)

    else:
        show_manager.play_events_from_file(recording_filename)
        expected = EventCounter.load(expected_events_counts_filename)
        event_counter.check_counts(expected)
コード例 #26
0
ファイル: test_pick.py プロジェクト: mlraglin/fury
def test_selector_manager():

    centers, colors, radii = _get_three_cubes()

    scene = window.Scene()

    cube_actor = actor.cube(centers,
                            directions=(1, 0, 2),
                            colors=colors,
                            scales=radii)

    pts = 100 * (np.random.rand(100, 3) - 0.5) + np.array([20, 0, 0.])
    pts_actor = actor.dots(pts, dot_size=10)

    rgb = 255 * np.ones((400, 400, 3), dtype=np.uint8)
    tex_actor = actor.texture(rgb)

    scene.add(cube_actor)
    scene.add(pts_actor)
    scene.add(tex_actor)

    showm = window.ShowManager(scene,
                               size=(900, 768),
                               reset_camera=False,
                               order_transparent=True)

    showm.initialize()

    tb = ui.TextBlock2D(bold=True)

    # use itertools to avoid global variables
    counter = itertools.count()

    selm = pick.SelectionManager(select='faces')

    selm.selectable_off([tex_actor])
    selm.selectable_on([tex_actor])
    selm.selectable_off([tex_actor])

    def timer_callback(_obj, _event):
        cnt = next(counter)
        tb.message = "Let's count up to 15 and exit :" + str(cnt)
        if cnt % 10 == 0:
            # select large area
            info_plus = selm.select((900 // 2, 768 // 2), scene, (30, 30))
            for info in info_plus.keys():
                if info_plus[info]['actor'] in [cube_actor, pts_actor]:
                    npt.assert_(True)
                else:
                    npt.assert_(False)
            # select single pixel
            info_ = selm.pick((900 // 2, 768 // 2), scene)
            if info_['actor'] in [cube_actor, pts_actor]:
                npt.assert_(True)
            else:
                npt.assert_(False)

        showm.render()
        if cnt == 15:
            showm.exit()
            pass

    scene.add(tb)

    # Run every 200 milliseconds
    showm.add_timer_callback(True, 200, timer_callback)
    showm.start()
コード例 #27
0
ファイル: test_containers.py プロジェクト: m-agour/fury
def test_ui_tab_ui(interactive=False):
    filename = "test_ui_tab_ui"
    recording_filename = pjoin(DATA_DIR, filename + ".log.gz")
    expected_events_counts_filename = pjoin(DATA_DIR, filename + ".json")

    tab_ui = ui.TabUI(position=(50, 50),
                      size=(300, 300),
                      nb_tabs=3,
                      draggable=True)

    tab_ui.tabs[0].title = "Tab 1"
    tab_ui.tabs[1].title = "Tab 2"
    tab_ui.tabs[2].title = "Tab 3"

    tab_ui.add_element(0, ui.Checkbox(["Option 1", "Option 2"]), (0.5, 0.5))
    tab_ui.add_element(1, ui.LineSlider2D(), (0.0, 0.5))
    tab_ui.add_element(2, ui.TextBlock2D(), (0.5, 0.5))

    with npt.assert_raises(IndexError):
        tab_ui.add_element(3, ui.TextBlock2D(), (0.5, 0.5, 0.5))

    with npt.assert_raises(IndexError):
        tab_ui.remove_element(3, ui.TextBlock2D())

    with npt.assert_raises(IndexError):
        tab_ui.update_element(3, ui.TextBlock2D(), (0.5, 0.5, 0.5))

    npt.assert_equal("Tab 1", tab_ui.tabs[0].title)
    npt.assert_equal("Tab 2", tab_ui.tabs[1].title)
    npt.assert_equal("Tab 3", tab_ui.tabs[2].title)

    npt.assert_equal(3, tab_ui.nb_tabs)

    collapses = itertools.count()
    changes = itertools.count()

    def collapse(tab_ui):
        if tab_ui.collapsed:
            next(collapses)

    def tab_change(tab_ui):
        next(changes)

    tab_ui.on_change = tab_change
    tab_ui.on_collapse = collapse

    event_counter = EventCounter()
    event_counter.monitor(tab_ui)

    current_size = (800, 800)
    show_manager = window.ShowManager(size=current_size, title="Tab UI Test")
    show_manager.scene.add(tab_ui)

    if interactive:
        show_manager.record_events_to_file(recording_filename)
        print(list(event_counter.events_counts.items()))
        event_counter.save(expected_events_counts_filename)
    else:
        show_manager.play_events_from_file(recording_filename)
        expected = EventCounter.load(expected_events_counts_filename)
        event_counter.check_counts(expected)

    npt.assert_equal(0, tab_ui.active_tab_idx)
    npt.assert_equal(11, next(changes))
    npt.assert_equal(5, next(collapses))
コード例 #28
0
ファイル: test_pick.py プロジェクト: mlraglin/fury
def test_picking_manager():

    xyz = 10 * np.random.rand(100, 3)
    colors = np.random.rand(100, 4)
    radii = np.random.rand(100) + 0.5

    scene = window.Scene()

    sphere_actor = actor.sphere(centers=xyz, colors=colors, radii=radii)

    scene.add(sphere_actor)

    showm = window.ShowManager(scene,
                               size=(900, 768),
                               reset_camera=False,
                               order_transparent=True)

    showm.initialize()

    tb = ui.TextBlock2D(bold=True)

    # use itertools to avoid global variables
    counter = itertools.count()

    pickm = pick.PickingManager()

    record_indices = {
        'vertex_indices': [],
        'face_indices': [],
        'xyz': [],
        'actor': []
    }

    def timer_callback(_obj, _event):
        cnt = next(counter)
        tb.message = "Let's count up to 15 and exit :" + str(cnt)
        showm.scene.azimuth(0.05 * cnt)
        # sphere_actor.GetProperty().SetOpacity(cnt/100.)
        if cnt % 10 == 0:
            # pick at position
            info = pickm.pick((900 / 2, 768 / 2), scene)
            record_indices['vertex_indices'].append(info['vertex'])
            record_indices['face_indices'].append(info['face'])
            record_indices['xyz'].append(info['xyz'])
            record_indices['actor'].append(info['actor'])

        showm.render()
        if cnt == 15:
            showm.exit()

    scene.add(tb)

    # Run every 200 milliseconds
    showm.add_timer_callback(True, 200, timer_callback)
    showm.start()

    assert_greater(np.sum(np.array(record_indices['vertex_indices'])), 1)
    assert_greater(np.sum(np.array(record_indices['face_indices'])), 1)

    for ac in record_indices['actor']:
        if ac is not None:
            npt.assert_equal(ac is sphere_actor, True)

    assert_greater(
        np.sum(np.abs(np.diff(np.array(record_indices['xyz']), axis=0))), 0)
コード例 #29
0
ファイル: viz_ball_collide.py プロジェクト: m-agour/fury
showm.initialize()
counter = itertools.count()

###############################################################################
# Method to sync objects.


def sync_actor(actor, multibody):
    pos, orn = p.getBasePositionAndOrientation(multibody)
    actor.SetPosition(*pos)
    orn_deg = np.degrees(p.getEulerFromQuaternion(orn))
    actor.SetOrientation(*orn_deg)


apply_force = True
tb = ui.TextBlock2D(position=(0, 600), font_size=30, color=(1, 0.5, 0),
                    text="")
scene.add(tb)
scene.set_camera(position=(0.30, -18.78, 0.89),
                 focal_point=(0.15, 0.25, 0.40),
                 view_up=(0, 0, 1.00))


###############################################################################
# Timer callback to sync and step simulation every second.

def timer_callback(_obj, _event):
    global apply_force
    cnt = next(counter)
    showm.render()
    red_pos, red_orn = p.getBasePositionAndOrientation(red_ball)
    blue_pos, blue_orn = p.getBasePositionAndOrientation(blue_ball)
コード例 #30
0
    rotation_angle = angle - previous_angle
    showm.scene.azimuth(rotation_angle)
    
y_ring_slider.on_change = change_slice_y



def change_slice_z(slider):
    angle = slider.value
    previous_angle = slider.previous_value
    rotation_angle = angle - previous_angle
    showm.scene.roll(rotation_angle)
    
z_ring_slider.on_change = change_slice_z

xlabel = ui.TextBlock2D(position=(70,40),text="x-axis")
ylabel = ui.TextBlock2D(position=(70,100),text="y-axis")
zlabel = ui.TextBlock2D(position=(70,160),text="z-axis")
scene.add(xlabel)
scene.add(ylabel)
scene.add(zlabel)


ax = actor.axes(scale=(100, 100, 100))
# scene.add(ax)

# mesh_structure = mcds.get_mesh()
# X_domain = np.unique(mesh_structure[0][0])
# Y_domain = np.unique(mesh_structure[1][0])
# Z_domain = np.unique(mesh_structure[2][0])
# dx = X_domain[1]-X_domain[0]